Skip to content

Commit ad3336c

Browse files
1 parent f9f0cda commit ad3336c

File tree

1 file changed

+60
-116
lines changed

1 file changed

+60
-116
lines changed

scripts/aem.js

+60-116
Original file line numberDiff line numberDiff line change
@@ -11,120 +11,83 @@
1111
*/
1212

1313
/* eslint-env browser */
14-
15-
/**
16-
* log RUM if part of the sample.
17-
* @param {string} checkpoint identifies the checkpoint in funnel
18-
* @param {Object} data additional data for RUM sample
19-
* @param {string} data.source DOM node that is the source of a checkpoint event,
20-
* identified by #id or .classname
21-
* @param {string} data.target subject of the checkpoint event,
22-
* for instance the href of a link, or a search term
23-
*/
24-
function sampleRUM(checkpoint, data = {}) {
25-
sampleRUM.baseURL = sampleRUM.baseURL
26-
|| new URL(window.RUM_BASE == null ? 'https://rum.hlx.page' : window.RUM_BASE, window.location);
27-
sampleRUM.defer = sampleRUM.defer || [];
28-
const defer = (fnname) => {
29-
sampleRUM[fnname] = sampleRUM[fnname] || ((...args) => sampleRUM.defer.push({ fnname, args }));
30-
};
31-
sampleRUM.drain = sampleRUM.drain
32-
|| ((dfnname, fn) => {
33-
sampleRUM[dfnname] = fn;
34-
sampleRUM.defer
35-
.filter(({ fnname }) => dfnname === fnname)
36-
.forEach(({ fnname, args }) => sampleRUM[fnname](...args));
37-
});
38-
sampleRUM.always = sampleRUM.always || [];
39-
sampleRUM.always.on = (chkpnt, fn) => {
40-
sampleRUM.always[chkpnt] = fn;
41-
};
42-
sampleRUM.on = (chkpnt, fn) => {
43-
sampleRUM.cases[chkpnt] = fn;
44-
};
45-
defer('observe');
46-
defer('cwv');
14+
function sampleRUM(checkpoint, data) {
15+
// eslint-disable-next-line max-len
16+
const timeShift = () => (window.performance ? window.performance.now() : Date.now() - window.hlx.rum.firstReadTime);
4717
try {
4818
window.hlx = window.hlx || {};
19+
sampleRUM.enhance = () => {};
4920
if (!window.hlx.rum) {
50-
const usp = new URLSearchParams(window.location.search);
51-
const weight = usp.get('rum') === 'on' ? 1 : 100; // with parameter, weight is 1. Defaults to 100.
21+
const weight = new URLSearchParams(window.location.search).get('rum') === 'on' ? 1 : 100;
5222
const id = Math.random().toString(36).slice(-4);
53-
const random = Math.random();
54-
const isSelected = random * weight < 1;
55-
const firstReadTime = window.performance ? window.performance.timeOrigin : Date.now();
56-
const urlSanitizers = {
57-
full: () => window.location.href,
58-
origin: () => window.location.origin,
59-
path: () => window.location.href.replace(/\?.*$/, ''),
60-
};
23+
const isSelected = Math.random() * weight < 1;
6124
// eslint-disable-next-line object-curly-newline, max-len
6225
window.hlx.rum = {
6326
weight,
6427
id,
65-
random,
6628
isSelected,
67-
firstReadTime,
29+
firstReadTime: window.performance ? window.performance.timeOrigin : Date.now(),
6830
sampleRUM,
69-
sanitizeURL: urlSanitizers[window.hlx.RUM_MASK_URL || 'path'],
70-
};
71-
}
72-
73-
const { weight, id, firstReadTime } = window.hlx.rum;
74-
if (window.hlx && window.hlx.rum && window.hlx.rum.isSelected) {
75-
const knownProperties = [
76-
'weight',
77-
'id',
78-
'referer',
79-
'checkpoint',
80-
't',
81-
'source',
82-
'target',
83-
'cwv',
84-
'CLS',
85-
'FID',
86-
'LCP',
87-
'INP',
88-
'TTFB',
89-
];
90-
const sendPing = (pdata = data) => {
91-
// eslint-disable-next-line max-len
92-
const t = Math.round(
93-
window.performance ? window.performance.now() : Date.now() - firstReadTime,
94-
);
95-
// eslint-disable-next-line object-curly-newline, max-len, no-use-before-define
96-
const body = JSON.stringify(
97-
{
98-
weight, id, referer: window.hlx.rum.sanitizeURL(), checkpoint, t, ...data,
99-
},
100-
knownProperties,
101-
);
102-
const url = new URL(`.rum/${weight}`, sampleRUM.baseURL).href;
103-
navigator.sendBeacon(url, body);
104-
// eslint-disable-next-line no-console
105-
console.debug(`ping:${checkpoint}`, pdata);
31+
queue: [],
32+
collector: (...args) => window.hlx.rum.queue.push(args),
10633
};
107-
sampleRUM.cases = sampleRUM.cases || {
108-
cwv: () => sampleRUM.cwv(data) || true,
109-
lazy: () => {
110-
// use classic script to avoid CORS issues
34+
if (isSelected) {
35+
['error', 'unhandledrejection'].forEach((event) => {
36+
window.addEventListener(event, ({ reason, error }) => {
37+
const errData = { source: 'undefined error' };
38+
try {
39+
errData.target = (reason || error).toString();
40+
errData.source = (reason || error).stack
41+
.split('\n')
42+
.filter((line) => line.match(/https?:\/\//))
43+
.shift()
44+
.replace(/at ([^ ]+) \((.+)\)/, '$1@$2')
45+
.trim();
46+
} catch (err) {
47+
/* error structure was not as expected */
48+
}
49+
sampleRUM('error', errData);
50+
});
51+
});
52+
sampleRUM.baseURL = sampleRUM.baseURL || new URL(window.RUM_BASE || '/', new URL('https://rum.hlx.page'));
53+
sampleRUM.collectBaseURL = sampleRUM.collectBaseURL || sampleRUM.baseURL;
54+
sampleRUM.sendPing = (ck, time, pingData = {}) => {
55+
// eslint-disable-next-line max-len, object-curly-newline
56+
const rumData = JSON.stringify({
57+
weight,
58+
id,
59+
referer: window.location.href,
60+
checkpoint: ck,
61+
t: time,
62+
...pingData,
63+
});
64+
const { href: url, origin } = new URL(`.rum/${weight}`, sampleRUM.collectBaseURL);
65+
const body = origin === window.location.origin
66+
? new Blob([rumData], { type: 'application/json' })
67+
: rumData;
68+
navigator.sendBeacon(url, body);
69+
// eslint-disable-next-line no-console
70+
console.debug(`ping:${ck}`, pingData);
71+
};
72+
sampleRUM.sendPing('top', timeShift());
73+
74+
sampleRUM.enhance = () => {
11175
const script = document.createElement('script');
11276
script.src = new URL(
113-
'.rum/@adobe/helix-rum-enhancer@^1/src/index.js',
77+
'.rum/@adobe/helix-rum-enhancer@^2/src/index.js',
11478
sampleRUM.baseURL,
11579
).href;
11680
document.head.appendChild(script);
117-
return true;
118-
},
119-
};
120-
sendPing(data);
121-
if (sampleRUM.cases[checkpoint]) {
122-
sampleRUM.cases[checkpoint]();
81+
};
82+
if (!window.hlx.RUM_MANUAL_ENHANCE) {
83+
sampleRUM.enhance();
84+
}
12385
}
12486
}
125-
if (sampleRUM.always[checkpoint]) {
126-
sampleRUM.always[checkpoint](data);
87+
if (window.hlx.rum && window.hlx.rum.isSelected && checkpoint) {
88+
window.hlx.rum.collector(checkpoint, data, timeShift());
12789
}
90+
document.dispatchEvent(new CustomEvent('rum', { detail: { checkpoint, data } }));
12891
} catch (error) {
12992
// something went wrong
13093
}
@@ -136,6 +99,7 @@ function sampleRUM(checkpoint, data = {}) {
13699
function setup() {
137100
window.hlx = window.hlx || {};
138101
window.hlx.RUM_MASK_URL = 'full';
102+
window.hlx.RUM_MANUAL_ENHANCE = true;
139103
window.hlx.codeBasePath = '';
140104
window.hlx.lighthouse = new URLSearchParams(window.location.search).get('lighthouse') === 'on';
141105

@@ -156,27 +120,7 @@ function setup() {
156120

157121
function init() {
158122
setup();
159-
sampleRUM('top');
160-
161-
window.addEventListener('load', () => sampleRUM('load'));
162-
163-
['error', 'unhandledrejection'].forEach((event) => {
164-
window.addEventListener(event, ({ reason, error }) => {
165-
const errData = { source: 'undefined error' };
166-
try {
167-
errData.target = (reason || error).toString();
168-
errData.source = (reason || error).stack
169-
.split('\n')
170-
.filter((line) => line.match(/https?:\/\//))
171-
.shift()
172-
.replace(/at ([^ ]+) \((.+)\)/, '$1@$2')
173-
.trim();
174-
} catch (err) {
175-
/* error structure was not as expected */
176-
}
177-
sampleRUM('error', errData);
178-
});
179-
});
123+
sampleRUM();
180124
}
181125

182126
/**

0 commit comments

Comments
 (0)