@tolinku/web-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/README.md CHANGED
@@ -160,6 +160,29 @@ tolinku.dismissBanner();
160
160
 
161
161
  Banners include an app icon, title, body text, and a call-to-action button. Dismissal state is tracked so banners do not reappear until the configured duration has passed.
162
162
 
163
+ ### Resolving a Link
164
+
165
+ Short links arrive as an opaque code, `/s7k2p9q/4821`. On the open web you will
166
+ rarely see one, since the browser follows it to Tolinku first. Inside a
167
+ Capacitor or Cordova app you will see it every time: the operating system hands
168
+ the web layer the URL that was tapped, and code parsing the path itself has no
169
+ idea what the code stands for, so the link opens the app and nothing happens.
170
+
171
+ `resolve` asks Tolinku, which answers with the route, the token and the
172
+ canonical path. A readable URL comes back unchanged, so you can resolve
173
+ everything rather than guessing which kind you have. It never throws: a link it
174
+ cannot resolve is one to fall back to your own handling for.
175
+
176
+ ```js
177
+ const link = await tolinku.links.resolve(url);
178
+ if (link) {
179
+ // link.deep_link_path -> "/order/4821/receipt"
180
+ // link.token -> "4821"
181
+ // link.route.prefix -> "order/{token}/receipt"
182
+ route(link.deep_link_path);
183
+ }
184
+ ```
185
+
163
186
  ## Configuration Options
164
187
 
