File size: 2,320 Bytes
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Search REST API
 *
 * POST /api/search          β€” ε…¨ε±€ε·₯作区搜紒
 * POST /api/search/sessions β€” ζœη΄’δΌšθ―εŽ†ε²
 */

import { SearchService } from '../services/searchService.js'
import { ApiError, errorResponse } from '../middleware/errorHandler.js'

const searchService = new SearchService()

export async function handleSearchApi(
  req: Request,
  _url: URL,
  segments: string[],
): Promise<Response> {
  try {
    const method = req.method
    const sub = segments[2] // 'sessions' | undefined

    if (method !== 'POST') {
      throw new ApiError(
        405,
        `Method ${method} not allowed. Use POST.`,
        'METHOD_NOT_ALLOWED',
      )
    }

    const body = await parseJsonBody(req)
    const query = body.query as string
    if (!query || typeof query !== 'string') {
      throw ApiError.badRequest('Missing or invalid "query" in request body')
    }

    // ── POST /api/search/sessions ──────────────────────────────────────────
    if (sub === 'sessions') {
      const results = await searchService.searchSessions(query)
      return Response.json({ results })
    }

    // ── POST /api/search ───────────────────────────────────────────────────
    if (!sub) {
      const results = await searchService.searchWorkspace(query, {
        cwd: body.cwd as string | undefined,
        maxResults: body.maxResults as number | undefined,
        glob: body.glob as string | undefined,
        caseSensitive: body.caseSensitive as boolean | undefined,
      })
      return Response.json({ results, total: results.length })
    }

    throw ApiError.notFound(`Unknown search endpoint: ${sub}`)
  } catch (error) {
    return errorResponse(error)
  }
}

// ─── Helpers ────────────────────────────────────────────────────────────────

async function parseJsonBody(req: Request): Promise<Record<string, unknown>> {
  try {
    return (await req.json()) as Record<string, unknown>
  } catch {
    throw ApiError.badRequest('Invalid JSON body')
  }
}