@traqio/web 0.4.0 → 0.5.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.cjs CHANGED
@@ -230,6 +230,141 @@ 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.EXPOSURE_EVENT = exports.MAX_PROPS_BYTES = exports.MAX_SCREEN_NAME = exports.MAX_EVENT_NAME = exports.ANALYTICS_SESSION_IDLE_MS = exports.MAX_TRAITS = exports.MAX_GROUP_TYPES = void 0;
239
+ exports.cleanGroupType = cleanGroupType2;
240
+ exports.cleanGroupKey = cleanGroupKey2;
241
+ exports.cleanGroups = cleanGroups2;
242
+ exports.withGroup = withGroup2;
243
+ exports.cleanTraits = cleanTraits2;
244
+ exports.withSuperProps = withSuperProps2;
245
+ exports.cleanEventName = cleanEventName;
246
+ exports.cleanScreenName = cleanScreenName;
247
+ exports.cleanProps = cleanProps;
248
+ exports.touchSession = touchSession;
249
+ exports.parseSession = parseSession;
250
+ var GROUP_TYPE2 = /^[a-z][a-z0-9_]{0,29}$/;
251
+ exports.MAX_GROUP_TYPES = 5;
252
+ var MAX_GROUP_KEY = 256;
253
+ function cleanGroupType2(v) {
254
+ if (typeof v !== "string")
255
+ return null;
256
+ const t = v.trim();
257
+ return GROUP_TYPE2.test(t) ? t : null;
258
+ }
259
+ function cleanGroupKey2(v) {
260
+ if (typeof v === "number" && Number.isFinite(v))
261
+ return String(v);
262
+ if (typeof v !== "string")
263
+ return null;
264
+ const t = v.trim();
265
+ return t && t.length <= MAX_GROUP_KEY ? t : null;
266
+ }
267
+ function cleanGroups2(v) {
268
+ const out = {};
269
+ if (typeof v !== "object" || v === null || Array.isArray(v))
270
+ return out;
271
+ for (const [t, k] of Object.entries(v)) {
272
+ if (Object.keys(out).length >= exports.MAX_GROUP_TYPES)
273
+ break;
274
+ const type = cleanGroupType2(t);
275
+ const key = cleanGroupKey2(k);
276
+ if (type && key)
277
+ out[type] = key;
278
+ }
279
+ return out;
280
+ }
281
+ function withGroup2(groups, type, key) {
282
+ const t = cleanGroupType2(type);
283
+ const k = cleanGroupKey2(key);
284
+ if (!t || !k)
285
+ return null;
286
+ if (!(t in groups) && Object.keys(groups).length >= exports.MAX_GROUP_TYPES)
287
+ return null;
288
+ return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };
289
+ }
290
+ var TRAIT_KEY2 = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
291
+ exports.MAX_TRAITS = 50;
292
+ var MAX_TRAIT_TEXT = 200;
293
+ function cleanTraits2(v) {
294
+ const out = {};
295
+ if (typeof v !== "object" || v === null || Array.isArray(v))
296
+ return out;
297
+ for (const [k, raw] of Object.entries(v)) {
298
+ if (Object.keys(out).length >= exports.MAX_TRAITS)
299
+ break;
300
+ if (!TRAIT_KEY2.test(k))
301
+ continue;
302
+ if (typeof raw === "string") {
303
+ const t = raw.trim();
304
+ if (t)
305
+ out[k] = t.slice(0, MAX_TRAIT_TEXT);
306
+ } else if (typeof raw === "number" && Number.isFinite(raw) || typeof raw === "boolean") {
307
+ out[k] = raw;
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+ function withSuperProps2(own, sup) {
313
+ var _a;
314
+ if (!Object.keys(sup).length)
315
+ return own;
316
+ return (_a = cleanProps({ ...sup, ...own != null ? own : {} })) != null ? _a : own;
317
+ }
318
+ exports.ANALYTICS_SESSION_IDLE_MS = 30 * 60 * 1e3;
319
+ exports.MAX_EVENT_NAME = 128;
320
+ exports.MAX_SCREEN_NAME = 512;
321
+ exports.MAX_PROPS_BYTES = 4096;
322
+ exports.EXPOSURE_EVENT = "$exposure";
323
+ function cleanEventName(name) {
324
+ if (typeof name !== "string")
325
+ return null;
326
+ const n = name.trim();
327
+ if (!n || n.length > exports.MAX_EVENT_NAME || n.startsWith("$") && n !== exports.EXPOSURE_EVENT)
328
+ return null;
329
+ return n;
330
+ }
331
+ function cleanScreenName(name) {
332
+ if (typeof name !== "string")
333
+ return null;
334
+ const n = name.trim();
335
+ return n ? n.slice(0, exports.MAX_SCREEN_NAME) : null;
336
+ }
337
+ function cleanProps(props) {
338
+ if (typeof props !== "object" || props === null || Array.isArray(props))
339
+ return void 0;
340
+ try {
341
+ const json = JSON.stringify(props);
342
+ if (!json || json === "{}" || json.length > exports.MAX_PROPS_BYTES)
343
+ return void 0;
344
+ return JSON.parse(json);
345
+ } catch {
346
+ return void 0;
347
+ }
348
+ }
349
+ function touchSession(current, now, newId2) {
350
+ if (current && typeof current.id === "string" && typeof current.last === "number" && now - current.last <= exports.ANALYTICS_SESSION_IDLE_MS && now >= current.last - 6e4) {
351
+ return { id: current.id, last: Math.max(now, current.last) };
352
+ }
353
+ return { id: newId2(), last: now };
354
+ }
355
+ function parseSession(raw) {
356
+ if (!raw)
357
+ return null;
358
+ try {
359
+ const s = JSON.parse(raw);
360
+ return typeof s.id === "string" && typeof s.last === "number" ? { id: s.id, last: s.last } : null;
361
+ } catch {
362
+ return null;
363
+ }
364
+ }
365
+ }
366
+ });
367
+
233
368
  // ../sdk-core/build/adservices.js
