'use strict';

var tslib_es6 = require('../../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.js');
var fp_esm = require('../../node_modules/.pnpm/@fingerprintjs_fingerprintjs@4.6.2/node_modules/@fingerprintjs/fingerprintjs/dist/fp.esm.js');
var fingerprintShared = require('./fingerprint-shared.js');

/**
 * Fingerprint Client Utilities
 * 客户端专用的指纹生成和管理逻辑
 * 只能在浏览器环境中使用
 */
/**
 * 检查浏览器存储（localStorage 和 cookie）中的指纹 ID
 * 返回有效的 ID 或 null
 */
function checkStoredFingerprintId() {
    if (typeof window === 'undefined') {
        return null;
    }
    // 优先检查 localStorage
    const localStorageId = localStorage.getItem(fingerprintShared.FINGERPRINT_STORAGE_KEY);
    if (localStorageId && fingerprintShared.isValidFingerprintId(localStorageId)) {
        return localStorageId;
    }
    // 检查 cookie
    const cookieId = getCookieValue(fingerprintShared.FINGERPRINT_COOKIE_NAME);
    if (cookieId && fingerprintShared.isValidFingerprintId(cookieId)) {
        // 同步到 localStorage
        localStorage.setItem(fingerprintShared.FINGERPRINT_STORAGE_KEY, cookieId);
        return cookieId;
    }
    return null;
}
/**
 * 生成基于真实浏览器特征的fingerprint ID
 * 使用 FingerprintJS 收集浏览器特征并生成唯一标识
 */
function generateFingerprintId() {
    return tslib_es6.__awaiter(this, void 0, void 0, function* () {
        if (typeof window === 'undefined') {
            throw new Error('generateFingerprintId can only be used in browser environment');
        }
        // 检查现有 ID
        const existingId = checkStoredFingerprintId();
        if (existingId) {
            console.log('Using existing fingerprint ID:', existingId);
            return existingId;
        }
        try {
            // 使用 FingerprintJS 生成指纹
            const fp = yield fp_esm.default.load();
            const result = yield fp.get();
            const fingerprintId = `fp_${result.visitorId}`;
            // 存储到 localStorage 和 cookie
            localStorage.setItem(fingerprintShared.FINGERPRINT_STORAGE_KEY, fingerprintId);
            setCookie(fingerprintShared.FINGERPRINT_COOKIE_NAME, fingerprintId, 365);
            console.log('Generated new fingerprint ID:', fingerprintId);
            return fingerprintId;
        }
        catch (error) {
            console.warn('Failed to generate fingerprint with FingerprintJS:', error);
            // 降级方案：生成基于时间戳和随机数的 ID
            const fallbackId = `fp_fallback_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
            localStorage.setItem(fingerprintShared.FINGERPRINT_STORAGE_KEY, fallbackId);
            setCookie(fingerprintShared.FINGERPRINT_COOKIE_NAME, fallbackId, 365);
            console.log('Generated fallback fingerprint ID:', fallbackId);
            return fallbackId;
        }
    });
}
/**
 * 获取当前的fingerprint ID
 */
function getFingerprintId() {
    return checkStoredFingerprintId();
}
/**
 * 设置fingerprint ID到存储
 */
function setFingerprintId(fingerprintId) {
    if (typeof window === 'undefined') {
        throw new Error('setFingerprintId can only be used in browser environment');
    }
    if (!fingerprintShared.isValidFingerprintId(fingerprintId)) {
        throw new Error('Invalid fingerprint ID');
    }
    localStorage.setItem(fingerprintShared.FINGERPRINT_STORAGE_KEY, fingerprintId);
    setCookie(fingerprintShared.FINGERPRINT_COOKIE_NAME, fingerprintId, 365);
}
/**
 * 清除fingerprint ID
 */
function clearFingerprintId() {
    if (typeof window === 'undefined') {
        throw new Error('clearFingerprintId can only be used in browser environment');
    }
    localStorage.removeItem(fingerprintShared.FINGERPRINT_STORAGE_KEY);
    deleteCookie(fingerprintShared.FINGERPRINT_COOKIE_NAME);
}
/**
 * 获取或生成fingerprint ID
 * 如果不存在则自动生成新的
 */
function getOrGenerateFingerprintId() {
    return tslib_es6.__awaiter(this, void 0, void 0, function* () {
        const existingId = checkStoredFingerprintId();
        if (existingId) {
            console.log('Retrieved existing fingerprint ID:', existingId);
            return existingId;
        }
        return yield generateFingerprintId();
    });
}
/**
 * 创建包含fingerprint ID的fetch headers
 */
function createFingerprintHeaders() {
    return tslib_es6.__awaiter(this, void 0, void 0, function* () {
        const fingerprintId = yield getOrGenerateFingerprintId();
        return {
            [fingerprintShared.FINGERPRINT_HEADER_NAME]: fingerprintId,
        };
    });
}
/**
 * Hook for generating fingerprint headers
 */
function useFingerprintHeaders() {
    return createFingerprintHeaders;
}
/**
 * Create a fetch wrapper that automatically includes fingerprint headers
 */
function createFingerprintFetch() {
    return (url, init) => tslib_es6.__awaiter(this, void 0, void 0, function* () {
        const fingerprintHeaders = yield createFingerprintHeaders();
        const headers = Object.assign(Object.assign(Object.assign({}, fingerprintHeaders), { [fingerprintShared.FINGERPRINT_SOURCE_REFER]: document.referrer || '' }), ((init === null || init === void 0 ? void 0 : init.headers) || {}));
        return fetch(url, Object.assign(Object.assign({}, init), { headers }));
    });
}
// Cookie 辅助函数 (私有)
function getCookieValue(name) {
    var _a;
    if (typeof document === 'undefined') {
        return null;
    }
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
        return ((_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(';').shift()) || null;
    }
    return null;
}
function setCookie(name, value, days) {
    if (typeof document === 'undefined') {
        return;
    }
    const expires = new Date();
    expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
}
function deleteCookie(name) {
    if (typeof document === 'undefined') {
        return;
    }
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
}

exports.clearFingerprintId = clearFingerprintId;
exports.createFingerprintFetch = createFingerprintFetch;
exports.createFingerprintHeaders = createFingerprintHeaders;
exports.generateFingerprintId = generateFingerprintId;
exports.getFingerprintId = getFingerprintId;
exports.getOrGenerateFingerprintId = getOrGenerateFingerprintId;
exports.setFingerprintId = setFingerprintId;
exports.useFingerprintHeaders = useFingerprintHeaders;
