@hitkeep/tracker 2.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +164 -0
- package/dist/core.d.cts +83 -0
- package/dist/core.d.ts +83 -0
- package/dist/index.cjs +669 -0
- package/dist/index.js +646 -0
- package/dist/package.d.cts +65 -0
- package/dist/package.d.ts +65 -0
- package/dist/version.d.cts +1 -0
- package/dist/version.d.ts +1 -0
- package/package.json +67 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,646 @@
|
|
|
1
|
+
// src/tracker/core.ts
|
|
2
|
+
var SESSION_KEY = "hk_session";
|
|
3
|
+
var SESSION_EXPIRY = 30 * 60 * 1e3;
|
|
4
|
+
var MAX_PENDING_REQUESTS = 10;
|
|
5
|
+
var RETRY_DELAY_MS = 2e3;
|
|
6
|
+
var DUPLICATE_PAGEVIEW_WINDOW_MS = 1500;
|
|
7
|
+
var OPT_OUT_KEY = "hk_ignore";
|
|
8
|
+
var DOWNLOAD_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
9
|
+
"7z",
|
|
10
|
+
"avi",
|
|
11
|
+
"csv",
|
|
12
|
+
"doc",
|
|
13
|
+
"docx",
|
|
14
|
+
"epub",
|
|
15
|
+
"gz",
|
|
16
|
+
"ics",
|
|
17
|
+
"jpeg",
|
|
18
|
+
"jpg",
|
|
19
|
+
"json",
|
|
20
|
+
"key",
|
|
21
|
+
"mov",
|
|
22
|
+
"mp3",
|
|
23
|
+
"mp4",
|
|
24
|
+
"pdf",
|
|
25
|
+
"png",
|
|
26
|
+
"ppt",
|
|
27
|
+
"pptx",
|
|
28
|
+
"rar",
|
|
29
|
+
"rtf",
|
|
30
|
+
"svg",
|
|
31
|
+
"tar",
|
|
32
|
+
"tgz",
|
|
33
|
+
"txt",
|
|
34
|
+
"webp",
|
|
35
|
+
"xls",
|
|
36
|
+
"xlsx",
|
|
37
|
+
"xml",
|
|
38
|
+
"zip"
|
|
39
|
+
]);
|
|
40
|
+
var EXPLICIT_TRACKING_SELECTORS = ["[data-hk-event]", "[data-hitkeep-event]"].join(", ");
|
|
41
|
+
var noop = () => void 0;
|
|
42
|
+
function ignoreError(error) {
|
|
43
|
+
void error;
|
|
44
|
+
}
|
|
45
|
+
function isTrackerBlocked(hostname, userAgent, doNotTrack, collectDnt, captureOnLocalhost = false) {
|
|
46
|
+
const isBot = /bot|spider|crawl|slurp|ia_archiver/i.test(userAgent);
|
|
47
|
+
const isLocal = !captureOnLocalhost && (hostname === "localhost" || hostname === "127.0.0.1");
|
|
48
|
+
const dntEnabled = doNotTrack === "1";
|
|
49
|
+
return isLocal || isBot || dntEnabled && !collectDnt;
|
|
50
|
+
}
|
|
51
|
+
function isTrackingOptedOut(win) {
|
|
52
|
+
try {
|
|
53
|
+
return win.localStorage.getItem(OPT_OUT_KEY) === "true";
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function setTrackingOptOut(win, optedOut) {
|
|
59
|
+
try {
|
|
60
|
+
if (optedOut) {
|
|
61
|
+
win.localStorage.setItem(OPT_OUT_KEY, "true");
|
|
62
|
+
} else {
|
|
63
|
+
win.localStorage.removeItem(OPT_OUT_KEY);
|
|
64
|
+
}
|
|
65
|
+
} catch (error) {
|
|
66
|
+
ignoreError(error);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function sanitizeTrackedUrl(rawUrl, baseUrl) {
|
|
70
|
+
try {
|
|
71
|
+
const url = new URL(rawUrl, baseUrl);
|
|
72
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
url.search = "";
|
|
76
|
+
url.hash = "";
|
|
77
|
+
return url;
|
|
78
|
+
} catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function sanitizeTrackedPath(url) {
|
|
83
|
+
return url.pathname || "/";
|
|
84
|
+
}
|
|
85
|
+
function resolveTrackerUrl(scriptUrl, relativePath) {
|
|
86
|
+
const scriptDirectory = new URL(".", scriptUrl);
|
|
87
|
+
const normalizedPath = relativePath.replace(/^\/+/, "");
|
|
88
|
+
return new URL(normalizedPath, scriptDirectory).toString();
|
|
89
|
+
}
|
|
90
|
+
function resolveWebVitalsBundleUrl(scriptUrl, bundleName = "hk-vitals.js") {
|
|
91
|
+
return resolveTrackerUrl(scriptUrl, bundleName);
|
|
92
|
+
}
|
|
93
|
+
function resolveTrackerEndpoints(baseUrl, enableWebVitals) {
|
|
94
|
+
return {
|
|
95
|
+
pageEndpoint: resolveTrackerUrl(baseUrl, "ingest"),
|
|
96
|
+
eventEndpoint: resolveTrackerUrl(baseUrl, "ingest/event"),
|
|
97
|
+
webVitalsEndpoint: resolveTrackerUrl(baseUrl, "ingest/web-vitals"),
|
|
98
|
+
webVitalsBundleUrl: enableWebVitals ? resolveWebVitalsBundleUrl(baseUrl) : null
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function loadWebVitalsBundle(win, bundleUrl) {
|
|
102
|
+
if (win.hk?._webVitalsLoaded) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const script = win.document.createElement("script");
|
|
106
|
+
script.async = true;
|
|
107
|
+
script.src = bundleUrl;
|
|
108
|
+
win.hk = win.hk || {};
|
|
109
|
+
win.hk._webVitalsLoaded = true;
|
|
110
|
+
win.document.head.appendChild(script);
|
|
111
|
+
}
|
|
112
|
+
function extractDownloadExtension(url) {
|
|
113
|
+
const lastSegment = sanitizeTrackedPath(url).split("/").pop() ?? "";
|
|
114
|
+
const parts = lastSegment.split(".");
|
|
115
|
+
if (parts.length < 2) {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const extension = parts[parts.length - 1]?.toLowerCase() ?? "";
|
|
119
|
+
return DOWNLOAD_EXTENSIONS.has(extension) ? extension : null;
|
|
120
|
+
}
|
|
121
|
+
function hasExplicitTrackingTag(element) {
|
|
122
|
+
for (let current = element; current; current = current.parentElement) {
|
|
123
|
+
if (current.matches(EXPLICIT_TRACKING_SELECTORS)) {
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
function classifyLinkEvent(link, currentUrl) {
|
|
130
|
+
if (link.closest("form") || hasExplicitTrackingTag(link)) {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
const href = link.getAttribute("href");
|
|
134
|
+
if (!href) {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
const targetUrl = sanitizeTrackedUrl(href, currentUrl);
|
|
138
|
+
if (!targetUrl) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
if (targetUrl.hostname !== currentUrl.hostname) {
|
|
142
|
+
return {
|
|
143
|
+
name: "outbound_click",
|
|
144
|
+
properties: {
|
|
145
|
+
target_host: targetUrl.hostname,
|
|
146
|
+
target_path: sanitizeTrackedPath(targetUrl),
|
|
147
|
+
target_protocol: targetUrl.protocol.replace(":", "")
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const fileExtension = link.hasAttribute("download") ? extractDownloadExtension(targetUrl) ?? "unknown" : extractDownloadExtension(targetUrl);
|
|
152
|
+
if (!fileExtension) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
name: "file_download",
|
|
157
|
+
properties: {
|
|
158
|
+
file_host: targetUrl.hostname,
|
|
159
|
+
file_path: sanitizeTrackedPath(targetUrl),
|
|
160
|
+
file_ext: fileExtension
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function classifyFormSubmit(form, currentUrl, submitter) {
|
|
165
|
+
if (hasExplicitTrackingTag(submitter ?? null) || hasExplicitTrackingTag(form)) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
const rawAction = form.getAttribute("action")?.trim() || currentUrl.toString();
|
|
169
|
+
const actionUrl = sanitizeTrackedUrl(rawAction, currentUrl);
|
|
170
|
+
if (!actionUrl) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const method = (form.getAttribute("method")?.trim() || "get").toLowerCase();
|
|
174
|
+
const formId = form.getAttribute("id")?.trim();
|
|
175
|
+
const properties = {
|
|
176
|
+
action_host: actionUrl.hostname,
|
|
177
|
+
action_path: sanitizeTrackedPath(actionUrl),
|
|
178
|
+
method,
|
|
179
|
+
same_origin: actionUrl.origin === currentUrl.origin
|
|
180
|
+
};
|
|
181
|
+
if (formId) {
|
|
182
|
+
properties["form_id"] = formId;
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
name: "form_submit",
|
|
186
|
+
properties
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
function createTracker(win, config) {
|
|
190
|
+
const { document, location, navigator, screen, history, sessionStorage, crypto } = win;
|
|
191
|
+
win.hk = win.hk || {};
|
|
192
|
+
if (win.hk._bootstrapped) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
win.hk._bootstrapped = true;
|
|
196
|
+
if (isTrackerBlocked(location.hostname, navigator.userAgent, navigator.doNotTrack, config.collectDnt, config.captureOnLocalhost) || isTrackingOptedOut(win)) {
|
|
197
|
+
if (config.bindToWindow) {
|
|
198
|
+
win.hk.event = noop;
|
|
199
|
+
}
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
const generateUUID = () => {
|
|
203
|
+
if (crypto?.randomUUID) {
|
|
204
|
+
return crypto.randomUUID();
|
|
205
|
+
}
|
|
206
|
+
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (value) => (Number(value) ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> Number(value) / 4).toString(16));
|
|
207
|
+
};
|
|
208
|
+
const getSessionId = () => {
|
|
209
|
+
const now = Date.now();
|
|
210
|
+
let sessionId2 = null;
|
|
211
|
+
try {
|
|
212
|
+
const stored = sessionStorage.getItem(SESSION_KEY);
|
|
213
|
+
if (stored) {
|
|
214
|
+
const [id, lastActive] = stored.split("|");
|
|
215
|
+
if (id && lastActive && now - parseInt(lastActive, 10) < SESSION_EXPIRY) {
|
|
216
|
+
sessionId2 = id;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
} catch (error) {
|
|
220
|
+
ignoreError(error);
|
|
221
|
+
}
|
|
222
|
+
if (!sessionId2) {
|
|
223
|
+
sessionId2 = generateUUID();
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
sessionStorage.setItem(SESSION_KEY, `${sessionId2}|${now}`);
|
|
227
|
+
} catch (error) {
|
|
228
|
+
ignoreError(error);
|
|
229
|
+
}
|
|
230
|
+
return sessionId2;
|
|
231
|
+
};
|
|
232
|
+
const sessionId = getSessionId();
|
|
233
|
+
const initialReferrer = document.referrer;
|
|
234
|
+
const initialHost = location.hostname;
|
|
235
|
+
const readUtmValue = (params, key) => {
|
|
236
|
+
const value = params.get(key);
|
|
237
|
+
if (!value) {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
const trimmed = value.trim();
|
|
241
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
242
|
+
};
|
|
243
|
+
const initialSearchParams = new URLSearchParams(location.search);
|
|
244
|
+
const initialAttribution = {
|
|
245
|
+
u_src: readUtmValue(initialSearchParams, "utm_source"),
|
|
246
|
+
u_med: readUtmValue(initialSearchParams, "utm_medium"),
|
|
247
|
+
u_cmp: readUtmValue(initialSearchParams, "utm_campaign"),
|
|
248
|
+
u_trm: readUtmValue(initialSearchParams, "utm_term"),
|
|
249
|
+
u_cnt: readUtmValue(initialSearchParams, "utm_content"),
|
|
250
|
+
qr: readUtmValue(initialSearchParams, "hk_qr")
|
|
251
|
+
};
|
|
252
|
+
const pendingRequests = [];
|
|
253
|
+
const removers = [];
|
|
254
|
+
const on = (target, type, listener, options) => {
|
|
255
|
+
target.addEventListener(type, listener, options);
|
|
256
|
+
removers.push(() => target.removeEventListener(type, listener, options));
|
|
257
|
+
};
|
|
258
|
+
let active = true;
|
|
259
|
+
let retryTimer = null;
|
|
260
|
+
let lastPath = location.pathname;
|
|
261
|
+
let lastPageviewPath = "";
|
|
262
|
+
let lastPageviewAt = 0;
|
|
263
|
+
let currentPageId = generateUUID();
|
|
264
|
+
const queueRequest = (request) => {
|
|
265
|
+
pendingRequests.push(request);
|
|
266
|
+
if (pendingRequests.length > MAX_PENDING_REQUESTS) {
|
|
267
|
+
pendingRequests.splice(0, pendingRequests.length - MAX_PENDING_REQUESTS);
|
|
268
|
+
}
|
|
269
|
+
scheduleFlush();
|
|
270
|
+
};
|
|
271
|
+
const flushQueue = () => {
|
|
272
|
+
if (pendingRequests.length === 0) {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (retryTimer !== null) {
|
|
276
|
+
clearTimeout(retryTimer);
|
|
277
|
+
retryTimer = null;
|
|
278
|
+
}
|
|
279
|
+
const requests = pendingRequests.splice(0, pendingRequests.length);
|
|
280
|
+
for (const request of requests) {
|
|
281
|
+
sendRequest(request, true);
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
const scheduleFlush = () => {
|
|
285
|
+
if (retryTimer !== null || pendingRequests.length === 0) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
retryTimer = setTimeout(() => {
|
|
289
|
+
retryTimer = null;
|
|
290
|
+
flushQueue();
|
|
291
|
+
}, RETRY_DELAY_MS);
|
|
292
|
+
};
|
|
293
|
+
const sendRequest = (request, fromQueue = false) => {
|
|
294
|
+
if (!active) {
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const headers = { "Content-Type": "application/json" };
|
|
298
|
+
if (navigator.sendBeacon && !config.disableBeacon) {
|
|
299
|
+
const blob = new Blob([request.body], { type: "application/json" });
|
|
300
|
+
if (navigator.sendBeacon(request.endpoint, blob)) {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
fetch(request.endpoint, {
|
|
305
|
+
method: "POST",
|
|
306
|
+
body: request.body,
|
|
307
|
+
headers,
|
|
308
|
+
keepalive: true,
|
|
309
|
+
credentials: "omit"
|
|
310
|
+
}).then((response) => {
|
|
311
|
+
if (!response.ok) {
|
|
312
|
+
throw new Error(`tracker_request_failed_${response.status}`);
|
|
313
|
+
}
|
|
314
|
+
}).catch((error) => {
|
|
315
|
+
ignoreError(error);
|
|
316
|
+
if (!fromQueue) {
|
|
317
|
+
queueRequest(request);
|
|
318
|
+
} else {
|
|
319
|
+
pendingRequests.unshift(request);
|
|
320
|
+
if (pendingRequests.length > MAX_PENDING_REQUESTS) {
|
|
321
|
+
pendingRequests.length = MAX_PENDING_REQUESTS;
|
|
322
|
+
}
|
|
323
|
+
scheduleFlush();
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
};
|
|
327
|
+
const sendJson = (endpoint, payload) => {
|
|
328
|
+
sendRequest({
|
|
329
|
+
endpoint,
|
|
330
|
+
body: JSON.stringify(payload)
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
const currentReferrer = () => {
|
|
334
|
+
if (lastPath !== location.pathname) {
|
|
335
|
+
return `${location.origin}${lastPath}`;
|
|
336
|
+
}
|
|
337
|
+
return initialReferrer || null;
|
|
338
|
+
};
|
|
339
|
+
const emitEvent = (name, properties = {}) => {
|
|
340
|
+
sendJson(config.eventEndpoint, {
|
|
341
|
+
n: name,
|
|
342
|
+
p: properties,
|
|
343
|
+
r: currentReferrer(),
|
|
344
|
+
sid: sessionId,
|
|
345
|
+
path: location.pathname || "/",
|
|
346
|
+
ua: navigator.userAgent,
|
|
347
|
+
tsrc: config.trackerSource,
|
|
348
|
+
tv: config.trackerVersion
|
|
349
|
+
});
|
|
350
|
+
};
|
|
351
|
+
if (config.webVitalsBundleUrl) {
|
|
352
|
+
win.hk._webVitals = {
|
|
353
|
+
emit: (payload) => sendJson(config.webVitalsEndpoint, payload),
|
|
354
|
+
getPath: () => location.pathname || "/",
|
|
355
|
+
sessionId,
|
|
356
|
+
pageId: () => currentPageId,
|
|
357
|
+
trackerSource: config.trackerSource,
|
|
358
|
+
trackerVersion: config.trackerVersion,
|
|
359
|
+
userAgent: navigator.userAgent
|
|
360
|
+
};
|
|
361
|
+
loadWebVitalsBundle(win, config.webVitalsBundleUrl);
|
|
362
|
+
}
|
|
363
|
+
const sendPageView = () => {
|
|
364
|
+
const currentPath = location.pathname;
|
|
365
|
+
const now = Date.now();
|
|
366
|
+
currentPageId = generateUUID();
|
|
367
|
+
try {
|
|
368
|
+
sessionStorage.setItem(SESSION_KEY, `${sessionId}|${now}`);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
ignoreError(error);
|
|
371
|
+
}
|
|
372
|
+
if (currentPath === lastPageviewPath && now - lastPageviewAt < DUPLICATE_PAGEVIEW_WINDOW_MS) {
|
|
373
|
+
lastPath = currentPath;
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const referrer = currentReferrer();
|
|
377
|
+
const isUnique = lastPath === currentPath && referrer ? new URL(referrer, location.href).hostname !== initialHost : false;
|
|
378
|
+
sendJson(config.pageEndpoint, {
|
|
379
|
+
path: currentPath,
|
|
380
|
+
referrer: referrer || null,
|
|
381
|
+
ua: navigator.userAgent,
|
|
382
|
+
vp_w: win.innerWidth,
|
|
383
|
+
vp_h: win.innerHeight,
|
|
384
|
+
sc_w: screen.width,
|
|
385
|
+
sc_h: screen.height,
|
|
386
|
+
lang: navigator.language,
|
|
387
|
+
...initialAttribution,
|
|
388
|
+
unique: Boolean(isUnique),
|
|
389
|
+
session_id: sessionId,
|
|
390
|
+
page_id: currentPageId,
|
|
391
|
+
tsrc: config.trackerSource,
|
|
392
|
+
tv: config.trackerVersion
|
|
393
|
+
});
|
|
394
|
+
lastPageviewPath = currentPath;
|
|
395
|
+
lastPageviewAt = now;
|
|
396
|
+
lastPath = currentPath;
|
|
397
|
+
};
|
|
398
|
+
const patchHistoryMethod = (method) => {
|
|
399
|
+
const original = history[method];
|
|
400
|
+
const patched = function patchedHistory(...args) {
|
|
401
|
+
original.apply(this, args);
|
|
402
|
+
sendPageView();
|
|
403
|
+
};
|
|
404
|
+
history[method] = patched;
|
|
405
|
+
removers.push(() => {
|
|
406
|
+
if (history[method] === patched) {
|
|
407
|
+
history[method] = original;
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
};
|
|
411
|
+
if (!config.disableSpaTracking) {
|
|
412
|
+
patchHistoryMethod("pushState");
|
|
413
|
+
patchHistoryMethod("replaceState");
|
|
414
|
+
on(win, "popstate", sendPageView);
|
|
415
|
+
on(win, "hashchange", sendPageView);
|
|
416
|
+
}
|
|
417
|
+
const handleVisibilityFlush = () => {
|
|
418
|
+
if (document.visibilityState === "hidden") {
|
|
419
|
+
flushQueue();
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
on(win, "online", flushQueue);
|
|
423
|
+
on(win, "pagehide", flushQueue);
|
|
424
|
+
on(document, "visibilitychange", handleVisibilityFlush);
|
|
425
|
+
if (config.capturePageviews) {
|
|
426
|
+
if (document.visibilityState === "prerender") {
|
|
427
|
+
const handlePrerenderVisible = () => {
|
|
428
|
+
if (document.visibilityState === "visible") {
|
|
429
|
+
sendPageView();
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
on(document, "visibilitychange", handlePrerenderVisible, { once: true });
|
|
433
|
+
} else {
|
|
434
|
+
sendPageView();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
bindAutoTracking(document, () => new URL(location.href), config, emitEvent, on);
|
|
438
|
+
const track2 = (name, properties) => emitEvent(name, properties ?? {});
|
|
439
|
+
if (config.bindToWindow) {
|
|
440
|
+
win.hk.event = track2;
|
|
441
|
+
}
|
|
442
|
+
const cleanup2 = () => {
|
|
443
|
+
if (!active) {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
active = false;
|
|
447
|
+
if (retryTimer !== null) {
|
|
448
|
+
clearTimeout(retryTimer);
|
|
449
|
+
retryTimer = null;
|
|
450
|
+
}
|
|
451
|
+
for (const remove of removers.splice(0, removers.length)) {
|
|
452
|
+
remove();
|
|
453
|
+
}
|
|
454
|
+
if (win.hk) {
|
|
455
|
+
if (win.hk.event === track2) {
|
|
456
|
+
delete win.hk.event;
|
|
457
|
+
}
|
|
458
|
+
win.hk._bootstrapped = false;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
return {
|
|
462
|
+
track: track2,
|
|
463
|
+
trackPageview: sendPageView,
|
|
464
|
+
cleanup: cleanup2
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
function bindAutoTracking(document, getCurrentUrl, options, emitEvent, on) {
|
|
468
|
+
if (!options.disableOutboundTracking || !options.disableDownloadTracking) {
|
|
469
|
+
const handleLinkInteraction = (event) => {
|
|
470
|
+
if (event.type === "click" && event.button !== 0 || event.type === "auxclick" && event.button !== 1) {
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
const target = event.target;
|
|
474
|
+
if (!(target instanceof Element)) {
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
const link = target.closest("a[href], area[href]");
|
|
478
|
+
if (!(link instanceof HTMLAnchorElement || link instanceof HTMLAreaElement)) {
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
const trackedEvent = classifyLinkEvent(link, getCurrentUrl());
|
|
482
|
+
if (!trackedEvent) {
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (trackedEvent.name === "outbound_click" && options.disableOutboundTracking) {
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
if (trackedEvent.name === "file_download" && options.disableDownloadTracking) {
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
emitEvent(trackedEvent.name, trackedEvent.properties);
|
|
492
|
+
};
|
|
493
|
+
on(document, "click", handleLinkInteraction, true);
|
|
494
|
+
on(document, "auxclick", handleLinkInteraction, true);
|
|
495
|
+
}
|
|
496
|
+
if (!options.disableFormTracking) {
|
|
497
|
+
const handleFormSubmit = (event) => {
|
|
498
|
+
const target = event.target;
|
|
499
|
+
if (!(target instanceof HTMLFormElement)) {
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
const submitter = event instanceof SubmitEvent && event.submitter instanceof Element ? event.submitter : null;
|
|
503
|
+
const trackedEvent = classifyFormSubmit(target, getCurrentUrl(), submitter);
|
|
504
|
+
if (!trackedEvent) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
emitEvent(trackedEvent.name, trackedEvent.properties);
|
|
508
|
+
};
|
|
509
|
+
on(document, "submit", handleFormSubmit, true);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// src/tracker/version.ts
|
|
514
|
+
var TRACKER_VERSION = "2.12.0";
|
|
515
|
+
|
|
516
|
+
// src/tracker/package.ts
|
|
517
|
+
var MAX_PRE_INIT_EVENTS = 32;
|
|
518
|
+
var DEFAULT_TRACKER_SOURCE = "@hitkeep/tracker";
|
|
519
|
+
var activeHandle = null;
|
|
520
|
+
var initialized = false;
|
|
521
|
+
var preInitEvents = [];
|
|
522
|
+
function debugLog(message) {
|
|
523
|
+
if (console?.debug) {
|
|
524
|
+
console.debug("[HitKeep]", message);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
function resolveWindow(win) {
|
|
528
|
+
if (win) {
|
|
529
|
+
return win;
|
|
530
|
+
}
|
|
531
|
+
return typeof window === "undefined" ? null : window;
|
|
532
|
+
}
|
|
533
|
+
function resolveRuntimeConfig(config) {
|
|
534
|
+
const host = (config.host ?? "").trim();
|
|
535
|
+
if (!host) {
|
|
536
|
+
throw new Error('@hitkeep/tracker: init requires a host, e.g. init({ host: "https://stats.example.com" })');
|
|
537
|
+
}
|
|
538
|
+
const enableWebVitals = config.webVitals === true;
|
|
539
|
+
const endpoints = resolveTrackerEndpoints(new URL(`${host.replace(/\/+$/, "")}/`), enableWebVitals);
|
|
540
|
+
return {
|
|
541
|
+
...endpoints,
|
|
542
|
+
collectDnt: config.respectDoNotTrack === false,
|
|
543
|
+
disableBeacon: config.useBeacon === false,
|
|
544
|
+
disableSpaTracking: config.autoTrackSpaNavigation === false,
|
|
545
|
+
disableOutboundTracking: config.outboundLinks === false,
|
|
546
|
+
disableDownloadTracking: config.fileDownloads === false,
|
|
547
|
+
disableFormTracking: config.formSubmissions === false,
|
|
548
|
+
enableWebVitals,
|
|
549
|
+
trackerSource: (config.trackerSource || DEFAULT_TRACKER_SOURCE).trim().slice(0, 64) || DEFAULT_TRACKER_SOURCE,
|
|
550
|
+
trackerVersion: TRACKER_VERSION,
|
|
551
|
+
capturePageviews: config.autoCapturePageviews !== false,
|
|
552
|
+
captureOnLocalhost: config.captureOnLocalhost === true,
|
|
553
|
+
bindToWindow: config.bindToWindow !== false
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
var publicHandle = {
|
|
557
|
+
track: (name, properties) => track(name, properties),
|
|
558
|
+
trackPageview: () => trackPageview(),
|
|
559
|
+
cleanup: () => cleanup()
|
|
560
|
+
};
|
|
561
|
+
function init(config, win) {
|
|
562
|
+
if (initialized) {
|
|
563
|
+
debugLog("tracker already initialized; returning the existing handle");
|
|
564
|
+
return publicHandle;
|
|
565
|
+
}
|
|
566
|
+
const runtimeConfig = resolveRuntimeConfig(config);
|
|
567
|
+
initialized = true;
|
|
568
|
+
const queued = preInitEvents.splice(0, preInitEvents.length);
|
|
569
|
+
const targetWindow = resolveWindow(win);
|
|
570
|
+
if (!targetWindow) {
|
|
571
|
+
debugLog("tracker skipped outside a browser environment");
|
|
572
|
+
return publicHandle;
|
|
573
|
+
}
|
|
574
|
+
activeHandle = createTracker(targetWindow, runtimeConfig);
|
|
575
|
+
if (!activeHandle) {
|
|
576
|
+
debugLog("tracker not started (already bootstrapped, blocked, or opted out)");
|
|
577
|
+
return publicHandle;
|
|
578
|
+
}
|
|
579
|
+
for (const event of queued) {
|
|
580
|
+
activeHandle.track(event.name, event.properties);
|
|
581
|
+
}
|
|
582
|
+
return publicHandle;
|
|
583
|
+
}
|
|
584
|
+
function track(name, properties) {
|
|
585
|
+
if (activeHandle) {
|
|
586
|
+
activeHandle.track(name, properties);
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
if (initialized) {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
preInitEvents.push({ name, properties });
|
|
593
|
+
if (preInitEvents.length > MAX_PRE_INIT_EVENTS) {
|
|
594
|
+
preInitEvents.shift();
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function trackPageview() {
|
|
598
|
+
activeHandle?.trackPageview();
|
|
599
|
+
}
|
|
600
|
+
function cleanup() {
|
|
601
|
+
activeHandle?.cleanup();
|
|
602
|
+
activeHandle = null;
|
|
603
|
+
initialized = false;
|
|
604
|
+
}
|
|
605
|
+
function blockTrackingForMe(win) {
|
|
606
|
+
const targetWindow = resolveWindow(win);
|
|
607
|
+
if (targetWindow) {
|
|
608
|
+
setTrackingOptOut(targetWindow, true);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
function enableTrackingForMe(win) {
|
|
612
|
+
const targetWindow = resolveWindow(win);
|
|
613
|
+
if (targetWindow) {
|
|
614
|
+
setTrackingOptOut(targetWindow, false);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
function isTrackingEnabled(win) {
|
|
618
|
+
const targetWindow = resolveWindow(win);
|
|
619
|
+
return targetWindow ? !isTrackingOptedOut(targetWindow) : false;
|
|
620
|
+
}
|
|
621
|
+
function trackViewItem(properties) {
|
|
622
|
+
track("view_item", properties);
|
|
623
|
+
}
|
|
624
|
+
function trackAddToCart(properties) {
|
|
625
|
+
track("add_to_cart", properties);
|
|
626
|
+
}
|
|
627
|
+
function trackBeginCheckout(properties) {
|
|
628
|
+
track("begin_checkout", properties);
|
|
629
|
+
}
|
|
630
|
+
function trackPurchase(properties) {
|
|
631
|
+
track("purchase", properties);
|
|
632
|
+
}
|
|
633
|
+
export {
|
|
634
|
+
TRACKER_VERSION,
|
|
635
|
+
blockTrackingForMe,
|
|
636
|
+
cleanup,
|
|
637
|
+
enableTrackingForMe,
|
|
638
|
+
init,
|
|
639
|
+
isTrackingEnabled,
|
|
640
|
+
track,
|
|
641
|
+
trackAddToCart,
|
|
642
|
+
trackBeginCheckout,
|
|
643
|
+
trackPageview,
|
|
644
|
+
trackPurchase,
|
|
645
|
+
trackViewItem
|
|
646
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { EventProperties, HitKeepWindow, TrackerHandle } from './core.cjs';
|
|
2
|
+
export type { EventProperties, TrackerHandle } from './core.cjs';
|
|
3
|
+
export { TRACKER_VERSION } from './version.cjs';
|
|
4
|
+
export interface TrackerConfig {
|
|
5
|
+
/** HitKeep origin the tracker reports to, e.g. `https://stats.example.com` or `https://example.net/hitkeep`. */
|
|
6
|
+
host: string;
|
|
7
|
+
/** Send a pageview on init. Default `true`. */
|
|
8
|
+
autoCapturePageviews?: boolean;
|
|
9
|
+
/** Track history-based SPA navigations as pageviews. Default `true`. */
|
|
10
|
+
autoTrackSpaNavigation?: boolean;
|
|
11
|
+
/** Track clicks on links to other hostnames as `outbound_click`. Default `true`. */
|
|
12
|
+
outboundLinks?: boolean;
|
|
13
|
+
/** Track same-origin file downloads as `file_download`. Default `true`. */
|
|
14
|
+
fileDownloads?: boolean;
|
|
15
|
+
/** Track form submissions as `form_submit`. Default `true`. */
|
|
16
|
+
formSubmissions?: boolean;
|
|
17
|
+
/** Load the Web Vitals bundle from `${host}/hk-vitals.js`. Default `false`. */
|
|
18
|
+
webVitals?: boolean;
|
|
19
|
+
/** Prefer `navigator.sendBeacon` over keepalive fetch. Default `true`. */
|
|
20
|
+
useBeacon?: boolean;
|
|
21
|
+
/** Drop tracking when the browser sends `DNT: 1`. Default `true`. */
|
|
22
|
+
respectDoNotTrack?: boolean;
|
|
23
|
+
/** Track on `localhost`/`127.0.0.1`, which is blocked by default. Default `false`. */
|
|
24
|
+
captureOnLocalhost?: boolean;
|
|
25
|
+
/** Expose `window.hk.event` for snippet-compatible callers. Default `true`. */
|
|
26
|
+
bindToWindow?: boolean;
|
|
27
|
+
/** Attribution source reported with every request. Default `@hitkeep/tracker`. */
|
|
28
|
+
trackerSource?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface EcommerceItem {
|
|
31
|
+
item_id?: string;
|
|
32
|
+
item_name?: string;
|
|
33
|
+
quantity?: number;
|
|
34
|
+
price?: number;
|
|
35
|
+
}
|
|
36
|
+
export interface ItemEventProperties {
|
|
37
|
+
item_id?: string;
|
|
38
|
+
item_name?: string;
|
|
39
|
+
category?: string;
|
|
40
|
+
price?: number;
|
|
41
|
+
currency?: string;
|
|
42
|
+
[key: string]: unknown;
|
|
43
|
+
}
|
|
44
|
+
export interface PurchaseProperties {
|
|
45
|
+
transaction_id: string;
|
|
46
|
+
value: number;
|
|
47
|
+
currency: string;
|
|
48
|
+
items?: EcommerceItem[];
|
|
49
|
+
items_count?: number;
|
|
50
|
+
coupon?: string;
|
|
51
|
+
tax?: number;
|
|
52
|
+
shipping?: number;
|
|
53
|
+
[key: string]: unknown;
|
|
54
|
+
}
|
|
55
|
+
export declare function init(config: TrackerConfig, win?: HitKeepWindow): TrackerHandle;
|
|
56
|
+
export declare function track(name: string, properties?: EventProperties): void;
|
|
57
|
+
export declare function trackPageview(): void;
|
|
58
|
+
export declare function cleanup(): void;
|
|
59
|
+
export declare function blockTrackingForMe(win?: Window): void;
|
|
60
|
+
export declare function enableTrackingForMe(win?: Window): void;
|
|
61
|
+
export declare function isTrackingEnabled(win?: Window): boolean;
|
|
62
|
+
export declare function trackViewItem(properties: ItemEventProperties): void;
|
|
63
|
+
export declare function trackAddToCart(properties: ItemEventProperties): void;
|
|
64
|
+
export declare function trackBeginCheckout(properties: ItemEventProperties): void;
|
|
65
|
+
export declare function trackPurchase(properties: PurchaseProperties): void;
|