@tolinku/react-native-sdk 0.4.0 → 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/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { useState, useRef, useMemo, useEffect, useCallback } from 'react';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
 
6
6
  // src/types.ts
7
- var SDK_VERSION = "0.4.0";
7
+ var SDK_VERSION = "0.6.0";
8
8
 
9
9
  // src/debug.ts
10
10
  var _debugEnabled = false;
@@ -68,6 +68,25 @@ var HttpClient = class {
68
68
  headers: this.publicHeaders()
69
69
  });
70
70
  }
71
+ /**
72
+ * POST to a host other than the configured one, without the API key.
73
+ *
74
+ * A few public endpoints work out which Appspace they belong to from the
75
+ * hostname the request arrived on rather than from a key or an id, so a
76
+ * question about a link on a customer's own domain has to be asked on that
77
+ * domain. Everything else about the request is unchanged: same timeout, same
78
+ * retries, same headers.
79
+ */
80
+ async postPublicToOrigin(origin, path, body) {
81
+ return this.executeWithRetry(origin.replace(/\/+$/, "") + path, {
82
+ method: "POST",
83
+ headers: {
84
+ ...this.publicHeaders(),
85
+ "Content-Type": "application/json"
86
+ },
87
+ body: body ? JSON.stringify(body) : void 0
88
+ });
89
+ }
71
90
  /** POST without API key auth (for public endpoints like deferred claim) */
