/**
 * 工具类型定义
 * 提供JSON↔SSE双向转换中常用的工具类型和辅助函数
 */
// 类型守卫工具函数
export const TypeGuards = {
    isString: (value) => typeof value === 'string',
    isNumber: (value) => typeof value === 'number' && !Number.isNaN(value),
    isBoolean: (value) => typeof value === 'boolean',
    isObject: (value) => value !== null && typeof value === 'object' && !Array.isArray(value),
    isArray: (value) => Array.isArray(value),
    isFunction: (value) => typeof value === 'function',
    isDate: (value) => value instanceof Date,
    isNull: (value) => value === null,
    isUndefined: (value) => value === undefined,
    isNullOrUndefined: (value) => value === null || value === undefined
};
// 异步工具函数
export const AsyncUtils = {
    delay: (ms) => new Promise(resolve => setTimeout(resolve, ms)),
    timeout: (promise, ms) => {
        return Promise.race([
            promise,
            new Promise((_, reject) => setTimeout(() => reject(new Error(`Operation timed out after ${ms}ms`)), ms))
        ]);
    },
    retry: async (fn, config) => {
        let lastError;
        for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
            try {
                return await fn();
            }
            catch (error) {
                const normalizedError = error instanceof Error ? error : new Error(String(error));
                lastError = normalizedError;
                if (!config.retryableErrors.includes(normalizedError.name) || attempt === config.maxAttempts) {
                    throw normalizedError;
                }
                const delay = Math.min(config.initialDelayMs * Math.pow(config.backoffMultiplier, attempt - 1), config.maxDelayMs);
                const jitter = config.jitter ? Math.random() * delay * 0.1 : 0;
                await AsyncUtils.delay(delay + jitter);
            }
        }
        throw lastError ?? new Error('Operation failed after retry attempts');
    }
};
