UNPKG

@mate-academy/sourcebuster

Version:

Get sources of your site's visitors (utm / organic / referral / typein).

109 lines (89 loc) 2.5 kB
const SECOND = 1000; const MINUTE = 60 * SECOND; const HOUR = 60 * MINUTE; const DAY = 24 * HOUR; let cookieStore = {}; function parseCookieString(cookieString) { const parts = cookieString.split(';').map(p => p.trim()); const [nameValue, ...attributes] = parts; const eqIndex = nameValue.indexOf('='); const name = nameValue.substring(0, eqIndex).trim(); const value = nameValue.substring(eqIndex + 1); const cookie = { value, expires: null, domain: null, path: null }; for (const attr of attributes) { const [key, val] = attr.split('=').map(s => s.trim()); const keyLower = key.toLowerCase(); if (keyLower === 'expires') { cookie.expires = new Date(val); } else if (keyLower === 'domain') { cookie.domain = val; } else if (keyLower === 'path') { cookie.path = val; } } return { name, cookie }; } Object.defineProperty(document, 'cookie', { get: () => { return Object.entries(cookieStore) .map(([key, data]) => `${key}=${data.value}`) .join('; '); }, set: (cookieString) => { const { name, cookie } = parseCookieString(cookieString); if (cookieString.includes('expires=Thu, 01 Jan 1970')) { delete cookieStore[name]; } else { cookieStore[name] = cookie; } }, configurable: true, }); global.clearCookies = () => { cookieStore = {}; }; global.setCookie = (name, value, expires = null) => { cookieStore[name] = { value, expires, domain: null, path: null }; }; global.getCookie = (name) => { return cookieStore[name]?.value; }; global.getCookieExpires = (name) => { return cookieStore[name]?.expires; }; global.getCookieLifetimeDays = (name) => { const expires = cookieStore[name]?.expires; if (!expires) { return null; } return Math.round((expires.getTime() - Date.now()) / DAY); }; global.setLocation = (url) => { const urlObj = new URL(url); Object.defineProperty(window, 'location', { value: { href: urlObj.href, search: urlObj.search, hostname: urlObj.hostname, pathname: urlObj.pathname, protocol: urlObj.protocol, origin: urlObj.origin, host: urlObj.host, }, writable: true, configurable: true, }); }; global.setReferrer = (referrer) => { Object.defineProperty(document, 'referrer', { value: referrer, writable: true, configurable: true, }); }; beforeEach(() => { clearCookies(); setLocation('https://example.com/'); setReferrer(''); jest.resetModules(); });