@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 CHANGED
@@ -101,6 +101,31 @@ because a browser and a signed-in user are not tied together yet.
101
101
  Events are batched, retried, kept across page loads, and flushed when the tab is
102
102
  hidden or the page is left.
103
103
 
104
+ ## Product analytics
105
+
106
+ Page views, traffic sources, clicks, scroll depth, front-end errors and your own
107
+ analytics events — read in the console's **Analytics** section (and through the API /
108
+ MCP). Off by default:
109
+
110
+ ```ts
111
+ Traqio.init({ sdkKey: "YOUR_WEB_KEY", analytics: true });
112
+ // or pick: analytics: { pageviews: true, clicks: true, scroll: true, errors: false }
113
+
114
+ Traqio.capture("search_performed", { results: 12 }); // an analytics event, for events and funnels
115
+ ```
116
+
117
+ - **Page views** are recorded on load and on every client-side route change (the history
118
+ API), so single-page apps need nothing more. `Traqio.pageview()` records one by hand.
119
+ - **The source** of a visit — `utm_*`, `gclid`/`fbclid`/`ttclid`, the referring site — is
120
+ read once per session (30 minutes of inactivity end one).
121
+ - **Clicks** record a link's or a button's visible text and link, never what was typed.
122
+ Add `data-traqio-ignore` to an element to leave it out.
123
+ - URLs are stored **without their query string**: tokens and emails live there.
124
+
125
+ **`capture()` is not `track()`.** An analytics event is never billed, never counted as a
126
+ conversion and never sent to an ad network — it has its own route and its own table.
127
+ A sign-up or a purchase stays `track()` (or your backend's server SDK).
128
+
104
129
  ## Frameworks
105
130
 
106
131
  - **React / Next.js** — call `init()` in a `useEffect` of a client component mounted
@@ -137,6 +162,7 @@ networks.
137
162
  | `trackIdDays` | `30` | How long the trackID and the visit's source are kept |
138
163
  | `cookies` | `true` | `false` = localStorage only, no sharing across subdomains |
139
164
  | `debug` | detected | Debug traffic, kept out of every report (see below) |
165
+ | `analytics` | `false` | Product analytics: `true`, or `{ pageviews, clicks, scroll, errors }` |
140
166
 
141
167
  **Debug traffic.** Omitted, `debug` is on for a page served from `localhost`, `127.0.0.1`, `*.localhost`, `*.local` or `file:`, and off everywhere else; `true` forces it (a staging site), `false` counts a local page. `traqio.isDebug` tells which mode is on. Debug traffic shows in the console's **Live events › Debug** view, but it is never counted in a report, attributed, sent to an ad network or a webhook, or billed.
142
168
 
@@ -0,0 +1,73 @@
1
+ import type { KeyValueStore } from "@traqio/core";
2
+ export interface AnalyticsOptions {
3
+ /** A page view on load and on every client-side route change (history API). Default true. */
4
+ pageviews?: boolean;
5
+ /** Clicks on links and buttons: their text and link. Default true. */
6
+ clicks?: boolean;
7
+ /** The deepest of 25/50/75/100 % each page view reached, sent once per page view. Default true. */
8
+ scroll?: boolean;
9
+ /** Uncaught errors and unhandled promise rejections. Default true. */
10
+ errors?: boolean;
11
+ }
12
+ /** Where the SESSION landed from — copied on each of its events (the server stores it per row). */
13
+ export interface SessionSource {
14
+ utmSource?: string;
15
+ utmMedium?: string;
16
+ utmCampaign?: string;
17
+ utmContent?: string;
18
+ utmTerm?: string;
19
+ referrer?: string;
20
+ gclid?: string;
21
+ fbclid?: string;
22
+ ttclid?: string;
23
+ }
24
+ export interface AnalyticsDeps {
25
+ store: KeyValueStore & {
26
+ getSync(key: string): string | null;
27
+ setSync(key: string, value: string): void;
28
+ };
29
+ endpoint: string;
30
+ sdkKey: string;
31
+ anonymousId: () => string | null;
32
+ userId: () => string | undefined;
33
+ isDebug: () => boolean;
34
+ isForgotten: () => boolean;
35
+ options: AnalyticsOptions;
36
+ }
37
+ export declare const SESSION_KEY = "traq_session";
38
+ /** 30 minutes without activity end a session — the convention PostHog and GA share. */
39
+ export declare const SESSION_IDLE_MS: number;
40
+ /** The landing's source: the URL's utm_* and click ids, and the referrer when it is another site. */
41
+ export declare function landingSource(href: string, referrer: string): SessionSource | undefined;
42
+ export declare class AnalyticsTracker {
43
+ private readonly deps;
44
+ private queue;
45
+ private timer;
46
+ private lastPath;
47
+ private maxScroll;
48
+ private scrollUrl;
49
+ private errorsThisPage;
50
+ private stopped;
51
+ constructor(deps: AnalyticsDeps);
52
+ /** Wires the listeners the options ask for and records the first page view. */
53
+ start(): void;
54
+ /** A custom analytics event — never a conversion (that is `track()`). */
55
+ capture(name: string, props?: Record<string, unknown>): void;
56
+ /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
57
+ pageview(): void;
58
+ /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
59
+ flush(leaving: boolean): void;
60
+ /** Forget everything and stop: after `forgetMe()`, or on a server. */
61
+ stop(): void;
62
+ private requeue;
63
+ private session;
64
+ private enqueue;
65
+ private leave;
66
+ /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
67
+ private watchRoutes;
68
+ private onScroll;
69
+ private sendScroll;
70
+ private onClick;
71
+ private onError;
72
+ private onRejection;
73
+ }
package/build/index.cjs CHANGED
@@ -641,7 +641,7 @@ var require_build = __commonJS({
641
641
  var adservices_1 = require_adservices();
642
642
  var deeplink_1 = require_deeplink();
643
643
  var adRevenue_1 = require_adRevenue();
644
- exports.SDK_VERSION = "0.5.1";
644
+ exports.SDK_VERSION = "0.6.0";
645
645
  var skan_2 = require_skan();
646
646
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
647
647
  return skan_2.Skan;
@@ -697,6 +697,9 @@ var require_build = __commonJS({
697
697
  var INSTALL_SENT_KEY = "traq_install_sent";
698
698
  var INSTALL_SENT_DEBUG_KEY = "traq_install_sent_debug";
699
699
  var INSTALL_ATTEMPTS_KEY = "traq_install_attempts";
700
+ var AD_ID_SENT_KEY = "traq_ad_id_sent";
701
+ var AD_ID_SENT_DEBUG_KEY = "traq_ad_id_sent_debug";
702
+ var AD_ID_PATH = "/ingest/advertising-id";
700
703
  var REFERRER_KEY = "traq_referrer";
701
704
  var QUEUE_KEY = "traq_queue";
702
705
  var AD_QUEUE_KEY = "traq_ad_queue";
@@ -709,7 +712,7 @@ var require_build = __commonJS({
709
712
  var CONSENT_KEY = "traq_consent";
710
713
  var MAX_BATCH = 20;
711
714
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
712
- var MAX_QUEUE = 500;
715
+ var MAX_QUEUE2 = 500;
713
716
  var MAX_AD_BATCH = 100;
714
717
  var MAX_AD_QUEUE = 1e3;
715
718
  var BASE_RETRY_MS = 1e3;
@@ -816,6 +819,7 @@ var require_build = __commonJS({
816
819
  this.deferred = null;
817
820
  this.consent = null;
818
821
  this.att = null;
822
+ this.adIdSync = null;
819
823
  this.debug = false;
820
824
  this.maxRevenuePaid = (adInfo) => {
821
825
  try {
@@ -850,6 +854,7 @@ var require_build = __commonJS({
850
854
  if (!this.isWeb) {
851
855
  const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
852
856
  await this.sendInstallOnce();
857
+ void this.syncAdvertisingId();
853
858
  if (this.opts.deepLinking !== false) {
854
859
  this.deferred = this.resolveDeferredOnce(freshInstall).then((link) => link != null ? link : this.retryDeferredWithConsent());
855
860
  this.wireDeepLinks();
@@ -1152,6 +1157,7 @@ var require_build = __commonJS({
1152
1157
  if (!this.started || this.erased)
1153
1158
  return;
1154
1159
  void this.maybeStartSession();
1160
+ void this.syncAdvertisingId();
1155
1161
  }
1156
1162
  /** The conversion-value mapping in force on this device, once fetched. */
1157
1163
  get skanMapping() {
@@ -1316,6 +1322,9 @@ var require_build = __commonJS({
1316
1322
  get installSentKey() {
1317
1323
  return this.debug ? INSTALL_SENT_DEBUG_KEY : INSTALL_SENT_KEY;
1318
1324
  }
1325
+ get adIdSentKey() {
1326
+ return this.debug ? AD_ID_SENT_DEBUG_KEY : AD_ID_SENT_KEY;
1327
+ }
1319
1328
  /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */
1320
1329
  debugField() {
1321
1330
  return this.debug ? { debug: true } : {};
@@ -1339,6 +1348,7 @@ var require_build = __commonJS({
1339
1348
  return;
1340
1349
  }
1341
1350
  void this.maybeStartSession();
1351
+ void this.syncAdvertisingId();
1342
1352
  });
1343
1353
  } catch {
1344
1354
  }
@@ -1374,8 +1384,8 @@ var require_build = __commonJS({
1374
1384
  }
1375
1385
  enqueue(e) {
1376
1386
  this.queue.push(e);
1377
- if (this.queue.length > MAX_QUEUE)
1378
- this.queue.splice(0, this.queue.length - MAX_QUEUE);
1387
+ if (this.queue.length > MAX_QUEUE2)
1388
+ this.queue.splice(0, this.queue.length - MAX_QUEUE2);
1379
1389
  void this.persistQueue();
1380
1390
  this.scheduleFlush();
1381
1391
  }
@@ -1548,17 +1558,56 @@ var require_build = __commonJS({
1548
1558
  return;
1549
1559
  }
1550
1560
  }
1561
+ const advertisingId = await this.readAdvertisingId();
1551
1562
  const ok = await this.post({
1552
1563
  install: {
1553
1564
  platform,
1554
1565
  installReferrer: referrer.referrer,
1555
1566
  appUserId: this.opts.userId,
1556
- advertisingId: await this.readAdvertisingId(),
1567
+ advertisingId,
1557
1568
  context: this.context
1558
1569
  }
1559
1570
  });
1560
- if (ok)
1571
+ if (ok) {
1561
1572
  await (store == null ? void 0 : store.setItem(this.installSentKey, "1"));
1573
+ if (advertisingId)
1574
+ await (store == null ? void 0 : store.setItem(this.adIdSentKey, advertisingId).catch(() => void 0));
1575
+ }
1576
+ }
1577
+ /**
1578
+ * The opted-in advertising id the install could not carry (todo cmwlauev). The
1579
+ * install leaves at first launch, before an app shows its own ATT prompt, so on iOS
1580
+ * it almost never has the IDFA. Re-read at every start and foreground — reading
1581
+ * never prompts (decision cmvjohk6) — and posted ONCE when it differs from the one
1582
+ * the server last acknowledged; a failure is retried at the next foreground.
1583
+ *
1584
+ * Only after the install is reported: the install itself carries an id it can read.
1585
+ */
1586
+ syncAdvertisingId() {
1587
+ if (this.adIdSync)
1588
+ return this.adIdSync;
1589
+ this.adIdSync = this.postAdvertisingIdIfChanged().finally(() => {
1590
+ this.adIdSync = null;
1591
+ });
1592
+ return this.adIdSync;
1593
+ }
1594
+ async postAdvertisingIdIfChanged() {
1595
+ var _a;
1596
+ const store = this.opts.storage;
1597
+ if (this.isWeb || this.erased || !store || !this.opts.collectAdvertisingId)
1598
+ return;
1599
+ try {
1600
+ if (!await store.getItem(this.installSentKey))
1601
+ return;
1602
+ const advertisingId = await this.readAdvertisingId();
1603
+ if (!advertisingId || await store.getItem(this.adIdSentKey) === advertisingId)
1604
+ return;
1605
+ const deviceId = (_a = this.context.deviceId) != null ? _a : await this.getOrCreateDeviceId();
1606
+ if (await this.post({ deviceId, appUserId: this.opts.userId, advertisingId }, AD_ID_PATH)) {
1607
+ await store.setItem(this.adIdSentKey, advertisingId);
1608
+ }
1609
+ } catch {
1610
+ }
1562
1611
  }
1563
1612
  scheduleFlush(delay = FLUSH_DELAY_MS) {
1564
1613
  if (this.flushTimer)
@@ -1688,8 +1737,8 @@ var require_build = __commonJS({
1688
1737
  * key fixed in the console makes the same queued batch succeed.
1689
1738
  */
1690
1739
  async send(body, path = "/ingest") {
1691
- const consent = this.consent && (path === "/ingest" || path === "/ingest/session") ? { consent: this.consent } : {};
1692
- const att = path === "/ingest" && this.asksTrackingAuthorization ? await this.readTrackingAuthorization() : null;
1740
+ const consent = this.consent && (path === "/ingest" || path === "/ingest/session" || path === AD_ID_PATH) ? { consent: this.consent } : {};
1741
+ const att = (path === "/ingest" || path === AD_ID_PATH) && this.asksTrackingAuthorization ? await this.readTrackingAuthorization() : null;
1693
1742
  try {
1694
1743
  const res = await fetch(`${this.opts.endpoint}${path}`, {
1695
1744
  method: "POST",
@@ -2097,6 +2146,245 @@ var TrackIdKeeper = class {
2097
2146
  }
2098
2147
  };
2099
2148
 
2149
+ // src/analytics.ts
2150
+ var SESSION_KEY = "traq_session";
2151
+ var SESSION_IDLE_MS = 30 * 60 * 1e3;
2152
+ var FLUSH_EVERY_MS = 5e3;
2153
+ var FLUSH_AT = 20;
2154
+ var MAX_QUEUE = 200;
2155
+ var MAX_ERRORS_PER_PAGE = 10;
2156
+ var SCROLL_STEPS = [25, 50, 75, 100];
2157
+ var UTM = [
2158
+ ["utm_source", "utmSource"],
2159
+ ["utm_medium", "utmMedium"],
2160
+ ["utm_campaign", "utmCampaign"],
2161
+ ["utm_content", "utmContent"],
2162
+ ["utm_term", "utmTerm"],
2163
+ ["gclid", "gclid"],
2164
+ ["fbclid", "fbclid"],
2165
+ ["ttclid", "ttclid"]
2166
+ ];
2167
+ function newId() {
2168
+ try {
2169
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
2170
+ } catch {
2171
+ }
2172
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
2173
+ }
2174
+ function landingSource(href, referrer) {
2175
+ var _a;
2176
+ const src = {};
2177
+ try {
2178
+ const u = new URL(href);
2179
+ for (const [param, key] of UTM) {
2180
+ const v = (_a = u.searchParams.get(param)) == null ? void 0 : _a.trim();
2181
+ if (v) src[key] = v.slice(0, 200);
2182
+ }
2183
+ if (referrer) {
2184
+ const r = new URL(referrer);
2185
+ if (r.hostname.replace(/^www\./, "") !== u.hostname.replace(/^www\./, "")) src.referrer = `${r.protocol}//${r.host}/`;
2186
+ }
2187
+ } catch {
2188
+ }
2189
+ return Object.keys(src).length ? src : void 0;
2190
+ }
2191
+ function bare2(href) {
2192
+ if (!href) return void 0;
2193
+ try {
2194
+ const u = new URL(href, typeof location !== "undefined" ? location.href : void 0);
2195
+ if (u.protocol !== "http:" && u.protocol !== "https:") return void 0;
2196
+ return `${u.origin}${u.pathname}`;
2197
+ } catch {
2198
+ return void 0;
2199
+ }
2200
+ }
2201
+ var AnalyticsTracker = class {
2202
+ constructor(deps) {
2203
+ this.deps = deps;
2204
+ this.queue = [];
2205
+ this.timer = null;
2206
+ this.lastPath = null;
2207
+ this.maxScroll = 0;
2208
+ this.scrollUrl = null;
2209
+ this.errorsThisPage = 0;
2210
+ this.stopped = false;
2211
+ }
2212
+ /** Wires the listeners the options ask for and records the first page view. */
2213
+ start() {
2214
+ const o = this.deps.options;
2215
+ this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);
2216
+ document.addEventListener("visibilitychange", () => {
2217
+ if (document.visibilityState === "hidden") this.leave();
2218
+ });
2219
+ window.addEventListener("pagehide", () => this.leave());
2220
+ if (o.pageviews !== false) {
2221
+ this.pageview();
2222
+ this.watchRoutes();
2223
+ }
2224
+ if (o.clicks !== false) document.addEventListener("click", (e) => this.onClick(e), true);
2225
+ if (o.scroll !== false) window.addEventListener("scroll", () => this.onScroll(), { passive: true });
2226
+ if (o.errors !== false) {
2227
+ window.addEventListener("error", (e) => this.onError(e));
2228
+ window.addEventListener("unhandledrejection", (e) => this.onRejection(e));
2229
+ }
2230
+ }
2231
+ /** A custom analytics event — never a conversion (that is `track()`). */
2232
+ capture(name, props) {
2233
+ if (typeof name !== "string" || !name.trim() || name.startsWith("$")) return;
2234
+ this.enqueue({ kind: "custom", name: name.trim(), props });
2235
+ }
2236
+ /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
2237
+ pageview() {
2238
+ const url = bare2(location.href);
2239
+ if (!url) return;
2240
+ if (url === this.lastPath) return;
2241
+ this.sendScroll();
2242
+ this.lastPath = url;
2243
+ this.scrollUrl = url;
2244
+ this.maxScroll = 0;
2245
+ this.errorsThisPage = 0;
2246
+ this.enqueue({ kind: "pageview" });
2247
+ this.onScroll();
2248
+ }
2249
+ /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
2250
+ flush(leaving) {
2251
+ if (!this.queue.length || this.stopped) return;
2252
+ if (this.deps.isForgotten()) {
2253
+ this.stop();
2254
+ return;
2255
+ }
2256
+ const anonymousId = this.deps.anonymousId();
2257
+ if (!anonymousId) return;
2258
+ const events = this.queue.splice(0, 100);
2259
+ const body = JSON.stringify({
2260
+ sdkKey: this.deps.sdkKey,
2261
+ anonymousId,
2262
+ userId: this.deps.userId(),
2263
+ debug: this.deps.isDebug() || void 0,
2264
+ events
2265
+ });
2266
+ try {
2267
+ void fetch(`${this.deps.endpoint}/ingest/analytics`, {
2268
+ method: "POST",
2269
+ headers: { "content-type": "application/json" },
2270
+ body,
2271
+ keepalive: leaving
2272
+ }).then((res) => {
2273
+ if (!res.ok && (res.status >= 500 || res.status === 429)) this.requeue(events);
2274
+ }).catch(() => this.requeue(events));
2275
+ } catch {
2276
+ this.requeue(events);
2277
+ }
2278
+ }
2279
+ /** Forget everything and stop: after `forgetMe()`, or on a server. */
2280
+ stop() {
2281
+ this.stopped = true;
2282
+ this.queue = [];
2283
+ if (this.timer) clearInterval(this.timer);
2284
+ this.timer = null;
2285
+ }
2286
+ // ── internals ──────────────────────────────────────────────────────────────
2287
+ requeue(events) {
2288
+ if (this.stopped) return;
2289
+ this.queue = [...events, ...this.queue].slice(-MAX_QUEUE);
2290
+ }
2291
+ session() {
2292
+ const now = Date.now();
2293
+ let s = null;
2294
+ try {
2295
+ const raw = this.deps.store.getSync(SESSION_KEY);
2296
+ s = raw ? JSON.parse(raw) : null;
2297
+ } catch {
2298
+ s = null;
2299
+ }
2300
+ if (!s || typeof s.id !== "string" || typeof s.last !== "number" || now - s.last > SESSION_IDLE_MS) {
2301
+ s = { id: newId(), last: now, src: landingSource(location.href, document.referrer) };
2302
+ } else {
2303
+ s.last = now;
2304
+ }
2305
+ try {
2306
+ this.deps.store.setSync(SESSION_KEY, JSON.stringify(s));
2307
+ } catch {
2308
+ }
2309
+ return s;
2310
+ }
2311
+ enqueue(e) {
2312
+ var _a, _b;
2313
+ if (this.stopped) return;
2314
+ const s = this.session();
2315
+ const title = typeof document.title === "string" && document.title ? document.title.slice(0, 200) : void 0;
2316
+ 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 } : {} });
2317
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
2318
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
2319
+ }
2320
+ leave() {
2321
+ this.sendScroll();
2322
+ this.flush(true);
2323
+ }
2324
+ /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
2325
+ watchRoutes() {
2326
+ if (typeof history === "undefined") return;
2327
+ const after = () => {
2328
+ setTimeout(() => this.pageview(), 0);
2329
+ };
2330
+ for (const method of ["pushState", "replaceState"]) {
2331
+ const original = history[method];
2332
+ if (typeof original !== "function") continue;
2333
+ history[method] = function(...args) {
2334
+ const out = original.apply(this, args);
2335
+ after();
2336
+ return out;
2337
+ };
2338
+ }
2339
+ window.addEventListener("popstate", after);
2340
+ }
2341
+ onScroll() {
2342
+ var _a;
2343
+ if (typeof document.documentElement === "undefined" || !document.documentElement) return;
2344
+ const doc2 = document.documentElement;
2345
+ const viewport = window.innerHeight || doc2.clientHeight || 0;
2346
+ const height = Math.max(doc2.scrollHeight || 0, ((_a = document.body) == null ? void 0 : _a.scrollHeight) || 0);
2347
+ if (!height) return;
2348
+ const seen = height <= viewport ? 1 : Math.min(1, ((window.scrollY || doc2.scrollTop || 0) + viewport) / height);
2349
+ const pct = Math.round(seen * 100);
2350
+ for (const step of SCROLL_STEPS) if (pct >= step && step > this.maxScroll) this.maxScroll = step;
2351
+ }
2352
+ sendScroll() {
2353
+ if (this.deps.options.scroll === false || !this.scrollUrl || this.maxScroll < 25) return;
2354
+ this.enqueue({ kind: "scroll", url: this.scrollUrl, props: { depth: this.maxScroll } });
2355
+ this.scrollUrl = null;
2356
+ this.maxScroll = 0;
2357
+ }
2358
+ onClick(e) {
2359
+ const target = e.target;
2360
+ const el = target && typeof target.closest === "function" ? target.closest("a, button, [role='button'], input[type='submit'], input[type='button']") : null;
2361
+ if (!el || el.closest("[data-traqio-ignore]")) return;
2362
+ const input = el;
2363
+ const text = (el.tagName === "INPUT" ? input.value : el.innerText || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
2364
+ const href = el.tagName === "A" ? bare2(el.getAttribute("href")) : void 0;
2365
+ const props = { tag: el.tagName.toLowerCase() };
2366
+ if (text) props.text = text;
2367
+ if (href) props.href = href;
2368
+ if (el.id) props.id = el.id.slice(0, 100);
2369
+ this.enqueue({ kind: "click", props });
2370
+ }
2371
+ onError(e) {
2372
+ if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
2373
+ const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
2374
+ this.errorsThisPage++;
2375
+ const stack = e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack.slice(0, 1500) : void 0;
2376
+ this.enqueue({ kind: "error", props: { message, ...stack ? { stack } : {}, ...e.filename ? { source: bare2(e.filename) } : {}, ...e.lineno ? { line: e.lineno } : {} } });
2377
+ }
2378
+ onRejection(e) {
2379
+ if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
2380
+ const reason = e.reason;
2381
+ const message = (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection").slice(0, 300);
2382
+ this.errorsThisPage++;
2383
+ const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack.slice(0, 1500) : void 0;
2384
+ this.enqueue({ kind: "error", props: { message, unhandledRejection: true, ...stack ? { stack } : {} } });
2385
+ }
2386
+ };
2387
+
2100
2388
  // src/index.ts
2101
2389
  var DEFAULT_ENDPOINT = "https://api.traqio.app";
2102
2390
  var DEFAULT_TRACK_ID_DAYS = 30;
@@ -2119,6 +2407,11 @@ var TraqioWeb = class {
2119
2407
  this.sources = null;
2120
2408
  this.waitForConsent = false;
2121
2409
  this.started = false;
2410
+ this.analytics = null;
2411
+ /** `capture()` calls made before `init()` finished — replayed once the tracker exists. */
2412
+ this.earlyCaptures = [];
2413
+ /** `init()` has finished (or will never run here): early captures are no longer kept. */
2414
+ this.ready = false;
2122
2415
  }
2123
2416
  /**
2124
2417
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -2146,9 +2439,11 @@ var TraqioWeb = class {
2146
2439
  const id = randomId();
2147
2440
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
2148
2441
  }
2442
+ this.userId = opts.userId;
2443
+ const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
2149
2444
  await this.core.init({
2150
2445
  sdkKey: opts.sdkKey,
2151
- endpoint: ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, ""),
2446
+ endpoint,
2152
2447
  storage: this.store,
2153
2448
  platform: "web",
2154
2449
  userId: opts.userId,
@@ -2159,6 +2454,23 @@ var TraqioWeb = class {
2159
2454
  window.addEventListener("pagehide", background);
2160
2455
  }
2161
2456
  });
2457
+ if (opts.analytics) {
2458
+ const store = this.store;
2459
+ this.analytics = new AnalyticsTracker({
2460
+ store,
2461
+ endpoint,
2462
+ sdkKey: opts.sdkKey,
2463
+ anonymousId: () => store.getSync(DEVICE_ID_KEY),
2464
+ userId: () => this.userId,
2465
+ isDebug: () => this.core.isDebug,
2466
+ isForgotten: () => this.core.forgotten,
2467
+ options: opts.analytics === true ? {} : opts.analytics
2468
+ });
2469
+ this.analytics.start();
2470
+ for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
2471
+ }
2472
+ this.earlyCaptures = [];
2473
+ this.ready = true;
2162
2474
  }
2163
2475
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
2164
2476
  get isDebug() {
@@ -2168,8 +2480,27 @@ var TraqioWeb = class {
2168
2480
  track(name, props) {
2169
2481
  this.core.track(name, props);
2170
2482
  }
2483
+ /**
2484
+ * A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
2485
+ * console's Analytics section (events, funnels). NOT a conversion: it is never
2486
+ * billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
2487
+ * Needs `analytics` at init; names starting with `$` are reserved.
2488
+ */
2489
+ capture(name, props) {
2490
+ if (this.analytics) this.analytics.capture(name, props);
2491
+ else if (!this.ready && this.earlyCaptures.length < 50) this.earlyCaptures.push([name, props]);
2492
+ }
2493
+ /**
2494
+ * Record a page view now. Not needed with the history API (route changes are
2495
+ * caught by themselves); for a router that changes the page another way.
2496
+ */
2497
+ pageview() {
2498
+ var _a;
2499
+ (_a = this.analytics) == null ? void 0 : _a.pageview();
2500
+ }
2171
2501
  /** Set the user id once known (after sign-in). */
2172
2502
  setUserId(id) {
2503
+ this.userId = id;
2173
2504
  this.core.setUserId(id);
2174
2505
  }
2175
2506
  /**
@@ -2218,17 +2549,20 @@ var TraqioWeb = class {
2218
2549
  * Resolves false when the request did not reach the server — then nothing changed.
2219
2550
  */
2220
2551
  async forgetMe() {
2221
- var _a, _b;
2552
+ var _a, _b, _c;
2222
2553
  const ok = await this.core.forgetMe();
2223
2554
  if (ok) {
2224
2555
  (_a = this.trackIds) == null ? void 0 : _a.clear();
2225
2556
  (_b = this.sources) == null ? void 0 : _b.clear();
2557
+ (_c = this.analytics) == null ? void 0 : _c.stop();
2226
2558
  }
2227
2559
  return ok;
2228
2560
  }
2229
2561
  /** Send what is queued now. Already wired to tab hide and page exit. */
2230
2562
  flush() {
2563
+ var _a;
2231
2564
  this.core.flush();
2565
+ (_a = this.analytics) == null ? void 0 : _a.flush(false);
2232
2566
  }
2233
2567
  /** True once `forgetMe()` has been honoured: this browser sends nothing any more. */
2234
2568
  get forgotten() {