@traqio/web 0.5.0 → 0.6.1

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
@@ -231,6 +231,10 @@ var require_analytics = __commonJS({
231
231
  "use strict";
232
232
  Object.defineProperty(exports, "__esModule", { value: true });
233
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;
234
238
  exports.cleanGroupType = cleanGroupType2;
235
239
  exports.cleanGroupKey = cleanGroupKey2;
236
240
  exports.cleanGroups = cleanGroups2;
@@ -242,6 +246,49 @@ var require_analytics = __commonJS({
242
246
  exports.cleanProps = cleanProps;
243
247
  exports.touchSession = touchSession;
244
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
+ }
245
292
  var GROUP_TYPE2 = /^[a-z][a-z0-9_]{0,29}$/;
246
293
  exports.MAX_GROUP_TYPES = 5;
247
294
  var MAX_GROUP_KEY = 256;
@@ -763,6 +810,7 @@ var require_build = __commonJS({
763
810
  "use strict";
764
811
  Object.defineProperty(exports, "__esModule", { value: true });
765
812
  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;
813
+ exports.normalizeMetaInstallReferrers = normalizeMetaInstallReferrers;
766
814
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
767
815
  exports.fromMaxAd = fromMaxAd;
768
816
  exports.detectDebug = detectDebug;
@@ -772,7 +820,7 @@ var require_build = __commonJS({
772
820
  var adservices_1 = require_adservices();
773
821
  var deeplink_1 = require_deeplink();
774
822
  var adRevenue_1 = require_adRevenue();
775
- exports.SDK_VERSION = "0.8.0";
823
+ exports.SDK_VERSION = "0.10.0";
776
824
  var skan_2 = require_skan();
777
825
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
778
826
  return skan_2.Skan;
@@ -863,6 +911,32 @@ var require_build = __commonJS({
863
911
  var FLUSH_DELAY_MS = 3e3;
864
912
  var MAX_INSTALL_ATTEMPTS = 3;
865
913
  var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
914
+ var META_PROVIDERS = ["facebook", "instagram", "facebook_lite"];
915
+ function normalizeMetaInstallReferrers(raw) {
916
+ if (!Array.isArray(raw))
917
+ return [];
918
+ const out = [];
919
+ for (const item of raw) {
920
+ if (!item || typeof item !== "object")
921
+ continue;
922
+ const r = item;
923
+ if (typeof r.provider !== "string" || !META_PROVIDERS.includes(r.provider))
924
+ continue;
925
+ if (typeof r.installReferrer !== "string" || !r.installReferrer.trim())
926
+ continue;
927
+ const isCt = r.isCt === 1 || r.isCt === true ? 1 : r.isCt === 0 || r.isCt === false ? 0 : null;
928
+ if (isCt === null)
929
+ continue;
930
+ const ts = typeof r.actualTimestamp === "number" && Number.isFinite(r.actualTimestamp) && r.actualTimestamp > 0 ? r.actualTimestamp : void 0;
931
+ out.push({
932
+ provider: r.provider,
933
+ installReferrer: r.installReferrer,
934
+ isCt,
935
+ ...ts !== void 0 ? { actualTimestamp: ts } : {}
936
+ });
937
+ }
938
+ return out;
939
+ }
866
940
  var TRACKING_AUTHORIZATIONS = ["not_determined", "restricted", "denied", "authorized"];
867
941
  var MAX_PRECISION = {
868
942
  exact: "precise",
@@ -970,6 +1044,7 @@ var require_build = __commonJS({
970
1044
  this.currentScreen = null;
971
1045
  this.superProps = {};
972
1046
  this.groups = {};
1047
+ this.resetBeforeInit = false;
973
1048
  this.maxRevenuePaid = (adInfo) => {
974
1049
  try {
975
1050
  const max = (0, adRevenue_1.fromMaxAdInfo)(adInfo);
@@ -1018,7 +1093,10 @@ var require_build = __commonJS({
1018
1093
  this.wireDeepLinks();
1019
1094
  }
1020
1095
  }
1021
- await this.maybeStartSession(!this.isWeb);
1096
+ if (this.isWeb)
1097
+ void this.maybeStartSession(false);
1098
+ else
1099
+ await this.maybeStartSession(true);
1022
1100
  await this.initSkan();
1023
1101
  await this.initAppleAds();
1024
1102
  this.wireLifecycle();
@@ -1184,6 +1262,81 @@ var require_build = __commonJS({
1184
1262
  getGroups() {
1185
1263
  return { ...this.groups };
1186
1264
  }
1265
+ /**
1266
+ * Two ids, one person: the user known so far as `previousId` (a guest id, an id
1267
+ * from before sign-up, an older system's) IS the current user (`setUserId` /
1268
+ * `identify`). Their analytics history and properties are merged under the current
1269
+ * id — the current id's own properties win. From an app, only what THIS device sent
1270
+ * under `previousId` is merged; a backend (secret key) merges everything.
1271
+ *
1272
+ * Traqio.identify("u_123");
1273
+ * Traqio.alias("guest_8f2c");
1274
+ *
1275
+ * Ignored without a current user id, or when `previousId` is the current one.
1276
+ */
1277
+ alias(previousId) {
1278
+ try {
1279
+ const userId = this.opts ? this.opts.userId : this.earlyUserId;
1280
+ const prev = (0, analytics_1.cleanUserId)(previousId);
1281
+ if (!userId || !prev || prev === userId)
1282
+ return;
1283
+ this.queueAnalytics({ kind: "alias", ts: Date.now(), userId, previousId: prev });
1284
+ } catch {
1285
+ }
1286
+ }
1287
+ /**
1288
+ * Sign-out: forget who the user was on this device — the user id, the
1289
+ * super-properties (`register`), the accounts (`group`) — and end the analytics
1290
+ * session, so the next person's visit starts clean. Events already queued keep the
1291
+ * user they were captured under. The device id is KEPT: it is the install's
1292
+ * attribution identity, and a new one would read as a new install.
1293
+ */
1294
+ reset() {
1295
+ try {
1296
+ const userId = this.opts ? this.opts.userId : this.earlyUserId;
1297
+ if (userId) {
1298
+ for (const e of this.analyticsQueue)
1299
+ if (!(0, analytics_1.isEntry)(e.kind) && e.asUser === void 0)
1300
+ e.asUser = userId;
1301
+ for (const e of this.earlyAnalytics)
1302
+ if (!(0, analytics_1.isEntry)(e.kind) && e.asUser === void 0)
1303
+ e.asUser = userId;
1304
+ }
1305
+ if (this.opts)
1306
+ this.opts.userId = void 0;
1307
+ else {
1308
+ this.earlyUserId = void 0;
1309
+ this.resetBeforeInit = true;
1310
+ }
1311
+ this.superProps = {};
1312
+ this.groups = {};
1313
+ this.analyticsSession = null;
1314
+ this.currentScreen = null;
1315
+ if (this.opts && this.isWeb)
1316
+ return;
1317
+ void this.persistSuperProps();
1318
+ void this.persistGroups();
1319
+ void this.forgetAnalyticsSession();
1320
+ } catch {
1321
+ }
1322
+ }
1323
+ /**
1324
+ * An experiment exposure: the user SAW `variant` of `experiment` — what the console's
1325
+ * experiment analysis reads (uplift and significance per variant). Your app assigns
1326
+ * the variant (its own flags, a remote config, a hash); call this where the user
1327
+ * first meets it. Sends `$exposure { experiment, variant, ...props }`.
1328
+ *
1329
+ * Traqio.exposure("paywall_copy", "b");
1330
+ */
1331
+ exposure(experiment, variant, props) {
1332
+ var _a;
1333
+ try {
1334
+ const p = (0, analytics_1.exposureProps)(experiment, variant, props);
1335
+ if (p)
1336
+ this.capture(analytics_1.EXPOSURE_EVENT, (_a = (0, analytics_1.cleanProps)(p)) != null ? _a : { experiment: p.experiment, variant: p.variant });
1337
+ } catch {
1338
+ }
1339
+ }
1187
1340
  /**
1188
1341
  * A screen view — the app's page view, read under « Top pages » and usable as a
1189
1342
  * funnel step. Call it when a screen gets the focus, or let `trackScreens()` (React
@@ -1733,7 +1886,7 @@ var require_build = __commonJS({
1733
1886
  if (this.erased)
1734
1887
  return;
1735
1888
  let e = event;
1736
- if (event.kind !== "identify" && event.kind !== "group") {
1889
+ if (!(0, analytics_1.isEntry)(event.kind)) {
1737
1890
  const screen = (_b = (_a = event.screen) != null ? _a : this.currentScreen) != null ? _b : void 0;
1738
1891
  const props = (0, analytics_1.withSuperProps)(event.props, this.superProps);
1739
1892
  const groups = Object.keys(this.groups).length ? { ...this.groups } : void 0;
@@ -1749,12 +1902,12 @@ var require_build = __commonJS({
1749
1902
  this.pushAnalytics(e);
1750
1903
  }
1751
1904
  pushAnalytics(e, schedule = true) {
1752
- var _a, _b;
1753
- if (e.kind === "identify" || e.kind === "group")
1905
+ var _a, _b, _c;
1906
+ if ((0, analytics_1.isEntry)(e.kind))
1754
1907
  this.analyticsQueue.push({ ...e, sessionId: (_b = (_a = this.analyticsSession) == null ? void 0 : _a.id) != null ? _b : "" });
1755
1908
  else {
1756
1909
  this.analyticsSession = (0, analytics_1.touchSession)(this.analyticsSession, e.ts, uuid);
1757
- this.analyticsQueue.push({ ...e, sessionId: this.analyticsSession.id });
1910
+ this.analyticsQueue.push({ ...e, id: (_c = e.id) != null ? _c : uuid(), sessionId: this.analyticsSession.id });
1758
1911
  }
1759
1912
  if (this.analyticsQueue.length > MAX_ANALYTICS_QUEUE)
1760
1913
  this.analyticsQueue.splice(0, this.analyticsQueue.length - MAX_ANALYTICS_QUEUE);
@@ -1773,9 +1926,17 @@ var require_build = __commonJS({
1773
1926
  } catch {
1774
1927
  }
1775
1928
  try {
1776
- (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1929
+ if (!this.resetBeforeInit)
1930
+ (_c = this.analyticsSession) != null ? _c : this.analyticsSession = (0, analytics_1.parseSession)(await ((_b = this.opts.storage) == null ? void 0 : _b.getItem(ANALYTICS_SESSION_KEY)));
1777
1931
  } catch {
1778
1932
  }
1933
+ if (this.resetBeforeInit) {
1934
+ this.resetBeforeInit = false;
1935
+ await this.persistSuperProps();
1936
+ await this.persistGroups();
1937
+ await this.forgetAnalyticsSession();
1938
+ return;
1939
+ }
1779
1940
  try {
1780
1941
  const raw = await ((_d = this.opts.storage) == null ? void 0 : _d.getItem(SUPER_PROPS_KEY2));
1781
1942
  const early = Object.keys(this.superProps).length > 0;
@@ -1795,6 +1956,16 @@ var require_build = __commonJS({
1795
1956
  } catch {
1796
1957
  }
1797
1958
  }
1959
+ async forgetAnalyticsSession() {
1960
+ var _a;
1961
+ if (!this.opts)
1962
+ return;
1963
+ try {
1964
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ANALYTICS_SESSION_KEY, ""));
1965
+ await this.persistAnalyticsQueue();
1966
+ } catch {
1967
+ }
1968
+ }
1798
1969
  async persistGroups() {
1799
1970
  var _a;
1800
1971
  if (!this.opts)
@@ -1960,6 +2131,24 @@ var require_build = __commonJS({
1960
2131
  }
1961
2132
  return result;
1962
2133
  }
2134
+ /**
2135
+ * Meta's Install Referrer answers, Android only, read just before the install
2136
+ * leaves. Never throws: an old native build, a bridge teardown or no Meta app
2137
+ * installed all mean « no field ».
2138
+ */
2139
+ async readMetaInstallReferrers(platform) {
2140
+ var _a, _b;
2141
+ const read = (_a = this.opts.native) == null ? void 0 : _a.getMetaInstallReferrers;
2142
+ if (platform !== "android" || !read)
2143
+ return void 0;
2144
+ try {
2145
+ const appId = ((_b = this.opts.metaAppId) == null ? void 0 : _b.trim()) || void 0;
2146
+ const list = normalizeMetaInstallReferrers(await read.call(this.opts.native, appId));
2147
+ return list.length ? list : void 0;
2148
+ } catch {
2149
+ return void 0;
2150
+ }
2151
+ }
1963
2152
  /** Only with the host's opt-in; a zeroed or malformed id is never sent. */
1964
2153
  async readAdvertisingId() {
1965
2154
  var _a;
@@ -1992,10 +2181,12 @@ var require_build = __commonJS({
1992
2181
  }
1993
2182
  }
1994
2183
  const advertisingId = await this.readAdvertisingId();
2184
+ const metaInstallReferrers = await this.readMetaInstallReferrers(platform);
1995
2185
  const ok = await this.post({
1996
2186
  install: {
1997
2187
  platform,
1998
2188
  installReferrer: referrer.referrer,
2189
+ ...metaInstallReferrers ? { metaInstallReferrers } : {},
1999
2190
  appUserId: this.opts.userId,
2000
2191
  advertisingId,
2001
2192
  context: this.context
@@ -2101,18 +2292,18 @@ var require_build = __commonJS({
2101
2292
  this.retryMs = BASE_RETRY_MS;
2102
2293
  }
2103
2294
  while (this.analyticsQueue.length) {
2104
- const batch = this.analyticsQueue.slice(0, MAX_ANALYTICS_BATCH);
2295
+ const batch = (0, analytics_1.nextAnalyticsBatch)(this.analyticsQueue, this.opts.userId, MAX_ANALYTICS_BATCH);
2105
2296
  const outcome = await this.send({
2106
2297
  anonymousId: (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId(),
2107
- userId: this.opts.userId,
2298
+ userId: batch.userId,
2108
2299
  platform: this.hostPlatform,
2109
- events: batch
2300
+ events: batch.events
2110
2301
  }, ANALYTICS_PATH);
2111
2302
  if (outcome === "retry")
2112
2303
  return this.backOff();
2113
2304
  if (outcome === "refused")
2114
- console.warn(`[traqio] the server refused ${batch.length} analytics event(s) as malformed \u2014 dropped, not retried`);
2115
- this.analyticsQueue.splice(0, batch.length);
2305
+ console.warn(`[traqio] the server refused ${batch.taken} analytics event(s) as malformed \u2014 dropped, not retried`);
2306
+ this.analyticsQueue.splice(0, batch.taken);
2116
2307
  await this.persistAnalyticsQueue();
2117
2308
  this.retryMs = BASE_RETRY_MS;
2118
2309
  }
@@ -2294,7 +2485,8 @@ function deleteCookie(name, domain) {
2294
2485
 
2295
2486
  // src/storage.ts
2296
2487
  var DEVICE_ID_KEY = "traq_device_id";
2297
- var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY]);
2488
+ var INTERNAL_KEY = "traq_internal";
2489
+ var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY, INTERNAL_KEY]);
2298
2490
  var MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60;
2299
2491
  function local() {
2300
2492
  try {
@@ -2734,6 +2926,7 @@ function watchVitals(c) {
2734
2926
  }
2735
2927
 
2736
2928
  // src/analytics.ts
2929
+ var isEntry = (e) => e.kind === "identify" || e.kind === "group" || e.kind === "alias";
2737
2930
  var GROUP_TYPE = /^[a-z][a-z0-9_]{0,29}$/;
2738
2931
  var MAX_GROUP_TYPES = 5;
2739
2932
  function cleanGroupType(v) {
@@ -2793,11 +2986,46 @@ function withSuperProps(own, sup) {
2793
2986
  }
2794
2987
  }
2795
2988
  var SESSION_KEY = "traq_session";
2989
+ function cleanUserId(v) {
2990
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
2991
+ if (typeof v !== "string") return null;
2992
+ const t = v.trim();
2993
+ return t && t.length <= 256 ? t : null;
2994
+ }
2995
+ function exposureText(v) {
2996
+ const t = typeof v === "string" ? v.trim() : typeof v === "number" && Number.isFinite(v) || typeof v === "boolean" ? String(v) : "";
2997
+ return t && t.length <= 200 ? t : null;
2998
+ }
2999
+ function exposureProps(experiment, variant, props) {
3000
+ const e = exposureText(experiment);
3001
+ const v = exposureText(variant);
3002
+ if (!e || !v) return null;
3003
+ return { ...props && typeof props === "object" && !Array.isArray(props) ? props : {}, experiment: e, variant: v };
3004
+ }
3005
+ function takeBatch(queue, current, max) {
3006
+ let n = 0;
3007
+ let userId = current;
3008
+ let fixed = false;
3009
+ for (const e of queue) {
3010
+ if (n >= max) break;
3011
+ const entry = e.kind === "identify" || e.kind === "group" || e.kind === "alias";
3012
+ if (!entry) {
3013
+ const who = e.asUser !== void 0 ? e.asUser || void 0 : current;
3014
+ if (!fixed) {
3015
+ userId = who;
3016
+ fixed = true;
3017
+ } else if (who !== userId) break;
3018
+ }
3019
+ n++;
3020
+ }
3021
+ return { events: queue.splice(0, n), userId };
3022
+ }
2796
3023
  var SESSION_IDLE_MS = 30 * 60 * 1e3;
2797
3024
  var FLUSH_EVERY_MS = 5e3;
2798
3025
  var FLUSH_AT = 20;
2799
3026
  var MAX_QUEUE = 200;
2800
3027
  var MAX_ERRORS_PER_PAGE = 10;
3028
+ var LINK_SCANNER_ERROR = /^Object Not Found Matching Id:\d+, MethodName:\w+, ParamCount:\d+$/;
2801
3029
  var SCROLL_STEPS = [25, 50, 75, 100];
2802
3030
  var UTM = [
2803
3031
  ["utm_source", "utmSource"],
@@ -2874,6 +3102,8 @@ var AnalyticsTracker = class {
2874
3102
  this.scrollUrl = null;
2875
3103
  this.errorsThisPage = 0;
2876
3104
  this.stopped = false;
3105
+ /** This page is driven by a mail link scanner: every later batch says so (the server keeps it out of the figures). */
3106
+ this.scanner = false;
2877
3107
  this.rage = new RageClickDetector();
2878
3108
  this.vitals = null;
2879
3109
  this.vitalsUrl = null;
@@ -2934,6 +3164,26 @@ var AnalyticsTracker = class {
2934
3164
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
2935
3165
  if (this.queue.length >= FLUSH_AT) this.flush(false);
2936
3166
  }
3167
+ /** Two ids, one person (`alias(previousId)`): one entry in the batch, under the current user. Not activity. */
3168
+ alias(userId, previousId) {
3169
+ if (this.stopped) return;
3170
+ this.queue.push({ kind: "alias", ts: Date.now(), userId, previousId });
3171
+ if (this.queue.length > MAX_QUEUE) this.queue.shift();
3172
+ if (this.queue.length >= FLUSH_AT) this.flush(false);
3173
+ }
3174
+ /**
3175
+ * Sign-out (`reset()`): what is queued keeps `userId`, the user it was captured
3176
+ * under, and the session ends — the next event opens a new one.
3177
+ */
3178
+ reset(userId) {
3179
+ if (userId) {
3180
+ for (const e of this.queue) if (!isEntry(e) && e.asUser === void 0) e.asUser = userId;
3181
+ }
3182
+ try {
3183
+ this.deps.store.removeSync(SESSION_KEY);
3184
+ } catch {
3185
+ }
3186
+ }
2937
3187
  /** Records a page view of the current URL. Called by itself on route changes; exposed for routers that need it. */
2938
3188
  pageview() {
2939
3189
  const url = bare2(location.href);
@@ -2949,6 +3199,7 @@ var AnalyticsTracker = class {
2949
3199
  }
2950
3200
  /** Sends what is queued. `leaving` = the page is going away: keepalive, so the request outlives it. */
2951
3201
  flush(leaving) {
3202
+ var _a, _b;
2952
3203
  if (!this.queue.length || this.stopped) return;
2953
3204
  if (this.deps.isForgotten()) {
2954
3205
  this.stop();
@@ -2956,13 +3207,17 @@ var AnalyticsTracker = class {
2956
3207
  }
2957
3208
  const anonymousId = this.deps.anonymousId();
2958
3209
  if (!anonymousId) return;
2959
- const events = this.queue.splice(0, 100);
3210
+ const taken = takeBatch(this.queue, this.deps.userId(), 100);
3211
+ const userId = taken.userId;
3212
+ const events = userId ? taken.events.map((e) => isEntry(e) || e.asUser !== void 0 ? e : { ...e, asUser: userId }) : taken.events;
2960
3213
  const body = JSON.stringify({
2961
3214
  sdkKey: this.deps.sdkKey,
2962
3215
  anonymousId,
2963
- userId: this.deps.userId(),
3216
+ userId,
2964
3217
  debug: this.deps.isDebug() || void 0,
2965
- events
3218
+ internal: ((_b = (_a = this.deps).isInternal) == null ? void 0 : _b.call(_a)) || void 0,
3219
+ scanner: this.scanner || void 0,
3220
+ events: events.map((e) => isEntry(e) ? e : { ...e, asUser: void 0 })
2966
3221
  });
2967
3222
  try {
2968
3223
  void fetch(`${this.deps.endpoint}/ingest/analytics`, {
@@ -3017,7 +3272,7 @@ var AnalyticsTracker = class {
3017
3272
  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 : {});
3018
3273
  const g = (_f = (_e = (_d = this.deps).groups) == null ? void 0 : _e.call(_d)) != null ? _f : {};
3019
3274
  const groups = Object.keys(g).length ? { ...g } : void 0;
3020
- 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 } : {} });
3275
+ 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 } : {} });
3021
3276
  if (this.queue.length > MAX_QUEUE) this.queue.shift();
3022
3277
  if (this.queue.length >= FLUSH_AT) this.flush(false);
3023
3278
  }
@@ -3101,6 +3356,7 @@ var AnalyticsTracker = class {
3101
3356
  onError(e) {
3102
3357
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
3103
3358
  const message = (e.message || (e.error instanceof Error ? e.error.message : "") || "Script error").slice(0, 300);
3359
+ if (LINK_SCANNER_ERROR.test(message.replace(/^Uncaught (?:Error: )?/, ""))) this.scanner = true;
3104
3360
  this.errorsThisPage++;
3105
3361
  const stack = e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack.slice(0, 1500) : void 0;
3106
3362
  this.enqueue({ kind: "error", props: { message, ...stack ? { stack } : {}, ...e.filename ? { source: bare2(e.filename) } : {}, ...e.lineno ? { line: e.lineno } : {} } });
@@ -3109,6 +3365,7 @@ var AnalyticsTracker = class {
3109
3365
  if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;
3110
3366
  const reason = e.reason;
3111
3367
  const message = (reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection").slice(0, 300);
3368
+ if (LINK_SCANNER_ERROR.test(message)) this.scanner = true;
3112
3369
  this.errorsThisPage++;
3113
3370
  const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack.slice(0, 1500) : void 0;
3114
3371
  this.enqueue({ kind: "error", props: { message, unhandledRejection: true, ...stack ? { stack } : {} } });
@@ -3131,6 +3388,15 @@ function randomId() {
3131
3388
  return null;
3132
3389
  }
3133
3390
  }
3391
+ function internalParam(href) {
3392
+ try {
3393
+ const v = new URL(href).searchParams.get("traqio_internal");
3394
+ if (v === "1" || v === "true") return true;
3395
+ if (v === "0" || v === "false") return false;
3396
+ } catch {
3397
+ }
3398
+ return null;
3399
+ }
3134
3400
  var TraqioWeb = class {
3135
3401
  constructor() {
3136
3402
  this.core = new import_core.Client();
@@ -3152,6 +3418,10 @@ var TraqioWeb = class {
3152
3418
  this.groups = {};
3153
3419
  /** Group entries made before `init()` — replayed once the tracker exists. */
3154
3420
  this.earlyGroups = [];
3421
+ /** `alias()` calls made before `init()`: [userId, previousId]. */
3422
+ this.earlyAliases = [];
3423
+ /** A `reset()` before `init()`: what earlier pages kept (super-properties, accounts) is dropped, not restored. */
3424
+ this.resetBeforeInit = false;
3155
3425
  }
3156
3426
  /**
3157
3427
  * Call once, as early as possible on every page (or once in a single-page app).
@@ -3175,11 +3445,17 @@ var TraqioWeb = class {
3175
3445
  this.trackIds.capture(location.href);
3176
3446
  this.sources = new SourceKeeper(this.store, keepMs, cookieDomain, cookies);
3177
3447
  this.sources.capture(location.href, document.referrer);
3448
+ const optOut = internalParam(location.href);
3449
+ if (optOut !== null) this.setInternal(optOut);
3178
3450
  if (!this.store.getSync(DEVICE_ID_KEY)) {
3179
3451
  const id = randomId();
3180
3452
  if (id) this.store.setSync(DEVICE_ID_KEY, id);
3181
3453
  }
3182
3454
  this.userId = (_c = opts.userId) != null ? _c : this.userId;
3455
+ if (this.resetBeforeInit) {
3456
+ this.store.removeSync(SUPER_PROPS_KEY);
3457
+ this.store.removeSync(GROUPS_KEY);
3458
+ }
3183
3459
  try {
3184
3460
  const raw = this.store.getSync(SUPER_PROPS_KEY);
3185
3461
  const early = Object.keys(this.superProps).length > 0;
@@ -3220,18 +3496,45 @@ var TraqioWeb = class {
3220
3496
  groups: () => this.groups,
3221
3497
  isDebug: () => this.core.isDebug,
3222
3498
  isForgotten: () => this.core.forgotten,
3499
+ isInternal: () => this.isInternal,
3223
3500
  options: opts.analytics === true ? {} : opts.analytics
3224
3501
  });
3225
3502
  this.analytics.start();
3226
3503
  for (const [id, set, once] of this.earlyIdentifies) this.analytics.identify(id, set, once);
3227
3504
  for (const [type, key, set, once] of this.earlyGroups) this.analytics.group(type, key, set, once);
3505
+ for (const [user, prev] of this.earlyAliases) this.analytics.alias(user, prev);
3228
3506
  for (const [name, props] of this.earlyCaptures) this.analytics.capture(name, props);
3229
3507
  }
3230
3508
  this.earlyCaptures = [];
3231
3509
  this.earlyIdentifies = [];
3232
3510
  this.earlyGroups = [];
3511
+ this.earlyAliases = [];
3233
3512
  this.ready = true;
3234
3513
  }
3514
+ /**
3515
+ * Mark this browser as the team's own (`true`) or as a visitor again (`false`) — what
3516
+ * opening the site with `?traqio_internal=1` / `=0` does. Its analytics events are
3517
+ * still sent, flagged: the console leaves them out of every figure by default and
3518
+ * shows them under « Internal traffic only ». Conversions (`track()`) are not
3519
+ * affected. Kept on the device, like the visitor id (and under the same consent).
3520
+ */
3521
+ setInternal(on) {
3522
+ if (!this.store) return;
3523
+ try {
3524
+ if (on) this.store.setSync(INTERNAL_KEY, "1");
3525
+ else this.store.removeSync(INTERNAL_KEY);
3526
+ } catch {
3527
+ }
3528
+ }
3529
+ /** True when this browser opted itself out as internal traffic — see `setInternal()`. */
3530
+ get isInternal() {
3531
+ var _a;
3532
+ try {
3533
+ return ((_a = this.store) == null ? void 0 : _a.getSync(INTERNAL_KEY)) === "1";
3534
+ } catch {
3535
+ return false;
3536
+ }
3537
+ }
3235
3538
  /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
3236
3539
  get isDebug() {
3237
3540
  return this.core.isDebug;
@@ -3340,6 +3643,67 @@ var TraqioWeb = class {
3340
3643
  getGroups() {
3341
3644
  return { ...this.groups };
3342
3645
  }
3646
+ /**
3647
+ * Two ids, one person: the user known so far as `previousId` (a guest id, an id
3648
+ * from before sign-up) IS the current user (`setUserId` / `identify`). Their
3649
+ * analytics history and properties are merged under the current id — its own
3650
+ * properties win. From the browser only what THIS visitor sent under `previousId`
3651
+ * is merged; a backend (`@traqio/node`, secret key) merges everything.
3652
+ *
3653
+ * Traqio.identify("u_123");
3654
+ * Traqio.alias("guest_8f2c");
3655
+ *
3656
+ * Ignored without a current user id, or when `previousId` is the current one. Needs `analytics` at init.
3657
+ */
3658
+ alias(previousId) {
3659
+ const prev = cleanUserId(previousId);
3660
+ const user = this.userId;
3661
+ if (!user || !prev || prev === user) return;
3662
+ if (this.analytics) this.analytics.alias(user, prev);
3663
+ else if (!this.ready && this.earlyAliases.length < 10) this.earlyAliases.push([user, prev]);
3664
+ }
3665
+ /**
3666
+ * Sign-out: forget who the user was in this browser — the user id, the
3667
+ * super-properties, the accounts — and end the analytics session, so the next
3668
+ * person's visit starts clean. Events already queued keep the user they were
3669
+ * captured under. The visitor id is KEPT: it carries the visitor's attribution
3670
+ * (the click, the campaign) for the next sign-up.
3671
+ */
3672
+ reset() {
3673
+ var _a;
3674
+ const user = this.userId;
3675
+ (_a = this.analytics) == null ? void 0 : _a.reset(user);
3676
+ this.userId = void 0;
3677
+ this.core.reset();
3678
+ this.superProps = {};
3679
+ this.groups = {};
3680
+ this.earlyIdentifies = [];
3681
+ this.earlyGroups = [];
3682
+ this.earlyAliases = [];
3683
+ if (this.store) {
3684
+ this.persistSuperProps();
3685
+ this.persistGroups();
3686
+ } else this.resetBeforeInit = true;
3687
+ }
3688
+ /**
3689
+ * An experiment exposure: the visitor SAW `variant` of `experiment` — what the
3690
+ * console's experiment analysis reads (uplift, significance per variant). Your site
3691
+ * assigns the variant (its own flags, an edge split, a cookie); call this where the
3692
+ * visitor first meets it. Sends `$exposure { experiment, variant, ...props }`.
3693
+ *
3694
+ * Traqio.exposure("pricing_page", "annual_first");
3695
+ */
3696
+ exposure(experiment, variant, props) {
3697
+ const p = exposureProps(experiment, variant, props);
3698
+ if (!p) return;
3699
+ let fits = false;
3700
+ try {
3701
+ fits = JSON.stringify(p).length <= 4096;
3702
+ } catch {
3703
+ fits = false;
3704
+ }
3705
+ this.capture("$exposure", fits ? p : { experiment: p.experiment, variant: p.variant });
3706
+ }
3343
3707
  persistGroups() {
3344
3708
  try {
3345
3709
  if (!this.store) return;
@@ -3430,6 +3794,7 @@ var Traqio = new TraqioWeb();
3430
3794
  export {
3431
3795
  DEFAULT_ENDPOINT,
3432
3796
  Traqio,
3433
- TraqioWeb
3797
+ TraqioWeb,
3798
+ internalParam
3434
3799
  };
3435
3800
  //# sourceMappingURL=index.js.map