Skip to content

Commit

Permalink
wp
Browse files Browse the repository at this point in the history
  • Loading branch information
mokimo committed Oct 16, 2024
1 parent ec48f3c commit a205756
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 101 deletions.
149 changes: 64 additions & 85 deletions libs/utils/samplerum.js
Original file line number Diff line number Diff line change
@@ -1,101 +1,80 @@
/* eslint-disable import/prefer-default-export */
// code from https://github.com/adobe/helix-rum-js/blob/main/src/index.js
export function sampleRUM(checkpoint, data = {}) {
const SESSION_STORAGE_KEY = 'aem-rum';
sampleRUM.baseURL = sampleRUM.baseURL || new URL(window.RUM_BASE == null ? 'https://rum.hlx.page' : window.RUM_BASE, window.location);
sampleRUM.defer = sampleRUM.defer || [];
const defer = (fnname) => {
sampleRUM[fnname] = sampleRUM[fnname]
|| ((...args) => sampleRUM.defer.push({ fnname, args }));
};
/* c8 ignore start */
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;
};
/* c8 ignore stop */
defer('observe');
defer('cwv');
export 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 param = new URLSearchParams(window.location.search).get('rum');
const weight = (window.SAMPLE_PAGEVIEWS_AT_RATE === 'high' && 10)
|| (window.SAMPLE_PAGEVIEWS_AT_RATE === 'low' && 1000)
|| (new URLSearchParams(window.location.search).get('rum') === 'on' && 1)
|| 100;
|| (window.SAMPLE_PAGEVIEWS_AT_RATE === 'low' && 1000)
|| (param === 'on' && 1)
|| 100;
const id = Math.random().toString(36).slice(-4);
const isSelected = (Math.random() * weight < 1);
const firstReadTime = Date.now();
const urlSanitizers = {
full: () => window.location.href,
origin: () => window.location.origin,
path: () => window.location.href.replace(/\?.*$/, ''),
};
// eslint-disable-next-line max-len
const rumSessionStorage = sessionStorage.getItem(SESSION_STORAGE_KEY) ? JSON.parse(sessionStorage.getItem(SESSION_STORAGE_KEY)) : {};
rumSessionStorage.pages = rumSessionStorage.pages ? rumSessionStorage.pages + 1 : 1;
sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(rumSessionStorage));
const isSelected = true;
// eslint-disable-next-line object-curly-newline, max-len
window.hlx.rum = { weight, id, isSelected, firstReadTime, sampleRUM, sanitizeURL: urlSanitizers[window.hlx.RUM_MASK_URL || 'path'], rumSessionStorage };
}
window.hlx.rum = { weight, id, isSelected, firstReadTime: window.performance ? window.performance.timeOrigin : Date.now(), sampleRUM, queue: [], collector: (...args) => window.hlx.rum.queue.push(args) };
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);
});

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', 'TTFB'];
const sendPing = (pdata = data) => {
// eslint-disable-next-line object-curly-newline, max-len, no-use-before-define
const body = JSON.stringify({ weight, id, referer: window.hlx.rum.sanitizeURL(), checkpoint, t: (Date.now() - firstReadTime), ...data }, knownProperties);
const url = new URL(`.rum/${weight}`, sampleRUM.baseURL).href;
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${checkpoint}`, pdata);
};
sampleRUM.cases = sampleRUM.cases || {
load: () => sampleRUM('pagesviewed', { source: window.hlx.rum.rumSessionStorage.pages }) || true,
cwv: () => sampleRUM.cwv(data) || true,
/* c8 ignore next 7 */
lazy: () => {
// use classic script to avoid CORS issues
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.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 = () => {
const script = document.createElement('script');
script.src = new URL('.rum/@adobe/helix-rum-enhancer@^1/src/index.js', sampleRUM.baseURL).href;
script.src = new URL('.rum/@adobe/helix-rum-enhancer@^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
}
}

/* c8 ignore start */
export function addRumListeners() {
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 });
});
}
/* c8 ignore stop */

sampleRUM('top');
8 changes: 3 additions & 5 deletions libs/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,8 @@ export async function loadBlock(block) {
return null;
}
const { name, blockPath, hasStyles } = getBlockData(block);
block.dataset.blockName = name;
block.classList.add('block');
const styleLoaded = hasStyles && new Promise((resolve) => {
loadStyle(`${blockPath}.css`, resolve);
});
Expand Down Expand Up @@ -1119,8 +1121,6 @@ export async function loadDeferred(area, blocks, config) {

import('./samplerum.js').then(({ sampleRUM }) => {
sampleRUM('lazy');
sampleRUM.observe(blocks);
sampleRUM.observe(area.querySelectorAll('picture > img'));
});

if (getMetadata('pageperf') === 'on') {
Expand Down Expand Up @@ -1180,9 +1180,7 @@ function decorateDocumentExtras() {
decorateMeta();
decorateHeader();

import('./samplerum.js').then(({ addRumListeners }) => {
addRumListeners();
});
import('./samplerum.js');
}

async function documentPostSectionLoading(config) {
Expand Down
1 change: 1 addition & 0 deletions nala/libs/webutil.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export default class WebUtil {
let result = true;
await Promise.allSettled(
Object.entries(cssProps).map(async ([property, expectedValue]) => {
if (property === 'block') return;
try {
await expect(this.locator).toHaveCSS(property, expectedValue);
} catch (error) {
Expand Down
23 changes: 12 additions & 11 deletions test/utils/samplerum.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,29 @@

import { expect } from '@esm-bundle/chai';
import sinon from 'sinon';
import { sampleRUM } from '../../libs/utils/samplerum.js';

describe('SampleRUM', () => {
it('Collects RUM data', () => {
const sendBeacon = sinon.stub(navigator, 'sendBeacon');
// turn on RUM
window.history.pushState({}, '', `${window.location.href}&rum=on`);
delete window.hlx;
it('Collects RUM data', async () => {
const { fetch } = window;
window.fetch = () => Promise.resolve({ json: () => Promise.resolve({}) });
const { sampleRUM } = await import('../../libs/utils/samplerum.js');
window.hlx.rum.collector = sinon.stub();
window.hlx.rum.isSelected = true;

// sends checkpoint beacon
sampleRUM('test', { foo: 'bar' });
expect(sendBeacon.called).to.be.true;
sendBeacon.resetHistory();
// check the call count
expect(window.hlx.rum.collector.callCount).to.equal(1);

// sends cwv beacon
sampleRUM('cwv', { foo: 'bar' });
expect(sendBeacon.called).to.be.true;
expect(window.hlx.rum.collector.callCount).to.equal(2);

// test error handling
sendBeacon.throws();
sampleRUM('error', { foo: 'bar' });
expect(window.hlx.rum.collector.callCount).to.equal(3);

sendBeacon.restore();
window.fetch = fetch;
document.head.innerHTML = '';
});
});
4 changes: 4 additions & 0 deletions web-test-runner.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export default {
<head>
<link rel="icon" href="/libs/img/favicons/favicon.ico" size="any">
<script type='module'>
window.hlx = {
rum: {}
}
console.log(window.hlx)
const oldFetch = window.fetch;
window.fetch = async (resource, options) => {
if (!resource.startsWith('/') && !resource.startsWith('http://localhost')) {
Expand Down

0 comments on commit a205756

Please sign in to comment.