All files / frontend/helpers drawioUrl.js

100% Statements 55/55
90.9% Branches 50/55
100% Functions 10/10
100% Lines 53/53

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                                      2x   2x   2x                                 23x 17x   6x 6x 5x 2x 2x     5x 5x   1x 1x   1x         176x 3x   173x 1x   172x 167x   5x               92x 2x     90x 6x 6x 1x   5x 5x 8x 7x     5x     84x 82x 82x 177x 1x   176x 176x 5x 5x   171x   82x     2x 2x                       23x                         23x 23x 23x 23x           23x 23x    
/*
  Copyright (C) 2023 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.
*/
 
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import env from '@front/helpers/env';
 
const logger = getLoggerWithTag('f/h/drawioUrl');
 
const DEFAULT_DRAWIO_BASE_URI = 'https://embed.diagrams.net/';
 
const DRAWIO_DEFAULT_PARAMS = {
  embed: '1',
  ui: 'atlas',
  spin: '1',
  modified: 'unsavedChanges',
  saveAndExit: '0',
  noExitBtn: '1',
  proto: 'json'
};
 
/**
 * Resolve DrawIO host+path from env (backend env-config first, then build-time envar).
 * A relative path (e.g. /drawio/) is resolved against the page origin.
 * Search/hash from the envar are dropped.
 * Falls back to DEFAULT_DRAWIO_BASE_URI when missing or unparseable.
 */
function resolveDrawioBaseUri(raw = env.drawioServerUri) {
  if (!raw || typeof raw !== 'string' || !raw.trim()) {
    return DEFAULT_DRAWIO_BASE_URI;
  }
  try {
    const url = new URL(raw.trim(), typeof window !== 'undefined' ? window.location.origin : undefined);
    if (url.search || url.hash) {
      logger.warn(() =>
        `VUE_APP_DOCHUB_PLUGIN_DRAWIO_SERVER_URI query/hash ignored; use VUE_APP_DOCHUB_PLUGIN_DRAWIO_URL_PARAMS or drawio_url_params instead. Raw: ${raw}`
      );
    }
    const path = url.pathname.endsWith('/') ? url.pathname : `${url.pathname}/`;
    return `${url.origin}${path}`;
  } catch (error) {
    logger.warn(() =>
      `Invalid VUE_APP_DOCHUB_PLUGIN_DRAWIO_SERVER_URI "${raw}", falling back to ${DEFAULT_DRAWIO_BASE_URI}. ${error}`
    );
    return DEFAULT_DRAWIO_BASE_URI;
  }
}
 
function coerceParamValue(value) {
  if (typeof value === 'boolean') {
    return value ? '1' : '0';
  }
  if (typeof value === 'number' && Number.isFinite(value)) {
    return String(value);
  }
  if (typeof value === 'string') {
    return value;
  }
  return null;
}
 
/**
 * Normalize string (query) or flat object into a plain string map.
 * Nested objects/arrays and invalid values are skipped.
 */
function parseDrawioUrlParams(input) {
  if (input == null || input === '') {
    return {};
  }
 
  if (typeof input === 'string') {
    const query = input.trim().replace(/^\?/, '');
    if (!query) {
      return {};
    }
    const result = {};
    new URLSearchParams(query).forEach((value, key) => {
      if (key) {
        result[key] = value;
      }
    });
    return result;
  }
 
  if (typeof input === 'object' && !Array.isArray(input)) {
    const result = {};
    for (const [key, value] of Object.entries(input)) {
      if (!key || typeof key !== 'string') {
        continue;
      }
      const coerced = coerceParamValue(value);
      if (coerced === null) {
        logger.warn(() => `Skipping invalid drawio url param "${key}" (type ${typeof value})`);
        continue;
      }
      result[key] = coerced;
    }
    return result;
  }
 
  logger.warn(() => `Ignoring drawio url params of unsupported type: ${typeof input}`);
  return {};
}
 
/**
 * Merge param layers: defaults → global → document → mandatory (later wins).
 */
function mergeDrawioUrlParams({
  defaults = {},
  globalParams = {},
  documentParams = {},
  mandatory = {}
} = {}) {
  return {
    ...parseDrawioUrlParams(defaults),
    ...parseDrawioUrlParams(globalParams),
    ...parseDrawioUrlParams(documentParams),
    ...parseDrawioUrlParams(mandatory)
  };
}
 
export function buildDrawioUrl({
  componentDefaults = {},
  documentParams = {},
  componentMandatory = {}
} = {}) {
  const defaults = {...DRAWIO_DEFAULT_PARAMS, ...componentDefaults};
  const globalParams = env.drawioUrlParams;
  const baseUri = resolveDrawioBaseUri();
  const merged = mergeDrawioUrlParams({
    defaults,
    globalParams,
    documentParams,
    mandatory: componentMandatory
  });
  const search = new URLSearchParams(merged).toString();
  return search ? `${baseUri}?${search}` : baseUri;
}