@tolinku/react-native-sdk 0.8.1 → 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
@@ -297,6 +297,29 @@ declare class HttpClient {
297
297
  * retries, same headers.
298
298
  */
299
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>;
300
323
  /** POST without API key auth (for public endpoints like deferred claim) */
301
324
  postPublic<T>(path: string, body?: Record<string, unknown>): Promise<T>;
302
325
  /**
@@ -306,6 +329,12 @@ declare class HttpClient {
306
329
  abort(): void;
307
330
  private authenticatedHeaders;
308
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;
309
338
  /**
310
339
  * Execute a fetch request with retry logic. Retries on:
311
340
  * - Network errors (fetch throws)
@@ -317,6 +346,11 @@ declare class HttpClient {
317
346
  */
318
347
  private executeWithRetry;
319
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
+ }
320
354
  declare class TolinkuError extends Error {
321
355
  status: number;
322
356
  code: string | undefined;
@@ -453,14 +487,23 @@ declare class Links {
453
487
  *
454
488
  * `url` is a whole link as the app received it. The question goes to the
455
489
  * link's own host, because that is how the platform knows which Appspace is
456
- * being asked about, which also means a link on a domain that is not yours
457
- * 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.
458
498
  *
459
499
  * Never throws. A link that cannot be resolved, for a bad network or any
460
500
  * other reason, is one the app should fall back to its own handling for, and
461
501
  * an exception in the middle of a cold start is no way to say so.
462
502
  */
463
503
  resolve(url: string): Promise<ResolvedLink | null>;
504
+ private resolveLink;
505
+ /** One request; null when there was no reply at all. */
506
+ private askOnce;
464
507
  }
465
508
 
466
509
  /**
@@ -473,7 +516,7 @@ declare class Links {
473
516
  * await Tolinku.track('signup', { source: 'onboarding' });
474
517
  */
475
518
  declare class Tolinku {
476
- static readonly VERSION = "0.8.1";
519
+ static readonly VERSION = "0.8.2";
477
520
  private static client;
478
521
  private static analyticsInstance;
479
522
  private static ecommerceInstance;
package/dist/index.d.ts CHANGED
@@ -297,6 +297,29 @@ declare class HttpClient {
297
297
  * retries, same headers.
298
298
  */
299
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>;
300
323
  /** POST without API key auth (for public endpoints like deferred claim) */
301
324
  postPublic<T>(path: string, body?: Record<string, unknown>): Promise<T>;
302
325
  /**
@@ -306,6 +329,12 @@ declare class HttpClient {
306
329
  abort(): void;
307
330
  private authenticatedHeaders;
308
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;
309
338
  /**
310
339
  * Execute a fetch request with retry logic. Retries on:
311
340
  * - Network errors (fetch throws)
@@ -317,6 +346,11 @@ declare class HttpClient {
317
346
  */
318
347
  private executeWithRetry;
319
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
+ }
320
354
  declare class TolinkuError extends Error {
321
355
  status: number;
322
356
  code: string | undefined;
@@ -453,14 +487,23 @@ declare class Links {
453
487
  *
454
488
  * `url` is a whole link as the app received it. The question goes to the
455
489
  * link's own host, because that is how the platform knows which Appspace is
456
- * being asked about, which also means a link on a domain that is not yours
457
- * 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.
458
498
  *
459
499
  * Never throws. A link that cannot be resolved, for a bad network or any
460
500
  * other reason, is one the app should fall back to its own handling for, and
461
501
  * an exception in the middle of a cold start is no way to say so.
462
502
  */
463
503
  resolve(url: string): Promise<ResolvedLink | null>;
504
+ private resolveLink;
505
+ /** One request; null when there was no reply at all. */
506
+ private askOnce;
464
507
  }
465
508
 
466
509
  /**
@@ -473,7 +516,7 @@ declare class Links {
473
516
  * await Tolinku.track('signup', { source: 'onboarding' });
474
517
  */
475
518
  declare class Tolinku {
476
- static readonly VERSION = "0.8.1";
519
+ static readonly VERSION = "0.8.2";
477
520
  private static client;
478
521
  private static analyticsInstance;
479
522
  private static ecommerceInstance;
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ var React__default = /*#__PURE__*/_interopDefault(React);
13
13
  // src/Tolinku.ts
14
14
 
15
15
  // src/types.ts
16
- var SDK_VERSION = "0.8.1";
16
+ var SDK_VERSION = "0.8.2";
17
17
 
18
18
  // src/debug.ts
19
19
  var _debugEnabled = false;
@@ -99,6 +99,52 @@ var HttpClient = class {
99
99
  body: body ? JSON.stringify(body) : void 0
100
100
  });
101
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
+ }
102
148
  /** POST without API key auth (for public endpoints like deferred claim) */
103
149
  async postPublic(path, body) {
104
150
  return this.executeWithRetry(this.baseUrl + path, {
@@ -134,6 +180,40 @@ var HttpClient = class {
134
180
  "User-Agent": `TolinkuReactNativeSDK/${SDK_VERSION}`
135
181
  };
136
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
+ }
137
217
  /**
138
218
  * Execute a fetch request with retry logic. Retries on:
139
219
  * - Network errors (fetch throws)
@@ -217,6 +297,10 @@ var HttpClient = class {
217
297
  throw lastError || new TolinkuError("Tolinku: request failed after retries", 0);
218
298
  }
219
299
  };
300
+ function hostnameOf(authority) {
301
+ const match = /^(\[[^\]]*\]|[^:]*)/.exec(authority);
302
+ return (match ? match[1] : authority).toLowerCase();
303
+ }
220
304
  function sleep(ms) {
221
305
  return new Promise((resolve) => setTimeout(resolve, ms));
222
306
  }
@@ -236,20 +320,6 @@ function urlScheme(url) {
236
320
  const match = /^([a-zA-Z][a-zA-Z\d+\-._]*):/.exec(cleaned);
237
321
  return match ? `${match[1].toLowerCase()}:` : null;
238
322
  }
239
- function parseHttpUrl(url) {
240
- if (!url || typeof url !== "string") return null;
241
- const cleaned = url.replace(/[\t\n\r]/g, "").trim();
242
- const match = /^(https?):\/\/([^/?#]+)([^?#]*)/i.exec(cleaned);
243
- if (!match) return null;
244
- const [, scheme, authority, path] = match;
245
- if (!authority) return null;
246
- return {
247
- origin: `${scheme.toLowerCase()}://${authority.toLowerCase()}`,
248
- // A URL with no path means the root, which is what a server expects to be
249
- // asked about.
250
- pathname: path || "/"
251
- };
252
- }
253
323
  function isSafeUrl(url) {
254
324
  const scheme = urlScheme(url);
255
325
  return scheme === "http:" || scheme === "https:";
@@ -919,6 +989,36 @@ function override(value) {
919
989
  function isRoutablePath(path) {
920
990
  return typeof path === "string" && path.startsWith("/") && !path.startsWith("//");
921
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
+ }
922
1022
  var Links = class {
923
1023
  constructor(client) {
924
1024
  this.client = client;
@@ -928,30 +1028,63 @@ var Links = class {
928
1028
  *
929
1029
  * `url` is a whole link as the app received it. The question goes to the
930
1030
  * link's own host, because that is how the platform knows which Appspace is
931
- * being asked about, which also means a link on a domain that is not yours
932
- * 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.
933
1039
  *
934
1040
  * Never throws. A link that cannot be resolved, for a bad network or any
935
1041
  * other reason, is one the app should fall back to its own handling for, and
936
1042
  * an exception in the middle of a cold start is no way to say so.
937
1043
  */
938
1044
  async resolve(url) {
939
- if (!url || typeof url !== "string") return null;
940
- const parsed = parseHttpUrl(url);
941
- 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) {
942
1055
  debugWarn(`Links.resolve: not an http(s) URL: ${url}`);
943
1056
  return null;
944
1057
  }
945
- try {
946
- const result = await this.client.postPublicToOrigin(
947
- parsed.origin,
1058
+ const direct = await this.askOnce(
1059
+ () => this.client.postPublicOnceToOrigin(
1060
+ link.origin,
948
1061
  "/v1/api/path",
949
- { path: parsed.pathname }
950
- );
951
- if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;
952
- 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();
953
1086
  } catch (err) {
954
- debugWarn(`Links.resolve failed: ${err.message}`);
1087
+ debugWarn(`${label} failed: ${err.message}`);
955
1088
  return null;
956
1089
  }
957
1090
  }