All files / src/pipeline/references collect-external-references.js

6.39% Statements 11/172
0% Branches 0/73
0% Functions 0/27
6.39% Lines 11/172

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                  1x 1x 1x 1x   1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1x          
/**
 * @file Orchestrates external reference collection and enrichment within the pipeline.
 *
 * This module coordinates three stages:
 * 1. Scan local markdown for `[[xref:...]]` / `[[tref:...]]` references.
 * 2. Enrich references with metadata derived from `specs.json`.
 * 3. Persist the combined dataset for downstream consumers.
 */
 
require('dotenv').config();
const path = require('node:path');
const fs = require('fs-extra');
const readlineSync = require('readline-sync');
 
const Logger = require('../../utils/logger');
const messageCollector = require('../../utils/message-collector');
const { shouldProcessFile } = require('../../utils/file-filter');
const { getCurrentBranch } = require('../../utils/git-info');
const { addNewXTrefsFromMarkdown, isXTrefInAnyFile } = require('./xtref-utils');
const { processXTrefObject } = require('../../parsers/template-tag-parser');
 
/**
 * Reuses the main rendering entry point once reference collection has refreshed the cache.
 * Keeping this invocation on the Node side (instead of the menu script) guarantees that
 * automated callers of `collectExternalReferences` continue to receive a fully rendered spec.
 */
function renderSpecification() {
    // Pass skipClear to preserve messages from collectExternalReferences
    require('../../../index.js')({ nowatch: true, skipClear: true });
}
 
/**
 * Normalizes the specs structure pulled from specs.json so callers can rely on predictable shapes.
 *
 * The helper guarantees:
 * - the returned `specs` array is always an array;
 * - callers get the first spec entry (or an empty object) as `primarySpec`;
 * - callers receive a safe `externalSpecsRepos` array for follow-up validation or iteration;
 * - when the specs array is empty, an explanatory error is logged and `null` is returned to signal abortion.
 *
 * @param {object} config - Parsed specs configuration.
 * @param {{ noSpecsMessage: string }} options - Allows callers to tailor the abort message for their context.
 * @returns {{ specs: Array<object>, primarySpec: object, externalSpecsRepos: Array<object>, hasExternalSpecsField: boolean } | null}
 */
function normalizeSpecConfiguration(config, { noSpecsMessage }) {
    const specs = Array.isArray(config?.specs) ? config.specs : [];
 
    if (specs.length === 0) {
        Logger.error(noSpecsMessage, {
            context: 'specs.json is missing or has no specs array',
            hint: 'Create a valid specs.json file in your project root. Run "npm run init" or copy from: https://github.com/trustoverip/spec-up-t-starter-pack',
            details: 'The specs array is required to configure your specification'
        });
        return null;
    }
 
    const primarySpec = specs[0] ?? {};
    const hasExternalSpecsField = Array.isArray(primarySpec.external_specs);
    const externalSpecsRepos = hasExternalSpecsField ? primarySpec.external_specs : [];
 
    return { specs, primarySpec, externalSpecsRepos, hasExternalSpecsField };
}
 
/**
 * Augments reference records with repository metadata pulled from `specs.json`.
 *
 * @param {object} config - Parsed specs configuration.
 * @param {Array<object>} xtrefs - Reference entries collected from markdown.
 */
function extendXTrefs(config, xtrefs) {
    if (config.specs[0].external_specs_repos) {
        Logger.warn('Your specs.json file uses an outdated structure', {
            context: 'The "external_specs_repos" field is deprecated',
            hint: 'Update to the new structure using "external_specs" instead. See: https://github.com/trustoverip/spec-up-t/blob/master/src/install-from-boilerplate/boilerplate/specs.json',
            details: 'External references may not work correctly with the old structure'
        });
        return;
    }
 
    const repoLookup = new Map();
    const siteLookup = new Map();
 
    config.specs.forEach(spec => {
        spec.external_specs.forEach(repo => {
            if (repo.external_spec) {
                repoLookup.set(repo.external_spec, repo);
            }
        });
 
        spec.external_specs
            .filter(externalSpec => typeof externalSpec === 'object' && externalSpec !== null)
            .forEach(externalSpec => {
                const key = Object.keys(externalSpec)[0];
                siteLookup.set(key, externalSpec[key]);
            });
    });
 
    xtrefs.forEach(xtref => {
        xtref.repoUrl = null;
        xtref.terms_dir = null;
        xtref.owner = null;
        xtref.repo = null;
        xtref.site = null;
        xtref.branch = null;
 
        const repo = repoLookup.get(xtref.externalSpec);
        if (repo) {
            xtref.repoUrl = repo.url;
            xtref.terms_dir = repo.terms_dir;
 
            if (xtref.repoUrl) {
                const urlParts = new URL(xtref.repoUrl).pathname.split('/');
                xtref.owner = urlParts[1];
                xtref.repo = urlParts[2];
            }
 
            xtref.avatarUrl = repo.avatar_url;
            xtref.ghPageUrl = repo.gh_page;
        }
 
        const site = siteLookup.get(xtref.externalSpec);
        if (site) {
            xtref.site = site;
        }
 
        try {
            xtref.branch = getCurrentBranch();
        } catch (error) {
            Logger.warn(`Could not get current branch for xtref ${xtref.externalSpec}:${xtref.term}`, {
                context: 'Git branch detection failed for external reference',
                hint: 'Ensure you\'re in a git repository, or specify github_repo_branch in specs.json external_specs configuration',
                details: `${error.message}. Using default: main`
            });
            xtref.branch = 'main';
        }
    });
}
 
