All files / backend/dist/build-actions build-action-service.js

4.65% Statements 4/86
3.03% Branches 2/66
7.14% Functions 1/14
4.65% Lines 4/86

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            1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                    
import { spawn } from 'child_process';
import { SITE_CATEGORIES } from '../logging/index.js';
/**
 * Platform types
 */
export var Platform;
(function (Platform) {
    Platform["WINDOWS"] = "windows";
    Platform["UNIX"] = "unix";
    Platform["MACOS"] = "macos";
})(Platform || (Platform = {}));
/**
 * Service for executing custom build actions on documents
 *
 * Build actions allow running platform-specific commands with variable substitution.
 * Commonly used for Quarto rendering and other custom document processing.
 */
export class BuildActionService {
    logger;
    container;
    constructor(logger, container) {
        this.logger = logger;
        this.container = container;
    }
    /**
     * Run a build action on a document
     *
     * @param actionName - Name of the build action
     * @param executeDict - Execution configuration (windows/unix commands)
     * @param filePath - Path to the document file
     * @param sitePath - Path to the site root
     * @param siteKey - Site key for logging
     * @param workspaceKey - Workspace key for logging
     * @returns Promise with build result
     */
    async runAction(actionName, executeDict, filePath, sitePath, siteKey, workspaceKey) {
        const platform = this.detectPlatform();
        // Log build action start
        if (this.container && siteKey && workspaceKey) {
            this.container.logger.infoSite(siteKey, workspaceKey, SITE_CATEGORIES.BUILDACTION, 'Build action started', { actionName, filePath, sitePath, platform });
        }
        try {
            let result;
            if (platform === Platform.WINDOWS) {
                result = await this.runOn(actionName, executeDict.windows, filePath, sitePath, executeDict.stdout_type, executeDict.variables, siteKey, workspaceKey);
            }
            else {
                // Unix or macOS
                result = await this.runOn(actionName, executeDict.unix, filePath, sitePath, executeDict.stdout_type, executeDict.variables, siteKey, workspaceKey);
            }
            // Log success
            if (this.container && siteKey && workspaceKey) {
                this.container.logger.infoSite(siteKey, workspaceKey, SITE_CATEGORIES.BUILDACTION, 'Build action completed', { actionName, filePath, stdoutType: result.stdoutType });
            }
            return result;
        }
        catch (error) {
            // Log error
            if (this.container && siteKey && workspaceKey) {
                this.container.logger.errorSite(siteKey, workspaceKey, SITE_CATEGORIES.BUILDACTION, 'Build action failed', {
                    actionName,
                    filePath,
                    error: error instanceof Error ? error.message : String(error)
                });
            }
            throw error;
        }
    }
    /**
     * Detect the current platform
     */
    detectPlatform() {
        const platform = process.platform;
        if (platform.startsWith('win')) {
            return Platform.WINDOWS;
        }
        else if (platform.startsWith('darwin')) {
            return Platform.MACOS;
        }
        else if (platform.startsWith('linux')) {
            return Platform.UNIX;
        }
        else {
            return Platform.UNIX; // Default to Unix for unknown platforms
        }
    }
    /**
     * Replace path variables in command strings
     *
     * Supported variables:
     * - %SITE_PATH or %site_path - Path to the site root
     * - %DOCUMENT_PATH or %document_path - Path to the document file
     * - Custom variables from execute.variables
     */
    replacePathVars(sourcePath, filePath, sitePath, customVariables) {
        let result = sourcePath
            .replace(/%site_path/gi, sitePath)
            .replace(/%SITE_PATH/g, sitePath)
            .replace(/%document_path/gi, filePath)
            .replace(/%DOCUMENT_PATH/g, filePath);
        // Replace custom variables
        if (customVariables) {
            for (const variable of customVariables) {
                const pattern = new RegExp(`%${variable.name}`, 'g');
                result = result.replace(pattern, variable.value);
            }
        }
        return result;
    }
    /**
     * Apply path replacements (for WSL path mapping, etc.)
     */
    applyPathReplacements(path, replacements) {
        if (!replacements || replacements.length === 0) {
            return path;
        }
        let result = path;
        for (const replacement of replacements) {
            // Escape special regex characters in the search string
            const searchPattern = replacement.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const regex = new RegExp(searchPattern, 'g');
            result = result.replace(regex, replacement.replace);
        }
        return result;
    }
    /**
     * Run a platform-specific command
     */
    runOn(actionName, commandDict, filePath, sitePath, stdoutType, customVariables, siteKey, workspaceKey) {
        // Apply document_path replacements to filePath if specified
        let processedFilePath = filePath;
        if (commandDict.document_path_replace) {
            processedFilePath = this.applyPathReplacements(filePath, commandDict.document_path_replace);
        }
        // Apply site_path replacements to sitePath if specified
        let processedSitePath = sitePath;
        if (commandDict.site_path_replace) {
            processedSitePath = this.applyPathReplacements(sitePath, commandDict.site_path_replace);
        }
        // Replace variables in command
        const command = this.replacePathVars(commandDict.command, processedFilePath, processedSitePath, customVariables);
        // Replace variables in args
        let args = [];
        if (commandDict.args && commandDict.args.length > 0) {
            args = commandDict.args.map((arg) => {
                return this.replacePathVars(arg, processedFilePath, processedSitePath, customVariables);
            });
        }
        return new Promise((resolve, reject) => {
            try {
                const stdoutChunks = [];
                const stderrChunks = [];
                const child = spawn(command, args);
                child.on('exit', (code) => {
                    if (code === 0) {
                        let stdoutContent = Buffer.concat(stdoutChunks).toString();
                        // Apply file_path replacements to stdout if it's a file path
                        if (stdoutType === 'file_path' && commandDict.file_path_replace) {
                            stdoutContent = this.applyPathReplacements(stdoutContent, commandDict.file_path_replace);
                        }
                        resolve({
                            actionName,
                            stdoutType,
                            stdoutContent,
                            filePath: processedFilePath
                        });
                    }
                    else {
                        const error = new Error(`Process exited with code ${code}`);
                        reject(error);
                    }
                });
                child.on('error', (error) => {
                    this.logger.appendLine(`Build action error: ${error.message}`);
                    // Log error to structured logs
                    if (this.container && siteKey && workspaceKey) {
                        this.container.logger.errorSite(siteKey, workspaceKey, SITE_CATEGORIES.BUILDACTION, 'Build action process error', { actionName, error: error.message });
                    }
                    reject(error);
                });
                child.stdout.on('data', (data) => {
                    stdoutChunks.push(data);
                });
                child.stdout.on('end', () => {
                    const stdoutContent = Buffer.concat(stdoutChunks).toString();
                    if (stdoutContent) {
                        this.logger.appendLine(stdoutContent);
                        // Log stdout to structured logs
                        if (this.container && siteKey && workspaceKey) {
                            this.container.logger.infoSite(siteKey, workspaceKey, SITE_CATEGORIES.BUILDACTION, 'Build action output', { actionName, message: stdoutContent });
                        }
                    }
                });
                child.stderr.on('data', (data) => {
                    stderrChunks.push(data);
                    const stderrContent = Buffer.concat(stderrChunks).toString();
                    if (stderrContent) {
                        this.logger.appendLine(stderrContent);
                        // Log stderr to structured logs
                        if (this.container && siteKey && workspaceKey) {
                            this.container.logger.errorSite(siteKey, workspaceKey, SITE_CATEGORIES.BUILDACTION, 'Build action error output', { actionName, message: stderrContent });
                        }
                    }
                });
            }
            catch (error) {
                reject(error);
            }
        });
    }
}