/**
 * Get normalized URL of the API,
 * by combining server URL with absolute or
 * relative API pathname
 *
 * @example
 * getAPIUrl('https://localhost/p1/p2?q=1', '/v1/api').href;
 * // returns 'https://localhost/v1/api?q=1'
 *
 * getAPIUrl('https://localhost/p1/p2?q=1', './v2/api').href;
 * // returns 'https://localhost/p1/p2/v2/api?q=1'
 *
 * getAPIUrl('https://localhost/p1/p2?q=1', './p3//v3/api').href;
 * // returns 'https://localhost/v3/api?q=1'
 *
 * @param {string} serverUrl - base API server URL
 * @param {string} path - API path
 * @returns {URL} fully qualified URL to call API
 */
export const getApiUrl = (serverUrl, path) => {
    const apiUrl = new URL(serverUrl);
    apiUrl.pathname = apiUrl.pathname +
        (apiUrl.pathname.endsWith('/') ? '' : '/') +
        (path.startsWith('./') ? path.slice(2) : path);
    const idx = apiUrl.pathname.lastIndexOf('//');
    if (idx >= 0) {
        apiUrl.pathname = apiUrl.pathname.slice(idx + 1);
    }
    return apiUrl;
};
