@tolinku/react-native-sdk 0.8.0 → 0.8.2

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.d.mts CHANGED
@@ -10,6 +10,20 @@ interface TolinkuConfig {
10
10
  debug?: boolean;
11
11
  /** Request timeout in milliseconds. Defaults to 30000 (30 seconds). */
12
12
  timeout?: number;
13
+ /**
14
+ * Report incoming links automatically, instead of calling trackLinkOpen by
15
+ * hand. Defaults to false.
16
+ *
17
+ * Off by default because a reported open is billed as a click. Turning this
18
+ * on by upgrading would raise somebody's bill without them asking, so it is
19
+ * a decision the app makes rather than one a release makes for it.
20
+ *
21
+ * Covers both ways a link arrives on React Native, the cold start and the
22
+ * listener, which is the pair that is easy to get half right by hand. It does
23
+ * not cover the open after a deferred install: only your app knows that it
24
+ * just claimed a link, so that one is still reported explicitly.
25
+ */
26
+ autoTrackLinkOpens?: boolean;
13
27
  }
14
28
  /** Resolved configuration with all defaults applied */
15
29
  interface ResolvedTolinkuConfig {
@@ -101,6 +115,15 @@ interface LeaderboardEntry {
101
115
  interface DeferredLink {
102
116
  deep_link_path: string;
103
117
  appspace_id: string;
118
+ /**
119
+ * The absolute URL for this link, for reporting the open that follows.
120
+ *
121
+ * Reporting an open needs the whole URL, not the path: the host is how the
122
+ * server finds the Appspace and the only thing proving the link belongs to
123
+ * it, and the device has no way to know it. Absent from servers older than
124
+ * this field, so treat it as optional.
125
+ */
126
+ url?: string;
104
127
  referrer_id?: string;
105
128
  referral_code?: string;
106
129
  }
@@ -274,6 +297,29 @@ declare class HttpClient {
274
297
  * retries, same headers.
275
298
  */
276
299
  postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T>;
300
+ /**
301
+ * The hostname of the configured API, lowercased and without a port, for
302
+ * telling whether some other URL points at the same host. Empty if the base
303
+ * URL cannot be read, which init's validation should already have ruled out.
304
+ */
305
+ get apiHostname(): string;
306
+ /** Whether there is a key to send, so callers can skip a call that would only be refused. */
307
+ get hasApiKey(): boolean;
308
+ /**
309
+ * POST once, without the API key, to a host other than the configured one,
310
+ * and hand back whatever came back, whatever the status.
311
+ *
312
+ * For a question that must not be asked twice: no retries, and its own time
313
+ * limit rather than the client's. Throws only when there is no reply at all
314
+ * (a network failure, the time limit, or a destroyed client).
315
+ */
316
+ postPublicOnceToOrigin(origin: string, path: string, body: Record<string, unknown>, timeoutMs: number): Promise<OnceReply>;
317
+ /**
318
+ * POST once, with the API key, to the configured API. Same terms as
319
+ * {@link postPublicOnceToOrigin}: one attempt, its own time limit, the reply
320
+ * handed back whatever its status.
321
+ */
322
+ postOnce(path: string, body: Record<string, unknown>, timeoutMs: number): Promise<OnceReply>;
277
323
  /** POST without API key auth (for public endpoints like deferred claim) */
278
324
  postPublic<T>(path: string, body?: Record<string, unknown>): Promise<T>;
279
325
  /**
@@ -283,6 +329,12 @@ declare class HttpClient {
283
329
  abort(): void;
284
330
  private authenticatedHeaders;
285
331
  private publicHeaders;
332
+ /**
333
+ * One request, one attempt, aborted after `timeoutMs`. The body is read as
334
+ * JSON when it is JSON and left undefined when it is not, so the caller can
335
+ * tell a reply from our own server apart from somebody else's error page.
336
+ */
337
+ private executeOnce;
286
338
  /**
287
339
  * Execute a fetch request with retry logic. Retries on:
288
340
  * - Network errors (fetch throws)
@@ -294,6 +346,11 @@ declare class HttpClient {
294
346
  */
295
347
  private executeWithRetry;
296
348
  }
349
+ /** A reply to a single attempt: its status, and its body if that was JSON. */
350
+ interface OnceReply {
351
+ status: number;
352
+ body: unknown;
353
+ }
297
354
  declare class TolinkuError extends Error {
298
355
  status: number;
299
356
  code: string | undefined;
@@ -430,14 +487,23 @@ declare class Links {
430
487
  *
431
488
  * `url` is a whole link as the app received it. The question goes to the
432
489
  * link's own host, because that is how the platform knows which Appspace is
433
- * being asked about, which also means a link on a domain that is not yours
434
- * simply answers nothing.
490
+ * being asked about. If that host is not Tolinku's (no reply, or one that is
491
+ * not ours), and it is not the API's own host, the question goes once more to
492
+ * the configured API with the key: a link in an email arrives wrapped in the
493
+ * email platform's click tracking domain, which knows nothing about routes,
494
+ * and the API can unwrap it.
495
+ *
496
+ * Each question is asked once, with a five second limit. Asking a click
497
+ * tracking host again would count the email click again.
435
498
  *
436
499
  * Never throws. A link that cannot be resolved, for a bad network or any
437
500
  * other reason, is one the app should fall back to its own handling for, and
438
501
  * an exception in the middle of a cold start is no way to say so.
439
502
  */
440
503
  resolve(url: string): Promise<ResolvedLink | null>;
504
+ private resolveLink;
505
+ /** One request; null when there was no reply at all. */
506
+ private askOnce;
441
507
  }
442
508
 
443
509
  /**
@@ -450,7 +516,7 @@ declare class Links {
450
516
  * await Tolinku.track('signup', { source: 'onboarding' });
451
517
  */
452
518
  declare class Tolinku {
453
- static readonly VERSION = "0.8.0";
519
+ static readonly VERSION = "0.8.2";
454
520
  private static client;
455
521
  private static analyticsInstance;
456
522
  private static ecommerceInstance;
@@ -474,7 +540,28 @@ declare class Tolinku {
474
540
  * moving off it is a one-line change rather than a surprise.
475
541
  */
476
542
  static configure(config: TolinkuConfig): void;
543
+ /**
544
+ * Removes the automatic link listener, when one was installed.
545
+ *
546
+ * Held here rather than inside Analytics because it is a property of this
547
+ * configuration: destroy() has to take it back down or a reconfigured SDK
548
+ * reports every link twice.
549
+ */
550
+ private static linkSubscription;
477
551
  static init(config: TolinkuConfig): void;
552
+ /**
553
+ * Report incoming links without the app wiring anything.
554
+ *
555
+ * A link arrives in two places and both need reporting: one that launches the
556
+ * app cold arrives at getInitialURL, one tapped while it is already running
557
+ * arrives at the listener. Instrumenting only the second is the common
558
+ * mistake, because it works in every test done by hand with the app open.
559
+ *
560
+ * Both are wired, and the same link arriving at both inside a few seconds is
561
+ * reported once: trackLinkOpen drops a repeat of the same URL, which is why
562
+ * covering both here is safe rather than double counting.
563
+ */
564
+ private static startAutoLinkTracking;
478
565
  /** Check whether the SDK has been initialized. */
479
566
  static isConfigured(): boolean;
480
567
  /**
package/dist/index.d.ts CHANGED
@@ -10,6 +10,20 @@ interface TolinkuConfig {
10
10
  debug?: boolean;
11
11
  /** Request timeout in milliseconds. Defaults to 30000 (30 seconds). */
12
12
  timeout?: number;
13
+ /**
14
+ * Report incoming links automatically, instead of calling trackLinkOpen by
15
+ * hand. Defaults to false.
16
+ *
17
+ * Off by default because a reported open is billed as a click. Turning this
18
+ * on by upgrading would raise somebody's bill without them asking, so it is
19
+ * a decision the app makes rather than one a release makes for it.
20
+ *
21
+ * Covers both ways a link arrives on React Native, the cold start and the
22
+ * listener, which is the pair that is easy to get half right by hand. It does
23
+ * not cover the open after a deferred install: only your app knows that it
24
+ * just claimed a link, so that one is still reported explicitly.
25
+ */
26
+ autoTrackLinkOpens?: boolean;
13
27
  }
14
28
  /** Resolved configuration with all defaults applied */
15
29
  interface ResolvedTolinkuConfig {
@@ -101,6 +115,15 @@ interface LeaderboardEntry {
101
115
  interface DeferredLink {
102
116
  deep_link_path: string;
103
117
  appspace_id: string;
118
+ /**
119
+ * The absolute URL for this link, for reporting the open that follows.
120
+ *
121
+ * Reporting an open needs the whole URL, not the path: the host is how the
122
+ * server finds the Appspace and the only thing proving the link belongs to
123
+ * it, and the device has no way to know it. Absent from servers older than
124
+ * this field, so treat it as optional.
125
+ */
126
+ url?: string;
104
127
  referrer_id?: string;
105
128
  referral_code?: string;
106
129
  }
@@ -274,6 +297,29 @@ declare class HttpClient {
274
297
  * retries, same headers.
275
298
  */
276
299
  postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T>;
300
+ /**
301
+ * The hostname of the configured API, lowercased and without a port, for
302
+ * telling whether some other URL points at the same host. Empty if the base
303
+ * URL cannot be read, which init's validation should already have ruled out.
304
+ */
305
+ get apiHostname(): string;
306
+ /** Whether there is a key to send, so callers can skip a call that would only be refused. */
307
+ get hasApiKey(): boolean;
308
+ /**
309
+ * POST once, without the API key, to a host other than the configured one,
310
+ * and hand back whatever came back, whatever the status.
311
+ *
312
+ * For a question that must not be asked twice: no retries, and its own time
313
+ * limit rather than the client's. Throws only when there is no reply at all
314
+ * (a network failure, the time limit, or a destroyed client).
315
+ */
316
+ postPublicOnceToOrigin(origin: string, path: string, body: Record<string, unknown>, timeoutMs: number): Promise<OnceReply>;
317
+ /**
318
+ * POST once, with the API key, to the configured API. Same terms as
319
+ * {@link postPublicOnceToOrigin}: one attempt, its own time limit, the reply
320
+ * handed back whatever its status.
321
+ */
322
+ postOnce(path: string, body: Record<string, unknown>, timeoutMs: number): Promise<OnceReply>;
277
323
  /** POST without API key auth (for public endpoints like deferred claim) */
278
324
  postPublic<T>(path: string, body?: Record<string, unknown>): Promise<T>;
279
325
  /**
@@ -283,6 +329,12 @@ declare class HttpClient {
283
329
  abort(): void;
284
330
  private authenticatedHeaders;
285
331
  private publicHeaders;
332
+ /**
333
+ * One request, one attempt, aborted after `timeoutMs`. The body is read as
334
+ * JSON when it is JSON and left undefined when it is not, so the caller can
335
+ * tell a reply from our own server apart from somebody else's error page.
336
+ */
337
+ private executeOnce;
286
338
  /**
287
339
  * Execute a fetch request with retry logic. Retries on:
288
340
  * - Network errors (fetch throws)
@@ -294,6 +346,11 @@ declare class HttpClient {
294
346
  */
295
347
  private executeWithRetry;
296
348
  }
349
+ /** A reply to a single attempt: its status, and its body if that was JSON. */
350
+ interface OnceReply {
351
+ status: number;
352
+ body: unknown;
353
+ }
297
354
  declare class TolinkuError extends Error {
298
355
  status: number;
299
356
  code: string | undefined;
@@ -430,14 +487,23 @@ declare class Links {
430
487
  *
431
488
  * `url` is a whole link as the app received it. The question goes to the
432
489
  * link's own host, because that is how the platform knows which Appspace is
433
- * being asked about, which also means a link on a domain that is not yours
434
- * simply answers nothing.
490
+ * being asked about. If that host is not Tolinku's (no reply, or one that is
491
+ * not ours), and it is not the API's own host, the question goes once more to
492
+ * the configured API with the key: a link in an email arrives wrapped in the
493
+ * email platform's click tracking domain, which knows nothing about routes,
494
+ * and the API can unwrap it.
495
+ *
496
+ * Each question is asked once, with a five second limit. Asking a click
497
+ * tracking host again would count the email click again.
435
498
  *
436
499
  * Never throws. A link that cannot be resolved, for a bad network or any
437
500
  * other reason, is one the app should fall back to its own handling for, and
438
501
  * an exception in the middle of a cold start is no way to say so.
439
502
  */
440
503
  resolve(url: string): Promise<ResolvedLink | null>;
504
+ private resolveLink;
505
+ /** One request; null when there was no reply at all. */
506
+ private askOnce;
441
507
  }
442
508
 
443
509
  /**
@@ -450,7 +516,7 @@ declare class Links {
450
516
  * await Tolinku.track('signup', { source: 'onboarding' });
451
517
  */
452
518
  declare class Tolinku {
453
- static readonly VERSION = "0.8.0";
519
+ static readonly VERSION = "0.8.2";
454
520
  private static client;
455
521
  private static analyticsInstance;
456
522
  private static ecommerceInstance;
@@ -474,7 +540,28 @@ declare class Tolinku {
474
540
  * moving off it is a one-line change rather than a surprise.
475
541
  */
476
542
  static configure(config: TolinkuConfig): void;
543
+ /**
544
+ * Removes the automatic link listener, when one was installed.
545
+ *
546
+ * Held here rather than inside Analytics because it is a property of this
547
+ * configuration: destroy() has to take it back down or a reconfigured SDK
548
+ * reports every link twice.
549
+ */
550
+ private static linkSubscription;
477
551
  static init(config: TolinkuConfig): void;
552
+ /**
553
+ * Report incoming links without the app wiring anything.
554
+ *
555
+ * A link arrives in two places and both need reporting: one that launches the
556
+ * app cold arrives at getInitialURL, one tapped while it is already running
557
+ * arrives at the listener. Instrumenting only the second is the common
558
+ * mistake, because it works in every test done by hand with the app open.
559
+ *
560
+ * Both are wired, and the same link arriving at both inside a few seconds is
561
+ * reported once: trackLinkOpen drops a repeat of the same URL, which is why
562
+ * covering both here is safe rather than double counting.
563
+ */
564
+ private static startAutoLinkTracking;
478
565
  /** Check whether the SDK has been initialized. */
479
566
  static isConfigured(): boolean;
480
567
  /**
package/dist/index.js CHANGED
@@ -10,8 +10,10 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
10
  var AsyncStorage__default = /*#__PURE__*/_interopDefault(AsyncStorage);
11
11
  var React__default = /*#__PURE__*/_interopDefault(React);
12
12
 
13
+ // src/Tolinku.ts
14
+
13
15
  // src/types.ts
14
- var SDK_VERSION = "0.8.0";
16
+ var SDK_VERSION = "0.8.2";
15
17
 
16
18
  // src/debug.ts
17
19
  var _debugEnabled = false;
@@ -97,6 +99,52 @@ var HttpClient = class {
97
99
  body: body ? JSON.stringify(body) : void 0
98
100
  });
99
101
  }
102
+ /**
103
+ * The hostname of the configured API, lowercased and without a port, for
104
+ * telling whether some other URL points at the same host. Empty if the base
105
+ * URL cannot be read, which init's validation should already have ruled out.
106
+ */
107
+ get apiHostname() {
108
+ const match = /^https?:\/\/(?:[^/?#@]*@)?([^/?#]+)/i.exec(this.baseUrl);
109
+ return match ? hostnameOf(match[1]) : "";
110
+ }
111
+ /** Whether there is a key to send, so callers can skip a call that would only be refused. */
112
+ get hasApiKey() {
113
+ return typeof this.apiKey === "string" && this.apiKey.length > 0;
114
+ }
115
+ /**
116
+ * POST once, without the API key, to a host other than the configured one,
117
+ * and hand back whatever came back, whatever the status.
118
+ *
119
+ * For a question that must not be asked twice: no retries, and its own time
120
+ * limit rather than the client's. Throws only when there is no reply at all
121
+ * (a network failure, the time limit, or a destroyed client).
122
+ */
123
+ async postPublicOnceToOrigin(origin, path, body, timeoutMs) {
124
+ return this.executeOnce(origin.replace(/\/+$/, "") + path, {
125
+ method: "POST",
126
+ headers: {
127
+ ...this.publicHeaders(),
128
+ "Content-Type": "application/json"
129
+ },
130
+ body: JSON.stringify(body)
131
+ }, timeoutMs);
132
+ }
133
+ /**
134
+ * POST once, with the API key, to the configured API. Same terms as
135
+ * {@link postPublicOnceToOrigin}: one attempt, its own time limit, the reply
136
+ * handed back whatever its status.
137
+ */
138
+ async postOnce(path, body, timeoutMs) {
139
+ return this.executeOnce(this.baseUrl + path, {
140
+ method: "POST",
141
+ headers: {
142
+ ...this.authenticatedHeaders(),
143
+ "Content-Type": "application/json"
144
+ },
145
+ body: JSON.stringify(body)
146
+ }, timeoutMs);
147
+ }
100
148
  /** POST without API key auth (for public endpoints like deferred claim) */
101
149
  async postPublic(path, body) {
102
150
  return this.executeWithRetry(this.baseUrl + path, {
@@ -132,6 +180,40 @@ var HttpClient = class {
132
180
  "User-Agent": `TolinkuReactNativeSDK/${SDK_VERSION}`
133
181
  };
134
182
  }
183
+ /**
184
+ * One request, one attempt, aborted after `timeoutMs`. The body is read as
185
+ * JSON when it is JSON and left undefined when it is not, so the caller can
186
+ * tell a reply from our own server apart from somebody else's error page.
187
+ */
188
+ async executeOnce(url, init, timeoutMs) {
189
+ if (this.destroyed) {
190
+ throw new TolinkuError("Tolinku: client has been destroyed. Call Tolinku.init() to reinitialize.", 0);
191
+ }
192
+ const controller = new AbortController();
193
+ this.pendingControllers.add(controller);
194
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
195
+ try {
196
+ const res = await fetch(url, { ...init, signal: controller.signal });
197
+ let body;
198
+ try {
199
+ body = JSON.parse(await res.text());
200
+ } catch {
201
+ body = void 0;
202
+ }
203
+ return { status: res.status, body };
204
+ } catch (err) {
205
+ if (this.destroyed) {
206
+ throw new TolinkuError("Tolinku: request aborted (client destroyed).", 0);
207
+ }
208
+ if (isAbortError(err)) {
209
+ throw new TolinkuError(`Tolinku: request timed out after ${timeoutMs}ms`, 0);
210
+ }
211
+ throw err;
212
+ } finally {
213
+ clearTimeout(timeoutId);
214
+ this.pendingControllers.delete(controller);
215
+ }
216
+ }
135
217
  /**
136
218
  * Execute a fetch request with retry logic. Retries on:
137
219
  * - Network errors (fetch throws)
@@ -215,6 +297,10 @@ var HttpClient = class {
215
297
  throw lastError || new TolinkuError("Tolinku: request failed after retries", 0);
216
298
  }
217
299
  };
300
+ function hostnameOf(authority) {
301
+ const match = /^(\[[^\]]*\]|[^:]*)/.exec(authority);
302
+ return (match ? match[1] : authority).toLowerCase();
303
+ }
218
304
  function sleep(ms) {
219
305
  return new Promise((resolve) => setTimeout(resolve, ms));
220
306
  }
@@ -234,20 +320,6 @@ function urlScheme(url) {
234
320
  const match = /^([a-zA-Z][a-zA-Z\d+\-._]*):/.exec(cleaned);
235
321
  return match ? `${match[1].toLowerCase()}:` : null;
236
322
  }
237
- function parseHttpUrl(url) {
238
- if (!url || typeof url !== "string") return null;
239
- const cleaned = url.replace(/[\t\n\r]/g, "").trim();
240
- const match = /^(https?):\/\/([^/?#]+)([^?#]*)/i.exec(cleaned);
241
- if (!match) return null;
242
- const [, scheme, authority, path] = match;
243
- if (!authority) return null;
244
- return {
245
- origin: `${scheme.toLowerCase()}://${authority.toLowerCase()}`,
246
- // A URL with no path means the root, which is what a server expects to be
247
- // asked about.
248
- pathname: path || "/"
249
- };
250
- }
251
323
  function isSafeUrl(url) {
252
324
  const scheme = urlScheme(url);
253
325
  return scheme === "http:" || scheme === "https:";
@@ -331,6 +403,16 @@ var _Analytics = class _Analytics {
331
403
  */
332
404
  this.lastOpenUrl = null;
333
405
  this.lastOpenAt = 0;
406
+ /**
407
+ * Part of the key, not carried alongside it. An ordinary open and a deferred
408
+ * one are different events on the server and only the app can tell them
409
+ * apart, so a deferred report just after an ordinary one for the same link is
410
+ * new information rather than a repeat. Keyed on the URL alone, somebody who
411
+ * tapped a link, installed, then tapped it again would have the deferred
412
+ * report swallowed, losing the last stage of the install funnel in the one
413
+ * case it exists to show.
414
+ */
415
+ this.lastOpenDeferred = false;
334
416
  this.handleAppStateChange = (state) => {
335
417
  if (state === "background" || state === "inactive") {
336
418
  this.flush().catch(() => {
@@ -364,9 +446,10 @@ var _Analytics = class _Analytics {
364
446
  if (!trimmed) return;
365
447
  if (!isSafeUrl(trimmed)) return;
366
448
  const now = Date.now();
367
- if (this.lastOpenUrl === trimmed && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
449
+ if (this.lastOpenUrl === trimmed && this.lastOpenDeferred === deferred && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
368
450
  this.lastOpenUrl = trimmed;
369
451
  this.lastOpenAt = now;
452
+ this.lastOpenDeferred = deferred;
370
453
  try {
371
454
  const result = await this.client.postPublic(
372
455
  "/v1/api/opens",
@@ -906,6 +989,36 @@ function override(value) {
906
989
  function isRoutablePath(path) {
907
990
  return typeof path === "string" && path.startsWith("/") && !path.startsWith("//");
908
991
  }
992
+ var RESOLVE_TIMEOUT_MS = 5e3;
993
+ function normaliseLink(url) {
994
+ if (!url || typeof url !== "string") return null;
995
+ const cleaned = url.replace(/[\t\n\r]/g, "").trim();
996
+ const match = /^https?:\/\/([^/?#]*)([^?#]*)(\?[^#]*)?/i.exec(cleaned);
997
+ if (!match) return null;
998
+ const [, rawAuthority, rawPath, rawQuery] = match;
999
+ const authority = rawAuthority.slice(rawAuthority.lastIndexOf("@") + 1);
1000
+ const hostPort = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(authority);
1001
+ if (!hostPort || !hostPort[1]) return null;
1002
+ const hostname = hostPort[1].toLowerCase();
1003
+ const port = hostPort[2];
1004
+ const keepPort = port && port !== "443" && port !== "80" ? `:${port}` : "";
1005
+ const origin = `https://${hostname}${keepPort}`;
1006
+ const path = rawPath || "/";
1007
+ const query = rawQuery && rawQuery.length > 1 ? rawQuery : "";
1008
+ return { origin, hostname, path, whole: origin + path + query };
1009
+ }
1010
+ function answerIn(reply) {
1011
+ if (reply.status !== 200) return null;
1012
+ const result = reply.body;
1013
+ if (!result || typeof result !== "object" || !result.route || !isRoutablePath(result.deep_link_path)) {
1014
+ return null;
1015
+ }
1016
+ return result;
1017
+ }
1018
+ function isTolinkuReply(reply) {
1019
+ const body = reply.body;
1020
+ return typeof body === "object" && body !== null && typeof body.error === "string";
1021
+ }
909
1022
  var Links = class {
910
1023
  constructor(client) {
911
1024
  this.client = client;
@@ -915,30 +1028,63 @@ var Links = class {
915
1028
  *
916
1029
  * `url` is a whole link as the app received it. The question goes to the
917
1030
  * link's own host, because that is how the platform knows which Appspace is
918
- * being asked about, which also means a link on a domain that is not yours
919
- * simply answers nothing.
1031
+ * being asked about. If that host is not Tolinku's (no reply, or one that is
1032
+ * not ours), and it is not the API's own host, the question goes once more to
1033
+ * the configured API with the key: a link in an email arrives wrapped in the
1034
+ * email platform's click tracking domain, which knows nothing about routes,
1035
+ * and the API can unwrap it.
1036
+ *
1037
+ * Each question is asked once, with a five second limit. Asking a click
1038
+ * tracking host again would count the email click again.
920
1039
  *
921
1040
  * Never throws. A link that cannot be resolved, for a bad network or any
922
1041
  * other reason, is one the app should fall back to its own handling for, and
923
1042
  * an exception in the middle of a cold start is no way to say so.
924
1043
  */
925
1044
  async resolve(url) {
926
- if (!url || typeof url !== "string") return null;
927
- const parsed = parseHttpUrl(url);
928
- if (!parsed) {
1045
+ try {
1046
+ return await this.resolveLink(url);
1047
+ } catch (err) {
1048
+ debugWarn(`Links.resolve failed: ${err.message}`);
1049
+ return null;
1050
+ }
1051
+ }
1052
+ async resolveLink(url) {
1053
+ const link = normaliseLink(url);
1054
+ if (!link) {
929
1055
  debugWarn(`Links.resolve: not an http(s) URL: ${url}`);
930
1056
  return null;
931
1057
  }
932
- try {
933
- const result = await this.client.postPublicToOrigin(
934
- parsed.origin,
1058
+ const direct = await this.askOnce(
1059
+ () => this.client.postPublicOnceToOrigin(
1060
+ link.origin,
935
1061
  "/v1/api/path",
936
- { path: parsed.pathname }
937
- );
938
- if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;
939
- return result;
1062
+ { path: link.path, url: link.whole },
1063
+ RESOLVE_TIMEOUT_MS
1064
+ ),
1065
+ "Links.resolve"
1066
+ );
1067
+ if (direct) {
1068
+ const found = answerIn(direct);
1069
+ if (found) return found;
1070
+ if (isTolinkuReply(direct)) return null;
1071
+ }
1072
+ const apiHostname = this.client.apiHostname;
1073
+ if (!this.client.hasApiKey || !apiHostname || link.hostname === apiHostname) {
1074
+ return null;
1075
+ }
1076
+ const fallback = await this.askOnce(
1077
+ () => this.client.postOnce("/v1/api/links/resolve", { url: link.whole }, RESOLVE_TIMEOUT_MS),
1078
+ "Links.resolve fallback"
1079
+ );
1080
+ return fallback ? answerIn(fallback) : null;
1081
+ }
1082
+ /** One request; null when there was no reply at all. */
1083
+ async askOnce(request, label) {
1084
+ try {
1085
+ return await request();
940
1086
  } catch (err) {
941
- debugWarn(`Links.resolve failed: ${err.message}`);
1087
+ debugWarn(`${label} failed: ${err.message}`);
942
1088
  return null;
943
1089
  }
944
1090
  }
@@ -1068,8 +1214,30 @@ var _Tolinku = class _Tolinku {
1068
1214
  _Tolinku.deferredInstance = new Deferred(_Tolinku.client);
1069
1215
  _Tolinku.linksInstance = new Links(_Tolinku.client);
1070
1216
  _Tolinku._initialized = true;
1217
+ if (config.autoTrackLinkOpens === true) _Tolinku.startAutoLinkTracking();
1071
1218
  debugLog(`Tolinku SDK v${SDK_VERSION} initialized (baseUrl=${baseUrl})`);
1072
1219
  }
1220
+ /**
1221
+ * Report incoming links without the app wiring anything.
1222
+ *
1223
+ * A link arrives in two places and both need reporting: one that launches the
1224
+ * app cold arrives at getInitialURL, one tapped while it is already running
1225
+ * arrives at the listener. Instrumenting only the second is the common
1226
+ * mistake, because it works in every test done by hand with the app open.
1227
+ *
1228
+ * Both are wired, and the same link arriving at both inside a few seconds is
1229
+ * reported once: trackLinkOpen drops a repeat of the same URL, which is why
1230
+ * covering both here is safe rather than double counting.
1231
+ */
1232
+ static startAutoLinkTracking() {
1233
+ reactNative.Linking.getInitialURL().then((url) => {
1234
+ if (url) void _Tolinku.trackLinkOpen(url);
1235
+ }).catch(() => {
1236
+ });
1237
+ _Tolinku.linkSubscription = reactNative.Linking.addEventListener("url", ({ url }) => {
1238
+ if (url) void _Tolinku.trackLinkOpen(url);
1239
+ });
1240
+ }
1073
1241
  /** Check whether the SDK has been initialized. */
1074
1242
  static isConfigured() {
1075
1243
  return _Tolinku._initialized;
@@ -1202,6 +1370,10 @@ var _Tolinku = class _Tolinku {
1202
1370
  _Tolinku.client.abort();
1203
1371
  }
1204
1372
  resetStorageNamespace();
1373
+ if (_Tolinku.linkSubscription) {
1374
+ _Tolinku.linkSubscription.remove();
1375
+ _Tolinku.linkSubscription = null;
1376
+ }
1205
1377
  _Tolinku.client = null;
1206
1378
  _Tolinku.analyticsInstance = null;
1207
1379
  _Tolinku.ecommerceInstance = null;
@@ -1222,6 +1394,14 @@ _Tolinku.deferredInstance = null;
1222
1394
  _Tolinku.linksInstance = null;
1223
1395
  _Tolinku._initialized = false;
1224
1396
  _Tolinku._userId = null;
1397
+ /**
1398
+ * Removes the automatic link listener, when one was installed.
1399
+ *
1400
+ * Held here rather than inside Analytics because it is a property of this
1401
+ * configuration: destroy() has to take it back down or a reconfigured SDK
1402
+ * reports every link twice.
1403
+ */
1404
+ _Tolinku.linkSubscription = null;
1225
1405
  var Tolinku = _Tolinku;
1226
1406
  var DEFAULT_IMAGE_HEIGHT = 200;
1227
1407
  function dimension(raw) {