@frak-labs/core-sdk 0.2.1 → 1.0.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.
Files changed (77) hide show
  1. package/README.md +1 -2
  2. package/cdn/bundle.js +3 -3
  3. package/dist/actions-D4aBXbdp.cjs +1 -0
  4. package/dist/actions-Dq_uN-wn.js +1 -0
  5. package/dist/actions.cjs +1 -1
  6. package/dist/actions.d.cts +3 -3
  7. package/dist/actions.d.ts +3 -3
  8. package/dist/actions.js +1 -1
  9. package/dist/bundle.cjs +1 -1
  10. package/dist/bundle.d.cts +4 -4
  11. package/dist/bundle.d.ts +4 -4
  12. package/dist/bundle.js +1 -1
  13. package/dist/{computeLegacyProductId-CCAZvLa5.d.cts → index-BV5D9DsW.d.ts} +91 -37
  14. package/dist/{siweAuthenticate-CnCZ7mok.d.ts → index-BphwTmKA.d.cts} +122 -8
  15. package/dist/{computeLegacyProductId-b5cUWdAm.d.ts → index-Dwmo109y.d.cts} +91 -37
  16. package/dist/{siweAuthenticate-CVigMOxz.d.cts → index-_f8EuN_1.d.ts} +122 -8
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.d.cts +3 -3
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +1 -1
  21. package/dist/{openSso-B0g7-807.d.cts → openSso-BwEK2M98.d.cts} +283 -44
  22. package/dist/{openSso-CMzwvaCa.d.ts → openSso-C1Wzl5-i.d.ts} +283 -44
  23. package/dist/src-B1eliIi6.cjs +13 -0
  24. package/dist/src-C0UH1GsN.js +13 -0
  25. package/dist/trackEvent-BqJqRZ-u.cjs +1 -0
  26. package/dist/trackEvent-Bqq4jd6R.js +1 -0
  27. package/package.json +11 -12
  28. package/src/actions/displayEmbeddedWallet.ts +6 -2
  29. package/src/actions/displayModal.ts +6 -2
  30. package/src/actions/displaySharingPage.ts +49 -0
  31. package/src/actions/ensureIdentity.ts +2 -2
  32. package/src/actions/getMerchantInformation.test.ts +13 -1
  33. package/src/actions/getMerchantInformation.ts +20 -5
  34. package/src/actions/getMergeToken.ts +33 -0
  35. package/src/actions/getUserReferralStatus.ts +42 -0
  36. package/src/actions/index.ts +8 -1
  37. package/src/actions/referral/setupReferral.test.ts +79 -0
  38. package/src/actions/referral/setupReferral.ts +32 -0
  39. package/src/actions/trackPurchaseStatus.test.ts +32 -20
  40. package/src/actions/trackPurchaseStatus.ts +3 -5
  41. package/src/actions/wrapper/modalBuilder.test.ts +4 -2
  42. package/src/actions/wrapper/modalBuilder.ts +6 -8
  43. package/src/clients/createIFrameFrakClient.ts +151 -27
  44. package/src/clients/transports/iframeLifecycleManager.test.ts +14 -94
  45. package/src/clients/transports/iframeLifecycleManager.ts +35 -53
  46. package/src/index.ts +17 -4
  47. package/src/stubs/rrweb.ts +9 -0
  48. package/src/types/config.ts +10 -3
  49. package/src/types/index.ts +13 -1
  50. package/src/types/lifecycle/client.ts +22 -27
  51. package/src/types/lifecycle/iframe.ts +7 -8
  52. package/src/types/resolvedConfig.ts +128 -0
  53. package/src/types/rpc/displaySharingPage.ts +82 -0
  54. package/src/types/rpc/embedded/index.ts +1 -1
  55. package/src/types/rpc/interaction.ts +4 -0
  56. package/src/types/rpc/userReferralStatus.ts +20 -0
  57. package/src/types/rpc.ts +54 -5
  58. package/src/utils/backendUrl.test.ts +2 -2
  59. package/src/utils/backendUrl.ts +1 -1
  60. package/src/utils/cache/index.ts +7 -0
  61. package/src/utils/cache/lruMap.test.ts +55 -0
  62. package/src/utils/cache/lruMap.ts +38 -0
  63. package/src/utils/cache/withCache.test.ts +168 -0
  64. package/src/utils/cache/withCache.ts +124 -0
  65. package/src/utils/inAppBrowser.ts +60 -0
  66. package/src/utils/index.ts +6 -4
  67. package/src/utils/sdkConfigStore.test.ts +405 -0
  68. package/src/utils/sdkConfigStore.ts +263 -0
  69. package/src/utils/sso.ts +3 -7
  70. package/dist/setupClient-BduY6Sym.cjs +0 -13
  71. package/dist/setupClient-ftmdQ-I8.js +0 -13
  72. package/dist/siweAuthenticate-BWmI2_TN.cjs +0 -1
  73. package/dist/siweAuthenticate-zczqxm0a.js +0 -1
  74. package/dist/trackEvent-CeLFVzZn.js +0 -1
  75. package/dist/trackEvent-Ew5r5zfI.cjs +0 -1
  76. package/src/utils/merchantId.test.ts +0 -653
  77. package/src/utils/merchantId.ts +0 -143
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it } from "../../../tests/vitest-fixtures";
2
+ import { LruMap } from "./lruMap";
3
+
4
+ describe("LruMap", () => {
5
+ it("should store and retrieve values", () => {
6
+ const map = new LruMap<number>(3);
7
+ map.set("a", 1);
8
+ map.set("b", 2);
9
+
10
+ expect(map.get("a")).toBe(1);
11
+ expect(map.get("b")).toBe(2);
12
+ });
13
+
14
+ it("should evict least recently used when exceeding max size", () => {
15
+ const map = new LruMap<number>(2);
16
+ map.set("a", 1);
17
+ map.set("b", 2);
18
+ map.set("c", 3); // Should evict "a"
19
+
20
+ expect(map.get("a")).toBeUndefined();
21
+ expect(map.get("b")).toBe(2);
22
+ expect(map.get("c")).toBe(3);
23
+ });
24
+
25
+ it("should promote accessed keys to most recently used", () => {
26
+ const map = new LruMap<number>(2);
27
+ map.set("a", 1);
28
+ map.set("b", 2);
29
+
30
+ // Access "a" to promote it
31
+ map.get("a");
32
+
33
+ // "b" is now least recently used, should be evicted
34
+ map.set("c", 3);
35
+
36
+ expect(map.get("a")).toBe(1);
37
+ expect(map.get("b")).toBeUndefined();
38
+ expect(map.get("c")).toBe(3);
39
+ });
40
+
41
+ it("should overwrite existing keys without increasing size", () => {
42
+ const map = new LruMap<number>(2);
43
+ map.set("a", 1);
44
+ map.set("b", 2);
45
+ map.set("a", 10); // Overwrite, not a new entry
46
+
47
+ expect(map.size).toBe(2);
48
+ expect(map.get("a")).toBe(10);
49
+ });
50
+
51
+ it("should return undefined for missing keys", () => {
52
+ const map = new LruMap<number>(2);
53
+ expect(map.get("missing")).toBeUndefined();
54
+ });
55
+ });
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Map with a LRU (Least Recently Used) eviction policy.
3
+ *
4
+ * When the map exceeds `maxSize`, the least recently accessed entry is removed.
5
+ * Accessing a key via `get()` promotes it to "most recently used".
6
+ *
7
+ * Adapted from viem's LruMap utility.
8
+ * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
9
+ */
10
+ export class LruMap<TValue = unknown> extends Map<string, TValue> {
11
+ maxSize: number;
12
+
13
+ constructor(size: number) {
14
+ super();
15
+ this.maxSize = size;
16
+ }
17
+
18
+ override get(key: string) {
19
+ const value = super.get(key);
20
+ if (super.has(key)) {
21
+ // Move to end (most recently used)
22
+ super.delete(key);
23
+ super.set(key, value as TValue);
24
+ }
25
+ return value;
26
+ }
27
+
28
+ override set(key: string, value: TValue) {
29
+ if (super.has(key)) super.delete(key);
30
+ super.set(key, value);
31
+ // Evict least recently used if over capacity
32
+ if (this.maxSize && this.size > this.maxSize) {
33
+ const firstKey = super.keys().next().value;
34
+ if (firstKey !== undefined) super.delete(firstKey);
35
+ }
36
+ return this;
37
+ }
38
+ }
@@ -0,0 +1,168 @@
1
+ import {
2
+ afterEach,
3
+ beforeEach,
4
+ describe,
5
+ expect,
6
+ it,
7
+ vi,
8
+ } from "../../../tests/vitest-fixtures";
9
+ import { clearAllCache, withCache } from "./withCache";
10
+
11
+ describe("withCache", () => {
12
+ beforeEach(() => {
13
+ clearAllCache();
14
+ });
15
+
16
+ afterEach(() => {
17
+ vi.restoreAllMocks();
18
+ });
19
+
20
+ describe("caching behavior", () => {
21
+ it("should call fn on first invocation", async () => {
22
+ const fn = vi.fn().mockResolvedValue("result");
23
+
24
+ const result = await withCache(fn, {
25
+ cacheKey: "test-key",
26
+ });
27
+
28
+ expect(fn).toHaveBeenCalledOnce();
29
+ expect(result).toBe("result");
30
+ });
31
+
32
+ it("should return cached result on subsequent calls within TTL", async () => {
33
+ const fn = vi.fn().mockResolvedValue("result");
34
+
35
+ await withCache(fn, {
36
+ cacheKey: "test-key",
37
+ cacheTime: 10_000,
38
+ });
39
+ const result = await withCache(fn, {
40
+ cacheKey: "test-key",
41
+ cacheTime: 10_000,
42
+ });
43
+
44
+ expect(fn).toHaveBeenCalledOnce();
45
+ expect(result).toBe("result");
46
+ });
47
+
48
+ it("should re-fetch after cache expires", async () => {
49
+ vi.useFakeTimers();
50
+
51
+ const fn = vi
52
+ .fn()
53
+ .mockResolvedValueOnce("first")
54
+ .mockResolvedValueOnce("second");
55
+
56
+ const first = await withCache(fn, {
57
+ cacheKey: "test-key",
58
+ cacheTime: 100,
59
+ });
60
+ expect(first).toBe("first");
61
+
62
+ // Advance past TTL
63
+ vi.advanceTimersByTime(200);
64
+
65
+ const second = await withCache(fn, {
66
+ cacheKey: "test-key",
67
+ cacheTime: 100,
68
+ });
69
+ expect(second).toBe("second");
70
+ expect(fn).toHaveBeenCalledTimes(2);
71
+
72
+ vi.useRealTimers();
73
+ });
74
+
75
+ it("should not cache when cacheTime is 0", async () => {
76
+ const fn = vi.fn().mockResolvedValue("result");
77
+
78
+ await withCache(fn, { cacheKey: "test-key", cacheTime: 0 });
79
+ await withCache(fn, { cacheKey: "test-key", cacheTime: 0 });
80
+
81
+ expect(fn).toHaveBeenCalledTimes(2);
82
+ });
83
+
84
+ it("should use different caches for different keys", async () => {
85
+ const fnA = vi.fn().mockResolvedValue("a");
86
+ const fnB = vi.fn().mockResolvedValue("b");
87
+
88
+ const a = await withCache(fnA, { cacheKey: "key-a" });
89
+ const b = await withCache(fnB, { cacheKey: "key-b" });
90
+
91
+ expect(a).toBe("a");
92
+ expect(b).toBe("b");
93
+ expect(fnA).toHaveBeenCalledOnce();
94
+ expect(fnB).toHaveBeenCalledOnce();
95
+ });
96
+ });
97
+
98
+ describe("deduplication", () => {
99
+ it("should deduplicate concurrent calls with the same key", async () => {
100
+ let resolvePromise: (value: string) => void;
101
+ const fn = vi.fn().mockImplementation(
102
+ () =>
103
+ new Promise<string>((resolve) => {
104
+ resolvePromise = resolve;
105
+ })
106
+ );
107
+
108
+ const promise1 = withCache(fn, { cacheKey: "dedup-key" });
109
+ const promise2 = withCache(fn, { cacheKey: "dedup-key" });
110
+
111
+ // fn should only be called once
112
+ expect(fn).toHaveBeenCalledOnce();
113
+
114
+ // Both should resolve to the same value
115
+ resolvePromise!("shared");
116
+ const [result1, result2] = await Promise.all([promise1, promise2]);
117
+ expect(result1).toBe("shared");
118
+ expect(result2).toBe("shared");
119
+ });
120
+ });
121
+
122
+ describe("error handling", () => {
123
+ it("should propagate errors from fn", async () => {
124
+ const fn = vi.fn().mockRejectedValue(new Error("fetch failed"));
125
+
126
+ await expect(
127
+ withCache(fn, { cacheKey: "error-key" })
128
+ ).rejects.toThrow("fetch failed");
129
+ });
130
+
131
+ it("should not cache errors — subsequent call retries", async () => {
132
+ vi.useFakeTimers();
133
+ const fn = vi
134
+ .fn()
135
+ .mockRejectedValueOnce(new Error("fail"))
136
+ .mockResolvedValueOnce("recovered");
137
+
138
+ await expect(
139
+ withCache(fn, { cacheKey: "retry-key" })
140
+ ).rejects.toThrow("fail");
141
+
142
+ // Advance past the negative cache backoff (1s)
143
+ vi.advanceTimersByTime(1_001);
144
+
145
+ const result = await withCache(fn, { cacheKey: "retry-key" });
146
+ expect(result).toBe("recovered");
147
+ expect(fn).toHaveBeenCalledTimes(2);
148
+
149
+ vi.useRealTimers();
150
+ });
151
+ });
152
+
153
+ describe("clearAllCache", () => {
154
+ it("should clear all cached data", async () => {
155
+ const fn = vi
156
+ .fn()
157
+ .mockResolvedValueOnce("first")
158
+ .mockResolvedValueOnce("second");
159
+
160
+ await withCache(fn, { cacheKey: "clear-key" });
161
+ clearAllCache();
162
+ const result = await withCache(fn, { cacheKey: "clear-key" });
163
+
164
+ expect(result).toBe("second");
165
+ expect(fn).toHaveBeenCalledTimes(2);
166
+ });
167
+ });
168
+ });
@@ -0,0 +1,124 @@
1
+ import { LruMap } from "./lruMap";
2
+
3
+ type CacheEntry<TData> = {
4
+ data: TData;
5
+ created: number;
6
+ };
7
+
8
+ /** Global cache for in-flight promises (dedup concurrent calls) */
9
+ const promiseCache = new LruMap<Promise<unknown>>(1024);
10
+
11
+ /** Global cache for resolved responses (TTL-based) */
12
+ const responseCache = new LruMap<CacheEntry<unknown>>(1024);
13
+
14
+ /** Default cache time: 30 seconds */
15
+ export const DEFAULT_CACHE_TIME = 30_000;
16
+
17
+ /** Short negative cache to avoid flooding on transient failures */
18
+ const NEGATIVE_CACHE_TIME = 1_000;
19
+
20
+ /** Tracks recently failed keys to avoid request floods */
21
+ const failureCache = new LruMap<number>(1024);
22
+
23
+ type WithCacheOptions = {
24
+ /** The key to cache the data against */
25
+ cacheKey: string;
26
+ /** Time in ms that cached data will remain valid. Default: 30_000 (30s). Set to 0 to disable caching. */
27
+ cacheTime?: number;
28
+ };
29
+
30
+ /**
31
+ * Returns the result of a given promise, and caches the result for
32
+ * subsequent invocations against a provided cache key.
33
+ *
34
+ * Also deduplicates concurrent calls — if multiple callers request the same
35
+ * cache key while the promise is pending, they share the same promise.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * // First call fetches, subsequent calls return cached data for 30s
40
+ * const data = await withCache(
41
+ * () => client.request({ method: "frak_getMerchantInformation" }),
42
+ * { cacheKey: "merchantInfo", cacheTime: 30_000 }
43
+ * );
44
+ * ```
45
+ */
46
+ export async function withCache<TData>(
47
+ fn: () => Promise<TData>,
48
+ { cacheKey, cacheTime = DEFAULT_CACHE_TIME }: WithCacheOptions
49
+ ): Promise<TData> {
50
+ // Check response cache — return immediately if fresh
51
+ if (cacheTime > 0) {
52
+ const cached = responseCache.get(cacheKey) as
53
+ | CacheEntry<TData>
54
+ | undefined;
55
+ if (cached) {
56
+ const age = Date.now() - cached.created;
57
+ if (age < cacheTime) return cached.data;
58
+ }
59
+ }
60
+
61
+ // Check if this key recently failed — back off briefly
62
+ const lastFailure = failureCache.get(cacheKey);
63
+ if (lastFailure && Date.now() - lastFailure < NEGATIVE_CACHE_TIME) {
64
+ throw new Error(`Cache: ${cacheKey} recently failed, backing off`);
65
+ }
66
+
67
+ // Check if there's already a pending promise (dedup concurrent calls)
68
+ let promise = promiseCache.get(cacheKey) as Promise<TData> | undefined;
69
+ if (!promise) {
70
+ promise = fn();
71
+ promiseCache.set(cacheKey, promise);
72
+ }
73
+
74
+ try {
75
+ const data = await promise;
76
+ // Store the response with a timestamp
77
+ responseCache.set(cacheKey, { data, created: Date.now() });
78
+ // Clear any previous failure
79
+ failureCache.delete(cacheKey);
80
+ return data;
81
+ } catch (error) {
82
+ // Record the failure timestamp
83
+ failureCache.set(cacheKey, Date.now());
84
+ throw error;
85
+ } finally {
86
+ // Clear the promise cache so subsequent calls can re-fetch after TTL
87
+ promiseCache.delete(cacheKey);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Get a cache handle for a specific key, useful for manual invalidation.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * // Invalidate merchant info cache after a mutation
97
+ * getCache("frak_getMerchantInformation").clear();
98
+ * ```
99
+ */
100
+ export function getCache(cacheKey: string) {
101
+ return {
102
+ /** Clear both the pending promise and the cached response */
103
+ clear: () => {
104
+ promiseCache.delete(cacheKey);
105
+ responseCache.delete(cacheKey);
106
+ },
107
+ /** Check if a non-expired response exists */
108
+ has: (cacheTime: number = DEFAULT_CACHE_TIME) => {
109
+ const cached = responseCache.get(cacheKey);
110
+ if (!cached) return false;
111
+ return Date.now() - cached.created < cacheTime;
112
+ },
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Clear all cached data (both pending promises and resolved responses).
118
+ * Called automatically when the client is destroyed.
119
+ */
120
+ export function clearAllCache() {
121
+ promiseCache.clear();
122
+ responseCache.clear();
123
+ failureCache.clear();
124
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Check if the current device runs iOS (including iPadOS 13+).
3
+ */
4
+ function checkIsIOS(): boolean {
5
+ if (typeof navigator === "undefined") return false;
6
+ const ua = navigator.userAgent;
7
+ // Standard iOS devices
8
+ if (/iPhone|iPad|iPod/i.test(ua)) return true;
9
+ // iPadOS 13+ reports as Macintosh — detect via touch support
10
+ if (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1) return true;
11
+ return false;
12
+ }
13
+
14
+ /**
15
+ * Whether the current device runs iOS (including iPadOS 13+).
16
+ */
17
+ export const isIOS: boolean = checkIsIOS();
18
+
19
+ /**
20
+ * Check if the current browser is a social media in-app browser
21
+ * (Instagram, Facebook WebView).
22
+ */
23
+ function checkInAppBrowser(): boolean {
24
+ if (typeof navigator === "undefined") return false;
25
+ const ua = navigator.userAgent.toLowerCase();
26
+ return (
27
+ ua.includes("instagram") ||
28
+ ua.includes("fban") ||
29
+ ua.includes("fbav") ||
30
+ ua.includes("facebook")
31
+ );
32
+ }
33
+
34
+ /**
35
+ * Whether the current browser is a social media in-app browser
36
+ * (Instagram, Facebook).
37
+ */
38
+ export const isInAppBrowser: boolean = checkInAppBrowser();
39
+
40
+ /**
41
+ * Redirect to external browser from in-app WebView.
42
+ *
43
+ * - **iOS**: Uses `x-safari-https://` scheme — server-side 302 redirects
44
+ * to custom URL schemes are silently swallowed by WKWebView.
45
+ * Direct `window.location.href` assignment works (confirmed iOS 17+).
46
+ *
47
+ * - **Android**: Uses backend `/common/social` endpoint which returns a PDF
48
+ * Content-Type response, forcing the WebView to hand off to the default browser.
49
+ *
50
+ * @param targetUrl - The URL to open in the external browser
51
+ */
52
+ export function redirectToExternalBrowser(targetUrl: string): void {
53
+ if (isIOS && targetUrl.startsWith("https://")) {
54
+ window.location.href = `x-safari-https://${targetUrl.slice(8)}`;
55
+ } else if (isIOS && targetUrl.startsWith("http://")) {
56
+ window.location.href = `x-safari-http://${targetUrl.slice(7)}`;
57
+ } else {
58
+ window.location.href = `${process.env.BACKEND_URL}/common/social?u=${encodeURIComponent(targetUrl)}`;
59
+ }
60
+ }
@@ -1,5 +1,6 @@
1
1
  export { Deferred } from "@frak-labs/frame-connector";
2
2
  export { getBackendUrl } from "./backendUrl";
3
+ export { clearAllCache, getCache, withCache } from "./cache";
3
4
  export { getClientId } from "./clientId";
4
5
  export { base64urlDecode, base64urlEncode } from "./compression/b64";
5
6
  export { compressJsonToB64 } from "./compression/compress";
@@ -23,10 +24,11 @@ export {
23
24
  findIframeInOpener,
24
25
  } from "./iframeHelper";
25
26
  export {
26
- clearMerchantIdCache,
27
- fetchMerchantId,
28
- resolveMerchantId,
29
- } from "./merchantId";
27
+ isInAppBrowser,
28
+ isIOS,
29
+ redirectToExternalBrowser,
30
+ } from "./inAppBrowser";
31
+ export { sdkConfigStore } from "./sdkConfigStore";
30
32
  export {
31
33
  type AppSpecificSsoMetadata,
32
34
  type CompressedSsoData,