All files / ide/idea papi.js

87.42% Statements 146/167
92.98% Branches 53/57
73.33% Functions 55/75
95.77% Lines 136/142

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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428                                                                                72x 72x 72x 72x   72x             139x   139x 139x 139x   20x 20x 20x 20x 1x   19x   1x     139x   8x 8x                 139x               1x       2x     1x     1x     1x     4x   4x 4x     9x 8x 8x 8x 8x 8x 8x 8x   8x 3x 3x   8x 8x 9x 5x 5x 3x   8x 8x 8x 8x 8x             2x     1x     1x     2x                       1x     2x       2x 2x 1x         4x     71x     1x     2x       1x       1x     1x         4x 2x   2x           3x 1x   2x       3x 3x 2x 2x 2x   1x     2x       1x       1x       1x       1x       1x       1x       1x       1x     1x     1x               1x             1x     1x         1x     1x           1x     1x   1x                                                       3x 3x 6x           6x   3x           3x                 72x         72x 72x     72x 67x 5x 2x 2x 3x 2x 2x   1x       72x   72x 70x 70x 70x                         70x   70x 4x 4x 1x 1x 1x     4x 4x         4x 1x   4x   1x 1x       70x   2x        
/*
  Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
 
  Copyright (C) 2022 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0
 
  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project
 
  https://dochub.info
 
  The use of this product or its derivatives for any purpose cannot be a secret.
 
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 
  Maintainers:
      R.Piontik <r.piontik@mail.ru>
 
  Contributors:
      R.Piontik <r.piontik@mail.ru> - 2024
      R.Piontik <r.piontik@mail.ru> - 2023
      R.Piontik <r.piontik@mail.ru> - 2022
      Rostislav Kabalin <kabalin2009@yandex.ru> - 2022
*/
 
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {papiSettingUpdated} from '@ide/papiLifeCycle';
import { v4 as uuidv4 } from 'uuid';
import gateway from '@ide/gateway';
 
const logger = getLoggerWithTag('i/i/papi');
const mcpServerlogger = getLoggerWithTag('i/i/papi (MCPServer)');
const mcpClientlogger = getLoggerWithTag('i/i/papi (MCPClient)');
const javaMessageLimit = 15000000; // лимит размера сообщения в логе для отправки в java код
 
