@traqio/web 0.3.2 → 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/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
@@ -707,7 +707,7 @@ var require_build = __commonJS({
707
707
  var CONSENT_KEY = "traq_consent";
708
708
  var MAX_BATCH = 20;
709
709
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
710
- var MAX_QUEUE = 500;
710
+ var MAX_QUEUE2 = 500;
711
711
  var MAX_AD_BATCH = 100;
712
712
  var MAX_AD_QUEUE = 1e3;
713
713
  var BASE_RETRY_MS = 1e3;
@@ -1379,8 +1379,8 @@ var require_build = __commonJS({
1379
1379
  }
1380
1380
  enqueue(e) {
1381
1381
  this.queue.push(e);
1382
- if (this.queue.length > MAX_QUEUE)
1383
- this.queue.splice(0, this.queue.length - MAX_QUEUE);
1382
+ if (this.queue.length > MAX_QUEUE2)
1383
+ this.queue.splice(0, this.queue.length - MAX_QUEUE2);
1384
1384
  void this.persistQueue();
1385
1385
  this.scheduleFlush();
1386
1386
  }
@@ -2134,6 +2134,245 @@ var TrackIdKeeper = class {
2134
2134
  }
2135
2135
  };
2136
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
+
2137
2376
  // src/index.ts
2138
2377
  var DEFAULT_ENDPOINT = "https://api.traqio.app";
2139
2378
  var DEFAULT_TRACK_ID_DAYS = 30;
@@ -2156,6 +2395,11 @@ var TraqioWeb = class {
2156
2395
  this.sources = null;
2157
2396
  this.waitForConsent = false;
2158
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;
2159
2403
  }
2160
2404
  /**
2161
2405
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -2183,9 +2427,11 @@ var TraqioWeb = class {
2183
2427
  const id = randomId();
2184
2428
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
2185
2429
  }
2430
+ this.userId = opts.userId;
2431
+ const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
2186
2432
  await this.core.init({
2187
2433
  sdkKey: opts.sdkKey,
2188
- endpoint: ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, ""),
2434
+ endpoint,
2189
2435
  storage: this.store,
2190
2436
  platform: "web",
2191
2437
  userId: opts.userId,
@@ -2196,6 +2442,23 @@ var TraqioWeb = class {
2196
2442
  window.addEventListener("pagehide", background);
2197
2443
  }
2198
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;
2199
2462
  }
2200
2463
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
2201
2464
  get isDebug() {
@@ -2205,8 +2468,27 @@ var TraqioWeb = class {
2205
2468
  track(name, props) {
2206
2469
  this.core.track(name, props);
2207
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
+ }
2208
2489
  /** Set the user id once known (after sign-in). */
2209
2490
  setUserId(id) {
2491
+ this.userId = id;
2210
2492
  this.core.setUserId(id);
2211
2493
  }
2212
2494
  /**
@@ -2255,17 +2537,20 @@ var TraqioWeb = class {
2255
2537
  * Resolves false when the request did not reach the server — then nothing changed.
2256
2538
  */
2257
2539
  async forgetMe() {
2258
- var _a, _b;
2540
+ var _a, _b, _c;
2259
2541
  const ok = await this.core.forgetMe();
2260
2542
  if (ok) {
2261
2543
  (_a = this.trackIds) == null ? void 0 : _a.clear();
2262
2544
  (_b = this.sources) == null ? void 0 : _b.clear();
2545
+ (_c = this.analytics) == null ? void 0 : _c.stop();
2263
2546
  }
2264
2547
  return ok;
2265
2548
  }
2266
2549
  /** Send what is queued now. Already wired to tab hide and page exit. */
2267
2550
  flush() {
2551
+ var _a;
2268
2552
  this.core.flush();
2553
+ (_a = this.analytics) == null ? void 0 : _a.flush(false);
2269
2554
  }
2270
2555
  /** True once `forgetMe()` has been honoured: this browser sends nothing any more. */
2271
2556
  get forgotten() {