mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-22 10:21:36 +03:00
c765c3230e
refs TryGhost/Team#1907 - calculates final attribution source and medium using captured referrer information in history - adds new referrer-translator that goes through available history and based to determine most valid referrer info - includes referrer url, source and medium in the attribution data for storage
92 lines
2.0 KiB
JavaScript
92 lines
2.0 KiB
JavaScript
/**
|
|
* @typedef {Object} UrlHistoryItem
|
|
* @prop {string} [path]
|
|
* @prop {string} [id]
|
|
* @prop {string} [type]
|
|
* @prop {string} [refSource]
|
|
* @prop {string} [refMedium]
|
|
* @prop {string} [refUrl]
|
|
* @prop {number} time
|
|
*/
|
|
|
|
/**
|
|
* @typedef {UrlHistoryItem[]} UrlHistoryArray
|
|
*/
|
|
|
|
/**
|
|
* Types allowed to add in the URLHistory manually
|
|
*/
|
|
const ALLOWED_TYPES = ['post'];
|
|
|
|
/**
|
|
* Represents a validated history
|
|
*/
|
|
class UrlHistory {
|
|
/**
|
|
* @private
|
|
* @param {UrlHistoryArray} urlHistory
|
|
*/
|
|
constructor(urlHistory) {
|
|
/** @private */
|
|
this.history = urlHistory;
|
|
}
|
|
|
|
get length() {
|
|
return this.history.length;
|
|
}
|
|
|
|
/**
|
|
* Iterate from latest item to newest item (reversed!)
|
|
*/
|
|
*[Symbol.iterator]() {
|
|
yield* this.history.slice().reverse();
|
|
}
|
|
|
|
/**
|
|
* @private
|
|
* @param {any[]} history
|
|
* @returns {boolean}
|
|
*/
|
|
static isValidHistory(history) {
|
|
for (const item of history) {
|
|
const isValidIdEntry = typeof item?.id === 'string' && typeof item?.type === 'string' && ALLOWED_TYPES.includes(item.type);
|
|
const isValidPathEntry = typeof item?.path === 'string';
|
|
|
|
const isValidEntry = isValidPathEntry || isValidIdEntry;
|
|
|
|
if (!isValidEntry || !Number.isSafeInteger(item?.time)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @param {unknown} urlHistory
|
|
* @returns {UrlHistory}
|
|
*/
|
|
static create(urlHistory) {
|
|
if (!Array.isArray(urlHistory)) {
|
|
return new UrlHistory([]);
|
|
}
|
|
|
|
if (!this.isValidHistory(urlHistory)) {
|
|
return new UrlHistory([]);
|
|
}
|
|
|
|
const now = Date.now();
|
|
const filteredHistory = urlHistory.filter((item) => {
|
|
return now - item.time < this.MAX_AGE;
|
|
});
|
|
|
|
return new UrlHistory(filteredHistory);
|
|
}
|
|
|
|
/**
|
|
* @private
|
|
*/
|
|
static MAX_AGE = 1000 * 60 * 60 * 24;
|
|
}
|
|
|
|
module.exports = UrlHistory;
|