All files / blong-gogo/src lib.ts

58.21% Statements 124/213
80% Branches 28/35
72.72% Functions 8/11
58.21% Lines 124/213

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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 2141x 1x 1x 2349x 2349x 2193x 2057x 136x 136x 136x   2193x 2349x 2349x 1x 1x 242x 242x 242x 242x 242x 242x 1x 1x     1x 1x       1x 1x 295x 295x 295x 295x 295x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 6x 6x 9x 13x 6x 6x 13x 7x 7x 13x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42x 42x 42x 42x 33x 33x 35x 13x 13x 22x 22x 33x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x                               2x 2x     1x 1x                                                                                                                            
import ky from 'ky';
 
export function methodId<T>(what: T): T {
    return (
        what &&
        ((typeof what === 'string'
            ? what.replace(/\./g, '').toLowerCase()
            : typeof what === 'object'
              ? Object.fromEntries(
                    Object.entries(what).map(([name, value]) => [methodId(name), value]),
                )
              : what) as T)
    );
}
 
export function methodParts(what: string): string {
    if (what.includes('.')) return what;
    const lowercase = (match: string, word1: string, word2: string, letter: string): string =>
        `${word1}.${word2.toLowerCase()}${letter ? '.' + letter.toLowerCase() : ''}`;
    const capitalWords = /^([^A-Z]+)([A-Z][^A-Z]+)([A-Z])?/;
    return what.replace(capitalWords, lowercase);
}
 
export function snakeToCamel(string: string): string {
    return string.replace(/([-_]\w)/g, g => g[1].toUpperCase());
}
 
export function identifier(string: string): string {
    string = snakeToCamel(string);
    return /[^\w$]/.test(string) ? `'${string}'` : string;
}
 
export function camelToSentence(str: string): string {
    return str
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
        .toLowerCase();
}
 
export interface IAnnotation {
    name: string;
    params: string[];
}
 
export function parseAnnotatedKey(key: string): {
    annotations: IAnnotation[];
    handlerName: string;
} {
    const tokens = key.trim().split(/\s+/);
    const handlerName = tokens.pop()!;
    if (!handlerName || handlerName.startsWith('@')) {
        throw new Error(
            `Malformed annotated key "${key}": the last token must be a non-empty handler name and must not start with "@".`,
        );
    }
    const annotations: IAnnotation[] = [];
    let current: IAnnotation | null = null;
    for (const token of tokens) {
        if (token.startsWith('@')) {
            current = {name: token.slice(1), params: []};
            annotations.push(current);
        } else if (current) {
            current.params.push(token);
        }
    }
    return {annotations, handlerName};
}
 
/**
 * Returns true when an error type matches the `expect` declaration on `$meta`.
 *
 * Matching rules:
 *  - Exact string: `'foo.bar'` matches only `foo.bar`
 *  - Array of strings: any element that matches (exact or wildcard)
 *  - Wildcard prefix: `'foo.*'` matches any type starting with `foo.`
 */
export function isExpectedError(
    errorType: string | undefined,
    expect: string | string[] | undefined,
): boolean {
    if (!errorType || !expect) return false;
    const patterns = ([] as string[]).concat(expect);
    return patterns.some(pattern => {
        if (pattern.endsWith('.*')) {
            return errorType.startsWith(pattern.slice(0, -1));
        }
        return errorType === pattern;
    });
}
 
let loginCache: Promise<{protocol: string; hostname: string; port: number}> | null = null;
export async function loginService(
    discovery: (service: string) => Promise<{protocol: string; hostname: string; port: number}>,
): Promise<{protocol: string; hostname: string; port: number}> {
    if (!loginCache) loginCache = discovery('login');
    try {
        return await loginCache;
    } catch (error) {
        loginCache = null;
        throw error;
    }
}
 
export async function requestGet(
    url: string,
    errorHttp: (params: Record<string, unknown>) => unknown,
    errorEmpty: () => unknown,
    headers: Record<string, string | undefined> | undefined,
    protocol: string,
    tls: Record<string, unknown> | undefined,
): Promise<unknown> {
    const response = await ky.get(url, {
        ...tls,
        ...(headers && {
            headers: {
                'x-forwarded-proto': headers['x-forwarded-proto'] || protocol,
                'x-forwarded-host': headers['x-forwarded-host'] || headers.host,
            },
        }),
        throwHttpErrors: false,
    });
 
    const responseText = await response.text();
    let body: {[key: string]: unknown} | undefined;
    try {
        body = responseText ? JSON.parse(responseText) : undefined;
    } catch {
        body = undefined;
    }
 
    if (response.status < 200 || response.status >= 300) {
        throw errorHttp({
            statusCode: response.status,
            statusText: response.statusText,
            statusMessage: response.statusText,
            validation: body?.validation,
            debug: body?.debug,
            params: {
                code: response.status,
            },
            req: {
                url: response.url,
                method: 'GET',
            },
        });
    }
 
    if (body) return body;
    throw errorEmpty();
}
 
export async function requestPostForm(
    url: string,
    errorHttp: (params: Record<string, unknown>) => unknown,
    errorEmpty: () => unknown,
    headers: Record<string, string | undefined> | undefined,
    protocol: string,
    tls: Record<string, unknown> | undefined,
    form: Record<string, string | number | boolean | null | undefined> | URLSearchParams,
): Promise<string> {
    const forwardedHeaders = headers && {
        'x-forwarded-proto': headers['x-forwarded-proto'] || protocol,
        'x-forwarded-host': headers['x-forwarded-host'] || headers.host,
    };

    const body =
        form instanceof URLSearchParams
            ? form
            : new URLSearchParams(
                  Object.entries(form).map(([key, value]) => [
                      key,
                      value == null ? '' : String(value),
                  ]),
              );

    const response = await ky.post(url, {
        ...tls,
        headers: {
            ...(forwardedHeaders || {}),
            'content-type': 'application/x-www-form-urlencoded',
        },
        body,
        throwHttpErrors: false,
    });

    const responseText = await response.text();
    let responseJson: {[key: string]: unknown} | undefined;
    try {
        responseJson = responseText ? JSON.parse(responseText) : undefined;
    } catch {
        responseJson = undefined;
    }

    if (response.status < 200 || response.status >= 300) {
        throw errorHttp({
            statusCode: response.status,
            statusText: response.statusText,
            statusMessage: response.statusText,
            validation: responseJson?.validation,
            debug: responseJson?.debug,
            params: {
                code: response.status,
            },
            req: {
                url: response.url,
                method: 'POST',
            },
        });
    }

    if (responseText) return responseText;
    throw errorEmpty();
}