"use strict";
/**
 * Version Discovery Utility
 * Discovers actual versions of dependencies from multiple sources:
 * - Node.js: package.json
 * - Python: requirements.txt, pyproject.toml, Pipfile
 * - Go: go.mod
 * - Rust: Cargo.toml
 * - PHP: composer.json
 * Enables version-aware documentation generation
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.discoverVersions = discoverVersions;
exports.getPackageVersion = getPackageVersion;
exports.cleanVersion = cleanVersion;
exports.getMajorVersion = getMajorVersion;
exports.parseVersion = parseVersion;
exports.satisfiesVersion = satisfiesVersion;
exports.discoverTechnologyVersions = discoverTechnologyVersions;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
/**
 * Discover versions from all dependency files in the output directory
 * Supports multiple languages and package managers
 */
async function discoverVersions(outputDirectory) {
    const versions = {};
    // Define component locations and their possible dependency files
    const components = [
        {
            name: 'frontend',
            paths: [
                'frontend/package.json',
                'frontend/requirements.txt',
                'frontend/pyproject.toml',
            ]
        },
        {
            name: 'backend',
            paths: [
                'backend/package.json',
                'backend/requirements.txt',
                'backend/pyproject.toml',
                'backend/Pipfile',
                'backend/go.mod',
                'backend/Cargo.toml',
                'backend/composer.json',
            ]
        },
        {
            name: 'root',
            paths: [
                'package.json',
                'requirements.txt',
                'go.mod',
                'Cargo.toml',
            ]
        },
    ];
    for (const component of components) {
        // Try each possible dependency file
        for (const relativePath of component.paths) {
            const fullPath = path.join(outputDirectory, relativePath);
            if (fs.existsSync(fullPath)) {
                try {
                    const versionMap = await parseVersionFile(fullPath);
                    if (versionMap) {
                        // Merge with existing versions if already found
                        if (versions[component.name]) {
                            versions[component.name] = {
                                dependencies: {
                                    ...versions[component.name].dependencies,
                                    ...versionMap.dependencies,
                                },
                                devDependencies: {
                                    ...versions[component.name].devDependencies,
                                    ...versionMap.devDependencies,
                                },
                            };
                        }
                        else {
                            versions[component.name] = versionMap;
                        }
                    }
                }
                catch (error) {
                    console.warn(`Failed to parse ${fullPath}:`, error);
                }
            }
        }
    }
    return versions;
}
/**
 * Parse a dependency file and extract versions
 */
async function parseVersionFile(filePath) {
    const filename = path.basename(filePath);
    switch (filename) {
        case 'package.json':
            return parsePackageJson(filePath);
        case 'requirements.txt':
            return parseRequirementsTxt(filePath);
        case 'pyproject.toml':
            return parsePyprojectToml(filePath);
        case 'Pipfile':
            return parsePipfile(filePath);
        case 'go.mod':
            return parseGoMod(filePath);
        case 'Cargo.toml':
            return parseCargoToml(filePath);
        case 'composer.json':
            return parseComposerJson(filePath);
        default:
            return null;
    }
}
/**
 * Parse package.json (Node.js/npm)
 */
function parsePackageJson(filePath) {
    const content = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    return {
        dependencies: content.dependencies || {},
        devDependencies: content.devDependencies || {},
    };
}
/**
 * Parse requirements.txt (Python/pip)
 * Format: package==1.2.3 or package>=1.2.3
 */
function parseRequirementsTxt(filePath) {
    const content = fs.readFileSync(filePath, 'utf-8');
    const dependencies = {};
    for (const line of content.split('\n')) {
        const trimmed = line.trim();
        // Skip comments and empty lines
        if (!trimmed || trimmed.startsWith('#'))
            continue;
        // Parse package==version or package>=version
        const match = trimmed.match(/^([a-zA-Z0-9_-]+)\s*([=><~!]+)\s*([0-9.]+)/);
        if (match) {
            const [, packageName, operator, version] = match;
            dependencies[packageName] = `${operator}${version}`;
        }
    }
    return { dependencies, devDependencies: {} };
}
/**
 * Parse pyproject.toml (Python/Poetry)
 * Simple TOML parser for dependencies section
 */
