Skip to content

Commit

Permalink
added sampleRUM task
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelecalamita committed Apr 23, 2024
1 parent ca9373c commit 3c53554
Show file tree
Hide file tree
Showing 10 changed files with 192 additions and 12 deletions.
2 changes: 1 addition & 1 deletion dist/__chunks__/fetch.service.C1Ie3Sjw.js.map

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions dist/main/main.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/main/main.js.map

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import setupHlxObj from './tasks/setupHlxObj';
import { decorateTemplateAndTheme } from './tasks/decorateTemplateAndTheme';
import { decorateButtons } from './tasks/decorateButtons';
import { setDocLanguage } from './tasks/setDocLanguage';
import { waitForLCP } from './tasks/waitForLCP';
import { loadFonts } from './tasks/loadFonts';
import { initSampleRUM } from './tasks/initSampleRUM';

class HLX {
private beforeEagerCallbacks: Array<() => Promise<void>> = [];
Expand Down Expand Up @@ -111,7 +111,7 @@ class HLX {

private async beforeLoadEager(): Promise<void> {
const beforeLoadEagerTask: Promise<void> = new Promise((resolve) => {
setupHlxObj();
initSampleRUM();
decorateTemplateAndTheme();
setDocLanguage();
resolve();
Expand Down
17 changes: 17 additions & 0 deletions src/app/tasks/initSampleRUM.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { sampleRUM } from './sampleRUM';
import setupHlxObj from './setupHlxObj';

export function initSampleRUM() {
setupHlxObj();
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 });
});
}
135 changes: 135 additions & 0 deletions src/app/tasks/sampleRUM.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* 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
*/

export function sampleRUM(checkpoint, data = {}) {
// @ts-ignore
sampleRUM.defer = sampleRUM.defer || [];
const defer = (fnname) => {
// @ts-ignore
sampleRUM[fnname] = sampleRUM[fnname] || ((...args) => sampleRUM.defer.push({ fnname, args }));
};
// @ts-ignore
sampleRUM.drain =
// @ts-ignore
sampleRUM.drain ||
((dfnname, fn) => {
sampleRUM[dfnname] = fn;
// @ts-ignore
sampleRUM.defer
.filter(({ fnname }) => dfnname === fnname)
.forEach(({ fnname, args }) => sampleRUM[fnname](...args));
});
// @ts-ignore
sampleRUM.always = sampleRUM.always || [];
// @ts-ignore
sampleRUM.always.on = (chkpnt, fn) => {
// @ts-ignore
sampleRUM.always[chkpnt] = fn;
};
// @ts-ignore
sampleRUM.on = (chkpnt, fn) => {
// @ts-ignore
sampleRUM.cases[chkpnt] = fn;
};
defer('observe');
defer('cwv');
try {
window.hlx = window.hlx || {};
// @ts-ignore
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(/\?.*$/, ''),
};
// @ts-ignore
window.hlx.rum = {
weight,
id,
random,
isSelected,
firstReadTime,
sampleRUM,
sanitizeURL: urlSanitizers[window.hlx.RUM_MASK_URL || 'path'],
};
}
// @ts-ignore
const { weight, id, firstReadTime } = window.hlx.rum;
// @ts-ignore
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) => {
const body = JSON.stringify(
{
weight,
id,
// @ts-ignore
referer: window.hlx.rum.sanitizeURL(),
checkpoint,
t: Date.now() - firstReadTime,
...data,
},
knownProperties
);
const url = `https://rum.hlx.page/.rum/${weight}`;
navigator.sendBeacon(url, body);
// eslint-disable-next-line no-console
console.debug(`ping:${checkpoint}`, pdata);
};
// @ts-ignore
sampleRUM.cases = sampleRUM.cases || {
// @ts-ignore
cwv: () => sampleRUM.cwv(data) || true,
lazy: () => {
// use classic script to avoid CORS issues
const script = document.createElement('script');
script.src = 'https://rum.hlx.page/.rum/@adobe/helix-rum-enhancer@^1/src/index.js';
document.head.appendChild(script);
return true;
},
};
sendPing(data);
// @ts-ignore
if (sampleRUM.cases[checkpoint]) {
// @ts-ignore
sampleRUM.cases[checkpoint]();
}
}
// @ts-ignore
if (sampleRUM.always[checkpoint]) {
// @ts-ignore
sampleRUM.always[checkpoint](data);
}
} catch (error) {
// something went wrong
}
}
10 changes: 9 additions & 1 deletion src/app/utils/getUrlForEndpoint.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
/**
* Get the URL for an endpoint.
* @param endpoint - The endpoint.
* @returns URL
* @example
* const url = getUrlForEndpoint('block1/block1.css');
* console.log(url);
* Output: URL { href: 'http://localhost:3000/block1/block1.css' }
*/
export const getUrlForEndpoint = (endpoint: string): URL => {
// TODO: do we really need to use window.hlx.codeBasePath here?
const baseUrl = new URL(window.hlx.codeBasePath, window.location.origin);
return new URL(endpoint, baseUrl);
};
1 change: 1 addition & 0 deletions types/src/app/tasks/initSampleRUM.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function initSampleRUM(): void;
10 changes: 10 additions & 0 deletions types/src/app/tasks/sampleRUM.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* 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
*/
export declare function sampleRUM(checkpoint: any, data?: {}): void;
9 changes: 9 additions & 0 deletions types/src/app/utils/getUrlForEndpoint.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
/**
* Get the URL for an endpoint.
* @param endpoint - The endpoint.
* @returns URL
* @example
* const url = getUrlForEndpoint('block1/block1.css');
* console.log(url);
* Output: URL { href: 'http://localhost:3000/block1/block1.css' }
*/
export declare const getUrlForEndpoint: (endpoint: string) => URL;

0 comments on commit 3c53554

Please sign in to comment.