@frak-labs/core-sdk 0.2.1 → 1.0.0-beta.10dada3f

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 (93) hide show
  1. package/README.md +1 -2
  2. package/cdn/bundle.js +3 -3
  3. package/dist/actions-Bsl5ub7_.js +1 -0
  4. package/dist/actions-C_B0fn1P.cjs +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-BSGP3dbi.d.ts} +250 -73
  14. package/dist/{siweAuthenticate-CVigMOxz.d.cts → index-Bh0TuKYS.d.ts} +122 -8
  15. package/dist/{siweAuthenticate-CnCZ7mok.d.ts → index-DW8xes2o.d.cts} +122 -8
  16. package/dist/{computeLegacyProductId-b5cUWdAm.d.ts → index-TRJNS6B5.d.cts} +250 -73
  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-Bvhy_urG.d.cts} +395 -50
  22. package/dist/{openSso-CMzwvaCa.d.ts → openSso-D2kTUv0-.d.ts} +394 -49
  23. package/dist/sdkConfigStore-B6CkorsU.cjs +1 -0
  24. package/dist/sdkConfigStore-Dx0oAVEO.js +1 -0
  25. package/dist/src-CLF8o8WB.cjs +13 -0
  26. package/dist/src-al3X6r-n.js +13 -0
  27. package/package.json +12 -13
  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/processReferral.test.ts +73 -8
  38. package/src/actions/referral/processReferral.ts +15 -12
  39. package/src/actions/referral/setupReferral.test.ts +79 -0
  40. package/src/actions/referral/setupReferral.ts +32 -0
  41. package/src/actions/trackPurchaseStatus.test.ts +32 -20
  42. package/src/actions/trackPurchaseStatus.ts +3 -5
  43. package/src/actions/wrapper/modalBuilder.test.ts +4 -2
  44. package/src/actions/wrapper/modalBuilder.ts +6 -8
  45. package/src/clients/createIFrameFrakClient.ts +233 -28
  46. package/src/clients/transports/iframeLifecycleManager.test.ts +14 -94
  47. package/src/clients/transports/iframeLifecycleManager.ts +35 -53
  48. package/src/index.ts +25 -5
  49. package/src/stubs/rrweb.ts +9 -0
  50. package/src/types/config.ts +19 -3
  51. package/src/types/context.ts +16 -4
  52. package/src/types/index.ts +15 -1
  53. package/src/types/lifecycle/client.ts +29 -27
  54. package/src/types/lifecycle/iframe.ts +7 -8
  55. package/src/types/resolvedConfig.ts +138 -0
  56. package/src/types/rpc/displaySharingPage.ts +100 -0
  57. package/src/types/rpc/embedded/index.ts +1 -1
  58. package/src/types/rpc/interaction.ts +4 -0
  59. package/src/types/rpc/userReferralStatus.ts +20 -0
  60. package/src/types/rpc.ts +54 -5
  61. package/src/types/tracking.ts +36 -0
  62. package/src/utils/FrakContext.test.ts +179 -1
  63. package/src/utils/FrakContext.ts +83 -8
  64. package/src/utils/analytics/events/component.ts +58 -0
  65. package/src/utils/analytics/events/index.ts +20 -0
  66. package/src/utils/analytics/events/lifecycle.ts +26 -0
  67. package/src/utils/analytics/events/referral.ts +11 -0
  68. package/src/utils/analytics/index.ts +8 -0
  69. package/src/utils/{trackEvent.test.ts → analytics/trackEvent.test.ts} +22 -30
  70. package/src/utils/analytics/trackEvent.ts +34 -0
  71. package/src/utils/backendUrl.test.ts +2 -2
  72. package/src/utils/backendUrl.ts +1 -1
  73. package/src/utils/cache/index.ts +7 -0
  74. package/src/utils/cache/lruMap.test.ts +55 -0
  75. package/src/utils/cache/lruMap.ts +38 -0
  76. package/src/utils/cache/withCache.test.ts +168 -0
  77. package/src/utils/cache/withCache.ts +124 -0
  78. package/src/utils/inAppBrowser.ts +60 -0
  79. package/src/utils/index.ts +11 -5
  80. package/src/utils/mergeAttribution.test.ts +153 -0
  81. package/src/utils/mergeAttribution.ts +75 -0
  82. package/src/utils/sdkConfigStore.test.ts +405 -0
  83. package/src/utils/sdkConfigStore.ts +263 -0
  84. package/src/utils/sso.ts +3 -7
  85. package/dist/setupClient-BduY6Sym.cjs +0 -13
  86. package/dist/setupClient-ftmdQ-I8.js +0 -13
  87. package/dist/siweAuthenticate-BWmI2_TN.cjs +0 -1
  88. package/dist/siweAuthenticate-zczqxm0a.js +0 -1
  89. package/dist/trackEvent-CeLFVzZn.js +0 -1
  90. package/dist/trackEvent-Ew5r5zfI.cjs +0 -1
  91. package/src/utils/merchantId.test.ts +0 -653
  92. package/src/utils/merchantId.ts +0 -143
  93. package/src/utils/trackEvent.ts +0 -41
