All files / frontend/plugins plugins.js

98.75% Statements 79/80
100% Branches 14/14
97.43% Functions 38/39
98.68% Lines 75/76

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                                                                                                  99x 99x   99x 99x     9x     99x       63x         99x                 2x     2x     1x     1x           8x           9x 1x           26x 26x     26x 26x 1x           26x 26x         19x 2x     17x 17x     3x   15x 3x 3x       15x 2x     26x       19x 19x   7x   19x                         1x     1x     1x         7x 7x   2x 2x           63x 10x   10x 1x       9x 9x     9x         63x 3x     63x 63x   63x   63x         63x 19x     44x 5x 5x     39x     13x         6x       6x               39x           35x     3x       6x 2x       6x     39x       39x 39x          
/*
  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> - 2023
      R.Piontik <r.piontik@mail.ru> - 2022
*/
 
/* Модуль Vuex для работы с плагинами */
import * as Vue from 'vue';
import requests from '@front/helpers/requests';
import env, { Plugins } from '@front/helpers/env';
import { getLogger, getLoggerWithTag } from '@global/logger/v2/logger.mjs';
import { pluginManager } from '@front/plugins/plugin-manager';
import { loadIdeaPlugin } from '@front/plugins/loaders/idea-plugin-loader';
import {
  parsePluginCatalog,
  parsePluginMetadata
} from '@front/plugins/parse-plugin-metadata';
import { PLUGINS_API_VERSION } from '@front/plugins/public-api/contracts';
import { DocTypes } from '@front/components/Docs/enums/doc-types.enum';
import { registerPluginTool } from '@global/gigachat/tools/pluginToolRegistry';
 
 
const logger = getLoggerWithTag('f/p/plugins');
const IDE_PLUGINS_CATALOG_TIMEOUT_MS = 60000;
 
let appInstance = null;
let catalogRequestId = 0;
 
export function setPluginsStoreAppInstance(app) {
  appInstance = app;
}
 
const plugins = {
	documents: [],
	// Все ранее зарегистрированные плагины переносим в основной менеджер
	pull() {
		this.documents.forEach((el) => DocHub.documents.register(el.type, el.component));
	}
};
 
// Регистрируем временный менеджер регистрации плагинов
window.DocHub = {
  // Внешние сборки используют общий Vue runtime через DocHub.runtime.vue.
  runtime: Object.freeze({
    // Deprecated: compatibility alias для ранее собранных внешних плагинов.
    apiVersion: PLUGINS_API_VERSION,
    vue: Vue
  }),
  documents: {
    register(type, component) {
      plugins.documents.push({ type, component });
    },
    fetch() {
      return JSON.parse(JSON.stringify(plugins.documents));
    },
    getLoggerWithTag(pluginName) {
      return getLoggerWithTag(`plugin/${pluginName}`);
    },
    getLogger() {
      return getLogger();
    }
  },
  // Инструменты агента ai-chat от плагинов: реестр модульный, init его не переносит
  ai: {
    registerTool(type, tool) {
      registerPluginTool(type, tool);
    }
  }
};
 
function logIdeaPluginsCatalogError(error) {
  logger.warn(
    () => 'Не удалось обновить каталог документных плагинов из IDE',
    error?.response?.data || error
  );
}
 
function refreshIdeaPluginsCatalog() {
  const requestId = ++catalogRequestId;
  logger.info(() => 'Обновляем каталог документных плагинов из IDE');
 
  let timeout;
  const catalogTimeout = new Promise((resolve, reject) => {
    timeout = setTimeout(
      () => reject(new Error('IDE не ответила на запрос каталога за 60 секунд')),
      IDE_PLUGINS_CATALOG_TIMEOUT_MS
    );
  });
 
  // У PAPI нет таймаута: необязательный каталог не должен блокировать встроенные документы.
  return Promise.race([
    Promise.resolve().then(() => window.$PAPI.getDocumentPluginsCatalog()),
    catalogTimeout
  ])
    .then((response) => {
      // Ручное обновление делает ответ стартового запроса неактуальным даже при ошибке обновления.
      if (requestId !== catalogRequestId) {
        return;
      }
 
      const catalog = response?.data;
      const catalogPlugins = parsePluginCatalog(
        catalog,
        PLUGINS_API_VERSION,
        (message) => logger.warn(() => message)
      );
      pluginManager.replaceCatalogPlugins(catalogPlugins, (plugin) => {
        return loadIdeaPlugin(plugin, () => {
          return pluginManager.getAvailablePluginByDocumentType(plugin.documents[0]) === plugin;
        });
      });
 
      logger.info(
        () => `Каталог документных плагинов обновлён: [${catalogPlugins.length}]`
      );
    })
    .finally(() => clearTimeout(timeout));
}
 
