@traqio/web 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -112,6 +112,9 @@ networks.
112
112
  | `waitForConsent` | `false` | Store nothing until `setConsent(true)` |
113
113
  | `trackIdDays` | `30` | How long the trackID is kept after the click |
114
114
  | `cookies` | `true` | `false` = localStorage only, no sharing across subdomains |
115
+ | `debug` | detected | Debug traffic, kept out of every report (see below) |
116
+
117
+ **Debug traffic.** Omitted, `debug` is on for a page served from `localhost`, `127.0.0.1`, `*.localhost`, `*.local` or `file:`, and off everywhere else; `true` forces it (a staging site), `false` counts a local page. `traqio.isDebug` tells which mode is on. Debug traffic shows in the console's **Live events › Debug** view, but it is never counted in a report, attributed, sent to an ad network or a webhook, or billed.
115
118
 
116
119
  ## Requirements
117
120
 
package/build/index.cjs CHANGED
@@ -269,7 +269,8 @@ var require_adservices = __commonJS({
269
269
  sdkKey: opts.sdkKey,
270
270
  token: token.trim(),
271
271
  deviceId: opts.deviceId,
272
- appUserId: opts.userId
272
+ appUserId: opts.userId,
273
+ ...opts.debug ? { debug: true } : {}
273
274
  })
274
275
  });
275
276
  if (!res.ok)
