This repository was archived by the owner on May 26, 2026. It is now read-only.
forked from snowplow/snowplow-javascript-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
executable file
·554 lines (503 loc) · 16.1 KB
/
Copy pathhelpers.ts
File metadata and controls
executable file
·554 lines (503 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/*
* Copyright (c) 2021 Snowplow Analytics Ltd, 2010 Anthon Pang
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare global {
interface EventTarget {
attachEvent?: (type: string, fn: EventListenerOrEventListenerObject) => void;
}
}
/**
* The criteria which will be used to filter results to specific classes or elements
*/
export interface FilterCriterion<T> {
/** A collection of class names to include */
allowlist?: string[];
/** A collector of class names to exclude */
denylist?: string[];
/** A callback which returns a boolean as to whether the element should be included */
filter?: (elt: T) => boolean;
}
/**
* Checks if an object is a string
* @param str - The object to check
*/
export function isString(str: Object): str is string {
if (str && typeof str.valueOf() === 'string') {
return true;
}
return false;
}
/**
* Checks if an object is an integer
* @param int - The object to check
*/
export function isInteger(int: Object): int is number {
return (
(Number.isInteger && Number.isInteger(int)) || (typeof int === 'number' && isFinite(int) && Math.floor(int) === int)
);
}
/**
* Checks if the input parameter is a function
* @param func - The object to check
*/
export function isFunction(func: unknown) {
if (func && typeof func === 'function') {
return true;
}
return false;
}
/**
* Cleans up the page title
*/
export function fixupTitle(title: string | { text: string }) {
if (!isString(title)) {
title = title.text || '';
var tmp = document.getElementsByTagName('title');
if (tmp && tmp[0] != null) {
title = tmp[0].text;
}
}
return title;
}
/**
* Extract hostname from URL
*/
export function getHostName(url: string) {
// scheme : // [username [: password] @] hostname [: port] [/ [path] [? query] [# fragment]]
var e = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)'),
matches = e.exec(url);
return matches ? matches[1] : url;
}
/**
* Fix-up domain
*/
export function fixupDomain(domain: string) {
var dl = domain.length;
// remove trailing '.'
if (domain.charAt(--dl) === '.') {
domain = domain.slice(0, dl);
}
// remove leading '*'
if (domain.slice(0, 2) === '*.') {
domain = domain.slice(1);
}
return domain;
}
/**
* Get page referrer. In the case of a single-page app,
* if the URL changes without the page reloading, pass
* in the old URL. It will be returned unless overriden
* by a "refer(r)er" parameter in the querystring.
*
* @param string - oldLocation Optional.
* @return string The referrer
*/
export function getReferrer(oldLocation?: string) {
let windowAlias = window,
referrer = '',
fromQs =
fromQuerystring('referrer', windowAlias.location.href) || fromQuerystring('referer', windowAlias.location.href);
// Short-circuit
if (fromQs) {
return fromQs;
}
// In the case of a single-page app, return the old URL
if (oldLocation) {
return oldLocation;
}
try {
referrer = windowAlias.top.document.referrer;
} catch (e) {
if (windowAlias.parent) {
try {
referrer = windowAlias.parent.document.referrer;
} catch (e2) {
referrer = '';
}
}
}
if (referrer === '') {
referrer = document.referrer;
}
return referrer;
}
/**
* Cross-browser helper function to add event handler
*/
export function addEventListener(
element: HTMLElement | EventTarget,
eventType: string,
eventHandler: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions
) {
if (element.addEventListener) {
element.addEventListener(eventType, eventHandler, options);
return true;
}
// IE Support
if (element.attachEvent) {
return element.attachEvent('on' + eventType, eventHandler);
}
(element as any)['on' + eventType] = eventHandler;
}
/**
* Return value from name-value pair in querystring
*/
export function fromQuerystring(field: string, url: string) {
var match = new RegExp('^[^#]*[?&]' + field + '=([^&#]*)').exec(url);
if (!match) {
return null;
}
return decodeURIComponent(match[1].replace(/\+/g, ' '));
}
/**
* Add a name-value pair to the querystring of a URL
*
* @param string - url URL to decorate
* @param string - name Name of the querystring pair
* @param string - value Value of the querystring pair
*/
export function decorateQuerystring(url: string, name: string, value: string) {
var initialQsParams = name + '=' + value;
var hashSplit = url.split('#');
var qsSplit = hashSplit[0].split('?');
var beforeQuerystring = qsSplit.shift();
// Necessary because a querystring may contain multiple question marks
var querystring = qsSplit.join('?');
if (!querystring) {
querystring = initialQsParams;
} else {
// Whether this is the first time the link has been decorated
var initialDecoration = true;
var qsFields = querystring.split('&');
for (var i = 0; i < qsFields.length; i++) {
if (qsFields[i].substr(0, name.length + 1) === name + '=') {
initialDecoration = false;
qsFields[i] = initialQsParams;
querystring = qsFields.join('&');
break;
}
}
if (initialDecoration) {
querystring = initialQsParams + '&' + querystring;
}
}
hashSplit[0] = beforeQuerystring + '?' + querystring;
return hashSplit.join('#');
}
/**
* Attempt to get a value from localStorage
*
* @param string - key
* @return string The value obtained from localStorage, or
* undefined if localStorage is inaccessible
*/
export function attemptGetLocalStorage(key: string) {
try {
const localStorageAlias = window.localStorage,
exp = localStorageAlias.getItem(key + '.expires');
if (exp === null || +exp > Date.now()) {
return localStorageAlias.getItem(key);
} else {
localStorageAlias.removeItem(key);
localStorageAlias.removeItem(key + '.expires');
}
return undefined;
} catch (e) {
return undefined;
}
}
/**
* Attempt to write a value to localStorage
*
* @param string - key
* @param string - value
* @param number - ttl Time to live in seconds, defaults to 2 years from Date.now()
* @return boolean Whether the operation succeeded
*/
export function attemptWriteLocalStorage(key: string, value: string, ttl = 63072000) {
try {
const localStorageAlias = window.localStorage,
t = Date.now() + ttl * 1000;
localStorageAlias.setItem(`${key}.expires`, t.toString());
localStorageAlias.setItem(key, value);
return true;
} catch (e) {
return false;
}
}
/**
* Attempt to delete a value from localStorage
*
* @param string - key
* @return boolean Whether the operation succeeded
*/
export function attemptDeleteLocalStorage(key: string) {
try {
const localStorageAlias = window.localStorage;
localStorageAlias.removeItem(key);
localStorageAlias.removeItem(key + '.expires');
return true;
} catch (e) {
return false;
}
}
/**
* Attempt to get a value from sessionStorage
*
* @param string - key
* @return string The value obtained from sessionStorage, or
* undefined if sessionStorage is inaccessible
*/
export function attemptGetSessionStorage(key: string) {
try {
return window.sessionStorage.getItem(key);
} catch (e) {
return undefined;
}
}
/**
* Attempt to write a value to sessionStorage
*
* @param string - key
* @param string - value
* @return boolean Whether the operation succeeded
*/
export function attemptWriteSessionStorage(key: string, value: string) {
try {
window.sessionStorage.setItem(key, value);
return true;
} catch (e) {
return false;
}
}
/**
* Finds the root domain
*/
export function findRootDomain(sameSite: string, secure: boolean) {
const windowLocationHostnameAlias = window.location.hostname,
cookiePrefix = '_sp_root_domain_test_',
cookieName = cookiePrefix + new Date().getTime(),
cookieValue = '_test_value_' + new Date().getTime();
var split = windowLocationHostnameAlias.split('.');
var position = split.length - 1;
while (position >= 0) {
var currentDomain = split.slice(position, split.length).join('.');
cookie(cookieName, cookieValue, 0, '/', currentDomain, sameSite, secure);
if (cookie(cookieName) === cookieValue) {
// Clean up created cookie(s)
deleteCookie(cookieName, currentDomain, sameSite, secure);
var cookieNames = getCookiesWithPrefix(cookiePrefix);
for (var i = 0; i < cookieNames.length; i++) {
deleteCookie(cookieNames[i], currentDomain, sameSite, secure);
}
return currentDomain;
}
position -= 1;
}
// Cookies cannot be read
return windowLocationHostnameAlias;
}
/**
* Checks whether a value is present within an array
*
* @param val - The value to check for
* @param array - The array to check within
* @return boolean Whether it exists
*/
export function isValueInArray<T>(val: T, array: T[]) {
for (var i = 0; i < array.length; i++) {
if (array[i] === val) {
return true;
}
}
return false;
}
/**
* Deletes an arbitrary cookie by setting the expiration date to the past
*
* @param cookieName - The name of the cookie to delete
* @param domainName - The domain the cookie is in
*/
export function deleteCookie(cookieName: string, domainName?: string, sameSite?: string, secure?: boolean) {
cookie(cookieName, '', -1, '/', domainName, sameSite, secure);
}
/**
* Fetches the name of all cookies beginning with a certain prefix
*
* @param cookiePrefix - The prefix to check for
* @return array The cookies that begin with the prefix
*/
export function getCookiesWithPrefix(cookiePrefix: string) {
var cookies = document.cookie.split('; ');
var cookieNames = [];
for (var i = 0; i < cookies.length; i++) {
if (cookies[i].substring(0, cookiePrefix.length) === cookiePrefix) {
cookieNames.push(cookies[i]);
}
}
return cookieNames;
}
/**
* Get and set the cookies associated with the current document in browser
* This implementation always returns a string, returns the cookie value if only name is specified
*
* @param name - The cookie name (required)
* @param value - The cookie value
* @param ttl - The cookie Time To Live (seconds)
* @param path - The cookies path
* @param domain - The cookies domain
* @param samesite - The cookies samesite attribute
* @param secure - Boolean to specify if cookie should be secure
* @return string The cookies value
*/
export function cookie(
name: string,
value?: string,
ttl?: number,
path?: string,
domain?: string,
samesite?: string,
secure?: boolean
) {
if (arguments.length > 1) {
return (document.cookie =
name +
'=' +
encodeURIComponent(value ?? '') +
(ttl ? '; Expires=' + new Date(+new Date() + ttl * 1000).toUTCString() : '') +
(path ? '; Path=' + path : '') +
(domain ? '; Domain=' + domain : '') +
(samesite ? '; SameSite=' + samesite : '') +
(secure ? '; Secure' : ''));
}
return decodeURIComponent((('; ' + document.cookie).split('; ' + name + '=')[1] || '').split(';')[0]);
}
/**
* Parses an object and returns either the
* integer or undefined.
*
* @param obj - The object to parse
* @return the result of the parse operation
*/
export function parseAndValidateInt(obj: unknown) {
var result = parseInt(obj as string);
return isNaN(result) ? undefined : result;
}
/**
* Parses an object and returns either the
* number or undefined.
*
* @param obj - The object to parse
* @return the result of the parse operation
*/
export function parseAndValidateFloat(obj: unknown) {
var result = parseFloat(obj as string);
return isNaN(result) ? undefined : result;
}
/**
* Convert a criterion object to a filter function
*
* @param object - criterion Either {allowlist: [array of allowable strings]}
* or {denylist: [array of allowable strings]}
* or {filter: function (elt) {return whether to track the element}
* @param boolean - byClass Whether to allowlist/denylist based on an element's classes (for forms)
* or name attribute (for fields)
*/
export function getFilterByClass(criterion?: FilterCriterion<HTMLElement> | null): (elt: HTMLElement) => boolean {
// If the criterion argument is not an object, add listeners to all elements
if (criterion == null || typeof criterion !== 'object' || Array.isArray(criterion)) {
return function () {
return true;
};
}
const inclusive = Object.prototype.hasOwnProperty.call(criterion, 'allowlist');
const specifiedClassesSet = getSpecifiedClassesSet(criterion);
return getFilter(criterion, function (elt: HTMLElement) {
return checkClass(elt, specifiedClassesSet) === inclusive;
});
}
/**
* Convert a criterion object to a filter function
*
* @param object - criterion Either {allowlist: [array of allowable strings]}
* or {denylist: [array of allowable strings]}
* or {filter: function (elt) {return whether to track the element}
*/
export function getFilterByName<T extends { name: string }>(criterion?: FilterCriterion<T>): (elt: T) => boolean {
// If the criterion argument is not an object, add listeners to all elements
if (criterion == null || typeof criterion !== 'object' || Array.isArray(criterion)) {
return function () {
return true;
};
}
const inclusive = criterion.hasOwnProperty('allowlist');
const specifiedClassesSet = getSpecifiedClassesSet(criterion);
return getFilter(criterion, function (elt: T) {
return elt.name in specifiedClassesSet === inclusive;
});
}
/**
* List the classes of a DOM element without using elt.classList (for compatibility with IE 9)
*/
export function getCssClasses(elt: Element) {
return elt.className.match(/\S+/g) || [];
}
/**
* Check whether an element has at least one class from a given list
*/
function checkClass(elt: Element, classList: Record<string, boolean>) {
var classes = getCssClasses(elt);
for (const className of classes) {
if (classList[className]) {
return true;
}
}
return false;
}
function getFilter<T>(criterion: FilterCriterion<T>, fallbackFilter: (elt: T) => boolean) {
if (criterion.hasOwnProperty('filter') && criterion.filter) {
return criterion.filter;
}
return fallbackFilter;
}
function getSpecifiedClassesSet<T>(criterion: FilterCriterion<T>) {
// Convert the array of classes to an object of the form {class1: true, class2: true, ...}
var specifiedClassesSet: Record<string, boolean> = {};
var specifiedClasses = criterion.allowlist || criterion.denylist;
if (specifiedClasses) {
if (!Array.isArray(specifiedClasses)) {
specifiedClasses = [specifiedClasses];
}
for (var i = 0; i < specifiedClasses.length; i++) {
specifiedClassesSet[specifiedClasses[i]] = true;
}
}
return specifiedClassesSet;
}