All files / backend/dist/services/configuration configuration-data-provider.js

0% Statements 0/89
0% Branches 0/41
0% Functions 0/11
0% Lines 0/88

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                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Configuration Data Provider
 *
 * Discovers, loads, and caches site configurations from the filesystem.
 * Handles automatic migrations for legacy configs and etalage data loading.
 *
 * Migrated from: backend/src-main/app-prefs-state/configuration-data-provider.js
 */
import fs from 'fs-extra';
import path from 'path';
import { glob } from 'glob';
import { isRecord } from '../../utils/format-providers/types.js';
import { siteConfigSchema } from '@quiqr/types/schemas';
/**
 * ConfigurationDataProvider loads and caches site configurations
 */
export class ConfigurationDataProvider {
    cache;
    pathHelper;
    formatResolver;
    logger;
    constructor(pathHelper, formatResolver, logger) {
        this.pathHelper = pathHelper;
        this.formatResolver = formatResolver;
        this.logger = logger;
    }
    /**
     * Invalidate the configuration cache
     */
    invalidateCache() {
        this.cache = undefined;
    }
    /**
     * Get all site configurations (async)
     * @param options - Optional invalidateCache flag
     */
    async getConfigurations(options = {}) {
        if (options.invalidateCache) {
            this.cache = undefined;
        }
        if (this.cache) {
            return this.cache;
        }
        const root = this.pathHelper.getRoot();
        // Search patterns for site configs
        const sitePathPattern = path.join(root, 'sites', '*/config.json').replace(/\\/gi, '/');
        const oldSitePathPattern = path.join(root, 'config.*.json').replace(/\\/gi, '/');
        // Find all config files
        const files = [
            ...(await glob(sitePathPattern)),
            ...(await glob(oldSitePathPattern))
        ].map(x => path.normalize(x));
        const sites = [];
        for (const conffile of files) {
            if (!fs.existsSync(conffile)) {
                continue;
            }
            try {
                // Read and parse the config file
                const strData = fs.readFileSync(conffile, { encoding: 'utf-8' });
                const formatProvider = this.formatResolver.resolveForFilePath(conffile);
                if (!formatProvider) {
                    throw new Error(`Could not resolve a format provider for file ${conffile}.`);
                }
                const site = formatProvider.parse(strData);
                const result = siteConfigSchema.safeParse(site);
                let needsMigration = false;
                // Migration: Ensure name field exists - use key as fallback
                if (result.success && !result.data.name) {
                    result.data.name = result.data.key;
                    needsMigration = true;
                    this.logger.appendLine(`Migration: Added missing 'name' field to '${conffile}'`);
                }
                // Migration: Ensure source field exists - use default folder source
                if (result.success && !result.data.source) {
                    result.data.source = {
                        type: 'folder',
                        path: 'main'
                    };
                    needsMigration = true;
                    this.logger.appendLine(`Migration: Added missing 'source' field to '${conffile}'`);
                }
                // Save the migrated config back to disk
                if (needsMigration) {
                    try {
                        fs.writeFileSync(conffile, JSON.stringify(site, null, 2), { encoding: 'utf8' });
                        this.logger.appendLine(`Migrated site config '${conffile}'`);
                    }
                    catch (writeErr) {
                        this.logger.appendLine(`Warning: Could not save migrated config '${conffile}': ${writeErr instanceof Error ? writeErr.message : String(writeErr)}`);
                    }
                }
                // Validate the site config with Zod
                const validatedSite = siteConfigSchema.parse(site);
                // Convert relative paths to absolute
                if (validatedSite.source) {
                    validatedSite.source.path = this.siteSourceRelativeToAbsolute(validatedSite, conffile);
                }
                // Add runtime properties
                const runtimeSite = {
                    ...validatedSite,
                    published: 'unknown',
                    configPath: conffile,
                    etalage: this.getEtalage(validatedSite)
                };
                sites.push(runtimeSite);
            }
            catch (e) {
                const errorMsg = e instanceof Error ? e.message : String(e);
                this.logger.appendLine(`Configuration file is invalid '${conffile}': ${errorMsg}`);
            }
        }
        const configurations = { sites };
        this.cache = configurations;
        return configurations;
    }
    /**
     * Get a single site configuration by key
     */
    async getSiteConfig(siteKey) {
        const configurations = await this.getConfigurations();
        const site = configurations.sites.find(s => s.key === siteKey);
        return site ? site : null;
    }
    /**
     * Convert relative site source paths to absolute paths
     */
    siteSourceRelativeToAbsolute(site, conffile) {
        if (!site.source) {
            return '';
        }
        const sourcePath = site.source.path;
        // If path is already absolute (starts with /), return as-is
        if (sourcePath.substring(0, 1) === '/') {
            return sourcePath;
        }
        // Otherwise, resolve relative to site directory
        const siteKey = path.basename(path.dirname(conffile));
        return path.join(this.pathHelper.getRoot(), 'sites', siteKey, sourcePath);
    }
    /**
     * Load etalage data (showcase metadata) for a site
     */
    getEtalage(site) {
        if (!site.source) {
            return { screenshots: [], favicons: [] };
        }
        const sourcePath = site.source.path;
        const etalagePath = path.join(sourcePath, 'quiqr/etalage/etalage.json');
        const etalageScreenshotsPath = path.join(sourcePath, 'quiqr/etalage/screenshots/');
        const etalageFaviconPath = path.join(sourcePath, 'quiqr/etalage/favicon/');
        let etalage = {
            screenshots: [],
            favicons: []
        };
        // Load etalage.json if it exists
        if (fs.existsSync(etalagePath)) {
            try {
                const strData = fs.readFileSync(etalagePath, { encoding: 'utf-8' });
                const formatProvider = this.formatResolver.resolveForFilePath(etalagePath);
                if (formatProvider) {
                    const parsed = formatProvider.parse(strData);
                    if (isRecord(parsed)) {
                        etalage = { ...etalage, ...parsed };
                    }
                }
            }
            catch (e) {
                this.logger.appendLine(`Warning: Could not load etalage.json for site: ${e instanceof Error ? e.message : String(e)}`);
            }
        }
        // Find screenshot files
        try {
            const screenshotPattern = path.join(etalageScreenshotsPath, '*.{png,jpg,jpeg,gif}').replace(/\\/gi, '/');
            const screenshotFiles = glob.sync(screenshotPattern).map(x => {
                const normalized = path.normalize(x);
                return normalized.substr(sourcePath.length);
            });
            etalage.screenshots = screenshotFiles;
        }
        catch {
            // Ignore glob errors (directory doesn't exist, etc.)
        }
        // Find favicon files
        try {
            const faviconPattern = path.join(etalageFaviconPath, '*.{png,jpg,jpeg,gif,ico}').replace(/\\/gi, '/');
            const faviconFiles = glob.sync(faviconPattern).map(x => {
                const normalized = path.normalize(x);
                return normalized.substr(sourcePath.length);
            });
            etalage.favicons = faviconFiles;
        }
        catch {
            // Ignore glob errors (directory doesn't exist, etc.)
        }
        return etalage;
    }
}
/**
 * Simple console logger adapter
 */
export class ConsoleLogger {
    appendLine(message) {
        console.log(message);
    }
}