Skip to content

Commit

Permalink
Merge pull request #33 from adobe/rum-v2
Browse files Browse the repository at this point in the history
chore: update to rum v2
  • Loading branch information
shsteimer authored Dec 9, 2024
2 parents 053e0f6 + 7c84687 commit 8466932
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 109 deletions.
202 changes: 96 additions & 106 deletions scripts/aem.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,119 +12,118 @@

/* eslint-env browser */

/**
* log RUM if part of the sample.
* @param {string} checkpoint identifies the checkpoint in funnel
* @param {Object} data additional data for RUM sample
* @param {string} data.source DOM node that is the source of a checkpoint event,
* identified by #id or .classname
* @param {string} data.target subject of the checkpoint event,
* for instance the href of a link, or a search term
*/
function sampleRUM(checkpoint, data = {}) {
sampleRUM.defer = sampleRUM.defer || [];
const defer = (fnname) => {
sampleRUM[fnname] = sampleRUM[fnname] || ((...args) => sampleRUM.defer.push({ fnname, args }));
};
sampleRUM.drain = sampleRUM.drain
|| ((dfnname, fn) => {
sampleRUM[dfnname] = fn;
sampleRUM.defer
.filter(({ fnname }) => dfnname === fnname)
.forEach(({ fnname, args }) => sampleRUM[fnname](...args));
});
sampleRUM.always = sampleRUM.always || [];
sampleRUM.always.on = (chkpnt, fn) => {
sampleRUM.always[chkpnt] = fn;
};
sampleRUM.on = (chkpnt, fn) => {
sampleRUM.cases[chkpnt] = fn;
};
defer('observe');
defer('cwv');
function sampleRUM(checkpoint, data) {
// eslint-disable-next-line max-len
const timeShift = () => (window.performance ? window.performance.now() : Date.now() - window.hlx.rum.firstReadTime);
try {
window.hlx = window.hlx || {};
sampleRUM.enhance = () => {};
if (!window.hlx.rum) {
const usp = new URLSearchParams(window.location.search);
const weight = usp.get('rum') === 'on' ? 1 : 100; // with parameter, weight is 1. Defaults to 100.
const id = Array.from({ length: 75 }, (_, i) => String.fromCharCode(48 + i))
.filter((a) => /\d|[A-Z]/i.test(a))
.filter(() => Math.random() * 75 > 70)
.join('');
const random = Math.random();
const isSelected = random * weight < 1;
const firstReadTime = Date.now();
const urlSanitizers = {
full: () => window.location.href,
origin: () => window.location.origin,
path: () => window.location.href.replace(/\?.*$/, ''),
};
const param = new URLSearchParams(window.location.search).get('rum');
const weight = (window.SAMPLE_PAGEVIEWS_AT_RATE === 'high' && 10)
|| (window.SAMPLE_PAGEVIEWS_AT_RATE === 'low' && 1000)
|| (param === 'on' && 1)
|| 100;
const id = Math.random().toString(36).slice(-4);
const isSelected = param !== 'off' && Math.random() * weight < 1;
// eslint-disable-next-line object-curly-newline, max-len
window.hlx.rum = {
weight,
id,
random,
isSelected,
firstReadTime,
firstReadTime: window.performance ? window.performance.timeOrigin : Date.now(),
sampleRUM,
sanitizeURL: urlSanitizers[window.hlx.RUM_MASK_URL || 'path'],
queue: [],
collector: (...args) => window.hlx.rum.queue.push(args),
};
}
const { weight, id, firstReadTime } = window.hlx.rum;
if (window.hlx && window.hlx.rum && window.hlx.rum.isSelected) {
const knownProperties = [
'weight',
'id',
'referer',
'checkpoint',
't',
'source',
'target',
'cwv',
'CLS',
'FID',
'LCP',
'INP',
];
const sendPing = (pdata = data) => {
// eslint-disable-next-line object-curly-newline, max-len, no-use-before-define
const body = JSON.stringify(
{
if (isSelected) {
const dataFromErrorObj = (error) => {
const errData = { source: 'undefined error' };
try {
errData.target = error.toString();
errData.source = error.stack
.split('\n')
.filter((line) => line.match(/https?:\/\//))
.shift()
.replace(/at ([^ ]+) \((.+)\)/, '$1@$2')
.replace(/ at /, '@')
.trim();
} catch (err) {
/* error structure was not as expected */
}
return errData;
};

window.addEventListener('error', ({ error }) => {
const errData = dataFromErrorObj(error);
sampleRUM('error', errData);
});

window.addEventListener('unhandledrejection', ({ reason }) => {
let errData = {
source: 'Unhandled Rejection',
target: reason || 'Unknown',
};
if (reason instanceof Error) {
errData = dataFromErrorObj(reason);
}
sampleRUM('error', errData);
});

sampleRUM.baseURL = sampleRUM.baseURL || new URL(window.RUM_BASE || '/', new URL('https://rum.hlx.page'));
sampleRUM.collectBaseURL = sampleRUM.collectBaseURL || sampleRUM.baseURL;
sampleRUM.sendPing = (ck, time, pingData = {}) => {
// eslint-disable-next-line max-len, object-curly-newline
const rumData = JSON.stringify({
weight,
id,
referer: window.hlx.rum.sanitizeURL(),
checkpoint,
t: Date.now() - firstReadTime,
...data,
},
knownProperties,
);
const url = `https://rum.hlx.page/.rum/${weight}`;
// eslint-disable-next-line no-unused-expressions
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${checkpoint}`, pdata);
};
sampleRUM.cases = sampleRUM.cases || {
cwv: () => sampleRUM.cwv(data) || true,
lazy: () => {
// use classic script to avoid CORS issues
referer: window.location.href,
checkpoint: ck,
t: time,
...pingData,
});
const urlParams = window.RUM_PARAMS
? `?${new URLSearchParams(window.RUM_PARAMS).toString()}`
: '';
const { href: url, origin } = new URL(
`.rum/${weight}${urlParams}`,
sampleRUM.collectBaseURL,
);
const body = origin === window.location.origin
? new Blob([rumData], { type: 'application/json' })
: rumData;
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${ck}`, pingData);
};
sampleRUM.sendPing('top', timeShift());

sampleRUM.enhance = () => {
// only enhance once
if (document.querySelector('script[src*="rum-enhancer"]')) return;
const { enhancerVersion, enhancerHash } = sampleRUM.enhancerContext || {};
const script = document.createElement('script');
script.src = 'https://rum.hlx.page/.rum/@adobe/helix-rum-enhancer@^1/src/index.js';
if (enhancerHash) {
script.integrity = enhancerHash;
script.setAttribute('crossorigin', 'anonymous');
}
script.src = new URL(
`.rum/@adobe/helix-rum-enhancer@${enhancerVersion || '^2'}/src/index.js`,
sampleRUM.baseURL,
).href;
document.head.appendChild(script);
return true;
},
};
sendPing(data);
if (sampleRUM.cases[checkpoint]) {
sampleRUM.cases[checkpoint]();
};
if (!window.hlx.RUM_MANUAL_ENHANCE) {
sampleRUM.enhance();
}
}
}
if (sampleRUM.always[checkpoint]) {
sampleRUM.always[checkpoint](data);
if (window.hlx.rum && window.hlx.rum.isSelected && checkpoint) {
window.hlx.rum.collector(checkpoint, data, timeShift());
}
document.dispatchEvent(new CustomEvent('rum', { detail: { checkpoint, data } }));
} catch (error) {
// something went wrong
// something went awry
}
}

Expand All @@ -134,6 +133,7 @@ function sampleRUM(checkpoint, data = {}) {
function setup() {
window.hlx = window.hlx || {};
window.hlx.RUM_MASK_URL = 'full';
window.hlx.RUM_MANUAL_ENHANCE = true;
window.hlx.codeBasePath = '';
window.hlx.lighthouse = new URLSearchParams(window.location.search).get('lighthouse') === 'on';

Expand All @@ -154,17 +154,7 @@ function setup() {

function init() {
setup();
sampleRUM('top');

window.addEventListener('load', () => sampleRUM('load'));

window.addEventListener('unhandledrejection', (event) => {
sampleRUM('error', { source: event.reason.sourceURL, target: event.reason.line });
});

window.addEventListener('error', (event) => {
sampleRUM('error', { source: event.filename, target: event.lineno });
});
sampleRUM();
}

/**
Expand Down
4 changes: 1 addition & 3 deletions scripts/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,7 @@ async function loadLazy(doc) {
loadCSS(`${window.hlx.codeBasePath}/styles/lazy-styles.css`);
loadFonts();

sampleRUM('lazy');
sampleRUM.observe(main.querySelectorAll('div[data-block-name]'));
sampleRUM.observe(main.querySelectorAll('picture > img'));
sampleRUM.enhance();
}

/**
Expand Down

0 comments on commit 8466932

Please sign in to comment.