function parsePyprojectToml(filePath) {
    const content = fs.readFileSync(filePath, 'utf-8');
    const dependencies = {};
    const devDependencies = {};
    // Simple regex-based parsing (not full TOML parser)
    const depSection = content.match(/\[tool\.poetry\.dependencies\]([\s\S]*?)(\[|$)/);
    const devDepSection = content.match(/\[tool\.poetry\.dev-dependencies\]([\s\S]*?)(\[|$)/);
    if (depSection) {
        parsePyprojectDeps(depSection[1], dependencies);
    }
    if (devDepSection) {
        parsePyprojectDeps(devDepSection[1], devDependencies);
    }
    return { dependencies, devDependencies };
}
function parsePyprojectDeps(section, target) {
    const lines = section.split('\n');
    for (const line of lines) {
        const match = line.match(/^([a-zA-Z0-9_-]+)\s*=\s*"([^"]+)"/);
        if (match) {
            const [, packageName, version] = match;
            if (packageName !== 'python') {
                target[packageName] = version;
            }
        }
    }
}
/**
 * Parse Pipfile (Python/Pipenv)
 */
function parsePipfile(filePath) {
    const content = fs.readFileSync(filePath, 'utf-8');
    const dependencies = {};
    const devDependencies = {};
    const depSection = content.match(/\[packages\]([\s\S]*?)(\[|$)/);
    const devDepSection = content.match(/\[dev-packages\]([\s\S]*?)(\[|$)/);
    if (depSection) {
        parsePipfileDeps(depSection[1], dependencies);
    }
    if (devDepSection) {
        parsePipfileDeps(devDepSection[1], devDependencies);
    }
    return { dependencies, devDependencies };
}
function parsePipfileDeps(section, target) {
    const lines = section.split('\n');
    for (const line of lines) {
        const match = line.match(/^([a-zA-Z0-9_-]+)\s*=\s*"([^"]+)"/);
        if (match) {
            const [, packageName, version] = match;
            target[packageName] = version;
        }
    }
}
/**
 * Parse go.mod (Go modules)
 * Format: require package v1.2.3
 */
function parseGoMod(filePath) {
    const content = fs.readFileSync(filePath, 'utf-8');
    const dependencies = {};
    // Match require blocks
    const requireBlock = content.match(/require\s*\(([\s\S]*?)\)/);
    if (requireBlock) {
        const lines = requireBlock[1].split('\n');
        for (const line of lines) {
            const match = line.trim().match(/^([^\s]+)\s+v([0-9.]+)/);
            if (match) {
                const [, packageName, version] = match;
                dependencies[packageName] = version;
            }
        }
    }
    // Match single require statements
    const singleRequires = content.matchAll(/require\s+([^\s]+)\s+v([0-9.]+)/g);
    for (const match of singleRequires) {
        const [, packageName, version] = match;
        dependencies[packageName] = version;
    }
    return { dependencies, devDependencies: {} };
}
/**
 * Parse Cargo.toml (Rust/Cargo)
 */
function parseCargoToml(filePath) {
    const content = fs.readFileSync(filePath, 'utf-8');
    const dependencies = {};
    const devDependencies = {};
    const depSection = content.match(/\[dependencies\]([\s\S]*?)(\[|$)/);
    const devDepSection = content.match(/\[dev-dependencies\]([\s\S]*?)(\[|$)/);
    if (depSection) {
        parseCargoDeps(depSection[1], dependencies);
    }
    if (devDepSection) {
        parseCargoDeps(devDepSection[1], devDependencies);
    }
    return { dependencies, devDependencies };
}
function parseCargoDeps(section, target) {
    const lines = section.split('\n');
    for (const line of lines) {
        // Simple format: package = "1.2.3"
        const simpleMatch = line.match(/^([a-zA-Z0-9_-]+)\s*=\s*"([^"]+)"/);
        if (simpleMatch) {
            const [, packageName, version] = simpleMatch;
            target[packageName] = version;
            continue;
        }
        // Object format: package = { version = "1.2.3" }
        const objMatch = line.match(/^([a-zA-Z0-9_-]+)\s*=\s*\{[^}]*version\s*=\s*"([^"]+)"/);
        if (objMatch) {
            const [, packageName, version] = objMatch;
            target[packageName] = version;
        }
    }
}
/**
 * Parse composer.json (PHP/Composer)
 */
function parseComposerJson(filePath) {
    const content = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    return {
        dependencies: content.require || {},
        devDependencies: content['require-dev'] || {},
    };
}
/**
 * Get version of a specific package from discovered versions
 */
function getPackageVersion(versions, packageName, component) {
    // If component specified, search in that component only
    if (component && versions[component]) {
        const versionMap = versions[component];
        return versionMap.dependencies[packageName] || versionMap.devDependencies[packageName];
    }
    // Otherwise, search all components
    for (const versionMap of Object.values(versions)) {
        if (!versionMap)
            continue;
        const version = versionMap.dependencies[packageName] || versionMap.devDependencies[packageName];
        if (version) {
            return version;
        }
    }
    return undefined;
}
/**
 * Clean version string (remove ^ ~ >= etc.)
 */
function cleanVersion(version) {
    return version.replace(/^[\^~>=<]+/, '');
}
/**
 * Get major version number
 */
function getMajorVersion(version) {
    const cleaned = cleanVersion(version);
    const match = cleaned.match(/^(\d+)/);
    return match ? parseInt(match[1], 10) : undefined;
}
/**
 * Get semantic version parts
 */
function parseVersion(version) {
    const cleaned = cleanVersion(version);
    const match = cleaned.match(/^(\d+)\.(\d+)\.(\d+)/);
    if (!match)
        return undefined;
    return {
        major: parseInt(match[1], 10),
        minor: parseInt(match[2], 10),
        patch: parseInt(match[3], 10),
    };
}
/**
 * Check if a version satisfies a requirement
 */
function satisfiesVersion(actual, required) {
    const actualParsed = parseVersion(actual);
    const requiredParsed = parseVersion(required);
    if (!actualParsed || !requiredParsed)
        return false;
    // Simple major.minor.patch comparison
    if (actualParsed.major !== requiredParsed.major) {
        return actualParsed.major > requiredParsed.major;
    }
    if (actualParsed.minor !== requiredParsed.minor) {
        return actualParsed.minor > requiredParsed.minor;
    }
    return actualParsed.patch >= requiredParsed.patch;
}
/**
 * Discover technology versions based on common package patterns
 * Supports multiple languages and frameworks
 */
async function discoverTechnologyVersions(outputDirectory) {
    const versions = await discoverVersions(outputDirectory);
    return {
        // Frontend
        react: getPackageVersion(versions, 'react'),
        vue: getPackageVersion(versions, 'vue'),
        angular: getPackageVersion(versions, '@angular/core'),
        svelte: getPackageVersion(versions, 'svelte'),
        // Backend - Node.js
        express: getPackageVersion(versions, 'express'),
        fastify: getPackageVersion(versions, 'fastify'),
        nestjs: getPackageVersion(versions, '@nestjs/core'),
        // Backend - Python
        flask: getPackageVersion(versions, 'Flask') || getPackageVersion(versions, 'flask'),
        django: getPackageVersion(versions, 'Django') || getPackageVersion(versions, 'django'),
        fastapi: getPackageVersion(versions, 'fastapi'),
        // Backend - Go
        gin: getPackageVersion(versions, 'github.com/gin-gonic/gin'),
        // Backend - Rust
        actix: getPackageVersion(versions, 'actix-web'),
        // ORMs
        prisma: getPackageVersion(versions, '@prisma/client'),
        typeorm: getPackageVersion(versions, 'typeorm'),
        drizzle: getPackageVersion(versions, 'drizzle-orm'),
        sqlalchemy: getPackageVersion(versions, 'SQLAlchemy') || getPackageVersion(versions, 'sqlalchemy'),
        // Auth
        clerk: getPackageVersion(versions, '@clerk/express') || getPackageVersion(versions, '@clerk/clerk-react'),
        auth0: getPackageVersion(versions, 'express-oauth2-jwt-bearer'),
        // Languages
        typescript: getPackageVersion(versions, 'typescript'),
        python: getPackageVersion(versions, 'python'), // From pyproject.toml
        go: undefined, // Go version usually in go.mod but not as a dependency
        rust: undefined, // Rust version not in Cargo.toml
    };
}
//# sourceMappingURL=version-discovery.js.map