All files apiClient.js

84.14% Statements 69/82
58.2% Branches 78/134
92.85% Functions 13/14
85.89% Lines 67/78

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 214    1x     4x 4x 4x       3x       1x                     4x   4x     4x 4x   4x       4x     7x         7x 7x       3x     3x             7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x       1x 1x 1x   6x 6x               4x       3x 3x 1x   2x       1x       1x 1x       1x                   1x 1x 1x 1x                                 1x 1x 1x 1x   1x 1x 1x                         1x 1x 1x 1x 1x 1x     1x 1x 1x                     1x 1x                                       4x                   1x  
'use strict';
 
const { USER_AGENT } = require('./constants');
 
function stripTrailingSlash(s) {
  let out = (s || '').trim();
  while (out.endsWith('/')) out = out.slice(0, -1);
  return out;
}
 
function urlEncodePathSegment(s) {
  return encodeURIComponent(s).replace(/\+/g, '%20');
}
 
function urlEncodeQuery(s) {
  return encodeURIComponent(s);
}
 
/**
 * @param {object} opts
 * @param {string} opts.baseUrl
 * @param {string|null} [opts.tenantId]
 * @param {(msg: string) => void} [opts.log]
 * @param {typeof fetch} [opts.fetchFn]
 */
function createApiClient(opts) {
  const baseUrl = stripTrailingSlash(opts.baseUrl);
  const tenantId =
    opts.tenantId == null || String(opts.tenantId).trim() === ''
      ? null
      : String(opts.tenantId).trim();
  const log = opts.log || (() => {});
  const fetchFn = opts.fetchFn || globalThis.fetch;
 
  Iif (typeof fetchFn !== 'function') {
    throw new Error('fetch is not available; pass fetchFn (Node 18+)');
  }
 
  let bearerToken = null;
 
  function baseHeaders() {
    const h = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'User-Agent': USER_AGENT,
    };
    Iif (tenantId) h['X-Tenant-ID'] = tenantId;
    return h;
  }
 
  function authedHeaders() {
    Iif (!bearerToken || !String(bearerToken).trim()) {
      throw new Error('No bearer token set; call login() first');
    }
    return {
      ...baseHeaders(),
      Authorization: `Bearer ${bearerToken}`,
    };
  }
 
  async function sendJson(method, path, { body, auth = true } = {}) {
    const url = baseUrl + path;
    const headers = auth ? authedHeaders() : baseHeaders();
    log(`[ShiftLeft] Request: ${method} ${url}`);
    const init = { method, headers, redirect: 'follow' };
    if (body !== undefined) init.body = body;
    const resp = await fetchFn(url, init);
    const text = await resp.text();
    log(`[ShiftLeft] Response: HTTP ${resp.status}`);
    if (!resp.ok) {
      const snippet = text && text.length > 2000 ? text.slice(0, 2000) + '...' : text || '';
      let msg = `HTTP ${resp.status} calling ${url}`;
      Iif (resp.status === 502) {
        msg +=
          '. Bad Gateway: proxy/server may not reach the backend. Check backend health and URL.';
      }
      log(`[ShiftLeft] ${msg}`);
      Eif (snippet) log(`[ShiftLeft] Response body: ${snippet}`);
      throw new Error(msg);
    }
    try {
      return text ? JSON.parse(text) : {};
    } catch (e) {
      log(`[ShiftLeft] Invalid JSON from ${url}`);
      throw new Error(`Invalid JSON from ${url}: ${e.message}`);
    }
  }
 
  async function login(email, password) {
    const json = await sendJson('POST', '/api/v1/login', {
      body: JSON.stringify({ email, password }),
      auth: false,
    });
    const token = json.token;
    if (token == null || String(token).trim() === '') {
      throw new Error('Login succeeded but token was missing in response');
    }
    return String(token);
  }
 
  function setBearerToken(token) {
    bearerToken = token;
  }
 
  async function triggerTestPack(packId) {
    const enc = urlEncodePathSegment(packId);
    const json = await sendJson('POST', `/api/v1/test-packs/${enc}/run`, {
      body: undefined,
      auth: true,
    });
    return {
      message: json.message ?? null,
      executionId: json.executionId ?? null,
      packId: json.packId ?? null,
      status: json.status ?? null,
      startTimeIso: json.startTime ?? null,
    };
  }
 
  async function getStatus(packId) {
    const enc = urlEncodePathSegment(packId);
    const json = await sendJson('GET', `/api/v1/test-packs/${enc}/status`, { auth: true });
    const summary = json.summary || {};
    return {
      packId: json.packId ?? null,
      name: json.name ?? null,
      status: json.status ?? null,
      executionId: json.executionId ?? null,
      startTimeIso: json.startTime ?? null,
      endTimeIso: json.endTime ?? null,
      summaryTotal: summary.total != null ? Number(summary.total) : 0,
      summaryPassed: summary.passed != null ? Number(summary.passed) : 0,
      summaryFailed: summary.failed != null ? Number(summary.failed) : 0,
      summaryError: summary.error != null ? Number(summary.error) : 0,
      summarySuccessRate:
        summary.successRate != null ? Number(summary.successRate) : 0.0,
    };
  }
 
  async function getResults(packId, executionId) {
    const enc = urlEncodePathSegment(packId);
    let path = `/api/v1/test-packs/${enc}/results`;
    Eif (executionId != null && String(executionId).trim() !== '') {
      path += `?executionId=${urlEncodeQuery(String(executionId).trim())}`;
    }
    const json = await sendJson('GET', path, { auth: true });
    const summary = json.summary;
    const r = {
      packId: json.packId ?? null,
      packName: json.packName ?? null,
      executionId: json.executionId ?? null,
      startTimeIso: json.startTime ?? null,
      endTimeIso: json.endTime ?? null,
      summaryTotal: null,
      summaryPassed: null,
      summaryFailed: null,
      summaryError: null,
      summarySuccessRate: null,
      results: [],
    };
    Eif (summary && typeof summary === 'object') {
      r.summaryTotal = summary.total != null ? Number(summary.total) : null;
      r.summaryPassed = summary.passed != null ? Number(summary.passed) : null;
      r.summaryFailed = summary.failed != null ? Number(summary.failed) : null;
      r.summaryError = summary.error != null ? Number(summary.error) : null;
      r.summarySuccessRate =
        summary.successRate != null ? Number(summary.successRate) : null;
    }
    const results = Array.isArray(json.results) ? json.results : [];
    for (const node of results) {
      r.results.push({
        testId: node.testId ?? null,
        testName: node.testName ?? null,
        status: node.status ?? null,
        duration: node.duration != null ? Number(node.duration) : 0,
        responseTime: node.responseTime != null ? Number(node.responseTime) : 0,
        error: node.error ?? null,
        startTimeIso: node.startTime ?? null,
        endTimeIso: node.endTime ?? null,
      });
    }
    r.resultsCount = r.results.length;
    return r;
  }
 
  async function listTestPacks() {
    const json = await sendJson('GET', '/api/v1/test-packs', { auth: true });
    const items = [];
    if (Array.isArray(json)) {
      for (const n of json) {
        items.push({
          packId: n.packId ?? null,
          name: n.name ?? null,
          projectName: n.projectName ?? null,
          environment: n.environment ?? null,
          lastStatus: n.lastStatus ?? null,
        });
      }
    }
    return items;
  }
 
  return {
    login,
    setBearerToken,
    triggerTestPack,
    getStatus,
    getResults,
    listTestPacks,
  };
}
 
module.exports = { createApiClient, stripTrailingSlash };