"use strict";
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyParser = void 0;
const parser = __importStar(require("@babel/parser"));
const traverse_1 = __importDefault(require("@babel/traverse"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class DependencyParser {
    constructor() {
        this.supportedExtensions = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs'];
    }
    parseFile(filePath) {
        const ext = path.extname(filePath);
        if (!this.supportedExtensions.includes(ext)) {
            return [];
        }
        try {
            const content = fs.readFileSync(filePath, 'utf-8');
            return this.extractDependencies(content, filePath);
        }
        catch (error) {
            console.error(`Error parsing ${filePath}:`, error);
            return [];
        }
    }
    extractDependencies(code, filePath) {
        const dependencies = [];
        try {
            const ast = parser.parse(code, {
                sourceType: 'module',
                plugins: [
                    'typescript',
                    'jsx',
                    'decorators-legacy',
                    'classProperties',
                    'dynamicImport'
                ]
            });
            (0, traverse_1.default)(ast, {
                // ES6 imports: import foo from 'bar'
                ImportDeclaration: (path) => {
                    const importPath = path.node.source.value;
                    const resolved = this.resolvePath(importPath, filePath);
                    if (resolved) {
                        dependencies.push(resolved);
                    }
                },
                // Dynamic imports: import('bar')
                CallExpression: (path) => {
                    // Handle require()
                    if (path.node.callee.type === 'Identifier' &&
                        path.node.callee.name === 'require' &&
                        path.node.arguments.length > 0) {
                        const arg = path.node.arguments[0];
                        if (arg.type === 'StringLiteral') {
                            const requirePath = arg.value;
                            const resolved = this.resolvePath(requirePath, filePath);
                            if (resolved) {
                                dependencies.push(resolved);
                            }
                        }
                    }
                    // Handle dynamic import()
                    if (path.node.callee.type === 'Import' &&
                        path.node.arguments.length > 0) {
                        const arg = path.node.arguments[0];
                        if (arg.type === 'StringLiteral') {
                            const importPath = arg.value;
                            const resolved = this.resolvePath(importPath, filePath);
                            if (resolved) {
                                dependencies.push(resolved);
                            }
                        }
                    }
                },
                // Export from: export { foo } from 'bar'
                ExportNamedDeclaration: (path) => {
                    if (path.node.source) {
                        const exportPath = path.node.source.value;
                        const resolved = this.resolvePath(exportPath, filePath);
                        if (resolved) {
                            dependencies.push(resolved);
                        }
                    }
                },
                // Export all: export * from 'bar'
                ExportAllDeclaration: (path) => {
                    const exportPath = path.node.source.value;
                    const resolved = this.resolvePath(exportPath, filePath);
                    if (resolved) {
                        dependencies.push(resolved);
                    }
                }
            });
        }
        catch (error) {
            console.error(`Error parsing AST for ${filePath}:`, error);
        }
        return [...new Set(dependencies)]; // Remove duplicates
    }
    resolvePath(importPath, fromFile) {
        // Skip node_modules and external packages
        if (!importPath.startsWith('.') && !importPath.startsWith('/')) {
            return null;
        }
        const dir = path.dirname(fromFile);
        let resolved = path.resolve(dir, importPath);
        // Try to find the file with various extensions
        if (fs.existsSync(resolved)) {
            const stat = fs.statSync(resolved);
            if (stat.isDirectory()) {
                // Try index files
                for (const ext of this.supportedExtensions) {
                    const indexFile = path.join(resolved, `index${ext}`);
                    if (fs.existsSync(indexFile)) {
                        return indexFile;
                    }
                }
            }
            else {
                return resolved;
            }
        }
        // Try adding extensions
        for (const ext of this.supportedExtensions) {
            const withExt = `${resolved}${ext}`;
            if (fs.existsSync(withExt)) {
                return withExt;
            }
        }
        return null;
    }
    buildDependencyMap(files) {
        const map = {};
        for (const file of files) {
            map[file] = this.parseFile(file);
        }
        return map;
    }
}
exports.DependencyParser = DependencyParser;
//# sourceMappingURL=DependencyParser.js.map