All files / frontend/helpers smartantsCompute.ts

100% Statements 32/32
100% Branches 28/28
100% Functions 9/9
100% Lines 29/29

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                                                                                                      10x 7x 7x     7x         19x 19x 5x 4x 4x       19x 15x     9x 1x   8x 3x 5x   6x 2x   4x 4x 1x   3x 3x   2x 2x 2x 2x 2x   2x              
/*
  Copyright (C) 2026 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
 
  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.
*/
 
// Выбор способа расчёта схемы SmartAnts и разбор ответа.
// Зависимости внедряются: компонент передаёт env, запросы и воркер, тесты - заглушки
 
// Ответ сервиса и воркера: {result, queryID, graph|error}
export interface SmartantsResponse {
  result?: string;
  queryID?: string;
  graph?: unknown;
  error?: unknown;
}
 
export interface SmartantsWorker {
  postMessage(message: unknown): void;
  onmessage: ((message: { data: SmartantsResponse }) => void) | null;
}
 
export type SmartantsParams = Record<string, unknown>;
 
export interface SmartantsComputeDeps {
  isPlugin(): boolean;
  isSmartantsInPlugin(): boolean;
  smartantsMode(): string;
  // Расчёт в плагине ($PAPI.computeSmartAnts)
  computeInPlugin(params: SmartantsParams): Promise<SmartantsResponse>;
  // Расчёт в backend; отдаёт тело ответа
  computeInBackend(params: SmartantsParams): Promise<{ graph?: unknown }>;
  // Воркер с легаси-библиотекой smartants.js; в сборке для плагинов его нет
  worker: SmartantsWorker | null;
  // Готовый результат из кэша браузера
  readCache(params: SmartantsParams): unknown;
  newQueryId(): string;
}
 
// Отказ плагина: {response: {data, status}}, data - обычно строка
export function pluginErrorOf(err: unknown): Error {
  if (err instanceof Error) return err;
  const data = (err as { response?: { data?: unknown } })?.response?.data;
  const text = (typeof data === 'string' && data)
    || (typeof (data as { message?: unknown })?.message === 'string' && (data as { message: string }).message)
    || (typeof err === 'string' && err);
  return new Error(text || 'SmartAnts plugin request failed');
}
 
export function createSmartantsCompute(deps: SmartantsComputeDeps) {
  // Слушатели ответов воркера
  const listeners: Record<string, (message: SmartantsResponse) => void> = {};
  if (deps.worker) {
    deps.worker.onmessage = (message) => {
      const queryID = message.data?.queryID;
      queryID && listeners[queryID]?.(message.data);
    };
  }
 
  return (params: SmartantsParams, availableWidth: number): Promise<unknown> => {
    if (deps.isPlugin()) {
      // В плагинах схемы считает только плагин (JetBrains - в процессе IDE, VS Code - JVM-сервисом);
      // расчёта в браузере в плагинах нет
      if (!deps.isSmartantsInPlugin()) {
        return Promise.reject(new Error('Плагин не поддерживает расчёт схем SmartAnts, обновите плагин'));
      }
      return deps.computeInPlugin({ ...params, availableWidth })
        .catch((err) => Promise.reject(pluginErrorOf(err)))
        .then((response) => response?.result === 'OK' ? response.graph : Promise.reject(response?.error));
    }
    if (deps.smartantsMode() !== 'front') {
      return deps.computeInBackend({ ...params, availableWidth }).then((data) => data.graph);
    }
    const worker = deps.worker;
    if (!worker) {
      return Promise.reject(new Error('SmartAnts: в этой сборке нет расчёта в браузере (smartants.js)'));
    }
    const cached = deps.readCache(params);
    if (cached) return Promise.resolve(cached);
    // Запись в кэш отключена: localStorage переполняется
    return new Promise((success, reject) => {
      const queryID = deps.newQueryId();
      listeners[queryID] = (message) => {
        delete listeners[queryID];
        message.result === 'OK' ? success(message.graph) : reject(message.error);
      };
      worker.postMessage({
        queryID,
        params: JSON.parse(JSON.stringify({ ...params, availableWidth }))
      });
    });
  };
}