@traqio/web 0.3.2 → 0.4.1
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/README.md +26 -0
- package/build/analytics.d.ts +73 -0
- package/build/index.cjs +524 -11
- package/build/index.cjs.map +4 -4
- package/build/index.d.ts +27 -0
- package/build/index.js +524 -11
- package/build/index.js.map +4 -4
- package/build/traqio.min.js +1 -1
- package/build/traqio.min.js.map +4 -4
- package/package.json +2 -2
package/build/index.cjs
CHANGED
|
@@ -230,6 +230,66 @@ var require_skan = __commonJS({
|
|
|
230
230
|
}
|
|
231
231
|
});
|
|
232
232
|
|
|
233
|
+
// ../sdk-core/build/analytics.js
|
|
234
|
+
var require_analytics = __commonJS({
|
|
235
|
+
"../sdk-core/build/analytics.js"(exports) {
|
|
236
|
+
"use strict";
|
|
237
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
238
|
+
exports.MAX_PROPS_BYTES = exports.MAX_SCREEN_NAME = exports.MAX_EVENT_NAME = exports.ANALYTICS_SESSION_IDLE_MS = void 0;
|
|
239
|
+
exports.cleanEventName = cleanEventName;
|
|
240
|
+
exports.cleanScreenName = cleanScreenName;
|
|
241
|
+
exports.cleanProps = cleanProps;
|
|
242
|
+
exports.touchSession = touchSession;
|
|
243
|
+
exports.parseSession = parseSession;
|
|
244
|
+
exports.ANALYTICS_SESSION_IDLE_MS = 30 * 60 * 1e3;
|
|
245
|
+
exports.MAX_EVENT_NAME = 128;
|
|
246
|
+
exports.MAX_SCREEN_NAME = 512;
|
|
247
|
+
exports.MAX_PROPS_BYTES = 4096;
|
|
248
|
+
function cleanEventName(name) {
|
|
249
|
+
if (typeof name !== "string")
|
|
250
|
+
return null;
|
|
251
|
+
const n = name.trim();
|
|
252
|
+
if (!n || n.length > exports.MAX_EVENT_NAME || n.startsWith("$"))
|
|
253
|
+
return null;
|
|
254
|
+
return n;
|
|
255
|
+
}
|
|
256
|
+
function cleanScreenName(name) {
|
|
257
|
+
if (typeof name !== "string")
|
|
258
|
+
return null;
|
|
259
|
+
const n = name.trim();
|
|
260
|
+
return n ? n.slice(0, exports.MAX_SCREEN_NAME) : null;
|
|
261
|
+
}
|
|
262
|
+
function cleanProps(props) {
|
|
263
|
+
if (typeof props !== "object" || props === null || Array.isArray(props))
|
|
264
|
+
return void 0;
|
|
265
|
+
try {
|
|
266
|
+
const json = JSON.stringify(props);
|
|
267
|
+
if (!json || json === "{}" || json.length > exports.MAX_PROPS_BYTES)
|
|
268
|
+
return void 0;
|
|
269
|
+
return JSON.parse(json);
|
|
270
|
+
} catch {
|
|
271
|
+
return void 0;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function touchSession(current, now, newId2) {
|
|
275
|
+
if (current && typeof current.id === "string" && typeof current.last === "number" && now - current.last <= exports.ANALYTICS_SESSION_IDLE_MS && now >= current.last - 6e4) {
|
|
276
|
+
return { id: current.id, last: Math.max(now, current.last) };
|
|
277
|
+
}
|
|
278
|
+
return { id: newId2(), last: now };
|
|
279
|
+
}
|
|
280
|
+
function parseSession(raw) {
|
|
281
|
+
if (!raw)
|
|
282
|
+
return null;
|
|
283
|
+
try {
|
|
284
|
+
const s = JSON.parse(raw);
|
|
285
|
+
return typeof s.id === "string" && typeof s.last === "number" ? { id: s.id, last: s.last } : null;
|
|
286
|
+
} catch {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
233
293
|
// ../sdk-core/build/adservices.js
|
|
234
294
|
var require_adservices = __commonJS({
|
|
235
295
|
"../sdk-core/build/adservices.js"(exports) {
|
|
@@ -632,16 +692,17 @@ var require_build = __commonJS({
|
|
|
632
692
|
"../sdk-core/build/index.js"(exports) {
|
|
633
693
|
"use strict";
|
|
634
694
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
635
|
-
exports.Traqio = exports.Client = exports.AdRevenueGate = exports.watchReactNativeAds = exports.fromMaxAdInfo = exports.fromGoogleMobileAdsPaid = exports.fromGoogleMobileAdsNativeAd = exports.fromGoogleMobileAdsChannel = exports.fromCapacitorAdMob = exports.MAX_RN_REVENUE_EVENTS = exports.MAX_RN_MIN_VERSION = exports.GMA_MIN_VERSION = exports.GMA_FULLSCREEN_CHANNELS = exports.CAPACITOR_ADMOB_PAID_EVENTS = exports.isTrackingUrl = exports.isOpenUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
|
|
695
|
+
exports.Traqio = exports.Client = exports.AdRevenueGate = exports.watchReactNativeAds = exports.fromMaxAdInfo = exports.fromGoogleMobileAdsPaid = exports.fromGoogleMobileAdsNativeAd = exports.fromGoogleMobileAdsChannel = exports.fromCapacitorAdMob = exports.MAX_RN_REVENUE_EVENTS = exports.MAX_RN_MIN_VERSION = exports.GMA_MIN_VERSION = exports.GMA_FULLSCREEN_CHANNELS = exports.CAPACITOR_ADMOB_PAID_EVENTS = exports.isTrackingUrl = exports.isOpenUrl = exports.ANALYTICS_SESSION_IDLE_MS = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
|
|
636
696
|
exports.normalizeAdvertisingId = normalizeAdvertisingId;
|
|
637
697
|
exports.fromMaxAd = fromMaxAd;
|
|
638
698
|
exports.detectDebug = detectDebug;
|
|
639
699
|
exports.isLocalPage = isLocalPage;
|
|
640
700
|
var skan_1 = require_skan();
|
|
701
|
+
var analytics_1 = require_analytics();
|
|
641
702
|
var adservices_1 = require_adservices();
|
|
642
703
|
var deeplink_1 = require_deeplink();
|
|
643
704
|
var adRevenue_1 = require_adRevenue();
|
|
644
|
-
exports.SDK_VERSION = "0.
|
|
705
|
+
exports.SDK_VERSION = "0.7.0";
|
|
645
706
|
var skan_2 = require_skan();
|
|
646
707
|
Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
|
|
647
708
|
return skan_2.Skan;
|
|
@@ -650,6 +711,10 @@ var require_build = __commonJS({
|
|
|
650
711
|
Object.defineProperty(exports, "reportAdServicesToken", { enumerable: true, get: function() {
|
|
651
712
|
return adservices_2.reportAdServicesToken;
|
|
652
713
|
} });
|
|
714
|
+
var analytics_2 = require_analytics();
|
|
715
|
+
Object.defineProperty(exports, "ANALYTICS_SESSION_IDLE_MS", { enumerable: true, get: function() {
|
|
716
|
+
return analytics_2.ANALYTICS_SESSION_IDLE_MS;
|
|
717
|
+
} });
|
|
653
718
|
var deeplink_2 = require_deeplink();
|
|
654
719
|
Object.defineProperty(exports, "isOpenUrl", { enumerable: true, get: function() {
|
|
655
720
|
return deeplink_2.isOpenUrl;
|
|
@@ -710,9 +775,15 @@ var require_build = __commonJS({
|
|
|
710
775
|
var DEFERRED_RETRY_KEY = "traq_deferred_consent_retry_until";
|
|
711
776
|
var DEFERRED_RETRY_WINDOW_MS = 60 * 6e4;
|
|
712
777
|
var CONSENT_KEY = "traq_consent";
|
|
778
|
+
var ANALYTICS_QUEUE_KEY = "traq_analytics_queue";
|
|
779
|
+
var ANALYTICS_SESSION_KEY = "traq_analytics_session";
|
|
780
|
+
var ANALYTICS_PATH = "/ingest/analytics";
|
|
781
|
+
var MAX_ANALYTICS_BATCH = 50;
|
|
782
|
+
var MAX_ANALYTICS_QUEUE = 1e3;
|
|
783
|
+
var MAX_EARLY_ANALYTICS = 100;
|
|
713
784
|
var MAX_BATCH = 20;
|
|
714
785
|
var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
|
|
715
|
-
var
|
|
786
|
+
var MAX_QUEUE2 = 500;
|
|
716
787
|
var MAX_AD_BATCH = 100;
|
|
717
788
|
var MAX_AD_QUEUE = 1e3;
|
|
718
789
|
var BASE_RETRY_MS = 1e3;
|
|
@@ -821,6 +892,10 @@ var require_build = __commonJS({
|
|
|
821
892
|
this.att = null;
|
|
822
893
|
this.adIdSync = null;
|
|
823
894
|
this.debug = false;
|
|
895
|
+
this.analyticsQueue = [];
|
|
896
|
+
this.analyticsSession = null;
|
|
897
|
+
this.earlyAnalytics = [];
|
|
898
|
+
this.currentScreen = null;
|
|
824
899
|
this.maxRevenuePaid = (adInfo) => {
|
|
825
900
|
try {
|
|
826
901
|
const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
|
|
@@ -848,9 +923,18 @@ var require_build = __commonJS({
|
|
|
848
923
|
await this.restoreConsent(opts.consent);
|
|
849
924
|
await this.restoreQueue();
|
|
850
925
|
await this.restoreAdQueue();
|
|
926
|
+
await this.restoreAnalytics();
|
|
851
927
|
await this.buildContext();
|
|
852
|
-
if (await this.restoreErased())
|
|
928
|
+
if (await this.restoreErased()) {
|
|
929
|
+
this.earlyAnalytics = [];
|
|
853
930
|
return;
|
|
931
|
+
}
|
|
932
|
+
if (this.isWeb) {
|
|
933
|
+
this.earlyAnalytics = [];
|
|
934
|
+
} else {
|
|
935
|
+
for (const e of this.earlyAnalytics.splice(0))
|
|
936
|
+
this.pushAnalytics(e, false);
|
|
937
|
+
}
|
|
854
938
|
if (!this.isWeb) {
|
|
855
939
|
const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
|
|
856
940
|
await this.sendInstallOnce();
|
|
@@ -865,7 +949,7 @@ var require_build = __commonJS({
|
|
|
865
949
|
await this.initAppleAds();
|
|
866
950
|
this.wireLifecycle();
|
|
867
951
|
this.wireAdRevenue();
|
|
868
|
-
if (this.queue.length || this.adQueue.length)
|
|
952
|
+
if (this.queue.length || this.adQueue.length || this.analyticsQueue.length)
|
|
869
953
|
this.scheduleFlush(0);
|
|
870
954
|
}
|
|
871
955
|
// `InitOptions.adRevenue`: hand the ad SDKs' own paid events to the trackers.
|
|
@@ -907,6 +991,82 @@ var require_build = __commonJS({
|
|
|
907
991
|
if (props == null ? void 0 : props.value)
|
|
908
992
|
this.skan.addRevenue(props.value);
|
|
909
993
|
}
|
|
994
|
+
/**
|
|
995
|
+
* A product-analytics event — `paywall_viewed`, `deck_built`, `search_performed`…
|
|
996
|
+
* — read in the console's Analytics section (events, funnels, property splits).
|
|
997
|
+
* NOT a conversion: never billed, never sent to an ad network (that is `track()`).
|
|
998
|
+
*
|
|
999
|
+
* Batched, persisted while offline and retried like every other call; it never
|
|
1000
|
+
* throws. Names starting with `$` are reserved; properties must survive JSON and
|
|
1001
|
+
* stay under 4 KB, else they are dropped (the event is kept). Callable before
|
|
1002
|
+
* `init()`: the first 100 calls wait for it.
|
|
1003
|
+
*
|
|
1004
|
+
* Traqio.capture("lead_captured", { magnet: "starter-deck" });
|
|
1005
|
+
*/
|
|
1006
|
+
capture(name, props) {
|
|
1007
|
+
try {
|
|
1008
|
+
const n = (0, analytics_1.cleanEventName)(name);
|
|
1009
|
+
if (!n)
|
|
1010
|
+
return;
|
|
1011
|
+
const p = (0, analytics_1.cleanProps)(props);
|
|
1012
|
+
this.queueAnalytics({ kind: "custom", name: n, ts: Date.now(), ...p ? { props: p } : {} });
|
|
1013
|
+
} catch {
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* A screen view — the app's page view, read under « Top pages » and usable as a
|
|
1018
|
+
* funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React
|
|
1019
|
+
* Navigation) or Expo Router's `usePathname()` do it (docs: /docs/sdks/react-native).
|
|
1020
|
+
* The same screen reported twice in a row inside a session counts once (re-renders).
|
|
1021
|
+
* Custom events captured afterwards carry this screen as their page.
|
|
1022
|
+
*/
|
|
1023
|
+
screen(name, props) {
|
|
1024
|
+
try {
|
|
1025
|
+
const s = (0, analytics_1.cleanScreenName)(name);
|
|
1026
|
+
if (!s)
|
|
1027
|
+
return;
|
|
1028
|
+
const now = Date.now();
|
|
1029
|
+
const sameVisit = this.analyticsSession !== null && now - this.analyticsSession.last <= analytics_1.ANALYTICS_SESSION_IDLE_MS;
|
|
1030
|
+
if (s === this.currentScreen && sameVisit)
|
|
1031
|
+
return;
|
|
1032
|
+
this.currentScreen = s;
|
|
1033
|
+
const p = (0, analytics_1.cleanProps)(props);
|
|
1034
|
+
this.queueAnalytics({ kind: "pageview", ts: now, screen: s, ...p ? { props: p } : {} });
|
|
1035
|
+
} catch {
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Screen views from a React Navigation container, by themselves:
|
|
1040
|
+
*
|
|
1041
|
+
* const navigationRef = useNavigationContainerRef();
|
|
1042
|
+
* useEffect(() => Traqio.trackScreens(navigationRef), [navigationRef]);
|
|
1043
|
+
*
|
|
1044
|
+
* Returns the unsubscribe. Typed by shape: no navigation library is a dependency.
|
|
1045
|
+
*/
|
|
1046
|
+
trackScreens(navigation) {
|
|
1047
|
+
const report = () => {
|
|
1048
|
+
try {
|
|
1049
|
+
const route = navigation.getCurrentRoute();
|
|
1050
|
+
if (route == null ? void 0 : route.name)
|
|
1051
|
+
this.screen(route.name);
|
|
1052
|
+
} catch {
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
let off;
|
|
1056
|
+
try {
|
|
1057
|
+
off = navigation.addListener("state", report);
|
|
1058
|
+
} catch {
|
|
1059
|
+
off = void 0;
|
|
1060
|
+
}
|
|
1061
|
+
report();
|
|
1062
|
+
return () => {
|
|
1063
|
+
try {
|
|
1064
|
+
if (typeof off === "function")
|
|
1065
|
+
off();
|
|
1066
|
+
} catch {
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
910
1070
|
/**
|
|
911
1071
|
* The store this app runs on: the native bridge's word, else React Native's
|
|
912
1072
|
* `Platform.OS`, else UNKNOWN. Never a guess — until 2026-11 a missing bridge meant
|
|
@@ -1375,8 +1535,11 @@ var require_build = __commonJS({
|
|
|
1375
1535
|
this.queue = [];
|
|
1376
1536
|
this.adQueue = [];
|
|
1377
1537
|
this.adBatchId = null;
|
|
1538
|
+
this.analyticsQueue = [];
|
|
1539
|
+
this.earlyAnalytics = [];
|
|
1378
1540
|
await this.persistQueue();
|
|
1379
1541
|
await this.persistAdQueue();
|
|
1542
|
+
await this.persistAnalyticsQueue();
|
|
1380
1543
|
try {
|
|
1381
1544
|
await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ERASED_KEY, "1"));
|
|
1382
1545
|
} catch {
|
|
@@ -1384,11 +1547,60 @@ var require_build = __commonJS({
|
|
|
1384
1547
|
}
|
|
1385
1548
|
enqueue(e) {
|
|
1386
1549
|
this.queue.push(e);
|
|
1387
|
-
if (this.queue.length >
|
|
1388
|
-
this.queue.splice(0, this.queue.length -
|
|
1550
|
+
if (this.queue.length > MAX_QUEUE2)
|
|
1551
|
+
this.queue.splice(0, this.queue.length - MAX_QUEUE2);
|
|
1389
1552
|
void this.persistQueue();
|
|
1390
1553
|
this.scheduleFlush();
|
|
1391
1554
|
}
|
|
1555
|
+
/** Before `init()` the call waits in memory; after it, it is stamped and queued. */
|
|
1556
|
+
queueAnalytics(event) {
|
|
1557
|
+
var _a, _b;
|
|
1558
|
+
if (this.erased)
|
|
1559
|
+
return;
|
|
1560
|
+
const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
|
|
1561
|
+
const e = screen ? { ...event, screen } : event;
|
|
1562
|
+
if (!this.started) {
|
|
1563
|
+
if (this.earlyAnalytics.length < MAX_EARLY_ANALYTICS)
|
|
1564
|
+
this.earlyAnalytics.push(e);
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
if (this.isWeb)
|
|
1568
|
+
return;
|
|
1569
|
+
this.pushAnalytics(e);
|
|
1570
|
+
}
|
|
1571
|
+
pushAnalytics(e, schedule = true) {
|
|
1572
|
+
this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
|
|
1573
|
+
this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession.id });
|
|
1574
|
+
if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE)
|
|
1575
|
+
this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);
|
|
1576
|
+
void this.persistAnalyticsQueue();
|
|
1577
|
+
if (schedule)
|
|
1578
|
+
this.scheduleFlush();
|
|
1579
|
+
}
|
|
1580
|
+
/** The persisted queue first (older), then whatever was captured while it was being read. */
|
|
1581
|
+
async restoreAnalytics() {
|
|
1582
|
+
var _a, _b, _c;
|
|
1583
|
+
try {
|
|
1584
|
+
const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(ANALYTICS_QUEUE_KEY));
|
|
1585
|
+
const stored = raw ? JSON.parse(raw) : null;
|
|
1586
|
+
if (Array.isArray(stored))
|
|
1587
|
+
this.analyticsQueue = [...stored, ...this.analyticsQueue].slice(-MAX_ANALYTICS_QUEUE);
|
|
1588
|
+
} catch {
|
|
1589
|
+
}
|
|
1590
|
+
try {
|
|
1591
|
+
(_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
|
|
1592
|
+
} catch {
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
async persistAnalyticsQueue() {
|
|
1596
|
+
var _a, _b;
|
|
1597
|
+
try {
|
|
1598
|
+
await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ANALYTICS_QUEUE_KEY, JSON.stringify(this.analyticsQueue)));
|
|
1599
|
+
if (this.analyticsSession)
|
|
1600
|
+
await ((_b = this.opts.storage) == null ? void 0 : _b.setItem(ANALYTICS_SESSION_KEY, JSON.stringify(this.analyticsSession)));
|
|
1601
|
+
} catch {
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1392
1604
|
async restoreQueue() {
|
|
1393
1605
|
var _a;
|
|
1394
1606
|
try {
|
|
@@ -1618,10 +1830,10 @@ var require_build = __commonJS({
|
|
|
1618
1830
|
}, delay);
|
|
1619
1831
|
}
|
|
1620
1832
|
async drain() {
|
|
1621
|
-
var _a;
|
|
1833
|
+
var _a, _b;
|
|
1622
1834
|
if (this.erased)
|
|
1623
1835
|
return;
|
|
1624
|
-
if (this.flushing || !this.queue.length && !this.adQueue.length)
|
|
1836
|
+
if (this.flushing || !this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)
|
|
1625
1837
|
return;
|
|
1626
1838
|
this.flushing = true;
|
|
1627
1839
|
try {
|
|
@@ -1667,6 +1879,22 @@ var require_build = __commonJS({
|
|
|
1667
1879
|
await this.persistAdQueue();
|
|
1668
1880
|
this.retryMs = BASE_RETRY_MS;
|
|
1669
1881
|
}
|
|
1882
|
+
while (this.analyticsQueue.length) {
|
|
1883
|
+
const batch = this.analyticsQueue.slice(0, MAX_ANALYTICS_BATCH);
|
|
1884
|
+
const outcome = await this.send({
|
|
1885
|
+
anonymousId: (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId(),
|
|
1886
|
+
userId: this.opts.userId,
|
|
1887
|
+
platform: this.hostPlatform,
|
|
1888
|
+
events: batch
|
|
1889
|
+
}, ANALYTICS_PATH);
|
|
1890
|
+
if (outcome === "retry")
|
|
1891
|
+
return this.backOff();
|
|
1892
|
+
if (outcome === "refused")
|
|
1893
|
+
console.warn(`[traqio] the server refused ${batch.length} analytics event(s) as malformed \u2014 dropped, not retried`);
|
|
1894
|
+
this.analyticsQueue.splice(0, batch.length);
|
|
1895
|
+
await this.persistAnalyticsQueue();
|
|
1896
|
+
this.retryMs = BASE_RETRY_MS;
|
|
1897
|
+
}
|
|
1670
1898
|
} finally {
|
|
1671
1899
|
this.flushing = false;
|
|
1672
1900
|
}
|
|
@@ -2146,6 +2374,245 @@ var TrackIdKeeper = class {
|
|
|
2146
2374
|
}
|
|
2147
2375
|
};
|
|
2148
2376
|
|
|
2377
|
+
// src/analytics.ts
|
|
2378
|
+
var SESSION_KEY = "traq_session";
|
|
2379
|
+
var SESSION_IDLE_MS = 30 * 60 * 1e3;
|
|
2380
|
+
var FLUSH_EVERY_MS = 5e3;
|
|
2381
|
+
var FLUSH_AT = 20;
|
|
2382
|
+
var MAX_QUEUE = 200;
|
|
2383
|
+
var MAX_ERRORS_PER_PAGE = 10;
|
|
2384
|
+
var SCROLL_STEPS = [25, 50, 75, 100];
|
|
2385
|
+
var UTM = [
|
|
2386
|
+
["utm_source", "utmSource"],
|
|
2387
|
+
["utm_medium", "utmMedium"],
|
|
2388
|
+
["utm_campaign", "utmCampaign"],
|
|
2389
|
+
["utm_content", "utmContent"],
|
|
2390
|
+
["utm_term", "utmTerm"],
|
|
2391
|
+
["gclid", "gclid"],
|
|
2392
|
+
["fbclid", "fbclid"],
|
|
2393
|
+
["ttclid", "ttclid"]
|
|
2394
|
+
];
|
|
2395
|
+
function newId() {
|
|
2396
|
+
try {
|
|
2397
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
2398
|
+
} catch {
|
|
2399
|
+
}
|
|
2400
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
2401
|
+
}
|
|
2402
|
+
function landingSource(href, referrer) {
|
|
2403
|
+
var _a;
|
|
2404
|
+
const src = {};
|
|
2405
|
+
try {
|
|
2406
|
+
const u = new URL(href);
|
|
2407
|
+
for (const [param, key] of UTM) {
|
|
2408
|
+
const v = (_a = u.searchParams.get(param)) == null ? void 0 : _a.trim();
|
|
2409
|
+
if (v) src[key] = v.slice(0, 200);
|
|
2410
|
+
}
|
|
2411
|
+
if (referrer) {
|
|
2412
|
+
const r = new URL(referrer);
|
|
2413
|
+
if (r.hostname.replace(/^www\./, "") !== u.hostname.replace(/^www\./, "")) src.referrer = `${r.protocol}//${r.host}/`;
|
|
2414
|
+
}
|
|
2415
|
+
} catch {
|
|
2416
|
+
}
|
|
2417
|
+
return Object.keys(src).length ? src : void 0;
|
|
2418
|
+
}
|
|
2419
|
+
function bare2(href) {
|
|
2420
|
+
if (!href) return void 0;
|
|
2421
|
+
try {
|
|
2422
|
+
const u = new URL(href, typeof location !== "undefined" ? location.href : void 0);
|
|
2423
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
|
|
2424
|
+
return `${u.origin}${u.pathname}`;
|
|
2425
|
+
} catch {
|
|
2426
|
+
return void 0;
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
var AnalyticsTracker = class {
|
|
2430
|
+
constructor(deps) {
|
|
2431
|
+
this.deps = deps;
|
|
2432
|
+
this.queue = [];
|
|
2433
|
+
this.timer = null;
|
|
2434
|
+
this.lastPath = null;
|
|
2435
|
+
this.maxScroll = 0;
|
|
2436
|
+
this.scrollUrl = null;
|
|
2437
|
+
this.errorsThisPage = 0;
|
|
2438
|
+
this.stopped = false;
|
|
2439
|
+
}
|
|
2440
|
+
/** Wires the listeners the options ask for and records the first page view. */
|
|
2441
|
+
start() {
|
|
2442
|
+
const o = this.deps.options;
|
|
2443
|
+
this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);
|
|
2444
|
+
document.addEventListener("visibilitychange", () => {
|
|
2445
|
+
if (document.visibilityState === "hidden") this.leave();
|
|
2446
|
+
});
|
|
2447
|
+
window.addEventListener("pagehide", () => this.leave());
|
|
2448
|
+
if (o.pageviews !== false) {
|
|
2449
|
+
this.pageview();
|
|
2450
|
+
this.watchRoutes();
|
|
2451
|
+
}
|
|
2452
|
+
if (o.clicks !== false) document.addEventListener("click", (e) => this.onClick(e), true);
|
|
2453
|
+
if (o.scroll !== false) window.addEventListener("scroll", () => this.onScroll(), { passive: true });
|
|
2454
|
+
if (o.errors !== false) {
|
|
2455
|
+
window.addEventListener("error", (e) => this.onError(e));
|
|
2456
|
+
window.addEventListener("unhandledrejection", (e) => this.onRejection(e));
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
/** A custom analytics event — never a conversion (that is `track()`). */
|
|
2460
|
+
capture(name, props) {
|
|
2461
|
+
if (typeof name !== "string" || !name.trim() || name.startsWith("$")) return;
|
|
2462
|
+
this.enqueue({ kind: "custom", name: name.trim(), props });
|
|
2463
|
+
}
|
|
2464
|
+
/** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
|
|
2465
|
+
pageview() {
|
|
2466
|
+
const url = bare2(location.href);
|
|
2467
|
+
if (!url) return;
|
|
2468
|
+
if (url === this.lastPath) return;
|
|
2469
|
+
this.sendScroll();
|
|
2470
|
+
this.lastPath = url;
|
|
2471
|
+
this.scrollUrl = url;
|
|
2472
|
+
this.maxScroll = 0;
|
|
2473
|
+
this.errorsThisPage = 0;
|
|
2474
|
+
this.enqueue({ kind: "pageview" });
|
|
2475
|
+
this.onScroll();
|
|
2476
|
+
}
|
|
2477
|
+
/** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
|
|
2478
|
+
flush(leaving) {
|
|
2479
|
+
if (!this.queue.length || this.stopped) return;
|
|
2480
|
+
if (this.deps.isForgotten()) {
|
|
2481
|
+
this.stop();
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
const anonymousId = this.deps.anonymousId();
|
|
2485
|
+
if (!anonymousId) return;
|
|
2486
|
+
const events = this.queue.splice(0, 100);
|
|
2487
|
+
const body = JSON.stringify({
|
|
2488
|
+
sdkKey: this.deps.sdkKey,
|
|
2489
|
+
anonymousId,
|
|
2490
|
+
userId: this.deps.userId(),
|
|
2491
|
+
debug: this.deps.isDebug() || void 0,
|
|
2492
|
+
events
|
|
2493
|
+
});
|
|
2494
|
+
try {
|
|
2495
|
+
void fetch(`${this.deps.endpoint}/ingest/analytics`, {
|
|
2496
|
+
method: "POST",
|
|
2497
|
+
headers: { "content-type": "application/json" },
|
|
2498
|
+
body,
|
|
2499
|
+
keepalive: leaving
|
|
2500
|
+
}).then((res) => {
|
|
2501
|
+
if (!res.ok && (res.status >= 500 || res.status === 429)) this.requeue(events);
|
|
2502
|
+
}).catch(() => this.requeue(events));
|
|
2503
|
+
} catch {
|
|
2504
|
+
this.requeue(events);
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
/** Forget everything and stop: after `forgetMe()`, or on a server. */
|
|
2508
|
+
stop() {
|
|
2509
|
+
this.stopped = true;
|
|
2510
|
+
this.queue = [];
|
|
2511
|
+
if (this.timer) clearInterval(this.timer);
|
|
2512
|
+
this.timer = null;
|
|
2513
|
+
}
|
|
2514
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
2515
|
+
requeue(events) {
|
|
2516
|
+
if (this.stopped) return;
|
|
2517
|
+
this.queue = [...events, ...this.queue].slice(-MAX_QUEUE);
|
|
2518
|
+
}
|
|
2519
|
+
session() {
|
|
2520
|
+
const now = Date.now();
|
|
2521
|
+
let s = null;
|
|
2522
|
+
try {
|
|
2523
|
+
const raw = this.deps.store.getSync(SESSION_KEY);
|
|
2524
|
+
s = raw ? JSON.parse(raw) : null;
|
|
2525
|
+
} catch {
|
|
2526
|
+
s = null;
|
|
2527
|
+
}
|
|
2528
|
+
if (!s || typeof s.id !== "string" || typeof s.last !== "number" || now - s.last > SESSION_IDLE_MS) {
|
|
2529
|
+
s = { id: newId(), last: now, src: landingSource(location.href, document.referrer) };
|
|
2530
|
+
} else {
|
|
2531
|
+
s.last = now;
|
|
2532
|
+
}
|
|
2533
|
+
try {
|
|
2534
|
+
this.deps.store.setSync(SESSION_KEY, JSON.stringify(s));
|
|
2535
|
+
} catch {
|
|
2536
|
+
}
|
|
2537
|
+
return s;
|
|
2538
|
+
}
|
|
2539
|
+
enqueue(e) {
|
|
2540
|
+
var _a, _b;
|
|
2541
|
+
if (this.stopped) return;
|
|
2542
|
+
const s = this.session();
|
|
2543
|
+
const title = typeof document.title === "string" && document.title ? document.title.slice(0, 200) : void 0;
|
|
2544
|
+
this.queue.push({ ...e, ts: Date.now(), url: (_b = (_a = e.url) != null ? _a : bare2(location.href)) != null ? _b : "", title, sessionId: s.id, ...s.src ? { src: s.src } : {} });
|
|
2545
|
+
if (this.queue.length > MAX_QUEUE) this.queue.shift();
|
|
2546
|
+
if (this.queue.length >= FLUSH_AT) this.flush(false);
|
|
2547
|
+
}
|
|
2548
|
+
leave() {
|
|
2549
|
+
this.sendScroll();
|
|
2550
|
+
this.flush(true);
|
|
2551
|
+
}
|
|
2552
|
+
/** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
|
|
2553
|
+
watchRoutes() {
|
|
2554
|
+
if (typeof history === "undefined") return;
|
|
2555
|
+
const after = () => {
|
|
2556
|
+
setTimeout(() => this.pageview(), 0);
|
|
2557
|
+
};
|
|
2558
|
+
for (const method of ["pushState", "replaceState"]) {
|
|
2559
|
+
const original = history[method];
|
|
2560
|
+
if (typeof original !== "function") continue;
|
|
2561
|
+
history[method] = function(...args) {
|
|
2562
|
+
const out = original.apply(this, args);
|
|
2563
|
+
after();
|
|
2564
|
+
return out;
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
window.addEventListener("popstate", after);
|
|
2568
|
+
}
|
|
2569
|
+
onScroll() {
|
|
2570
|
+
var _a;
|
|
2571
|
+
if (typeof document.documentElement === "undefined" || !document.documentElement) return;
|
|
2572
|
+
const doc2 = document.documentElement;
|
|
2573
|
+
const viewport = window.innerHeight || doc2.clientHeight || 0;
|
|
2574
|
+
const height = Math.max(doc2.scrollHeight || 0, ((_a = document.body) == null ? void 0 : _a.scrollHeight) || 0);
|
|
2575
|
+
if (!height) return;
|
|
2576
|
+
const seen = height <= viewport ? 1 : Math.min(1, ((window.scrollY || doc2.scrollTop || 0) + viewport) / height);
|
|
2577
|
+
const pct = Math.round(seen * 100);
|
|
2578
|
+
for (const step of SCROLL_STEPS) if (pct >= step && step > this.maxScroll) this.maxScroll = step;
|
|
2579
|
+
}
|
|
2580
|
+
sendScroll() {
|
|
2581
|
+
if (this.deps.options.scroll === false || !this.scrollUrl || this.maxScroll < 25) return;
|
|
2582
|
+
this.enqueue({ kind: "scroll", url: this.scrollUrl, props: { depth: this.maxScroll } });
|
|
2583
|
+
this.scrollUrl = null;
|
|
2584
|
+
this.maxScroll = 0;
|
|
2585
|
+
}
|
|
2586
|
+
onClick(e) {
|
|
2587
|
+
const target = e.target;
|
|
2588
|
+
const el = target && typeof target.closest === "function" ? target.closest("a, button, [role='button'], input[type='submit'], input[type='button']") : null;
|
|
2589
|
+
if (!el || el.closest("[data-traqio-ignore]")) return;
|
|
2590
|
+
const input = el;
|
|
2591
|
+
const text = (el.tagName === "INPUT" ? input.value : el.innerText || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
|
|
2592
|
+
const href = el.tagName === "A" ? bare2(el.getAttribute("href")) : void 0;
|
|
2593
|
+
const props = { tag: el.tagName.toLowerCase() };
|
|
2594
|
+
if (text) props.text = text;
|
|
2595
|
+
if (href) props.href = href;
|
|
2596
|
+
if (el.id) props.id = el.id.slice(0, 100);
|
|
2597
|
+
this.enqueue({ kind: "click", props });
|
|
2598
|
+
}
|
|
2599
|
+
onError(e) {
|
|
2600
|
+
if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
|
|
2601
|
+
const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
|
|
2602
|
+
this.errorsThisPage++;
|
|
2603
|
+
const stack = e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack.slice(0, 1500) : void 0;
|
|
2604
|
+
this.enqueue({ kind: "error", props: { message, ...stack ? { stack } : {}, ...e.filename ? { source: bare2(e.filename) } : {}, ...e.lineno ? { line: e.lineno } : {} } });
|
|
2605
|
+
}
|
|
2606
|
+
onRejection(e) {
|
|
2607
|
+
if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
|
|
2608
|
+
const reason = e.reason;
|
|
2609
|
+
const message = (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection").slice(0, 300);
|
|
2610
|
+
this.errorsThisPage++;
|
|
2611
|
+
const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack.slice(0, 1500) : void 0;
|
|
2612
|
+
this.enqueue({ kind: "error", props: { message, unhandledRejection: true, ...stack ? { stack } : {} } });
|
|
2613
|
+
}
|
|
2614
|
+
};
|
|
2615
|
+
|
|
2149
2616
|
// src/index.ts
|
|
2150
2617
|
var DEFAULT_ENDPOINT = "https://api.traqio.app";
|
|
2151
2618
|
var DEFAULT_TRACK_ID_DAYS = 30;
|
|
@@ -2168,6 +2635,11 @@ var TraqioWeb = class {
|
|
|
2168
2635
|
this.sources = null;
|
|
2169
2636
|
this.waitForConsent = false;
|
|
2170
2637
|
this.started = false;
|
|
2638
|
+
this.analytics = null;
|
|
2639
|
+
/** `capture()` calls made before `init()` finished — replayed once the tracker exists. */
|
|
2640
|
+
this.earlyCaptures = [];
|
|
2641
|
+
/** `init()` has finished (or will never run here): early captures are no longer kept. */
|
|
2642
|
+
this.ready = false;
|
|
2171
2643
|
}
|
|
2172
2644
|
/**
|
|
2173
2645
|
* Call once, as early as possible on every page (or once in a single-page app).
|
|
@@ -2195,9 +2667,11 @@ var TraqioWeb = class {
|
|
|
2195
2667
|
const id = randomId();
|
|
2196
2668
|
if (id) this.store.setSync(DEVICE_ID_KEY, id);
|
|
2197
2669
|
}
|
|
2670
|
+
this.userId = opts.userId;
|
|
2671
|
+
const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
2198
2672
|
await this.core.init({
|
|
2199
2673
|
sdkKey: opts.sdkKey,
|
|
2200
|
-
endpoint
|
|
2674
|
+
endpoint,
|
|
2201
2675
|
storage: this.store,
|
|
2202
2676
|
platform: "web",
|
|
2203
2677
|
userId: opts.userId,
|
|
@@ -2208,6 +2682,23 @@ var TraqioWeb = class {
|
|
|
2208
2682
|
window.addEventListener("pagehide", background);
|
|
2209
2683
|
}
|
|
2210
2684
|
});
|
|
2685
|
+
if (opts.analytics) {
|
|
2686
|
+
const store = this.store;
|
|
2687
|
+
this.analytics = new AnalyticsTracker({
|
|
2688
|
+
store,
|
|
2689
|
+
endpoint,
|
|
2690
|
+
sdkKey: opts.sdkKey,
|
|
2691
|
+
anonymousId: () => store.getSync(DEVICE_ID_KEY),
|
|
2692
|
+
userId: () => this.userId,
|
|
2693
|
+
isDebug: () => this.core.isDebug,
|
|
2694
|
+
isForgotten: () => this.core.forgotten,
|
|
2695
|
+
options: opts.analytics === true ? {} : opts.analytics
|
|
2696
|
+
});
|
|
2697
|
+
this.analytics.start();
|
|
2698
|
+
for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
|
|
2699
|
+
}
|
|
2700
|
+
this.earlyCaptures = [];
|
|
2701
|
+
this.ready = true;
|
|
2211
2702
|
}
|
|
2212
2703
|
/** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
|
|
2213
2704
|
get isDebug() {
|
|
@@ -2217,8 +2708,27 @@ var TraqioWeb = class {
|
|
|
2217
2708
|
track(name, props) {
|
|
2218
2709
|
this.core.track(name, props);
|
|
2219
2710
|
}
|
|
2711
|
+
/**
|
|
2712
|
+
* A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
|
|
2713
|
+
* console's Analytics section (events, funnels). NOT a conversion: it is never
|
|
2714
|
+
* billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
|
|
2715
|
+
* Needs `analytics` at init; names starting with `$` are reserved.
|
|
2716
|
+
*/
|
|
2717
|
+
capture(name, props) {
|
|
2718
|
+
if (this.analytics) this.analytics.capture(name, props);
|
|
2719
|
+
else if (!this.ready && this.earlyCaptures.length < 50) this.earlyCaptures.push([name, props]);
|
|
2720
|
+
}
|
|
2721
|
+
/**
|
|
2722
|
+
* Record a page view now. Not needed with the history API (route changes are
|
|
2723
|
+
* caught by themselves); for a router that changes the page another way.
|
|
2724
|
+
*/
|
|
2725
|
+
pageview() {
|
|
2726
|
+
var _a;
|
|
2727
|
+
(_a = this.analytics) == null ? void 0 : _a.pageview();
|
|
2728
|
+
}
|
|
2220
2729
|
/** Set the user id once known (after sign-in). */
|
|
2221
2730
|
setUserId(id) {
|
|
2731
|
+
this.userId = id;
|
|
2222
2732
|
this.core.setUserId(id);
|
|
2223
2733
|
}
|
|
2224
2734
|
/**
|
|
@@ -2267,17 +2777,20 @@ var TraqioWeb = class {
|
|
|
2267
2777
|
* Resolves false when the request did not reach the server — then nothing changed.
|
|
2268
2778
|
*/
|
|
2269
2779
|
async forgetMe() {
|
|
2270
|
-
var _a, _b;
|
|
2780
|
+
var _a, _b, _c;
|
|
2271
2781
|
const ok = await this.core.forgetMe();
|
|
2272
2782
|
if (ok) {
|
|
2273
2783
|
(_a = this.trackIds) == null ? void 0 : _a.clear();
|
|
2274
2784
|
(_b = this.sources) == null ? void 0 : _b.clear();
|
|
2785
|
+
(_c = this.analytics) == null ? void 0 : _c.stop();
|
|
2275
2786
|
}
|
|
2276
2787
|
return ok;
|
|
2277
2788
|
}
|
|
2278
2789
|
/** Send what is queued now. Already wired to tab hide and page exit. */
|
|
2279
2790
|
flush() {
|
|
2791
|
+
var _a;
|
|
2280
2792
|
this.core.flush();
|
|
2793
|
+
(_a = this.analytics) == null ? void 0 : _a.flush(false);
|
|
2281
2794
|
}
|
|
2282
2795
|
/** True once `forgetMe()` has been honoured: this browser sends nothing any more. */
|
|
2283
2796
|
get forgotten() {
|