All files / src/services/elevenLabsFirebase/signInWithPassword index.ts

62.5% Statements 10/16
33.33% Branches 2/6
100% Functions 1/1
62.5% Lines 10/16

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                    1x 1x       1x 1x                                 1x 1x   1x                     1x   1x       1x    
import { proxyAgentPool } from "@/lib/proxyAgentPool";
import { RequestType } from "./request";
import { Response, fetch as undiciFetch } from "undici";
import { ResponseSchema } from "./response";
import { NoThrow } from "@/utils/NoThrow";
import { ELEVEN_LABS_FIREBASE_API_KEY } from "../constants";
import { requestHeaders } from "@/requestHeaders";
 
// Handle errors properly
export async function signInWithPassword(req: RequestType) {
    const body = JSON.stringify({ returnSecureToken: true, ...req });
    const url = `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${ELEVEN_LABS_FIREBASE_API_KEY}`;
 
    let response: Response;
 
    try {
        response = await undiciFetch(url, {
            method: "POST",
            body,
            headers: {
                ...requestHeaders,
                "Content-Type": "application/json",
                Referer: "https://elevenlabs.io/app/sign-in",
                Origin: "https://elevenlabs.io",
            },
            dispatcher: proxyAgentPool.get(req.proxyURL),
        });
    } catch (error) {
        return NoThrow.createError(`Error fetching ${url}`, { cause: error });
    }
 
    let json: unknown;
 
    try {
        json = await response.json();
 
        Iif (response.status !== 200) {
            return NoThrow.error(new Error("Response status !== 200", { cause: json }));
        }
    } catch (error) {
        if (error instanceof SyntaxError) {
            return NoThrow.error(error);
        }
 
        return NoThrow.createError("Error parsing json", { cause: error });
    }
 
    const validatedDataResult = await ResponseSchema.safeParseAsync(json);
 
    Iif (!validatedDataResult.success) {
        return NoThrow.error(validatedDataResult.error);
    }
 
    return NoThrow.success(validatedDataResult.data);
}