/**
 * Executes the full collection pipeline once pre-flight checks pass.
 *
 * @param {object} config - Parsed specs configuration.
 * @param {string} GITHUB_API_TOKEN - GitHub PAT used for API calls.
 */
function processExternalReferences(config, GITHUB_API_TOKEN) {
    const { processXTrefsData } = require('./process-xtrefs-data');
    const { doesUrlExist } = require('../../utils/does-url-exist');
 
    const normalizedConfig = normalizeSpecConfiguration(config, {
        noSpecsMessage: 'No specs defined in specs.json. Skipping external reference collection.'
    });
 
    // Abort collection when the configuration is missing mandatory specs definitions.
    if (!normalizedConfig) {
        return;
    }
 
    const { specs, externalSpecsRepos } = normalizedConfig;
 
    externalSpecsRepos.forEach(repo => {
        doesUrlExist(repo.url)
            .then(exists => {
                if (exists) {
                    return;
                }
 
                const userInput = readlineSync.question(
                    `❌ This external reference is not a valid URL:
 
   Repository: ${repo.url},
   
   Terms directory: ${repo.terms_dir}
 
   Please fix the external references in the specs.json file that you will find at the root of your project.
 
   Do you want to stop? (yes/no): `);
 
                if (userInput.toLowerCase() === 'yes' || userInput.toLowerCase() === 'y') {
                    Logger.info('Stopping...');
                    process.exit(1);
                }
            })
            .catch(error => {
                Logger.error('Error checking URL existence:', error);
            });
    });
 
    const outputDir = '.cache';
    const xtrefsHistoryDir = path.join(outputDir, 'xtrefs-history');
    const outputPathJSON = path.join(outputDir, 'xtrefs-data.json');
    const outputPathJS = path.join(outputDir, 'xtrefs-data.js');
    const outputPathJSTimeStamped = path.join(xtrefsHistoryDir, `xtrefs-data-${Date.now()}.js`);
 
    fs.ensureDirSync(outputDir);
    fs.ensureDirSync(xtrefsHistoryDir);
 
    let allXTrefs = { xtrefs: [] };
    if (fs.existsSync(outputPathJSON)) {
        const existingXTrefs = fs.readJsonSync(outputPathJSON);
        if (existingXTrefs?.xtrefs) {
            allXTrefs = existingXTrefs;
        }
    }
 
    const specTermsDirectories = specs.reduce((directories, spec) => {
        const specDir = spec?.spec_directory;
        const termsDir = spec?.spec_terms_directory;
 
        if (!specDir || !termsDir) {
            Logger.warn(`Spec entry is missing spec_directory or spec_terms_directory`, {
                context: 'Invalid specs.json configuration',
                hint: 'Ensure each spec in specs.json has both "spec_directory" and "spec_terms_directory" fields',
                details: `Incomplete spec entry: ${JSON.stringify(spec)}`
            });
            return directories;
        }
 
        const resolvedDir = path.join(specDir, termsDir);
 
        if (!fs.existsSync(resolvedDir)) {
            Logger.warn(`Spec terms directory does not exist: ${resolvedDir}`, {
                context: 'Directory specified in specs.json not found',
                hint: 'Create the directory or update the path in specs.json. Typically this should be "spec/term-definitions" or similar',
                details: `Expected path: ${resolvedDir}`
            });
            return directories;
        }
 
        directories.push(resolvedDir);
        return directories;
    }, []);
 
    if (specTermsDirectories.length === 0) {
        Logger.warn('No spec terms directories found. Skipping external reference collection', {
            context: 'Cannot collect external references without valid terminology directories',
            hint: 'Check specs.json configuration. Ensure spec_directory and spec_terms_directory point to existing directories',
            details: 'External trefs and xrefs will not be processed'
        });
        return;
    }
 
    const fileContents = new Map();
 
    specTermsDirectories.forEach(specDirectory => {
        fs.readdirSync(specDirectory).forEach(file => {
            if (!shouldProcessFile(file)) {
                return;
            }
 
            const filePath = path.join(specDirectory, file);
            const markdown = fs.readFileSync(filePath, 'utf8');
            fileContents.set(file, markdown);
        });
    });
 
    // Filter out xtrefs that don't exist in any current file
    allXTrefs.xtrefs = allXTrefs.xtrefs.filter(existingXTref =>
        isXTrefInAnyFile(existingXTref, fileContents)
    );
 
    // Clean up sourceFiles arrays to remove deleted files
    // This ensures that if a file is deleted, its entry is removed from all sourceFiles arrays
    allXTrefs.xtrefs.forEach(xtref => {
        if (xtref.sourceFiles && Array.isArray(xtref.sourceFiles)) {
            const currentFiles = Array.from(fileContents.keys());
            xtref.sourceFiles = xtref.sourceFiles.filter(sf => 
                currentFiles.includes(sf.file)
            );
        }
    });
 
    fileContents.forEach((content, filename) => {
        addNewXTrefsFromMarkdown(content, allXTrefs, filename, processXTrefObject, externalSpecsRepos);
    });
 
    extendXTrefs(config, allXTrefs.xtrefs);
    return processXTrefsData(allXTrefs, GITHUB_API_TOKEN, outputPathJSON, outputPathJS, outputPathJSTimeStamped);
}
 
