# All files / src/trpc/routers project.ts

1.92% Statements 1/52
0% Branches 0/29
10% Functions 1/10
1.92% Lines 1/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158

    11x

     /**
     * Project Router — register, list, get, delete, initiative associations
     */

    import { TRPCError } from '@trpc/server';
    import { z } from 'zod';
    import { join } from 'node:path';
    import { rm } from 'node:fs/promises';
    import type { ProcedureBuilder } from '../trpc.js';
    import { requireProjectRepository } from './_helpers.js';
    import { cloneProject } from '../../git/clone.js';
    import { getProjectCloneDir } from '../../git/project-clones.js';

    export function projectProcedures(publicProcedure: ProcedureBuilder) {
      return {
        registerProject: publicProcedure
          .input(z.object({
            name: z.string().min(1),
            url: z.string().min(1),
            defaultBranch: z.string().min(1).optional(),
          }))
          .mutation(async ({ ctx, input }) => {
            const repo = requireProjectRepository(ctx);

            let project;
            try {
              project = await repo.create({
                name: input.name,
                url: input.url,
                ...(input.defaultBranch && { defaultBranch: input.defaultBranch }),
              });
            } catch (error) {
              const msg = (error as Error).message;
              if (msg.includes('UNIQUE') || msg.includes('unique')) {
                throw new TRPCError({
                  code: 'CONFLICT',
                  message: `A project with that name or URL already exists`,
                });
              }
              throw error;
            }

            if (ctx.workspaceRoot) {
              const clonePath = join(ctx.workspaceRoot, getProjectCloneDir(input.name, project.id));

              try {
                await cloneProject(input.url, clonePath);
              } catch (cloneError) {
                await repo.delete(project.id);
                throw new TRPCError({
                  code: 'INTERNAL_SERVER_ERROR',
                  message: `Failed to clone repository: ${(cloneError as Error).message}`,
                });
              }

              // Validate that the specified default branch exists in the cloned repo
              const branchToValidate = input.defaultBranch ?? 'main';
              if (ctx.branchManager) {
                const exists = await ctx.branchManager.remoteBranchExists(clonePath, branchToValidate);
                if (!exists) {
                  // Clean up: remove project and clone
                  await rm(clonePath, { recursive: true, force: true }).catch(() => {});
                  await repo.delete(project.id);
                  throw new TRPCError({
                    code: 'BAD_REQUEST',
                    message: `Branch '${branchToValidate}' does not exist in the repository`,
                  });
                }
              }
            }

            return project;
          }),

        listProjects: publicProcedure
          .query(async ({ ctx }) => {
            const repo = requireProjectRepository(ctx);
            return repo.findAll();
          }),

        getProject: publicProcedure
          .input(z.object({ id: z.string().min(1) }))
          .query(async ({ ctx, input }) => {
            const repo = requireProjectRepository(ctx);
            const project = await repo.findById(input.id);
            if (!project) {
              throw new TRPCError({
                code: 'NOT_FOUND',
                message: `Project '${input.id}' not found`,
              });
            }
            return project;
          }),

        deleteProject: publicProcedure
          .input(z.object({ id: z.string().min(1) }))
          .mutation(async ({ ctx, input }) => {
            const repo = requireProjectRepository(ctx);
            const project = await repo.findById(input.id);
            if (project && ctx.workspaceRoot) {
              const clonePath = join(ctx.workspaceRoot, getProjectCloneDir(project.name, project.id));
              await rm(clonePath, { recursive: true, force: true }).catch(() => {});
            }
            await repo.delete(input.id);
            return { success: true };
          }),

        updateProject: publicProcedure
          .input(z.object({
            id: z.string().min(1),
            defaultBranch: z.string().min(1).optional(),
          }))
          .mutation(async ({ ctx, input }) => {
            const repo = requireProjectRepository(ctx);
            const { id, ...data } = input;
            const existing = await repo.findById(id);
            if (!existing) {
              throw new TRPCError({
                code: 'NOT_FOUND',
                message: `Project '${id}' not found`,
              });
            }

            // Validate that the new default branch exists in the repo
            if (data.defaultBranch && ctx.workspaceRoot && ctx.branchManager) {
              const clonePath = join(ctx.workspaceRoot, getProjectCloneDir(existing.name, existing.id));
              const exists = await ctx.branchManager.remoteBranchExists(clonePath, data.defaultBranch);
              if (!exists) {
                throw new TRPCError({
                  code: 'BAD_REQUEST',
                  message: `Branch '${data.defaultBranch}' does not exist in the repository`,
                });
              }
            }

            return repo.update(id, data);
          }),

        getInitiativeProjects: publicProcedure
          .input(z.object({ initiativeId: z.string().min(1) }))
          .query(async ({ ctx, input }) => {
            const repo = requireProjectRepository(ctx);
            return repo.findProjectsByInitiativeId(input.initiativeId);
          }),

        updateInitiativeProjects: publicProcedure
          .input(z.object({
            initiativeId: z.string().min(1),
            projectIds: z.array(z.string().min(1)).min(1),
          }))
          .mutation(async ({ ctx, input }) => {
            const repo = requireProjectRepository(ctx);
            await repo.setInitiativeProjects(input.initiativeId, input.projectIds);
            return { success: true };
          }),
      };
    }