/ opencodehub / src / lib / stacks.ts
swadhinbiswas Fix: Add date validation in analysis.ts to prevent RangeError · 1/20/2026
a7662cd
299 lines · 8.7 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
 * Stacked PRs Library
 * Core functions for managing stacked pull request workflows
 */

import { eq, and, asc, desc } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { getDatabase, schema } from "@/db";
import { generateId } from "./utils";

// Types
export interface StackInfo {
    stack: typeof schema.prStacks.$inferSelect;
    entries: Array<{
        entry: typeof schema.prStackEntries.$inferSelect;
        pr: typeof schema.pullRequests.$inferSelect;
    }>;
}

export interface CreateStackOptions {
    repositoryId: string;
    baseBranch: string;
    name?: string;
    createdById: string;
}

export interface AddToStackOptions {
    stackId: string;
    pullRequestId: string;
    parentPrId?: string;
}

/**
 * Create a new PR stack
 */
export async function createStack(options: CreateStackOptions): Promise<typeof schema.prStacks.$inferSelect> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;
    const id = generateId();

    const stack = {
        id,
        repositoryId: options.repositoryId,
        baseBranch: options.baseBranch,
        name: options.name || null,
        status: "active",
        createdById: options.createdById,
        createdAt: new Date(),
        updatedAt: new Date(),
    };

    await db.insert(schema.prStacks).values(stack);
    return stack as typeof schema.prStacks.$inferSelect;
}

/**
 * Get stack by ID with all entries and PRs
 */
export async function getStack(stackId: string): Promise<StackInfo | null> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const stack = await db.query.prStacks.findFirst({
        where: eq(schema.prStacks.id, stackId),
    });

    if (!stack) return null;

    const entries = await db.query.prStackEntries.findMany({
        where: eq(schema.prStackEntries.stackId, stackId),
        orderBy: [asc(schema.prStackEntries.stackOrder)],
    });

    const entriesWithPrs = await Promise.all(
        entries.map(async (entry) => {
            const pr = await db.query.pullRequests.findFirst({
                where: eq(schema.pullRequests.id, entry.pullRequestId),
            });
            return { entry, pr: pr! };
        })
    );

    return { stack, entries: entriesWithPrs };
}

/**
 * Get stack for a specific PR
 */
export async function getStackForPr(pullRequestId: string): Promise<StackInfo | null> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const entry = await db.query.prStackEntries.findFirst({
        where: eq(schema.prStackEntries.pullRequestId, pullRequestId),
    });

    if (!entry) return null;

    return getStack(entry.stackId);
}

/**
 * Add a PR to an existing stack
 */
export async function addToStack(options: AddToStackOptions): Promise<typeof schema.prStackEntries.$inferSelect> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    // Get current max order in stack
    const existingEntries = await db.query.prStackEntries.findMany({
        where: eq(schema.prStackEntries.stackId, options.stackId),
        orderBy: [desc(schema.prStackEntries.stackOrder)],
    });

    const maxOrder = existingEntries.length > 0 ? existingEntries[0].stackOrder : 0;

    const entry = {
        id: generateId(),
        stackId: options.stackId,
        pullRequestId: options.pullRequestId,
        stackOrder: maxOrder + 1,
        parentPrId: options.parentPrId || (existingEntries[0]?.pullRequestId || null),
        createdAt: new Date(),
    };

    await db.insert(schema.prStackEntries).values(entry);

    // Update stack timestamp
    await db.update(schema.prStacks)
        .set({ updatedAt: new Date() })
        .where(eq(schema.prStacks.id, options.stackId));

    return entry as typeof schema.prStackEntries.$inferSelect;
}

/**
 * Remove a PR from its stack
 */
