All files / src create-docx.js

0% Statements 0/113
0% Branches 0/70
0% Functions 0/13
0% Lines 0/111

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
const fs = require('fs-extra');
const path = require('node:path');
const { JSDOM } = require('jsdom');
const { Document, Packer, Paragraph, TextRun, HeadingLevel, TableOfContents, Table, TableRow, TableCell, WidthType, AlignmentType } = require('docx');
const Logger = require('./utils/logger');
 
/**
 * Creates DOCX metadata from config
 */
function createDocxMetadata(config) {
    return {
        title: config.specs[0].title || 'Untitled Document',
        subject: config.specs[0].description || '',
        creator: config.specs[0].author || '',
        keywords: config.specs[0].keywords || [],
        description: config.specs[0].description || '',
        lastModifiedBy: 'Spec-Up DOCX Generator',
        revision: 1,
        createdAt: new Date(),
        modifiedAt: new Date()
    };
}
 
/**
 * Converts HTML heading to DOCX heading level
 */
function getHeadingLevel(tagName) {
    const levels = {
        'h1': HeadingLevel.HEADING_1,
        'h2': HeadingLevel.HEADING_2,
        'h3': HeadingLevel.HEADING_3,
        'h4': HeadingLevel.HEADING_4,
        'h5': HeadingLevel.HEADING_5,
        'h6': HeadingLevel.HEADING_6
    };
    return levels[tagName.toLowerCase()] || HeadingLevel.HEADING_1;
}
 
/**
 * Processes HTML node and converts to DOCX paragraphs
 */
function processNode(node, elements = []) {
    if (node.nodeType === 3) { // Text node
        const text = node.textContent.trim();
        if (text) {
            elements.push(new Paragraph({
                children: [new TextRun(text)]
            }));
        }
        return elements;
    }
 
    if (node.nodeType !== 1) return elements; // Skip non-element nodes
 
    const tagName = node.tagName.toLowerCase();
 
    switch (tagName) {
        case 'h1':
        case 'h2':
        case 'h3':
        case 'h4':
        case 'h5':
        case 'h6':
            elements.push(new Paragraph({
                text: node.textContent.trim(),
                heading: getHeadingLevel(tagName)
            }));
            break;
 
        case 'p':
            const textRuns = [];
            processInlineElements(node, textRuns);
            if (textRuns.length > 0) {
                elements.push(new Paragraph({
                    children: textRuns
                }));
            }
            break;
 
        case 'ul':
        case 'ol':
            const listItems = Array.from(node.children);
            listItems.forEach(li => {
                if (li.tagName.toLowerCase() === 'li') {
                    elements.push(new Paragraph({
                        text: li.textContent.trim(),
                        bullet: { level: 0 }
                    }));
                }
            });
            break;
 
        case 'table':
            const tableRows = Array.from(node.querySelectorAll('tr'));
            if (tableRows.length > 0) {
                const docxRows = tableRows.map(row => {
                    const cells = Array.from(row.querySelectorAll('td, th'));
                    return new TableRow({
                        children: cells.map(cell => new TableCell({
                            children: [new Paragraph({
                                text: cell.textContent.trim()
                            })],
                            width: {
                                size: 100 / cells.length,
                                type: WidthType.PERCENTAGE
                            }
                        }))
                    });
                });
 
                elements.push(new Table({
                    rows: docxRows,
                    width: {
                        size: 100,
                        type: WidthType.PERCENTAGE
                    }
                }));
            }
            break;
 
        case 'pre':
            // Treat the entire pre block as a single monospace paragraph.
            // Recursing into children would produce one paragraph per Prism token span.
            if (node.textContent.trim()) {
                elements.push(new Paragraph({
                    children: [new TextRun({
                        text: node.textContent,
                        font: 'Courier New',
                        size: 18 // 9pt (half-points)
                    })]
                }));
            }
            break;
 
        case 'blockquote':
            elements.push(new Paragraph({
                text: node.textContent.trim(),
                indent: {
                    left: 720 // 0.5 inch in twips
                }
            }));
            break;
 
        case 'dl':
            // Process definition lists
            const dlItems = Array.from(node.children);
            dlItems.forEach(item => {
                if (item.tagName.toLowerCase() === 'dt') {
                    elements.push(new Paragraph({
                        children: [new TextRun({
                            text: item.textContent.trim(),
                            bold: true
                        })]
                    }));
                } else if (item.tagName.toLowerCase() === 'dd') {
                    elements.push(new Paragraph({
                        text: item.textContent.trim(),
                        indent: {
                            left: 360 // 0.25 inch in twips
                        }
                    }));
                }
            });
            break;
 
        default:
            // For other elements, process their children
            Array.from(node.childNodes).forEach(child => {
                processNode(child, elements);
            });
            break;
    }
 
    return elements;
}
 
