All files / global/manifest/tools entitiesSource.mjs

93.75% Statements 45/48
100% Branches 31/31
40% Functions 2/5
100% Lines 45/45

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                                                                            14x 1x   13x 2x   11x 11x 10x 11x 11x 11x 11x 3x   11x 11x 1x 1x     10x 10x   10x 9x   2x 1x   1x       9x 1x   8x   2x 1x           1x 1x     6x     8x   1x 1x   7x   1x   6x       11x 11x   7x 2x 5x 4x   7x   11x    
/*
  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.
*/
 
import parser from '@global/manifest/parser3/index.mjs';
import yaml from 'yaml';
 
/**
 * Prepares entities data by merging provided entity values with data fetched from their source files.
 *
 * Iterates through entities grouped by schema, retrieves source file information from `sourceMap`,
 * fetches data from the LAST source file for each entity, merges the provided entity data,
 * and returns a map of source file paths to their updated content as strings.
 *
 * @param {Object} entities - A nested object of entities, structured as `{ [schema: string]: { [entKey: string]: entityValue: Object } }`. The function will only overwrite and add properties, will not delete existing ones.
 * @param {Function} request - A function that accepts a source URL/path as a string and returns a promise resolving to an object containing a `data` property with the parsed content (e.g., `{ data: {...} }`).
 * @param {Function} logger - A logger function.
 * @param {Object} [options] - An options object with the following properties:
 *   @property {string} [options.defaultSource] - A fallback source path for new entities that are not yet present in the existing architecture. If specified, it will be used as the first (and potentially only) source for new entities.
 *   @property {string} [options.baseURI] - A base URI to be prepended to source paths when fetching data via the `request` function.
 * @param {Record<string, { sources: string[] }>} [sourceMap=parser.sourceMap] - A source map from the manifest parser. If not provided, the sourceMap of the global parser object is used instead.
 * @returns {Promise<Object<string, string>>} A promise resolving to an object where keys are source file paths (with `@` prefix if from Bitbucket) and values are stringified JSON or YAML content.
 * @throws {Error} If `sourceMap` is missing or falsy.
 * @throws {Error} If `request` is not a function.
 */
export async function prepareEntitiesData(entities, request, logger, options, sourceMap = parser.sourceMap) {
    if (!sourceMap) {
        throw new Error('No source map could be established for the request to prepareEntitiesData');
    }
    if (typeof request !== 'function' || !logger) {
        throw new Error('request and logger are required in prepareEntitiesData');
    }
    const fileData = {};
    for (const [schema, schemaEntities] of Object.entries(entities)) {
        for (const [entKey, entValue] of Object.entries(schemaEntities)) {
            const key = `/${schema}/${entKey}`;
            const keySources = sourceMap[key]?.sources ?? [];
            const sources = [];
            if (options?.defaultSource) {
                sources.push(options.defaultSource);
            }
            sources.push(...keySources);
            if (!sources?.length) {
                logger.debug(() => `No sources received for entity ${entKey}`);
                continue;
            }
            // If the entity is described in several files, we take the last source file, because we need to choose one, might as well be the last one.
            const lastSource = sources[sources.length - 1];
            let data = fileData[lastSource];
            // If no fetch happened for this source, fetch it now.
            if (!data) {
                const requestData = await request(lastSource, options?.baseURI).catch((err) => {
                    // If there's no file, we might need to create it.
                    if (err?.response?.status === 404) {
                        return { data: null };
                    } else {
                        logger.warn(() => `Error while fetching data during preparation of entity ${entKey} for saving:`, err);
                    }
                });
                // If an error occurred, we already logged it.
                if (!requestData) {
                    continue;
                }
                if (!requestData.data) {
                    // If no data received for default source, either file doesn't exist or it's empty. Substitute with empty object.
                    if (options?.defaultSource === lastSource) {
                        fileData[lastSource] = data = {
                            [schema]: {
                                [entKey]: {}
                            }
                        };
                    } else {
                        logger.debug(`Expected entities data, but no data received for source ${lastSource}`);
                        continue;
                    }
                } else {
                    fileData[lastSource] = data = requestData.data;
                }
            }
            if (!data?.[schema]) {
                // Weird case, but you never know.
                logger.warn(() => `According to the source map, schema ${schema} was expected in source ${lastSource}, but it is missing from the received data.`);
                continue;
            }
            if (!data[schema][entKey]) {
                // If it's default source, the entity might be missing. Add it.
                data[schema][entKey] = entValue;
            } else {
                Object.assign(data[schema][entKey], entValue);
            }
        }
    }
    const output = {};
    for (const [source, data] of Object.entries(fileData)) {
        let dataString;
        if (source.endsWith('.json')) {
            dataString = JSON.stringify(data);
        } else if (source.endsWith('.yaml')) {
            dataString = yaml.stringify(data);
        }
        output[source] = dataString;
    }
    return output;
}