165
188
  ```typescript
package/dist/index.d.mts CHANGED
@@ -268,6 +268,26 @@ interface SpendCreditsParams {
268
268
  revenue: number;
269
269
  currency: string;
270
270
  }
271
+ /**
272
+ * What a Tolinku link turned out to mean.
273
+ *
274
+ * The same shape in every SDK, so an app moving between them reads one thing.
275
+ * The Appspace the link belongs to is deliberately not here: the caller already
276
+ * knows which Appspace it is, and nothing about routing a link needs it.
277
+ */
278
+ interface ResolvedLink {
279
+ /** The route that answers this link. */
280
+ route: {
281
+ prefix: string;
282
+ name: string;
283
+ template: string;
284
+ link_type?: string;
285
+ };
286
+ /** The token the link carried, or '' where it carried none. */
287
+ token: string;
288
+ /** The canonical path, with the token wherever the route's prefix puts it. */
289
+ deep_link_path: string;
290
+ }
271
291
 
272
292
  declare class HttpClient {
273
293
  private _baseUrl;
@@ -284,6 +304,16 @@ declare class HttpClient {
284
304
  get key(): string;
285
305
  get<T>(path: string, params?: Record<string, string>): Promise<T>;
286
306
  post<T>(path: string, body?: Record<string, unknown>): Promise<T>;
307
+ /**
308
+ * POST to a host other than the configured one, without the API key.
309
+ *
310
+ * A few public endpoints work out which Appspace they belong to from the
311
+ * hostname the request arrives on rather than from a key or an id, so a
312
+ * question about a link on a customer's own domain has to be asked on that
313
+ * domain. No key goes with it: the origin comes from a URL the caller was
314
+ * handed, which is not necessarily ours.
315
+ */
316
+ postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T>;
287
317
  /** GET without API key auth (for public endpoints like banner config) */
288
318
  getPublic<T>(path: string, params?: Record<string, string>): Promise<T>;
289
319
  /** POST without API key auth (for public endpoints like deferred claim) */
@@ -430,6 +460,44 @@ declare class Deferred {
430
460
  private attemptSignals;
431
461
  }
432
462
 
463
+ /**
464
+ * Working out what a link actually means.
465
+ *
466
+ * On the open web this rarely comes up: a browser follows a short link to
467
+ * Tolinku, which resolves it and serves the page, so nothing on the page ever
468
+ * sees an unreadable URL.
469
+ *
470
+ * Inside a Capacitor or Cordova app it comes up constantly. There the operating
471
+ * system hands the web layer the URL that was tapped, exactly as written, and
472
+ * the routing happens in JavaScript. A short link arrives as an opaque code:
473
+ *
474
+ * https://links.example.com/s7k2p9q/4821
475
+ *
476
+ * Nothing in that URL says which route it is, and nothing on the device can work
477
+ * it out. Code parsing the path itself sees a first segment it has never heard
478
+ * of and does nothing, so the link opens the app and then appears to fail: no
479
+ * error, no screen, no clue.
480
+ *
481
+ * `resolve` asks Tolinku, which answers with the route, the token and the
482
+ * canonical path. A readable URL comes back unchanged, so everything can be
483
+ * resolved rather than guessing which kind it is.
484
+ */
485
+ declare class Links {
486
+ private client;
487
+ constructor(client: HttpClient);
488
+ /**
489
+ * What this link means, or null if it means nothing here.
490
+ *
491
+ * The question goes to the link's own host, because that is how Tolinku knows
492
+ * which Appspace is being asked about, which also means a link on a domain
493
+ * that is not yours simply answers nothing.
494
+ *
495
+ * Never throws. A link that cannot be resolved, for a bad network or any
496
+ * other reason, is one to fall back to your own handling for.
497
+ */
498
+ resolve(url: string): Promise<ResolvedLink | null>;
499
+ }
500
+
433
501
  declare class Tolinku {
434
502
  private client;
435
503
  /** Analytics: track custom events */
@@ -440,6 +508,13 @@ declare class Tolinku {
440
508
  readonly referrals: Referrals;
441
509
  /** Deferred deep links: claim by token or signals */
442
510
  readonly deferred: Deferred;
511
+ /**
512
+ * Turning a link into the route and token it means.
513
+ *
514
+ * Needed for short links, which arrive as an opaque code. See
515
+ * {@link Links.resolve}.
516
+ */
517
+ readonly links: Links;
443
518
  private banners;
444
519
  private messages;
445
520
  /** The current user ID, used for segment targeting and analytics. */
@@ -470,4 +545,4 @@ declare class Tolinku {
470
545
  destroy(): void;
471
546
  }
472
547
 
473
- export { type AddPaymentInfoParams, type AddToCartParams, type AddToWishlistParams, type BannerConfig, type BannerItem, type BeginCheckoutParams, type ClaimBySignalsOptions, type CompleteReferralOptions, type CompleteReferralResult, type CreateReferralOptions, type CreateReferralResult, type DeferredLink, type EcommerceItem, type LeaderboardEntry, type Message, type MessageComponent, type MessageContent, type MilestoneOptions, type MilestoneResult, type PurchaseParams, type RateParams, type ReferralInfo, type RefundParams, type RemoveFromCartParams, type SearchParams, type ShareParams, type ShowBannerOptions, type ShowMessageOptions, type SpendCreditsParams, Tolinku, type TolinkuConfig, TolinkuError, type TrackProperties, type ViewItemParams };
548
+ export { type AddPaymentInfoParams, type AddToCartParams, type AddToWishlistParams, type BannerConfig, type BannerItem, type BeginCheckoutParams, type ClaimBySignalsOptions, type CompleteReferralOptions, type CompleteReferralResult, type CreateReferralOptions, type CreateReferralResult, type DeferredLink, type EcommerceItem, type LeaderboardEntry, type Message, type MessageComponent, type MessageContent, type MilestoneOptions, type MilestoneResult, type PurchaseParams, type RateParams, type ReferralInfo, type RefundParams, type RemoveFromCartParams, type ResolvedLink, type SearchParams, type ShareParams, type ShowBannerOptions, type ShowMessageOptions, type SpendCreditsParams, Tolinku, type TolinkuConfig, TolinkuError, type TrackProperties, type ViewItemParams };
package/dist/index.d.ts CHANGED
@@ -268,6 +268,26 @@ interface SpendCreditsParams {
268
268
  revenue: number;
269
269
  currency: string;
270
270
  }
271
+ /**
272
+ * What a Tolinku link turned out to mean.
273
+ *
274
+ * The same shape in every SDK, so an app moving between them reads one thing.
275
+ * The Appspace the link belongs to is deliberately not here: the caller already
276
+ * knows which Appspace it is, and nothing about routing a link needs it.
277
+ */
278
+ interface ResolvedLink {
279
+ /** The route that answers this link. */
280
+ route: {
281
+ prefix: string;
282
+ name: string;
283
+ template: string;
284
+ link_type?: string;
285
+ };
286
+ /** The token the link carried, or '' where it carried none. */
287
+ token: string;
288
+ /** The canonical path, with the token wherever the route's prefix puts it. */
289
+ deep_link_path: string;
290
+ }
271
291
 
272
292
  declare class HttpClient {
273
293
  private _baseUrl;
@@ -284,6 +304,16 @@ declare class HttpClient {
284
304
  get key(): string;
285
305
  get<T>(path: string, params?: Record<string, string>): Promise<T>;
286
306
  post<T>(path: string, body?: Record<string, unknown>): Promise<T>;
307
+ /**
308
+ * POST to a host other than the configured one, without the API key.
309
+ *
310
+ * A few public endpoints work out which Appspace they belong to from the
311
+ * hostname the request arrives on rather than from a key or an id, so a
312
+ * question about a link on a customer's own domain has to be asked on that
313
+ * domain. No key goes with it: the origin comes from a URL the caller was
314
+ * handed, which is not necessarily ours.
315
+ */
316
+ postPublicToOrigin<T>(origin: string, path: string, body?: Record<string, unknown>): Promise<T>;
287
317
  /** GET without API key auth (for public endpoints like banner config) */
288
318
  getPublic<T>(path: string, params?: Record<string, string>): Promise<T>;
289
319
  /** POST without API key auth (for public endpoints like deferred claim) */
@@ -430,6 +460,44 @@ declare class Deferred {
430
460
  private attemptSignals;
431
461
  }
432
462
 
463
+ /**
464
+ * Working out what a link actually means.
465
+ *
466
+ * On the open web this rarely comes up: a browser follows a short link to
467
+ * Tolinku, which resolves it and serves the page, so nothing on the page ever
468
+ * sees an unreadable URL.
469
+ *
470
+ * Inside a Capacitor or Cordova app it comes up constantly. There the operating
471
+ * system hands the web layer the URL that was tapped, exactly as written, and
472
+ * the routing happens in JavaScript. A short link arrives as an opaque code:
473
+ *
474
+ * https://links.example.com/s7k2p9q/4821
475
+ *
476
+ * Nothing in that URL says which route it is, and nothing on the device can work
477
+ * it out. Code parsing the path itself sees a first segment it has never heard
478
+ * of and does nothing, so the link opens the app and then appears to fail: no
479
+ * error, no screen, no clue.
480
+ *
481
+ * `resolve` asks Tolinku, which answers with the route, the token and the
482
+ * canonical path. A readable URL comes back unchanged, so everything can be
483
+ * resolved rather than guessing which kind it is.
484
+ */
485
+ declare class Links {
486
+ private client;
487
+ constructor(client: HttpClient);
488
+ /**
489
+ * What this link means, or null if it means nothing here.
490
+ *
491
+ * The question goes to the link's own host, because that is how Tolinku knows
492
+ * which Appspace is being asked about, which also means a link on a domain
493
+ * that is not yours simply answers nothing.
494
+ *
495
+ * Never throws. A link that cannot be resolved, for a bad network or any
496
+ * other reason, is one to fall back to your own handling for.
497
+ */
498
+ resolve(url: string): Promise<ResolvedLink | null>;
499
+ }
500
+
433
501
  declare class Tolinku {
434
502
  private client;
435
503
  /** Analytics: track custom events */
@@ -440,6 +508,13 @@ declare class Tolinku {
440
508
  readonly referrals: Referrals;
441
509
  /** Deferred deep links: claim by token or signals */
442
510
  readonly deferred: Deferred;
511
+ /**
512
+ * Turning a link into the route and token it means.
513
+ *
514
+ * Needed for short links, which arrive as an opaque code. See
515
+ * {@link Links.resolve}.
516
+ */
517
+ readonly links: Links;
443
518
  private banners;
444
519
  private messages;
445
520
  /** The current user ID, used for segment targeting and analytics. */
@@ -470,4 +545,4 @@ declare class Tolinku {
470
545
  destroy(): void;
471
546
  }
472
547
 
473
- export { type AddPaymentInfoParams, type AddToCartParams, type AddToWishlistParams, type BannerConfig, type BannerItem, type BeginCheckoutParams, type ClaimBySignalsOptions, type CompleteReferralOptions, type CompleteReferralResult, type CreateReferralOptions, type CreateReferralResult, type DeferredLink, type EcommerceItem, type LeaderboardEntry, type Message, type MessageComponent, type MessageContent, type MilestoneOptions, type MilestoneResult, type PurchaseParams, type RateParams, type ReferralInfo, type RefundParams, type RemoveFromCartParams, type SearchParams, type ShareParams, type ShowBannerOptions, type ShowMessageOptions, type SpendCreditsParams, Tolinku, type TolinkuConfig, TolinkuError, type TrackProperties, type ViewItemParams };
548
+ export { type AddPaymentInfoParams, type AddToCartParams, type AddToWishlistParams, type BannerConfig, type BannerItem, type BeginCheckoutParams, type ClaimBySignalsOptions, type CompleteReferralOptions, type CompleteReferralResult, type CreateReferralOptions, type CreateReferralResult, type DeferredLink, type EcommerceItem, type LeaderboardEntry, type Message, type MessageComponent, type MessageContent, type MilestoneOptions, type MilestoneResult, type PurchaseParams, type RateParams, type ReferralInfo, type RefundParams, type RemoveFromCartParams, type ResolvedLink, type SearchParams, type ShareParams, type ShowBannerOptions, type ShowMessageOptions, type SpendCreditsParams, Tolinku, type TolinkuConfig, TolinkuError, type TrackProperties, type ViewItemParams };
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ // src/types.ts
4
+ var SDK_VERSION = "0.6.0";
5
+
3
6
  // src/client.ts
4
7
  var MAX_RETRIES = 3;
5
8
  var BASE_DELAY_MS = 500;
@@ -65,6 +68,28 @@ var HttpClient = class {
65
68
  }
66
69
  return this.parseJson(res);
67
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 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.
79
+ */
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);
90
+ }
91
+ return this.parseJson(res);
92
+ }
68
93
  /** GET without API key auth (for public endpoints like banner config) */
69
94
  async getPublic(path, params) {
70
95
  let url = this._baseUrl + path;
@@ -170,6 +195,11 @@ var HttpClient = class {
170
195
  headers() {
171
196
  return {
172
197
  "X-API-Key": this.apiKey,
198
+ // Which SDK and version made the call. The other Tolinku SDKs say this in
199
+ // User-Agent, which a browser will not let a script set, so it goes in a
200
+ // header of our own. Without it a web integration is unidentifiable in the
201
+ // field and a version-specific bug cannot be traced to a version.
202
+ "X-Tolinku-SDK": `web/${SDK_VERSION}`,
173
203
  // Browsers default to "Accept: */*", which a server content-negotiating an
174
204
  // error page reads as "HTML is fine". Saying so explicitly keeps an error
175
205
  // parseable instead of arriving as a rendered page.
@@ -600,12 +630,12 @@ var Deferred = class {
600
630
  try {
601
631
  const link = await this.client.postPublic("/v1/api/deferred/claim-by-signals", {
602
632
  appspace_id: options.appspaceId,
603
- timezone: options.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone,
604
- language: options.language || navigator.language,
605
- screen_width: options.screenWidth || window.screen.width,
606
- screen_height: options.screenHeight || window.screen.height,
633
+ timezone: override(options.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone,
634
+ language: override(options.language) || navigator.language,
635
+ screen_width: override(options.screenWidth) || window.screen.width,
636
+ screen_height: override(options.screenHeight) || window.screen.height,
607
637
  // Separates devices reporting identical logical dimensions.
608
- device_pixel_ratio: options.devicePixelRatio || window.devicePixelRatio || 1
638
+ device_pixel_ratio: override(options.devicePixelRatio) || window.devicePixelRatio || 1
609
639
  });
610
640
  return { link, settled: true };
611
641
  } catch (err) {
@@ -627,6 +657,71 @@ var Deferred = class {
627
657
  }
628
658
  }
629
659
  };
660
+ function override(value) {
661
+ if (typeof value === "string") {
662
+ const trimmed = value.trim();
663
+ return trimmed === "" ? void 0 : trimmed;
664
+ }
665
+ if (typeof value === "number") {
666
+ return Number.isFinite(value) && value > 0 ? value : void 0;
667
+ }
668
+ return void 0;
669
+ }
670
+
671
+ // src/links.ts
672
+ function isRoutablePath(path) {
673
+ return typeof path === "string" && path.startsWith("/") && !path.startsWith("//");
674
+ }
675
+ var Links = class {
676
+ constructor(client) {
677
+ this.client = client;
678
+ }
679
+ /**
680
+ * What this link means, or null if it means nothing here.
681
+ *
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.
685
+ *
686
+ * Never throws. A link that cannot be resolved, for a bad network or any
687
+ * other reason, is one to fall back to your own handling for.
688
+ */
689
+ async resolve(url) {
690
+ if (!url || typeof url !== "string") return null;
691
+ let parsed;
692
+ try {
693
+ parsed = new URL(url.trim());
694
+ } catch {
695
+ return null;
696
+ }
697
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
698
+ 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;
706
+ } catch {
707
+ return null;
708
+ }
709
+ }
710
+ };
711
+
712
+ // src/url-safety.ts
713
+ function isSafeUrl(url) {
714
+ if (typeof url !== "string") return false;
715
+ const trimmed = url.trim();
716
+ if (!trimmed) return false;
717
+ try {
718
+ const base = typeof window !== "undefined" ? window.location.href : void 0;
719
+ const parsed = new URL(trimmed, base);
720
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
721
+ } catch {
722
+ return false;
723
+ }
724
+ }
630
725
 
631
726
  // src/storage.ts
632
727
  var BANNER_KEY = "tolinku_banner_dismissed";
@@ -745,14 +840,6 @@ function sanitizeClass(val) {
745
840
  if (!val || typeof val !== "string") return "";
746
841
  return val.replace(/[^a-zA-Z0-9_\-\s]/g, "").slice(0, 100).trim();
747
842
  }
748
- function isSafeUrl(url) {
749
- try {
750
- const parsed = new URL(url, window.location.href);
751
- return parsed.protocol === "http:" || parsed.protocol === "https:";
752
- } catch {
753
- return false;
754
- }
755
- }
756
843
  var Banners = class {
757
844
  constructor(client) {
758
845
  this.client = client;
@@ -1178,7 +1265,7 @@ var Messages = class {
1178
1265
  }
1179
1266
  case "Image": {
1180
1267
  const url = props.url || "";
1181
- if (!isSafeUrl2(url)) return null;
1268
+ if (!isSafeUrl(url)) return null;
1182
1269
  const el = document.createElement("img");
1183
1270
  el.src = url;
1184
1271
  el.alt = props.alt || "";
@@ -1209,7 +1296,7 @@ var Messages = class {
1209
1296
  if (options.onButtonPress) {
1210
1297
  options.onButtonPress(action, messageId);
1211
1298
  } else if (action) {
1212
- if (isSafeUrl2(action)) {
1299
+ if (isSafeUrl(action)) {
1213
1300
  window.location.href = action;
1214
1301
  }
1215
1302
  }
@@ -1254,16 +1341,8 @@ var Messages = class {
1254
1341
  }
1255
1342
  }
1256
1343
  };
1257
- function isSafeUrl2(url) {
1258
- try {
1259
- const parsed = new URL(url, window.location.href);
1260
- return parsed.protocol === "http:" || parsed.protocol === "https:";
1261
- } catch {
1262
- return false;
1263
- }
1264
- }
1265
1344
  function sanitizeCssUrl(url) {
1266
- if (!isSafeUrl2(url)) return null;
1345
+ if (!isSafeUrl(url)) return null;
1267
1346
  return url.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "").replace(/\r/g, "");
1268
1347
  }
1269
1348
  function sanitizeTextAlign(value) {
@@ -1312,6 +1391,7 @@ var Tolinku = class {
1312
1391
  this.ecommerce = new Ecommerce(this.client, () => this._userId);
1313
1392
  this.referrals = new Referrals(this.client);
1314
1393
  this.deferred = new Deferred(this.client);
1394
+ this.links = new Links(this.client);
1315
1395
  this.banners = new Banners(this.client);
1316
1396
  this.messages = new Messages(this.client);
1317
1397
  }