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