(op: Operation, input: Record<string, unknown> = {})
| 33 | } |
| 34 | |
| 35 | async call<T>(op: Operation, input: Record<string, unknown> = {}): Promise<T> { |
| 36 | if (op.auth === 'token' && !this.token) { |
| 37 | throw new ApiError( |
| 38 | 401, |
| 39 | 'not_logged_in', |
| 40 | 'Not signed in. Run `npx @decap/cli login` in a terminal.', |
| 41 | ); |
| 42 | } |
| 43 | |
| 44 | // Path segments, query and body come from the contract's buildRequest, so |
| 45 | // the CLI and the MCP server address the API the same way. |
| 46 | const request = buildRequest(op, input); |
| 47 | const url = new URL(`${this.apiUrl}/api/v1${request.path}`); |
| 48 | for (const [key, value] of Object.entries(request.query)) url.searchParams.set(key, value); |
| 49 | |
| 50 | const headers: Record<string, string> = { |
| 51 | accept: 'application/json', |
| 52 | 'user-agent': `decap-cli/${CLI_VERSION} (${this.client})`, |
| 53 | 'x-decap-client': this.client, |
| 54 | }; |
| 55 | if (op.auth === 'token' && this.token) headers.authorization = `Bearer ${this.token}`; |
| 56 | |
| 57 | let body: string | undefined; |
| 58 | if (op.method !== 'GET') { |
| 59 | // On every non-GET, even a body-less DELETE: Astro's cross-site check |
| 60 | // refuses a mutating request with no Content-Type and no matching |
| 61 | // Origin, and a CLI sends no Origin. |
| 62 | headers['content-type'] = 'application/json'; |
| 63 | if (request.body) body = JSON.stringify(request.body); |
| 64 | } |
| 65 | |
| 66 | let response: Response; |
| 67 | try { |
| 68 | response = await fetch(url, { method: op.method, headers, body, redirect: 'manual' }); |
| 69 | } catch (err) { |
| 70 | throw new ApiError( |
| 71 | 0, |
| 72 | 'network_error', |
| 73 | `Could not reach ${this.apiUrl}: ${(err as Error).message}`, |
| 74 | ); |
| 75 | } |
| 76 | |
| 77 | if (response.status === 204) return undefined as T; |
| 78 | |
| 79 | const text = await response.text(); |
| 80 | let parsed: unknown = null; |
| 81 | try { |
| 82 | parsed = text ? JSON.parse(text) : null; |
| 83 | } catch { |
| 84 | // Not JSON: a proxy error page, or the password wall on a non-production deploy. |
| 85 | } |
| 86 | |
| 87 | if (!response.ok) { |
| 88 | const error = (parsed as { error?: { code?: string; message?: string } } | null)?.error; |
| 89 | throw new ApiError( |
| 90 | response.status, |
| 91 | error?.code ?? 'http_error', |
| 92 | error?.message ?? `${op.method} ${url.pathname} answered ${response.status}.`, |
no test coverage detected