/**
 * Processes inline elements within paragraphs
 */
function processInlineElements(node, textRuns) {
    Array.from(node.childNodes).forEach(child => {
        if (child.nodeType === 3) { // Text node
            const text = child.textContent;
            if (text.trim()) {
                textRuns.push(new TextRun(text));
            }
        } else if (child.nodeType === 1) { // Element node
            const tagName = child.tagName.toLowerCase();
            const text = child.textContent.trim();
 
            if (text) {
                switch (tagName) {
                    case 'strong':
                    case 'b':
                        textRuns.push(new TextRun({
                            text: text,
                            bold: true
                        }));
                        break;
                    case 'em':
                    case 'i':
                        textRuns.push(new TextRun({
                            text: text,
                            italics: true
                        }));
                        break;
                    case 'code':
                        textRuns.push(new TextRun({
                            text: text,
                            font: 'Courier New'
                        }));
                        break;
                    case 'a':
                        textRuns.push(new TextRun({
                            text: text,
                            color: '0000FF',
                            underline: {}
                        }));
                        break;
                    default:
                        textRuns.push(new TextRun(text));
                        break;
                }
            }
        }
    });
}
 
/**
 * Creates a title page
 */
function createTitlePage(config) {
    const elements = [];
    const spec = config.specs[0];
 
    if (spec.title) {
        elements.push(new Paragraph({
            text: spec.title,
            heading: HeadingLevel.TITLE,
            alignment: AlignmentType.CENTER
        }));
    }
 
    if (spec.description) {
        elements.push(new Paragraph({
            text: spec.description,
            alignment: AlignmentType.CENTER
        }));
    }
 
    if (spec.author) {
        elements.push(new Paragraph({
            text: `Author: ${spec.author}`,
            alignment: AlignmentType.CENTER
        }));
    }
 
    // Add some spacing
    elements.push(new Paragraph({ text: '' }));
    elements.push(new Paragraph({ text: '' }));
 
    return elements;
}
 
(async () => {
    try {
        Logger.info('Starting DOCX generation...');
 
        // Read and parse the specs.json file
        const config = fs.readJsonSync('specs.json');
        const metadata = createDocxMetadata(config);
 
        // Extract configuration details
        const outputPath = config.specs[0].output_path;
        const filePath = path.resolve(process.cwd(), outputPath, 'index.html');
 
        // Check if HTML file exists
        if (!fs.existsSync(filePath)) {
            Logger.error('HTML file not found', {
                context: 'Cannot generate DOCX without rendered HTML',
                hint: 'Run "npm run render" first to generate the HTML file, then run "npm run docx"',
                details: `Expected file: ${filePath}`
            });
            return;
        }
 
        // Read and parse the HTML file
        const htmlContent = fs.readFileSync(filePath, 'utf8');
        const dom = new JSDOM(htmlContent);
        const document = dom.window.document;
 
        // Remove unnecessary elements
        document.querySelectorAll('script, style, .d-print-none, [style*="display: none"]').forEach(el => el.remove());
 
        // Start building the DOCX document
        const docElements = [];
 
        // Add title page
        docElements.push(...createTitlePage(config));
 
        // Add table of contents placeholder
        docElements.push(new TableOfContents('Table of Contents', {
            hyperlink: true,
            headingStyleRange: '1-6'
        }));
 
        // Add page break after TOC
        docElements.push(new Paragraph({
            text: '',
            pageBreakBefore: true
        }));
 
        // Process the main content
        const mainContent = document.querySelector('main') || document.body;
        processNode(mainContent, docElements);
 
        // Create the DOCX document
        const doc = new Document({
            properties: {
                title: metadata.title,
                subject: metadata.subject,
                creator: metadata.creator,
                keywords: metadata.keywords.join(', '),
                description: metadata.description,
                lastModifiedBy: metadata.lastModifiedBy,
                revision: metadata.revision,
                createdAt: metadata.createdAt,
                modifiedAt: metadata.modifiedAt
            },
            sections: [{
                children: docElements
            }]
        });
 
        // Generate the DOCX file
        const buffer = await Packer.toBuffer(doc);
        const docxPath = path.resolve(process.cwd(), 'docs/index.docx');
 
        // Ensure docs directory exists
        fs.ensureDirSync(path.dirname(docxPath));
 
        // Write the DOCX file
        fs.writeFileSync(docxPath, buffer);
 
        Logger.success('DOCX generated successfully! Find the DOCX file in the docs directory.');
    } catch (error) {
        Logger.error('Error generating DOCX', {
            context: 'Failed during DOCX document generation',
            hint: 'Ensure the HTML file is valid and all dependencies are installed. Check that you have write permissions for the output directory',
            details: error.message
        });
        process.exit(1);
    }
})();