/**
 * Public entry point for the external reference collection stage.
 *
 * @param {{ pat?: string, collectMessages?: boolean }} options - Optional overrides (GitHub PAT, message collection).
 */
function collectExternalReferences(options = {}) {
    // Start collecting messages if requested
    const shouldCollectMessages = options.collectMessages !== false; // Collect by default
 
    if (shouldCollectMessages) {
        messageCollector.clearMessages();
        messageCollector.startCollecting('collectExternalReferences');
    }
 
    const config = fs.readJsonSync('specs.json');
    const normalizedConfig = normalizeSpecConfiguration(config, {
        noSpecsMessage: 'No specs defined in specs.json. Nothing to collect.'
    });
 
    // Bail out immediately if the specs.json file lacks the required specs collection.
    if (!normalizedConfig) {
        if (shouldCollectMessages) {
            messageCollector.stopCollecting();
            messageCollector.saveMessages();
        }
        return;
    }
 
    const { externalSpecsRepos, hasExternalSpecsField } = normalizedConfig;
    const GITHUB_API_TOKEN = options.pat || process.env.GITHUB_API_TOKEN;
 
    // Communicate that the expected external_specs array is missing entirely.
    if (!hasExternalSpecsField) {
        Logger.info(
            'No external_specs array found on the first spec entry in specs.json. External reference collection is skipped.'
        );
 
        if (shouldCollectMessages) {
            messageCollector.stopCollecting();
            messageCollector.saveMessages().then(path => {
                Logger.success(`Console messages saved to: ${path}`);
                renderSpecification();
            });
        } else {
            renderSpecification();
        }
        return;
    }
 
    // Let the user know the array exists but contains no repositories, making collection pointless.
    if (externalSpecsRepos.length === 0) {
        Logger.info(
            'The external_specs array in specs.json is empty. Add external repositories to collect external references.'
        );
 
        if (shouldCollectMessages) {
            messageCollector.stopCollecting();
            messageCollector.saveMessages().then(path => {
                Logger.success(`Console messages saved to: ${path}`);
                renderSpecification();
            });
        } else {
            renderSpecification();
        }
        return;
    }
 
    const pipeline = processExternalReferences(config, GITHUB_API_TOKEN);
 
    // If the pipeline short-circuited (e.g. missing configuration), render immediately and return its value.
    if (pipeline && typeof pipeline.then === 'function') {
        return pipeline
            .then(result => {
                if (shouldCollectMessages) {
                    messageCollector.stopCollecting();
                    return messageCollector.saveMessages().then(path => {
                        Logger.success(`Console messages saved to: ${path}`);
                        renderSpecification();
                        return result;
                    });
                } else {
                    renderSpecification();
                    return result;
                }
            })
            .catch(error => {
                Logger.error('Rendering failed after collecting external references.', error);
 
                if (shouldCollectMessages) {
                    messageCollector.stopCollecting();
                    messageCollector.saveMessages().catch(() => {
                        // Silent fail on save error
                    });
                }
 
                throw error;
            });
    } else {
        if (shouldCollectMessages) {
            messageCollector.stopCollecting();
            messageCollector.saveMessages().then(path => {
                Logger.success(`Console messages saved to: ${path}`);
                renderSpecification();
            });
        } else {
            renderSpecification();
        }
        return pipeline;
    }
}
 
module.exports = {
    collectExternalReferences,
    extendXTrefs,
    processExternalReferences
};