UNPKG

@elhamdev/tracejs

Version:

A modern, privacy-conscious alternative to browser fingerprinting for unique user identification.

79 lines (78 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.saveToCache = saveToCache; exports.getFromCache = getFromCache; exports.generateCacheKey = generateCacheKey; const environment_1 = require("./environment"); /** * Utilities for caching fingerprint data to maintain consistency */ // Default cache validity period of 30 days const DEFAULT_CACHE_VALIDITY = 30 * 24 * 60 * 60 * 1000; const getStorage = () => { return (0, environment_1.getLocalStorage)(); }; /** * Save data to localStorage with the given key and expiration * Note: validityPeriod parameter isn't needed here since it's only used when retrieving */ function saveToCache(key, data) { const storage = getStorage(); if (!storage) { return; } try { const cacheItem = { data, timestamp: Date.now(), }; storage.setItem(key, JSON.stringify(cacheItem)); } catch (error) { console.error(`Failed to save data to cache (${key}):`, error); } } /** * Retrieve data from localStorage if it exists and is still valid * @returns The cached data if valid, null otherwise */ function getFromCache(key, validityPeriod = DEFAULT_CACHE_VALIDITY) { const storage = getStorage(); if (!storage) { return null; } try { const cachedItem = storage.getItem(key); if (!cachedItem) return null; const { data, timestamp } = JSON.parse(cachedItem); const now = Date.now(); // Check if the cache is still valid if (now - timestamp < validityPeriod) { return data; } // Cache expired, remove it storage.removeItem(key); return null; } catch (error) { console.error(`Failed to retrieve data from cache (${key}):`, error); return null; } } /** * Generate a consistent key for storing fingerprint data * This ensures fingerprints for the same origin remain stable */ function generateCacheKey(prefix) { const win = (0, environment_1.getGlobalWindow)(); const origin = win?.location?.origin ?? "global"; // Create a simple hash of the origin to avoid potential storage issues // with special characters or long origins let hash = 0; for (let i = 0; i < origin.length; i++) { hash = (hash << 5) - hash + origin.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return `tracejs_${prefix}_${hash}`; }