234
369
  var require_adservices = __commonJS({
235
370
  "../sdk-core/build/adservices.js"(exports) {
@@ -632,16 +767,17 @@ var require_build = __commonJS({
632
767
  "../sdk-core/build/index.js"(exports) {
633
768
  "use strict";
634
769
  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;
770
+ 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
771
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
637
772
  exports.fromMaxAd = fromMaxAd;
638
773
  exports.detectDebug = detectDebug;
639
774
  exports.isLocalPage = isLocalPage;
640
775
  var skan_1 = require_skan();
776
+ var analytics_1 = require_analytics();
641
777
  var adservices_1 = require_adservices();
642
778
  var deeplink_1 = require_deeplink();
643
779
  var adRevenue_1 = require_adRevenue();
644
- exports.SDK_VERSION = "0.6.0";
780
+ exports.SDK_VERSION = "0.8.0";
645
781
  var skan_2 = require_skan();
646
782
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
647
783
  return skan_2.Skan;
@@ -650,6 +786,10 @@ var require_build = __commonJS({
650
786
  Object.defineProperty(exports, "reportAdServicesToken", { enumerable: true, get: function() {
651
787
  return adservices_2.reportAdServicesToken;
652
788
  } });
789
+ var analytics_2 = require_analytics();
790
+ Object.defineProperty(exports, "ANALYTICS_SESSION_IDLE_MS", { enumerable: true, get: function() {
791
+ return analytics_2.ANALYTICS_SESSION_IDLE_MS;
792
+ } });
653
793
  var deeplink_2 = require_deeplink();
654
794
  Object.defineProperty(exports, "isOpenUrl", { enumerable: true, get: function() {
655
795
  return deeplink_2.isOpenUrl;
@@ -710,6 +850,14 @@ var require_build = __commonJS({
710
850
  var DEFERRED_RETRY_KEY = "traq_deferred_consent_retry_until";
711
851
  var DEFERRED_RETRY_WINDOW_MS = 60 * 6e4;
712
852
  var CONSENT_KEY = "traq_consent";
853
+ var ANALYTICS_QUEUE_KEY = "traq_analytics_queue";
854
+ var ANALYTICS_SESSION_KEY = "traq_analytics_session";
855
+ var SUPER_PROPS_KEY2 = "traq_super_props";
856
+ var GROUPS_KEY2 = "traq_groups";
857
+ var ANALYTICS_PATH = "/ingest/analytics";
858
+ var MAX_ANALYTICS_BATCH = 50;
859
+ var MAX_ANALYTICS_QUEUE = 1e3;
860
+ var MAX_EARLY_ANALYTICS = 100;
713
861
  var MAX_BATCH = 20;
714
862
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
715
863
  var MAX_QUEUE2 = 500;
@@ -821,6 +969,12 @@ var require_build = __commonJS({
821
969
  this.att = null;
822
970
  this.adIdSync = null;
823
971
  this.debug = false;
972
+ this.analyticsQueue = [];
973
+ this.analyticsSession = null;
974
+ this.earlyAnalytics = [];
975
+ this.currentScreen = null;
976
+ this.superProps = {};
977
+ this.groups = {};
824
978
  this.maxRevenuePaid = (adInfo) => {
825
979
  try {
826
980
  const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
@@ -836,11 +990,11 @@ var require_build = __commonJS({
836
990
  return this.debug;
837
991
  }
838
992
  async init(opts) {
839
- var _a;
993
+ var _a, _b;
840
994
  if (this.started)
841
995
  return;
842
996
  this.started = true;
843
- this.opts = { collectContext: true, ...opts, storage: (_a = opts.storage) != null ? _a : defaultStorage() };
997
+ this.opts = { collectContext: true, ...opts, userId: (_a = opts.userId) != null ? _a : this.earlyUserId, storage: (_b = opts.storage) != null ? _b : defaultStorage() };
844
998
  if (!this.opts.storage) {
845
999
  console.warn("[traqio] no storage available \u2014 pass `storage` to init() or install @react-native-async-storage/async-storage, otherwise the install is re-sent at every launch.");
846
1000
  }
@@ -848,9 +1002,18 @@ var require_build = __commonJS({
848
1002
  await this.restoreConsent(opts.consent);
849
1003
  await this.restoreQueue();
850
1004
  await this.restoreAdQueue();
1005
+ await this.restoreAnalytics();
851
1006
  await this.buildContext();
852
- if (await this.restoreErased())
1007
+ if (await this.restoreErased()) {
1008
+ this.earlyAnalytics = [];
853
1009
  return;
1010
+ }
1011
+ if (this.isWeb) {
1012
+ this.earlyAnalytics = [];
1013
+ } else {
1014
+ for (const e of this.earlyAnalytics.splice(0))
1015
+ this.pushAnalytics(e, false);
1016
+ }
854
1017
  if (!this.isWeb) {
855
1018
  const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
856
1019
  await this.sendInstallOnce();
@@ -865,7 +1028,7 @@ var require_build = __commonJS({
865
1028
  await this.initAppleAds();
866
1029
  this.wireLifecycle();
867
1030
  this.wireAdRevenue();
868
- if (this.queue.length || this.adQueue.length)
1031
+ if (this.queue.length || this.adQueue.length || this.analyticsQueue.length)
869
1032
  this.scheduleFlush(0);
870
1033
  }
871
1034
  // `InitOptions.adRevenue`: hand the ad SDKs' own paid events to the trackers.
@@ -907,6 +1070,179 @@ var require_build = __commonJS({
907
1070
  if (props == null ? void 0 : props.value)
908
1071
  this.skan.addRevenue(props.value);
909
1072
  }
1073
+ /**
1074
+ * A product-analytics event — `paywall_viewed`, `deck_built`, `search_performed`…
1075
+ * — read in the console's Analytics section (events, funnels, property splits).
1076
+ * NOT a conversion: never billed, never sent to an ad network (that is `track()`).
1077
+ *
1078
+ * Batched, persisted while offline and retried like every other call; it never
1079
+ * throws. Names starting with `$` are reserved (but `$exposure { experiment, variant }`, an experiment exposure); properties must survive JSON and
1080
+ * stay under 4 KB, else they are dropped (the event is kept). Callable before
1081
+ * `init()`: the first 100 calls wait for it.
1082
+ *
1083
+ * Traqio.capture("lead_captured", { magnet: "starter-deck" });
1084
+ */
1085
+ capture(name, props) {
1086
+ try {
1087
+ const n = (0, analytics_1.cleanEventName)(name);
1088
+ if (!n)
1089
+ return;
1090
+ const p = (0, analytics_1.cleanProps)(props);
1091
+ this.queueAnalytics({ kind: "custom", name: n, ts: Date.now(), ...p ? { props: p } : {} });
1092
+ } catch {
1093
+ }
1094
+ }
1095
+ /**
1096
+ * Who the user is, and what they are: sets the user id (like `setUserId`) and, with
1097
+ * traits, the user's PROPERTIES — `plan`, `role`, `company_size` — read in the
1098
+ * console as a breakdown, a report dimension and a cohort condition.
1099
+ *
1100
+ * Traqio.identify("u_123", { plan: "pro", seats: 12 }, { signup_platform: "ios" });
1101
+ *
1102
+ * `traits` overwrite what was set before; `traitsOnce` are written only where the
1103
+ * user has no value yet (a first plan, a sign-up source). Values are text, numbers
1104
+ * or booleans — never an email or a name: the docs say why. At most 50 keys.
1105
+ */
1106
+ identify(userId, traits, traitsOnce) {
1107
+ try {
1108
+ const id = typeof userId === "string" ? userId.trim() : "";
1109
+ if (!id)
1110
+ return;
1111
+ if (this.opts)
1112
+ this.setUserId(id);
1113
+ else
1114
+ this.earlyUserId = id;
1115
+ const set = (0, analytics_1.cleanTraits)(traits);
1116
+ const setOnce = (0, analytics_1.cleanTraits)(traitsOnce);
1117
+ if (!Object.keys(set).length && !Object.keys(setOnce).length)
1118
+ return;
1119
+ this.queueAnalytics({ kind: "identify", ts: Date.now(), userId: id, ...Object.keys(set).length ? { set } : {}, ...Object.keys(setOnce).length ? { setOnce } : {} });
1120
+ } catch {
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Super-properties: added to EVERY analytics event from now on (and across
1125
+ * launches) — an app version flavour, an A/B arm, a theme. An event's own property
1126
+ * of the same name wins. `unregister(key)` removes one.
1127
+ *
1128
+ * Traqio.register({ app_flavor: "beta", theme: "dark" });
1129
+ */
1130
+ register(props) {
1131
+ try {
1132
+ this.superProps = (0, analytics_1.cleanTraits)({ ...this.superProps, ...(0, analytics_1.cleanTraits)(props) });
1133
+ void this.persistSuperProps();
1134
+ } catch {
1135
+ }
1136
+ }
1137
+ /** Stop adding one super-property to the events. */
1138
+ unregister(key) {
1139
+ if (typeof key !== "string" || !(key in this.superProps))
1140
+ return;
1141
+ const rest = { ...this.superProps };
1142
+ delete rest[key];
1143
+ this.superProps = rest;
1144
+ void this.persistSuperProps();
1145
+ }
1146
+ /** The super-properties `register()` set — a copy. */
1147
+ getSuperProperties() {
1148
+ return { ...this.superProps };
1149
+ }
1150
+ /**
1151
+ * The B2B ACCOUNT the user works in (group analytics): every analytics event from now
1152
+ * on (and across launches) counts for it, so the console can count accounts — unique
1153
+ * accounts, funnels, retention and cohorts « by company » — and list them with their
1154
+ * traits. Call it after sign-in, and again when the user switches account.
1155
+ *
1156
+ * Traqio.group("company", "acc_42", { plan: "enterprise", seats: 40 });
1157
+ *
1158
+ * `groupType` is lowercase (`company`, `workspace`, `team`; 5 types at most),
1159
+ * `groupKey` your own account id — never an email. Traits follow identify's rules.
1160
+ */
1161
+ group(groupType, groupKey, traits, traitsOnce) {
1162
+ try {
1163
+ const next = (0, analytics_1.withGroup)(this.groups, groupType, groupKey);
1164
+ if (!next)
1165
+ return;
1166
+ this.groups = next.groups;
1167
+ void this.persistGroups();
1168
+ const set = (0, analytics_1.cleanTraits)(traits);
1169
+ const setOnce = (0, analytics_1.cleanTraits)(traitsOnce);
1170
+ if (!next.changed && !Object.keys(set).length && !Object.keys(setOnce).length)
1171
+ return;
1172
+ this.queueAnalytics({
1173
+ kind: "group",
1174
+ ts: Date.now(),
1175
+ groupType: next.type,
1176
+ groupKey: next.key,
1177
+ ...Object.keys(set).length ? { set } : {},
1178
+ ...Object.keys(setOnce).length ? { setOnce } : {}
1179
+ });
1180
+ } catch {
1181
+ }
1182
+ }
1183
+ /** Stop stamping the events with any account — call it on sign-out. */
1184
+ resetGroups() {
1185
+ this.groups = {};
1186
+ void this.persistGroups();
1187
+ }
1188
+ /** The accounts `group()` set, by type — a copy. */
1189
+ getGroups() {
1190
+ return { ...this.groups };
1191
+ }
1192
+ /**
1193
+ * A screen view — the app's page view, read under « Top pages » and usable as a
1194
+ * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React
1195
+ * Navigation) or Expo Router's `usePathname()` do it (docs: /docs/sdks/react-native).
1196
+ * The same screen reported twice in a row inside a session counts once (re-renders).
1197
+ * Custom events captured afterwards carry this screen as their page.
1198
+ */
1199
+ screen(name, props) {
1200
+ try {
1201
+ const s = (0, analytics_1.cleanScreenName)(name);
1202
+ if (!s)
1203
+ return;
1204
+ const now = Date.now();
1205
+ const sameVisit = this.analyticsSession !== null && now - this.analyticsSession.last <= analytics_1.ANALYTICS_SESSION_IDLE_MS;
1206
+ if (s === this.currentScreen && sameVisit)
1207
+ return;
1208
+ this.currentScreen = s;
1209
+ const p = (0, analytics_1.cleanProps)(props);
1210
+ this.queueAnalytics({ kind: "pageview", ts: now, screen: s, ...p ? { props: p } : {} });
1211
+ } catch {
1212
+ }
1213
+ }
1214
+ /**
1215
+ * Screen views from a React Navigation container, by themselves:
1216
+ *
1217
+ * const navigationRef = useNavigationContainerRef();
1218
+ * useEffect(() => Traqio.trackScreens(navigationRef), [navigationRef]);
1219
+ *
1220
+ * Returns the unsubscribe. Typed by shape: no navigation library is a dependency.
1221
+ */
1222
+ trackScreens(navigation) {
1223
+ const report = () => {
1224
+ try {
1225
+ const route = navigation.getCurrentRoute();
1226
+ if (route == null ? void 0 : route.name)
1227
+ this.screen(route.name);
1228
+ } catch {
1229
+ }
1230
+ };
1231
+ let off;
1232
+ try {
1233
+ off = navigation.addListener("state", report);
1234
+ } catch {
1235
+ off = void 0;
1236
+ }
1237
+ report();
1238
+ return () => {
1239
+ try {
1240
+ if (typeof off === "function")
1241
+ off();
1242
+ } catch {
1243
+ }
1244
+ };
1245
+ }
910
1246
  /**
911
1247
  * The store this app runs on: the native bridge's word, else React Native's
912
1248
  * `Platform.OS`, else UNKNOWN. Never a guess — until 2026-11 a missing bridge meant
@@ -1375,8 +1711,15 @@ var require_build = __commonJS({
1375
1711
  this.queue = [];
1376
1712
  this.adQueue = [];
1377
1713
  this.adBatchId = null;
1714
+ this.analyticsQueue = [];
1715
+ this.earlyAnalytics = [];
1716
+ this.superProps = {};
1717
+ this.groups = {};
1718
+ await this.persistSuperProps();
1719
+ await this.persistGroups();
1378
1720
  await this.persistQueue();
1379
1721
  await this.persistAdQueue();
1722
+ await this.persistAnalyticsQueue();
1380
1723
  try {
1381
1724
  await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ERASED_KEY, "1"));
1382
1725
  } catch {
@@ -1389,6 +1732,101 @@ var require_build = __commonJS({
1389
1732
  void this.persistQueue();
1390
1733
  this.scheduleFlush();
1391
1734
  }
1735
+ /** Before `init()` the call waits in memory; after it, it is stamped and queued. */
1736
+ queueAnalytics(event) {
1737
+ var _a, _b;
1738
+ if (this.erased)
1739
+ return;
1740
+ let e = event;
1741
+ if (event.kind !== "identify" && event.kind !== "group") {
1742
+ const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
1743
+ const props = (0, analytics_1.withSuperProps)(event.props, this.superProps);
1744
+ const groups = Object.keys(this.groups).length ? { ...this.groups } : void 0;
1745
+ e = { ...event, ...screen ? { screen } : {}, ...props ? { props } : {}, ...groups ? { groups } : {} };
1746
+ }
1747
+ if (!this.started) {
1748
+ if (this.earlyAnalytics.length < MAX_EARLY_ANALYTICS)
1749
+ this.earlyAnalytics.push(e);
1750
+ return;
1751
+ }
1752
+ if (this.isWeb)
1753
+ return;
1754
+ this.pushAnalytics(e);
1755
+ }
1756
+ pushAnalytics(e, schedule = true) {
1757
+ var _a, _b;
1758
+ if (e.kind === "identify" || e.kind === "group")
1759
+ this.analyticsQueue.push({ ...e, sessionId: (_b = (_a = this.analyticsSession) == null ? void 0 : _a.id) != null ? _b : "" });
1760
+ else {
1761
+ this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
1762
+ this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession.id });
1763
+ }
1764
+ if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE)
1765
+ this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);
1766
+ void this.persistAnalyticsQueue();
1767
+ if (schedule)
1768
+ this.scheduleFlush();
1769
+ }
1770
+ /** The persisted queue first (older), then whatever was captured while it was being read. */
1771
+ async restoreAnalytics() {
1772
+ var _a, _b, _c, _d, _e;
1773
+ try {
1774
+ const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(ANALYTICS_QUEUE_KEY));
1775
+ const stored = raw ? JSON.parse(raw) : null;
1776
+ if (Array.isArray(stored))
1777
+ this.analyticsQueue = [...stored, ...this.analyticsQueue].slice(-MAX_ANALYTICS_QUEUE);
1778
+ } catch {
1779
+ }
1780
+ try {
1781
+ (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1782
+ } catch {
1783
+ }
1784
+ try {
1785
+ const raw = await ((_d = this.opts.storage) == null ? void 0 : _d.getItem(SUPER_PROPS_KEY2));
1786
+ const early = Object.keys(this.superProps).length > 0;
1787
+ if (raw)
1788
+ this.superProps = (0, analytics_1.cleanTraits)({ ...(0, analytics_1.cleanTraits)(JSON.parse(raw)), ...this.superProps });
1789
+ if (early)
1790
+ await this.persistSuperProps();
1791
+ } catch {
1792
+ }
1793
+ try {
1794
+ const raw = await ((_e = this.opts.storage) == null ? void 0 : _e.getItem(GROUPS_KEY2));
1795
+ const early = Object.keys(this.groups).length > 0;
1796
+ if (raw)
1797
+ this.groups = (0, analytics_1.cleanGroups)({ ...(0, analytics_1.cleanGroups)(JSON.parse(raw)), ...this.groups });
1798
+ if (early)
1799
+ await this.persistGroups();
1800
+ } catch {
1801
+ }
1802
+ }
1803
+ async persistGroups() {
1804
+ var _a;
1805
+ if (!this.opts)
1806
+ return;
1807
+ try {
1808
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(GROUPS_KEY2, JSON.stringify(this.groups)));
1809
+ } catch {
1810
+ }
1811
+ }
1812
+ async persistSuperProps() {
1813
+ var _a;
1814
+ if (!this.opts)
1815
+ return;
1816
+ try {
1817
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(SUPER_PROPS_KEY2, JSON.stringify(this.superProps)));
1818
+ } catch {
1819
+ }
1820
+ }
1821
+ async persistAnalyticsQueue() {
1822
+ var _a, _b;
1823
+ try {
1824
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ANALYTICS_QUEUE_KEY, JSON.stringify(this.analyticsQueue)));
1825
+ if (this.analyticsSession)
1826
+ await ((_b = this.opts.storage) == null ? void 0 : _b.setItem(ANALYTICS_SESSION_KEY, JSON.stringify(this.analyticsSession)));
1827
+ } catch {
1828
+ }
1829
+ }
1392
1830
  async restoreQueue() {
1393
1831
  var _a;
1394
1832
  try {
@@ -1618,10 +2056,10 @@ var require_build = __commonJS({
1618
2056
  }, delay);
1619
2057
  }
1620
2058
  async drain() {
1621
- var _a;
2059
+ var _a, _b;
1622
2060
  if (this.erased)
1623
2061
  return;
1624
- if (this.flushing || !this.queue.length && !this.adQueue.length)
2062
+ if (this.flushing || !this.queue.length && !this.adQueue.length && !this.analyticsQueue.length)
1625
2063
  return;
1626
2064
  this.flushing = true;
1627
2065
  try {
@@ -1667,6 +2105,22 @@ var require_build = __commonJS({
1667
2105
  await this.persistAdQueue();
1668
2106
  this.retryMs = BASE_RETRY_MS;
1669
2107
  }
2108
+ while (this.analyticsQueue.length) {
2109
+ const batch = this.analyticsQueue.slice(0, MAX_ANALYTICS_BATCH);
2110
+ const outcome = await this.send({
2111
+ anonymousId: (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId(),
2112
+ userId: this.opts.userId,
2113
+ platform: this.hostPlatform,
2114
+ events: batch
2115
+ }, ANALYTICS_PATH);
2116
+ if (outcome === "retry")
2117
+ return this.backOff();
2118
+ if (outcome === "refused")
2119
+ console.warn(`[traqio] the server refused ${batch.length} analytics event(s) as malformed \u2014 dropped, not retried`);
2120
+ this.analyticsQueue.splice(0, batch.length);
2121
+ await this.persistAnalyticsQueue();
2122
+ this.retryMs = BASE_RETRY_MS;
2123
+ }
1670
2124
  } finally {
1671
2125
  this.flushing = false;
1672
2126
  }
@@ -2146,7 +2600,210 @@ var TrackIdKeeper = class {
2146
2600
  }
2147
2601
  };
2148
2602
 
2603
+ // src/vitals.ts
2604
+ var DEFAULT_VITALS_SAMPLE_RATE = 0.5;
2605
+ function sampled(rate, random = Math.random) {
2606
+ const r = typeof rate === "number" && Number.isFinite(rate) && rate >= 0 && rate <= 1 ? rate : DEFAULT_VITALS_SAMPLE_RATE;
2607
+ if (r <= 0) return false;
2608
+ return r >= 1 || random() < r;
2609
+ }
2610
+ var CLS_GAP_MS = 1e3;
2611
+ var CLS_WINDOW_MS = 5e3;
2612
+ var INP_KEEP = 10;
2613
+ var VitalsCollector = class {
2614
+ constructor() {
2615
+ this.clsMax = 0;
2616
+ this.clsSeen = false;
2617
+ this.clsWindow = { value: 0, first: 0, last: 0 };
2618
+ /** The longest interactions, by interactionId: their longest entry. */
2619
+ this.longest = /* @__PURE__ */ new Map();
2620
+ this.interactions = /* @__PURE__ */ new Set();
2621
+ this.inpSeen = false;
2622
+ }
2623
+ /** A `largest-contentful-paint` entry: the latest one is the LCP. */
2624
+ addLcp(startTime) {
2625
+ if (Number.isFinite(startTime) && startTime >= 0) this.lcp = startTime;
2626
+ }
2627
+ /** The `first-contentful-paint` paint entry. */
2628
+ addFcp(startTime) {
2629
+ if (this.fcp === void 0 && Number.isFinite(startTime) && startTime >= 0) this.fcp = startTime;
2630
+ }
2631
+ /** The navigation entry's `responseStart` (minus `activationStart` for a prerendered page). */
2632
+ setTtfb(ms) {
2633
+ if (Number.isFinite(ms) && ms >= 0) this.ttfb = ms;
2634
+ }
2635
+ /**
2636
+ * A `layout-shift` entry. Shifts right after an input are expected and skipped; the
2637
+ * rest are grouped in session windows and CLS is the largest window's sum.
2638
+ */
2639
+ addShift(value, startTime, hadRecentInput) {
2640
+ this.clsSeen = true;
2641
+ if (hadRecentInput || !Number.isFinite(value) || value < 0) return;
2642
+ const w = this.clsWindow;
2643
+ if (w.value > 0 && startTime - w.last < CLS_GAP_MS && startTime - w.first < CLS_WINDOW_MS) {
2644
+ w.value += value;
2645
+ w.last = startTime;
2646
+ } else {
2647
+ this.clsWindow = { value, first: startTime, last: startTime };
2648
+ }
2649
+ this.clsMax = Math.max(this.clsMax, this.clsWindow.value);
2650
+ }
2651
+ /** The browser supports layout shifts: a page that never moved has a CLS of 0, not none. */
2652
+ clsObserved() {
2653
+ this.clsSeen = true;
2654
+ }
2655
+ /** An `event` (or `first-input`) entry with an interactionId: one interaction's latency. */
2656
+ addInteraction(interactionId, duration) {
2657
+ if (!interactionId || !Number.isFinite(duration) || duration < 0) return;
2658
+ this.inpSeen = true;
2659
+ this.interactions.add(interactionId);
2660
+ const prev = this.longest.get(interactionId);
2661
+ if (prev !== void 0 && prev >= duration) return;
2662
+ this.longest.set(interactionId, duration);
2663
+ if (this.longest.size > INP_KEEP) {
2664
+ let minId = 0;
2665
+ let min = Infinity;
2666
+ for (const [id, d] of this.longest) {
2667
+ if (d < min) {
2668
+ min = d;
2669
+ minId = id;
2670
+ }
2671
+ }
2672
+ this.longest.delete(minId);
2673
+ }
2674
+ }
2675
+ /**
2676
+ * INP: the longest interaction, ignoring one per 50 — the 98th percentile for a busy
2677
+ * page, the worst one for an ordinary visit.
2678
+ */
2679
+ inp() {
2680
+ if (!this.inpSeen || !this.longest.size) return void 0;
2681
+ const sorted = [...this.longest.values()].sort((a, b) => b - a);
2682
+ return sorted[Math.min(sorted.length - 1, Math.floor(this.interactions.size / 50))];
2683
+ }
2684
+ /** What was measured, rounded: ms for the timings, 4 decimals for CLS. Null when nothing was. */
2685
+ snapshot() {
2686
+ const out = {};
2687
+ if (this.lcp !== void 0) out.lcp = Math.round(this.lcp);
2688
+ const inp = this.inp();
2689
+ if (inp !== void 0) out.inp = Math.round(inp);
2690
+ if (this.clsSeen) out.cls = Math.round(this.clsMax * 1e4) / 1e4;
2691
+ if (this.fcp !== void 0) out.fcp = Math.round(this.fcp);
2692
+ if (this.ttfb !== void 0) out.ttfb = Math.round(this.ttfb);
2693
+ return Object.keys(out).length ? out : null;
2694
+ }
2695
+ };
2696
+ function observe(type, onEntries, extra = {}) {
2697
+ var _a;
2698
+ try {
2699
+ const PO = globalThis.PerformanceObserver;
2700
+ if (!PO || !((_a = PO.supportedEntryTypes) == null ? void 0 : _a.includes(type))) return false;
2701
+ const po = new PO((list) => onEntries(list.getEntries()));
2702
+ po.observe({ type, buffered: true, ...extra });
2703
+ return true;
2704
+ } catch {
2705
+ return false;
2706
+ }
2707
+ }
2708
+ function watchVitals(c) {
2709
+ var _a;
2710
+ const startedVisible = typeof document === "undefined" || document.visibilityState !== "hidden";
2711
+ let activation = 0;
2712
+ try {
2713
+ const nav = performance.getEntriesByType("navigation")[0];
2714
+ if (nav) {
2715
+ activation = Math.max(0, (_a = nav.activationStart) != null ? _a : 0);
2716
+ if (typeof nav.responseStart === "number" && nav.responseStart > 0) c.setTtfb(Math.max(0, nav.responseStart - activation));
2717
+ }
2718
+ } catch {
2719
+ }
2720
+ if (startedVisible) {
2721
+ let lcpFinal = false;
2722
+ const finalize = () => {
2723
+ lcpFinal = true;
2724
+ };
2725
+ for (const type of ["keydown", "click", "pointerdown"]) window.addEventListener(type, finalize, { once: true, capture: true });
2726
+ observe("largest-contentful-paint", (es) => {
2727
+ if (lcpFinal) return;
2728
+ for (const e of es) c.addLcp(Math.max(0, e.startTime - activation));
2729
+ });
2730
+ observe("paint", (es) => {
2731
+ for (const e of es) if (e.name === "first-contentful-paint") c.addFcp(Math.max(0, e.startTime - activation));
2732
+ });
2733
+ }
2734
+ if (observe("layout-shift", (es) => es.forEach((e) => {
2735
+ var _a2;
2736
+ return c.addShift((_a2 = e.value) != null ? _a2 : 0, e.startTime, !!e.hadRecentInput);
2737
+ }))) c.clsObserved();
2738
+ observe("event", (es) => es.forEach((e) => {
2739
+ var _a2;
2740
+ return c.addInteraction((_a2 = e.interactionId) != null ? _a2 : 0, e.duration);
2741
+ }), { durationThreshold: 40 });
2742
+ observe("first-input", (es) => es.forEach((e) => {
2743
+ var _a2;
2744
+ return c.addInteraction((_a2 = e.interactionId) != null ? _a2 : 0, e.duration);
2745
+ }));
2746
+ }
2747
+
2149
2748
  // src/analytics.ts
2749
+ var GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;
2750
+ var MAX_GROUP_TYPES = 5;
2751
+ function cleanGroupType(v) {
2752
+ if (typeof v !== "string") return null;
2753
+ const t = v.trim();
2754
+ return GROUP_TYPE.test(t) ? t : null;
2755
+ }
2756
+ function cleanGroupKey(v) {
2757
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
2758
+ if (typeof v !== "string") return null;
2759
+ const t = v.trim();
2760
+ return t && t.length <= 256 ? t : null;
2761
+ }
2762
+ function cleanGroups(v) {
2763
+ const out = {};
2764
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
2765
+ for (const [t, k] of Object.entries(v)) {
2766
+ if (Object.keys(out).length >= MAX_GROUP_TYPES) break;
2767
+ const type = cleanGroupType(t);
2768
+ const key = cleanGroupKey(k);
2769
+ if (type && key) out[type] = key;
2770
+ }
2771
+ return out;
2772
+ }
2773
+ function withGroup(groups, type, key) {
2774
+ const t = cleanGroupType(type);
2775
+ const k = cleanGroupKey(key);
2776
+ if (!t || !k) return null;
2777
+ if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;
2778
+ return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };
2779
+ }
2780
+ var TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
2781
+ var MAX_TRAITS = 50;
2782
+ var MAX_PROPS_BYTES = 4096;
2783
+ function cleanTraits(v) {
2784
+ const out = {};
2785
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
2786
+ for (const [k, raw] of Object.entries(v)) {
2787
+ if (Object.keys(out).length >= MAX_TRAITS) break;
2788
+ if (!TRAIT_KEY.test(k)) continue;
2789
+ if (typeof raw === "string") {
2790
+ const t = raw.trim();
2791
+ if (t) out[k] = t.slice(0, 200);
2792
+ } else if (typeof raw === "number" && Number.isFinite(raw) || typeof raw === "boolean") {
2793
+ out[k] = raw;
2794
+ }
2795
+ }
2796
+ return out;
2797
+ }
2798
+ function withSuperProps(own, sup) {
2799
+ if (!Object.keys(sup).length) return own;
2800
+ const merged = { ...sup, ...own != null ? own : {} };
2801
+ try {
2802
+ return JSON.stringify(merged).length <= MAX_PROPS_BYTES ? merged : own;
2803
+ } catch {
2804
+ return own;
2805
+ }
2806
+ }
2150
2807
  var SESSION_KEY = "traq_session";
2151
2808
  var SESSION_IDLE_MS = 30 * 60 * 1e3;
2152
2809
  var FLUSH_EVERY_MS = 5e3;
@@ -2198,6 +2855,27 @@ function bare2(href) {
2198
2855
  return void 0;
2199
2856
  }
2200
2857
  }
2858
+ var RAGE_WINDOW_MS = 1e3;
2859
+ var RAGE_RADIUS_PX = 30;
2860
+ var RAGE_THRESHOLD = 3;
2861
+ var RageClickDetector = class {
2862
+ constructor() {
2863
+ this.burst = null;
2864
+ }
2865
+ hit(x, y, t) {
2866
+ const b = this.burst;
2867
+ const near = b !== null && t - b.last <= RAGE_WINDOW_MS && Math.hypot(x - b.x, y - b.y) <= RAGE_RADIUS_PX;
2868
+ if (!near || !b.reported && t - b.first > RAGE_WINDOW_MS) {
2869
+ this.burst = { x, y, first: t, last: t, count: 1, reported: false };
2870
+ return false;
2871
+ }
2872
+ b.count++;
2873
+ b.last = t;
2874
+ if (b.reported || b.count < RAGE_THRESHOLD) return false;
2875
+ b.reported = true;
2876
+ return true;
2877
+ }
2878
+ };
2201
2879
  var AnalyticsTracker = class {
2202
2880
  constructor(deps) {
2203
2881
  this.deps = deps;
@@ -2208,9 +2886,13 @@ var AnalyticsTracker = class {
2208
2886
  this.scrollUrl = null;
2209
2887
  this.errorsThisPage = 0;
2210
2888
  this.stopped = false;
2889
+ this.rage = new RageClickDetector();
2890
+ this.vitals = null;
2891
+ this.vitalsUrl = null;
2211
2892
  }
2212
2893
  /** Wires the listeners the options ask for and records the first page view. */
2213
2894
  start() {
2895
+ var _a;
2214
2896
  const o = this.deps.options;
2215
2897
  this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);
2216
2898
  document.addEventListener("visibilitychange", () => {
@@ -2222,17 +2904,48 @@ var AnalyticsTracker = class {
2222
2904
  this.watchRoutes();
2223
2905
  }
2224
2906
  if (o.clicks !== false) document.addEventListener("click", (e) => this.onClick(e), true);
2907
+ if (o.rageClicks !== false) document.addEventListener("click", (e) => this.onRageClick(e), true);
2225
2908
  if (o.scroll !== false) window.addEventListener("scroll", () => this.onScroll(), { passive: true });
2226
2909
  if (o.errors !== false) {
2227
2910
  window.addEventListener("error", (e) => this.onError(e));
2228
2911
  window.addEventListener("unhandledrejection", (e) => this.onRejection(e));
2229
2912
  }
2913
+ if (o.webVitals !== false) {
2914
+ const rate = typeof o.webVitals === "object" ? o.webVitals.sampleRate : DEFAULT_VITALS_SAMPLE_RATE;
2915
+ if (sampled(rate)) {
2916
+ this.vitals = new VitalsCollector();
2917
+ this.vitalsUrl = (_a = bare2(location.href)) != null ? _a : null;
2918
+ watchVitals(this.vitals);
2919
+ }
2920
+ }
2230
2921
  }
2231
2922
  /** A custom analytics event — never a conversion (that is `track()`). */
2232
2923
  capture(name, props) {
2233
- if (typeof name !== "string" || !name.trim() || name.startsWith("$")) return;
2924
+ if (typeof name !== "string" || !name.trim() || name.startsWith("$") && name.trim() !== "$exposure") return;
2234
2925
  this.enqueue({ kind: "custom", name: name.trim(), props });
2235
2926
  }
2927
+ /**
2928
+ * The user's properties (`identify(userId, traits, traitsOnce)`): one entry in the
2929
+ * batch, under its own user id. Not activity — it neither opens nor prolongs a session.
2930
+ */
2931
+ identify(userId, set, setOnce) {
2932
+ if (this.stopped || !userId) return;
2933
+ const hasSet = Object.keys(set).length > 0;
2934
+ const hasOnce = Object.keys(setOnce).length > 0;
2935
+ if (!hasSet && !hasOnce) return;
2936
+ this.queue.push({ kind: "identify", ts: Date.now(), userId, ...hasSet ? { set } : {}, ...hasOnce ? { setOnce } : {} });
2937
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
2938
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
2939
+ }
2940
+ /** An account's properties (`group(type, key, traits)`): one entry in the batch. Not activity either. */
2941
+ group(groupType, groupKey, set, setOnce) {
2942
+ if (this.stopped) return;
2943
+ const hasSet = Object.keys(set).length > 0;
2944
+ const hasOnce = Object.keys(setOnce).length > 0;
2945
+ this.queue.push({ kind: "group", ts: Date.now(), groupType, groupKey, ...hasSet ? { set } : {}, ...hasOnce ? { setOnce } : {} });
2946
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
2947
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
2948
+ }
2236
2949
  /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
2237
2950
  pageview() {
2238
2951
  const url = bare2(location.href);
@@ -2309,18 +3022,30 @@ var AnalyticsTracker = class {
2309
3022
  return s;
2310
3023
  }
2311
3024
  enqueue(e) {
2312
- var _a, _b;
3025
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2313
3026
  if (this.stopped) return;
2314
3027
  const s = this.session();
2315
3028
  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 } : {} });
3029
+ const props = e.kind === "scroll" || e.kind === "vitals" ? e.props : withSuperProps(e.props, (_c = (_b = (_a = this.deps).superProps) == null ? void 0 : _b.call(_a)) != null ? _c : {});
3030
+ const g = (_f = (_e = (_d = this.deps).groups) == null ? void 0 : _e.call(_d)) != null ? _f : {};
3031
+ const groups = Object.keys(g).length ? { ...g } : void 0;
3032
+ this.queue.push({ ...e, ...props ? { props } : {}, ...groups ? { groups } : {}, ts: Date.now(), url: (_h = (_g = e.url) != null ? _g : bare2(location.href)) != null ? _h : "", title, sessionId: s.id, ...s.src ? { src: s.src } : {} });
2317
3033
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
2318
3034
  if (this.queue.length >= FLUSH_AT) this.flush(false);
2319
3035
  }
2320
3036
  leave() {
2321
3037
  this.sendScroll();
3038
+ this.sendVitals();
2322
3039
  this.flush(true);
2323
3040
  }
3041
+ /** Once per load, at the first hide: LCP is final then, and CLS and INP have seen the visit. */
3042
+ sendVitals() {
3043
+ const c = this.vitals;
3044
+ if (!c || !this.vitalsUrl) return;
3045
+ this.vitals = null;
3046
+ const props = c.snapshot();
3047
+ if (props) this.enqueue({ kind: "vitals", url: this.vitalsUrl, props: { ...props } });
3048
+ }
2324
3049
  /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
2325
3050
  watchRoutes() {
2326
3051
  if (typeof history === "undefined") return;
@@ -2368,6 +3093,23 @@ var AnalyticsTracker = class {
2368
3093
  if (el.id) props.id = el.id.slice(0, 100);
2369
3094
  this.enqueue({ kind: "click", props });
2370
3095
  }
3096
+ /** Any element: frustration is most telling where nothing was clickable. */
3097
+ onRageClick(e) {
3098
+ var _a;
3099
+ const x = typeof e.clientX === "number" ? e.clientX : 0;
3100
+ const y = typeof e.clientY === "number" ? e.clientY : 0;
3101
+ if (!this.rage.hit(x, y, Date.now())) return;
3102
+ const target = e.target;
3103
+ if (!target || typeof target.closest !== "function" || target.closest("[data-traqio-ignore]")) return;
3104
+ const el = (_a = target.closest("a, button, [role='button'], input[type='submit'], input[type='button']")) != null ? _a : target;
3105
+ const text = (el.tagName === "INPUT" ? el.value : el.innerText || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
3106
+ const props = { tag: el.tagName.toLowerCase(), count: RAGE_THRESHOLD };
3107
+ if (text) props.text = text;
3108
+ const href = el.tagName === "A" ? bare2(el.getAttribute("href")) : void 0;
3109
+ if (href) props.href = href;
3110
+ if (el.id) props.id = el.id.slice(0, 100);
3111
+ this.enqueue({ kind: "rageclick", props });
3112
+ }
2371
3113
  onError(e) {
2372
3114
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
2373
3115
  const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
@@ -2387,6 +3129,8 @@ var AnalyticsTracker = class {
2387
3129
 
2388
3130
  // src/index.ts
2389
3131
  var DEFAULT_ENDPOINT = "https://api.traqio.app";
3132
+ var SUPER_PROPS_KEY = "traq_super";
3133
+ var GROUPS_KEY = "traq_groups";
2390
3134
  var DEFAULT_TRACK_ID_DAYS = 30;
2391
3135
  var DAY_MS = 24 * 60 * 60 * 1e3;
2392
3136
  function inBrowser() {
@@ -2412,6 +3156,14 @@ var TraqioWeb = class {
2412
3156
  this.earlyCaptures = [];
2413
3157
  /** `init()` has finished (or will never run here): early captures are no longer kept. */
2414
3158
  this.ready = false;
3159
+ /** `register()`: properties added to every analytics event, kept in `traq_super`. */
3160
+ this.superProps = {};
3161
+ /** `identify()` calls with traits made before `init()` — replayed once the tracker exists. */
3162
+ this.earlyIdentifies = [];
3163
+ /** `group()`: the accounts every analytics event is stamped with, kept in `traq_groups`. */
3164
+ this.groups = {};
3165
+ /** Group entries made before `init()` — replayed once the tracker exists. */
3166
+ this.earlyGroups = [];
2415
3167
  }
2416
3168
  /**
2417
3169
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -2420,7 +3172,7 @@ var TraqioWeb = class {
2420
3172
  * does nothing there.
2421
3173
  */
2422
3174
  async init(opts) {
2423
- var _a, _b, _c;
3175
+ var _a, _b, _c, _d;
2424
3176
  if (this.started || !inBrowser()) return;
2425
3177
  this.started = true;
2426
3178
  this.waitForConsent = opts.waitForConsent === true;
@@ -2439,14 +3191,28 @@ var TraqioWeb = class {
2439
3191
  const id = randomId();
2440
3192
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
2441
3193
  }
2442
- this.userId = opts.userId;
2443
- const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
3194
+ this.userId = (_c = opts.userId) != null ? _c : this.userId;
3195
+ try {
3196
+ const raw = this.store.getSync(SUPER_PROPS_KEY);
3197
+ const early = Object.keys(this.superProps).length > 0;
3198
+ if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });
3199
+ if (early) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));
3200
+ } catch {
3201
+ }
3202
+ try {
3203
+ const raw = this.store.getSync(GROUPS_KEY);
3204
+ const early = Object.keys(this.groups).length > 0;
3205
+ if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });
3206
+ if (early) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));
3207
+ } catch {
3208
+ }
3209
+ const endpoint = ((_d = opts.endpoint) != null ? _d : DEFAULT_ENDPOINT).replace(/\/+$/, "");
2444
3210
  await this.core.init({
2445
3211
  sdkKey: opts.sdkKey,
2446
3212
  endpoint,
2447
3213
  storage: this.store,
2448
3214
  platform: "web",
2449
- userId: opts.userId,
3215
+ userId: this.userId,
2450
3216
  consent,
2451
3217
  debug: opts.debug,
2452
3218
  lifecycle: ({ background, foreground }) => {
@@ -2462,14 +3228,20 @@ var TraqioWeb = class {
2462
3228
  sdkKey: opts.sdkKey,
2463
3229
  anonymousId: () => store.getSync(DEVICE_ID_KEY),
2464
3230
  userId: () => this.userId,
3231
+ superProps: () => this.superProps,
3232
+ groups: () => this.groups,
2465
3233
  isDebug: () => this.core.isDebug,
2466
3234
  isForgotten: () => this.core.forgotten,
2467
3235
  options: opts.analytics === true ? {} : opts.analytics
2468
3236
  });
2469
3237
  this.analytics.start();
3238
+ for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);
3239
+ for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);
2470
3240
  for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
2471
3241
  }
2472
3242
  this.earlyCaptures = [];
3243
+ this.earlyIdentifies = [];
3244
+ this.earlyGroups = [];
2473
3245
  this.ready = true;
2474
3246
  }
2475
3247
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
@@ -2484,7 +3256,8 @@ var TraqioWeb = class {
2484
3256
  * A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
2485
3257
  * console's Analytics section (events, funnels). NOT a conversion: it is never
2486
3258
  * billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
2487
- * Needs `analytics` at init; names starting with `$` are reserved.
3259
+ * Needs `analytics` at init; names starting with `$` are reserved, but for an
3260
+ * experiment exposure: `capture("$exposure", { experiment, variant })`.
2488
3261
  */
2489
3262
  capture(name, props) {
2490
3263
  if (this.analytics) this.analytics.capture(name, props);
@@ -2503,6 +3276,98 @@ var TraqioWeb = class {
2503
3276
  this.userId = id;
2504
3277
  this.core.setUserId(id);
2505
3278
  }
3279
+ /**
3280
+ * Who the user is, and what they are: sets the user id (like `setUserId`) and, with
3281
+ * traits, the user's PROPERTIES — `plan`, `role`, `company_size` — read in the
3282
+ * console as a breakdown, a report dimension and a cohort condition. Needs
3283
+ * `analytics` at init for the traits.
3284
+ *
3285
+ * Traqio.identify("u_123", { plan: "pro", seats: 12 }, { signup_source: "webinar" });
3286
+ *
3287
+ * `traits` overwrite what was set before; `traitsOnce` are written only where the
3288
+ * user has no value yet. Text, numbers, booleans — never an email or a name. At most 50 keys.
3289
+ */
3290
+ identify(userId, traits, traitsOnce) {
3291
+ const id = typeof userId === "string" ? userId.trim() : "";
3292
+ if (!id) return;
3293
+ this.setUserId(id);
3294
+ const set = cleanTraits(traits);
3295
+ const once = cleanTraits(traitsOnce);
3296
+ if (!Object.keys(set).length && !Object.keys(once).length) return;
3297
+ if (this.analytics) this.analytics.identify(id, set, once);
3298
+ else if (!this.ready && this.earlyIdentifies.length < 10) this.earlyIdentifies.push([id, set, once]);
3299
+ }
3300
+ /**
3301
+ * Super-properties: added to EVERY analytics event from now on, on this page and the
3302
+ * next ones — an A/B arm, a pricing variant, a theme. An event's own property of the
3303
+ * same name wins. Kept with the visitor id (same consent rules). `unregister(key)` removes one.
3304
+ *
3305
+ * Traqio.register({ pricing_variant: "b" });
3306
+ */
3307
+ register(props) {
3308
+ this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });
3309
+ this.persistSuperProps();
3310
+ }
3311
+ /** Stop adding one super-property to the events. */
3312
+ unregister(key) {
3313
+ if (typeof key !== "string" || !(key in this.superProps)) return;
3314
+ const rest = { ...this.superProps };
3315
+ delete rest[key];
3316
+ this.superProps = rest;
3317
+ this.persistSuperProps();
3318
+ }
3319
+ /** The super-properties `register()` set — a copy. */
3320
+ getSuperProperties() {
3321
+ return { ...this.superProps };
3322
+ }
3323
+ /**
3324
+ * The B2B ACCOUNT the visitor works in (group analytics): every analytics event from
3325
+ * now on — on this page and the next ones — counts for it, so the console can count
3326
+ * accounts (unique accounts, funnels, retention, cohorts « by company ») and list them
3327
+ * with their traits. Call it after sign-in, and again on an account switch. Needs
3328
+ * `analytics` at init.
3329
+ *
3330
+ * Traqio.group("company", "acc_42", { plan: "enterprise", seats: 40 });
3331
+ *
3332
+ * `groupType` is lowercase (`company`, `workspace`; 5 types at most), `groupKey` your
3333
+ * own account id — never an email. Traits follow identify's rules.
3334
+ */
3335
+ group(groupType, groupKey, traits, traitsOnce) {
3336
+ const next = withGroup(this.groups, groupType, groupKey);
3337
+ if (!next) return;
3338
+ this.groups = next.groups;
3339
+ this.persistGroups();
3340
+ const set = cleanTraits(traits);
3341
+ const once = cleanTraits(traitsOnce);
3342
+ if (!next.changed && !Object.keys(set).length && !Object.keys(once).length) return;
3343
+ if (this.analytics) this.analytics.group(next.type, next.key, set, once);
3344
+ else if (!this.ready && this.earlyGroups.length < 10) this.earlyGroups.push([next.type, next.key, set, once]);
3345
+ }
3346
+ /** Stop stamping the events with any account — call it on sign-out. */
3347
+ resetGroups() {
3348
+ this.groups = {};
3349
+ this.persistGroups();
3350
+ }
3351
+ /** The accounts `group()` set, by type — a copy. */
3352
+ getGroups() {
3353
+ return { ...this.groups };
3354
+ }
3355
+ persistGroups() {
3356
+ try {
3357
+ if (!this.store) return;
3358
+ if (Object.keys(this.groups).length) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));
3359
+ else this.store.removeSync(GROUPS_KEY);
3360
+ } catch {
3361
+ }
3362
+ }
3363
+ persistSuperProps() {
3364
+ try {
3365
+ if (!this.store) return;
3366
+ if (Object.keys(this.superProps).length) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));
3367
+ else this.store.removeSync(SUPER_PROPS_KEY);
3368
+ } catch {
3369
+ }
3370
+ }
2506
3371
  /**
2507
3372
  * The visitor's consent answer. Governs sharing with ad networks, and — with
2508
3373
  * `waitForConsent` — whether anything may be stored: `true` writes out what the
@@ -2555,6 +3420,10 @@ var TraqioWeb = class {
2555
3420
  (_a = this.trackIds) == null ? void 0 : _a.clear();
2556
3421
  (_b = this.sources) == null ? void 0 : _b.clear();
2557
3422
  (_c = this.analytics) == null ? void 0 : _c.stop();
3423
+ this.superProps = {};
3424
+ this.persistSuperProps();
3425
+ this.groups = {};
3426
+ this.persistGroups();
2558
3427
  }
2559
3428
  return ok;
2560
3429
  }