const PAPI = {
  isDebug: false,
  // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-empty-function
  middleware: null,
  settings: {},
  cefQuery: null,
  request(params) {
    const data = JSON.stringify(params);
    // eslint-disable-next-line no-console
    this.isDebug && logger.info(() => `plugin request.request ${data}`);
    return new Promise(function(res, rej) {
      const resolve = function(result) {
        // eslint-disable-next-line no-console
        this.isDebug && logger.info(() => `plugin request.response: ${JSON.stringify(result)}`);
        try {
          const parseData = result || null;
          if (window.$PAPI?.middleware)
            res(window.$PAPI.middleware(JSON.parse(parseData), params));
          else
            res(JSON.parse(parseData));
        } catch (e) {
          rej(e);
        }
      };
      const reject = function(errCode, errInfo) {
        // eslint-disable-next-line no-console
        logger.error(() => `plugin request.error: ${errCode}`);
        rej({
          response: {
            data: errInfo,
            headers: {},
            status: errCode
          }
        });
      };
 
      window.$PAPI.cefQuery({
        request: '' + data,
        onSuccess: resolve,
        onFailure: reject
      });
    });
  },
  renderPlantUML(uml) {
    return this.request({url: 'plugin:/idea/plantuml/svg', source: uml});
  },
  // Расчёт схемы SmartAnts в плагине; есть, только если плагин объявил поддержку в настройках (settings.smartants)
  computeSmartAnts(params) {
    return this.request({url: 'plugin:/idea/smartants', params: JSON.stringify(params)});
  },
  initProject(mode) {
    return this.request({url: 'plugin:/idea/initproject', mode});
  },
  reload() {
    this.request({url: 'plugin:/idea/reload'});
  },
  showDebugger() {
    this.request({url: 'plugin:/idea/debugger/show'});
  },
  goto(source, entity, id) {
    const navigation = this.request({url: 'plugin:/idea/goto', source, entity, id});
    // Некоторые вызовы не ждут ответа. request пишет сбой в журнал и передаёт его тем, кто ждёт результат.
    void navigation.catch(() => {});
    return navigation;
  },
  gotoWithResult(source, entity, id) {
    if (window.DocHubIDEACodeExt?.settings?.gotoResult !== true) return this.goto(source, entity, id);
    const requestId = uuidv4();
    const action = 'goto-result';
    return new Promise((resolve, reject) => {
      const cleanup = () => {
        clearTimeout(timer);
        gateway.removeListener(action, onResult);
        window.removeEventListener('pagehide', onPageHide);
      };
      const fail = (error) => {
        cleanup();
        reject(error);
      };
      const onPageHide = () => fail({code: 'navigation_failed'});
      const onResult = (payload) => {
        if (payload?.requestId !== requestId) return;
        cleanup();
        if (payload.result === 'opened') resolve();
        else reject({code: ['file_not_found', 'key_not_found'].includes(payload.result) ? payload.result : 'navigation_failed'});
      };
      const timer = setTimeout(() => fail({timeout: true}), 10000);
      gateway.appendListener(action, onResult);
      window.addEventListener('pagehide', onPageHide);
      try {
        this.request({url: 'plugin:/idea/goto-result', requestId, source, entity, id}).catch(fail);
      } catch (error) {
        fail(error);
      }
    });
  },
  download(content, title, description, extension, fileName = `dh_${Date.now()}`) {
    this.request({url: 'plugin:/idea/gateway/download', content, title, description, extension, fileName});
  },
  upload() {
    this.request({url: 'plugin:/idea/gateway/upload'});
  },
  applyEntitiesSchema(schema) {
    this.request({url: 'plugin:/idea/entities/applyschema', schema});
  },
  copyToClipboard(data) {
    return this.request({url: 'plugin:/idea/clipboard/copy', data});
  },
  // Мост JCEF записывает TSV и необязательный типизированный JSON версии 1 в системный буфер.
  writeClipboard({ text, internal = null }) {
    return this.request({url: 'plugin:/idea/clipboard/write', text, internal});
  },
  // Возвращает Promise<{text: string, internal: string | null}>; отсутствующие форматы — пустая строка/null.
  readClipboard() {
    return this.request({url: 'plugin:/idea/clipboard/read'});
  },
  // Выполняет нативный Copy/Paste JCEF, если таблица не обработала сочетание клавиш.
  performNativeClipboard(operation) {
    return this.request({url: 'plugin:/idea/clipboard/native', operation});
  },
  dispatchClipboardShortcut(operation) {
    const event = new CustomEvent('dochub:clipboard-shortcut', {
      cancelable: true,
      detail: { operation }
    });
    window.dispatchEvent(event);
    if (!event.defaultPrevented) {
      this.performNativeClipboard(operation).catch(error => logger.error(() => 'Не удалось выполнить нативную операцию буфера обмена', error));
    }
  },
  // Событие вызывается при необходимости актуализировать конфигурацию DoсHub.
  onReloadSetting() {
    papiSettingUpdated();
  },
  getSettings() {
    return this.request({url: 'plugin:/idea/settings/get'});
  },
  getDocumentPluginsCatalog() {
    return this.request({url: 'plugin:/idea/document-plugins/catalog'});
  },
  getDocumentPluginBundle(id) {
    return this.request({url: 'plugin:/idea/document-plugins/bundle', id});
  },
  // Сохраняет файл в проекте
  pushFile(source, content) {
    return this.request({url: 'plugin:/idea/code/push/file', source, content});
  },
  // TBD
  pushCode(code, metadata) {
    return this.request({url: 'plugin:/idea/code/push/code', code, metadata});
  },
  invalidateCache() {
    this.request({url: 'plugin:/idea/cache/invalidate'});
  },
  sendLog(logRow) {
    // принимающий java код имеет ограничение
    // JsonMappingException: String value length (20054016) exceeds the maximum allowed (20000000
    if (logRow.message.length > javaMessageLimit) {
      this._sendLogByPart(logRow);
    } else {
      this.request({url: 'plugin:/idea/logs/send', logRow});
    }
  },
  sendJsonataLog(logRow) {
    // принимающий java код имеет ограничение
    // JsonMappingException: String value length (20054016) exceeds the maximum allowed (20000000
    if (logRow.message.length > javaMessageLimit) {
      this._sendLogByPart(logRow);
    } else {
      this.request({url: 'plugin:/idea/logs/jsonata/send', logRow});
    }
  },
  async pullFromCache(key, resolver, args) {
    const result = await this.request({url: 'plugin:/idea/cache/pull', key});
    if (!result.data) {
      const dataset = await resolver(args);
      if(dataset) this.updateCache(key, dataset);
      return dataset;
    }
    return result.data ?? null;
  },
  updateCache(key, data) {
    this.request({url: 'plugin:/idea/cache/update', key, data: JSON.stringify(data)});
  },
  // Запрос к IDE: GET - запрос
  getMetaIntegrationData(url) {
    return this.request({url: 'plugin:/idea/meta/data/request', guid: url});
  },
  // Запрос к IDE: POST - запрос
  postDataInMeta(guid, postURL, data) {
    return this.request({url: 'plugin:/idea/meta/data/post', guid, postURL, data});
  },
  // Запрос к IDE: проверка аутинтификации
  checkIsAuth(backlink) {
    return this.request({url: 'plugin:/idea/meta/auth', backlink});
  },
  // Запрос к IDE: запуск прокси сервера для библиотеки Гигачат
  startGigachatProxy() {
    return this.request({url: 'plugin:/idea/proxy/start'});
  },
  // Запрос файла из бб проксируемый через idea
  downloadBitBucket(path) {
    return this.request({url: 'plugin:/idea/bitbucket/download', path});
  },
  // Clickstream: сохранить данные по ключу
  setClickstreamData(name, value, ms) {
    return this.request({url: 'plugin:/idea/clickstream/set', name, value, ms});
  },
  // Clickstream: сохранить данные по ключу
  getClickstreamData(name) {
    return this.request({url: 'plugin:/idea/clickstream/get', name});
  },
  // Clickstream: сохранить данные по ключу
  deleteClickstreamData(name) {
    return this.request({url: 'plugin:/idea/clickstream/delete', name});
  },
  toolList(config) {
    return this.request({url: 'plugin:/idea/mcp/toolList', config});
  },
  archLoad({traceId, datasetData, errorMessage}) {
    return this.request({
      url: 'plugin:/idea/arch/load',
      traceId: traceId,
      rawJson: JSON.stringify(datasetData),
      errorMessage: errorMessage
    });
  },
  callTool(config, name, args) {
    mcpClientlogger.debug(() => [
      'Вызов внешнего MCP-сервера через плагин.',
      { title: 'Tool name', obj: name },
      { title: 'Arguments', obj: args },
      { title: 'Config', obj: config }
    ]);
 
    return this.request({url: 'plugin:/idea/mcp/callTool', config, name, args});
  },
  mcpServerRegisterTools({ tools }) {
    mcpServerlogger.debug(() => [
      'Запрос на регистрацию тулов MCP-сервера в плагине.',
      { title: 'Tools', obj: tools }
    ]);
 
    return this.request({url: 'plugin:/idea/mcp/registerTools', tools});
  },
  mcpServerSubmitResult({ requestId, result }) {
    mcpServerlogger.debug(() => [
      'Передаю результат выполнения тула MCP-сервера в плагин.',
      { title: 'Request ID', obj: requestId },
      { title: 'Response', obj: result }
    ]);
 
    return this.request({url: 'plugin:/idea/mcp/frontend/result', requestId, result});
  },
  mcpServerStatus() {
    mcpServerlogger.debug(() => 'Запрос статуса MCP-сервера в плагине.');
 
    return this.request({url: 'plugin:/idea/mcp/server/status'});
  },
  // Выбор файлов для загрузки в fileloader2 диалогом IDE. Содержимое и путь остаются в плагине:
  // он держит у себя ref → путь, ref — случайный непрозрачный токен.
  // traceId — сквозной id операции (OpenTelemetry trace id).
  // Ответ: {files: [{ref, fileName, contentType, sizeBytes}]}, при отмене диалога files пустой
  fileloaderSelectFiles({ traceId }) {
    return this.request({url: 'plugin:/idea/fileloader/select', traceId});
  },
  // Загрузка выбранных файлов в fileloader2: плагин читает файлы по ref с диска в момент отправки,
  // сам собирает multipart с частями files в порядке refs и строит адрес сервиса.
  // Ответ: {statusCode, data: UploadResponse | ApiError}. На неизвестный ref или недоступный файл —
  // {statusCode: 400, data: {message}} без запроса к fileloader2
  fileloaderUpload({ refs, traceId }) {
    return this.request({url: 'plugin:/idea/fileloader/upload', refs, traceId});
  },
  // Скачивание файла из fileloader2: плагин сам показывает диалог и сохраняет файл.
  // Ответ: {statusCode, data?}, при ошибке в data тело ApiError
  fileloaderDownload({ fileId, traceId }) {
    return this.request({url: 'plugin:/idea/fileloader/download', fileId, traceId});
  },
 
  /**
   * Отправка лога частями, если его размер превышает максимальный лимит со стороны java кода
   * @param logRow - строка лога, которая будет разбта на части
   * @private
   */
  _sendLogByPart(logRow) {
    let logId = uuidv4();
    for (let i = 0; i < logRow.message.length; i += javaMessageLimit) {
      const partLog = {
        level: logRow.level,
        tag: logRow.tag,
        message: `part_${logId}: ${logRow.message.slice(i, i + javaMessageLimit)}`,
        errorStack: undefined
      };
      this.request({url: 'plugin:/idea/logs/send', partLog});
    }
    const partLog = {
      level: logRow.level,
      tag: logRow.tag,
      message: undefined,
      errorStack: logRow.errorStack
    };
    this.request({url: 'plugin:/idea/logs/send', partLog});
  }
};
 
