| 21 | import { enforceSameOrigin } from "./pull-request-shared.js"; |
| 22 | |
| 23 | export function commentRoutes(db: StageDb): Route[] { |
| 24 | return [ |
| 25 | // Threads are anchored to a diff scope, not a run, so they survive re-imports |
| 26 | // of the same diff. We resolve the run's scope key and key every query off it. |
| 27 | { |
| 28 | method: "GET", |
| 29 | pattern: "/api/runs/:runId/comment-threads", |
| 30 | handler: (_req, res, params) => { |
| 31 | const scopeKey = resolveRunScopeKey(db, params.runId); |
| 32 | if (scopeKey === null) { |
| 33 | writeJson(res, 404, { error: `Run ${params.runId} not found` }); |
| 34 | return; |
| 35 | } |
| 36 | writeJson(res, 200, listThreads(db, scopeKey)); |
| 37 | }, |
| 38 | }, |
| 39 | { |
| 40 | method: "POST", |
| 41 | pattern: "/api/runs/:runId/comment-threads", |
| 42 | handler: async (req, res, params) => { |
| 43 | if (!enforceSameOrigin(req, res)) return; |
| 44 | const scopeKey = resolveRunScopeKey(db, params.runId); |
| 45 | if (scopeKey === null) { |
| 46 | writeJson(res, 404, { error: `Run ${params.runId} not found` }); |
| 47 | return; |
| 48 | } |
| 49 | const body = await parseJsonBody(req, res, CreateCommentThreadBodySchema); |
| 50 | if (!body) return; |
| 51 | |
| 52 | const created = db.transaction((tx) => { |
| 53 | const [threadRow] = tx |
| 54 | .insert(commentThread) |
| 55 | .values({ |
| 56 | scopeKey, |
| 57 | filePath: body.filePath, |
| 58 | side: body.side, |
| 59 | startLine: body.startLine, |
| 60 | endLine: body.endLine, |
| 61 | }) |
| 62 | .returning() |
| 63 | .all(); |
| 64 | if (!threadRow) throw new Error("comment_thread insert returned no row"); |
| 65 | const [commentRow] = tx |
| 66 | .insert(comment) |
| 67 | .values({ threadId: threadRow.id, authorId: LOCAL_USER_ID, body: body.body }) |
| 68 | .returning() |
| 69 | .all(); |
| 70 | if (!commentRow) throw new Error("comment insert returned no row"); |
| 71 | return toThreadDto(threadRow, [commentRow]); |
| 72 | }); |
| 73 | writeJson(res, 201, created); |
| 74 | }, |
| 75 | }, |
| 76 | { |
| 77 | method: "POST", |
| 78 | pattern: "/api/comment-threads/:threadId/replies", |
| 79 | handler: async (req, res, params) => { |
| 80 | if (!enforceSameOrigin(req, res)) return; |