@tolinku/web-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
@@ -342,15 +342,27 @@ declare class HttpClient {
342
342
  get<T>(path: string, params?: Record<string, string>): Promise<T>;
343
343
  post<T>(path: string, body?: Record<string, unknown>): Promise<T>;
344
344
  /**
345
- * POST to a host other than the configured one, without the API key.
345
+ * One POST, no retries, with a time limit, reporting what came back instead
346
+ * of throwing.
346
347
  *
347
- * A few public endpoints work out which Appspace they belong to from the
348
- * hostname the request arrives on rather than from a key or an id, so a
349
- * question about a link on a customer's own domain has to be asked on that
350
- * domain. No key goes with it: the origin comes from a URL the caller was
351
- * handed, which is not necessarily ours.
348
+ * For questions where asking twice is worse than not getting an answer:
349
+ * resolving a link counts as a click on the server, so a retry would count
350
+ * it again. The caller decides what a reply means, so this hands back the
351
+ * status and the parsed JSON body. It resolves to null when there was no
352
+ * readable reply: a network error, a CORS refusal (which a browser reports
353
+ * as a network error), the time limit, or a body that is not JSON.
354
+ *
355
+ * `url` is absolute. With `authenticated` the SDK's normal headers go along
356
+ * (the API key); without it only Content-Type does, for a request to a host
357
+ * taken from a URL the caller was handed, which is not necessarily ours.
352
358
  */
353
- postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T>;
359
+ postOnce(url: string, body: Record<string, unknown>, options: {
360
+ authenticated: boolean;
361
+ timeoutMs: number;
362
+ }): Promise<{
363
+ status: number;
364
+ data: unknown;
365
+ } | null>;
354
366
  /** GET without API key auth (for public endpoints like banner config) */
355
367
  getPublic<T>(path: string, params?: Record<string, string>): Promise<T>;
356
368
  /** POST without API key auth (for public endpoints like deferred claim) */
@@ -525,14 +537,33 @@ declare class Links {
525
537
  /**
526
538
  * What this link means, or null if it means nothing here.
527
539
  *
528
- * The question goes to the link's own host, because that is how Tolinku knows
529
- * which Appspace is being asked about, which also means a link on a domain
530
- * that is not yours simply answers nothing.
540
+ * The question goes to the link's own host first, because that is how Tolinku
541
+ * knows which Appspace is being asked about, which also means a link on a
542
+ * domain that is not yours simply answers nothing there.
543
+ *
544
+ * If that host gives no reply Tolinku would give (on the web, a third-party
545
+ * click-tracking host usually refuses the request outright under CORS),
546
+ * Tolinku's own API is asked once with the whole link. A link in an email
547
+ * usually arrives wrapped in the email platform's click-tracking URL, on a
548
+ * host that has never heard of Tolinku; the API knows how to unwrap those,
549
+ * and the publishable key tells it which Appspace is asking.
550
+ *
551
+ * Each question is asked once, with a short time limit: resolving a link
552
+ * counts a click on the server, so a retry would count it twice.
531
553
  *
532
554
  * Never throws. A link that cannot be resolved, for a bad network or any
533
555
  * other reason, is one to fall back to your own handling for.
534
556
  */
535
557
  resolve(url: string): Promise<ResolvedLink | null>;
558
+ private resolveLink;
559
+ /**
560
+ * Whether a second question to Tolinku's own API could add anything.
561
+ *
562
+ * Not without a key, since the API would not know which Appspace is asking.
563
+ * Not when the link is already on the API's host either: that host was just
564
+ * asked, and asking again only doubles the wait for the same answer.
565
+ */
566
+ private shouldAskApi;
536
567
  }
537
568
 
538
569
  declare class Tolinku {
package/dist/index.d.ts CHANGED
@@ -342,15 +342,27 @@ declare class HttpClient {
342
342
  get<T>(path: string, params?: Record<string, string>): Promise<T>;
343
343
  post<T>(path: string, body?: Record<string, unknown>): Promise<T>;
344
344
  /**
345
- * POST to a host other than the configured one, without the API key.
345
+ * One POST, no retries, with a time limit, reporting what came back instead
346
+ * of throwing.
346
347
  *
347
- * A few public endpoints work out which Appspace they belong to from the
348
- * hostname the request arrives on rather than from a key or an id, so a
349
- * question about a link on a customer's own domain has to be asked on that
350
- * domain. No key goes with it: the origin comes from a URL the caller was
351
- * handed, which is not necessarily ours.
348
+ * For questions where asking twice is worse than not getting an answer:
349
+ * resolving a link counts as a click on the server, so a retry would count
350
+ * it again. The caller decides what a reply means, so this hands back the
351
+ * status and the parsed JSON body. It resolves to null when there was no
352
+ * readable reply: a network error, a CORS refusal (which a browser reports
353
+ * as a network error), the time limit, or a body that is not JSON.
354
+ *
355
+ * `url` is absolute. With `authenticated` the SDK's normal headers go along
356
+ * (the API key); without it only Content-Type does, for a request to a host
357
+ * taken from a URL the caller was handed, which is not necessarily ours.
352
358
  */
353
- postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T>;
359
+ postOnce(url: string, body: Record<string, unknown>, options: {
360
+ authenticated: boolean;
361
+ timeoutMs: number;
362
+ }): Promise<{
363
+ status: number;
364
+ data: unknown;
365
+ } | null>;
354
366
  /** GET without API key auth (for public endpoints like banner config) */
355
367
  getPublic<T>(path: string, params?: Record<string, string>): Promise<T>;
356
368
  /** POST without API key auth (for public endpoints like deferred claim) */
@@ -525,14 +537,33 @@ declare class Links {
525
537
  /**
526
538
  * What this link means, or null if it means nothing here.
527
539
  *
528
- * The question goes to the link's own host, because that is how Tolinku knows
529
- * which Appspace is being asked about, which also means a link on a domain
530
- * that is not yours simply answers nothing.
540
+ * The question goes to the link's own host first, because that is how Tolinku
541
+ * knows which Appspace is being asked about, which also means a link on a
542
+ * domain that is not yours simply answers nothing there.
543
+ *
544
+ * If that host gives no reply Tolinku would give (on the web, a third-party
545
+ * click-tracking host usually refuses the request outright under CORS),
546
+ * Tolinku's own API is asked once with the whole link. A link in an email
547
+ * usually arrives wrapped in the email platform's click-tracking URL, on a
548
+ * host that has never heard of Tolinku; the API knows how to unwrap those,
549
+ * and the publishable key tells it which Appspace is asking.
550
+ *
551
+ * Each question is asked once, with a short time limit: resolving a link
552
+ * counts a click on the server, so a retry would count it twice.
531
553
  *
532
554
  * Never throws. A link that cannot be resolved, for a bad network or any
533
555
  * other reason, is one to fall back to your own handling for.
534
556
  */
535
557
  resolve(url: string): Promise<ResolvedLink | null>;
558
+ private resolveLink;
559
+ /**
560
+ * Whether a second question to Tolinku's own API could add anything.
561
+ *
562
+ * Not without a key, since the API would not know which Appspace is asking.
563
+ * Not when the link is already on the API's host either: that host was just
564
+ * asked, and asking again only doubles the wait for the same answer.
565
+ */
566
+ private shouldAskApi;
536
567
  }
537
568
 
538
569
  declare class Tolinku {
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // src/types.ts
4
- var SDK_VERSION = "0.8.1";
4
+ var SDK_VERSION = "0.8.2";
5
5
 
6
6
  // src/client.ts
7
7
  var MAX_RETRIES = 3;
@@ -69,26 +69,47 @@ var HttpClient = class {
69
69
  return this.parseJson(res);
70
70
  }
71
71
  /**
72
- * POST to a host other than the configured one, without the API key.
72
+ * One POST, no retries, with a time limit, reporting what came back instead
73
+ * of throwing.
73
74
  *
74
- * A few public endpoints work out which Appspace they belong to from the
75
- * hostname the request arrives 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. No key goes with it: the origin comes from a URL the caller was
78
- * handed, which is not necessarily ours.
75
+ * For questions where asking twice is worse than not getting an answer:
76
+ * resolving a link counts as a click on the server, so a retry would count
77
+ * it again. The caller decides what a reply means, so this hands back the
78
+ * status and the parsed JSON body. It resolves to null when there was no
79
+ * readable reply: a network error, a CORS refusal (which a browser reports
80
+ * as a network error), the time limit, or a body that is not JSON.
81
+ *
82
+ * `url` is absolute. With `authenticated` the SDK's normal headers go along
83
+ * (the API key); without it only Content-Type does, for a request to a host
84
+ * taken from a URL the caller was handed, which is not necessarily ours.
79
85
  */
80
- async postPublicToOrigin(origin, path, body) {
81
- const res = await this.fetchWithRetry(origin.replace(/\/+$/, "") + path, {
82
- method: "POST",
83
- headers: { "Content-Type": "application/json" },
84
- body: body ? JSON.stringify(body) : void 0,
85
- signal: this.signal
86
- });
87
- if (!res.ok) {
88
- const data = await res.json().catch(() => ({ error: res.statusText }));
89
- throw new TolinkuError(data.error || res.statusText, res.status, data.code);
86
+ async postOnce(url, body, options) {
87
+ const controller = new AbortController();
88
+ const outer = this.signal;
89
+ const onAbort = () => controller.abort();
90
+ if (outer.aborted) controller.abort();
91
+ else outer.addEventListener("abort", onAbort, { once: true });
92
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
93
+ try {
94
+ const res = await fetch(url, {
95
+ method: "POST",
96
+ headers: options.authenticated ? { ...this.headers(), "Content-Type": "application/json" } : { "Content-Type": "application/json" },
97
+ body: JSON.stringify(body),
98
+ signal: controller.signal
99
+ });
100
+ let data;
101
+ try {
102
+ data = await res.json();
103
+ } catch {
104
+ return null;
105
+ }
106
+ return { status: res.status, data };
107
+ } catch {
108
+ return null;
109
+ } finally {
110
+ clearTimeout(timer);
111
+ outer.removeEventListener("abort", onAbort);
90
112
  }
91
- return this.parseJson(res);
92
113
  }
93
114
  /** GET without API key auth (for public endpoints like banner config) */
94
115
  async getPublic(path, params) {
@@ -679,35 +700,89 @@ var Links = class {
679
700
  /**
680
701
  * What this link means, or null if it means nothing here.
681
702
  *
682
- * The question goes to the link's own host, because that is how Tolinku knows
683
- * which Appspace is being asked about, which also means a link on a domain
684
- * that is not yours simply answers nothing.
703
+ * The question goes to the link's own host first, because that is how Tolinku
704
+ * knows which Appspace is being asked about, which also means a link on a
705
+ * domain that is not yours simply answers nothing there.
706
+ *
707
+ * If that host gives no reply Tolinku would give (on the web, a third-party
708
+ * click-tracking host usually refuses the request outright under CORS),
709
+ * Tolinku's own API is asked once with the whole link. A link in an email
710
+ * usually arrives wrapped in the email platform's click-tracking URL, on a
711
+ * host that has never heard of Tolinku; the API knows how to unwrap those,
712
+ * and the publishable key tells it which Appspace is asking.
713
+ *
714
+ * Each question is asked once, with a short time limit: resolving a link
715
+ * counts a click on the server, so a retry would count it twice.
685
716
  *
686
717
  * Never throws. A link that cannot be resolved, for a bad network or any
687
718
  * other reason, is one to fall back to your own handling for.
688
719
  */
689
720
  async resolve(url) {
690
- if (!url || typeof url !== "string") return null;
691
- let parsed;
692
721
  try {
693
- parsed = new URL(url.trim());
722
+ return await this.resolveLink(url);
694
723
  } catch {
695
724
  return null;
696
725
  }
697
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
726
+ }
727
+ async resolveLink(url) {
728
+ if (!url || typeof url !== "string") return null;
729
+ const link = normaliseLink(url);
730
+ if (!link) return null;
731
+ const own = await this.client.postOnce(
732
+ link.origin + "/v1/api/path",
733
+ { path: link.path, url: link.whole },
734
+ { authenticated: false, timeoutMs: RESOLVE_TIMEOUT_MS }
735
+ );
736
+ if (own && own.status === 200 && isAnswer(own.data)) return own.data;
737
+ if (own && isTolinkuReply(own.data)) return null;
738
+ if (!this.shouldAskApi(link.hostname)) return null;
739
+ const api = await this.client.postOnce(
740
+ this.client.baseUrl + "/v1/api/links/resolve",
741
+ { url: link.whole },
742
+ { authenticated: true, timeoutMs: RESOLVE_TIMEOUT_MS }
743
+ );
744
+ if (api && api.status === 200 && isAnswer(api.data)) return api.data;
745
+ return null;
746
+ }
747
+ /**
748
+ * Whether a second question to Tolinku's own API could add anything.
749
+ *
750
+ * Not without a key, since the API would not know which Appspace is asking.
751
+ * Not when the link is already on the API's host either: that host was just
752
+ * asked, and asking again only doubles the wait for the same answer.
753
+ */
754
+ shouldAskApi(hostname) {
755
+ if (!this.client.key) return false;
698
756
  try {
699
- const result = await this.client.postPublicToOrigin(
700
- parsed.origin,
701
- "/v1/api/path",
702
- { path: parsed.pathname }
703
- );
704
- if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;
705
- return result;
757
+ return new URL(this.client.baseUrl).hostname.toLowerCase() !== hostname;
706
758
  } catch {
707
- return null;
759
+ return false;
708
760
  }
709
761
  }
710
762
  };
763
+ var RESOLVE_TIMEOUT_MS = 5e3;
764
+ function normaliseLink(input) {
765
+ let parsed;
766
+ try {
767
+ parsed = new URL(input.trim());
768
+ } catch {
769
+ return null;
770
+ }
771
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
772
+ const hostname = parsed.hostname.toLowerCase();
773
+ const port = parsed.port === "" || parsed.port === "443" || parsed.port === "80" ? "" : ":" + parsed.port;
774
+ const origin = "https://" + hostname + port;
775
+ const path = parsed.pathname;
776
+ return { origin, hostname, path, whole: origin + path + parsed.search };
777
+ }
778
+ function isTolinkuReply(data) {
779
+ return typeof data === "object" && data !== null && typeof data.error === "string";
780
+ }
781
+ function isAnswer(data) {
782
+ if (typeof data !== "object" || data === null) return false;
783
+ const result = data;
784
+ return !!result.route && isRoutablePath(result.deep_link_path);
785
+ }
711
786
 
712
787
  // src/url-safety.ts
713
788
  function isSafeUrl(url) {
@@ -863,31 +938,31 @@ var Banners = class {
863
938
  this.currentPosition = "top";
864
939
  }
865
940
  /**
866
- * Tell the server a banner was tapped.
941
+ * Tell the server what happened to a banner: shown, closed, or its call to
942
+ * action tapped. Shown gives the dashboard a tap rate; closed is otherwise
943
+ * known only to this browser's storage.
867
944
  *
868
- * sendBeacon, because the navigation that follows cancels a plain fetch. It
869
- * is queued by the browser and delivered regardless, which is the only way to
870
- * report something that happens as the page is being left.
945
+ * sendBeacon, because the navigation that follows a tap cancels a plain
946
+ * fetch. It is queued by the browser and delivered regardless. The body is a
947
+ * string, so it goes as text/plain: the one content type a browser sends
948
+ * cross-origin without a preflight. The server reads it as JSON either way.
871
949
  *
872
- * Never throws and never awaits: a banner that cannot report a tap must still
873
- * open the link.
950
+ * Never throws and never awaits: a banner that cannot report must still work.
874
951
  */
875
- reportClick(bannerId, target) {
952
+ report(kind, bannerId, extra) {
876
953
  try {
877
- const url = this.client.baseUrl + "/v1/api/banner/click";
878
- const body = JSON.stringify({ banner_id: bannerId, target });
954
+ const url = this.client.baseUrl + "/v1/api/banner/" + kind;
955
+ const page = typeof location !== "undefined" ? location.origin + location.pathname : "";
956
+ const body = JSON.stringify({ banner_id: bannerId, page, ...extra || {} });
879
957
  const nav = navigator;
880
- if (typeof nav.sendBeacon === "function") {
881
- nav.sendBeacon(url, new Blob([body], { type: "application/json" }));
882
- } else {
883
- void fetch(url, {
884
- method: "POST",
885
- headers: { "Content-Type": "application/json" },
886
- body,
887
- keepalive: true
888
- }).catch(() => {
889
- });
890
- }
958
+ if (typeof nav.sendBeacon === "function" && nav.sendBeacon(url, body)) return;
959
+ void fetch(url, {
960
+ method: "POST",
961
+ headers: { "Content-Type": "text/plain" },
962
+ body,
963
+ keepalive: true
964
+ }).catch(() => {
965
+ });
891
966
  } catch {
892
967
  }
893
968
  }
@@ -1096,6 +1171,7 @@ var Banners = class {
1096
1171
  closeBtn.textContent = "\xD7";
1097
1172
  closeBtn.addEventListener("click", () => {
1098
1173
  saveBannerDismissal(banner.id);
1174
+ this.report("dismiss", banner.id);
1099
1175
  this.dismiss();
1100
1176
  });
1101
1177
  inner.appendChild(closeBtn);
@@ -1125,7 +1201,7 @@ var Banners = class {
1125
1201
  cta.href = isSafeUrl(installUrl) ? installUrl : "#";
1126
1202
  cta.textContent = ctaText;
1127
1203
  cta.addEventListener("click", () => {
1128
- this.reportClick(banner.id, cta.href);
1204
+ this.report("click", banner.id, { target: cta.href });
1129
1205
  });
1130
1206
  inner.appendChild(cta);
1131
1207
  container.appendChild(inner);
@@ -1152,6 +1228,7 @@ var Banners = class {
1152
1228
  }
1153
1229
  this.container = container;
1154
1230
  this.styleEl = style;
1231
+ this.report("view", banner.id);
1155
1232
  requestAnimationFrame(() => {
1156
1233
  requestAnimationFrame(() => {
1157
1234
  container.classList.add("tolk-visible");
@@ -1184,12 +1261,33 @@ function findStackedAnchor(position, explicit) {
1184
1261
  }
1185
1262
 
1186
1263
  // src/messages.ts
1264
+ var MAX_REPORTED_URL = 1e3;
1187
1265
  var Messages = class {
1188
1266
  constructor(client) {
1189
1267
  this.client = client;
1190
1268
  this.overlay = null;
1191
1269
  this.styleEl = null;
1192
1270
  this.app = null;
1271
+ this.tapped = false;
1272
+ }
1273
+ /**
1274
+ * Tell the server a message was shown, closed, or had a button tapped, so the dashboard has
1275
+ * numbers per message. A plain-text beacon (no preflight, survives a navigation) carrying the
1276
+ * publishable key in the body, since a beacon can't set headers. Never throws.
1277
+ */
1278
+ report(messageId, kind, url) {
1279
+ if (kind === "view") this.tapped = false;
1280
+ if (kind === "tap") this.tapped = true;
1281
+ if (kind === "dismiss" && this.tapped) return;
1282
+ try {
1283
+ const endpoint = this.client.baseUrl + "/v1/api/messages/" + encodeURIComponent(messageId) + "/event";
1284
+ const body = JSON.stringify(url ? { kind, apiKey: this.client.key, url: url.slice(0, MAX_REPORTED_URL) } : { kind, apiKey: this.client.key });
1285
+ const nav = navigator;
1286
+ if (typeof nav.sendBeacon === "function" && nav.sendBeacon(endpoint, body)) return;
1287
+ void fetch(endpoint, { method: "POST", headers: { "Content-Type": "text/plain" }, body, keepalive: true }).catch(() => {
1288
+ });
1289
+ } catch {
1290
+ }
1193
1291
  }
1194
1292
  /** Fetch messages and show the highest-priority non-dismissed one */
1195
1293
  async show(options = {}, userId) {
@@ -1204,6 +1302,7 @@ var Messages = class {
1204
1302
  const message = candidates[0];
1205
1303
  recordMessageImpression(message.id);
1206
1304
  this.render(message, options);
1305
+ this.report(message.id, "view");
1207
1306
  }
1208
1307
  /** Remove the message overlay */
1209
1308
  dismiss() {
@@ -1254,6 +1353,7 @@ var Messages = class {
1254
1353
  overlay.addEventListener("click", (e) => {
1255
1354
  if (e.target === overlay) {
1256
1355
  saveMessageDismissal(message.id);
1356
+ this.report(message.id, "dismiss");
1257
1357
  options.onDismiss?.(message.id);
1258
1358
  this.dismiss();
1259
1359
  }
@@ -1284,6 +1384,7 @@ var Messages = class {
1284
1384
  closeBtn.textContent = "\xD7";
1285
1385
  closeBtn.addEventListener("click", () => {
1286
1386
  saveMessageDismissal(message.id);
1387
+ this.report(message.id, "dismiss");
1287
1388
  options.onDismiss?.(message.id);
1288
1389
  this.dismiss();
1289
1390
  });
@@ -1502,11 +1603,13 @@ var Messages = class {
1502
1603
  el.addEventListener("click", () => {
1503
1604
  if (action === "close") {
1504
1605
  saveMessageDismissal(context.messageId);
1606
+ this.report(context.messageId, "dismiss");
1505
1607
  context.options.onDismiss?.(context.messageId);
1506
1608
  this.dismiss();
1507
1609
  return;
1508
1610
  }
1509
1611
  if (action && !isNavigableUrl(action)) return;
1612
+ if (action) this.report(context.messageId, "tap", action);
1510
1613
  if (context.options.onButtonPress) {
1511
1614
  context.options.onButtonPress(action, context.messageId);
1512
1615
  } else if (action) {