@traqio/web 0.3.1 → 0.4.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/README.md +26 -0
- package/build/analytics.d.ts +73 -0
- package/build/index.cjs +344 -10
- package/build/index.cjs.map +4 -4
- package/build/index.d.ts +27 -0
- package/build/index.js +344 -10
- 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.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type WebSource } from "./source";
|
|
2
|
+
import { type AnalyticsOptions } from "./analytics";
|
|
2
3
|
export type { WebSource } from "./source";
|
|
4
|
+
export type { AnalyticsOptions } from "./analytics";
|
|
3
5
|
export declare const DEFAULT_ENDPOINT = "https://api.traqio.app";
|
|
4
6
|
export interface WebInitOptions {
|
|
5
7
|
/** The site's WEB key (`tq_web_…`), from the console. Public by design: it is held to the site's origins. */
|
|
@@ -36,6 +38,13 @@ export interface WebInitOptions {
|
|
|
36
38
|
* site, `false` to count a local page.
|
|
37
39
|
*/
|
|
38
40
|
debug?: boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Product analytics — page views (route changes included), clicks, scroll depth and
|
|
43
|
+
* front-end errors, read in the console's Analytics section. `true` turns all four
|
|
44
|
+
* on; an object picks. Default off. Never billed and never sent to an ad network:
|
|
45
|
+
* analytics events have their own route and table, apart from conversions.
|
|
46
|
+
*/
|
|
47
|
+
analytics?: boolean | AnalyticsOptions;
|
|
39
48
|
}
|
|
40
49
|
/** What `track()` accepts beside the event name. */
|
|
41
50
|
export interface WebTrackProps {
|
|
@@ -56,6 +65,12 @@ export declare class TraqioWeb {
|
|
|
56
65
|
private started;
|
|
57
66
|
/** A `setConsent()` made before `init()` — it decides whether init may store. */
|
|
58
67
|
private earlyConsent;
|
|
68
|
+
private analytics;
|
|
69
|
+
private userId;
|
|
70
|
+
/** `capture()` calls made before `init()` finished — replayed once the tracker exists. */
|
|
71
|
+
private earlyCaptures;
|
|
72
|
+
/** `init()` has finished (or will never run here): early captures are no longer kept. */
|
|
73
|
+
private ready;
|
|
59
74
|
/**
|
|
60
75
|
* Call once, as early as possible on every page (or once in a single-page app).
|
|
61
76
|
* Reads the trackID from the current URL first, synchronously, so even a visitor
|
|
@@ -67,6 +82,18 @@ export declare class TraqioWeb {
|
|
|
67
82
|
get isDebug(): boolean;
|
|
68
83
|
/** Record an event — `signup`, `purchase`, `add_to_cart`… Batched, retried, kept across page loads. */
|
|
69
84
|
track(name: string, props?: WebTrackProps): void;
|
|
85
|
+
/**
|
|
86
|
+
* A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
|
|
87
|
+
* console's Analytics section (events, funnels). NOT a conversion: it is never
|
|
88
|
+
* billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
|
|
89
|
+
* Needs `analytics` at init; names starting with `$` are reserved.
|
|
90
|
+
*/
|
|
91
|
+
capture(name: string, props?: Record<string, unknown>): void;
|
|
92
|
+
/**
|
|
93
|
+
* Record a page view now. Not needed with the history API (route changes are
|
|
94
|
+
* caught by themselves); for a router that changes the page another way.
|
|
95
|
+
*/
|
|
96
|
+
pageview(): void;
|
|
70
97
|
/** Set the user id once known (after sign-in). */
|
|
71
98
|
setUserId(id: string): void;
|
|
72
99
|
/**
|
package/build/index.js
CHANGED
|
@@ -636,7 +636,7 @@ var require_build = __commonJS({
|
|
|
636
636
|
var adservices_1 = require_adservices();
|
|
637
637
|
var deeplink_1 = require_deeplink();
|
|
638
638
|
var adRevenue_1 = require_adRevenue();
|
|
639
|
-
exports.SDK_VERSION = "0.
|
|
639
|
+
exports.SDK_VERSION = "0.6.0";
|
|
640
640
|
var skan_2 = require_skan();
|
|
641
641
|
Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
|
|
642
642
|
return skan_2.Skan;
|
|
@@ -692,6 +692,9 @@ var require_build = __commonJS({
|
|
|
692
692
|
var INSTALL_SENT_KEY = "traq_install_sent";
|
|
693
693
|
var INSTALL_SENT_DEBUG_KEY = "traq_install_sent_debug";
|
|
694
694
|
var INSTALL_ATTEMPTS_KEY = "traq_install_attempts";
|
|
695
|
+
var AD_ID_SENT_KEY = "traq_ad_id_sent";
|
|
696
|
+
var AD_ID_SENT_DEBUG_KEY = "traq_ad_id_sent_debug";
|
|
697
|
+
var AD_ID_PATH = "/ingest/advertising-id";
|
|
695
698
|
var REFERRER_KEY = "traq_referrer";
|
|
696
699
|
var QUEUE_KEY = "traq_queue";
|
|
697
700
|
var AD_QUEUE_KEY = "traq_ad_queue";
|
|
@@ -704,7 +707,7 @@ var require_build = __commonJS({
|
|
|
704
707
|
var CONSENT_KEY = "traq_consent";
|
|
705
708
|
var MAX_BATCH = 20;
|
|
706
709
|
var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
|
|
707
|
-
var
|
|
710
|
+
var MAX_QUEUE2 = 500;
|
|
708
711
|
var MAX_AD_BATCH = 100;
|
|
709
712
|
var MAX_AD_QUEUE = 1e3;
|
|
710
713
|
var BASE_RETRY_MS = 1e3;
|
|
@@ -811,6 +814,7 @@ var require_build = __commonJS({
|
|
|
811
814
|
this.deferred = null;
|
|
812
815
|
this.consent = null;
|
|
813
816
|
this.att = null;
|
|
817
|
+
this.adIdSync = null;
|
|
814
818
|
this.debug = false;
|
|
815
819
|
this.maxRevenuePaid = (adInfo) => {
|
|
816
820
|
try {
|
|
@@ -845,6 +849,7 @@ var require_build = __commonJS({
|
|
|
845
849
|
if (!this.isWeb) {
|
|
846
850
|
const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
|
|
847
851
|
await this.sendInstallOnce();
|
|
852
|
+
void this.syncAdvertisingId();
|
|
848
853
|
if (this.opts.deepLinking !== false) {
|
|
849
854
|
this.deferred = this.resolveDeferredOnce(freshInstall).then((link) => link != null ? link : this.retryDeferredWithConsent());
|
|
850
855
|
this.wireDeepLinks();
|
|
@@ -1147,6 +1152,7 @@ var require_build = __commonJS({
|
|
|
1147
1152
|
if (!this.started || this.erased)
|
|
1148
1153
|
return;
|
|
1149
1154
|
void this.maybeStartSession();
|
|
1155
|
+
void this.syncAdvertisingId();
|
|
1150
1156
|
}
|
|
1151
1157
|
/** The conversion-value mapping in force on this device, once fetched. */
|
|
1152
1158
|
get skanMapping() {
|
|
@@ -1311,6 +1317,9 @@ var require_build = __commonJS({
|
|
|
1311
1317
|
get installSentKey() {
|
|
1312
1318
|
return this.debug ? INSTALL_SENT_DEBUG_KEY : INSTALL_SENT_KEY;
|
|
1313
1319
|
}
|
|
1320
|
+
get adIdSentKey() {
|
|
1321
|
+
return this.debug ? AD_ID_SENT_DEBUG_KEY : AD_ID_SENT_KEY;
|
|
1322
|
+
}
|
|
1314
1323
|
/** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */
|
|
1315
1324
|
debugField() {
|
|
1316
1325
|
return this.debug ? { debug: true } : {};
|
|
@@ -1334,6 +1343,7 @@ var require_build = __commonJS({
|
|
|
1334
1343
|
return;
|
|
1335
1344
|
}
|
|
1336
1345
|
void this.maybeStartSession();
|
|
1346
|
+
void this.syncAdvertisingId();
|
|
1337
1347
|
});
|
|
1338
1348
|
} catch {
|
|
1339
1349
|
}
|
|
@@ -1369,8 +1379,8 @@ var require_build = __commonJS({
|
|
|
1369
1379
|
}
|
|
1370
1380
|
enqueue(e) {
|
|
1371
1381
|
this.queue.push(e);
|
|
1372
|
-
if (this.queue.length >
|
|
1373
|
-
this.queue.splice(0, this.queue.length -
|
|
1382
|
+
if (this.queue.length > MAX_QUEUE2)
|
|
1383
|
+
this.queue.splice(0, this.queue.length - MAX_QUEUE2);
|
|
1374
1384
|
void this.persistQueue();
|
|
1375
1385
|
this.scheduleFlush();
|
|
1376
1386
|
}
|
|
@@ -1543,17 +1553,56 @@ var require_build = __commonJS({
|
|
|
1543
1553
|
return;
|
|
1544
1554
|
}
|
|
1545
1555
|
}
|
|
1556
|
+
const advertisingId = await this.readAdvertisingId();
|
|
1546
1557
|
const ok = await this.post({
|
|
1547
1558
|
install: {
|
|
1548
1559
|
platform,
|
|
1549
1560
|
installReferrer: referrer.referrer,
|
|
1550
1561
|
appUserId: this.opts.userId,
|
|
1551
|
-
advertisingId
|
|
1562
|
+
advertisingId,
|
|
1552
1563
|
context: this.context
|
|
1553
1564
|
}
|
|
1554
1565
|
});
|
|
1555
|
-
if (ok)
|
|
1566
|
+
if (ok) {
|
|
1556
1567
|
await (store == null ? void 0 : store.setItem(this.installSentKey, "1"));
|
|
1568
|
+
if (advertisingId)
|
|
1569
|
+
await (store == null ? void 0 : store.setItem(this.adIdSentKey, advertisingId).catch(() => void 0));
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* The opted-in advertising id the install could not carry (todo cmwlauev). The
|
|
1574
|
+
* install leaves at first launch, before an app shows its own ATT prompt, so on iOS
|
|
1575
|
+
* it almost never has the IDFA. Re-read at every start and foreground — reading
|
|
1576
|
+
* never prompts (decision cmvjohk6) — and posted ONCE when it differs from the one
|
|
1577
|
+
* the server last acknowledged; a failure is retried at the next foreground.
|
|
1578
|
+
*
|
|
1579
|
+
* Only after the install is reported: the install itself carries an id it can read.
|
|
1580
|
+
*/
|
|
1581
|
+
syncAdvertisingId() {
|
|
1582
|
+
if (this.adIdSync)
|
|
1583
|
+
return this.adIdSync;
|
|
1584
|
+
this.adIdSync = this.postAdvertisingIdIfChanged().finally(() => {
|
|
1585
|
+
this.adIdSync = null;
|
|
1586
|
+
});
|
|
1587
|
+
return this.adIdSync;
|
|
1588
|
+
}
|
|
1589
|
+
async postAdvertisingIdIfChanged() {
|
|
1590
|
+
var _a;
|
|
1591
|
+
const store = this.opts.storage;
|
|
1592
|
+
if (this.isWeb || this.erased || !store || !this.opts.collectAdvertisingId)
|
|
1593
|
+
return;
|
|
1594
|
+
try {
|
|
1595
|
+
if (!await store.getItem(this.installSentKey))
|
|
1596
|
+
return;
|
|
1597
|
+
const advertisingId = await this.readAdvertisingId();
|
|
1598
|
+
if (!advertisingId || await store.getItem(this.adIdSentKey) === advertisingId)
|
|
1599
|
+
return;
|
|
1600
|
+
const deviceId = (_a = this.context.deviceId) != null ? _a : await this.getOrCreateDeviceId();
|
|
1601
|
+
if (await this.post({ deviceId, appUserId: this.opts.userId, advertisingId }, AD_ID_PATH)) {
|
|
1602
|
+
await store.setItem(this.adIdSentKey, advertisingId);
|
|
1603
|
+
}
|
|
1604
|
+
} catch {
|
|
1605
|
+
}
|
|
1557
1606
|
}
|
|
1558
1607
|
scheduleFlush(delay = FLUSH_DELAY_MS) {
|
|
1559
1608
|
if (this.flushTimer)
|
|
@@ -1683,8 +1732,8 @@ var require_build = __commonJS({
|
|
|
1683
1732
|
* key fixed in the console makes the same queued batch succeed.
|
|
1684
1733
|
*/
|
|
1685
1734
|
async send(body, path = "/ingest") {
|
|
1686
|
-
const consent = this.consent && (path === "/ingest" || path === "/ingest/session") ? { consent: this.consent } : {};
|
|
1687
|
-
const att = path === "/ingest" && this.asksTrackingAuthorization ? await this.readTrackingAuthorization() : null;
|
|
1735
|
+
const consent = this.consent && (path === "/ingest" || path === "/ingest/session" || path === AD_ID_PATH) ? { consent: this.consent } : {};
|
|
1736
|
+
const att = (path === "/ingest" || path === AD_ID_PATH) && this.asksTrackingAuthorization ? await this.readTrackingAuthorization() : null;
|
|
1688
1737
|
try {
|
|
1689
1738
|
const res = await fetch(`${this.opts.endpoint}${path}`, {
|
|
1690
1739
|
method: "POST",
|
|
@@ -2085,6 +2134,245 @@ var TrackIdKeeper = class {
|
|
|
2085
2134
|
}
|
|
2086
2135
|
};
|
|
2087
2136
|
|
|
2137
|
+
// src/analytics.ts
|
|
2138
|
+
var SESSION_KEY = "traq_session";
|
|
2139
|
+
var SESSION_IDLE_MS = 30 * 60 * 1e3;
|
|
2140
|
+
var FLUSH_EVERY_MS = 5e3;
|
|
2141
|
+
var FLUSH_AT = 20;
|
|
2142
|
+
var MAX_QUEUE = 200;
|
|
2143
|
+
var MAX_ERRORS_PER_PAGE = 10;
|
|
2144
|
+
var SCROLL_STEPS = [25, 50, 75, 100];
|
|
2145
|
+
var UTM = [
|
|
2146
|
+
["utm_source", "utmSource"],
|
|
2147
|
+
["utm_medium", "utmMedium"],
|
|
2148
|
+
["utm_campaign", "utmCampaign"],
|
|
2149
|
+
["utm_content", "utmContent"],
|
|
2150
|
+
["utm_term", "utmTerm"],
|
|
2151
|
+
["gclid", "gclid"],
|
|
2152
|
+
["fbclid", "fbclid"],
|
|
2153
|
+
["ttclid", "ttclid"]
|
|
2154
|
+
];
|
|
2155
|
+
function newId() {
|
|
2156
|
+
try {
|
|
2157
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
|
2158
|
+
} catch {
|
|
2159
|
+
}
|
|
2160
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
2161
|
+
}
|
|
2162
|
+
function landingSource(href, referrer) {
|
|
2163
|
+
var _a;
|
|
2164
|
+
const src = {};
|
|
2165
|
+
try {
|
|
2166
|
+
const u = new URL(href);
|
|
2167
|
+
for (const [param, key] of UTM) {
|
|
2168
|
+
const v = (_a = u.searchParams.get(param)) == null ? void 0 : _a.trim();
|
|
2169
|
+
if (v) src[key] = v.slice(0, 200);
|
|
2170
|
+
}
|
|
2171
|
+
if (referrer) {
|
|
2172
|
+
const r = new URL(referrer);
|
|
2173
|
+
if (r.hostname.replace(/^www\./, "") !== u.hostname.replace(/^www\./, "")) src.referrer = `${r.protocol}//${r.host}/`;
|
|
2174
|
+
}
|
|
2175
|
+
} catch {
|
|
2176
|
+
}
|
|
2177
|
+
return Object.keys(src).length ? src : void 0;
|
|
2178
|
+
}
|
|
2179
|
+
function bare2(href) {
|
|
2180
|
+
if (!href) return void 0;
|
|
2181
|
+
try {
|
|
2182
|
+
const u = new URL(href, typeof location !== "undefined" ? location.href : void 0);
|
|
2183
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
|
|
2184
|
+
return `${u.origin}${u.pathname}`;
|
|
2185
|
+
} catch {
|
|
2186
|
+
return void 0;
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
var AnalyticsTracker = class {
|
|
2190
|
+
constructor(deps) {
|
|
2191
|
+
this.deps = deps;
|
|
2192
|
+
this.queue = [];
|
|
2193
|
+
this.timer = null;
|
|
2194
|
+
this.lastPath = null;
|
|
2195
|
+
this.maxScroll = 0;
|
|
2196
|
+
this.scrollUrl = null;
|
|
2197
|
+
this.errorsThisPage = 0;
|
|
2198
|
+
this.stopped = false;
|
|
2199
|
+
}
|
|
2200
|
+
/** Wires the listeners the options ask for and records the first page view. */
|
|
2201
|
+
start() {
|
|
2202
|
+
const o = this.deps.options;
|
|
2203
|
+
this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);
|
|
2204
|
+
document.addEventListener("visibilitychange", () => {
|
|
2205
|
+
if (document.visibilityState === "hidden") this.leave();
|
|
2206
|
+
});
|
|
2207
|
+
window.addEventListener("pagehide", () => this.leave());
|
|
2208
|
+
if (o.pageviews !== false) {
|
|
2209
|
+
this.pageview();
|
|
2210
|
+
this.watchRoutes();
|
|
2211
|
+
}
|
|
2212
|
+
if (o.clicks !== false) document.addEventListener("click", (e) => this.onClick(e), true);
|
|
2213
|
+
if (o.scroll !== false) window.addEventListener("scroll", () => this.onScroll(), { passive: true });
|
|
2214
|
+
if (o.errors !== false) {
|
|
2215
|
+
window.addEventListener("error", (e) => this.onError(e));
|
|
2216
|
+
window.addEventListener("unhandledrejection", (e) => this.onRejection(e));
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
/** A custom analytics event — never a conversion (that is `track()`). */
|
|
2220
|
+
capture(name, props) {
|
|
2221
|
+
if (typeof name !== "string" || !name.trim() || name.startsWith("$")) return;
|
|
2222
|
+
this.enqueue({ kind: "custom", name: name.trim(), props });
|
|
2223
|
+
}
|
|
2224
|
+
/** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
|
|
2225
|
+
pageview() {
|
|
2226
|
+
const url = bare2(location.href);
|
|
2227
|
+
if (!url) return;
|
|
2228
|
+
if (url === this.lastPath) return;
|
|
2229
|
+
this.sendScroll();
|
|
2230
|
+
this.lastPath = url;
|
|
2231
|
+
this.scrollUrl = url;
|
|
2232
|
+
this.maxScroll = 0;
|
|
2233
|
+
this.errorsThisPage = 0;
|
|
2234
|
+
this.enqueue({ kind: "pageview" });
|
|
2235
|
+
this.onScroll();
|
|
2236
|
+
}
|
|
2237
|
+
/** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
|
|
2238
|
+
flush(leaving) {
|
|
2239
|
+
if (!this.queue.length || this.stopped) return;
|
|
2240
|
+
if (this.deps.isForgotten()) {
|
|
2241
|
+
this.stop();
|
|
2242
|
+
return;
|
|
2243
|
+
}
|
|
2244
|
+
const anonymousId = this.deps.anonymousId();
|
|
2245
|
+
if (!anonymousId) return;
|
|
2246
|
+
const events = this.queue.splice(0, 100);
|
|
2247
|
+
const body = JSON.stringify({
|
|
2248
|
+
sdkKey: this.deps.sdkKey,
|
|
2249
|
+
anonymousId,
|
|
2250
|
+
userId: this.deps.userId(),
|
|
2251
|
+
debug: this.deps.isDebug() || void 0,
|
|
2252
|
+
events
|
|
2253
|
+
});
|
|
2254
|
+
try {
|
|
2255
|
+
void fetch(`${this.deps.endpoint}/ingest/analytics`, {
|
|
2256
|
+
method: "POST",
|
|
2257
|
+
headers: { "content-type": "application/json" },
|
|
2258
|
+
body,
|
|
2259
|
+
keepalive: leaving
|
|
2260
|
+
}).then((res) => {
|
|
2261
|
+
if (!res.ok && (res.status >= 500 || res.status === 429)) this.requeue(events);
|
|
2262
|
+
}).catch(() => this.requeue(events));
|
|
2263
|
+
} catch {
|
|
2264
|
+
this.requeue(events);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
/** Forget everything and stop: after `forgetMe()`, or on a server. */
|
|
2268
|
+
stop() {
|
|
2269
|
+
this.stopped = true;
|
|
2270
|
+
this.queue = [];
|
|
2271
|
+
if (this.timer) clearInterval(this.timer);
|
|
2272
|
+
this.timer = null;
|
|
2273
|
+
}
|
|
2274
|
+
// ── internals ──────────────────────────────────────────────────────────────
|
|
2275
|
+
requeue(events) {
|
|
2276
|
+
if (this.stopped) return;
|
|
2277
|
+
this.queue = [...events, ...this.queue].slice(-MAX_QUEUE);
|
|
2278
|
+
}
|
|
2279
|
+
session() {
|
|
2280
|
+
const now = Date.now();
|
|
2281
|
+
let s = null;
|
|
2282
|
+
try {
|
|
2283
|
+
const raw = this.deps.store.getSync(SESSION_KEY);
|
|
2284
|
+
s = raw ? JSON.parse(raw) : null;
|
|
2285
|
+
} catch {
|
|
2286
|
+
s = null;
|
|
2287
|
+
}
|
|
2288
|
+
if (!s || typeof s.id !== "string" || typeof s.last !== "number" || now - s.last > SESSION_IDLE_MS) {
|
|
2289
|
+
s = { id: newId(), last: now, src: landingSource(location.href, document.referrer) };
|
|
2290
|
+
} else {
|
|
2291
|
+
s.last = now;
|
|
2292
|
+
}
|
|
2293
|
+
try {
|
|
2294
|
+
this.deps.store.setSync(SESSION_KEY, JSON.stringify(s));
|
|
2295
|
+
} catch {
|
|
2296
|
+
}
|
|
2297
|
+
return s;
|
|
2298
|
+
}
|
|
2299
|
+
enqueue(e) {
|
|
2300
|
+
var _a, _b;
|
|
2301
|
+
if (this.stopped) return;
|
|
2302
|
+
const s = this.session();
|
|
2303
|
+
const title = typeof document.title === "string" && document.title ? document.title.slice(0, 200) : void 0;
|
|
2304
|
+
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 } : {} });
|
|
2305
|
+
if (this.queue.length > MAX_QUEUE) this.queue.shift();
|
|
2306
|
+
if (this.queue.length >= FLUSH_AT) this.flush(false);
|
|
2307
|
+
}
|
|
2308
|
+
leave() {
|
|
2309
|
+
this.sendScroll();
|
|
2310
|
+
this.flush(true);
|
|
2311
|
+
}
|
|
2312
|
+
/** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
|
|
2313
|
+
watchRoutes() {
|
|
2314
|
+
if (typeof history === "undefined") return;
|
|
2315
|
+
const after = () => {
|
|
2316
|
+
setTimeout(() => this.pageview(), 0);
|
|
2317
|
+
};
|
|
2318
|
+
for (const method of ["pushState", "replaceState"]) {
|
|
2319
|
+
const original = history[method];
|
|
2320
|
+
if (typeof original !== "function") continue;
|
|
2321
|
+
history[method] = function(...args) {
|
|
2322
|
+
const out = original.apply(this, args);
|
|
2323
|
+
after();
|
|
2324
|
+
return out;
|
|
2325
|
+
};
|
|
2326
|
+
}
|
|
2327
|
+
window.addEventListener("popstate", after);
|
|
2328
|
+
}
|
|
2329
|
+
onScroll() {
|
|
2330
|
+
var _a;
|
|
2331
|
+
if (typeof document.documentElement === "undefined" || !document.documentElement) return;
|
|
2332
|
+
const doc2 = document.documentElement;
|
|
2333
|
+
const viewport = window.innerHeight || doc2.clientHeight || 0;
|
|
2334
|
+
const height = Math.max(doc2.scrollHeight || 0, ((_a = document.body) == null ? void 0 : _a.scrollHeight) || 0);
|
|
2335
|
+
if (!height) return;
|
|
2336
|
+
const seen = height <= viewport ? 1 : Math.min(1, ((window.scrollY || doc2.scrollTop || 0) + viewport) / height);
|
|
2337
|
+
const pct = Math.round(seen * 100);
|
|
2338
|
+
for (const step of SCROLL_STEPS) if (pct >= step && step > this.maxScroll) this.maxScroll = step;
|
|
2339
|
+
}
|
|
2340
|
+
sendScroll() {
|
|
2341
|
+
if (this.deps.options.scroll === false || !this.scrollUrl || this.maxScroll < 25) return;
|
|
2342
|
+
this.enqueue({ kind: "scroll", url: this.scrollUrl, props: { depth: this.maxScroll } });
|
|
2343
|
+
this.scrollUrl = null;
|
|
2344
|
+
this.maxScroll = 0;
|
|
2345
|
+
}
|
|
2346
|
+
onClick(e) {
|
|
2347
|
+
const target = e.target;
|
|
2348
|
+
const el = target && typeof target.closest === "function" ? target.closest("a, button, [role='button'], input[type='submit'], input[type='button']") : null;
|
|
2349
|
+
if (!el || el.closest("[data-traqio-ignore]")) return;
|
|
2350
|
+
const input = el;
|
|
2351
|
+
const text = (el.tagName === "INPUT" ? input.value : el.innerText || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
|
|
2352
|
+
const href = el.tagName === "A" ? bare2(el.getAttribute("href")) : void 0;
|
|
2353
|
+
const props = { tag: el.tagName.toLowerCase() };
|
|
2354
|
+
if (text) props.text = text;
|
|
2355
|
+
if (href) props.href = href;
|
|
2356
|
+
if (el.id) props.id = el.id.slice(0, 100);
|
|
2357
|
+
this.enqueue({ kind: "click", props });
|
|
2358
|
+
}
|
|
2359
|
+
onError(e) {
|
|
2360
|
+
if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
|
|
2361
|
+
const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
|
|
2362
|
+
this.errorsThisPage++;
|
|
2363
|
+
const stack = e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack.slice(0, 1500) : void 0;
|
|
2364
|
+
this.enqueue({ kind: "error", props: { message, ...stack ? { stack } : {}, ...e.filename ? { source: bare2(e.filename) } : {}, ...e.lineno ? { line: e.lineno } : {} } });
|
|
2365
|
+
}
|
|
2366
|
+
onRejection(e) {
|
|
2367
|
+
if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
|
|
2368
|
+
const reason = e.reason;
|
|
2369
|
+
const message = (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection").slice(0, 300);
|
|
2370
|
+
this.errorsThisPage++;
|
|
2371
|
+
const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack.slice(0, 1500) : void 0;
|
|
2372
|
+
this.enqueue({ kind: "error", props: { message, unhandledRejection: true, ...stack ? { stack } : {} } });
|
|
2373
|
+
}
|
|
2374
|
+
};
|
|
2375
|
+
|
|
2088
2376
|
// src/index.ts
|
|
2089
2377
|
var DEFAULT_ENDPOINT = "https://api.traqio.app";
|
|
2090
2378
|
var DEFAULT_TRACK_ID_DAYS = 30;
|
|
@@ -2107,6 +2395,11 @@ var TraqioWeb = class {
|
|
|
2107
2395
|
this.sources = null;
|
|
2108
2396
|
this.waitForConsent = false;
|
|
2109
2397
|
this.started = false;
|
|
2398
|
+
this.analytics = null;
|
|
2399
|
+
/** `capture()` calls made before `init()` finished — replayed once the tracker exists. */
|
|
2400
|
+
this.earlyCaptures = [];
|
|
2401
|
+
/** `init()` has finished (or will never run here): early captures are no longer kept. */
|
|
2402
|
+
this.ready = false;
|
|
2110
2403
|
}
|
|
2111
2404
|
/**
|
|
2112
2405
|
* Call once, as early as possible on every page (or once in a single-page app).
|
|
@@ -2134,9 +2427,11 @@ var TraqioWeb = class {
|
|
|
2134
2427
|
const id = randomId();
|
|
2135
2428
|
if (id) this.store.setSync(DEVICE_ID_KEY, id);
|
|
2136
2429
|
}
|
|
2430
|
+
this.userId = opts.userId;
|
|
2431
|
+
const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
2137
2432
|
await this.core.init({
|
|
2138
2433
|
sdkKey: opts.sdkKey,
|
|
2139
|
-
endpoint
|
|
2434
|
+
endpoint,
|
|
2140
2435
|
storage: this.store,
|
|
2141
2436
|
platform: "web",
|
|
2142
2437
|
userId: opts.userId,
|
|
@@ -2147,6 +2442,23 @@ var TraqioWeb = class {
|
|
|
2147
2442
|
window.addEventListener("pagehide", background);
|
|
2148
2443
|
}
|
|
2149
2444
|
});
|
|
2445
|
+
if (opts.analytics) {
|
|
2446
|
+
const store = this.store;
|
|
2447
|
+
this.analytics = new AnalyticsTracker({
|
|
2448
|
+
store,
|
|
2449
|
+
endpoint,
|
|
2450
|
+
sdkKey: opts.sdkKey,
|
|
2451
|
+
anonymousId: () => store.getSync(DEVICE_ID_KEY),
|
|
2452
|
+
userId: () => this.userId,
|
|
2453
|
+
isDebug: () => this.core.isDebug,
|
|
2454
|
+
isForgotten: () => this.core.forgotten,
|
|
2455
|
+
options: opts.analytics === true ? {} : opts.analytics
|
|
2456
|
+
});
|
|
2457
|
+
this.analytics.start();
|
|
2458
|
+
for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
|
|
2459
|
+
}
|
|
2460
|
+
this.earlyCaptures = [];
|
|
2461
|
+
this.ready = true;
|
|
2150
2462
|
}
|
|
2151
2463
|
/** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
|
|
2152
2464
|
get isDebug() {
|
|
@@ -2156,8 +2468,27 @@ var TraqioWeb = class {
|
|
|
2156
2468
|
track(name, props) {
|
|
2157
2469
|
this.core.track(name, props);
|
|
2158
2470
|
}
|
|
2471
|
+
/**
|
|
2472
|
+
* A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
|
|
2473
|
+
* console's Analytics section (events, funnels). NOT a conversion: it is never
|
|
2474
|
+
* billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
|
|
2475
|
+
* Needs `analytics` at init; names starting with `$` are reserved.
|
|
2476
|
+
*/
|
|
2477
|
+
capture(name, props) {
|
|
2478
|
+
if (this.analytics) this.analytics.capture(name, props);
|
|
2479
|
+
else if (!this.ready && this.earlyCaptures.length < 50) this.earlyCaptures.push([name, props]);
|
|
2480
|
+
}
|
|
2481
|
+
/**
|
|
2482
|
+
* Record a page view now. Not needed with the history API (route changes are
|
|
2483
|
+
* caught by themselves); for a router that changes the page another way.
|
|
2484
|
+
*/
|
|
2485
|
+
pageview() {
|
|
2486
|
+
var _a;
|
|
2487
|
+
(_a = this.analytics) == null ? void 0 : _a.pageview();
|
|
2488
|
+
}
|
|
2159
2489
|
/** Set the user id once known (after sign-in). */
|
|
2160
2490
|
setUserId(id) {
|
|
2491
|
+
this.userId = id;
|
|
2161
2492
|
this.core.setUserId(id);
|
|
2162
2493
|
}
|
|
2163
2494
|
/**
|
|
@@ -2206,17 +2537,20 @@ var TraqioWeb = class {
|
|
|
2206
2537
|
* Resolves false when the request did not reach the server — then nothing changed.
|
|
2207
2538
|
*/
|
|
2208
2539
|
async forgetMe() {
|
|
2209
|
-
var _a, _b;
|
|
2540
|
+
var _a, _b, _c;
|
|
2210
2541
|
const ok = await this.core.forgetMe();
|
|
2211
2542
|
if (ok) {
|
|
2212
2543
|
(_a = this.trackIds) == null ? void 0 : _a.clear();
|
|
2213
2544
|
(_b = this.sources) == null ? void 0 : _b.clear();
|
|
2545
|
+
(_c = this.analytics) == null ? void 0 : _c.stop();
|
|
2214
2546
|
}
|
|
2215
2547
|
return ok;
|
|
2216
2548
|
}
|
|
2217
2549
|
/** Send what is queued now. Already wired to tab hide and page exit. */
|
|
2218
2550
|
flush() {
|
|
2551
|
+
var _a;
|
|
2219
2552
|
this.core.flush();
|
|
2553
|
+
(_a = this.analytics) == null ? void 0 : _a.flush(false);
|
|
2220
2554
|
}
|
|
2221
2555
|
/** True once `forgetMe()` has been honoured: this browser sends nothing any more. */
|
|
2222
2556
|
get forgotten() {
|