@traqio/web 0.4.1 → 0.6.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.js CHANGED
@@ -230,21 +230,143 @@ var require_analytics = __commonJS({
230
230
  "../sdk-core/build/analytics.js"(exports) {
231
231
  "use strict";
232
232
  Object.defineProperty(exports, "__esModule", { value: true });
233
- exports.MAX_PROPS_BYTES = exports.MAX_SCREEN_NAME = exports.MAX_EVENT_NAME = exports.ANALYTICS_SESSION_IDLE_MS = void 0;
233
+ 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;
234
+ exports.cleanUserId = cleanUserId2;
235
+ exports.isEntry = isEntry2;
236
+ exports.nextAnalyticsBatch = nextAnalyticsBatch;
237
+ exports.exposureProps = exposureProps2;
238
+ exports.cleanGroupType = cleanGroupType2;
239
+ exports.cleanGroupKey = cleanGroupKey2;
240
+ exports.cleanGroups = cleanGroups2;
241
+ exports.withGroup = withGroup2;
242
+ exports.cleanTraits = cleanTraits2;
243
+ exports.withSuperProps = withSuperProps2;
234
244
  exports.cleanEventName = cleanEventName;
235
245
  exports.cleanScreenName = cleanScreenName;
236
246
  exports.cleanProps = cleanProps;
237
247
  exports.touchSession = touchSession;
238
248
  exports.parseSession = parseSession;
249
+ function cleanUserId2(v) {
250
+ if (typeof v === "number" && Number.isFinite(v))
251
+ return String(v);
252
+ if (typeof v !== "string")
253
+ return null;
254
+ const t = v.trim();
255
+ return t && t.length <= 256 ? t : null;
256
+ }
257
+ function isEntry2(kind) {
258
+ return kind === "identify" || kind === "group" || kind === "alias";
259
+ }
260
+ function nextAnalyticsBatch(queue, current, max) {
261
+ let userId;
262
+ let fixed = false;
263
+ const events = [];
264
+ for (const e of queue) {
265
+ if (events.length >= max)
266
+ break;
267
+ if (!isEntry2(e.kind)) {
268
+ const who = e.asUser !== void 0 ? e.asUser || void 0 : current;
269
+ if (!fixed) {
270
+ userId = who;
271
+ fixed = true;
272
+ } else if (who !== userId)
273
+ break;
274
+ }
275
+ const { asUser: _asUser, ...wire } = e;
276
+ events.push(wire);
277
+ }
278
+ return { events, userId: fixed ? userId : current, taken: events.length };
279
+ }
280
+ var MAX_EXPOSURE_TEXT = 200;
281
+ function exposureText2(v) {
282
+ const t = typeof v === "string" ? v.trim() : typeof v === "number" && Number.isFinite(v) || typeof v === "boolean" ? String(v) : "";
283
+ return t && t.length <= MAX_EXPOSURE_TEXT ? t : null;
284
+ }
285
+ function exposureProps2(experiment, variant, props) {
286
+ const e = exposureText2(experiment);
287
+ const v = exposureText2(variant);
288
+ if (!e || !v)
289
+ return null;
290
+ return { ...props && typeof props === "object" && !Array.isArray(props) ? props : {}, experiment: e, variant: v };
291
+ }
292
+ var GROUP_TYPE2 = /^[a-z][a-z0-9_]{0,29}$/;
293
+ exports.MAX_GROUP_TYPES = 5;
294
+ var MAX_GROUP_KEY = 256;
295
+ function cleanGroupType2(v) {
296
+ if (typeof v !== "string")
297
+ return null;
298
+ const t = v.trim();
299
+ return GROUP_TYPE2.test(t) ? t : null;
300
+ }
301
+ function cleanGroupKey2(v) {
302
+ if (typeof v === "number" && Number.isFinite(v))
303
+ return String(v);
304
+ if (typeof v !== "string")
305
+ return null;
306
+ const t = v.trim();
307
+ return t && t.length <= MAX_GROUP_KEY ? t : null;
308
+ }
309
+ function cleanGroups2(v) {
310
+ const out = {};
311
+ if (typeof v !== "object" || v === null || Array.isArray(v))
312
+ return out;
313
+ for (const [t, k] of Object.entries(v)) {
314
+ if (Object.keys(out).length >= exports.MAX_GROUP_TYPES)
315
+ break;
316
+ const type = cleanGroupType2(t);
317
+ const key = cleanGroupKey2(k);
318
+ if (type && key)
319
+ out[type] = key;
320
+ }
321
+ return out;
322
+ }
323
+ function withGroup2(groups, type, key) {
324
+ const t = cleanGroupType2(type);
325
+ const k = cleanGroupKey2(key);
326
+ if (!t || !k)
327
+ return null;
328
+ if (!(t in groups) && Object.keys(groups).length >= exports.MAX_GROUP_TYPES)
329
+ return null;
330
+ return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };
331
+ }
332
+ var TRAIT_KEY2 = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
333
+ exports.MAX_TRAITS = 50;
334
+ var MAX_TRAIT_TEXT = 200;
335
+ function cleanTraits2(v) {
336
+ const out = {};
337
+ if (typeof v !== "object" || v === null || Array.isArray(v))
338
+ return out;
339
+ for (const [k, raw] of Object.entries(v)) {
340
+ if (Object.keys(out).length >= exports.MAX_TRAITS)
341
+ break;
342
+ if (!TRAIT_KEY2.test(k))
343
+ continue;
344
+ if (typeof raw === "string") {
345
+ const t = raw.trim();
346
+ if (t)
347
+ out[k] = t.slice(0, MAX_TRAIT_TEXT);
348
+ } else if (typeof raw === "number" && Number.isFinite(raw) || typeof raw === "boolean") {
349
+ out[k] = raw;
350
+ }
351
+ }
352
+ return out;
353
+ }
354
+ function withSuperProps2(own, sup) {
355
+ var _a;
356
+ if (!Object.keys(sup).length)
357
+ return own;
358
+ return (_a = cleanProps({ ...sup, ...own != null ? own : {} })) != null ? _a : own;
359
+ }
239
360
  exports.ANALYTICS_SESSION_IDLE_MS = 30 * 60 * 1e3;
240
361
  exports.MAX_EVENT_NAME = 128;
241
362
  exports.MAX_SCREEN_NAME = 512;
242
363
  exports.MAX_PROPS_BYTES = 4096;
364
+ exports.EXPOSURE_EVENT = "$exposure";
243
365
  function cleanEventName(name) {
244
366
  if (typeof name !== "string")
245
367
  return null;
246
368
  const n = name.trim();
247
- if (!n || n.length > exports.MAX_EVENT_NAME || n.startsWith("$"))
369
+ if (!n || n.length > exports.MAX_EVENT_NAME || n.startsWith("$") && n !== exports.EXPOSURE_EVENT)
248
370
  return null;
249
371
  return n;
250
372
  }
@@ -697,7 +819,7 @@ var require_build = __commonJS({
697
819
  var adservices_1 = require_adservices();
698
820
  var deeplink_1 = require_deeplink();
699
821
  var adRevenue_1 = require_adRevenue();
700
- exports.SDK_VERSION = "0.7.0";
822
+ exports.SDK_VERSION = "0.9.0";
701
823
  var skan_2 = require_skan();
702
824
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
703
825
  return skan_2.Skan;
@@ -772,6 +894,8 @@ var require_build = __commonJS({
772
894
  var CONSENT_KEY = "traq_consent";
773
895
  var ANALYTICS_QUEUE_KEY = "traq_analytics_queue";
774
896
  var ANALYTICS_SESSION_KEY = "traq_analytics_session";
897
+ var SUPER_PROPS_KEY2 = "traq_super_props";
898
+ var GROUPS_KEY2 = "traq_groups";
775
899
  var ANALYTICS_PATH = "/ingest/analytics";
776
900
  var MAX_ANALYTICS_BATCH = 50;
777
901
  var MAX_ANALYTICS_QUEUE = 1e3;
@@ -891,6 +1015,9 @@ var require_build = __commonJS({
891
1015
  this.analyticsSession = null;
892
1016
  this.earlyAnalytics = [];
893
1017
  this.currentScreen = null;
1018
+ this.superProps = {};
1019
+ this.groups = {};
1020
+ this.resetBeforeInit = false;
894
1021
  this.maxRevenuePaid = (adInfo) => {
895
1022
  try {
896
1023
  const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
@@ -906,11 +1033,11 @@ var require_build = __commonJS({
906
1033
  return this.debug;
907
1034
  }
908
1035
  async init(opts) {
909
- var _a;
1036
+ var _a, _b;
910
1037
  if (this.started)
911
1038
  return;
912
1039
  this.started = true;
913
- this.opts = { collectContext: true, ...opts, storage: (_a = opts.storage) != null ? _a : defaultStorage() };
1040
+ this.opts = { collectContext: true, ...opts, userId: (_a = opts.userId) != null ? _a : this.earlyUserId, storage: (_b = opts.storage) != null ? _b : defaultStorage() };
914
1041
  if (!this.opts.storage) {
915
1042
  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.");
916
1043
  }
@@ -939,7 +1066,10 @@ var require_build = __commonJS({
939
1066
  this.wireDeepLinks();
940
1067
  }
941
1068
  }
942
- await this.maybeStartSession(!this.isWeb);
1069
+ if (this.isWeb)
1070
+ void this.maybeStartSession(false);
1071
+ else
1072
+ await this.maybeStartSession(true);
943
1073
  await this.initSkan();
944
1074
  await this.initAppleAds();
945
1075
  this.wireLifecycle();
@@ -992,7 +1122,7 @@ var require_build = __commonJS({
992
1122
  * NOT a conversion: never billed, never sent to an ad network (that is `track()`).
993
1123
  *
994
1124
  * Batched, persisted while offline and retried like every other call; it never
995
- * throws. Names starting with `$` are reserved; properties must survive JSON and
1125
+ * throws. Names starting with `$` are reserved (but `$exposure { experiment, variant }`, an experiment exposure); properties must survive JSON and
996
1126
  * stay under 4 KB, else they are dropped (the event is kept). Callable before
997
1127
  * `init()`: the first 100 calls wait for it.
998
1128
  *
@@ -1008,6 +1138,178 @@ var require_build = __commonJS({
1008
1138
  } catch {
1009
1139
  }
1010
1140
  }
1141
+ /**
1142
+ * Who the user is, and what they are: sets the user id (like `setUserId`) and, with
1143
+ * traits, the user's PROPERTIES — `plan`, `role`, `company_size` — read in the
1144
+ * console as a breakdown, a report dimension and a cohort condition.
1145
+ *
1146
+ * Traqio.identify("u_123", { plan: "pro", seats: 12 }, { signup_platform: "ios" });
1147
+ *
1148
+ * `traits` overwrite what was set before; `traitsOnce` are written only where the
1149
+ * user has no value yet (a first plan, a sign-up source). Values are text, numbers
1150
+ * or booleans — never an email or a name: the docs say why. At most 50 keys.
1151
+ */
1152
+ identify(userId, traits, traitsOnce) {
1153
+ try {
1154
+ const id = typeof userId === "string" ? userId.trim() : "";
1155
+ if (!id)
1156
+ return;
1157
+ if (this.opts)
1158
+ this.setUserId(id);
1159
+ else
1160
+ this.earlyUserId = id;
1161
+ const set = (0, analytics_1.cleanTraits)(traits);
1162
+ const setOnce = (0, analytics_1.cleanTraits)(traitsOnce);
1163
+ if (!Object.keys(set).length && !Object.keys(setOnce).length)
1164
+ return;
1165
+ this.queueAnalytics({ kind: "identify", ts: Date.now(), userId: id, ...Object.keys(set).length ? { set } : {}, ...Object.keys(setOnce).length ? { setOnce } : {} });
1166
+ } catch {
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Super-properties: added to EVERY analytics event from now on (and across
1171
+ * launches) — an app version flavour, an A/B arm, a theme. An event's own property
1172
+ * of the same name wins. `unregister(key)` removes one.
1173
+ *
1174
+ * Traqio.register({ app_flavor: "beta", theme: "dark" });
1175
+ */
1176
+ register(props) {
1177
+ try {
1178
+ this.superProps = (0, analytics_1.cleanTraits)({ ...this.superProps, ...(0, analytics_1.cleanTraits)(props) });
1179
+ void this.persistSuperProps();
1180
+ } catch {
1181
+ }
1182
+ }
1183
+ /** Stop adding one super-property to the events. */
1184
+ unregister(key) {
1185
+ if (typeof key !== "string" || !(key in this.superProps))
1186
+ return;
1187
+ const rest = { ...this.superProps };
1188
+ delete rest[key];
1189
+ this.superProps = rest;
1190
+ void this.persistSuperProps();
1191
+ }
1192
+ /** The super-properties `register()` set — a copy. */
1193
+ getSuperProperties() {
1194
+ return { ...this.superProps };
1195
+ }
1196
+ /**
1197
+ * The B2B ACCOUNT the user works in (group analytics): every analytics event from now
1198
+ * on (and across launches) counts for it, so the console can count accounts — unique
1199
+ * accounts, funnels, retention and cohorts « by company » — and list them with their
1200
+ * traits. Call it after sign-in, and again when the user switches account.
1201
+ *
1202
+ * Traqio.group("company", "acc_42", { plan: "enterprise", seats: 40 });
1203
+ *
1204
+ * `groupType` is lowercase (`company`, `workspace`, `team`; 5 types at most),
1205
+ * `groupKey` your own account id — never an email. Traits follow identify's rules.
1206
+ */
1207
+ group(groupType, groupKey, traits, traitsOnce) {
1208
+ try {
1209
+ const next = (0, analytics_1.withGroup)(this.groups, groupType, groupKey);
1210
+ if (!next)
1211
+ return;
1212
+ this.groups = next.groups;
1213
+ void this.persistGroups();
1214
+ const set = (0, analytics_1.cleanTraits)(traits);
1215
+ const setOnce = (0, analytics_1.cleanTraits)(traitsOnce);
1216
+ if (!next.changed && !Object.keys(set).length && !Object.keys(setOnce).length)
1217
+ return;
1218
+ this.queueAnalytics({
1219
+ kind: "group",
1220
+ ts: Date.now(),
1221
+ groupType: next.type,
1222
+ groupKey: next.key,
1223
+ ...Object.keys(set).length ? { set } : {},
1224
+ ...Object.keys(setOnce).length ? { setOnce } : {}
1225
+ });
1226
+ } catch {
1227
+ }
1228
+ }
1229
+ /** Stop stamping the events with any account — call it on sign-out. */
1230
+ resetGroups() {
1231
+ this.groups = {};
1232
+ void this.persistGroups();
1233
+ }
1234
+ /** The accounts `group()` set, by type — a copy. */
1235
+ getGroups() {
1236
+ return { ...this.groups };
1237
+ }
1238
+ /**
1239
+ * Two ids, one person: the user known so far as `previousId` (a guest id, an id
1240
+ * from before sign-up, an older system's) IS the current user (`setUserId` /
1241
+ * `identify`). Their analytics history and properties are merged under the current
1242
+ * id — the current id's own properties win. From an app, only what THIS device sent
1243
+ * under `previousId` is merged; a backend (secret key) merges everything.
1244
+ *
1245
+ * Traqio.identify("u_123");
1246
+ * Traqio.alias("guest_8f2c");
1247
+ *
1248
+ * Ignored without a current user id, or when `previousId` is the current one.
1249
+ */
1250
+ alias(previousId) {
1251
+ try {
1252
+ const userId = this.opts ? this.opts.userId : this.earlyUserId;
1253
+ const prev = (0, analytics_1.cleanUserId)(previousId);
1254
+ if (!userId || !prev || prev === userId)
1255
+ return;
1256
+ this.queueAnalytics({ kind: "alias", ts: Date.now(), userId, previousId: prev });
1257
+ } catch {
1258
+ }
1259
+ }
1260
+ /**
1261
+ * Sign-out: forget who the user was on this device — the user id, the
1262
+ * super-properties (`register`), the accounts (`group`) — and end the analytics
1263
+ * session, so the next person's visit starts clean. Events already queued keep the
1264
+ * user they were captured under. The device id is KEPT: it is the install's
1265
+ * attribution identity, and a new one would read as a new install.
1266
+ */
1267
+ reset() {
1268
+ try {
1269
+ const userId = this.opts ? this.opts.userId : this.earlyUserId;
1270
+ if (userId) {
1271
+ for (const e of this.analyticsQueue)
1272
+ if (!(0, analytics_1.isEntry)(e.kind) && e.asUser === void 0)
1273
+ e.asUser = userId;
1274
+ for (const e of this.earlyAnalytics)
1275
+ if (!(0, analytics_1.isEntry)(e.kind) && e.asUser === void 0)
1276
+ e.asUser = userId;
1277
+ }
1278
+ if (this.opts)
1279
+ this.opts.userId = void 0;
1280
+ else {
1281
+ this.earlyUserId = void 0;
1282
+ this.resetBeforeInit = true;
1283
+ }
1284
+ this.superProps = {};
1285
+ this.groups = {};
1286
+ this.analyticsSession = null;
1287
+ this.currentScreen = null;
1288
+ if (this.opts && this.isWeb)
1289
+ return;
1290
+ void this.persistSuperProps();
1291
+ void this.persistGroups();
1292
+ void this.forgetAnalyticsSession();
1293
+ } catch {
1294
+ }
1295
+ }
1296
+ /**
1297
+ * An experiment exposure: the user SAW `variant` of `experiment` — what the console's
1298
+ * experiment analysis reads (uplift and significance per variant). Your app assigns
1299
+ * the variant (its own flags, a remote config, a hash); call this where the user
1300
+ * first meets it. Sends `$exposure { experiment, variant, ...props }`.
1301
+ *
1302
+ * Traqio.exposure("paywall_copy", "b");
1303
+ */
1304
+ exposure(experiment, variant, props) {
1305
+ var _a;
1306
+ try {
1307
+ const p = (0, analytics_1.exposureProps)(experiment, variant, props);
1308
+ if (p)
1309
+ this.capture(analytics_1.EXPOSURE_EVENT, (_a = (0, analytics_1.cleanProps)(p)) != null ? _a : { experiment: p.experiment, variant: p.variant });
1310
+ } catch {
1311
+ }
1312
+ }
1011
1313
  /**
1012
1314
  * A screen view — the app's page view, read under « Top pages » and usable as a
1013
1315
  * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React
@@ -1532,6 +1834,10 @@ var require_build = __commonJS({
1532
1834
  this.adBatchId = null;
1533
1835
  this.analyticsQueue = [];
1534
1836
  this.earlyAnalytics = [];
1837
+ this.superProps = {};
1838
+ this.groups = {};
1839
+ await this.persistSuperProps();
1840
+ await this.persistGroups();
1535
1841
  await this.persistQueue();
1536
1842
  await this.persistAdQueue();
1537
1843
  await this.persistAnalyticsQueue();
@@ -1552,8 +1858,13 @@ var require_build = __commonJS({
1552
1858
  var _a, _b;
1553
1859
  if (this.erased)
1554
1860
  return;
1555
- const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
1556
- const e = screen ? { ...event, screen } : event;
1861
+ let e = event;
1862
+ if (!(0, analytics_1.isEntry)(event.kind)) {
1863
+ const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
1864
+ const props = (0, analytics_1.withSuperProps)(event.props, this.superProps);
1865
+ const groups = Object.keys(this.groups).length ? { ...this.groups } : void 0;
1866
+ e = { ...event, ...screen ? { screen } : {}, ...props ? { props } : {}, ...groups ? { groups } : {} };
1867
+ }
1557
1868
  if (!this.started) {
1558
1869
  if (this.earlyAnalytics.length < MAX_EARLY_ANALYTICS)
1559
1870
  this.earlyAnalytics.push(e);
@@ -1564,8 +1875,13 @@ var require_build = __commonJS({
1564
1875
  this.pushAnalytics(e);
1565
1876
  }
1566
1877
  pushAnalytics(e, schedule = true) {
1567
- this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
1568
- this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession.id });
1878
+ var _a, _b, _c;
1879
+ if ((0, analytics_1.isEntry)(e.kind))
1880
+ this.analyticsQueue.push({ ...e, sessionId: (_b = (_a = this.analyticsSession) == null ? void 0 : _a.id) != null ? _b : "" });
1881
+ else {
1882
+ this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
1883
+ this.analyticsQueue.push({ ...e, id: (_c = e.id) != null ? _c : uuid(), sessionId: this.analyticsSession.id });
1884
+ }
1569
1885
  if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE)
1570
1886
  this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);
1571
1887
  void this.persistAnalyticsQueue();
@@ -1574,7 +1890,7 @@ var require_build = __commonJS({
1574
1890
  }
1575
1891
  /** The persisted queue first (older), then whatever was captured while it was being read. */
1576
1892
  async restoreAnalytics() {
1577
- var _a, _b, _c;
1893
+ var _a, _b, _c, _d, _e;
1578
1894
  try {
1579
1895
  const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(ANALYTICS_QUEUE_KEY));
1580
1896
  const stored = raw ? JSON.parse(raw) : null;
@@ -1583,7 +1899,61 @@ var require_build = __commonJS({
1583
1899
  } catch {
1584
1900
  }
1585
1901
  try {
1586
- (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1902
+ if (!this.resetBeforeInit)
1903
+ (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1904
+ } catch {
1905
+ }
1906
+ if (this.resetBeforeInit) {
1907
+ this.resetBeforeInit = false;
1908
+ await this.persistSuperProps();
1909
+ await this.persistGroups();
1910
+ await this.forgetAnalyticsSession();
1911
+ return;
1912
+ }
1913
+ try {
1914
+ const raw = await ((_d = this.opts.storage) == null ? void 0 : _d.getItem(SUPER_PROPS_KEY2));
1915
+ const early = Object.keys(this.superProps).length > 0;
1916
+ if (raw)
1917
+ this.superProps = (0, analytics_1.cleanTraits)({ ...(0, analytics_1.cleanTraits)(JSON.parse(raw)), ...this.superProps });
1918
+ if (early)
1919
+ await this.persistSuperProps();
1920
+ } catch {
1921
+ }
1922
+ try {
1923
+ const raw = await ((_e = this.opts.storage) == null ? void 0 : _e.getItem(GROUPS_KEY2));
1924
+ const early = Object.keys(this.groups).length > 0;
1925
+ if (raw)
1926
+ this.groups = (0, analytics_1.cleanGroups)({ ...(0, analytics_1.cleanGroups)(JSON.parse(raw)), ...this.groups });
1927
+ if (early)
1928
+ await this.persistGroups();
1929
+ } catch {
1930
+ }
1931
+ }
1932
+ async forgetAnalyticsSession() {
1933
+ var _a;
1934
+ if (!this.opts)
1935
+ return;
1936
+ try {
1937
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ANALYTICS_SESSION_KEY, ""));
1938
+ await this.persistAnalyticsQueue();
1939
+ } catch {
1940
+ }
1941
+ }
1942
+ async persistGroups() {
1943
+ var _a;
1944
+ if (!this.opts)
1945
+ return;
1946
+ try {
1947
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(GROUPS_KEY2, JSON.stringify(this.groups)));
1948
+ } catch {
1949
+ }
1950
+ }
1951
+ async persistSuperProps() {
1952
+ var _a;
1953
+ if (!this.opts)
1954
+ return;
1955
+ try {
1956
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(SUPER_PROPS_KEY2, JSON.stringify(this.superProps)));
1587
1957
  } catch {
1588
1958
  }
1589
1959
  }
@@ -1875,18 +2245,18 @@ var require_build = __commonJS({
1875
2245
  this.retryMs = BASE_RETRY_MS;
1876
2246
  }
1877
2247
  while (this.analyticsQueue.length) {
1878
- const batch = this.analyticsQueue.slice(0, MAX_ANALYTICS_BATCH);
2248
+ const batch = (0, analytics_1.nextAnalyticsBatch)(this.analyticsQueue, this.opts.userId, MAX_ANALYTICS_BATCH);
1879
2249
  const outcome = await this.send({
1880
2250
  anonymousId: (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId(),
1881
- userId: this.opts.userId,
2251
+ userId: batch.userId,
1882
2252
  platform: this.hostPlatform,
1883
- events: batch
2253
+ events: batch.events
1884
2254
  }, ANALYTICS_PATH);
1885
2255
  if (outcome === "retry")
1886
2256
  return this.backOff();
1887
2257
  if (outcome === "refused")
1888
- console.warn(`[traqio] the server refused ${batch.length} analytics event(s) as malformed \u2014 dropped, not retried`);
1889
- this.analyticsQueue.splice(0, batch.length);
2258
+ console.warn(`[traqio] the server refused ${batch.taken} analytics event(s) as malformed \u2014 dropped, not retried`);
2259
+ this.analyticsQueue.splice(0, batch.taken);
1890
2260
  await this.persistAnalyticsQueue();
1891
2261
  this.retryMs = BASE_RETRY_MS;
1892
2262
  }
@@ -2068,7 +2438,8 @@ function deleteCookie(name, domain) {
2068
2438
 
2069
2439
  // src/storage.ts
2070
2440
  var DEVICE_ID_KEY = "traq_device_id";
2071
- var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY]);
2441
+ var INTERNAL_KEY = "traq_internal";
2442
+ var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY, INTERNAL_KEY]);
2072
2443
  var MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60;
2073
2444
  function local() {
2074
2445
  try {
@@ -2362,13 +2733,252 @@ var TrackIdKeeper = class {
2362
2733
  }
2363
2734
  };
2364
2735
 
2736
+ // src/vitals.ts
2737
+ var DEFAULT_VITALS_SAMPLE_RATE = 0.5;
2738
+ function sampled(rate, random = Math.random) {
2739
+ const r = typeof rate === "number" && Number.isFinite(rate) && rate >= 0 && rate <= 1 ? rate : DEFAULT_VITALS_SAMPLE_RATE;
2740
+ if (r <= 0) return false;
2741
+ return r >= 1 || random() < r;
2742
+ }
2743
+ var CLS_GAP_MS = 1e3;
2744
+ var CLS_WINDOW_MS = 5e3;
2745
+ var INP_KEEP = 10;
2746
+ var VitalsCollector = class {
2747
+ constructor() {
2748
+ this.clsMax = 0;
2749
+ this.clsSeen = false;
2750
+ this.clsWindow = { value: 0, first: 0, last: 0 };
2751
+ /** The longest interactions, by interactionId: their longest entry. */
2752
+ this.longest = /* @__PURE__ */ new Map();
2753
+ this.interactions = /* @__PURE__ */ new Set();
2754
+ this.inpSeen = false;
2755
+ }
2756
+ /** A `largest-contentful-paint` entry: the latest one is the LCP. */
2757
+ addLcp(startTime) {
2758
+ if (Number.isFinite(startTime) && startTime >= 0) this.lcp = startTime;
2759
+ }
2760
+ /** The `first-contentful-paint` paint entry. */
2761
+ addFcp(startTime) {
2762
+ if (this.fcp === void 0 && Number.isFinite(startTime) && startTime >= 0) this.fcp = startTime;
2763
+ }
2764
+ /** The navigation entry's `responseStart` (minus `activationStart` for a prerendered page). */
2765
+ setTtfb(ms) {
2766
+ if (Number.isFinite(ms) && ms >= 0) this.ttfb = ms;
2767
+ }
2768
+ /**
2769
+ * A `layout-shift` entry. Shifts right after an input are expected and skipped; the
2770
+ * rest are grouped in session windows and CLS is the largest window's sum.
2771
+ */
2772
+ addShift(value, startTime, hadRecentInput) {
2773
+ this.clsSeen = true;
2774
+ if (hadRecentInput || !Number.isFinite(value) || value < 0) return;
2775
+ const w = this.clsWindow;
2776
+ if (w.value > 0 && startTime - w.last < CLS_GAP_MS && startTime - w.first < CLS_WINDOW_MS) {
2777
+ w.value += value;
2778
+ w.last = startTime;
2779
+ } else {
2780
+ this.clsWindow = { value, first: startTime, last: startTime };
2781
+ }
2782
+ this.clsMax = Math.max(this.clsMax, this.clsWindow.value);
2783
+ }
2784
+ /** The browser supports layout shifts: a page that never moved has a CLS of 0, not none. */
2785
+ clsObserved() {
2786
+ this.clsSeen = true;
2787
+ }
2788
+ /** An `event` (or `first-input`) entry with an interactionId: one interaction's latency. */
2789
+ addInteraction(interactionId, duration) {
2790
+ if (!interactionId || !Number.isFinite(duration) || duration < 0) return;
2791
+ this.inpSeen = true;
2792
+ this.interactions.add(interactionId);
2793
+ const prev = this.longest.get(interactionId);
2794
+ if (prev !== void 0 && prev >= duration) return;
2795
+ this.longest.set(interactionId, duration);
2796
+ if (this.longest.size > INP_KEEP) {
2797
+ let minId = 0;
2798
+ let min = Infinity;
2799
+ for (const [id, d] of this.longest) {
2800
+ if (d < min) {
2801
+ min = d;
2802
+ minId = id;
2803
+ }
2804
+ }
2805
+ this.longest.delete(minId);
2806
+ }
2807
+ }
2808
+ /**
2809
+ * INP: the longest interaction, ignoring one per 50 — the 98th percentile for a busy
2810
+ * page, the worst one for an ordinary visit.
2811
+ */
2812
+ inp() {
2813
+ if (!this.inpSeen || !this.longest.size) return void 0;
2814
+ const sorted = [...this.longest.values()].sort((a, b) => b - a);
2815
+ return sorted[Math.min(sorted.length - 1, Math.floor(this.interactions.size / 50))];
2816
+ }
2817
+ /** What was measured, rounded: ms for the timings, 4 decimals for CLS. Null when nothing was. */
2818
+ snapshot() {
2819
+ const out = {};
2820
+ if (this.lcp !== void 0) out.lcp = Math.round(this.lcp);
2821
+ const inp = this.inp();
2822
+ if (inp !== void 0) out.inp = Math.round(inp);
2823
+ if (this.clsSeen) out.cls = Math.round(this.clsMax * 1e4) / 1e4;
2824
+ if (this.fcp !== void 0) out.fcp = Math.round(this.fcp);
2825
+ if (this.ttfb !== void 0) out.ttfb = Math.round(this.ttfb);
2826
+ return Object.keys(out).length ? out : null;
2827
+ }
2828
+ };
2829
+ function observe(type, onEntries, extra = {}) {
2830
+ var _a;
2831
+ try {
2832
+ const PO = globalThis.PerformanceObserver;
2833
+ if (!PO || !((_a = PO.supportedEntryTypes) == null ? void 0 : _a.includes(type))) return false;
2834
+ const po = new PO((list) => onEntries(list.getEntries()));
2835
+ po.observe({ type, buffered: true, ...extra });
2836
+ return true;
2837
+ } catch {
2838
+ return false;
2839
+ }
2840
+ }
2841
+ function watchVitals(c) {
2842
+ var _a;
2843
+ const startedVisible = typeof document === "undefined" || document.visibilityState !== "hidden";
2844
+ let activation = 0;
2845
+ try {
2846
+ const nav = performance.getEntriesByType("navigation")[0];
2847
+ if (nav) {
2848
+ activation = Math.max(0, (_a = nav.activationStart) != null ? _a : 0);
2849
+ if (typeof nav.responseStart === "number" && nav.responseStart > 0) c.setTtfb(Math.max(0, nav.responseStart - activation));
2850
+ }
2851
+ } catch {
2852
+ }
2853
+ if (startedVisible) {
2854
+ let lcpFinal = false;
2855
+ const finalize = () => {
2856
+ lcpFinal = true;
2857
+ };
2858
+ for (const type of ["keydown", "click", "pointerdown"]) window.addEventListener(type, finalize, { once: true, capture: true });
2859
+ observe("largest-contentful-paint", (es) => {
2860
+ if (lcpFinal) return;
2861
+ for (const e of es) c.addLcp(Math.max(0, e.startTime - activation));
2862
+ });
2863
+ observe("paint", (es) => {
2864
+ for (const e of es) if (e.name === "first-contentful-paint") c.addFcp(Math.max(0, e.startTime - activation));
2865
+ });
2866
+ }
2867
+ if (observe("layout-shift", (es) => es.forEach((e) => {
2868
+ var _a2;
2869
+ return c.addShift((_a2 = e.value) != null ? _a2 : 0, e.startTime, !!e.hadRecentInput);
2870
+ }))) c.clsObserved();
2871
+ observe("event", (es) => es.forEach((e) => {
2872
+ var _a2;
2873
+ return c.addInteraction((_a2 = e.interactionId) != null ? _a2 : 0, e.duration);
2874
+ }), { durationThreshold: 40 });
2875
+ observe("first-input", (es) => es.forEach((e) => {
2876
+ var _a2;
2877
+ return c.addInteraction((_a2 = e.interactionId) != null ? _a2 : 0, e.duration);
2878
+ }));
2879
+ }
2880
+
2365
2881
  // src/analytics.ts
2882
+ var isEntry = (e) => e.kind === "identify" || e.kind === "group" || e.kind === "alias";
2883
+ var GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;
2884
+ var MAX_GROUP_TYPES = 5;
2885
+ function cleanGroupType(v) {
2886
+ if (typeof v !== "string") return null;
2887
+ const t = v.trim();
2888
+ return GROUP_TYPE.test(t) ? t : null;
2889
+ }
2890
+ function cleanGroupKey(v) {
2891
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
2892
+ if (typeof v !== "string") return null;
2893
+ const t = v.trim();
2894
+ return t && t.length <= 256 ? t : null;
2895
+ }
2896
+ function cleanGroups(v) {
2897
+ const out = {};
2898
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
2899
+ for (const [t, k] of Object.entries(v)) {
2900
+ if (Object.keys(out).length >= MAX_GROUP_TYPES) break;
2901
+ const type = cleanGroupType(t);
2902
+ const key = cleanGroupKey(k);
2903
+ if (type && key) out[type] = key;
2904
+ }
2905
+ return out;
2906
+ }
2907
+ function withGroup(groups, type, key) {
2908
+ const t = cleanGroupType(type);
2909
+ const k = cleanGroupKey(key);
2910
+ if (!t || !k) return null;
2911
+ if (!(t in groups) && Object.keys(groups).length >= MAX_GROUP_TYPES) return null;
2912
+ return { groups: { ...groups, [t]: k }, type: t, key: k, changed: groups[t] !== k };
2913
+ }
2914
+ var TRAIT_KEY = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
2915
+ var MAX_TRAITS = 50;
2916
+ var MAX_PROPS_BYTES = 4096;
2917
+ function cleanTraits(v) {
2918
+ const out = {};
2919
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return out;
2920
+ for (const [k, raw] of Object.entries(v)) {
2921
+ if (Object.keys(out).length >= MAX_TRAITS) break;
2922
+ if (!TRAIT_KEY.test(k)) continue;
2923
+ if (typeof raw === "string") {
2924
+ const t = raw.trim();
2925
+ if (t) out[k] = t.slice(0, 200);
2926
+ } else if (typeof raw === "number" && Number.isFinite(raw) || typeof raw === "boolean") {
2927
+ out[k] = raw;
2928
+ }
2929
+ }
2930
+ return out;
2931
+ }
2932
+ function withSuperProps(own, sup) {
2933
+ if (!Object.keys(sup).length) return own;
2934
+ const merged = { ...sup, ...own != null ? own : {} };
2935
+ try {
2936
+ return JSON.stringify(merged).length <= MAX_PROPS_BYTES ? merged : own;
2937
+ } catch {
2938
+ return own;
2939
+ }
2940
+ }
2366
2941
  var SESSION_KEY = "traq_session";
2942
+ function cleanUserId(v) {
2943
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
2944
+ if (typeof v !== "string") return null;
2945
+ const t = v.trim();
2946
+ return t && t.length <= 256 ? t : null;
2947
+ }
2948
+ function exposureText(v) {
2949
+ const t = typeof v === "string" ? v.trim() : typeof v === "number" && Number.isFinite(v) || typeof v === "boolean" ? String(v) : "";
2950
+ return t && t.length <= 200 ? t : null;
2951
+ }
2952
+ function exposureProps(experiment, variant, props) {
2953
+ const e = exposureText(experiment);
2954
+ const v = exposureText(variant);
2955
+ if (!e || !v) return null;
2956
+ return { ...props && typeof props === "object" && !Array.isArray(props) ? props : {}, experiment: e, variant: v };
2957
+ }
2958
+ function takeBatch(queue, current, max) {
2959
+ let n = 0;
2960
+ let userId = current;
2961
+ let fixed = false;
2962
+ for (const e of queue) {
2963
+ if (n >= max) break;
2964
+ const entry = e.kind === "identify" || e.kind === "group" || e.kind === "alias";
2965
+ if (!entry) {
2966
+ const who = e.asUser !== void 0 ? e.asUser || void 0 : current;
2967
+ if (!fixed) {
2968
+ userId = who;
2969
+ fixed = true;
2970
+ } else if (who !== userId) break;
2971
+ }
2972
+ n++;
2973
+ }
2974
+ return { events: queue.splice(0, n), userId };
2975
+ }
2367
2976
  var SESSION_IDLE_MS = 30 * 60 * 1e3;
2368
2977
  var FLUSH_EVERY_MS = 5e3;
2369
2978
  var FLUSH_AT = 20;
2370
2979
  var MAX_QUEUE = 200;
2371
2980
  var MAX_ERRORS_PER_PAGE = 10;
2981
+ var LINK_SCANNER_ERROR = /^Object Not Found Matching Id:\d+, MethodName:\w+, ParamCount:\d+$/;
2372
2982
  var SCROLL_STEPS = [25, 50, 75, 100];
2373
2983
  var UTM = [
2374
2984
  ["utm_source", "utmSource"],
@@ -2414,6 +3024,27 @@ function bare2(href) {
2414
3024
  return void 0;
2415
3025
  }
2416
3026
  }
3027
+ var RAGE_WINDOW_MS = 1e3;
3028
+ var RAGE_RADIUS_PX = 30;
3029
+ var RAGE_THRESHOLD = 3;
3030
+ var RageClickDetector = class {
3031
+ constructor() {
3032
+ this.burst = null;
3033
+ }
3034
+ hit(x, y, t) {
3035
+ const b = this.burst;
3036
+ const near = b !== null && t - b.last <= RAGE_WINDOW_MS && Math.hypot(x - b.x, y - b.y) <= RAGE_RADIUS_PX;
3037
+ if (!near || !b.reported && t - b.first > RAGE_WINDOW_MS) {
3038
+ this.burst = { x, y, first: t, last: t, count: 1, reported: false };
3039
+ return false;
3040
+ }
3041
+ b.count++;
3042
+ b.last = t;
3043
+ if (b.reported || b.count < RAGE_THRESHOLD) return false;
3044
+ b.reported = true;
3045
+ return true;
3046
+ }
3047
+ };
2417
3048
  var AnalyticsTracker = class {
2418
3049
  constructor(deps) {
2419
3050
  this.deps = deps;
@@ -2424,9 +3055,15 @@ var AnalyticsTracker = class {
2424
3055
  this.scrollUrl = null;
2425
3056
  this.errorsThisPage = 0;
2426
3057
  this.stopped = false;
3058
+ /** This page is driven by a mail link scanner: every later batch says so (the server keeps it out of the figures). */
3059
+ this.scanner = false;
3060
+ this.rage = new RageClickDetector();
3061
+ this.vitals = null;
3062
+ this.vitalsUrl = null;
2427
3063
  }
2428
3064
  /** Wires the listeners the options ask for and records the first page view. */
2429
3065
  start() {
3066
+ var _a;
2430
3067
  const o = this.deps.options;
2431
3068
  this.timer = setInterval(() => this.flush(false), FLUSH_EVERY_MS);
2432
3069
  document.addEventListener("visibilitychange", () => {
@@ -2438,17 +3075,68 @@ var AnalyticsTracker = class {
2438
3075
  this.watchRoutes();
2439
3076
  }
2440
3077
  if (o.clicks !== false) document.addEventListener("click", (e) => this.onClick(e), true);
3078
+ if (o.rageClicks !== false) document.addEventListener("click", (e) => this.onRageClick(e), true);
2441
3079
  if (o.scroll !== false) window.addEventListener("scroll", () => this.onScroll(), { passive: true });
2442
3080
  if (o.errors !== false) {
2443
3081
  window.addEventListener("error", (e) => this.onError(e));
2444
3082
  window.addEventListener("unhandledrejection", (e) => this.onRejection(e));
2445
3083
  }
3084
+ if (o.webVitals !== false) {
3085
+ const rate = typeof o.webVitals === "object" ? o.webVitals.sampleRate : DEFAULT_VITALS_SAMPLE_RATE;
3086
+ if (sampled(rate)) {
3087
+ this.vitals = new VitalsCollector();
3088
+ this.vitalsUrl = (_a = bare2(location.href)) != null ? _a : null;
3089
+ watchVitals(this.vitals);
3090
+ }
3091
+ }
2446
3092
  }
2447
3093
  /** A custom analytics event — never a conversion (that is `track()`). */
2448
3094
  capture(name, props) {
2449
- if (typeof name !== "string" || !name.trim() || name.startsWith("$")) return;
3095
+ if (typeof name !== "string" || !name.trim() || name.startsWith("$") && name.trim() !== "$exposure") return;
2450
3096
  this.enqueue({ kind: "custom", name: name.trim(), props });
2451
3097
  }
3098
+ /**
3099
+ * The user's properties (`identify(userId, traits, traitsOnce)`): one entry in the
3100
+ * batch, under its own user id. Not activity — it neither opens nor prolongs a session.
3101
+ */
3102
+ identify(userId, set, setOnce) {
3103
+ if (this.stopped || !userId) return;
3104
+ const hasSet = Object.keys(set).length > 0;
3105
+ const hasOnce = Object.keys(setOnce).length > 0;
3106
+ if (!hasSet && !hasOnce) return;
3107
+ this.queue.push({ kind: "identify", ts: Date.now(), userId, ...hasSet ? { set } : {}, ...hasOnce ? { setOnce } : {} });
3108
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
3109
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
3110
+ }
3111
+ /** An account's properties (`group(type, key, traits)`): one entry in the batch. Not activity either. */
3112
+ group(groupType, groupKey, set, setOnce) {
3113
+ if (this.stopped) return;
3114
+ const hasSet = Object.keys(set).length > 0;
3115
+ const hasOnce = Object.keys(setOnce).length > 0;
3116
+ this.queue.push({ kind: "group", ts: Date.now(), groupType, groupKey, ...hasSet ? { set } : {}, ...hasOnce ? { setOnce } : {} });
3117
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
3118
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
3119
+ }
3120
+ /** Two ids, one person (`alias(previousId)`): one entry in the batch, under the current user. Not activity. */
3121
+ alias(userId, previousId) {
3122
+ if (this.stopped) return;
3123
+ this.queue.push({ kind: "alias", ts: Date.now(), userId, previousId });
3124
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
3125
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
3126
+ }
3127
+ /**
3128
+ * Sign-out (`reset()`): what is queued keeps `userId`, the user it was captured
3129
+ * under, and the session ends — the next event opens a new one.
3130
+ */
3131
+ reset(userId) {
3132
+ if (userId) {
3133
+ for (const e of this.queue) if (!isEntry(e) && e.asUser === void 0) e.asUser = userId;
3134
+ }
3135
+ try {
3136
+ this.deps.store.removeSync(SESSION_KEY);
3137
+ } catch {
3138
+ }
3139
+ }
2452
3140
  /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
2453
3141
  pageview() {
2454
3142
  const url = bare2(location.href);
@@ -2464,6 +3152,7 @@ var AnalyticsTracker = class {
2464
3152
  }
2465
3153
  /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
2466
3154
  flush(leaving) {
3155
+ var _a, _b;
2467
3156
  if (!this.queue.length || this.stopped) return;
2468
3157
  if (this.deps.isForgotten()) {
2469
3158
  this.stop();
@@ -2471,13 +3160,17 @@ var AnalyticsTracker = class {
2471
3160
  }
2472
3161
  const anonymousId = this.deps.anonymousId();
2473
3162
  if (!anonymousId) return;
2474
- const events = this.queue.splice(0, 100);
3163
+ const taken = takeBatch(this.queue, this.deps.userId(), 100);
3164
+ const userId = taken.userId;
3165
+ const events = userId ? taken.events.map((e) => isEntry(e) || e.asUser !== void 0 ? e : { ...e, asUser: userId }) : taken.events;
2475
3166
  const body = JSON.stringify({
2476
3167
  sdkKey: this.deps.sdkKey,
2477
3168
  anonymousId,
2478
- userId: this.deps.userId(),
3169
+ userId,
2479
3170
  debug: this.deps.isDebug() || void 0,
2480
- events
3171
+ internal: ((_b = (_a = this.deps).isInternal) == null ? void 0 : _b.call(_a)) || void 0,
3172
+ scanner: this.scanner || void 0,
3173
+ events: events.map((e) => isEntry(e) ? e : { ...e, asUser: void 0 })
2481
3174
  });
2482
3175
  try {
2483
3176
  void fetch(`${this.deps.endpoint}/ingest/analytics`, {
@@ -2525,18 +3218,30 @@ var AnalyticsTracker = class {
2525
3218
  return s;
2526
3219
  }
2527
3220
  enqueue(e) {
2528
- var _a, _b;
3221
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2529
3222
  if (this.stopped) return;
2530
3223
  const s = this.session();
2531
3224
  const title = typeof document.title === "string" && document.title ? document.title.slice(0, 200) : void 0;
2532
- 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 } : {} });
3225
+ 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 : {});
3226
+ const g = (_f = (_e = (_d = this.deps).groups) == null ? void 0 : _e.call(_d)) != null ? _f : {};
3227
+ const groups = Object.keys(g).length ? { ...g } : void 0;
3228
+ this.queue.push({ ...e, ...props ? { props } : {}, ...groups ? { groups } : {}, id: newId(), ts: Date.now(), url: (_h = (_g = e.url) != null ? _g : bare2(location.href)) != null ? _h : "", title, sessionId: s.id, ...s.src ? { src: s.src } : {} });
2533
3229
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
2534
3230
  if (this.queue.length >= FLUSH_AT) this.flush(false);
2535
3231
  }
2536
3232
  leave() {
2537
3233
  this.sendScroll();
3234
+ this.sendVitals();
2538
3235
  this.flush(true);
2539
3236
  }
3237
+ /** Once per load, at the first hide: LCP is final then, and CLS and INP have seen the visit. */
3238
+ sendVitals() {
3239
+ const c = this.vitals;
3240
+ if (!c || !this.vitalsUrl) return;
3241
+ this.vitals = null;
3242
+ const props = c.snapshot();
3243
+ if (props) this.enqueue({ kind: "vitals", url: this.vitalsUrl, props: { ...props } });
3244
+ }
2540
3245
  /** Single-page apps change the URL through the history API: wrap it, and listen for back/forward. */
2541
3246
  watchRoutes() {
2542
3247
  if (typeof history === "undefined") return;
@@ -2584,9 +3289,27 @@ var AnalyticsTracker = class {
2584
3289
  if (el.id) props.id = el.id.slice(0, 100);
2585
3290
  this.enqueue({ kind: "click", props });
2586
3291
  }
3292
+ /** Any element: frustration is most telling where nothing was clickable. */
3293
+ onRageClick(e) {
3294
+ var _a;
3295
+ const x = typeof e.clientX === "number" ? e.clientX : 0;
3296
+ const y = typeof e.clientY === "number" ? e.clientY : 0;
3297
+ if (!this.rage.hit(x, y, Date.now())) return;
3298
+ const target = e.target;
3299
+ if (!target || typeof target.closest !== "function" || target.closest("[data-traqio-ignore]")) return;
3300
+ const el = (_a = target.closest("a, button, [role='button'], input[type='submit'], input[type='button']")) != null ? _a : target;
3301
+ const text = (el.tagName === "INPUT" ? el.value : el.innerText || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
3302
+ const props = { tag: el.tagName.toLowerCase(), count: RAGE_THRESHOLD };
3303
+ if (text) props.text = text;
3304
+ const href = el.tagName === "A" ? bare2(el.getAttribute("href")) : void 0;
3305
+ if (href) props.href = href;
3306
+ if (el.id) props.id = el.id.slice(0, 100);
3307
+ this.enqueue({ kind: "rageclick", props });
3308
+ }
2587
3309
  onError(e) {
2588
3310
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
2589
3311
  const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
3312
+ if (LINK_SCANNER_ERROR.test(message.replace(/^Uncaught (?:Error: )?/, ""))) this.scanner = true;
2590
3313
  this.errorsThisPage++;
2591
3314
  const stack = e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack.slice(0, 1500) : void 0;
2592
3315
  this.enqueue({ kind: "error", props: { message, ...stack ? { stack } : {}, ...e.filename ? { source: bare2(e.filename) } : {}, ...e.lineno ? { line: e.lineno } : {} } });
@@ -2595,6 +3318,7 @@ var AnalyticsTracker = class {
2595
3318
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
2596
3319
  const reason = e.reason;
2597
3320
  const message = (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection").slice(0, 300);
3321
+ if (LINK_SCANNER_ERROR.test(message)) this.scanner = true;
2598
3322
  this.errorsThisPage++;
2599
3323
  const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack.slice(0, 1500) : void 0;
2600
3324
  this.enqueue({ kind: "error", props: { message, unhandledRejection: true, ...stack ? { stack } : {} } });
@@ -2603,6 +3327,8 @@ var AnalyticsTracker = class {
2603
3327
 
2604
3328
  // src/index.ts
2605
3329
  var DEFAULT_ENDPOINT = "https://api.traqio.app";
3330
+ var SUPER_PROPS_KEY = "traq_super";
3331
+ var GROUPS_KEY = "traq_groups";
2606
3332
  var DEFAULT_TRACK_ID_DAYS = 30;
2607
3333
  var DAY_MS = 24 * 60 * 60 * 1e3;
2608
3334
  function inBrowser() {
@@ -2615,6 +3341,15 @@ function randomId() {
2615
3341
  return null;
2616
3342
  }
2617
3343
  }
3344
+ function internalParam(href) {
3345
+ try {
3346
+ const v = new URL(href).searchParams.get("traqio_internal");
3347
+ if (v === "1" || v === "true") return true;
3348
+ if (v === "0" || v === "false") return false;
3349
+ } catch {
3350
+ }
3351
+ return null;
3352
+ }
2618
3353
  var TraqioWeb = class {
2619
3354
  constructor() {
2620
3355
  this.core = new import_core.Client();
@@ -2628,6 +3363,18 @@ var TraqioWeb = class {
2628
3363
  this.earlyCaptures = [];
2629
3364
  /** `init()` has finished (or will never run here): early captures are no longer kept. */
2630
3365
  this.ready = false;
3366
+ /** `register()`: properties added to every analytics event, kept in `traq_super`. */
3367
+ this.superProps = {};
3368
+ /** `identify()` calls with traits made before `init()` — replayed once the tracker exists. */
3369
+ this.earlyIdentifies = [];
3370
+ /** `group()`: the accounts every analytics event is stamped with, kept in `traq_groups`. */
3371
+ this.groups = {};
3372
+ /** Group entries made before `init()` — replayed once the tracker exists. */
3373
+ this.earlyGroups = [];
3374
+ /** `alias()` calls made before `init()`: [userId, previousId]. */
3375
+ this.earlyAliases = [];
3376
+ /** A `reset()` before `init()`: what earlier pages kept (super-properties, accounts) is dropped, not restored. */
3377
+ this.resetBeforeInit = false;
2631
3378
  }
2632
3379
  /**
2633
3380
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -2636,7 +3383,7 @@ var TraqioWeb = class {
2636
3383
  * does nothing there.
2637
3384
  */
2638
3385
  async init(opts) {
2639
- var _a, _b, _c;
3386
+ var _a, _b, _c, _d;
2640
3387
  if (this.started || !inBrowser()) return;
2641
3388
  this.started = true;
2642
3389
  this.waitForConsent = opts.waitForConsent === true;
@@ -2651,18 +3398,38 @@ var TraqioWeb = class {
2651
3398
  this.trackIds.capture(location.href);
2652
3399
  this.sources = new SourceKeeper(this.store, keepMs, cookieDomain, cookies);
2653
3400
  this.sources.capture(location.href, document.referrer);
3401
+ const optOut = internalParam(location.href);
3402
+ if (optOut !== null) this.setInternal(optOut);
2654
3403
  if (!this.store.getSync(DEVICE_ID_KEY)) {
2655
3404
  const id = randomId();
2656
3405
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
2657
3406
  }
2658
- this.userId = opts.userId;
2659
- const endpoint = ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, "");
3407
+ this.userId = (_c = opts.userId) != null ? _c : this.userId;
3408
+ if (this.resetBeforeInit) {
3409
+ this.store.removeSync(SUPER_PROPS_KEY);
3410
+ this.store.removeSync(GROUPS_KEY);
3411
+ }
3412
+ try {
3413
+ const raw = this.store.getSync(SUPER_PROPS_KEY);
3414
+ const early = Object.keys(this.superProps).length > 0;
3415
+ if (raw) this.superProps = cleanTraits({ ...cleanTraits(JSON.parse(raw)), ...this.superProps });
3416
+ if (early) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));
3417
+ } catch {
3418
+ }
3419
+ try {
3420
+ const raw = this.store.getSync(GROUPS_KEY);
3421
+ const early = Object.keys(this.groups).length > 0;
3422
+ if (raw) this.groups = cleanGroups({ ...cleanGroups(JSON.parse(raw)), ...this.groups });
3423
+ if (early) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));
3424
+ } catch {
3425
+ }
3426
+ const endpoint = ((_d = opts.endpoint) != null ? _d : DEFAULT_ENDPOINT).replace(/\/+$/, "");
2660
3427
  await this.core.init({
2661
3428
  sdkKey: opts.sdkKey,
2662
3429
  endpoint,
2663
3430
  storage: this.store,
2664
3431
  platform: "web",
2665
- userId: opts.userId,
3432
+ userId: this.userId,
2666
3433
  consent,
2667
3434
  debug: opts.debug,
2668
3435
  lifecycle: ({ background, foreground }) => {
@@ -2678,16 +3445,49 @@ var TraqioWeb = class {
2678
3445
  sdkKey: opts.sdkKey,
2679
3446
  anonymousId: () => store.getSync(DEVICE_ID_KEY),
2680
3447
  userId: () => this.userId,
3448
+ superProps: () => this.superProps,
3449
+ groups: () => this.groups,
2681
3450
  isDebug: () => this.core.isDebug,
2682
3451
  isForgotten: () => this.core.forgotten,
3452
+ isInternal: () => this.isInternal,
2683
3453
  options: opts.analytics === true ? {} : opts.analytics
2684
3454
  });
2685
3455
  this.analytics.start();
3456
+ for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);
3457
+ for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);
3458
+ for (const [user, prev] of this.earlyAliases) this.analytics.alias(user, prev);
2686
3459
  for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
2687
3460
  }
2688
3461
  this.earlyCaptures = [];
3462
+ this.earlyIdentifies = [];
3463
+ this.earlyGroups = [];
3464
+ this.earlyAliases = [];
2689
3465
  this.ready = true;
2690
3466
  }
3467
+ /**
3468
+ * Mark this browser as the team's own (`true`) or as a visitor again (`false`) — what
3469
+ * opening the site with `?traqio_internal=1` / `=0` does. Its analytics events are
3470
+ * still sent, flagged: the console leaves them out of every figure by default and
3471
+ * shows them under « Internal traffic only ». Conversions (`track()`) are not
3472
+ * affected. Kept on the device, like the visitor id (and under the same consent).
3473
+ */
3474
+ setInternal(on) {
3475
+ if (!this.store) return;
3476
+ try {
3477
+ if (on) this.store.setSync(INTERNAL_KEY, "1");
3478
+ else this.store.removeSync(INTERNAL_KEY);
3479
+ } catch {
3480
+ }
3481
+ }
3482
+ /** True when this browser opted itself out as internal traffic — see `setInternal()`. */
3483
+ get isInternal() {
3484
+ var _a;
3485
+ try {
3486
+ return ((_a = this.store) == null ? void 0 : _a.getSync(INTERNAL_KEY)) === "1";
3487
+ } catch {
3488
+ return false;
3489
+ }
3490
+ }
2691
3491
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
2692
3492
  get isDebug() {
2693
3493
  return this.core.isDebug;
@@ -2700,7 +3500,8 @@ var TraqioWeb = class {
2700
3500
  * A product-analytics event — `search_performed`, `pricing_toggled`… — read in the
2701
3501
  * console's Analytics section (events, funnels). NOT a conversion: it is never
2702
3502
  * billed nor sent to an ad network. A conversion (sign-up, purchase) is `track()`.
2703
- * Needs `analytics` at init; names starting with `$` are reserved.
3503
+ * Needs `analytics` at init; names starting with `$` are reserved, but for an
3504
+ * experiment exposure: `capture("$exposure", { experiment, variant })`.
2704
3505
  */
2705
3506
  capture(name, props) {
2706
3507
  if (this.analytics) this.analytics.capture(name, props);
@@ -2719,6 +3520,159 @@ var TraqioWeb = class {
2719
3520
  this.userId = id;
2720
3521
  this.core.setUserId(id);
2721
3522
  }
3523
+ /**
3524
+ * Who the user is, and what they are: sets the user id (like `setUserId`) and, with
3525
+ * traits, the user's PROPERTIES — `plan`, `role`, `company_size` — read in the
3526
+ * console as a breakdown, a report dimension and a cohort condition. Needs
3527
+ * `analytics` at init for the traits.
3528
+ *
3529
+ * Traqio.identify("u_123", { plan: "pro", seats: 12 }, { signup_source: "webinar" });
3530
+ *
3531
+ * `traits` overwrite what was set before; `traitsOnce` are written only where the
3532
+ * user has no value yet. Text, numbers, booleans — never an email or a name. At most 50 keys.
3533
+ */
3534
+ identify(userId, traits, traitsOnce) {
3535
+ const id = typeof userId === "string" ? userId.trim() : "";
3536
+ if (!id) return;
3537
+ this.setUserId(id);
3538
+ const set = cleanTraits(traits);
3539
+ const once = cleanTraits(traitsOnce);
3540
+ if (!Object.keys(set).length && !Object.keys(once).length) return;
3541
+ if (this.analytics) this.analytics.identify(id, set, once);
3542
+ else if (!this.ready && this.earlyIdentifies.length < 10) this.earlyIdentifies.push([id, set, once]);
3543
+ }
3544
+ /**
3545
+ * Super-properties: added to EVERY analytics event from now on, on this page and the
3546
+ * next ones — an A/B arm, a pricing variant, a theme. An event's own property of the
3547
+ * same name wins. Kept with the visitor id (same consent rules). `unregister(key)` removes one.
3548
+ *
3549
+ * Traqio.register({ pricing_variant: "b" });
3550
+ */
3551
+ register(props) {
3552
+ this.superProps = cleanTraits({ ...this.superProps, ...cleanTraits(props) });
3553
+ this.persistSuperProps();
3554
+ }
3555
+ /** Stop adding one super-property to the events. */
3556
+ unregister(key) {
3557
+ if (typeof key !== "string" || !(key in this.superProps)) return;
3558
+ const rest = { ...this.superProps };
3559
+ delete rest[key];
3560
+ this.superProps = rest;
3561
+ this.persistSuperProps();
3562
+ }
3563
+ /** The super-properties `register()` set — a copy. */
3564
+ getSuperProperties() {
3565
+ return { ...this.superProps };
3566
+ }
3567
+ /**
3568
+ * The B2B ACCOUNT the visitor works in (group analytics): every analytics event from
3569
+ * now on — on this page and the next ones — counts for it, so the console can count
3570
+ * accounts (unique accounts, funnels, retention, cohorts « by company ») and list them
3571
+ * with their traits. Call it after sign-in, and again on an account switch. Needs
3572
+ * `analytics` at init.
3573
+ *
3574
+ * Traqio.group("company", "acc_42", { plan: "enterprise", seats: 40 });
3575
+ *
3576
+ * `groupType` is lowercase (`company`, `workspace`; 5 types at most), `groupKey` your
3577
+ * own account id — never an email. Traits follow identify's rules.
3578
+ */
3579
+ group(groupType, groupKey, traits, traitsOnce) {
3580
+ const next = withGroup(this.groups, groupType, groupKey);
3581
+ if (!next) return;
3582
+ this.groups = next.groups;
3583
+ this.persistGroups();
3584
+ const set = cleanTraits(traits);
3585
+ const once = cleanTraits(traitsOnce);
3586
+ if (!next.changed && !Object.keys(set).length && !Object.keys(once).length) return;
3587
+ if (this.analytics) this.analytics.group(next.type, next.key, set, once);
3588
+ else if (!this.ready && this.earlyGroups.length < 10) this.earlyGroups.push([next.type, next.key, set, once]);
3589
+ }
3590
+ /** Stop stamping the events with any account — call it on sign-out. */
3591
+ resetGroups() {
3592
+ this.groups = {};
3593
+ this.persistGroups();
3594
+ }
3595
+ /** The accounts `group()` set, by type — a copy. */
3596
+ getGroups() {
3597
+ return { ...this.groups };
3598
+ }
3599
+ /**
3600
+ * Two ids, one person: the user known so far as `previousId` (a guest id, an id
3601
+ * from before sign-up) IS the current user (`setUserId` / `identify`). Their
3602
+ * analytics history and properties are merged under the current id — its own
3603
+ * properties win. From the browser only what THIS visitor sent under `previousId`
3604
+ * is merged; a backend (`@traqio/node`, secret key) merges everything.
3605
+ *
3606
+ * Traqio.identify("u_123");
3607
+ * Traqio.alias("guest_8f2c");
3608
+ *
3609
+ * Ignored without a current user id, or when `previousId` is the current one. Needs `analytics` at init.
3610
+ */
3611
+ alias(previousId) {
3612
+ const prev = cleanUserId(previousId);
3613
+ const user = this.userId;
3614
+ if (!user || !prev || prev === user) return;
3615
+ if (this.analytics) this.analytics.alias(user, prev);
3616
+ else if (!this.ready && this.earlyAliases.length < 10) this.earlyAliases.push([user, prev]);
3617
+ }
3618
+ /**
3619
+ * Sign-out: forget who the user was in this browser — the user id, the
3620
+ * super-properties, the accounts — and end the analytics session, so the next
3621
+ * person's visit starts clean. Events already queued keep the user they were
3622
+ * captured under. The visitor id is KEPT: it carries the visitor's attribution
3623
+ * (the click, the campaign) for the next sign-up.
3624
+ */
3625
+ reset() {
3626
+ var _a;
3627
+ const user = this.userId;
3628
+ (_a = this.analytics) == null ? void 0 : _a.reset(user);
3629
+ this.userId = void 0;
3630
+ this.core.reset();
3631
+ this.superProps = {};
3632
+ this.groups = {};
3633
+ this.earlyIdentifies = [];
3634
+ this.earlyGroups = [];
3635
+ this.earlyAliases = [];
3636
+ if (this.store) {
3637
+ this.persistSuperProps();
3638
+ this.persistGroups();
3639
+ } else this.resetBeforeInit = true;
3640
+ }
3641
+ /**
3642
+ * An experiment exposure: the visitor SAW `variant` of `experiment` — what the
3643
+ * console's experiment analysis reads (uplift, significance per variant). Your site
3644
+ * assigns the variant (its own flags, an edge split, a cookie); call this where the
3645
+ * visitor first meets it. Sends `$exposure { experiment, variant, ...props }`.
3646
+ *
3647
+ * Traqio.exposure("pricing_page", "annual_first");
3648
+ */
3649
+ exposure(experiment, variant, props) {
3650
+ const p = exposureProps(experiment, variant, props);
3651
+ if (!p) return;
3652
+ let fits = false;
3653
+ try {
3654
+ fits = JSON.stringify(p).length <= 4096;
3655
+ } catch {
3656
+ fits = false;
3657
+ }
3658
+ this.capture("$exposure", fits ? p : { experiment: p.experiment, variant: p.variant });
3659
+ }
3660
+ persistGroups() {
3661
+ try {
3662
+ if (!this.store) return;
3663
+ if (Object.keys(this.groups).length) this.store.setSync(GROUPS_KEY, JSON.stringify(this.groups));
3664
+ else this.store.removeSync(GROUPS_KEY);
3665
+ } catch {
3666
+ }
3667
+ }
3668
+ persistSuperProps() {
3669
+ try {
3670
+ if (!this.store) return;
3671
+ if (Object.keys(this.superProps).length) this.store.setSync(SUPER_PROPS_KEY, JSON.stringify(this.superProps));
3672
+ else this.store.removeSync(SUPER_PROPS_KEY);
3673
+ } catch {
3674
+ }
3675
+ }
2722
3676
  /**
2723
3677
  * The visitor's consent answer. Governs sharing with ad networks, and — with
2724
3678
  * `waitForConsent` — whether anything may be stored: `true` writes out what the
@@ -2771,6 +3725,10 @@ var TraqioWeb = class {
2771
3725
  (_a = this.trackIds) == null ? void 0 : _a.clear();
2772
3726
  (_b = this.sources) == null ? void 0 : _b.clear();
2773
3727
  (_c = this.analytics) == null ? void 0 : _c.stop();
3728
+ this.superProps = {};
3729
+ this.persistSuperProps();
3730
+ this.groups = {};
3731
+ this.persistGroups();
2774
3732
  }
2775
3733
  return ok;
2776
3734
  }
@@ -2789,6 +3747,7 @@ var Traqio = new TraqioWeb();
2789
3747
  export {
2790
3748
  DEFAULT_ENDPOINT,
2791
3749
  Traqio,
2792
- TraqioWeb
3750
+ TraqioWeb,
3751
+ internalParam
2793
3752
  };
2794
3753
  //# sourceMappingURL=index.js.map