async function initializeIdeaPlugins(context) {
  try {
    await refreshIdeaPluginsCatalog();
  } catch (error) {
    logIdeaPluginsCatalogError(error);
  } finally {
    context.commit('setReady', true);
  }
}
 
export default {
	namespaced: true,
	state: {
		ready: false, // Признак готовности плагинов к использованию
		documents: {}, // Deprecated: зеркало для обратной совместимости
		metadataError: null // Сообщение для пользователя при ошибке загрузки или проверки lazy metadata
	},
	mutations: {
		setReady(state, value) {
			state.ready = value;
		},
		setMetadataError(state, message) {
			state.metadataError = message;
		},
		registerDocument(state, document) {
			state.documents[document.type] = document.component;
		}
	},
	actions: {
      async refreshCatalog() {
        try {
          return await refreshIdeaPluginsCatalog();
        } catch (error) {
          logIdeaPluginsCatalogError(error);
          throw error;
        }
      },
		// Загружаем плагины
		init(context) {
			// Регистрируем менеджер документов для плагинов
			window.DocHub.documents.register = function(type, component) {
				component.mixins = component.mixins || [];
 
				if (!appInstance) {
					throw new Error('Vue app instance is not initialized for plugin registration');
				}
 
				// Deprecated: сохраняем глобальную регистрацию для внешнего legacy-кода.
				appInstance.component(`plugin-doc-${type}`, component);
				pluginManager.registerDocumentRenderer(type, component);
 
				// Deprecated: сохраняем Vuex-зеркало для внешнего legacy-кода.
				context.commit('registerDocument', { type, component });
			};
 
			// Legacy API: возвращает только типы с зарегистрированным renderer,
			// без типов из lazy metadata, плагины которых ещё не загружены.
			window.DocHub.documents.fetch = () => {
				return pluginManager.getDocumentTypes();
			};
 
			context.commit('setReady', false);
			context.commit('setMetadataError', null);
 
      plugins.pull();
 
      pluginManager.reserveLocalPlugins(
        __BUILD_PLUGINS__,
        Object.values(DocTypes)
      );
 
      if (env.isPlugin(Plugins.idea)) {
        return initializeIdeaPlugins(context);
      }
 
			if (env.isPlugin()) {
				context.commit('setReady', true);
				return;
			}
 
			const lazyMetadataLoad = __HAS_LAZY_PLUGINS__
				? requests.request('/lazy-plugins.json', new URL('/', window.location))
					.then((response) => {
						pluginManager.registerAvailablePlugins(
							parsePluginMetadata(response?.data)
						);
					})
					.catch((error) => {
						logger.error(
							() => 'Не удалось загрузить metadata lazy-плагинов',
							error
						);
						context.commit(
							'setMetadataError',
							'Не удалось загрузить описание типов документов. Обновите страницу.'
						);
					})
				: Promise.resolve();
 
			// Загружаем каталог параллельно с lazy metadata, но регистрируем его после неё.
			const catalogMetadataLoad = requests.request(
				env.pluginsCatalogUrl,
				new URL('/', window.location),
				{ timeout: 10000 }
			)
				.then((response) => {
					return parsePluginCatalog(
						response?.data,
						PLUGINS_API_VERSION,
						(message) => logger.warn(() => message)
					);
				})
				.catch((error) => {
					logger.error(
            () => 'Не удалось загрузить каталог документных плагинов',
						error
					);
 
					return [];
				});
 
			return Promise.all([
				lazyMetadataLoad,
				catalogMetadataLoad
      ]).then(([, catalogPlugins]) => {
        pluginManager.registerCatalogPlugins(catalogPlugins);
				context.commit('setReady', true);
			});
		}
	}
};