export async function removeFromStack(pullRequestId: string): Promise<void> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const entry = await db.query.prStackEntries.findFirst({
        where: eq(schema.prStackEntries.pullRequestId, pullRequestId),
    });

    if (!entry) return;

    // Delete the entry
    await db.delete(schema.prStackEntries)
        .where(eq(schema.prStackEntries.pullRequestId, pullRequestId));

    // Update order of remaining entries
    const remainingEntries = await db.query.prStackEntries.findMany({
        where: eq(schema.prStackEntries.stackId, entry.stackId),
        orderBy: [asc(schema.prStackEntries.stackOrder)],
    });

    // Re-number and update parent references
    for (let i = 0; i < remainingEntries.length; i++) {
        const parentPrId = i > 0 ? remainingEntries[i - 1].pullRequestId : null;
        await db.update(schema.prStackEntries)
            .set({ stackOrder: i + 1, parentPrId })
            .where(eq(schema.prStackEntries.id, remainingEntries[i].id));
    }

    // If stack is now empty, mark it as closed
    if (remainingEntries.length === 0) {
        await db.update(schema.prStacks)
            .set({ status: "closed", updatedAt: new Date() })
            .where(eq(schema.prStacks.id, entry.stackId));
    }
}

/**
 * Reorder PRs within a stack
 */
export async function reorderStack(stackId: string, newOrder: string[]): Promise<void> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    for (let i = 0; i < newOrder.length; i++) {
        const parentPrId = i > 0 ? newOrder[i - 1] : null;

        await db.update(schema.prStackEntries)
            .set({ stackOrder: i + 1, parentPrId })
            .where(
                and(
                    eq(schema.prStackEntries.stackId, stackId),
                    eq(schema.prStackEntries.pullRequestId, newOrder[i])
                )
            );
    }

    await db.update(schema.prStacks)
        .set({ updatedAt: new Date() })
        .where(eq(schema.prStacks.id, stackId));
}

/**
 * Get all active stacks for a repository
 */
export async function getRepositoryStacks(repositoryId: string): Promise<Array<StackInfo>> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const stacks = await db.query.prStacks.findMany({
        where: and(
            eq(schema.prStacks.repositoryId, repositoryId),
            eq(schema.prStacks.status, "active")
        ),
        orderBy: [desc(schema.prStacks.updatedAt)],
    });

    const stackInfos = await Promise.all(
        stacks.map(async (stack) => {
            const info = await getStack(stack.id);
            return info!;
        })
    );

    return stackInfos.filter(Boolean);
}

/**
 * Check if a PR can be stacked on another PR
 */
export async function canStackOn(prId: string, targetPrId: string): Promise<boolean> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    const targetPr = await db.query.pullRequests.findFirst({
        where: eq(schema.pullRequests.id, targetPrId),
    });

    const pr = await db.query.pullRequests.findFirst({
        where: eq(schema.pullRequests.id, prId),
    });

    if (!targetPr || !pr) return false;

    // Must be same repository
    if (pr.repositoryId !== targetPr.repositoryId) return false;

    // Target must be open
    if (targetPr.state !== "open") return false;

    // Can't stack on itself
    if (prId === targetPrId) return false;

    return true;
}

/**
 * Get visualization data for a stack (for UI rendering)
 */
export async function getStackVisualization(stackId: string) {
    const stackInfo = await getStack(stackId);
    if (!stackInfo) return null;

    return {
        id: stackInfo.stack.id,
        name: stackInfo.stack.name,
        baseBranch: stackInfo.stack.baseBranch,
        status: stackInfo.stack.status,
        entries: stackInfo.entries.map(({ entry, pr }) => ({
            order: entry.stackOrder,
            pr: {
                id: pr.id,
                number: pr.number,
                title: pr.title,
                state: pr.state,
                isDraft: pr.isDraft,
                headBranch: pr.headBranch,
                isMerged: pr.isMerged,
            },
            parentPrId: entry.parentPrId,
        })),
    };
}

/**
 * Mark a stack as merged when all PRs are merged
 */
export async function updateStackStatus(stackId: string): Promise<void> {
    const db = getDatabase() as NodePgDatabase<typeof schema>;
    const stackInfo = await getStack(stackId);

    if (!stackInfo) return;

    const allMerged = stackInfo.entries.every(({ pr }) => pr.isMerged);
    const anyClosed = stackInfo.entries.some(({ pr }) => pr.state === "closed" && !pr.isMerged);

    let newStatus = "active";
    if (allMerged) {
        newStatus = "merged";
    } else if (anyClosed) {
        newStatus = "closed";
    }

    if (newStatus !== stackInfo.stack.status) {
        await db.update(schema.prStacks)
            .set({ status: newStatus, updatedAt: new Date() })
            .where(eq(schema.prStacks.id, stackId));
    }
}