// Ищем окружение плагина
 
// eslint-disable-next-line no-useless-escape
// const cefQuery = (Object.getOwnPropertyNames(window).filter(item => /^cefQuery\_[0-9]/.test(item)) || [])[0];
 
const params = new URLSearchParams(document.location.search);
// Пытаемся получить название интерфейсной функции из параметров.
// Если в параметрах ее нет, то берем '%$dochub-api-interface-func%' который
// заботливо должен был подложить плагин заменой.
 
const fwCefQuery = '%$dochub-api-interface-func%';
let cefQuery = params.get('$dochub-api-interface-func');
 
// Если в параметрах интерфейсная функция не передана...
if (cefQuery) {
  logger.info(() => 'Нашел интерфейсную функцию в параметрах!');
} else if (!cefQuery && window[fwCefQuery]) {
  cefQuery = fwCefQuery;
  logger.info(() => 'Нашел интерфейсную функцию в коде!');
} else if (!cefQuery && window.localStorage && localStorage.getItem('cefQuery')) {
  logger.info(() => 'Нашел интерфейсную функцию в localStorage!');
  cefQuery = localStorage.getItem('cefQuery');
} else {
  logger.info(() => 'Интерфейсную функцию не нашел.');
}
 
// eslint-disable-next-line no-console
cefQuery && logger.info(() => `Plugin API function: ${cefQuery}`);
 