72
91
  async postPublic(path, body) {
73
92
  return this.executeWithRetry(this.baseUrl + path, {
@@ -247,12 +266,33 @@ function validateEventType(eventType) {
247
266
  var BATCH_SIZE = 10;
248
267
  var FLUSH_INTERVAL_MS = 5e3;
249
268
  var MAX_QUEUE_SIZE = 1e3;
250
- var Analytics = class {
269
+ var _Analytics = class _Analytics {
251
270
  constructor(client) {
252
271
  this.queue = [];
253
272
  this.flushTimer = null;
254
273
  this.appStateSubscription = null;
255
274
  this.isFlushing = false;
275
+ /**
276
+ * Track a custom event. The event is added to the internal queue
277
+ * and will be flushed automatically or when flush() is called.
278
+ *
279
+ * Event type must match /^custom\.[a-z0-9_]+$/.
280
+ * Auto-prefixes with "custom." if missing.
281
+ */
282
+ /**
283
+ * Set once the server says this Appspace does not attribute app opens, so the
284
+ * setting costs one request a launch rather than one per link.
285
+ */
286
+ this.appOpensDisabled = false;
287
+ /**
288
+ * The last link reported, and when. Cold start and the link stream can both
289
+ * deliver the same tap, depending on the plugin, so an app instrumenting both
290
+ * paths would otherwise report it twice and be billed twice. A genuine second
291
+ * tap of the same link inside this window is implausible; a duplicate delivery
292
+ * of one tap is not.
293
+ */
294
+ this.lastOpenUrl = null;
295
+ this.lastOpenAt = 0;
256
296
  this.handleAppStateChange = (state) => {
257
297
  if (state === "background" || state === "inactive") {
258
298
  this.flush().catch(() => {
@@ -266,12 +306,51 @@ var Analytics = class {
266
306
  );
267
307
  }
268
308
  /**
269
- * Track a custom event. The event is added to the internal queue
270
- * and will be flushed automatically or when flush() is called.
309
+ * Report that a link opened the app without the browser being involved.
310
+ *
311
+ * A Universal Link or App Link hands the app the URL directly, so Tolinku is
312
+ * never contacted and the tap goes unrecorded. Those taps come from people who
313
+ * already have the app, so leaving them out makes a re-engagement campaign
314
+ * look like a failure exactly when it worked.
315
+ *
316
+ * Only http and https links are reported. A custom scheme means Tolinku's own
317
+ * hand-off page opened the app, and that tap was counted when the page was
318
+ * served, so passing one does nothing rather than counting it twice.
271
319
  *
272
- * Event type must match /^custom\.[a-z0-9_]+$/.
273
- * Auto-prefixes with "custom." if missing.
320
+ * Never throws. This runs on the path that routes the user somewhere, and a
321
+ * tap that goes unrecorded is not worth interrupting that.
274
322
  */
323
+ async trackLinkOpen(url, userId) {
324
+ if (this.appOpensDisabled) return;
325
+ const trimmed = typeof url === "string" ? url.trim() : "";
326
+ if (!trimmed) return;
327
+ let parsed;
328
+ try {
329
+ parsed = new URL(trimmed);
330
+ } catch {
331
+ return;
332
+ }
333
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
334
+ const now = Date.now();
335
+ if (this.lastOpenUrl === trimmed && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
336
+ this.lastOpenUrl = trimmed;
337
+ this.lastOpenAt = now;
338
+ try {
339
+ const result = await this.client.postPublic(
340
+ "/v1/api/opens",
341
+ {
342
+ url: trimmed,
343
+ // The User-Agent cannot say which platform this is: this SDK
344
+ // identifies itself the same way on both. Without it an app open has
345
+ // no platform and lands in a blank bucket on every breakdown.
346
+ platform: Platform.OS === "ios" || Platform.OS === "android" ? Platform.OS : void 0,
347
+ ...userId ? { user_id: userId } : {}
348
+ }
349
+ );
350
+ if (result?.attribute === false) this.appOpensDisabled = true;
351
+ } catch {
352
+ }
353
+ }
275
354
  async track(eventType, properties) {
276
355
  const normalizedType = validateEventType(eventType);
277
356
  const event = {
@@ -347,6 +426,8 @@ var Analytics = class {
347
426
  }
348
427
  }
349
428
  };
429
+ _Analytics.OPEN_DEDUPE_MS = 5e3;
430
+ var Analytics = _Analytics;
350
431
  var BATCH_SIZE2 = 10;
351
432
  var FLUSH_INTERVAL_MS2 = 5e3;
352
433
  var MAX_QUEUE_SIZE2 = 500;
@@ -741,17 +822,17 @@ var Deferred = class {
741
822
  async attemptSignals(options) {
742
823
  try {
743
824
  const { width, height } = Dimensions.get("screen");
744
- const resolvedTimezone = options.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
745
- const resolvedLanguage = options.language || (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function" ? Intl.DateTimeFormat().resolvedOptions().locale : void 0) || "en";
825
+ const resolvedTimezone = override(options.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone;
826
+ const resolvedLanguage = override(options.language) || (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function" ? Intl.DateTimeFormat().resolvedOptions().locale : void 0) || "en";
746
827
  const link = await this.client.postPublic("/v1/api/deferred/claim-by-signals", {
747
828
  appspace_id: options.appspaceId,
748
829
  timezone: resolvedTimezone,
749
830
  language: resolvedLanguage,
750
- screen_width: options.screenWidth || width,
751
- screen_height: options.screenHeight || height,
831
+ screen_width: override(options.screenWidth) || width,
832
+ screen_height: override(options.screenHeight) || height,
752
833
  // Separates devices reporting identical dp dimensions.
753
- device_pixel_ratio: options.devicePixelRatio || PixelRatio.get(),
754
- os_version: options.osVersion || String(Platform.Version)
834
+ device_pixel_ratio: override(options.devicePixelRatio) || PixelRatio.get(),
835
+ os_version: override(options.osVersion) || String(Platform.Version)
755
836
  });
756
837
  return { link, settled: true };
757
838
  } catch (err) {
@@ -771,6 +852,61 @@ var Deferred = class {
771
852
  }
772
853
  }
773
854
  };
855
+ function override(value) {
856
+ if (typeof value === "string") {
857
+ const trimmed = value.trim();
858
+ return trimmed === "" ? void 0 : trimmed;
859
+ }
860
+ if (typeof value === "number") {
861
+ return Number.isFinite(value) && value > 0 ? value : void 0;
862
+ }
863
+ return void 0;
864
+ }
865
+
866
+ // src/links.ts
867
+ function isRoutablePath(path) {
868
+ return typeof path === "string" && path.startsWith("/") && !path.startsWith("//");
869
+ }
870
+ var Links = class {
871
+ constructor(client) {
872
+ this.client = client;
873
+ }
874
+ /**
875
+ * What this link means, or null if it means nothing here.
876
+ *
877
+ * `url` is a whole link as the app received it. The question goes to the
878
+ * link's own host, because that is how the platform knows which Appspace is
879
+ * being asked about, which also means a link on a domain that is not yours
880
+ * simply answers nothing.
881
+ *
882
+ * Never throws. A link that cannot be resolved, for a bad network or any
883
+ * other reason, is one the app should fall back to its own handling for, and
884
+ * an exception in the middle of a cold start is no way to say so.
885
+ */
886
+ async resolve(url) {
887
+ if (!url || typeof url !== "string") return null;
888
+ let parsed;
889
+ try {
890
+ parsed = new URL(url.trim());
891
+ } catch {
892
+ debugWarn(`Links.resolve: not a URL: ${url}`);
893
+ return null;
894
+ }
895
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
896
+ try {
897
+ const result = await this.client.postPublicToOrigin(
898
+ parsed.origin,
899
+ "/v1/api/path",
900
+ { path: parsed.pathname }
901
+ );
902
+ if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;
903
+ return result;
904
+ } catch (err) {
905
+ debugWarn(`Links.resolve failed: ${err.message}`);
906
+ return null;
907
+ }
908
+ }
909
+ };
774
910
  var BASE_KEY = "tolinku_message_dismissed";
775
911
  var IMPRESSIONS_BASE_KEY = "tolinku_message_impressions";
776
912
  var LAST_SHOWN_BASE_KEY = "tolinku_message_last_shown";
@@ -894,6 +1030,7 @@ var _Tolinku = class _Tolinku {
894
1030
  _Tolinku.ecommerceInstance = new Ecommerce(_Tolinku.client, () => _Tolinku._userId);
895
1031
  _Tolinku.referralsInstance = new Referrals(_Tolinku.client);
896
1032
  _Tolinku.deferredInstance = new Deferred(_Tolinku.client);
1033
+ _Tolinku.linksInstance = new Links(_Tolinku.client);
897
1034
  _Tolinku._initialized = true;
898
1035
  debugLog(`Tolinku SDK v${SDK_VERSION} initialized (baseUrl=${baseUrl})`);
899
1036
  }
@@ -931,6 +1068,41 @@ var _Tolinku = class _Tolinku {
931
1068
  const mergedProps = _Tolinku._userId ? { user_id: _Tolinku._userId, ...properties } : properties;
932
1069
  return _Tolinku.analyticsInstance.track(eventType, mergedProps);
933
1070
  }
1071
+ /**
1072
+ * Report that a link opened the app, when it opened without the browser.
1073
+ *
1074
+ * A Universal Link or App Link hands the app the URL directly, so Tolinku is
1075
+ * never contacted and the tap goes unrecorded. Those taps come from people who
1076
+ * already have your app, so leaving them out makes a re-engagement campaign
1077
+ * look like a failure exactly when it worked.
1078
+ *
1079
+ * Both ways a link arrives need it. The listener fires only while the app is
1080
+ * already running, so a link that launched the app cold arrives separately:
1081
+ *
1082
+ * ```ts
1083
+ * // Launched by a link, app was not running.
1084
+ * const initial = await Linking.getInitialURL();
1085
+ * if (initial) Tolinku.trackLinkOpen(initial);
1086
+ *
1087
+ * // Tapped while the app was already open.
1088
+ * Linking.addEventListener('url', ({ url }) => {
1089
+ * Tolinku.trackLinkOpen(url);
1090
+ * // your own routing
1091
+ * });
1092
+ * ```
1093
+ *
1094
+ * Wiring both is safe: the same link arriving twice in quick succession is
1095
+ * reported once.
1096
+ *
1097
+ * Only http and https links are reported. A custom scheme means Tolinku's own
1098
+ * hand-off page opened the app, and that tap is already counted.
1099
+ *
1100
+ * Never throws.
1101
+ */
1102
+ static async trackLinkOpen(url) {
1103
+ if (!_Tolinku.analyticsInstance) return;
1104
+ return _Tolinku.analyticsInstance.trackLinkOpen(url, _Tolinku._userId ?? void 0);
1105
+ }
934
1106
  /**
935
1107
  * Immediately flush all queued analytics and ecommerce events to the server.
936
1108
  */
@@ -964,6 +1136,18 @@ var _Tolinku = class _Tolinku {
964
1136
  }
965
1137
  return _Tolinku.deferredInstance;
966
1138
  }
1139
+ /**
1140
+ * Turning a link the app was handed into the route and token it means.
1141
+ *
1142
+ * Needed for short links, which arrive as an opaque code that nothing on the
1143
+ * device can interpret. See {@link Links.resolve}.
1144
+ */
1145
+ static get links() {
1146
+ if (!_Tolinku.linksInstance) {
1147
+ throw new Error("Tolinku: SDK not initialized. Call Tolinku.init() first.");
1148
+ }
1149
+ return _Tolinku.linksInstance;
1150
+ }
967
1151
  /**
968
1152
  * Shut down the SDK and release resources.
969
1153
  * Flushes remaining analytics events, cancels timers, removes listeners,
@@ -987,6 +1171,7 @@ var _Tolinku = class _Tolinku {
987
1171
  _Tolinku.ecommerceInstance = null;
988
1172
  _Tolinku.referralsInstance = null;
989
1173
  _Tolinku.deferredInstance = null;
1174
+ _Tolinku.linksInstance = null;
990
1175
  _Tolinku._initialized = false;
991
1176
  _Tolinku._userId = null;
992
1177
  setDebugEnabled(false);
@@ -998,6 +1183,7 @@ _Tolinku.analyticsInstance = null;
998
1183
  _Tolinku.ecommerceInstance = null;
999
1184
  _Tolinku.referralsInstance = null;
1000
1185
  _Tolinku.deferredInstance = null;
1186
+ _Tolinku.linksInstance = null;
1001
1187
  _Tolinku._initialized = false;
1002
1188
  _Tolinku._userId = null;
1003
1189
  var Tolinku = _Tolinku;
@@ -1065,13 +1251,14 @@ function PuckComponentRenderer({ component, messageId, options }) {
1065
1251
  case "Button": {
1066
1252
  const handlePress = () => {
1067
1253
  const action = props.action || "";
1254
+ if (!action) return;
1255
+ if (!isSafeUrl(action)) {
1256
+ debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);
1257
+ return;
1258
+ }
1068
1259
  if (options.onButtonPress) {
1069
1260
  options.onButtonPress(action, messageId);
1070
- } else if (action) {
1071
- if (!isSafeUrl(action)) {
1072
- debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);
1073
- return;
1074
- }
1261
+ } else {
1075
1262
  Linking.openURL(action).catch(() => {
1076
1263
  });
1077
1264
  }