All files / packages/dataflint-mcp/src copilot-config-client.ts

98.57% Statements 69/70
80.95% Branches 17/21
100% Functions 4/4
98.57% Lines 69/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 831x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 7x 7x 7x 7x 7x 7x 7x 7x 5x 5x 7x 7x   1x 1x   1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 2x 2x   2x 2x 2x 2x 2x 2x 11x 11x 2x 2x 7x 7x 7x 11x 1x 1x 6x 11x 2x 2x 4x 11x 1x  
import { z } from "zod";
import { Logger } from "./logger";
 
interface ConfigServiceLike {
    getServerUrl(): string;
}
 
const CopilotConfigSchema = z.object({
    auth: z.object({
        url: z.string(),
        audience: z.string(),
        client_id: z.string(),
        scopes: z
            .array(
                z
                    .string()
                    .min(1)
                    .regex(/^[a-zA-Z0-9_:-]+$/, "invalid scope token")
            )
            .default([]),
    }),
});
 
export type CopilotConfig = z.infer<typeof CopilotConfigSchema>;
 
export type BackendFaultReason = "network" | "http_5xx" | "invalid_response";
 
export class BackendFault extends Error {
    readonly name = "BackendFault";
    constructor(
        readonly host: string,
        readonly reason: BackendFaultReason,
        cause?: unknown
    ) {
        super(`BackendFault(${reason}) reaching ${host}`);
        if (cause !== undefined) {
            (this as { cause?: unknown }).cause = cause;
        }
    }
}
 
export class CopilotConfigClient {
    constructor(private readonly configService: ConfigServiceLike) {}
 
    async getConfig(): Promise<CopilotConfig> {
        const serverUrl = this.configService.getServerUrl();
        const host = new URL(serverUrl).host;
        const url = `${serverUrl}/api/public/copilot/config`;
        const logger = Logger.tryGetInstance();
        logger?.info(`[copilot-config] fetching ${url}`);
        let response: Response;
        try {
            response = await fetch(url, {
                headers: { Accept: "application/json" },
            });
        } catch (err) {
            const cause =
                err instanceof Error && err.cause instanceof Error
                    ? ` (${(err.cause as NodeJS.ErrnoException).code ?? err.cause.message})`
                    : "";
            logger?.warn(
                `[copilot-config] network error reaching ${host}: ${err instanceof Error ? err.message : String(err)}${cause}`
            );
            throw new BackendFault(host, "network", err);
        }
        logger?.info(`[copilot-config] ${url} responded ${response.status}`);
        if (response.status >= 500) {
            throw new BackendFault(host, "http_5xx");
        }
        let json: unknown;
        try {
            json = await response.json();
        } catch (err) {
            throw new BackendFault(host, "invalid_response", err);
        }
        const parsed = CopilotConfigSchema.safeParse(json);
        if (!parsed.success) {
            throw new BackendFault(host, "invalid_response", parsed.error);
        }
        return parsed.data;
    }
}