@@ -304,17 +305,51 @@ var require_deeplink = __commonJS({
304
305
  "use strict";
305
306
  Object.defineProperty(exports, "__esModule", { value: true });
306
307
  exports.isTrackingUrl = isTrackingUrl;
308
+ exports.isOpenUrl = isOpenUrl;
307
309
  exports.toDeepLink = toDeepLink;
310
+ exports.upgradeStoredDeepLink = upgradeStoredDeepLink;
308
311
  var TRACKING_PATH = /^\/c\/[A-Za-z0-9_-]{1,50}\/?$/;
309
- function isTrackingUrl(url) {
312
+ var OPEN_PATH = /^\/o\/[0-9a-fA-F-]{36}\/?$/;
313
+ function pathOf(url) {
310
314
  var _a;
311
315
  const m = /^https?:\/\/[^/?#]+(\/[^?#]*)?/i.exec(url);
312
- return Boolean(m && TRACKING_PATH.test((_a = m[1]) != null ? _a : ""));
316
+ return m ? (_a = m[1]) != null ? _a : "" : null;
317
+ }
318
+ function isTrackingUrl(url) {
319
+ const path = pathOf(url);
320
+ return path !== null && (TRACKING_PATH.test(path) || OPEN_PATH.test(path));
321
+ }
322
+ function isOpenUrl(url) {
323
+ const path = pathOf(url);
324
+ return path !== null && OPEN_PATH.test(path);
313
325
  }
314
326
  function toDeepLink(answer, deferred, url) {
327
+ var _a, _b, _c;
315
328
  if (!(answer == null ? void 0 : answer.matched) || !answer.via)
316
329
  return null;
317
- return { deepLink: answer.deepLink, code: answer.code, deferred, via: answer.via, ...url ? { url } : {} };
330
+ const matchType = (_a = answer.matchType) != null ? _a : answer.via === "ip_match" ? "probabilistic" : answer.via;
331
+ const payload = (_b = answer.payload) != null ? _b : { deepLink: answer.deepLink, value: null, params: {} };
332
+ return {
333
+ payload,
334
+ matchType,
335
+ confidence: matchType === "probabilistic" ? (_c = answer.confidence) != null ? _c : "low" : null,
336
+ deferred,
337
+ code: answer.code,
338
+ deepLink: payload.deepLink,
339
+ via: answer.via,
340
+ ...url ? { url } : {}
341
+ };
342
+ }
343
+ function upgradeStoredDeepLink(stored) {
344
+ var _a, _b, _c;
345
+ if (!stored || typeof stored !== "object")
346
+ return null;
347
+ const link = stored;
348
+ if (link.payload && link.matchType)
349
+ return link;
350
+ if (!link.via)
351
+ return null;
352
+ return toDeepLink({ matched: true, via: link.via, code: (_a = link.code) != null ? _a : null, deepLink: (_b = link.deepLink) != null ? _b : null }, (_c = link.deferred) != null ? _c : true, link.url);
318
353
  }
319
354
  }
320
355
  });
@@ -332,13 +367,15 @@ var require_build = __commonJS({
332
367
  "../sdk-core/build/index.js"(exports) {
333
368
  "use strict";
334
369
  Object.defineProperty(exports, "__esModule", { value: true });
335
- exports.Traqio = exports.Client = exports.isTrackingUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
370
+ exports.Traqio = exports.Client = exports.isTrackingUrl = exports.isOpenUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
336
371
  exports.normalizeAdvertisingId = normalizeAdvertisingId;
337
372
  exports.fromMaxAd = fromMaxAd;
373
+ exports.detectDebug = detectDebug;
374
+ exports.isLocalPage = isLocalPage;
338
375
  var skan_1 = require_skan();
339
376
  var adservices_1 = require_adservices();
340
377
  var deeplink_1 = require_deeplink();
341
- exports.SDK_VERSION = "0.1.2";
378
+ exports.SDK_VERSION = "0.3.0";
342
379
  var skan_2 = require_skan();
343
380
  Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
344
381
  return skan_2.Skan;
@@ -348,10 +385,14 @@ var require_build = __commonJS({
348
385
  return adservices_2.reportAdServicesToken;
349
386
  } });
350
387
  var deeplink_2 = require_deeplink();
388
+ Object.defineProperty(exports, "isOpenUrl", { enumerable: true, get: function() {
389
+ return deeplink_2.isOpenUrl;
390
+ } });
351
391
  Object.defineProperty(exports, "isTrackingUrl", { enumerable: true, get: function() {
352
392
  return deeplink_2.isTrackingUrl;
353
393
  } });
354
394
  var INSTALL_SENT_KEY = "traq_install_sent";
395
+ var INSTALL_SENT_DEBUG_KEY = "traq_install_sent_debug";
355
396
  var INSTALL_ATTEMPTS_KEY = "traq_install_attempts";
356
397
  var REFERRER_KEY = "traq_referrer";
357
398
  var QUEUE_KEY = "traq_queue";
@@ -360,6 +401,8 @@ var require_build = __commonJS({
360
401
  var LAST_SESSION_KEY = "traq_last_session";
361
402
  var ERASED_KEY = "traq_erased";
362
403
  var DEFERRED_KEY = "traq_deferred_link";
404
+ var DEFERRED_RETRY_KEY = "traq_deferred_consent_retry_until";
405
+ var DEFERRED_RETRY_WINDOW_MS = 60 * 6e4;
363
406
  var CONSENT_KEY = "traq_consent";
364
407
  var MAX_BATCH = 20;
365
408
  var NON_RETRYABLE_STATUS = /* @__PURE__ */ new Set([400, 413, 422]);
@@ -458,6 +501,11 @@ var require_build = __commonJS({
458
501
  this.undelivered = [];
459
502
  this.deferred = null;
460
503
  this.consent = null;
504
+ this.debug = false;
505
+ }
506
+ /** Whether this run is in debug mode — see `InitOptions.debug`. Settled by `init()`. */
507
+ get isDebug() {
508
+ return this.debug;
461
509
  }
462
510
  async init(opts) {
463
511
  var _a;
@@ -468,6 +516,7 @@ var require_build = __commonJS({
468
516
  if (!this.opts.storage) {
469
517
  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.");
470
518
  }
519
+ this.debug = await detectDebug(opts);
471
520
  await this.restoreConsent(opts.consent);
472
521
  await this.restoreQueue();
473
522
  await this.restoreAdQueue();
@@ -475,10 +524,10 @@ var require_build = __commonJS({
475
524
  if (await this.restoreErased())
476
525
  return;
477
526
  if (!this.isWeb) {
478
- const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(INSTALL_SENT_KEY).catch(() => "1");
527
+ const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(this.installSentKey).catch(() => "1");
479
528
  await this.sendInstallOnce();
480
529
  if (this.opts.deepLinking !== false) {
481
- this.deferred = this.resolveDeferredOnce(freshInstall);
530
+ this.deferred = this.resolveDeferredOnce(freshInstall).then((link) => link != null ? link : this.retryDeferredWithConsent());
482
531
  this.wireDeepLinks();
483
532
  }
484
533
  }
@@ -596,20 +645,47 @@ var require_build = __commonJS({
596
645
  if (!this.started || this.erased || this.opts.deepLinking === false || !(0, deeplink_1.isTrackingUrl)(url))
597
646
  return null;
598
647
  const answer = await this.postJson({ url }, "/deeplink/open");
599
- const link = (0, deeplink_1.toDeepLink)(answer, false, url);
648
+ const deferred = (0, deeplink_1.isOpenUrl)(url);
649
+ const link = (0, deeplink_1.toDeepLink)(answer, deferred, url);
650
+ if (link && deferred)
651
+ await this.keepDeferred(link);
600
652
  if (link)
601
653
  this.emitDeepLink(link);
602
654
  return link;
603
655
  }
604
656
  /**
605
- * The deferred deep link of this install, if it came from one — resolved once,
606
- * on the first launch, and remembered. Null on every install that did not
607
- * come from a link (and on iOS unless the IP match is on for this app).
657
+ * The deferred deep link of this install, if it came from one — resolved on the
658
+ * first launch and remembered. Null on every install that did not come from a
659
+ * link. `matchType` says how it was found; read `payload.value` for the token the
660
+ * shared URL carried (`deep_link_value`).
661
+ *
662
+ * iOS has no install referrer: the deterministic carriers there are the landing
663
+ * page's « Open in app » link (delivered through `handleUrl` / `onDeepLink`) and
664
+ * its code (`redeemDeepLinkCode`). The probabilistic fallback runs only when the
665
+ * user consented — `setConsent(true)` or `consent: true` at init — and the app
666
+ * turned the IP match on in the console.
608
667
  */
609
668
  getDeferredDeepLink() {
610
669
  var _a;
611
670
  return (_a = this.deferred) != null ? _a : Promise.resolve(null);
612
671
  }
672
+ /**
673
+ * The code the iOS landing page showed (« ABCD-EFGH »), typed by the user in the
674
+ * app — the manual fallback when neither the store nor a link carried the click.
675
+ * Case, spaces and the dash are forgiven. Resolves to the link (`matchType:
676
+ * "code"`), delivered to `onDeepLink` too, or null for an unknown / expired code.
677
+ */
678
+ async redeemDeepLinkCode(code) {
679
+ if (!this.started || this.erased || this.opts.deepLinking === false || !code.trim())
680
+ return null;
681
+ const answer = await this.postJson({ code }, "/deeplink/code");
682
+ const link = (0, deeplink_1.toDeepLink)(answer, true);
683
+ if (!link)
684
+ return null;
685
+ await this.keepDeferred(link);
686
+ this.emitDeepLink(link);
687
+ return link;
688
+ }
613
689
  /**
614
690
  * GDPR Art. 17, from inside the app: delete everything the server holds about this
615
691
  * device and this user, and stop sending.
@@ -653,6 +729,10 @@ var require_build = __commonJS({
653
729
  var _a, _b;
654
730
  this.consent = granted ? "granted" : "denied";
655
731
  await ((_b = (_a = this.opts) == null ? void 0 : _a.storage) == null ? void 0 : _b.setItem(CONSENT_KEY, this.consent).catch(() => void 0));
732
+ if (granted && this.deferred && !this.erased) {
733
+ this.deferred = this.deferred.then((link) => link != null ? link : this.retryDeferredWithConsent());
734
+ await this.deferred;
735
+ }
656
736
  }
657
737
  /** True once `forgetMe()` has been honoured — this install sends nothing any more. */
658
738
  get forgotten() {
@@ -707,7 +787,8 @@ var require_build = __commonJS({
707
787
  deviceId: this.context.deviceId,
708
788
  userId: this.opts.userId,
709
789
  storage: this.opts.storage,
710
- native: { getAttributionToken: () => native.getAttributionToken() }
790
+ native: { getAttributionToken: () => native.getAttributionToken() },
791
+ debug: this.debug
711
792
  });
712
793
  }
713
794
  async initSkan() {
@@ -739,7 +820,7 @@ var require_build = __commonJS({
739
820
  try {
740
821
  const cached = await (store == null ? void 0 : store.getItem(DEFERRED_KEY));
741
822
  if (cached)
742
- return JSON.parse(cached);
823
+ return (0, deeplink_1.upgradeStoredDeepLink)(JSON.parse(cached));
743
824
  } catch {
744
825
  }
745
826
  if (!freshInstall && !await (store == null ? void 0 : store.getItem(`${DEFERRED_KEY}_pending`).catch(() => null)))
@@ -747,18 +828,78 @@ var require_build = __commonJS({
747
828
  const platform = (_b = (_a = this.opts.native) == null ? void 0 : _a.platform) != null ? _b : "android";
748
829
  const referrer = platform === "android" ? await this.readReferrer() : null;
749
830
  await (store == null ? void 0 : store.setItem(`${DEFERRED_KEY}_pending`, "1").catch(() => void 0));
750
- const answer = await this.postJson({ platform, installReferrer: referrer == null ? void 0 : referrer.referrer }, "/deeplink/deferred");
831
+ const answer = await this.askDeferred(platform, referrer == null ? void 0 : referrer.referrer);
751
832
  if (!answer)
752
833
  return null;
753
834
  const link = (0, deeplink_1.toDeepLink)(answer, true);
835
+ const kept = await this.storedDeferred();
836
+ if (kept)
837
+ return kept;
754
838
  try {
755
839
  await (store == null ? void 0 : store.setItem(DEFERRED_KEY, JSON.stringify(link)));
840
+ if (!link && this.consent !== "granted") {
841
+ await (store == null ? void 0 : store.setItem(DEFERRED_RETRY_KEY, String(Date.now() + DEFERRED_RETRY_WINDOW_MS)));
842
+ }
756
843
  } catch {
757
844
  }
758
845
  if (link)
759
846
  this.emitDeepLink(link);
760
847
  return link;
761
848
  }
849
+ /** The deferred ask: the referrer (Android), the consent, and what the tap is compared with. */
850
+ askDeferred(platform, installReferrer) {
851
+ return this.postJson({
852
+ platform,
853
+ installReferrer,
854
+ ...this.consent ? { consent: this.consent } : {},
855
+ ...this.context.osVersion ? { osVersion: this.context.osVersion } : {},
856
+ ...this.context.deviceModel ? { deviceModel: this.context.deviceModel } : {}
857
+ }, "/deeplink/deferred");
858
+ }
859
+ /**
860
+ * The user consented AFTER the first launch asked without consent and found
861
+ * nothing: ask once more, inside the hour, so the probabilistic layer can run.
862
+ * Never when a link is already known, never twice.
863
+ */
864
+ async retryDeferredWithConsent() {
865
+ var _a, _b, _c, _d;
866
+ const store = (_a = this.opts) == null ? void 0 : _a.storage;
867
+ if (!store || this.consent !== "granted" || this.opts.deepLinking === false || this.isWeb)
868
+ return null;
869
+ const until = Number(await store.getItem(DEFERRED_RETRY_KEY).catch(() => null));
870
+ if (!until)
871
+ return null;
872
+ await store.setItem(DEFERRED_RETRY_KEY, "").catch(() => void 0);
873
+ if (Date.now() > until)
874
+ return null;
875
+ const known = await this.storedDeferred();
876
+ if (known)
877
+ return known;
878
+ const link = (0, deeplink_1.toDeepLink)(await this.askDeferred((_c = (_b = this.opts.native) == null ? void 0 : _b.platform) != null ? _c : "ios", void 0), true);
879
+ if (!link)
880
+ return null;
881
+ await ((_d = this.opts.storage) == null ? void 0 : _d.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => void 0));
882
+ this.emitDeepLink(link);
883
+ return link;
884
+ }
885
+ /** The deferred link already stored for this install, if any. */
886
+ async storedDeferred() {
887
+ var _a;
888
+ try {
889
+ const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(DEFERRED_KEY));
890
+ return raw ? (0, deeplink_1.upgradeStoredDeepLink)(JSON.parse(raw)) : null;
891
+ } catch {
892
+ return null;
893
+ }
894
+ }
895
+ /** Remember `link` as this install's deferred link, unless one is already known. */
896
+ async keepDeferred(link) {
897
+ var _a;
898
+ if (await this.storedDeferred())
899
+ return;
900
+ await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(DEFERRED_KEY, JSON.stringify(link)).catch(() => void 0));
901
+ this.deferred = Promise.resolve(link);
902
+ }
762
903
  emitDeepLink(link) {
763
904
  if (!this.deepLinkListeners.size) {
764
905
  this.undelivered.push(link);
@@ -785,6 +926,13 @@ var require_build = __commonJS({
785
926
  var _a;
786
927
  return ((_a = this.opts) == null ? void 0 : _a.platform) === "web";
787
928
  }
929
+ get installSentKey() {
930
+ return this.debug ? INSTALL_SENT_DEBUG_KEY : INSTALL_SENT_KEY;
931
+ }
932
+ /** Spread into every body: present only in debug mode, so a release build's payload is unchanged. */
933
+ debugField() {
934
+ return this.debug ? { debug: true } : {};
935
+ }
788
936
  wireLifecycle() {
789
937
  const events = {
790
938
  background: () => this.flush(),
@@ -996,7 +1144,7 @@ var require_build = __commonJS({
996
1144
  async sendInstallOnce() {
997
1145
  var _a, _b;
998
1146
  const store = this.opts.storage;
999
- if (store && await store.getItem(INSTALL_SENT_KEY))
1147
+ if (store && await store.getItem(this.installSentKey))
1000
1148
  return;
1001
1149
  const platform = (_b = (_a = this.opts.native) == null ? void 0 : _a.platform) != null ? _b : "android";
1002
1150
  const referrer = await this.readReferrer();
@@ -1017,7 +1165,7 @@ var require_build = __commonJS({
1017
1165
  }
1018
1166
  });
1019
1167
  if (ok)
1020
- await (store == null ? void 0 : store.setItem(INSTALL_SENT_KEY, "1"));
1168
+ await (store == null ? void 0 : store.setItem(this.installSentKey, "1"));
1021
1169
  }
1022
1170
  scheduleFlush(delay = FLUSH_DELAY_MS) {
1023
1171
  if (this.flushTimer)
@@ -1092,7 +1240,7 @@ var require_build = __commonJS({
1092
1240
  const res = await fetch(`${this.opts.endpoint}${path}`, {
1093
1241
  method: "POST",
1094
1242
  headers: { "Content-Type": "application/json" },
1095
- body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body }),
1243
+ body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...this.debugField() }),
1096
1244
  ...this.keepalive()
1097
1245
  });
1098
1246
  return res.ok ? await res.json() : null;
@@ -1137,7 +1285,7 @@ var require_build = __commonJS({
1137
1285
  const res = await fetch(`${this.opts.endpoint}${path}`, {
1138
1286
  method: "POST",
1139
1287
  headers: { "Content-Type": "application/json" },
1140
- body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...consent }),
1288
+ body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...consent, ...this.debugField() }),
1141
1289
  ...this.keepalive()
1142
1290
  });
1143
1291
  if (res.ok)
@@ -1149,6 +1297,28 @@ var require_build = __commonJS({
1149
1297
  }
1150
1298
  };
1151
1299
  exports.Client = Client2;
1300
+ async function detectDebug(opts) {
1301
+ var _a, _b;
1302
+ if (opts.debug !== void 0)
1303
+ return opts.debug;
1304
+ if (opts.platform === "web")
1305
+ return isLocalPage();
1306
+ if (globalThis.__DEV__ === true)
1307
+ return true;
1308
+ try {
1309
+ return await ((_b = (_a = opts.native) == null ? void 0 : _a.isDebugBuild) == null ? void 0 : _b.call(_a)) === true;
1310
+ } catch {
1311
+ return false;
1312
+ }
1313
+ }
1314
+ function isLocalPage(loc = globalThis.location) {
1315
+ if (!loc)
1316
+ return false;
1317
+ if (loc.protocol === "file:")
1318
+ return true;
1319
+ const host = loc.hostname.toLowerCase().replace(/^\[|\]$/g, "");
1320
+ return host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host === "::1" || host === "0.0.0.0" || /^127\.\d+\.\d+\.\d+$/.test(host);
1321
+ }
1152
1322
  exports.Traqio = new Client2();
1153
1323
  }
1154
1324
  });
@@ -1440,12 +1610,17 @@ var TraqioWeb = class {
1440
1610
  platform: "web",
1441
1611
  userId: opts.userId,
1442
1612
  consent,
1613
+ debug: opts.debug,
1443
1614
  lifecycle: ({ background, foreground }) => {
1444
1615
  document.addEventListener("visibilitychange", () => document.visibilityState === "hidden" ? background() : foreground());
1445
1616
  window.addEventListener("pagehide", background);
1446
1617
  }
1447
1618
  });
1448
1619
  }
1620
+ /** Whether this page runs in debug mode — see `WebInitOptions.debug`. Settled by `init()`. */
1621
+ get isDebug() {
1622
+ return this.core.isDebug;
1623
+ }
1449
1624
  /** Record an event — `signup`, `purchase`, `add_to_cart`… Batched, retried, kept across page loads. */
1450
1625
  track(name, props) {
1451
1626
  this.core.track(name, props);