"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get LogFormat () {
        return LogFormat;
    },
    get Logger () {
        return Logger;
    },
    get createLogger () {
        return createLogger;
    },
    get logger () {
        return logger;
    }
});
const _loggertypes = require("./logger.types");
const _security = require("./security");
const _traceId = require("./traceId");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
/**
 * 检测运行环境是否为浏览器
 */ const isBrowser = ()=>{
    return typeof window !== 'undefined' && typeof window.document !== 'undefined';
};
/**
 * ANSI 颜色代码（用于 Node.js 环境）
 */ const ANSI_COLORS = {
    reset: '\x1b[0m',
    bright: '\x1b[1m',
    dim: '\x1b[2m',
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m',
    white: '\x1b[37m',
    bgRed: '\x1b[41m',
    bgGreen: '\x1b[42m',
    bgYellow: '\x1b[43m',
    bgBlue: '\x1b[44m',
    bgMagenta: '\x1b[45m',
    bgCyan: '\x1b[46m',
    bgWhite: '\x1b[47m'
};
/**
 * 浏览器控制台样式（用于浏览器环境）
 */ const BROWSER_STYLES = {
    debug: 'color: #888; font-weight: normal;',
    info: 'color: #2196F3; font-weight: normal;',
    warn: 'color: #FF9800; font-weight: bold;',
    error: 'color: #F44336; font-weight: bold;'
};
/**
 * 日志级别对应的颜色配置
 */ const LEVEL_COLORS = {
    [_loggertypes.LogLevel.DEBUG]: {
        node: ANSI_COLORS.dim + ANSI_COLORS.white,
        browser: BROWSER_STYLES.debug
    },
    [_loggertypes.LogLevel.INFO]: {
        node: ANSI_COLORS.cyan,
        browser: BROWSER_STYLES.info
    },
    [_loggertypes.LogLevel.WARN]: {
        node: ANSI_COLORS.yellow,
        browser: BROWSER_STYLES.warn
    },
    [_loggertypes.LogLevel.ERROR]: {
        node: ANSI_COLORS.red + ANSI_COLORS.bright,
        browser: BROWSER_STYLES.error
    },
    [_loggertypes.LogLevel.NONE]: {
        node: '',
        browser: ''
    }
};
/**
 * 日志级别标签
 */ const LEVEL_LABELS = {
    [_loggertypes.LogLevel.DEBUG]: 'DEBUG',
    [_loggertypes.LogLevel.INFO]: 'INFO',
    [_loggertypes.LogLevel.WARN]: 'WARN',
    [_loggertypes.LogLevel.ERROR]: 'ERROR',
    [_loggertypes.LogLevel.NONE]: ''
};
var LogFormat = /*#__PURE__*/ function(LogFormat) {
    /**
   * 文本格式（默认）
   */ LogFormat["TEXT"] = "text";
    /**
   * JSON 格式（用于日志聚合）
   */ LogFormat["JSON"] = "json";
    /**
   * 结构化格式（用于分析）
   */ LogFormat["STRUCTURED"] = "structured";
    return LogFormat;
}({});
/**
 * Logger 类
 */ let Logger = class Logger {
    /**
   * 设置日志级别
   */ setLevel(level) {
        this.level = level;
    }
    /**
   * 获取当前日志级别
   */ getLevel() {
        return this.level;
    }
    /**
   * 格式化时间戳
   */ formatTimestamp() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    }
    /**
   * 构建日志前缀
   */ buildPrefix(logLevel) {
        const parts = [];
        if (this.showTimestamp) {
            parts.push(`[${this.formatTimestamp()}]`);
        }
        if (this.showLevel) {
            parts.push(`[${LEVEL_LABELS[logLevel]}]`);
        }
        // 添加追踪 ID（如果存在）
        const traceId = (0, _traceId.getCurrentTraceId)();
        if (traceId) {
            parts.push(`[Trace:${traceId.substring(0, 8)}]`);
        }
        if (this.prefix) {
            parts.push(`[${this.prefix}]`);
        }
        return parts.join(' ');
    }
    /**
   * 输出日志（Node.js 环境）
   */ logNode(level, ...args) {
        if (level < this.level) {
            return;
        }
        const prefix = this.buildPrefix(level);
        const colorConfig = LEVEL_COLORS[level];
        const reset = this.enableColors ? ANSI_COLORS.reset : '';
        if (this.enableColors && colorConfig.node) {
            console.log(`${colorConfig.node}${prefix}${reset}`, ...args);
        } else {
            console.log(prefix, ...args);
        }
    }
    /**
   * 输出日志（浏览器环境）
   */ logBrowser(level, ...args) {
        if (level < this.level) {
            return;
        }
        const prefix = this.buildPrefix(level);
        const colorConfig = LEVEL_COLORS[level];
        if (this.enableColors && colorConfig.browser) {
            console.log(`%c${prefix}`, colorConfig.browser, ...args);
        } else {
            console.log(prefix, ...args);
        }
    }
    /**
   * 脱敏处理
   */ sanitizeValue(value) {
        if (!this.enableSanitization) {
            return value;
        }
        if (typeof value === 'string') {
            // 检查是否包含敏感内容
            if (_security.SecurityUtils.containsDangerousContent(value)) {
                return _security.SecurityUtils.sanitizeText(value);
            }
            return value;
        }
        if (value && typeof value === 'object') {
            if (Array.isArray(value)) {
                return value.map((item)=>this.sanitizeValue(item));
            }
            const sanitized = {};
            for (const [key, val] of Object.entries(value)){
                // 检查是否为敏感字段
                if (_security.SecurityUtils.isSensitiveField(key)) {
                    sanitized[key] = '***';
                } else {
                    sanitized[key] = this.sanitizeValue(val);
                }
            }
            return sanitized;
        }
        return value;
    }
    /**
   * 处理日志参数（脱敏、过滤等）
   */ processLogArgs(...args) {
        // 生产环境自动禁用 DEBUG 级别
        if (this.isProduction && this.level === _loggertypes.LogLevel.DEBUG) {
            return [];
        }
        return args.map((arg)=>this.sanitizeValue(arg));
    }
    /**
   * 设置日志格式
   */ setFormat(format) {
        this.format = format;
    }
    /**
   * 设置日志上下文
   */ setContext(context) {
        this.context = {
            ...this.context,
            ...context
        };
    }
    /**
   * 更新日志上下文
   */ updateContext(context) {
        this.context = {
            ...this.context,
            ...context
        };
    }
    /**
   * 获取日志上下文
   */ getContext() {
        return {
            ...this.context
        };
    }
    /**
   * 清除日志上下文
   */ clearContext() {
        this.context = {};
    }
    /**
   * 注册日志处理器（用于日志聚合）
   */ addLogHandler(handler) {
        this.logHandlers.push(handler);
        return ()=>{
            const index = this.logHandlers.indexOf(handler);
            if (index > -1) {
                this.logHandlers.splice(index, 1);
            }
        };
    }
    /**
   * 创建结构化日志条目
   */ createStructuredEntry(level, message, data) {
        const traceId = (0, _traceId.getCurrentTraceId)();
        const entry = {
            timestamp: new Date().toISOString(),
            level,
            message,
            context: {
                ...this.context,
                traceId: traceId || this.context.traceId
            },
            source: this.prefix || 'framework'
        };
        if (data !== undefined) {
            entry.data = this.sanitizeValue(data);
        }
        // 如果是错误，提取堆栈信息
        if (data instanceof Error) {
            entry.stack = data.stack;
            entry.message = data.message || message;
        }
        return entry;
    }
    /**
   * 输出结构化日志
   */ outputStructured(entry) {
        // 调用日志处理器
        this.logHandlers.forEach((handler)=>{
            try {
                handler(entry);
            } catch (error) {
            // 忽略处理器错误，避免循环
            }
        });
        // 根据格式输出
        if (this.format === "json") {
            console.log(JSON.stringify(entry));
        } else if (this.format === "structured") {
            console.log(entry);
        } else {
            // TEXT 格式使用原有输出方式
            const args = entry.data !== undefined ? [
                entry.data
            ] : [];
            if (isBrowser()) {
                this.logBrowser(entry.level, entry.message, ...args);
            } else {
                this.logNode(entry.level, entry.message, ...args);
            }
        }
    }
    /**
   * 通用日志输出方法
   */ log(level, ...args) {
        if (level < this.level) {
            return;
        }
        const processedArgs = this.processLogArgs(...args);
        // 如果处理后没有参数（被过滤），则不输出
        if (processedArgs.length === 0) {
            return;
        }
        // 提取消息和数据
        const message = typeof processedArgs[0] === 'string' ? processedArgs[0] : 'Log message';
        const data = processedArgs.length > 1 ? processedArgs.slice(1) : typeof processedArgs[0] === 'string' ? undefined : processedArgs[0];
        // 创建结构化日志条目
        const entry = this.createStructuredEntry(level, message, data);
        // 输出日志
        this.outputStructured(entry);
    }
    /**
   * 输出 DEBUG 级别日志
   */ debug(...args) {
        this.log(_loggertypes.LogLevel.DEBUG, ...args);
    }
    /**
   * 输出 INFO 级别日志
   */ info(...args) {
        this.log(_loggertypes.LogLevel.INFO, ...args);
    }
    /**
   * 输出 WARN 级别日志
   */ warn(...args) {
        this.log(_loggertypes.LogLevel.WARN, ...args);
    }
    /**
   * 输出 ERROR 级别日志
   */ error(...args) {
        this.log(_loggertypes.LogLevel.ERROR, ...args);
    }
    constructor(options = {}){
        _define_property(this, "level", void 0);
        _define_property(this, "enableColors", void 0);
        _define_property(this, "showTimestamp", void 0);
        _define_property(this, "showLevel", void 0);
        _define_property(this, "prefix", void 0);
        _define_property(this, "enableSanitization", void 0);
        _define_property(this, "isProduction", void 0);
        _define_property(this, "format", void 0);
        _define_property(this, "context", {});
        _define_property(this, "logHandlers", []);
        this.level = options.level ?? _loggertypes.LogLevel.INFO;
        this.enableColors = options.enableColors ?? true;
        this.showTimestamp = options.showTimestamp ?? true;
        this.showLevel = options.showLevel ?? true;
        this.prefix = options.prefix ?? '';
        this.enableSanitization = options.enableSanitization ?? true;
        this.isProduction = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
        this.format = options.format ?? "text";
        this.context = options.context ?? {};
    }
};
const createLogger = (options)=>{
    return new Logger(options);
};
const logger = createLogger();

//# sourceMappingURL=logger.js.map