(
opts: {
method: string; pathname: string; tokenOk: boolean; body: any; cwd: string;
renderHtml: () => Promise<string>; getState: () => Promise<any>;
},
)
| 21 | /** Pure-ish request router: (method, pathname, token-ok, json body) → response. Used by the |
| 22 | * server and by tests. `renderHtml` / `getState` are injected so this stays decoupled. */ |
| 23 | export async function handleRequest( |
| 24 | opts: { |
| 25 | method: string; pathname: string; tokenOk: boolean; body: any; cwd: string; |
| 26 | renderHtml: () => Promise<string>; getState: () => Promise<any>; |
| 27 | }, |
| 28 | ): Promise<RouteResult> { |
| 29 | const json = (status: number, obj: any): RouteResult => ({ status, body: JSON.stringify(obj), contentType: 'application/json' }); |
| 30 | if (!opts.tokenOk) return json(401, { ok: false, message: 'Unauthorized — missing or bad token.' }); |
| 31 | |
| 32 | if (opts.method === 'GET' && (opts.pathname === '/' || opts.pathname === '')) { |
| 33 | return { status: 200, body: await opts.renderHtml(), contentType: 'text/html; charset=utf-8' }; |
| 34 | } |
| 35 | if (opts.method === 'GET' && opts.pathname === '/api/state') { |
| 36 | return json(200, { ok: true, state: await opts.getState() }); |
| 37 | } |
| 38 | if (opts.method === 'POST' && opts.pathname === '/api/action') { |
| 39 | const name = String(opts.body?.action ?? ''); |
| 40 | if (!name) return json(400, { ok: false, message: 'Missing action.' }); |
| 41 | const result = await dispatchAction(name, opts.body?.params ?? {}, opts.cwd); |
| 42 | return json(result.ok ? 200 : 400, result); |
| 43 | } |
| 44 | return json(404, { ok: false, message: 'Not found.' }); |
| 45 | } |
| 46 | |
| 47 | /** Start the control server on 127.0.0.1. `renderHtml`/`getState` close over the token so the |
| 48 | * page can call the API. Returns a handle with the tokened URL. */ |
no test coverage detected