expo-superwall 0.0.11 → 0.0.13

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.13
4
+
5
+ ### Patch Changes
6
+
7
+ - 2ead245: feat: add getDeviceAttributes
8
+ - efbd9d5: feat: add getDeviceAttributes to ios
9
+
10
+ ## 0.0.12
11
+
12
+ ### Patch Changes
13
+
14
+ - 4751b75: Fixes issues with identify on Android, updates Android SDK to 2.2.3
15
+
3
16
  ## 0.0.11
4
17
 
5
18
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  <p align="center">
2
2
  <br />
3
- <img src="https://i.imgur.com/7y68VTw.png" alt="logo" height="150px" />
3
+ <img src=https://user-images.githubusercontent.com/3296904/158817914-144c66d0-572d-43a4-9d47-d7d0b711c6d7.png alt="logo" height="100px" />
4
4
  <h3 style="font-size:26" align="center">In-App Paywalls Made Easy 💸</h3>
5
5
  <br />
6
6
  </p>
@@ -15,129 +15,379 @@
15
15
 
16
16
  This repository contains two SDKs for integrating Superwall with your Expo app:
17
17
 
18
- * **For new projects:** We recommend using our new **Hooks-based SDK**. Get started with the [Expo Superwall Hooks SDK Guide](./HOOK_SDK_GETTING_STARTED.md).
19
- * **For migrating from the Superwall React Native SDK:** Get setup in minutes with the **legacy/compat SDK (`expo-superwall/compat`)** below
18
+ * **For new projects:** We recommend using our new **Hooks-based SDK**. See the guide below.
19
+ * **For migrating from the Superwall React Native SDK:** Get setup in minutes with the [legacy/compat SDK (`expo-superwall/compat`) guide](./COMPAT_SDK_GETTING_STARTED.md).
20
20
  * **For older Expo SDKs:** Please refer to our [legacy React Native SDK](https://github.com/superwall/react-native-superwall).
21
21
 
22
- The documentation below primarily covers the **legacy/compat SDK (`expo-superwall/compat`)**. If you are using the new Hooks SDK, please refer to its specific [getting started guide](./HOOK_SDK_GETTING_STARTED.md).
23
-
24
- [Superwall](https://superwall.com/) lets you remotely configure every aspect of your paywall — helping you find winners quickly.
25
-
26
- ## Superwall
27
-
28
- **Superwall** is an open source framework that provides a wrapper for presenting and creating paywalls. It interacts with the Superwall backend letting you easily iterate paywalls on the fly in `React Native`!
29
-
30
- ## Features
31
- | | Superwall |
32
- | --- | --- |
33
- ✅ | Server-side paywall iteration
34
- 🎯 | Paywall conversion rate tracking - know whether a user converted after seeing a paywall
35
- 🆓 | Trial start rate tracking - know and measure your trial start rate out of the box
36
- 📊 | Analytics - automatic calculation of metrics like conversion and views
37
- ✏️ | A/B Testing - automatically calculate metrics for different paywalls
38
- 📝 | [Online documentation](https://superwall.com/docs/home) up to date
39
- 🔀 | [Integrations](https://superwall.com/docs/home) - over a dozen integrations to easily send conversion data where you need it
40
- 💯 | Well maintained - [frequent releases](https://superwall.com/docs/home)
41
- 📮 | Great support - email a founder: jake@superwall.com
42
-
22
+ ---
43
23
 
44
- ## Getting Started
24
+ # Getting Started with Expo Superwall SDK
45
25
 
46
- [Sign up for a free account on Superwall](https://superwall.com/sign-up) and [read our docs](https://superwall.com/docs/home).
26
+ This guide will help you integrate the Expo Superwall Hooks SDK into your React Native application, allowing you to easily manage users and display paywalls.
47
27
 
28
+ **Warning**: This SDK only supports Expo SDK Version >= 53. If you'd like to use older versions, please use our [legacy react-native sdk](https://github.com/superwall/react-native-superwall).
48
29
 
49
30
  ## Installation
50
31
 
32
+ First, you need to install the `expo-superwall` package. You can do this using npm or yarn:
33
+
51
34
  ```bash
52
35
  npx expo install expo-superwall
53
36
  # or
54
37
  bunx expo install expo-superwall
55
38
  ```
56
39
 
57
- > [!WARNING]
58
- > **Important: Expo SDK 53+ Required**
59
- >
60
- > This SDK is exclusively compatible with Expo SDK version 53 and newer.
61
- > For projects using older Expo versions, please use our [legacy React Native SDK](https://github.com/superwall/react-native-superwall).
40
+ ## Setup
62
41
 
63
- ### Basic Setup
42
+ To use the Superwall SDK, you need to wrap your application (or the relevant part of it) with the `<SuperwallProvider />`. This provider initializes the SDK with your API key.
64
43
 
65
44
  ```tsx
66
- import Superwall from "expo-superwall/compat"
67
- import { useEffect, useState } from "react"
68
- import { Platform } from "react-native"
69
-
70
- // Initialize Superwall
71
- useEffect(()=> {
72
- const apiKey = Platform.OS === "ios"
73
- ? "yourSuperwall_iOSKey"
74
- : "yourSuperwall_androidKey"
75
- await Superwall.configure({
76
- apiKey,
77
- })
78
- })
45
+ import { SuperwallProvider } from "expo-superwall";
46
+
47
+ // Replace with your actual Superwall API key
48
+ export default function App() {
49
+ return (
50
+ <SuperwallProvider apiKeys={{ ios: "YOUR_SUPERWALL_API_KEY" /* android: API_KEY */ }}>
51
+ {/* Your app content goes here */}
52
+ </SuperwallProvider>
53
+ );
54
+ }
79
55
  ```
80
56
 
81
- ### Identify User
57
+ **Note:** You can find your API key in your Superwall dashboard.
58
+
59
+ ## Basic Usage
60
+
61
+ The SDK provides hooks to interact with Superwall's features.
62
+
63
+ ### Handling Loading States
64
+
65
+ While the SDK is initializing, you can display a loading indicator. The `<SuperwallLoading />` and `<SuperwallLoaded />` components help manage this.
82
66
 
83
67
  ```tsx
84
- // Identify a user
85
- await Superwall.shared.identify({ userId })
86
-
87
- // Set User Attributes
88
- await Superwall.shared.setUserAttributes({
89
- someCustomVal: "abc",
90
- platform: Platform.OS,
91
- timestamp: new Date().toISOString(),
92
- })
68
+ import {
69
+ SuperwallProvider,
70
+ SuperwallLoading,
71
+ SuperwallLoaded,
72
+ } from "expo-superwall";
73
+ import { ActivityIndicator, View, Text } from "react-native";
74
+
75
+ const API_KEY = "YOUR_SUPERWALL_API_KEY";
76
+
77
+ export default function App() {
78
+ return (
79
+ <SuperwallProvider apiKeys={{ ios: API_KEY }}>
80
+ <SuperwallLoading>
81
+ <ActivityIndicator style={{ flex: 1 }} />
82
+ </SuperwallLoading>
83
+ <SuperwallLoaded>
84
+ {/* Your main app screen or component */}
85
+ <MainAppScreen />
86
+ </SuperwallLoaded>
87
+ </SuperwallProvider>
88
+ );
89
+ }
90
+
91
+ function MainAppScreen() {
92
+ return (
93
+ <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
94
+ <Text>Superwall SDK is ready!</Text>
95
+ {/* Rest of your app's UI */}
96
+ </View>
97
+ );
98
+ }
93
99
  ```
94
100
 
101
+ ### Managing Users with `useUser`
95
102
 
96
- ### Present a Paywall
103
+ The `useUser` hook provides functions to identify users, sign them out, update their attributes, and access user and subscription status information.
97
104
 
98
105
  ```tsx
99
- // Present a paywall
100
- Superwall.shared.register({
101
- "yourPlacementName",
106
+ import { useUser } from "expo-superwall";
107
+ import { Button, Text, View } from "react-native";
108
+
109
+ function UserManagementScreen() {
110
+ const { identify, user, signOut, update, subscriptionStatus } = useUser();
111
+
112
+ const handleLogin = async () => {
113
+ // Identify the user with a unique ID
114
+ await identify(`user_${Date.now()}`);
115
+ };
116
+
117
+ const handleSignOut = async () => {
118
+ await signOut();
119
+ };
120
+
121
+ const handleUpdateUserAttributes = async () => {
122
+ // Update custom user attributes
123
+ await update((oldAttributes) => ({
124
+ ...oldAttributes,
125
+ customProperty: "new_value",
126
+ counter: (oldAttributes.counter || 0) + 1,
127
+ }));
128
+ };
129
+
130
+ return (
131
+ <View style={{ padding: 20 }}>
132
+ <Text>Subscription Status: {subscriptionStatus?.status ?? "unknown"}</Text>
133
+ {user && <Text>User ID: {user.appUserId}</Text>}
134
+ {user && <Text>User Attributes: {JSON.stringify(user, null, 2)}</Text>}
135
+
136
+ <Button title="Login" onPress={handleLogin} />
137
+ <Button title="Sign Out" onPress={handleSignOut} />
138
+ <Button title="Update Attributes" onPress={handleUpdateUserAttributes} />
139
+ </View>
140
+ );
141
+ }
142
+ ```
143
+
144
+ Key functions from `useUser`:
145
+ - `identify(userId)`: Identifies the current user with Superwall. This is typically called when a user logs in.
146
+ - `signOut()`: Signs the current user out. Call this when a user logs out.
147
+ - `update(attributesUpdater)`: Updates the user's attributes. You can provide a function that receives the old attributes and returns the new ones.
148
+ - `user`: An object containing the user's `appUserId` and other attributes.
149
+ - `subscriptionStatus`: An object indicating the user's subscription status (e.g., `active`, `inactive`).
150
+
151
+ ### Triggering Paywalls with `usePlacement`
152
+
153
+ The `usePlacement` hook allows you to register and trigger paywalls (placements) that you've configured in your Superwall dashboard.
154
+
155
+ ```tsx
156
+ import { usePlacement, useUser } from "expo-superwall";
157
+ import { Alert, Button, Text, View } from "react-native";
158
+
159
+ function PaywallScreen() {
160
+ const { registerPlacement, state: placementState } = usePlacement({
161
+ onError: (err) => console.error("Placement Error:", err),
162
+ onPresent: (info) => console.log("Paywall Presented:", info),
163
+ onDismiss: (info, result) =>
164
+ console.log("Paywall Dismissed:", info, "Result:", result),
165
+ });
166
+
167
+ const handleTriggerPlacement = async () => {
168
+ await registerPlacement({
169
+ placement: "your_placement_id", // Replace with your actual placement ID
102
170
  feature() {
103
- console.log(`Feature called!`)
171
+ // This function is called if the user is already subscribed
172
+ // or successfully subscribes through the paywall.
173
+ console.log("Feature unlocked!");
174
+ Alert.alert("Feature Unlocked!", "You can now access this feature.");
104
175
  },
105
- })
176
+ });
177
+ };
178
+
179
+ return (
180
+ <View style={{ padding: 20 }}>
181
+ <Button title="Show Paywall for 'your_placement_id'" onPress={handleTriggerPlacement} />
182
+ {placementState && (
183
+ <Text>Last Paywall Result: {JSON.stringify(placementState)}</Text>
184
+ )}
185
+ </View>
186
+ );
187
+ }
106
188
  ```
107
189
 
190
+ Key aspects of `usePlacement`:
191
+ - `registerPlacement(options)`: Registers and potentially presents a paywall.
192
+ - `options.placement`: The ID of the placement you want to show (e.g., "fishing" from the example, or "onboarding_paywall").
193
+ - `options.feature()`: A callback function that is executed if the user has access to the feature (either by already being subscribed or by purchasing through the presented paywall).
194
+ - Callbacks (passed as options to `usePlacement`):
195
+ - `onError`: Handles errors during paywall presentation.
196
+ - `onPresent`: Called when a paywall is presented.
197
+ - `onDismiss`: Called when a paywall is dismissed.
198
+ - `state`: An object returned by the hook, containing information about the last paywall presentation attempt (e.g., `presented`, `purchased`, `cancelled`, `skipped`).
199
+
200
+ This covers the basic setup and usage of the `expo-superwall` Hooks SDK. For more advanced scenarios and detailed API information, refer to the official Superwall documentation.
108
201
 
109
- ### Listen to Events
202
+ ---
203
+
204
+ ## Hooks API Reference
205
+
206
+ This section provides a detailed reference for each hook available in the `expo-superwall` SDK.
207
+
208
+ ### `useSuperwall`
209
+
210
+ **Purpose:**
211
+ The `useSuperwall` hook is the core hook that provides access to the Superwall store and underlying SDK functionality. It's generally used internally by other more specific hooks like `useUser` and `usePlacement`, but can be used directly for advanced scenarios. It ensures that native event listeners are set up on first use.
212
+
213
+ **Returned Values (Store State and Actions):**
214
+
215
+ The hook returns an object representing the Superwall store. If a `selector` function is provided, it returns the selected slice of the store.
216
+
217
+ - **State:**
218
+ - `isConfigured: boolean`: True if the Superwall SDK has been configured with an API key.
219
+ - `isLoading: boolean`: True when the SDK is performing an asynchronous operation like configuration.
220
+ - `listenersInitialized: boolean`: True if native event listeners have been initialized.
221
+ - `user?: UserAttributes | null`: An object containing the current user's attributes.
222
+ - `UserAttributes`:
223
+ - `aliasId: string`: The alias ID of the user.
224
+ - `appUserId: string`: The application-specific user ID.
225
+ - `applicationInstalledAt: string`: ISO date string of when the application was installed.
226
+ - `seed: number`: A seed value for the user.
227
+ - `[key: string]: any`: Other custom user attributes.
228
+ - `subscriptionStatus?: SubscriptionStatus`: The current subscription status of the user.
229
+ - `SubscriptionStatus` (see `SuperwallExpoModule.types.ts` for full details):
230
+ - `status: "UNKNOWN" | "INACTIVE" | "ACTIVE"`
231
+ - `entitlements?: Entitlement[]` (if status is "ACTIVE")
232
+ - `Entitlement`: `{ id: string, type: EntitlementType }`
233
+
234
+ - **Actions (Functions):**
235
+ - `configure: (apiKey: string, options?: Record<string, any>) => Promise<void>`: Initializes the Superwall SDK with the provided API key and optional configuration options.
236
+ - `identify: (userId: string, options?: IdentifyOptions) => Promise<void>`: Identifies the user with the given `userId`.
237
+ - `IdentifyOptions`:
238
+ - `restorePaywallAssignments?: boolean`: If true, restores paywall assignments from a previous session.
239
+ - `reset: () => Promise<void>`: Resets the user's identity and clears any stored user-specific data. This is equivalent to logging out the user.
240
+ - `registerPlacement: (placement: string, params?: Record<string, any>, handlerId?: string | null) => Promise<void>`: Registers a placement. This may or may not present a paywall depending on campaign rules. `handlerId` is used internally by `usePlacement` to associate events.
241
+ - `getPresentationResult: (placement: string, params?: Record<string, any>) => Promise<any>`: Gets the presentation result for a given placement.
242
+ - `dismiss: () => Promise<void>`: Dismisses any currently presented paywall.
243
+ - `preloadAllPaywalls: () => Promise<void>`: Preloads all paywalls.
244
+ - `preloadPaywalls: (placements: string[]) => Promise<void>`: Preloads paywalls for the specified placement IDs.
245
+ - `setUserAttributes: (attrs: Record<string, any>) => Promise<void>`: Sets custom attributes for the current user.
246
+ - `getUserAttributes: () => Promise<Record<string, any>>`: Retrieves the attributes of the current user.
247
+ - `setLogLevel: (level: string) => Promise<void>`: Sets the log level for the SDK. `level` can be one of: `"debug"`, `"info"`, `"warn"`, `"error"`, `"none"`.
248
+
249
+ **Selector (Optional Parameter):**
250
+
251
+ - `selector?: (state: SuperwallStore) => T`: A function that receives the entire `SuperwallStore` state and returns a selected part of it. Useful for performance optimization by only re-rendering components when the selected state changes. Uses `zustand/shallow` for shallow equality checking.
252
+
253
+ **Example (Direct Usage - Advanced):**
110
254
 
111
255
  ```tsx
112
- // 1. Define your superwall Delegat
113
- import {
114
- EventType,
115
- type PaywallInfo,
116
- type RedemptionResult,
117
- type SubscriptionStatus,
118
- SuperwallDelegate,
119
- type SuperwallEventInfo,
120
- } from "expo-superwall/compat"
121
-
122
- export class MyDelegate extends SuperwallDelegate {
123
- handleSuperwallEvent(eventInfo) {
124
- switch (eventInfo.event.type) {
125
- case EventType.paywallOpen:
126
- console.log("Paywall opened");
127
- break;
128
- case EventType.paywallClose:
129
- console.log("Paywall closed");
130
- break;
131
- }
256
+ import { useSuperwall } from 'expo-superwall';
257
+
258
+ function MyAdvancedComponent() {
259
+ const { isConfigured, configure, setUserAttributes } = useSuperwall();
260
+
261
+ if (!isConfigured) {
262
+ return <Text>SDK not configured yet.</Text>;
132
263
  }
264
+
265
+ const handleSetCustomAttribute = () => {
266
+ setUserAttributes({ myCustomFlag: true });
267
+ };
268
+
269
+ return <Button title="Set Custom Flag" onPress={handleSetCustomAttribute} />;
133
270
  }
271
+ ```
134
272
 
135
- // 2. Simply set the delegate
136
- const delegate = new MySuperwallDelegate()
137
- await Superwall.shared.setDelegate(delegate)
273
+ ### `useUser`
274
+
275
+ **Purpose:**
276
+ The `useUser` hook provides a convenient way to manage user identity and attributes, and access user-specific information like subscription status.
277
+
278
+ **Returned Values:**
279
+
280
+ An object containing:
281
+
282
+ - `identify: (userId: string, options?: IdentifyOptions) => Promise<void>`: Identifies the user with Superwall.
283
+ - `userId: string`: The unique identifier for the user.
284
+ - `options?: IdentifyOptions`: Optional parameters for identification.
285
+ - `restorePaywallAssignments?: boolean`: If true, attempts to restore paywall assignments for this user.
286
+ - `update: (attributes: Record<string, any> | ((old: Record<string, any>) => Record<string, any>)) => Promise<void>`: Updates the current user's attributes.
287
+ - `attributes`: Either an object of attributes to set/update, or a function that takes the old attributes and returns the new attributes.
288
+ - `signOut: () => void`: Resets the user's identity, effectively signing them out from Superwall's perspective.
289
+ - `refresh: () => Promise<Record<string, any>>`: Manually refreshes the user's attributes and subscription status from the Superwall servers. Returns the refreshed user attributes.
290
+ - `subscriptionStatus?: SubscriptionStatus`: The current subscription status of the user.
291
+ - `SubscriptionStatus`: (As defined in `useSuperwall` and `SuperwallExpoModule.types.ts`)
292
+ - `status: "UNKNOWN" | "INACTIVE" | "ACTIVE"`
293
+ - `entitlements?: Entitlement[]` (if status is "ACTIVE")
294
+ - `user?: UserAttributes | null`: An object containing the current user's attributes (e.g., `appUserId`, `aliasId`, custom attributes).
295
+ - `UserAttributes`: (As defined in `useSuperwall`)
296
+
297
+ **Example:**
298
+ (Covered in the Basic Usage section)
299
+
300
+ ### `usePlacement`
301
+
302
+ **Purpose:**
303
+ The `usePlacement` hook is designed to handle the presentation of paywalls based on placements configured in your Superwall dashboard. It manages the state of paywall presentation and provides callbacks for various events.
304
+
305
+ **Parameters:**
306
+
307
+ - `callbacks?: usePlacementCallbacks`: An optional object containing callback functions for different paywall events.
308
+ - `usePlacementCallbacks`:
309
+ - `onPresent?: (paywallInfo: PaywallInfo) => void`: Called when a paywall is presented.
310
+ - `paywallInfo: PaywallInfo`: Detailed information about the presented paywall (see `SuperwallExpoModule.types.ts`).
311
+ - `onDismiss?: (paywallInfo: PaywallInfo, result: PaywallResult) => void`: Called when a paywall is dismissed.
312
+ - `paywallInfo: PaywallInfo`: Information about the dismissed paywall.
313
+ - `result: PaywallResult`: The result of the paywall interaction (e.g., `purchased`, `declined`, `restored`). See `SuperwallExpoModule.types.ts`.
314
+ - `onSkip?: (reason: PaywallSkippedReason) => void`: Called when a paywall is skipped (e.g., due to holdout group, no audience match).
315
+ - `reason: PaywallSkippedReason`: The reason why the paywall was skipped. See `SuperwallExpoModule.types.ts`.
316
+ - `onError?: (error: string) => void`: Called when an error occurs during paywall presentation or other SDK operations related to this placement.
317
+ - `error: string`: The error message.
318
+
319
+ **Returned Values:**
320
+
321
+ An object containing:
322
+
323
+ - `registerPlacement: (args: RegisterPlacementArgs) => Promise<void>`: A function to register a placement and potentially trigger a paywall.
324
+ - `RegisterPlacementArgs`:
325
+ - `placement: string`: The placement name as defined on the Superwall dashboard.
326
+ - `params?: Record<string, any>`: Optional parameters to pass to the placement.
327
+ - `feature?: () => void`: An optional function to execute if the placement does *not* result in a paywall presentation (i.e., the user is allowed through, or is already subscribed).
328
+ - `state: PaywallState`: An object representing the current state of the paywall associated with this hook instance.
329
+ - `PaywallState`:
330
+ - `{ status: "idle" }`
331
+ - `{ status: "presented"; paywallInfo: PaywallInfo }`
332
+ - `{ status: "dismissed"; result: PaywallResult }`
333
+ - `{ status: "skipped"; reason: PaywallSkippedReason }`
334
+ - `{ status: "error"; error: string }`
335
+
336
+ **Example:**
337
+ (Covered in the Basic Usage section)
338
+
339
+ ### `useSuperwallEvents`
340
+
341
+ **Purpose:**
342
+ The `useSuperwallEvents` hook provides a low-level way to subscribe to *any* native Superwall event. This is useful for advanced use cases or for events not covered by the more specific hooks. Listeners are automatically cleaned up when the component using this hook unmounts.
343
+
344
+ **Parameters:**
345
+
346
+ - `callbacks?: SuperwallEventCallbacks`: An object where keys are event names and values are the corresponding callback functions.
347
+ - `SuperwallEventCallbacks`: (Refer to `src/useSuperwallEvents.ts` and `src/SuperwallExpoModule.types.ts` for a full list of subscribable events and their payload types. Common events include):
348
+ - `onPaywallPresent?: (info: PaywallInfo) => void`
349
+ - `onPaywallDismiss?: (info: PaywallInfo, result: PaywallResult) => void`
350
+ - `onPaywallSkip?: (reason: PaywallSkippedReason) => void`
351
+ - `onPaywallError?: (error: string) => void`
352
+ - `onSubscriptionStatusChange?: (status: SubscriptionStatus) => void`
353
+ - `onSuperwallEvent?: (eventInfo: SuperwallEventInfo) => void`: For generic Superwall events.
354
+ - `SuperwallEventInfo`: `{ event: SuperwallEvent, params: Record<string, any> }`
355
+ - `onCustomPaywallAction?: (name: string) => void`: When a custom action is triggered from a paywall.
356
+ - `willDismissPaywall?: (info: PaywallInfo) => void`
357
+ - `willPresentPaywall?: (info: PaywallInfo) => void`
358
+ - `didDismissPaywall?: (info: PaywallInfo) => void`
359
+ - `didPresentPaywall?: (info: PaywallInfo) => void`
360
+ - `onPaywallWillOpenURL?: (url: string) => void`
361
+ - `onPaywallWillOpenDeepLink?: (url: string) => void`
362
+ - `onLog?: (params: { level: LogLevel, scope: LogScope, message: string | null, info: Record<string, any> | null, error: string | null }) => void`
363
+ - `handlerId?: string`: (Optional) If provided, some events like `onPaywallPresent`, `onPaywallDismiss`, `onPaywallSkip` will only be triggered if the event originated from a `registerPlacement` call associated with the same `handlerId`. This is used internally by `usePlacement`.
364
+
365
+ **Returned Values:**
366
+
367
+ This hook does not return any values (`void`). Its purpose is to set up and tear down event listeners.
368
+
369
+ **Example:**
138
370
 
371
+ ```tsx
372
+ import { useSuperwallEvents } from 'expo-superwall';
373
+
374
+ function EventLogger() {
375
+ useSuperwallEvents({
376
+ onSuperwallEvent: (eventInfo) => {
377
+ console.log('Superwall Event:', eventInfo.event.event, eventInfo.params);
378
+ },
379
+ onSubscriptionStatusChange: (newStatus) => {
380
+ console.log('Subscription Status Changed:', newStatus.status);
381
+ },
382
+ onPaywallPresent: (info) => {
383
+ console.log('Paywall Presented (via useSuperwallEvents):', info.name);
384
+ }
385
+ });
386
+
387
+ }
139
388
  ```
140
389
 
390
+ For detailed type information on `PaywallInfo`, `PaywallResult`, `PaywallSkippedReason`, `SubscriptionStatus`, `SuperwallEventInfo`, and other types, please refer to the `SuperwallExpoModule.types.ts` file in the `expo-superwall` package.
141
391
 
142
392
  ## Resources
143
393
 
@@ -43,7 +43,7 @@ android {
43
43
  }
44
44
 
45
45
  dependencies {
46
- implementation "com.superwall.sdk:superwall-android:2.1.2"
46
+ implementation "com.superwall.sdk:superwall-android:2.2.3"
47
47
  implementation 'com.android.billingclient:billing:6.1.0'
48
48
  implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.2'
49
49
  }
@@ -106,9 +106,9 @@ class SuperwallExpoModule : Module() {
106
106
  return@Function applicationInfo?.metaData?.getString("SUPERWALL_API_KEY")
107
107
  }
108
108
 
109
- Function("identify") { userId: String, options: Map<String, Any> ->
109
+ Function("identify") { userId: String, options: Map<String, Any>? ->
110
110
  try {
111
- val options = identityOptionsFromJson(options)
111
+ val options = options?.let { identityOptionsFromJson(options) }
112
112
  Superwall.instance.identify(userId = userId, options = options)
113
113
  } catch (error: Exception) {
114
114
  error.printStackTrace()
@@ -291,6 +291,18 @@ class SuperwallExpoModule : Module() {
291
291
  promise.resolve(attributes)
292
292
  }
293
293
 
294
+ AsyncFunction("getDeviceAttributes") { promise: Promise ->
295
+ scope.launch {
296
+ try {
297
+ val attributes = Superwall.instance.deviceAttributes()
298
+ promise.resolve(attributes)
299
+ } catch (e: Exception) {
300
+ promise.reject("GET_DEVICE_ATTRIBUTES_ERROR", e.message, e)
301
+ }
302
+ }
303
+ }
304
+
305
+
294
306
  Function("setUserAttributes") { userAttributes: Map<String, Any> ->
295
307
  Superwall.instance.setUserAttributes(userAttributes)
296
308
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-superwall",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "Offical Expo Integration for Superwall",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -21,6 +21,7 @@ declare class SuperwallExpoModule extends NativeModule<SuperwallExpoModuleEvents
21
21
  dismiss(): Promise<void>;
22
22
  confirmAllAssignments(): Promise<any[]>;
23
23
  getPresentationResult(placement: string, params?: Map<string, any> | Record<string, any>): Promise<any>;
24
+ getDeviceAttributes(): Promise<Record<string, any>>;
24
25
  preloadPaywalls(placementNames: string[]): void;
25
26
  preloadAllPaywalls(): void;
26
27
  setLogLevel(level: string): void;
@@ -1 +1 @@
1
- {"version":3,"file":"SuperwallExpoModule.d.ts","sourceRoot":"","sources":["../../src/SuperwallExpoModule.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAuB,MAAM,MAAM,CAAA;AACxD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAA;AAE5E,MAAM,MAAM,kBAAkB,GAAG,GAAG,CAAA;AAEpC,OAAO,OAAO,mBAAoB,SAAQ,YAAY,CAAC,yBAAyB,CAAC;IAC/E,SAAS,IAAI,MAAM;IACnB,iBAAiB,CACf,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC/C,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,GACxB,OAAO,CAAC,IAAI,CAAC;IAEhB,SAAS,CACP,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,G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ot":"","sources":["../../src/SuperwallExpoModule.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,mBAAmB,EAAE,MAAM,MAAM,CAAA;AAsDxD,eAAe,mBAAmB,CAAsB,eAAe,CAAC,CAAA","sourcesContent":["import { NativeModule, requireNativeModule } from \"expo\"\nimport type { SuperwallExpoModuleEvents } from \"./SuperwallExpoModule.types\"\n\nexport type SubscriptionStatus = any\n\ndeclare class SuperwallExpoModule extends NativeModule<SuperwallExpoModuleEvents> {\n getApiKey(): string\n registerPlacement(\n placement: string,\n params?: Map<string, any> | Record<string, any>,\n handlerId?: string | null,\n ): Promise<void>\n\n configure(\n apiKey: string,\n options?: Map<string, any> | Record<string, any>,\n usingPurchaseController?: boolean,\n sdkVersion?: string,\n ): Promise<void>\n\n getConfigurationStatus(): Promise<string>\n\n identify(userId: string, options?: Map<string, any> | Record<string, any> | null): void\n reset(): void\n\n getAssignments(): Promise<any[]>\n getEntitlements(): Promise<any>\n getSubscriptionStatus(): Promise<SubscriptionStatus>\n setSubscriptionStatus(status: Record<string, any>): void\n\n setInterfaceStyle(style?: string): void\n\n getUserAttributes(): Promise<Record<string, any>>\n setUserAttributes(userAttributes: Record<string, any>): void\n\n handleDeepLink(url: string): Promise<boolean>\n\n didPurchase(result: Record<string, any>): void\n didRestore(result: Record<string, any>): void\n\n dismiss(): Promise<void>\n confirmAllAssignments(): Promise<any[]>\n\n getPresentationResult(\n placement: string,\n params?: Map<string, any> | Record<string, any>,\n ): Promise<any>\n\n preloadPaywalls(placementNames: string[]): void\n preloadAllPaywalls(): void\n\n setLogLevel(level: string): void\n}\n\nexport default requireNativeModule<SuperwallExpoModule>(\"SuperwallExpo\")\n"]}
1
+ {"version":3,"file":"SuperwallExpoModule.js","sourceRoot":"","sources":["../../src/SuperwallExpoModule.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,mBAAmB,EAAE,MAAM,MAAM,CAAA;AAwDxD,eAAe,mBAAmB,CAAsB,eAAe,CAAC,CAAA","sourcesContent":["import { NativeModule, requireNativeModule } from \"expo\"\nimport type { SuperwallExpoModuleEvents } from \"./SuperwallExpoModule.types\"\n\nexport type SubscriptionStatus = any\n\ndeclare class SuperwallExpoModule extends NativeModule<SuperwallExpoModuleEvents> {\n getApiKey(): string\n registerPlacement(\n placement: string,\n params?: Map<string, any> | Record<string, any>,\n handlerId?: string | null,\n ): Promise<void>\n\n configure(\n apiKey: string,\n options?: Map<string, any> | Record<string, any>,\n usingPurchaseController?: boolean,\n sdkVersion?: string,\n ): Promise<void>\n\n getConfigurationStatus(): Promise<string>\n\n identify(userId: string, options?: Map<string, any> | Record<string, any> | null): void\n reset(): void\n\n getAssignments(): Promise<any[]>\n getEntitlements(): Promise<any>\n getSubscriptionStatus(): Promise<SubscriptionStatus>\n setSubscriptionStatus(status: Record<string, any>): void\n\n setInterfaceStyle(style?: string): void\n\n getUserAttributes(): Promise<Record<string, any>>\n setUserAttributes(userAttributes: Record<string, any>): void\n\n handleDeepLink(url: string): Promise<boolean>\n\n didPurchase(result: Record<string, any>): void\n didRestore(result: Record<string, any>): void\n\n dismiss(): Promise<void>\n confirmAllAssignments(): Promise<any[]>\n\n getPresentationResult(\n placement: string,\n params?: Map<string, any> | Record<string, any>,\n ): Promise<any>\n\n getDeviceAttributes(): Promise<Record<string, any>>\n\n preloadPaywalls(placementNames: string[]): void\n preloadAllPaywalls(): void\n\n setLogLevel(level: string): void\n}\n\nexport default requireNativeModule<SuperwallExpoModule>(\"SuperwallExpo\")\n"]}
@@ -123,6 +123,7 @@ export interface SuperwallStore {
123
123
  */
124
124
  _initListeners: () => () => void;
125
125
  setSubscriptionStatus: (status: SubscriptionStatus) => Promise<void>;
126
+ getDeviceAttributes: () => Promise<Record<string, any>>;
126
127
  }
127
128
  /**
128
129
  * Zustand store for Superwall SDK state and actions.
@@ -1 +1 @@
1
- {"version":3,"file":"useSuperwall.d.ts","sourceRoot":"","sources":["../../src/useSuperwall.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAA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CAAA;AAEH,eAAO,MAAM,gBAAgB,kCAAgC,CAAA;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,YAAY,CAAC,CAAC,GAAG,cAAc,EAAE,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,CAAC,GAAG,CAAC,CAS3F"}
@@ -71,6 +71,10 @@ export const useSuperwallStore = create((set, get) => ({
71
71
  setSubscriptionStatus: async (status) => {
72
72
  SuperwallExpoModule.setSubscriptionStatus(status);
73
73
  },
74
+ getDeviceAttributes: async () => {
75
+ const attributes = await SuperwallExpoModule.getDeviceAttributes();
76
+ return attributes;
77
+ },
74
78
  /* -------------------- Listener helpers -------------------- */
75
79
  _initListeners: () => {
76
80
  // Use get() to read the state from within the store
@@ -1 +1 @@
1
- {"version":3,"file":"useSuperwall.js","sourceRoot":"","sources":["../../src/useSuperwall.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,mBAAmB,MAAM,uBAAuB,CAAA;AAGvD,OAAO,GAAG,MAAM,iBAAiB,CAAA;AAyJjC;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;IACrE,qDAAqD;IACrD,YAAY,EAAE,KAAK;IACnB,SAAS,EAAE,KAAK;IAChB,oBAAoB,EAAE,KAAK;IAE3B,IAAI,EAAE,IAAI;IACV,kBAAkB,EAAE;QAClB,MAAM,EAAE,SAAS;KAClB;IAED,uDAAuD;IACvD,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE;QACnC,GAAG,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA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AI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;IAED,MAAM,QAAQ,GAAG,CAAC,KAAqB,EAAE,EAAE,CAAC,KAAqB,CAAA;IACjE,iEAAiE;IACjE,OAAO,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAA;AACtE,CAAC","sourcesContent":["import { createContext, useContext } from \"react\"\nimport { create } from \"zustand\"\nimport { useShallow } from \"zustand/shallow\"\nimport SuperwallExpoModule from \"./SuperwallExpoModule\"\nimport type { SubscriptionStatus } from \"./SuperwallExpoModule.types\"\n\nimport pkg from \"../package.json\"\n\n/**\n * Interface representing the attributes of a user.\n */\nexport interface UserAttributes {\n /** The user's alias ID, if set. */\n aliasId: string\n /** The user's application-specific user ID. */\n appUserId: string\n /** The ISO 8601 date string representation of when the application was installed on the user's device. */\n applicationInstalledAt: string\n /** A seed value associated with the user, used for consistent variant assignments in experiments. */\n seed: number\n /** Allows for custom attributes to be set for the user. These can be of any type. */\n [key: string]: any\n}\n\n/**\n * Options for the `identify` method.\n */\nexport interface IdentifyOptions {\n /**\n * Determines whether to restore paywall assignments from a previous session for the identified user.\n * If `true`, the SDK attempts to restore the assignments. Defaults to `false`.\n */\n restorePaywallAssignments?: boolean\n}\n\n/**\n * Defines the structure of the Superwall store, including its state and actions.\n * This store is managed by Zustand.\n */\nexport interface SuperwallStore {\n /* -------------------- State -------------------- */\n /** Indicates whether the Superwall SDK has been successfully configured. */\n isConfigured: boolean\n /** Indicates whether the SDK is currently performing a loading operation (e.g., configuring, fetching data). */\n isLoading: boolean\n /** Indicates whether the native event listeners have been initialized. */\n listenersInitialized: boolean\n\n /**\n * The current user's attributes.\n * `null` if no user is identified or after `reset` is called.\n * `undefined` initially before any user data is fetched or set.\n */\n user?: UserAttributes | null\n\n /** The current subscription status of the user. */\n subscriptionStatus: SubscriptionStatus\n\n /* -------------------- Internal -------------------- */\n // Internal listener references for cleanup handled inside Provider effect.\n // Not reactive, so we store outside Zustand state to avoid unnecessary rerenders.\n\n /* -------------------- Actions -------------------- */\n /**\n * Configures the Superwall SDK with the provided API key and options.\n * This must be called before most other SDK functions can be used.\n * @param apiKey - Your Superwall API key.\n * @param options - Optional configuration settings for the SDK.\n * @returns A promise that resolves when configuration is complete.\n */\n configure: (\n apiKey: string,\n options?: {\n manualPurchaseManagment?: boolean\n enableExperimentalDeviceVariables?: boolean\n } & Record<string, any>,\n ) => Promise<void>\n /**\n * Identifies the current user with a unique ID.\n * @param userId - The unique identifier for the user.\n * @param options - Optional parameters for identification.\n * @returns A promise that resolves when identification is complete.\n */\n identify: (userId: string, options?: IdentifyOptions) => Promise<void>\n /**\n * Resets the user's identity and clears all user-specific data, effectively logging them out.\n */\n reset: () => Promise<void>\n\n /**\n * Registers a placement to potentially show a paywall.\n * The decision to show a paywall is determined by campaign rules and user assignments on the Superwall dashboard.\n * @param placement - The ID of the placement to register.\n * @param params - Optional parameters to pass with the placement.\n * @param handlerId - An optional identifier used to associate specific event handlers (e.g., from `usePlacement`). Defaults to \"default\".\n * @returns A promise that resolves when the placement registration is complete.\n */\n registerPlacement: (\n placement: string,\n params?: Record<string, any>,\n handlerId?: string | null,\n ) => Promise<void>\n /**\n * Retrieves the presentation result for a given placement.\n * This can be used to understand what would happen if a placement were to be registered, without actually registering it.\n * @param placement - The ID of the placement.\n * @param params - Optional parameters for the placement.\n * @returns A promise that resolves with the presentation result.\n */\n getPresentationResult: (placement: string, params?: Record<string, any>) => Promise<any>\n /**\n * Dismisses any currently presented Superwall paywall.\n * @returns A promise that resolves when the dismissal is complete.\n */\n dismiss: () => Promise<void>\n\n /**\n * Preloads all paywalls configured in your Superwall dashboard.\n * @returns A promise that resolves when preloading is complete.\n */\n preloadAllPaywalls: () => Promise<void>\n /**\n * Preloads specific paywalls.\n * @param placements - An array of placement IDs for which to preload paywalls.\n * @returns A promise that resolves when preloading is complete.\n */\n preloadPaywalls: (placements: string[]) => Promise<void>\n\n /**\n * Sets custom attributes for the current user.\n * @param attrs - An object containing the attributes to set.\n * @returns A promise that resolves when attributes are set.\n */\n setUserAttributes: (attrs: Record<string, any>) => Promise<void>\n /**\n * Retrieves the current user's attributes.\n * @returns A promise that resolves with the user's attributes.\n */\n getUserAttributes: () => Promise<Record<string, any>>\n\n /**\n * Sets the logging level for the Superwall SDK.\n * @param level - The desired log level (e.g., \"debug\", \"info\", \"warn\", \"error\", \"none\").\n * @returns A promise that resolves when the log level is set.\n */\n setLogLevel: (level: string) => Promise<void>\n\n /* -------------------- Listener helpers -------------------- */\n /**\n * Initializes native event listeners for the SDK.\n * This is typically called internally by the `SuperwallProvider`.\n * @returns A cleanup function to remove the listeners.\n * @internal\n */\n _initListeners: () => () => void\n\n setSubscriptionStatus: (status: SubscriptionStatus) => Promise<void>\n}\n\n/**\n * Zustand store for Superwall SDK state and actions.\n * @internal\n */\nexport const useSuperwallStore = create<SuperwallStore>((set, get) => ({\n /* -------------------- State -------------------- */\n isConfigured: false,\n isLoading: false,\n listenersInitialized: false,\n\n user: null,\n subscriptionStatus: {\n status: \"UNKNOWN\",\n },\n\n /* -------------------- Actions -------------------- */\n configure: async (apiKey, options) => {\n set({ isLoading: true })\n const { manualPurchaseManagment, ...restOptions } = options || {}\n\n await SuperwallExpoModule.configure(\n apiKey,\n restOptions,\n !!options?.manualPurchaseManagment,\n pkg.version,\n )\n set({ isConfigured: true, isLoading: false })\n\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n const subscriptionStatus = await SuperwallExpoModule.getSubscriptionStatus()\n\n set({ user: currentUser, subscriptionStatus })\n },\n identify: async (userId, options) => {\n SuperwallExpoModule.identify(userId, options)\n\n // TODO: Instead of setting users after identify, we should set this based on an event\n setTimeout(async () => {\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n const subscriptionStatus = await SuperwallExpoModule.getSubscriptionStatus()\n set({ user: currentUser, subscriptionStatus })\n }, 0)\n },\n reset: async () => {\n SuperwallExpoModule.reset()\n\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n\n set({ user: currentUser })\n },\n registerPlacement: async (placement, params, handlerId = \"default\") => {\n await SuperwallExpoModule.registerPlacement(placement, params, handlerId)\n },\n getPresentationResult: async (placement, params) => {\n return SuperwallExpoModule.getPresentationResult(placement, params)\n },\n dismiss: async () => {\n await SuperwallExpoModule.dismiss()\n },\n preloadAllPaywalls: async () => {\n SuperwallExpoModule.preloadAllPaywalls()\n },\n preloadPaywalls: async (placements) => {\n SuperwallExpoModule.preloadPaywalls(placements)\n },\n setUserAttributes: async (attrs) => {\n SuperwallExpoModule.setUserAttributes(attrs)\n\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n set({ user: currentUser })\n },\n getUserAttributes: async () => {\n const attributes = await SuperwallExpoModule.getUserAttributes()\n set({ user: attributes as UserAttributes })\n return attributes\n },\n setLogLevel: async (level) => {\n SuperwallExpoModule.setLogLevel(level)\n },\n\n setSubscriptionStatus: async (status) => {\n SuperwallExpoModule.setSubscriptionStatus(status)\n },\n\n /* -------------------- Listener helpers -------------------- */\n _initListeners: (): (() => void) => {\n // Use get() to read the state from within the store\n if (get().listenersInitialized) {\n console.warn(\"Listeners already initialized. Skipping.\")\n return () => {} // Return no-op cleanup\n }\n\n const subscriptions: { remove: () => void }[] = []\n\n subscriptions.push(\n SuperwallExpoModule.addListener(\n \"subscriptionStatusDidChange\",\n ({ to }: { to: SubscriptionStatus }) => {\n set({ subscriptionStatus: to })\n },\n ),\n )\n\n set({ listenersInitialized: true })\n console.log(\"Initialized listeners\", subscriptions.length)\n\n return (): void => {\n console.log(\"Cleaning up listeners\", subscriptions.length)\n subscriptions.forEach((s) => s.remove())\n // Reset the state on cleanup\n set({ listenersInitialized: false })\n }\n },\n}))\n\nexport const SuperwallContext = createContext<boolean>(false)\n\n/**\n/**\n * Core React hook for interacting with the Superwall SDK.\n *\n * This hook provides access to the Superwall store, which includes SDK state\n * (like configuration status, user information, subscription status) and actions\n * (like `identify`, `reset`, `registerPlacement`).\n *\n * It must be used within a component that is a descendant of `<SuperwallProvider />`.\n *\n * @template T - Optional type parameter for the selected state. Defaults to the entire `SuperwallStore`.\n * @param selector - An optional function to select a specific slice of the store's state.\n * This is useful for performance optimization, as components will only re-render\n * if the selected part of the state changes. Uses shallow equality checking\n * via `zustand/shallow`. If omitted, the entire store is returned.\n * @returns The selected slice of the Superwall store state, or the entire store if no selector is provided.\n * @throws Error if used outside of a `SuperwallProvider`.\n *\n * @example\n * // Get the entire store\n * const superwall = useSuperwall();\n * console.log(superwall.isConfigured);\n * superwall.identify(\"user_123\");\n *\n * @example\n * // Select specific state properties\n * const { user, subscriptionStatus } = useSuperwall(state => ({\n * user: state.user,\n * subscriptionStatus: state.subscriptionStatus,\n * }));\n * console.log(user?.appUserId, subscriptionStatus?.status);\n */\nexport function useSuperwall<T = SuperwallStore>(selector?: (state: SuperwallStore) => T): T {\n const inProvider = useContext(SuperwallContext)\n if (!inProvider) {\n throw new Error(\"useSuperwall must be used within a SuperwallProvider\")\n }\n\n const identity = (state: SuperwallStore) => state as unknown as T\n // biome-ignore lint/correctness/useHookAtTopLevel: <explanation>\n return useSuperwallStore(selector ? useShallow(selector) : identity)\n}\n"]}
1
+ {"version":3,"file":"useSuperwall.js","sourceRoot":"","sources":["../../src/useSuperwall.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,mBAAmB,MAAM,uBAAuB,CAAA;AAGvD,OAAO,GAAG,MAAM,iBAAiB,CAAA;AA2JjC;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAiB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;IACrE,qD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C,CAAC,MAAM,EAAE,CAAC,CAAA;YACxC,6BAA6B;YAC7B,GAAG,CAAC,EAAE,oBAAoB,EAAE,KAAK,EAAE,CAAC,CAAA;QACtC,CAAC,CAAA;IACH,CAAC;CACF,CAAC,CAAC,CAAA;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAAU,KAAK,CAAC,CAAA;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,YAAY,CAAqB,QAAuC;IACtF,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,CAAC,CAAA;IAC/C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;IAED,MAAM,QAAQ,GAAG,CAAC,KAAqB,EAAE,EAAE,CAAC,KAAqB,CAAA;IACjE,iEAAiE;IACjE,OAAO,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAA;AACtE,CAAC","sourcesContent":["import { createContext, useContext } from \"react\"\nimport { create } from \"zustand\"\nimport { useShallow } from \"zustand/shallow\"\nimport SuperwallExpoModule from \"./SuperwallExpoModule\"\nimport type { SubscriptionStatus } from \"./SuperwallExpoModule.types\"\n\nimport pkg from \"../package.json\"\n\n/**\n * Interface representing the attributes of a user.\n */\nexport interface UserAttributes {\n /** The user's alias ID, if set. */\n aliasId: string\n /** The user's application-specific user ID. */\n appUserId: string\n /** The ISO 8601 date string representation of when the application was installed on the user's device. */\n applicationInstalledAt: string\n /** A seed value associated with the user, used for consistent variant assignments in experiments. */\n seed: number\n /** Allows for custom attributes to be set for the user. These can be of any type. */\n [key: string]: any\n}\n\n/**\n * Options for the `identify` method.\n */\nexport interface IdentifyOptions {\n /**\n * Determines whether to restore paywall assignments from a previous session for the identified user.\n * If `true`, the SDK attempts to restore the assignments. Defaults to `false`.\n */\n restorePaywallAssignments?: boolean\n}\n\n/**\n * Defines the structure of the Superwall store, including its state and actions.\n * This store is managed by Zustand.\n */\nexport interface SuperwallStore {\n /* -------------------- State -------------------- */\n /** Indicates whether the Superwall SDK has been successfully configured. */\n isConfigured: boolean\n /** Indicates whether the SDK is currently performing a loading operation (e.g., configuring, fetching data). */\n isLoading: boolean\n /** Indicates whether the native event listeners have been initialized. */\n listenersInitialized: boolean\n\n /**\n * The current user's attributes.\n * `null` if no user is identified or after `reset` is called.\n * `undefined` initially before any user data is fetched or set.\n */\n user?: UserAttributes | null\n\n /** The current subscription status of the user. */\n subscriptionStatus: SubscriptionStatus\n\n /* -------------------- Internal -------------------- */\n // Internal listener references for cleanup handled inside Provider effect.\n // Not reactive, so we store outside Zustand state to avoid unnecessary rerenders.\n\n /* -------------------- Actions -------------------- */\n /**\n * Configures the Superwall SDK with the provided API key and options.\n * This must be called before most other SDK functions can be used.\n * @param apiKey - Your Superwall API key.\n * @param options - Optional configuration settings for the SDK.\n * @returns A promise that resolves when configuration is complete.\n */\n configure: (\n apiKey: string,\n options?: {\n manualPurchaseManagment?: boolean\n enableExperimentalDeviceVariables?: boolean\n } & Record<string, any>,\n ) => Promise<void>\n /**\n * Identifies the current user with a unique ID.\n * @param userId - The unique identifier for the user.\n * @param options - Optional parameters for identification.\n * @returns A promise that resolves when identification is complete.\n */\n identify: (userId: string, options?: IdentifyOptions) => Promise<void>\n /**\n * Resets the user's identity and clears all user-specific data, effectively logging them out.\n */\n reset: () => Promise<void>\n\n /**\n * Registers a placement to potentially show a paywall.\n * The decision to show a paywall is determined by campaign rules and user assignments on the Superwall dashboard.\n * @param placement - The ID of the placement to register.\n * @param params - Optional parameters to pass with the placement.\n * @param handlerId - An optional identifier used to associate specific event handlers (e.g., from `usePlacement`). Defaults to \"default\".\n * @returns A promise that resolves when the placement registration is complete.\n */\n registerPlacement: (\n placement: string,\n params?: Record<string, any>,\n handlerId?: string | null,\n ) => Promise<void>\n /**\n * Retrieves the presentation result for a given placement.\n * This can be used to understand what would happen if a placement were to be registered, without actually registering it.\n * @param placement - The ID of the placement.\n * @param params - Optional parameters for the placement.\n * @returns A promise that resolves with the presentation result.\n */\n getPresentationResult: (placement: string, params?: Record<string, any>) => Promise<any>\n /**\n * Dismisses any currently presented Superwall paywall.\n * @returns A promise that resolves when the dismissal is complete.\n */\n dismiss: () => Promise<void>\n\n /**\n * Preloads all paywalls configured in your Superwall dashboard.\n * @returns A promise that resolves when preloading is complete.\n */\n preloadAllPaywalls: () => Promise<void>\n /**\n * Preloads specific paywalls.\n * @param placements - An array of placement IDs for which to preload paywalls.\n * @returns A promise that resolves when preloading is complete.\n */\n preloadPaywalls: (placements: string[]) => Promise<void>\n\n /**\n * Sets custom attributes for the current user.\n * @param attrs - An object containing the attributes to set.\n * @returns A promise that resolves when attributes are set.\n */\n setUserAttributes: (attrs: Record<string, any>) => Promise<void>\n /**\n * Retrieves the current user's attributes.\n * @returns A promise that resolves with the user's attributes.\n */\n getUserAttributes: () => Promise<Record<string, any>>\n\n /**\n * Sets the logging level for the Superwall SDK.\n * @param level - The desired log level (e.g., \"debug\", \"info\", \"warn\", \"error\", \"none\").\n * @returns A promise that resolves when the log level is set.\n */\n setLogLevel: (level: string) => Promise<void>\n\n /* -------------------- Listener helpers -------------------- */\n /**\n * Initializes native event listeners for the SDK.\n * This is typically called internally by the `SuperwallProvider`.\n * @returns A cleanup function to remove the listeners.\n * @internal\n */\n _initListeners: () => () => void\n\n setSubscriptionStatus: (status: SubscriptionStatus) => Promise<void>\n\n getDeviceAttributes: () => Promise<Record<string, any>>\n}\n\n/**\n * Zustand store for Superwall SDK state and actions.\n * @internal\n */\nexport const useSuperwallStore = create<SuperwallStore>((set, get) => ({\n /* -------------------- State -------------------- */\n isConfigured: false,\n isLoading: false,\n listenersInitialized: false,\n\n user: null,\n subscriptionStatus: {\n status: \"UNKNOWN\",\n },\n\n /* -------------------- Actions -------------------- */\n configure: async (apiKey, options) => {\n set({ isLoading: true })\n const { manualPurchaseManagment, ...restOptions } = options || {}\n\n await SuperwallExpoModule.configure(\n apiKey,\n restOptions,\n !!options?.manualPurchaseManagment,\n pkg.version,\n )\n set({ isConfigured: true, isLoading: false })\n\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n const subscriptionStatus = await SuperwallExpoModule.getSubscriptionStatus()\n\n set({ user: currentUser, subscriptionStatus })\n },\n identify: async (userId, options) => {\n SuperwallExpoModule.identify(userId, options)\n\n // TODO: Instead of setting users after identify, we should set this based on an event\n setTimeout(async () => {\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n const subscriptionStatus = await SuperwallExpoModule.getSubscriptionStatus()\n set({ user: currentUser, subscriptionStatus })\n }, 0)\n },\n reset: async () => {\n SuperwallExpoModule.reset()\n\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n\n set({ user: currentUser })\n },\n registerPlacement: async (placement, params, handlerId = \"default\") => {\n await SuperwallExpoModule.registerPlacement(placement, params, handlerId)\n },\n getPresentationResult: async (placement, params) => {\n return SuperwallExpoModule.getPresentationResult(placement, params)\n },\n dismiss: async () => {\n await SuperwallExpoModule.dismiss()\n },\n preloadAllPaywalls: async () => {\n SuperwallExpoModule.preloadAllPaywalls()\n },\n preloadPaywalls: async (placements) => {\n SuperwallExpoModule.preloadPaywalls(placements)\n },\n setUserAttributes: async (attrs) => {\n SuperwallExpoModule.setUserAttributes(attrs)\n\n const currentUser = (await SuperwallExpoModule.getUserAttributes()) as UserAttributes\n set({ user: currentUser })\n },\n getUserAttributes: async () => {\n const attributes = await SuperwallExpoModule.getUserAttributes()\n set({ user: attributes as UserAttributes })\n return attributes\n },\n setLogLevel: async (level) => {\n SuperwallExpoModule.setLogLevel(level)\n },\n\n setSubscriptionStatus: async (status) => {\n SuperwallExpoModule.setSubscriptionStatus(status)\n },\n getDeviceAttributes: async () => {\n const attributes = await SuperwallExpoModule.getDeviceAttributes()\n return attributes\n },\n\n /* -------------------- Listener helpers -------------------- */\n _initListeners: (): (() => void) => {\n // Use get() to read the state from within the store\n if (get().listenersInitialized) {\n console.warn(\"Listeners already initialized. Skipping.\")\n return () => {} // Return no-op cleanup\n }\n\n const subscriptions: { remove: () => void }[] = []\n\n subscriptions.push(\n SuperwallExpoModule.addListener(\n \"subscriptionStatusDidChange\",\n ({ to }: { to: SubscriptionStatus }) => {\n set({ subscriptionStatus: to })\n },\n ),\n )\n\n set({ listenersInitialized: true })\n console.log(\"Initialized listeners\", subscriptions.length)\n\n return (): void => {\n console.log(\"Cleaning up listeners\", subscriptions.length)\n subscriptions.forEach((s) => s.remove())\n // Reset the state on cleanup\n set({ listenersInitialized: false })\n }\n },\n}))\n\nexport const SuperwallContext = createContext<boolean>(false)\n\n/**\n/**\n * Core React hook for interacting with the Superwall SDK.\n *\n * This hook provides access to the Superwall store, which includes SDK state\n * (like configuration status, user information, subscription status) and actions\n * (like `identify`, `reset`, `registerPlacement`).\n *\n * It must be used within a component that is a descendant of `<SuperwallProvider />`.\n *\n * @template T - Optional type parameter for the selected state. Defaults to the entire `SuperwallStore`.\n * @param selector - An optional function to select a specific slice of the store's state.\n * This is useful for performance optimization, as components will only re-render\n * if the selected part of the state changes. Uses shallow equality checking\n * via `zustand/shallow`. If omitted, the entire store is returned.\n * @returns The selected slice of the Superwall store state, or the entire store if no selector is provided.\n * @throws Error if used outside of a `SuperwallProvider`.\n *\n * @example\n * // Get the entire store\n * const superwall = useSuperwall();\n * console.log(superwall.isConfigured);\n * superwall.identify(\"user_123\");\n *\n * @example\n * // Select specific state properties\n * const { user, subscriptionStatus } = useSuperwall(state => ({\n * user: state.user,\n * subscriptionStatus: state.subscriptionStatus,\n * }));\n * console.log(user?.appUserId, subscriptionStatus?.status);\n */\nexport function useSuperwall<T = SuperwallStore>(selector?: (state: SuperwallStore) => T): T {\n const inProvider = useContext(SuperwallContext)\n if (!inProvider) {\n throw new Error(\"useSuperwall must be used within a SuperwallProvider\")\n }\n\n const identity = (state: SuperwallStore) => state as unknown as T\n // biome-ignore lint/correctness/useHookAtTopLevel: <explanation>\n return useSuperwallStore(selector ? useShallow(selector) : identity)\n}\n"]}
@@ -117,7 +117,7 @@ extension SuperwallEvent {
117
117
  case .paywallWebviewLoadStart(let paywallInfo):
118
118
  return ["event": "paywallWebviewLoadStart", "paywallInfo": paywallInfo.toJson()]
119
119
  case .paywallWebviewLoadFail(let paywallInfo):
120
- return ["event": "paywallWebviewLoadFail", "paywallInfotoJson": paywallInfo.toJson()]
120
+ return ["event": "paywallWebviewLoadFail", "paywallInfo": paywallInfo.toJson()]
121
121
  case .paywallWebviewLoadComplete(let paywallInfo):
122
122
  return ["event": "paywallWebviewLoadComplete", "paywallInfo": paywallInfo.toJson()]
123
123
  case .paywallWebviewLoadTimeout(let paywallInfo):
@@ -212,7 +212,7 @@ extension SuperwallEvent {
212
212
  return json
213
213
  case .enrichmentFail:
214
214
  return ["event": "enrichmentFail"]
215
- @unknown default:
215
+ default:
216
216
  return ["event": "unknown"]
217
217
  }
218
218
 
@@ -110,12 +110,8 @@ public class SuperwallExpoModule: Module {
110
110
  }
111
111
 
112
112
  AsyncFunction("getConfigurationStatus") { (promise: Promise) in
113
- do {
114
- let configurationStatus = try Superwall.shared.configurationStatus.toString()
115
- promise.resolve(configurationStatus)
116
- } catch {
117
- promise.reject(error)
118
- }
113
+ let configurationStatus = Superwall.shared.configurationStatus.toString()
114
+ promise.resolve(configurationStatus)
119
115
  }
120
116
 
121
117
  AsyncFunction("registerPlacement") {
@@ -250,6 +246,10 @@ public class SuperwallExpoModule: Module {
250
246
  promise.resolve(attributes)
251
247
  }
252
248
 
249
+ AsyncFunction("getDeviceAttributes") {
250
+ return await Superwall.shared.getDeviceAttributes()
251
+ }
252
+
253
253
  Function("setUserAttributes") { (userAttributes: [String: Any]) in
254
254
  Superwall.shared.setUserAttributes(userAttributes)
255
255
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-superwall",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "Offical Expo Integration for Superwall",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",