@@ -8,7 +8,6 @@ export type IFrameLifecycleEvent =
8
8
  data?: never;
9
9
  }
10
10
  | DoBackupEvent
11
- | HandshakeRequestEvent
12
11
  | RedirectRequestEvent;
13
12
 
14
13
  type DoBackupEvent = {
@@ -16,13 +15,6 @@ type DoBackupEvent = {
16
15
  data: { backup?: string };
17
16
  };
18
17
 
19
- type HandshakeRequestEvent = {
20
- iframeLifecycle: "handshake";
21
- data: {
22
- token: string;
23
- };
24
- };
25
-
26
18
  type RedirectRequestEvent = {
27
19
  iframeLifecycle: "redirect";
28
20
  data: {
@@ -37,5 +29,12 @@ type RedirectRequestEvent = {
37
29
  * Used when redirecting out of social browsers to preserve identity across contexts
38
30
  */
39
31
  mergeToken?: string;
32
+ /**
33
+ * When true, open the URL in a new tab via window.open(_blank)
34
+ * instead of navigating the current page.
35
+ * Requires the postMessage to include user activation delegation
36
+ * (includeUserActivation: true) so Safari allows the popup.
37
+ */
38
+ openInNewTab?: boolean;
40
39
  };
41
40
  };
@@ -0,0 +1,138 @@
1
+ import type { Currency, Language } from "./config";
2
+ import type { AttributionDefaults } from "./tracking";
3
+
4
+ /**
5
+ * Response from the merchant resolve endpoint
6
+ * @category Config
7
+ */
8
+ export type MerchantConfigResponse = {
9
+ merchantId: string;
10
+ name: string;
11
+ domain: string;
12
+ allowedDomains: string[];
13
+ sdkConfig?: ResolvedSdkConfig;
14
+ };
15
+
16
+ /**
17
+ * Resolved placement config from backend
18
+ * Translations already flattened: default + lang-specific merged into one record
19
+ * @category Config
20
+ */
21
+ export type ResolvedPlacement = {
22
+ /** Per-component configuration within this placement */
23
+ components?: {
24
+ buttonShare?: {
25
+ text?: string;
26
+ noRewardText?: string;
27
+ clickAction?: "embedded-wallet" | "share-modal" | "sharing-page";
28
+ useReward?: boolean;
29
+ css?: string;
30
+ };
31
+ buttonWallet?: {
32
+ position?: "right" | "left";
33
+ css?: string;
34
+ };
35
+ openInApp?: {
36
+ text?: string;
37
+ css?: string;
38
+ };
39
+ postPurchase?: {
40
+ badgeText?: string;
41
+ refereeText?: string;
42
+ refereeNoRewardText?: string;
43
+ referrerText?: string;
44
+ referrerNoRewardText?: string;
45
+ ctaText?: string;
46
+ ctaNoRewardText?: string;
47
+ css?: string;
48
+ };
49
+ banner?: {
50
+ referralTitle?: string;
51
+ referralDescription?: string;
52
+ referralCta?: string;
53
+ inappTitle?: string;
54
+ inappDescription?: string;
55
+ inappCta?: string;
56
+ css?: string;
57
+ };
58
+ };
59
+ targetInteraction?: string;
60
+ /** Already flattened: default + lang-specific merged into one record */
61
+ translations?: Record<string, string>;
62
+ /** Global placement CSS (applied to modals/listener) */
63
+ css?: string;
64
+ };
65
+
66
+ /**
67
+ * Resolved SDK config from backend `/resolve` endpoint
68
+ * Language resolution and translation merging already applied
69
+ * @category Config
70
+ */
71
+ export type ResolvedSdkConfig = {
72
+ name?: string;
73
+ logoUrl?: string;
74
+ homepageLink?: string;
75
+ currency?: Currency;
76
+ lang?: Language;
77
+ /** When true, all SDK components should be hidden */
78
+ hidden?: boolean;
79
+ css?: string;
80
+ translations?: Record<string, string>;
81
+ placements?: Record<string, ResolvedPlacement>;
82
+ /** Global component defaults (used when no placement override exists) */
83
+ components?: ResolvedPlacement["components"];
84
+ /**
85
+ * Default attribution params applied when building outbound sharing URLs.
86
+ * Per-call overrides win over these backend defaults; `utm_content` is
87
+ * intentionally excluded (per-content/per-product, never a merchant default).
88
+ */
89
+ attribution?: AttributionDefaults;
90
+ };
91
+
92
+ /**
93
+ * Internal SDK config store state
94
+ * Merged config: backend > SDK static > defaults
95
+ * Components subscribe to this reactively
96
+ * @category Config
97
+ */
98
+ export type SdkResolvedConfig = {
99
+ /** Whether the backend config has been resolved */
100
+ isResolved: boolean;
101
+
102
+ /** Merchant ID from resolution */
103
+ merchantId: string;
104
+
105
+ /** Domain returned by the resolve endpoint */
106
+ domain?: string;
107
+
108
+ /** Domains allowed for this merchant (used by iframe trust check) */
109
+ allowedDomains?: string[];
110
+
111
+ /** Whether the resolve returned a backend sdkConfig object */
112
+ hasRawSdkConfig?: boolean;
113
+
114
+ /** Merged metadata fields */
115
+ name?: string;
116
+ logoUrl?: string;
117
+ homepageLink?: string;
118
+ lang?: Language;
119
+ currency?: Currency;
120
+
121
+ /** When true, all SDK components should be hidden */
122
+ hidden?: boolean;
123
+
124
+ /** Global CSS from backend config (passed to iframe) */
125
+ css?: string;
126
+
127
+ /** Global translations (for reference / component fallback) */
128
+ translations?: Record<string, string>;
129
+
130
+ /** Named placements (keyed by placement ID) */
131
+ placements?: Record<string, ResolvedPlacement>;
132
+
133
+ /** Global component defaults (fallback for placement-level overrides) */
134
+ components?: ResolvedPlacement["components"];
135
+
136
+ /** Merged attribution defaults: backend > SDK static config */
137
+ attribution?: AttributionDefaults;
138
+ };
@@ -0,0 +1,100 @@
1
+ import type { InteractionTypeKey } from "../../constants/interactionTypes";
2
+ import type { I18nConfig } from "../config";
3
+ import type { AttributionParams } from "../tracking";
4
+
5
+ /**
6
+ * Product information to display on the sharing page
7
+ * @group Sharing Page
8
+ */
9
+ export type SharingPageProduct = {
10
+ /**
11
+ * The product title / name
12
+ */
13
+ title: string;
14
+ /**
15
+ * Optional product image URL
16
+ */
17
+ imageUrl?: string;
18
+ /**
19
+ * Optional product-specific sharing link
20
+ * When provided and the product is selected, this link is used instead of the default sharing link
21
+ */
22
+ link?: string;
23
+ /**
24
+ * Optional `utm_content` value to apply when this product is selected.
25
+ * Falls back to the page-level `attribution.utmContent` when omitted.
26
+ */
27
+ utmContent?: string;
28
+ };
29
+
30
+ /**
31
+ * Parameters to display the sharing page
32
+ * @group Sharing Page
33
+ * @group RPC Schema
34
+ */
35
+ export type DisplaySharingPageParamsType = {
36
+ /**
37
+ * Products to showcase on the sharing page
38
+ * If provided, they will be displayed in a product card section
39
+ */
40
+ products?: SharingPageProduct[];
41
+ /**
42
+ * Optional link override for sharing
43
+ * If not provided, the sharing link will be generated from the current page URL + merchant context
44
+ */
45
+ link?: string;
46
+ /**
47
+ * Optional attribution overrides for the outbound sharing URL.
48
+ *
49
+ * When provided (even as an empty object), Frak adds standard affiliation
50
+ * params (`utm_source=frak`, `utm_medium=referral`, `utm_campaign=<merchantId>`,
51
+ * `ref=<clientId>`, `via=frak`) alongside `fCtx`. Existing UTMs on the base
52
+ * URL are preserved (gap-fill). Set this to `null` to disable attribution
53
+ * params entirely (only `fCtx` is added).
54
+ *
55
+ * @default {} — defaults applied
56
+ */
57
+ attribution?: AttributionParams | null;
58
+ /**
59
+ * Optional metadata overrides for the sharing page
60
+ */
61
+ metadata?: {
62
+ /**
63
+ * Logo override for the sharing page header
64
+ */
65
+ logo?: string;
66
+ /**
67
+ * Link to the homepage of the calling website
68
+ */
69
+ homepageLink?: string;
70
+ /**
71
+ * The target interaction behind this sharing page
72
+ */
73
+ targetInteraction?: InteractionTypeKey;
74
+ /**
75
+ * i18n overrides for the sharing page
76
+ */
77
+ i18n?: I18nConfig;
78
+ };
79
+ };
80
+
81
+ /**
82
+ * Result of the sharing page display
83
+ * @group Sharing Page
84
+ * @group RPC Schema
85
+ */
86
+ export type DisplaySharingPageResultType = {
87
+ /**
88
+ * The action the user took
89
+ * - "shared": User used the native share dialog
90
+ * - "copied": User copied the link to clipboard
91
+ * - "dismissed": User dismissed the sharing page without acting
92
+ */
93
+ action: "shared" | "copied" | "dismissed";
94
+ /**
95
+ * The install URL for the Frak app
96
+ * Can be used as a fallback to redirect the user to the install page
97
+ * from the merchant's top-level page (e.g. via `window.location.href`)
98
+ */
99
+ installUrl?: string;
100
+ };
@@ -9,10 +9,10 @@ import type {
9
9
  import type { LoggedOutEmbeddedView } from "./loggedOut";
10
10
 
11
11
  export type {
12
+ EmbeddedViewActionReferred,
12
13
  EmbeddedViewActionSharing,
13
14
  LoggedInEmbeddedView,
14
15
  LoggedOutEmbeddedView,
15
- EmbeddedViewActionReferred,
16
16
  };
17
17
 
18
18
  /**
@@ -26,6 +26,10 @@ export type SendInteractionParamsType =
26
26
  }
27
27
  | {
28
28
  type: "sharing";
29
+ /** Epoch seconds timestamp matching the V2 context `t` field embedded in the referral link URL, used for backend correlation */
30
+ sharingTimestamp?: number;
31
+ /** Merchant order ID linking this sharing event to a purchase (stays server-side, never in URL) */
32
+ purchaseId?: string;
29
33
  }
30
34
  | {
31
35
  type: "custom";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * User referral status returned by `frak_getUserReferralStatus`.
3
+ *
4
+ * Generic referral context for the current user on a merchant.
5
+ * Used by components like `<frak-post-purchase>` and `<frak-referred-banner>`
6
+ * to adapt their display based on the user's referral relationship.
7
+ *
8
+ * Returns `null` when the user's identity cannot be resolved
9
+ * (e.g. no clientId and no wallet session).
10
+ *
11
+ * @group RPC Schema
12
+ */
13
+ export type UserReferralStatusType = {
14
+ /**
15
+ * Whether the user was referred to this merchant by someone else.
16
+ *
17
+ * `true` means a referral link exists where this user is the referee.
18
+ */
19
+ isReferred: boolean;
20
+ };
package/src/types/rpc.ts CHANGED
@@ -4,6 +4,10 @@ import type {
4
4
  ModalRpcStepsInput,
5
5
  ModalRpcStepsResultType,
6
6
  } from "./rpc/displayModal";
7
+ import type {
8
+ DisplaySharingPageParamsType,
9
+ DisplaySharingPageResultType,
10
+ } from "./rpc/displaySharingPage";
7
11
  import type {
8
12
  DisplayEmbeddedWalletParamsType,
9
13
  DisplayEmbeddedWalletResultType,
@@ -16,6 +20,7 @@ import type {
16
20
  PrepareSsoParamsType,
17
21
  PrepareSsoReturnType,
18
22
  } from "./rpc/sso";
23
+ import type { UserReferralStatusType } from "./rpc/userReferralStatus";
19
24
  import type { WalletStatusReturnType } from "./rpc/walletStatus";
20
25
 
21
26
  /**
@@ -38,7 +43,7 @@ import type { WalletStatusReturnType } from "./rpc/walletStatus";
38
43
  * - Response Type: stream (emits updates when wallet status changes)
39
44
  *
40
45
  * #### frak_displayModal
41
- * - Params: [requests: {@link ModalRpcStepsInput}, metadata?: {@link ModalRpcMetadata}, configMetadata: {@link FrakWalletSdkConfig}["metadata"]]
46
+ * - Params: [requests: {@link ModalRpcStepsInput}, metadata?: {@link ModalRpcMetadata}, configMetadata: {@link FrakWalletSdkConfig}["metadata"], placement?: string]
42
47
  * - Returns: {@link ModalRpcStepsResultType}
43
48
  * - Response Type: promise (one-shot)
44
49
  *
@@ -53,9 +58,14 @@ import type { WalletStatusReturnType } from "./rpc/walletStatus";
53
58
  * - Response Type: promise (one-shot)
54
59
  *
55
60
  * #### frak_displayEmbeddedWallet
56
- * - Params: [request: {@link DisplayEmbeddedWalletParamsType}, metadata: {@link FrakWalletSdkConfig}["metadata"]]
61
+ * - Params: [request: {@link DisplayEmbeddedWalletParamsType}, metadata: {@link FrakWalletSdkConfig}["metadata"], placement?: string]
57
62
  * - Returns: {@link DisplayEmbeddedWalletResultType}
58
63
  * - Response Type: promise (one-shot)
64
+ *
65
+ * #### frak_displaySharingPage
66
+ * - Params: [request: {@link DisplaySharingPageParamsType}, configMetadata: {@link FrakWalletSdkConfig}["metadata"], placement?: string]
67
+ * - Returns: {@link DisplaySharingPageResultType}
68
+ * - Response Type: promise (one-shot)
59
69
  */
60
70
  export type IFrameRpcSchema = [
61
71
  /**
@@ -77,6 +87,7 @@ export type IFrameRpcSchema = [
77
87
  requests: ModalRpcStepsInput,
78
88
  metadata: ModalRpcMetadata | undefined,
79
89
  configMetadata: FrakWalletSdkConfig["metadata"],
90
+ placement?: string,
80
91
  ];
81
92
  ReturnType: ModalRpcStepsResultType;
82
93
  },
@@ -89,7 +100,7 @@ export type IFrameRpcSchema = [
89
100
  Method: "frak_prepareSso";
90
101
  Parameters: [
91
102
  params: PrepareSsoParamsType,
92
- name: string,
103
+ name?: string,
93
104
  customCss?: string,
94
105
  ];
95
106
  ReturnType: PrepareSsoReturnType;
@@ -104,7 +115,7 @@ export type IFrameRpcSchema = [
104
115
  Method: "frak_openSso";
105
116
  Parameters: [
106
117
  params: OpenSsoParamsType,
107
- name: string,
118
+ name?: string,
108
119
  customCss?: string,
109
120
  ];
110
121
  ReturnType: OpenSsoReturnType;
@@ -130,6 +141,7 @@ export type IFrameRpcSchema = [
130
141
  Parameters: [
131
142
  request: DisplayEmbeddedWalletParamsType,
132
143
  metadata: FrakWalletSdkConfig["metadata"],
144
+ placement?: string,
133
145
  ];
134
146
  ReturnType: DisplayEmbeddedWalletResultType;
135
147
  },
@@ -137,7 +149,7 @@ export type IFrameRpcSchema = [
137
149
  * Method to send interactions (arrival, sharing, custom events)
138
150
  * Fire-and-forget method - no return value expected
139
151
  * merchantId is resolved from context
140
- * clientId is passed via metadata as safeguard against handshake race condition
152
+ * clientId is passed via metadata as safeguard against race conditions
141
153
  */
142
154
  {
143
155
  Method: "frak_sendInteraction";
@@ -147,4 +159,41 @@ export type IFrameRpcSchema = [
147
159
  ];
148
160
  ReturnType: undefined;
149
161
  },
162
+ /**
163
+ * Method to get the current user's referral status on this merchant.
164
+ * Returns whether the user was referred (has a referral link as referee).
165
+ * Returns null when the user's identity cannot be resolved.
166
+ * This is a one-shot request.
167
+ */
168
+ {
169
+ Method: "frak_getUserReferralStatus";
170
+ Parameters?: undefined;
171
+ ReturnType: UserReferralStatusType | null;
172
+ },
173
+ /**
174
+ * Method to display a sharing page with product info and sharing buttons
175
+ * Resolves on first user action (share/copy) but the page stays visible
176
+ * This is a one-shot request
177
+ */
178
+ {
179
+ Method: "frak_displaySharingPage";
180
+ Parameters: [
181
+ request: DisplaySharingPageParamsType,
182
+ configMetadata: FrakWalletSdkConfig["metadata"],
183
+ placement?: string,
184
+ ];
185
+ ReturnType: DisplaySharingPageResultType;
186
+ },
187
+ /**
188
+ * Method to get a merge token for the current anonymous identity.
189
+ * Used by in-app browser redirect flows to preserve identity
190
+ * when switching from a WebView to the system browser.
191
+ * Returns the merge token string, or null if unavailable.
192
+ * This is a one-shot request.
193
+ */
194
+ {
195
+ Method: "frak_getMergeToken";
196
+ Parameters?: undefined;
197
+ ReturnType: string | null;
198
+ },
150
199
  ];
@@ -8,6 +8,42 @@ export type UtmParams = {
8
8
  content?: string;
9
9
  };
10
10
 
11
+ /**
12
+ * Attribution parameters appended to outbound sharing URLs.
13
+ *
14
+ * Defaults are derived from the V2 Frak context when available:
15
+ * - `utmSource`: `"frak"`
16
+ * - `utmMedium`: `"referral"`
17
+ * - `utmCampaign`: merchantId (`context.m`)
18
+ * - `via`: `"frak"`
19
+ * - `ref`: clientId (`context.c`)
20
+ *
21
+ * Fields explicitly set here override the defaults. Existing params on the
22
+ * base URL are preserved (gap-fill policy) to respect merchant-provided UTMs.
23
+ */
24
+ export type AttributionParams = {
25
+ utmSource?: string;
26
+ utmMedium?: string;
27
+ utmCampaign?: string;
28
+ utmContent?: string;
29
+ utmTerm?: string;
30
+ via?: string;
31
+ ref?: string;
32
+ };
33
+
34
+ /**
35
+ * Merchant-level attribution defaults.
36
+ *
37
+ * Same shape as {@link AttributionParams} minus `utmContent`, because
38
+ * `utm_content` describes the specific content/creative being shared and is
39
+ * inherently per-call or per-product (never a merchant-wide default).
40
+ *
41
+ * Used as the shape for both:
42
+ * - `FrakWalletSdkConfig.attribution` (SDK-side compile-time defaults)
43
+ * - Backend merchant-config attribution (dashboard-driven defaults)
44
+ */
45
+ export type AttributionDefaults = Omit<AttributionParams, "utmContent">;
46
+
11
47
  export type TrackArrivalParams = {
12
48
  /** @deprecated V1 legacy — use referrerClientId for v2 contexts */
13
49
  referrerWallet?: Address;
@@ -42,7 +42,7 @@ describe("FrakContextManager", () => {
42
42
  expect(result).not.toMatch(/[+/=]/);
43
43
  });
44
44
 
45
- it("should return undefined when v2 context is missing clientId", () => {
45
+ it("should return undefined when v2 context has neither clientId nor wallet", () => {
46
46
  const partial = { v: 2 as const, m: "m", t: 123 };
47
47
  const result = FrakContextManager.compress(
48
48
  partial as FrakContextV2
@@ -50,6 +50,33 @@ describe("FrakContextManager", () => {
50
50
  expect(result).toBeUndefined();
51
51
  });
52
52
 
53
+ it("should compress v2 context with wallet only (no clientId)", () => {
54
+ const v2WithWalletOnly: FrakContextV2 = {
55
+ v: 2,
56
+ m: "merchant-uuid-1234",
57
+ t: 1709654400,
58
+ w: "0x1234567890123456789012345678901234567890" as Address,
59
+ };
60
+ const result = FrakContextManager.compress(v2WithWalletOnly);
61
+ expect(result).toBeDefined();
62
+ const decompressed = FrakContextManager.decompress(result);
63
+ expect(decompressed).toEqual(v2WithWalletOnly);
64
+ });
65
+
66
+ it("should compress v2 context with both clientId and wallet", () => {
67
+ const v2Hybrid: FrakContextV2 = {
68
+ v: 2,
69
+ c: "test-client-id-uuid",
70
+ m: "merchant-uuid-1234",
71
+ t: 1709654400,
72
+ w: "0x1234567890123456789012345678901234567890" as Address,
73
+ };
74
+ const result = FrakContextManager.compress(v2Hybrid);
75
+ expect(result).toBeDefined();
76
+ const decompressed = FrakContextManager.decompress(result);
77
+ expect(decompressed).toEqual(v2Hybrid);
78
+ });
79
+
53
80
  it("should return undefined when v2 context is missing merchantId", () => {
54
81
  const partial = { v: 2 as const, c: "c", t: 123 };
55
82
  const result = FrakContextManager.compress(
@@ -121,6 +148,157 @@ describe("FrakContextManager", () => {
121
148
  expect(result).toContain("baz=qux");
122
149
  expect(result).toContain("fCtx=");
123
150
  });
151
+
152
+ describe("update with attribution", () => {
153
+ const url = "https://example.com/product";
154
+
155
+ it("should apply default attribution params when attribution is omitted", () => {
156
+ const result = FrakContextManager.update({
157
+ url,
158
+ context: v2Context,
159
+ });
160
+
161
+ expect(result).toBeDefined();
162
+ expect(result).toContain("fCtx=");
163
+ const parsedUrl = new URL(result!);
164
+ expect(parsedUrl.searchParams.get("utm_source")).toBe(
165
+ "frak"
166
+ );
167
+ expect(parsedUrl.searchParams.get("utm_medium")).toBe(
168
+ "referral"
169
+ );
170
+ expect(parsedUrl.searchParams.get("utm_campaign")).toBe(
171
+ v2Context.m
172
+ );
173
+ expect(parsedUrl.searchParams.get("via")).toBe("frak");
174
+ expect(parsedUrl.searchParams.get("ref")).toBe(v2Context.c);
175
+ });
176
+
177
+ it("should apply default attribution params when attribution is an empty object", () => {
178
+ const result = FrakContextManager.update({
179
+ url,
180
+ context: v2Context,
181
+ attribution: {},
182
+ });
183
+
184
+ expect(result).toBeDefined();
185
+ const parsedUrl = new URL(result!);
186
+ expect(parsedUrl.searchParams.get("utm_source")).toBe(
187
+ "frak"
188
+ );
189
+ expect(parsedUrl.searchParams.get("utm_medium")).toBe(
190
+ "referral"
191
+ );
192
+ expect(parsedUrl.searchParams.get("utm_campaign")).toBe(
193
+ v2Context.m
194
+ );
195
+ expect(parsedUrl.searchParams.get("via")).toBe("frak");
196
+ expect(parsedUrl.searchParams.get("ref")).toBe(v2Context.c);
197
+ expect(
198
+ parsedUrl.searchParams.get("utm_content")
199
+ ).toBeNull();
200
+ expect(parsedUrl.searchParams.get("utm_term")).toBeNull();
201
+ });
202
+
203
+ it("should honor overrides over defaults", () => {
204
+ const result = FrakContextManager.update({
205
+ url,
206
+ context: v2Context,
207
+ attribution: {
208
+ utmSource: "newsletter",
209
+ utmMedium: "email",
210
+ utmCampaign: "spring-sale",
211
+ utmContent: "hero-banner",
212
+ utmTerm: "wallet",
213
+ via: "partner",
214
+ ref: "alice",
215
+ },
216
+ });
217
+
218
+ const parsedUrl = new URL(result!);
219
+ expect(parsedUrl.searchParams.get("utm_source")).toBe(
220
+ "newsletter"
221
+ );
222
+ expect(parsedUrl.searchParams.get("utm_medium")).toBe(
223
+ "email"
224
+ );
225
+ expect(parsedUrl.searchParams.get("utm_campaign")).toBe(
226
+ "spring-sale"
227
+ );
228
+ expect(parsedUrl.searchParams.get("utm_content")).toBe(
229
+ "hero-banner"
230
+ );
231
+ expect(parsedUrl.searchParams.get("utm_term")).toBe(
232
+ "wallet"
233
+ );
234
+ expect(parsedUrl.searchParams.get("via")).toBe("partner");
235
+ expect(parsedUrl.searchParams.get("ref")).toBe("alice");
236
+ });
237
+
238
+ it("should preserve merchant-provided UTMs on the base URL (gap-fill)", () => {
239
+ const baseUrl =
240
+ "https://example.com/product?utm_source=google&utm_campaign=merchant-spring";
241
+ const result = FrakContextManager.update({
242
+ url: baseUrl,
243
+ context: v2Context,
244
+ attribution: {},
245
+ });
246
+
247
+ const parsedUrl = new URL(result!);
248
+ // Merchant-provided values preserved
249
+ expect(parsedUrl.searchParams.get("utm_source")).toBe(
250
+ "google"
251
+ );
252
+ expect(parsedUrl.searchParams.get("utm_campaign")).toBe(
253
+ "merchant-spring"
254
+ );
255
+ // Missing ones filled by Frak defaults
256
+ expect(parsedUrl.searchParams.get("utm_medium")).toBe(
257
+ "referral"
258
+ );
259
+ expect(parsedUrl.searchParams.get("ref")).toBe(v2Context.c);
260
+ });
261
+
262
+ it("should skip fields with empty-string overrides", () => {
263
+ const result = FrakContextManager.update({
264
+ url,
265
+ context: v2Context,
266
+ attribution: { utmContent: "", utmTerm: "" },
267
+ });
268
+
269
+ const parsedUrl = new URL(result!);
270
+ expect(parsedUrl.searchParams.has("utm_content")).toBe(
271
+ false
272
+ );
273
+ expect(parsedUrl.searchParams.has("utm_term")).toBe(false);
274
+ });
275
+
276
+ it("should skip context-derived defaults for V1 (no merchantId/clientId)", () => {
277
+ const v1Context: FrakContextV1 = {
278
+ r: "0x1234567890123456789012345678901234567890" as Address,
279
+ };
280
+ const result = FrakContextManager.update({
281
+ url,
282
+ context: v1Context,
283
+ attribution: {},
284
+ });
285
+
286
+ const parsedUrl = new URL(result!);
287
+ // Static defaults still applied
288
+ expect(parsedUrl.searchParams.get("utm_source")).toBe(
289
+ "frak"
290
+ );
291
+ expect(parsedUrl.searchParams.get("utm_medium")).toBe(
292
+ "referral"
293
+ );
294
+ expect(parsedUrl.searchParams.get("via")).toBe("frak");
295
+ // No derivable values from V1
296
+ expect(parsedUrl.searchParams.has("utm_campaign")).toBe(
297
+ false
298
+ );
299
+ expect(parsedUrl.searchParams.has("ref")).toBe(false);
300
+ });
301
+ });
124
302
  });
125
303
  });
126
304