if (cefQuery && window[cefQuery]) {
  PAPI.cefQuery = window[cefQuery];
  window.$PAPI = PAPI;
  window.DocHubIDEACodeExt = {
    rootManifest: 'plugin:/idea/source/$root',
    settings: {
      // Тут нужно определиться или признаком Enerprise является запуск под протоколом http/https или настройка в плагине
      isEnterprise: ['http:', 'https:'].indexOf(window.location.protocol) >= 0,
      render: {
        external: false,
        mode: 'ELK',
        server: ''
      },
      s3CloudUrl: ''
    }
  };
  gateway.initIdeaGateway();
 
  PAPI.getSettings().then((config) => {
    const supportAPI = process.env.VUE_APP_DOCHUB_IDE_IDEA_API || [];
    if (supportAPI.indexOf(config.api) < 0) {
      const message = `Данная версия плагина имеет версию API [${config.api}]. Требуются версии: ${supportAPI.join(';')}. Возможно необходимо обновить плагин.`;
      logger.error(() => message);
      alert(message);
    }
    // Тут нужно определиться или признаком Enerprise является запуск под протоколом http/https или настройка в плагине
    window.DocHubIDEACodeExt.settings = config;
    logger.info(() => [
        'IDE ENVIRONMENTS:',
        {title: 'config', obj: config}
    ]);
    // Если ide передает дополнительные переменные окружения, сохраняем их разобрав на пары ключ-значение
    if (config.additionalEnv) {
      window.additionalIdeEnv = config.additionalEnv;
    }
    PAPI.onReloadSetting();
  }).catch(() => {
    alert('Не могу получить конфигурацию плагина.');
    logger.error(() => 'Не могу получить конфигурацию плагина.');
  });
 
  // Оставляем след интерфейсной функции для рефрешей и т.п.
  window.localStorage && localStorage.setItem('cefQuery', cefQuery);
} else {
  logger.info(() => 'Это не плагин jetbrains...');
}
 
export default cefQuery ? PAPI : false;