@cloudparse/up-miniapps-sdk 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@ The official SDK for building Mini-Apps within the UP Shell environment. This SD
5
5
  ## 🚀 Installation
6
6
 
7
7
  ```bash
8
- npm install up-miniapps-sdk
8
+ npm i @cloudparse/up-miniapps-sdk
9
9
  ```
10
10
 
11
11
  ## 📖 Usage
@@ -37,6 +37,10 @@ Local SQLite Storage and Hardware-level Secure Storage (Keychain/Keystore). Data
37
37
  - `sdk.secureStore.get(key: string): Promise<string | null>` - Retrieves a value from the device's secure enclave.
38
38
  - `sdk.secureStore.set(key: string, value: string): Promise<void>` - Stores hardware-encrypted data.
39
39
 
40
+ #### Database Storage (`sdk.database`)
41
+ - `sdk.database.getUserData<T = unknown>(): Promise<T>` - Retrieves user-app specific data from the backend database.
42
+ - `sdk.database.setUserData<T = unknown>(data: T): Promise<void>` - Updates user-app specific data in the backend database.
43
+
40
44
  </details>
41
45
 
42
46
  <details>
@@ -109,37 +113,11 @@ Integration with the Fidelity program.
109
113
  <summary><b>🚪 UI & Navigation</b></summary>
110
114
 
111
115
  - `sdk.ui.exit(): Promise<void>` - Closes the Mini-App and returns to the host shell.
112
- - `sdk.ui.setScrollConfig(config: ScrollConfig): Promise<void>` - Configure native Pull-to-Refresh and Infinite Scroll.
113
116
 
114
117
  </details>
115
118
 
116
119
  ---
117
120
 
118
- ## 💡 Examples
119
-
120
- ### Pull-to-Refresh
121
-
122
- ```typescript
123
- import sdk, { UIEvent } from 'up-miniapps-sdk';
124
-
125
- // 1. Enable native pull-to-refresh
126
- sdk.ui.setScrollConfig({
127
- topScrollMore: { enabled: true }
128
- });
129
-
130
- // 2. Listen for the event
131
- sdk.on(UIEvent.TOP_SCROLL_MORE, async () => {
132
- await fetchData();
133
-
134
- // 3. Stop the native spinner
135
- sdk.ui.setScrollConfig({
136
- topScrollMore: { enabled: true, refreshing: false }
137
- });
138
- });
139
- ```
140
-
141
- ---
142
-
143
121
  ## 🔔 Event Listeners
144
122
 
145
123
  Register for events emitted by the native host shell.
@@ -1,2 +1,2 @@
1
- "use strict";var MiniAppSDK=(()=>{var l=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var f=(n,e)=>{for(var i in e)l(n,i,{get:e[i],enumerable:!0})},y=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of b(e))!m.call(n,r)&&r!==i&&l(n,r,{get:()=>e[r],enumerable:!(t=p(e,r))||t.enumerable});return n};var I=n=>y(l({},"__esModule",{value:!0}),n);var h={};f(h,{MiniAppSDK:()=>s,UIEvent:()=>g,default:()=>T,sdk:()=>a});var o=class{callbacks={};eventListeners={};constructor(){typeof window<"u"&&(window.__MiniAppBridge={onNativeMessage:e=>this.handleNativeMessage(e)},window.addEventListener("message",e=>{try{let i=typeof e.data=="string"?JSON.parse(e.data):e.data;this.handleNativeMessage(i)}catch{}}))}handleNativeMessage(e){if(!(!e||typeof e!="object")){if(e.callbackId&&typeof e.callbackId=="string"&&this.callbacks[e.callbackId]){let{callbackId:i}=e,{resolve:t,reject:r}=this.callbacks[i];e.success===!1||e.error?r(e.error||"Unknown error"):t(e.value!==void 0?e.value:e.payload||e),delete this.callbacks[i];return}if(e.event&&typeof e.event=="string"){let i=this.eventListeners[e.event];if(i)for(let t of i)try{t(e.payload||e.value)}catch(r){console.error(`Error in event listener for ${e.event}:`,r)}}}}on(e,i){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(i),()=>this.off(e,i)}off(e,i){this.eventListeners[e]&&(this.eventListeners[e]=this.eventListeners[e].filter(t=>t!==i))}send(e,i){return new Promise((t,r)=>{let d=`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;this.callbacks[d]={reject:r,resolve:t};let u={callbackId:d,payload:i,type:e},c=window;c.ReactNativeWebView?.postMessage?c.ReactNativeWebView.postMessage(JSON.stringify(u)):(console.warn("UP Bridge not available. Are you running inside the UP Shell?"),delete this.callbacks[d],r(new Error("Bridge not available")))})}};var s=class{bridge;constructor(){this.bridge=new o}initialize(e){return this.bridge.send("INITIALIZE",e)}storage={get:e=>this.bridge.send("STORAGE_GET",{key:e}),getAll:()=>this.bridge.send("STORAGE_GET_ALL"),set:(e,i)=>this.bridge.send("STORAGE_SET",{key:e,value:i})};secureStore={get:e=>this.bridge.send("SECURE_GET",{key:e}),set:(e,i)=>this.bridge.send("SECURE_SET",{key:e,value:i})};location={getCurrentPosition:()=>this.bridge.send("GET_LOCATION")};user={getIdentityToken:e=>this.bridge.send("GET_IDENTITY_TOKEN",{scopes:e}),getProfile:e=>this.bridge.send("GET_USER_PROFILE",{fields:e})};permission={request:((e,i)=>this.bridge.send("REQUEST_PERMISSION",{fields:i,type:e}))};payment={request:e=>this.bridge.send("PAYMENT_REQUEST",e)};activity={start:(e,i,t)=>this.bridge.send("START_ACTIVITY",{id:e,status:t,title:i})};haptic={trigger:e=>this.bridge.send("TRIGGER_HAPTIC",{style:e})};network={request:e=>this.bridge.send("NETWORK_REQUEST",e)};fidelity={getFidelityBalance:()=>this.bridge.send("GET_FIDELITY_BALANCE"),getFidelityHistory:e=>this.bridge.send("GET_FIDELITY_HISTORY",e),spendFPoints:e=>this.bridge.send("SPEND_FPOINTS",{intentUuid:e})};ui={exit:()=>this.bridge.send("EXIT"),setScrollConfig:e=>this.bridge.send("SET_SCROLL_CONFIG",e)};debug={log:(...e)=>this.bridge.send("DEBUG_LOG",{message:e})};on(e,i){return this.bridge.on(e,i)}off(e,i){this.bridge.off(e,i)}},a=new s;var g=(i=>(i.TOP_SCROLL_MORE="TOP_SCROLL_MORE",i.BOTTOM_SCROLL_MORE="BOTTOM_SCROLL_MORE",i))(g||{});var T=a;return I(h);})();
1
+ "use strict";var MiniAppSDK=(()=>{var l=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var T=(n,e)=>{for(var i in e)l(n,i,{get:e[i],enumerable:!0})},y=(n,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of b(e))!m.call(n,r)&&r!==i&&l(n,r,{get:()=>e[r],enumerable:!(t=p(e,r))||t.enumerable});return n};var I=n=>y(l({},"__esModule",{value:!0}),n);var E={};T(E,{MiniAppSDK:()=>s,UIEvent:()=>g,default:()=>f,sdk:()=>a});var o=class{callbacks={};eventListeners={};constructor(){typeof window<"u"&&(window.__MiniAppBridge={onNativeMessage:e=>this.handleNativeMessage(e)},window.addEventListener("message",e=>{try{let i=typeof e.data=="string"?JSON.parse(e.data):e.data;this.handleNativeMessage(i)}catch{}}))}handleNativeMessage(e){if(!(!e||typeof e!="object")){if(e.callbackId&&typeof e.callbackId=="string"&&this.callbacks[e.callbackId]){let{callbackId:i}=e,{resolve:t,reject:r}=this.callbacks[i];e.success===!1||e.error?r(e.error||"Unknown error"):t(e.value??e.payload??e),delete this.callbacks[i];return}if(e.event&&typeof e.event=="string"){let i=this.eventListeners[e.event];if(i)for(let t of i)try{t(e.payload||e.value)}catch(r){console.error(`Error in event listener for ${e.event}:`,r)}}}}on(e,i){return this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(i),()=>this.off(e,i)}off(e,i){this.eventListeners[e]&&(this.eventListeners[e]=this.eventListeners[e].filter(t=>t!==i))}send(e,i){return new Promise((t,r)=>{let d=`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;this.callbacks[d]={reject:r,resolve:t};let u={callbackId:d,payload:i,type:e},c=window;c.ReactNativeWebView?.postMessage?c.ReactNativeWebView.postMessage(JSON.stringify(u)):(console.warn("UP Bridge not available. Are you running inside the UP Shell?"),delete this.callbacks[d],r(new Error("Bridge not available")))})}};var s=class{bridge;constructor(){this.bridge=new o}initialize(e){return this.bridge.send("INITIALIZE",e)}storage={get:e=>this.bridge.send("STORAGE_GET",{key:e}),getAll:()=>this.bridge.send("STORAGE_GET_ALL"),set:(e,i)=>this.bridge.send("STORAGE_SET",{key:e,value:i})};secureStore={get:e=>this.bridge.send("SECURE_GET",{key:e}),set:(e,i)=>this.bridge.send("SECURE_SET",{key:e,value:i})};database={getUserData:()=>this.bridge.send("DATABASE_GET_USER_DATA"),setUserData:e=>this.bridge.send("DATABASE_SET_USER_DATA",{data:e})};location={getCurrentPosition:()=>this.bridge.send("GET_LOCATION")};user={getIdentityToken:e=>this.bridge.send("GET_IDENTITY_TOKEN",{scopes:e}),getProfile:e=>this.bridge.send("GET_USER_PROFILE",{fields:e})};permission={request:((e,i)=>this.bridge.send("REQUEST_PERMISSION",{fields:i,type:e}))};payment={request:e=>this.bridge.send("PAYMENT_REQUEST",e)};activity={start:(e,i,t)=>this.bridge.send("START_ACTIVITY",{id:e,status:t,title:i})};haptic={trigger:e=>this.bridge.send("TRIGGER_HAPTIC",{style:e})};network={request:e=>this.bridge.send("NETWORK_REQUEST",e)};fidelity={getFidelityBalance:()=>this.bridge.send("GET_FIDELITY_BALANCE"),getFidelityHistory:e=>this.bridge.send("GET_FIDELITY_HISTORY",e),spendFPoints:e=>this.bridge.send("SPEND_FPOINTS",{intentUuid:e})};ui={exit:()=>this.bridge.send("EXIT"),setScrollConfig:e=>this.bridge.send("SET_SCROLL_CONFIG",e)};debug={log:(...e)=>this.bridge.send("DEBUG_LOG",{message:e})};on(e,i){return this.bridge.on(e,i)}off(e,i){this.bridge.off(e,i)}},a=new s;var g=(i=>(i.TOP_SCROLL_MORE="TOP_SCROLL_MORE",i.BOTTOM_SCROLL_MORE="BOTTOM_SCROLL_MORE",i))(g||{});var f=a;return I(E);})();
2
2
  //# sourceMappingURL=index.browser.min.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/bridge.ts","../src/sdk.ts","../src/types/types.ts"],"sourcesContent":["export { MiniAppSDK, sdk } from \"@miniapps-sdk/sdk\";\nexport * from \"@miniapps-sdk/types\";\n\nimport { sdk } from \"@miniapps-sdk/sdk\";\nexport default sdk;\n","import type { IBridgeEnvelope } from \"@miniapps-sdk/types\";\n\n/**\n * The Bridge handles low-level communication between the Mini-App WebView\n * and the Native Host Shell (iOS/Android).\n *\n * It manages asynchronous request-response cycles via callbacks and\n * supports subscription to pushed events from the native environment.\n */\nexport class Bridge {\n private callbacks: Record<\n string,\n { resolve: (val: unknown) => void; reject: (err: unknown) => void }\n > = {};\n private eventListeners: Record<string, ((data: unknown) => void)[]> = {};\n\n /**\n * Registers a global listener for messages coming from the native shell.\n * Also listens for standard browser `message` events to support multiple\n * communication channels (e.g., React Native WebView postMessage).\n */\n constructor() {\n if (typeof window !== \"undefined\") {\n // Set up the global bridge receiver for React Native WebView\n (window as unknown as { __MiniAppBridge: unknown }).__MiniAppBridge = {\n onNativeMessage: (envelope: IBridgeEnvelope) =>\n this.handleNativeMessage(envelope),\n };\n\n // Also listen for postMessage events\n window.addEventListener(\"message\", (event) => {\n try {\n const data =\n typeof event.data === \"string\"\n ? JSON.parse(event.data)\n : event.data;\n this.handleNativeMessage(data);\n } catch (_e) {\n // Ignore non-JSON messages\n }\n });\n }\n }\n\n /**\n * Internal handler for all incoming messages from the native shell.\n * Matches incoming payloads to either pending callbacks or event listeners.\n *\n * @internal\n * @param envelope The message envelope received from native code.\n */\n private handleNativeMessage(envelope: IBridgeEnvelope) {\n if (!envelope || typeof envelope !== \"object\") return;\n\n // 1. Handle Response Callbacks\n if (\n envelope.callbackId &&\n typeof envelope.callbackId === \"string\" &&\n this.callbacks[envelope.callbackId]\n ) {\n const { callbackId } = envelope;\n const { resolve, reject } = this.callbacks[callbackId];\n\n if (envelope.success === false || envelope.error) {\n reject(envelope.error || \"Unknown error\");\n } else {\n resolve(\n envelope.value !== undefined\n ? envelope.value\n : envelope.payload || envelope,\n );\n }\n\n delete this.callbacks[callbackId];\n return;\n }\n\n // 2. Handle Pushed Events\n if (envelope.event && typeof envelope.event === \"string\") {\n const listeners = this.eventListeners[envelope.event];\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(envelope.payload || envelope.value);\n } catch (e) {\n console.error(`Error in event listener for ${envelope.event}:`, e);\n }\n }\n }\n }\n }\n\n /**\n * Subscribes to a pushed event from the native shell.\n *\n * @param event The event name to listen for.\n * @param callback Function to execute when the event occurs.\n * @returns An unsubscription function.\n */\n public on(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) {\n this.eventListeners[event] = [];\n }\n this.eventListeners[event].push(callback);\n return () => this.off(event, callback);\n }\n\n /**\n * Unsubscribes a specific callback from an event.\n *\n * @param event The event name.\n * @param callback The callback function to remove.\n */\n public off(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) return;\n this.eventListeners[event] = this.eventListeners[event].filter(\n (cb) => cb !== callback,\n );\n }\n\n /**\n * Sends a message to the native shell and waits for a response.\n *\n * @template T The expected response type.\n * @param type The action type (e.g., \"GET_LOCATION\").\n * @param payload Data associated with the action.\n * @returns A promise that resolves with the native response.\n */\n public send<T = unknown>(type: string, payload?: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const callbackId = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.callbacks[callbackId] = {\n reject,\n resolve: resolve as (val: unknown) => void,\n };\n\n const message = {\n callbackId,\n payload,\n type,\n };\n\n const win = window as unknown as {\n ReactNativeWebView?: { postMessage: (msg: string) => void };\n };\n\n if (win.ReactNativeWebView?.postMessage) {\n win.ReactNativeWebView.postMessage(JSON.stringify(message));\n } else {\n console.warn(\n \"UP Bridge not available. Are you running inside the UP Shell?\",\n );\n delete this.callbacks[callbackId];\n reject(new Error(\"Bridge not available\"));\n }\n });\n }\n}\n","import { Bridge } from \"@miniapps-sdk/bridge\";\nimport type {\n HapticStyleType,\n IFidelityBalance,\n IFidelityHistoryParams,\n IFidelityTransaction,\n IInitializationOptions,\n IInitializationResponse,\n ILocationData,\n INetworkOptions,\n INetworkResponse,\n IPaymentRequest,\n IUserProfile,\n ScrollConfig,\n SDKEvent,\n} from \"@miniapps-sdk/types/types\";\n\n/**\n * Main SDK for UP Mini-Apps.\n * Provides access to native device features, storage, identity, and shell UI.\n */\nexport class MiniAppSDK {\n private bridge: Bridge;\n\n constructor() {\n this.bridge = new Bridge();\n }\n\n /**\n * The starting point for the Mini-App. Must be called before any other SDK methods.\n * @param options The options to provide to the shell app\n */\n public initialize(\n options: IInitializationOptions,\n ): Promise<IInitializationResponse> {\n return this.bridge.send(\"INITIALIZE\", options);\n }\n\n /**\n * Local SQLite Storage.\n * Data is persisted on the device and is isolated per Mini-App.\n */\n public storage = {\n /** Retrieves a value by key. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"STORAGE_GET\", { key }),\n /** Retrieves all key-value pairs stored for this Mini-App. */\n getAll: (): Promise<Record<string, string>> =>\n this.bridge.send(\"STORAGE_GET_ALL\"),\n /** Sets a value for a specific key. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"STORAGE_SET\", { key, value }),\n };\n\n /**\n * Hardware-level Secure Storage.\n * Data is stored in the device's secure enclave (Keychain/Keystore) and is isolated per Mini-App.\n */\n public secureStore = {\n /** Retrieves a value by key from secure storage. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"SECURE_GET\", { key }),\n /** Sets a value for a specific key in secure storage. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"SECURE_SET\", { key, value }),\n };\n\n /**\n * Device Location services.\n */\n public location = {\n /** Retrieves the current GPS position of the device. */\n getCurrentPosition: (): Promise<ILocationData> =>\n this.bridge.send(\"GET_LOCATION\"),\n };\n\n /**\n * Identity & Profile management.\n */\n public user = {\n /**\n * Fetch a short-lived Scoped Identity Token (JWT).\n * This token is signed by the UP Hub and can be verified by your backend.\n * @param scopes Optional list of scopes requested (e.g., ['profile', 'email']).\n */\n getIdentityToken: (scopes?: string[]): Promise<string> =>\n this.bridge.send(\"GET_IDENTITY_TOKEN\", { scopes }),\n /**\n * Fetch user profile data.\n * @param fields Optional list of specific fields to retrieve (e.g., ['fullName', 'username']).\n */\n getProfile: <T extends keyof IUserProfile>(\n fields?: T[],\n ): Promise<Partial<IUserProfile>> =>\n this.bridge.send(\"GET_USER_PROFILE\", { fields }),\n };\n\n /**\n * Explicit Permission Management.\n * Allows requesting access to sensitive device features or user data.\n */\n public permission = {\n /**\n * Explicitly request access to sensitive data.\n * @param type The type of permission to request ('location' or 'profile').\n * @param fields If requesting 'profile', the specific fields required.\n */\n request: ((type: \"location\" | \"profile\", fields?: string[]) => {\n return this.bridge.send(\"REQUEST_PERMISSION\", { fields, type });\n }) as {\n (type: \"location\"): Promise<boolean>;\n (type: \"profile\", fields: (keyof IUserProfile)[]): Promise<boolean>;\n },\n };\n\n /**\n * Payments integration.\n */\n public payment = {\n /**\n * Triggers the native payment flow.\n * @param payload Amount, currency, and itemized list for the payment.\n */\n request: (\n payload: IPaymentRequest,\n ): Promise<{ success: true; transactionId: string }> =>\n this.bridge.send(\"PAYMENT_REQUEST\", payload),\n };\n\n /**\n * Live Activities & Notifications.\n * Allows the Mini-App to display real-time updates in the host shell.\n */\n public activity = {\n /**\n * Starts a new live activity.\n * @param id Unique identifier for the activity.\n * @param title Display title for the activity.\n * @param status Initial status message.\n */\n start: (id: string, title: string, status: string): Promise<void> =>\n this.bridge.send(\"START_ACTIVITY\", { id, status, title }),\n };\n\n /**\n * Haptic feedback.\n */\n public haptic = {\n /**\n * Triggers a haptic vibration on the device.\n * @param style The style of haptic feedback (e.g., 'light', 'medium', 'heavy', 'success', 'warning', 'error').\n */\n trigger: (style: HapticStyleType): Promise<void> =>\n this.bridge.send(\"TRIGGER_HAPTIC\", { style }),\n };\n\n /**\n * Network Proxy.\n * Allows the Mini-App to make network requests through the host shell to bypass CORS or use host-level authentication.\n */\n public network = {\n /**\n * Performs a network request via the host shell.\n * @param options Request method, URL, headers, and body.\n */\n request: (options: INetworkOptions): Promise<INetworkResponse> =>\n this.bridge.send(\"NETWORK_REQUEST\", options),\n };\n\n /**\n * Fidelity & Rewards program integration.\n */\n public fidelity = {\n /** Returns current fidelity balance. */\n getFidelityBalance: (): Promise<IFidelityBalance> =>\n this.bridge.send(\"GET_FIDELITY_BALANCE\"),\n /**\n * Retrieves fidelity transaction history.\n * @param params Filtering and pagination parameters.\n */\n getFidelityHistory: (\n params?: IFidelityHistoryParams,\n ): Promise<IFidelityTransaction[]> =>\n this.bridge.send(\"GET_FIDELITY_HISTORY\", params),\n /**\n * Authorize spending fidelity points (FPoints) via Two-Phase Authorization.\n * @param intentUuid UUID generated by your backend for the transaction.\n */\n spendFPoints: (\n intentUuid: string,\n ): Promise<{ success: boolean; transactionId: string }> =>\n this.bridge.send(\"SPEND_FPOINTS\", { intentUuid }),\n };\n\n /**\n * UI and Navigation controls.\n */\n public ui = {\n /** Closes the Mini-App and returns to the host shell. */\n exit: (): Promise<void> => this.bridge.send(\"EXIT\"),\n /**\n * Configures native scroll behaviors like Pull-to-Refresh and Infinite Scroll.\n * @param config Scroll configuration for top/bottom detection.\n */\n setScrollConfig: (config: ScrollConfig): Promise<void> =>\n this.bridge.send(\"SET_SCROLL_CONFIG\", config),\n };\n\n /**\n * Debug controls\n */\n public debug = {\n /**\n * Log to the shell app\n * @param message\n */\n log: (...message: unknown[]) => this.bridge.send(\"DEBUG_LOG\", { message }),\n };\n\n /**\n * Registers a callback for a specific event from the native shell.\n * @param event The name of the event to listen for.\n * @param callback The function to execute when the event is triggered.\n * @returns A function to unregister the listener.\n */\n public on(event: SDKEvent, callback: (data: unknown) => void) {\n return this.bridge.on(event as string, callback);\n }\n\n /**\n * Unregisters a previously registered event listener.\n * @param event The name of the event.\n * @param callback The callback function to remove.\n */\n public off(event: SDKEvent, callback: (data: unknown) => void) {\n this.bridge.off(event as string, callback);\n }\n}\n\n/**\n * Singleton instance of the MiniAppSDK.\n */\nexport const sdk = new MiniAppSDK();\n","/**\n * UP Mini-App SDK Types\n */\n\n/**\n * Represents the user's profile information.\n */\nexport interface IUserProfile {\n /** Unique identifier for the user. */\n uuid: string;\n /** Full legal name of the user. */\n fullName: string;\n /** Primary email address. */\n email: string;\n /** Chosen username within the UP ecosystem. */\n username: string;\n /** ISO country code (e.g., \"FR\", \"US\"). */\n countryCode: string;\n /** Phone number without country code. */\n localNumber: string;\n}\n\n/**\n * Geographic location data.\n */\nexport interface ILocationData {\n coords: {\n /** Latitude in decimal degrees. */\n latitude: number;\n /** Longitude in decimal degrees. */\n longitude: number;\n /** Altitude in meters above the WGS 84 reference ellipsoid, or null if not available. */\n altitude: number | null;\n /** Accuracy of the latitude and longitude properties in meters. */\n accuracy: number | null;\n /** Accuracy of the altitude property in meters. */\n altitudeAccuracy: number | null;\n /** The direction in which the device is traveling, in degrees (0-360). */\n heading: number | null;\n /** The velocity of the device in meters per second. */\n speed: number | null;\n };\n /** The time at which the location was retrieved (Unix timestamp). */\n timestamp: number;\n}\n\n/**\n * Request payload for triggering a payment flow.\n */\nexport interface IPaymentRequest {\n /** The specific amount to charge. */\n amount: number;\n /** ISO currency code (e.g., \"EUR\", \"USD\"). */\n currency: string;\n /** Total amount including taxes/fees. */\n total: number;\n /** Itemized breakdown of the purchase. */\n items: Array<{\n /** Name or description of the item. */\n item: string;\n /** Price per unit. */\n price?: number;\n /** Number of units. */\n quantity?: number;\n }>;\n}\n\n/**\n * Style of haptic feedback.\n */\nexport type HapticStyleType =\n | \"light\"\n | \"medium\"\n | \"heavy\"\n | \"rigid\"\n | \"soft\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\n/**\n * Network Proxy Types\n */\n\n/**\n * The HTTP method to use as request method\n */\nexport type NetworkMethodType = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configuration for network proxy requests.\n */\nexport interface INetworkOptions {\n /** Full URL for the request. */\n url: string;\n /** HTTP method to use. */\n method: NetworkMethodType;\n /** Request body for POST/PUT/PATCH. */\n body?: unknown;\n /** Custom HTTP headers. */\n headers?: Record<string, string>;\n}\n\n/**\n * Response from a network proxy request.\n */\nexport interface INetworkResponse {\n /** HTTP status code. */\n status: number;\n /** Response data payload. */\n data: unknown;\n /** Response headers. */\n headers: Record<string, string>;\n}\n\n/**\n * Fidelity & Rewards Types\n */\n\n/**\n * Fidelity program balance information.\n */\nexport interface IFidelityBalance {\n /** Current point or currency balance. */\n balance: number;\n /** Name or symbol of the fidelity currency (e.g., \"FPoints\"). */\n currency: string;\n}\n\n/**\n * Parameters for retrieving fidelity transaction history.\n */\nexport interface IFidelityHistoryParams {\n /** Maximum number of records to return. */\n limit?: number;\n /** Number of records to skip. */\n offset?: number;\n}\n\n/** Type of transaction: credit (add) or debit (remove). */\nexport type FidelityTransactionTypeType = \"credit\" | \"debit\";\n\n/**\n * A single fidelity program transaction.\n */\nexport interface IFidelityTransaction {\n /** Unique identifier for the transaction. */\n id: string;\n /** Amount of the transaction. */\n amount: number;\n /** Human-readable description. */\n description: string;\n /** ISO 8601 date string. */\n date: string;\n /** Type of transaction */\n type: FidelityTransactionTypeType;\n}\n\n/**\n * The initialization options required to set up the Mini-App SDK.\n */\nexport type IInitializationOptions = {};\n\n/**\n * The post initialization response\n */\nexport interface IInitializationResponse {\n /** The name of the mini app */\n name: string;\n /** The uuid of the mini app */\n uuid: string;\n /** The description of the mini app */\n description: string;\n /** The authors of the mini app */\n authors?: string;\n /** The current version in the registry */\n version?: string;\n}\n\n/**\n * Events emitted by the UI module.\n */\nexport enum UIEvent {\n /** Triggered when the user performs a native \"Pull-to-Refresh\". */\n TOP_SCROLL_MORE = \"TOP_SCROLL_MORE\",\n /** Triggered when the user scrolls near the bottom of the page (within 200px threshold). */\n BOTTOM_SCROLL_MORE = \"BOTTOM_SCROLL_MORE\",\n}\n\n/**\n * Union type for all SDK events, allowing for both known enums and custom strings.\n * The (string & {}) pattern preserves IntelliSense for enum members.\n */\nexport type SDKEvent = UIEvent | (string & {});\n\n/**\n * Configuration for native scroll interactions managed by the Host Shell.\n */\nexport interface ScrollConfig {\n /** Configuration for Pull-to-Refresh (Top). */\n topScrollMore?: {\n /** Show/hide the native RefreshControl. */\n enabled: boolean;\n /** Set to true to show the loading spinner, false to hide it. */\n refreshing?: boolean;\n };\n /** Configuration for Infinite Scroll (Bottom). */\n bottomScrollMore?: {\n /** Enable/disable bottom scroll detection. */\n enabled: boolean;\n /** If false, detection stops and the indicator is hidden. */\n hasMore?: boolean;\n /** Set to true to show the bottom ActivityIndicator. */\n loadingMore?: boolean;\n };\n}\n"],"mappings":"8bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gBAAAE,EAAA,YAAAC,EAAA,YAAAC,EAAA,QAAAC,ICSO,IAAMC,EAAN,KAAa,CACV,UAGJ,CAAC,EACG,eAA8D,CAAC,EAOvE,aAAc,CACR,OAAO,OAAW,MAEnB,OAAmD,gBAAkB,CACpE,gBAAkBC,GAChB,KAAK,oBAAoBA,CAAQ,CACrC,EAGA,OAAO,iBAAiB,UAAYC,GAAU,CAC5C,GAAI,CACF,IAAMC,EACJ,OAAOD,EAAM,MAAS,SAClB,KAAK,MAAMA,EAAM,IAAI,EACrBA,EAAM,KACZ,KAAK,oBAAoBC,CAAI,CAC/B,MAAa,CAEb,CACF,CAAC,EAEL,CASQ,oBAAoBF,EAA2B,CACrD,GAAI,GAACA,GAAY,OAAOA,GAAa,UAGrC,IACEA,EAAS,YACT,OAAOA,EAAS,YAAe,UAC/B,KAAK,UAAUA,EAAS,UAAU,EAClC,CACA,GAAM,CAAE,WAAAG,CAAW,EAAIH,EACjB,CAAE,QAAAI,EAAS,OAAAC,CAAO,EAAI,KAAK,UAAUF,CAAU,EAEjDH,EAAS,UAAY,IAASA,EAAS,MACzCK,EAAOL,EAAS,OAAS,eAAe,EAExCI,EACEJ,EAAS,QAAU,OACfA,EAAS,MACTA,EAAS,SAAWA,CAC1B,EAGF,OAAO,KAAK,UAAUG,CAAU,EAChC,MACF,CAGA,GAAIH,EAAS,OAAS,OAAOA,EAAS,OAAU,SAAU,CACxD,IAAMM,EAAY,KAAK,eAAeN,EAAS,KAAK,EAC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E,WAAAA,CAAW,CAAC,CACpD,EAKO,GAAK,CAEV,KAAM,IAAqB,KAAK,OAAO,KAAK,MAAM,EAKlD,gBAAkBC,GAChB,KAAK,OAAO,KAAK,oBAAqBA,CAAM,CAChD,EAKO,MAAQ,CAKb,IAAK,IAAIC,IAAuB,KAAK,OAAO,KAAK,YAAa,CAAE,QAAAA,CAAQ,CAAC,CAC3E,EAQO,GAAGC,EAAiBC,EAAmC,CAC5D,OAAO,KAAK,OAAO,GAAGD,EAAiBC,CAAQ,CACjD,CAOO,IAAID,EAAiBC,EAAmC,CAC7D,KAAK,OAAO,IAAID,EAAiBC,CAAQ,CAC3C,CACF,EAKaC,EAAM,IAAInB,EC5DhB,IAAKoB,OAEVA,EAAA,gBAAkB,kBAElBA,EAAA,mBAAqB,qBAJXA,OAAA,IHlLZ,IAAOC,EAAQC","names":["index_exports","__export","MiniAppSDK","UIEvent","index_default","sdk","Bridge","envelope","event","data","callbackId","resolve","reject","listeners","listener","e","callback","cb","type","payload","message","win","MiniAppSDK","Bridge","options","key","value","scopes","fields","type","payload","id","title","status","style","params","intentUuid","config","message","event","callback","sdk","UIEvent","index_default","sdk"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/bridge.ts","../src/sdk.ts","../src/types/types.ts"],"sourcesContent":["export { MiniAppSDK, sdk } from \"@miniapps-sdk/sdk\";\nexport * from \"@miniapps-sdk/types\";\n\nimport { sdk } from \"@miniapps-sdk/sdk\";\nexport default sdk;\n","import type { IBridgeEnvelope } from \"@miniapps-sdk/types\";\n\n/**\n * The Bridge handles low-level communication between the Mini-App WebView\n * and the Native Host Shell (iOS/Android).\n *\n * It manages asynchronous request-response cycles via callbacks and\n * supports subscription to pushed events from the native environment.\n */\nexport class Bridge {\n private callbacks: Record<\n string,\n { resolve: (val: unknown) => void; reject: (err: unknown) => void }\n > = {};\n private eventListeners: Record<string, ((data: unknown) => void)[]> = {};\n\n /**\n * Registers a global listener for messages coming from the native shell.\n * Also listens for standard browser `message` events to support multiple\n * communication channels (e.g., React Native WebView postMessage).\n */\n constructor() {\n if (typeof window !== \"undefined\") {\n // Set up the global bridge receiver for React Native WebView\n (window as unknown as { __MiniAppBridge: unknown }).__MiniAppBridge = {\n onNativeMessage: (envelope: IBridgeEnvelope) =>\n this.handleNativeMessage(envelope),\n };\n\n // Also listen for postMessage events\n window.addEventListener(\"message\", (event) => {\n try {\n const data =\n typeof event.data === \"string\"\n ? JSON.parse(event.data)\n : event.data;\n this.handleNativeMessage(data);\n } catch (_e) {\n // Ignore non-JSON messages\n }\n });\n }\n }\n\n /**\n * Internal handler for all incoming messages from the native shell.\n * Matches incoming payloads to either pending callbacks or event listeners.\n *\n * @internal\n * @param envelope The message envelope received from native code.\n */\n private handleNativeMessage(envelope: IBridgeEnvelope) {\n if (!envelope || typeof envelope !== \"object\") return;\n\n // 1. Handle Response Callbacks\n if (\n envelope.callbackId &&\n typeof envelope.callbackId === \"string\" &&\n this.callbacks[envelope.callbackId]\n ) {\n const { callbackId } = envelope;\n const { resolve, reject } = this.callbacks[callbackId];\n\n if (envelope.success === false || envelope.error) {\n reject(envelope.error || \"Unknown error\");\n } else {\n resolve(envelope.value ?? envelope.payload ?? envelope);\n }\n\n delete this.callbacks[callbackId];\n return;\n }\n\n // 2. Handle Pushed Events\n if (envelope.event && typeof envelope.event === \"string\") {\n const listeners = this.eventListeners[envelope.event];\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(envelope.payload || envelope.value);\n } catch (e) {\n console.error(`Error in event listener for ${envelope.event}:`, e);\n }\n }\n }\n }\n }\n\n /**\n * Subscribes to a pushed event from the native shell.\n *\n * @param event The event name to listen for.\n * @param callback Function to execute when the event occurs.\n * @returns An unsubscription function.\n */\n public on(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) {\n this.eventListeners[event] = [];\n }\n this.eventListeners[event].push(callback);\n return () => this.off(event, callback);\n }\n\n /**\n * Unsubscribes a specific callback from an event.\n *\n * @param event The event name.\n * @param callback The callback function to remove.\n */\n public off(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) return;\n this.eventListeners[event] = this.eventListeners[event].filter(\n (cb) => cb !== callback,\n );\n }\n\n /**\n * Sends a message to the native shell and waits for a response.\n *\n * @template T The expected response type.\n * @param type The action type (e.g., \"GET_LOCATION\").\n * @param payload Data associated with the action.\n * @returns A promise that resolves with the native response.\n */\n public send<T = unknown>(type: string, payload?: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const callbackId = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.callbacks[callbackId] = {\n reject,\n resolve: resolve as (val: unknown) => void,\n };\n\n const message = {\n callbackId,\n payload,\n type,\n };\n\n const win = window as unknown as {\n ReactNativeWebView?: { postMessage: (msg: string) => void };\n };\n\n if (win.ReactNativeWebView?.postMessage) {\n win.ReactNativeWebView.postMessage(JSON.stringify(message));\n } else {\n console.warn(\n \"UP Bridge not available. Are you running inside the UP Shell?\",\n );\n delete this.callbacks[callbackId];\n reject(new Error(\"Bridge not available\"));\n }\n });\n }\n}\n","import { Bridge } from \"@miniapps-sdk/bridge\";\nimport type {\n HapticStyleType,\n IFidelityBalance,\n IFidelityHistoryParams,\n IFidelityTransaction,\n IInitializationOptions,\n IInitializationResponse,\n ILocationData,\n INetworkOptions,\n INetworkResponse,\n IPaymentRequest,\n IUserProfile,\n ScrollConfig,\n SDKEvent,\n} from \"@miniapps-sdk/types/types\";\n\n/**\n * Main SDK for UP Mini-Apps.\n * Provides access to native device features, storage, identity, and shell UI.\n */\nexport class MiniAppSDK {\n private bridge: Bridge;\n\n constructor() {\n this.bridge = new Bridge();\n }\n\n /**\n * The starting point for the Mini-App. Must be called before any other SDK methods.\n * @param options The options to provide to the shell app\n */\n public initialize(\n options: IInitializationOptions,\n ): Promise<IInitializationResponse> {\n return this.bridge.send(\"INITIALIZE\", options);\n }\n\n /**\n * Local SQLite Storage.\n * Data is persisted on the device and is isolated per Mini-App.\n */\n public storage = {\n /** Retrieves a value by key. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"STORAGE_GET\", { key }),\n /** Retrieves all key-value pairs stored for this Mini-App. */\n getAll: (): Promise<Record<string, string>> =>\n this.bridge.send(\"STORAGE_GET_ALL\"),\n /** Sets a value for a specific key. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"STORAGE_SET\", { key, value }),\n };\n\n /**\n * Hardware-level Secure Storage.\n * Data is stored in the device's secure enclave (Keychain/Keystore) and is isolated per Mini-App.\n */\n public secureStore = {\n /** Retrieves a value by key from secure storage. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"SECURE_GET\", { key }),\n /** Sets a value for a specific key in secure storage. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"SECURE_SET\", { key, value }),\n };\n\n /**\n * Database Storage.\n * Access to user-app specific persistent database storage.\n */\n public database = {\n /** Retrieves the user data stored in the backend database. */\n getUserData: <T = unknown>(): Promise<T> =>\n this.bridge.send<T>(\"DATABASE_GET_USER_DATA\"),\n /** Updates the user data stored in the backend database. */\n setUserData: <T = unknown>(data: T): Promise<void> =>\n this.bridge.send<void>(\"DATABASE_SET_USER_DATA\", { data }),\n };\n\n /**\n * Device Location services.\n */\n public location = {\n /** Retrieves the current GPS position of the device. */\n getCurrentPosition: (): Promise<ILocationData> =>\n this.bridge.send(\"GET_LOCATION\"),\n };\n\n /**\n * Identity & Profile management.\n */\n public user = {\n /**\n * Fetch a short-lived Scoped Identity Token (JWT).\n * This token is signed by the UP Hub and can be verified by your backend.\n * @param scopes Optional list of scopes requested (e.g., ['profile', 'email']).\n */\n getIdentityToken: (scopes?: string[]): Promise<string> =>\n this.bridge.send(\"GET_IDENTITY_TOKEN\", { scopes }),\n /**\n * Fetch user profile data.\n * @param fields Optional list of specific fields to retrieve (e.g., ['fullName', 'username']).\n */\n getProfile: <T extends keyof IUserProfile>(\n fields?: T[],\n ): Promise<Partial<IUserProfile>> =>\n this.bridge.send(\"GET_USER_PROFILE\", { fields }),\n };\n\n /**\n * Explicit Permission Management.\n * Allows requesting access to sensitive device features or user data.\n */\n public permission = {\n /**\n * Explicitly request access to sensitive data.\n * @param type The type of permission to request ('location' or 'profile').\n * @param fields If requesting 'profile', the specific fields required.\n */\n request: ((type: \"location\" | \"profile\", fields?: string[]) => {\n return this.bridge.send(\"REQUEST_PERMISSION\", { fields, type });\n }) as {\n (type: \"location\"): Promise<boolean>;\n (type: \"profile\", fields: (keyof IUserProfile)[]): Promise<boolean>;\n },\n };\n\n /**\n * Payments integration.\n */\n public payment = {\n /**\n * Triggers the native payment flow.\n * @param payload Amount, currency, and itemized list for the payment.\n */\n request: (\n payload: IPaymentRequest,\n ): Promise<{ success: true; transactionId: string }> =>\n this.bridge.send(\"PAYMENT_REQUEST\", payload),\n };\n\n /**\n * Live Activities & Notifications.\n * Allows the Mini-App to display real-time updates in the host shell.\n */\n public activity = {\n /**\n * Starts a new live activity.\n * @param id Unique identifier for the activity.\n * @param title Display title for the activity.\n * @param status Initial status message.\n */\n start: (id: string, title: string, status: string): Promise<void> =>\n this.bridge.send(\"START_ACTIVITY\", { id, status, title }),\n };\n\n /**\n * Haptic feedback.\n */\n public haptic = {\n /**\n * Triggers a haptic vibration on the device.\n * @param style The style of haptic feedback (e.g., 'light', 'medium', 'heavy', 'success', 'warning', 'error').\n */\n trigger: (style: HapticStyleType): Promise<void> =>\n this.bridge.send(\"TRIGGER_HAPTIC\", { style }),\n };\n\n /**\n * Network Proxy.\n * Allows the Mini-App to make network requests through the host shell to bypass CORS or use host-level authentication.\n */\n public network = {\n /**\n * Performs a network request via the host shell.\n * @param options Request method, URL, headers, and body.\n */\n request: (options: INetworkOptions): Promise<INetworkResponse> =>\n this.bridge.send(\"NETWORK_REQUEST\", options),\n };\n\n /**\n * Fidelity & Rewards program integration.\n */\n public fidelity = {\n /** Returns current fidelity balance. */\n getFidelityBalance: (): Promise<IFidelityBalance> =>\n this.bridge.send(\"GET_FIDELITY_BALANCE\"),\n /**\n * Retrieves fidelity transaction history.\n * @param params Filtering and pagination parameters.\n */\n getFidelityHistory: (\n params?: IFidelityHistoryParams,\n ): Promise<IFidelityTransaction[]> =>\n this.bridge.send(\"GET_FIDELITY_HISTORY\", params),\n /**\n * Authorize spending fidelity points (FPoints) via Two-Phase Authorization.\n * @param intentUuid UUID generated by your backend for the transaction.\n */\n spendFPoints: (\n intentUuid: string,\n ): Promise<{ success: boolean; transactionId: string }> =>\n this.bridge.send(\"SPEND_FPOINTS\", { intentUuid }),\n };\n\n /**\n * UI and Navigation controls.\n */\n public ui = {\n /** Closes the Mini-App and returns to the host shell. */\n exit: (): Promise<void> => this.bridge.send(\"EXIT\"),\n /**\n * Configures native scroll behaviors like Pull-to-Refresh and Infinite Scroll.\n * @param config Scroll configuration for top/bottom detection.\n */\n setScrollConfig: (config: ScrollConfig): Promise<void> =>\n this.bridge.send(\"SET_SCROLL_CONFIG\", config),\n };\n\n /**\n * Debug controls\n */\n public debug = {\n /**\n * Log to the shell app\n * @param message\n */\n log: (...message: unknown[]) => this.bridge.send(\"DEBUG_LOG\", { message }),\n };\n\n /**\n * Registers a callback for a specific event from the native shell.\n * @param event The name of the event to listen for.\n * @param callback The function to execute when the event is triggered.\n * @returns A function to unregister the listener.\n */\n public on(event: SDKEvent, callback: (data: unknown) => void) {\n return this.bridge.on(event as string, callback);\n }\n\n /**\n * Unregisters a previously registered event listener.\n * @param event The name of the event.\n * @param callback The callback function to remove.\n */\n public off(event: SDKEvent, callback: (data: unknown) => void) {\n this.bridge.off(event as string, callback);\n }\n}\n\n/**\n * Singleton instance of the MiniAppSDK.\n */\nexport const sdk = new MiniAppSDK();\n","/**\n * UP Mini-App SDK Types\n */\n\n/**\n * Represents the user's profile information.\n */\nexport interface IUserProfile {\n /** Unique identifier for the user. */\n uuid: string;\n /** Full legal name of the user. */\n fullName: string;\n /** Primary email address. */\n email: string;\n /** Chosen username within the UP ecosystem. */\n username: string;\n /** ISO country code (e.g., \"FR\", \"US\"). */\n countryCode: string;\n /** Phone number without country code. */\n localNumber: string;\n}\n\n/**\n * Geographic location data.\n */\nexport interface ILocationData {\n coords: {\n /** Latitude in decimal degrees. */\n latitude: number;\n /** Longitude in decimal degrees. */\n longitude: number;\n /** Altitude in meters above the WGS 84 reference ellipsoid, or null if not available. */\n altitude: number | null;\n /** Accuracy of the latitude and longitude properties in meters. */\n accuracy: number | null;\n /** Accuracy of the altitude property in meters. */\n altitudeAccuracy: number | null;\n /** The direction in which the device is traveling, in degrees (0-360). */\n heading: number | null;\n /** The velocity of the device in meters per second. */\n speed: number | null;\n };\n /** The time at which the location was retrieved (Unix timestamp). */\n timestamp: number;\n}\n\n/**\n * Request payload for triggering a payment flow.\n */\nexport interface IPaymentRequest {\n /** The specific amount to charge. */\n amount: number;\n /** ISO currency code (e.g., \"EUR\", \"USD\"). */\n currency: string;\n /** Total amount including taxes/fees. */\n total: number;\n /** Itemized breakdown of the purchase. */\n items: Array<{\n /** Name or description of the item. */\n item: string;\n /** Price per unit. */\n price?: number;\n /** Number of units. */\n quantity?: number;\n }>;\n}\n\n/**\n * Style of haptic feedback.\n */\nexport type HapticStyleType =\n | \"light\"\n | \"medium\"\n | \"heavy\"\n | \"rigid\"\n | \"soft\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\n/**\n * Network Proxy Types\n */\n\n/**\n * The HTTP method to use as request method\n */\nexport type NetworkMethodType = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configuration for network proxy requests.\n */\nexport interface INetworkOptions {\n /** Full URL for the request. */\n url: string;\n /** HTTP method to use. */\n method: NetworkMethodType;\n /** Request body for POST/PUT/PATCH. */\n body?: unknown;\n /** Custom HTTP headers. */\n headers?: Record<string, string>;\n}\n\n/**\n * Response from a network proxy request.\n */\nexport interface INetworkResponse<T = unknown> {\n /** HTTP status code. */\n status: number;\n /** Response data payload. */\n data: T;\n /** Response headers. */\n headers: Headers;\n}\n\n/**\n * Fidelity & Rewards Types\n */\n\n/**\n * Fidelity program balance information.\n */\nexport interface IFidelityBalance {\n /** Current point or currency balance. */\n balance: number;\n /** Name or symbol of the fidelity currency (e.g., \"FPoints\"). */\n currency: string;\n}\n\n/**\n * Parameters for retrieving fidelity transaction history.\n */\nexport interface IFidelityHistoryParams {\n /** Maximum number of records to return. */\n limit?: number;\n\n /** Cursor for pagination; null for the first page. */\n cursor?: string | null;\n}\n\n/** Type of transaction: credit (add) or debit (remove). */\nexport type FidelityTransactionTypeType = \"credit\" | \"debit\";\n\n/**\n * A single fidelity program transaction.\n */\nexport interface IFidelityTransaction {\n /** Unique identifier for the transaction. */\n id: string;\n /** Amount of the transaction. */\n amount: number;\n /** Human-readable description. */\n description: string;\n /** ISO 8601 date string. */\n date: string;\n /** Type of transaction */\n type: FidelityTransactionTypeType;\n}\n\n/**\n * The initialization options required to set up the Mini-App SDK.\n */\nexport type IInitializationOptions = {};\n\n/**\n * The post initialization response\n */\nexport interface IInitializationResponse<\n Env extends Record<string, unknown> = Record<string, unknown>,\n UserData extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The name of the mini app */\n name: string;\n /** The uuid of the mini app */\n uuid: string;\n /** The description of the mini app */\n description: string;\n /** The authors of the mini app */\n authors?: string;\n /** The current version in the registry */\n version?: string;\n /** The identity token got from the shell's backend */\n identityToken: string;\n /** The scoped profile based on the requested fields during initialization or the getUserProfile call */\n profile: Partial<IUserProfile | null>;\n /** The environment variables defined for the mini app in the shell's backend */\n env: Env;\n /** The user data passed during the initialization or the setUserData call */\n userData: UserData;\n}\n\n/**\n * Events emitted by the UI module.\n */\nexport enum UIEvent {\n /** Triggered when the user performs a native \"Pull-to-Refresh\". */\n TOP_SCROLL_MORE = \"TOP_SCROLL_MORE\",\n /** Triggered when the user scrolls near the bottom of the page (within 200px threshold). */\n BOTTOM_SCROLL_MORE = \"BOTTOM_SCROLL_MORE\",\n}\n\n/**\n * Union type for all SDK events, allowing for both known enums and custom strings.\n * The (string & {}) pattern preserves IntelliSense for enum members.\n */\nexport type SDKEvent = UIEvent | (string & {});\n\n/**\n * Configuration for native scroll interactions managed by the Host Shell.\n */\nexport interface ScrollConfig {\n /** Configuration for Pull-to-Refresh (Top). */\n topScrollMore?: {\n /** Show/hide the native RefreshControl. */\n enabled: boolean;\n /** Set to true to show the loading spinner, false to hide it. */\n refreshing?: boolean;\n };\n /** Configuration for Infinite Scroll (Bottom). */\n bottomScrollMore?: {\n /** Enable/disable bottom scroll detection. */\n enabled: boolean;\n /** If false, detection stops and the indicator is hidden. */\n hasMore?: boolean;\n /** Set to true to show the bottom ActivityIndicator. */\n loadingMore?: boolean;\n };\n}\n"],"mappings":"8bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gBAAAE,EAAA,YAAAC,EAAA,YAAAC,EAAA,QAAAC,ICSO,IAAMC,EAAN,KAAa,CACV,UAGJ,CAAC,EACG,eAA8D,CAAC,EAOvE,aAAc,CACR,OAAO,OAAW,MAEnB,OAAmD,gBAAkB,CACpE,gBAAkBC,GAChB,KAAK,oBAAoBA,CAAQ,CACrC,EAGA,OAAO,iBAAiB,UAAYC,GAAU,CAC5C,GAAI,CACF,IAAMC,EACJ,OAAOD,EAAM,MAAS,SAClB,KAAK,MAAMA,EAAM,IAAI,EACrBA,EAAM,KACZ,KAAK,oBAAoBC,CAAI,CAC/B,MAAa,CAEb,CACF,CAAC,EAEL,CASQ,oBAAoBF,EAA2B,CACrD,GAAI,GAACA,GAAY,OAAOA,GAAa,UAGrC,IACEA,EAAS,YACT,OAAOA,EAAS,YAAe,UAC/B,KAAK,UAAUA,EAAS,UAAU,EAClC,CACA,GAAM,CAAE,WAAAG,CAAW,EAAIH,EACjB,CAAE,QAAAI,EAAS,OAAAC,CAAO,EAAI,KAAK,UAAUF,CAAU,EAEjDH,EAAS,UAAY,IAASA,EAAS,MACzCK,EAAOL,EAAS,OAAS,eAAe,EAExCI,EAAQJ,EAAS,OAASA,EAAS,SAAWA,CAAQ,EAGxD,OAAO,KAAK,UAAUG,CAAU,EAChC,MACF,CAGA,GAA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AU,CAKf,QAAUX,GACR,KAAK,OAAO,KAAK,kBAAmBA,CAAO,CAC/C,EAKO,SAAW,CAEhB,mBAAoB,IAClB,KAAK,OAAO,KAAK,sBAAsB,EAKzC,mBACEY,GAEA,KAAK,OAAO,KAAK,uBAAwBA,CAAM,EAKjD,aACEC,GAEA,KAAK,OAAO,KAAK,gBAAiB,CAAE,WAAAA,CAAW,CAAC,CACpD,EAKO,GAAK,CAEV,KAAM,IAAqB,KAAK,OAAO,KAAK,MAAM,EAKlD,gBAAkBC,GAChB,KAAK,OAAO,KAAK,oBAAqBA,CAAM,CAChD,EAKO,MAAQ,CAKb,IAAK,IAAIC,IAAuB,KAAK,OAAO,KAAK,YAAa,CAAE,QAAAA,CAAQ,CAAC,CAC3E,EAQO,GAAGC,EAAiBC,EAAmC,CAC5D,OAAO,KAAK,OAAO,GAAGD,EAAiBC,CAAQ,CACjD,CAOO,IAAID,EAAiBC,EAAmC,CAC7D,KAAK,OAAO,IAAID,EAAiBC,CAAQ,CAC3C,CACF,EAKaC,EAAM,IAAIpB,EC7DhB,IAAKqB,OAEVA,EAAA,gBAAkB,kBAElBA,EAAA,mBAAqB,qBAJXA,OAAA,IH9LZ,IAAOC,EAAQC","names":["index_exports","__export","MiniAppSDK","UIEvent","index_default","sdk","Bridge","envelope","event","data","callbackId","resolve","reject","listeners","listener","e","callback","cb","type","payload","message","win","MiniAppSDK","Bridge","options","key","value","data","scopes","fields","type","payload","id","title","status","style","params","intentUuid","config","message","event","callback","sdk","UIEvent","index_default","sdk"]}
package/dist/index.d.mts CHANGED
@@ -88,13 +88,13 @@ interface INetworkOptions {
88
88
  /**
89
89
  * Response from a network proxy request.
90
90
  */
91
- interface INetworkResponse {
91
+ interface INetworkResponse<T = unknown> {
92
92
  /** HTTP status code. */
93
93
  status: number;
94
94
  /** Response data payload. */
95
- data: unknown;
95
+ data: T;
96
96
  /** Response headers. */
97
- headers: Record<string, string>;
97
+ headers: Headers;
98
98
  }
99
99
  /**
100
100
  * Fidelity & Rewards Types
@@ -114,8 +114,8 @@ interface IFidelityBalance {
114
114
  interface IFidelityHistoryParams {
115
115
  /** Maximum number of records to return. */
116
116
  limit?: number;
117
- /** Number of records to skip. */
118
- offset?: number;
117
+ /** Cursor for pagination; null for the first page. */
118
+ cursor?: string | null;
119
119
  }
120
120
  /** Type of transaction: credit (add) or debit (remove). */
121
121
  type FidelityTransactionTypeType = "credit" | "debit";
@@ -141,7 +141,7 @@ type IInitializationOptions = {};
141
141
  /**
142
142
  * The post initialization response
143
143
  */
144
- interface IInitializationResponse {
144
+ interface IInitializationResponse<Env extends Record<string, unknown> = Record<string, unknown>, UserData extends Record<string, unknown> = Record<string, unknown>> {
145
145
  /** The name of the mini app */
146
146
  name: string;
147
147
  /** The uuid of the mini app */
@@ -152,6 +152,14 @@ interface IInitializationResponse {
152
152
  authors?: string;
153
153
  /** The current version in the registry */
154
154
  version?: string;
155
+ /** The identity token got from the shell's backend */
156
+ identityToken: string;
157
+ /** The scoped profile based on the requested fields during initialization or the getUserProfile call */
158
+ profile: Partial<IUserProfile | null>;
159
+ /** The environment variables defined for the mini app in the shell's backend */
160
+ env: Env;
161
+ /** The user data passed during the initialization or the setUserData call */
162
+ userData: UserData;
155
163
  }
156
164
  /**
157
165
  * Events emitted by the UI module.
@@ -223,6 +231,16 @@ declare class MiniAppSDK {
223
231
  /** Sets a value for a specific key in secure storage. */
224
232
  set: (key: string, value: string) => Promise<void>;
225
233
  };
234
+ /**
235
+ * Database Storage.
236
+ * Access to user-app specific persistent database storage.
237
+ */
238
+ database: {
239
+ /** Retrieves the user data stored in the backend database. */
240
+ getUserData: <T = unknown>() => Promise<T>;
241
+ /** Updates the user data stored in the backend database. */
242
+ setUserData: <T = unknown>(data: T) => Promise<void>;
243
+ };
226
244
  /**
227
245
  * Device Location services.
228
246
  */
@@ -373,19 +391,19 @@ declare const sdk: MiniAppSDK;
373
391
  * Internal message envelope for bridge communication.
374
392
  * @internal
375
393
  */
376
- interface IBridgeEnvelope<T = unknown> {
394
+ interface IBridgeEnvelope<P = unknown, V = unknown> {
377
395
  /** Unique identifier to match responses with requests. */
378
396
  callbackId?: string;
379
397
  /** The type/action of the message. */
380
- type: string;
398
+ type?: string;
381
399
  /** Data payload for the message. */
382
- payload?: T;
400
+ payload?: P;
383
401
  /** Whether the operation was successful. */
384
402
  success?: boolean;
385
403
  /** Error message if success is false. */
386
404
  error?: string;
387
405
  /** The result value for successful operations. */
388
- value?: unknown;
406
+ value?: V;
389
407
  /** Event name for pushed notifications. */
390
408
  event?: string;
391
409
  }
@@ -470,15 +488,22 @@ type BridgeMessageType = {
470
488
  callbackId: string;
471
489
  } | {
472
490
  type: "GET_FIDELITY_HISTORY";
473
- payload: {
474
- limit: number;
475
- offset: number;
476
- };
491
+ payload: IFidelityHistoryParams;
477
492
  callbackId: string;
478
493
  } | {
479
494
  type: "EXIT";
480
495
  payload?: unknown;
481
496
  callbackId: string;
497
+ } | {
498
+ type: "DATABASE_GET_USER_DATA";
499
+ payload?: unknown;
500
+ callbackId: string;
501
+ } | {
502
+ type: "DATABASE_SET_USER_DATA";
503
+ payload: {
504
+ data: unknown;
505
+ };
506
+ callbackId: string;
482
507
  } | {
483
508
  type: "REQUEST_PERMISSION";
484
509
  payload: {
package/dist/index.d.ts CHANGED
@@ -88,13 +88,13 @@ interface INetworkOptions {
88
88
  /**
89
89
  * Response from a network proxy request.
90
90
  */
91
- interface INetworkResponse {
91
+ interface INetworkResponse<T = unknown> {
92
92
  /** HTTP status code. */
93
93
  status: number;
94
94
  /** Response data payload. */
95
- data: unknown;
95
+ data: T;
96
96
  /** Response headers. */
97
- headers: Record<string, string>;
97
+ headers: Headers;
98
98
  }
99
99
  /**
100
100
  * Fidelity & Rewards Types
@@ -114,8 +114,8 @@ interface IFidelityBalance {
114
114
  interface IFidelityHistoryParams {
115
115
  /** Maximum number of records to return. */
116
116
  limit?: number;
117
- /** Number of records to skip. */
118
- offset?: number;
117
+ /** Cursor for pagination; null for the first page. */
118
+ cursor?: string | null;
119
119
  }
120
120
  /** Type of transaction: credit (add) or debit (remove). */
121
121
  type FidelityTransactionTypeType = "credit" | "debit";
@@ -141,7 +141,7 @@ type IInitializationOptions = {};
141
141
  /**
142
142
  * The post initialization response
143
143
  */
144
- interface IInitializationResponse {
144
+ interface IInitializationResponse<Env extends Record<string, unknown> = Record<string, unknown>, UserData extends Record<string, unknown> = Record<string, unknown>> {
145
145
  /** The name of the mini app */
146
146
  name: string;
147
147
  /** The uuid of the mini app */
@@ -152,6 +152,14 @@ interface IInitializationResponse {
152
152
  authors?: string;
153
153
  /** The current version in the registry */
154
154
  version?: string;
155
+ /** The identity token got from the shell's backend */
156
+ identityToken: string;
157
+ /** The scoped profile based on the requested fields during initialization or the getUserProfile call */
158
+ profile: Partial<IUserProfile | null>;
159
+ /** The environment variables defined for the mini app in the shell's backend */
160
+ env: Env;
161
+ /** The user data passed during the initialization or the setUserData call */
162
+ userData: UserData;
155
163
  }
156
164
  /**
157
165
  * Events emitted by the UI module.
@@ -223,6 +231,16 @@ declare class MiniAppSDK {
223
231
  /** Sets a value for a specific key in secure storage. */
224
232
  set: (key: string, value: string) => Promise<void>;
225
233
  };
234
+ /**
235
+ * Database Storage.
236
+ * Access to user-app specific persistent database storage.
237
+ */
238
+ database: {
239
+ /** Retrieves the user data stored in the backend database. */
240
+ getUserData: <T = unknown>() => Promise<T>;
241
+ /** Updates the user data stored in the backend database. */
242
+ setUserData: <T = unknown>(data: T) => Promise<void>;
243
+ };
226
244
  /**
227
245
  * Device Location services.
228
246
  */
@@ -373,19 +391,19 @@ declare const sdk: MiniAppSDK;
373
391
  * Internal message envelope for bridge communication.
374
392
  * @internal
375
393
  */
376
- interface IBridgeEnvelope<T = unknown> {
394
+ interface IBridgeEnvelope<P = unknown, V = unknown> {
377
395
  /** Unique identifier to match responses with requests. */
378
396
  callbackId?: string;
379
397
  /** The type/action of the message. */
380
- type: string;
398
+ type?: string;
381
399
  /** Data payload for the message. */
382
- payload?: T;
400
+ payload?: P;
383
401
  /** Whether the operation was successful. */
384
402
  success?: boolean;
385
403
  /** Error message if success is false. */
386
404
  error?: string;
387
405
  /** The result value for successful operations. */
388
- value?: unknown;
406
+ value?: V;
389
407
  /** Event name for pushed notifications. */
390
408
  event?: string;
391
409
  }
@@ -470,15 +488,22 @@ type BridgeMessageType = {
470
488
  callbackId: string;
471
489
  } | {
472
490
  type: "GET_FIDELITY_HISTORY";
473
- payload: {
474
- limit: number;
475
- offset: number;
476
- };
491
+ payload: IFidelityHistoryParams;
477
492
  callbackId: string;
478
493
  } | {
479
494
  type: "EXIT";
480
495
  payload?: unknown;
481
496
  callbackId: string;
497
+ } | {
498
+ type: "DATABASE_GET_USER_DATA";
499
+ payload?: unknown;
500
+ callbackId: string;
501
+ } | {
502
+ type: "DATABASE_SET_USER_DATA";
503
+ payload: {
504
+ data: unknown;
505
+ };
506
+ callbackId: string;
482
507
  } | {
483
508
  type: "REQUEST_PERMISSION";
484
509
  payload: {
package/dist/index.js CHANGED
@@ -65,9 +65,7 @@ var Bridge = class {
65
65
  if (envelope.success === false || envelope.error) {
66
66
  reject(envelope.error || "Unknown error");
67
67
  } else {
68
- resolve(
69
- envelope.value !== void 0 ? envelope.value : envelope.payload || envelope
70
- );
68
+ resolve(envelope.value ?? envelope.payload ?? envelope);
71
69
  }
72
70
  delete this.callbacks[callbackId];
73
71
  return;
@@ -180,6 +178,16 @@ var MiniAppSDK = class {
180
178
  /** Sets a value for a specific key in secure storage. */
181
179
  set: (key, value) => this.bridge.send("SECURE_SET", { key, value })
182
180
  };
181
+ /**
182
+ * Database Storage.
183
+ * Access to user-app specific persistent database storage.
184
+ */
185
+ database = {
186
+ /** Retrieves the user data stored in the backend database. */
187
+ getUserData: () => this.bridge.send("DATABASE_GET_USER_DATA"),
188
+ /** Updates the user data stored in the backend database. */
189
+ setUserData: (data) => this.bridge.send("DATABASE_SET_USER_DATA", { data })
190
+ };
183
191
  /**
184
192
  * Device Location services.
185
193
  */
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/bridge.ts","../src/sdk.ts","../src/types/types.ts"],"sourcesContent":["export { MiniAppSDK, sdk } from \"@miniapps-sdk/sdk\";\nexport * from \"@miniapps-sdk/types\";\n\nimport { sdk } from \"@miniapps-sdk/sdk\";\nexport default sdk;\n","import type { IBridgeEnvelope } from \"@miniapps-sdk/types\";\n\n/**\n * The Bridge handles low-level communication between the Mini-App WebView\n * and the Native Host Shell (iOS/Android).\n *\n * It manages asynchronous request-response cycles via callbacks and\n * supports subscription to pushed events from the native environment.\n */\nexport class Bridge {\n private callbacks: Record<\n string,\n { resolve: (val: unknown) => void; reject: (err: unknown) => void }\n > = {};\n private eventListeners: Record<string, ((data: unknown) => void)[]> = {};\n\n /**\n * Registers a global listener for messages coming from the native shell.\n * Also listens for standard browser `message` events to support multiple\n * communication channels (e.g., React Native WebView postMessage).\n */\n constructor() {\n if (typeof window !== \"undefined\") {\n // Set up the global bridge receiver for React Native WebView\n (window as unknown as { __MiniAppBridge: unknown }).__MiniAppBridge = {\n onNativeMessage: (envelope: IBridgeEnvelope) =>\n this.handleNativeMessage(envelope),\n };\n\n // Also listen for postMessage events\n window.addEventListener(\"message\", (event) => {\n try {\n const data =\n typeof event.data === \"string\"\n ? JSON.parse(event.data)\n : event.data;\n this.handleNativeMessage(data);\n } catch (_e) {\n // Ignore non-JSON messages\n }\n });\n }\n }\n\n /**\n * Internal handler for all incoming messages from the native shell.\n * Matches incoming payloads to either pending callbacks or event listeners.\n *\n * @internal\n * @param envelope The message envelope received from native code.\n */\n private handleNativeMessage(envelope: IBridgeEnvelope) {\n if (!envelope || typeof envelope !== \"object\") return;\n\n // 1. Handle Response Callbacks\n if (\n envelope.callbackId &&\n typeof envelope.callbackId === \"string\" &&\n this.callbacks[envelope.callbackId]\n ) {\n const { callbackId } = envelope;\n const { resolve, reject } = this.callbacks[callbackId];\n\n if (envelope.success === false || envelope.error) {\n reject(envelope.error || \"Unknown error\");\n } else {\n resolve(\n envelope.value !== undefined\n ? envelope.value\n : envelope.payload || envelope,\n );\n }\n\n delete this.callbacks[callbackId];\n return;\n }\n\n // 2. Handle Pushed Events\n if (envelope.event && typeof envelope.event === \"string\") {\n const listeners = this.eventListeners[envelope.event];\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(envelope.payload || envelope.value);\n } catch (e) {\n console.error(`Error in event listener for ${envelope.event}:`, e);\n }\n }\n }\n }\n }\n\n /**\n * Subscribes to a pushed event from the native shell.\n *\n * @param event The event name to listen for.\n * @param callback Function to execute when the event occurs.\n * @returns An unsubscription function.\n */\n public on(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) {\n this.eventListeners[event] = [];\n }\n this.eventListeners[event].push(callback);\n return () => this.off(event, callback);\n }\n\n /**\n * Unsubscribes a specific callback from an event.\n *\n * @param event The event name.\n * @param callback The callback function to remove.\n */\n public off(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) return;\n this.eventListeners[event] = this.eventListeners[event].filter(\n (cb) => cb !== callback,\n );\n }\n\n /**\n * Sends a message to the native shell and waits for a response.\n *\n * @template T The expected response type.\n * @param type The action type (e.g., \"GET_LOCATION\").\n * @param payload Data associated with the action.\n * @returns A promise that resolves with the native response.\n */\n public send<T = unknown>(type: string, payload?: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const callbackId = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.callbacks[callbackId] = {\n reject,\n resolve: resolve as (val: unknown) => void,\n };\n\n const message = {\n callbackId,\n payload,\n type,\n };\n\n const win = window as unknown as {\n ReactNativeWebView?: { postMessage: (msg: string) => void };\n };\n\n if (win.ReactNativeWebView?.postMessage) {\n win.ReactNativeWebView.postMessage(JSON.stringify(message));\n } else {\n console.warn(\n \"UP Bridge not available. Are you running inside the UP Shell?\",\n );\n delete this.callbacks[callbackId];\n reject(new Error(\"Bridge not available\"));\n }\n });\n }\n}\n","import { Bridge } from \"@miniapps-sdk/bridge\";\nimport type {\n HapticStyleType,\n IFidelityBalance,\n IFidelityHistoryParams,\n IFidelityTransaction,\n IInitializationOptions,\n IInitializationResponse,\n ILocationData,\n INetworkOptions,\n INetworkResponse,\n IPaymentRequest,\n IUserProfile,\n ScrollConfig,\n SDKEvent,\n} from \"@miniapps-sdk/types/types\";\n\n/**\n * Main SDK for UP Mini-Apps.\n * Provides access to native device features, storage, identity, and shell UI.\n */\nexport class MiniAppSDK {\n private bridge: Bridge;\n\n constructor() {\n this.bridge = new Bridge();\n }\n\n /**\n * The starting point for the Mini-App. Must be called before any other SDK methods.\n * @param options The options to provide to the shell app\n */\n public initialize(\n options: IInitializationOptions,\n ): Promise<IInitializationResponse> {\n return this.bridge.send(\"INITIALIZE\", options);\n }\n\n /**\n * Local SQLite Storage.\n * Data is persisted on the device and is isolated per Mini-App.\n */\n public storage = {\n /** Retrieves a value by key. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"STORAGE_GET\", { key }),\n /** Retrieves all key-value pairs stored for this Mini-App. */\n getAll: (): Promise<Record<string, string>> =>\n this.bridge.send(\"STORAGE_GET_ALL\"),\n /** Sets a value for a specific key. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"STORAGE_SET\", { key, value }),\n };\n\n /**\n * Hardware-level Secure Storage.\n * Data is stored in the device's secure enclave (Keychain/Keystore) and is isolated per Mini-App.\n */\n public secureStore = {\n /** Retrieves a value by key from secure storage. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"SECURE_GET\", { key }),\n /** Sets a value for a specific key in secure storage. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"SECURE_SET\", { key, value }),\n };\n\n /**\n * Device Location services.\n */\n public location = {\n /** Retrieves the current GPS position of the device. */\n getCurrentPosition: (): Promise<ILocationData> =>\n this.bridge.send(\"GET_LOCATION\"),\n };\n\n /**\n * Identity & Profile management.\n */\n public user = {\n /**\n * Fetch a short-lived Scoped Identity Token (JWT).\n * This token is signed by the UP Hub and can be verified by your backend.\n * @param scopes Optional list of scopes requested (e.g., ['profile', 'email']).\n */\n getIdentityToken: (scopes?: string[]): Promise<string> =>\n this.bridge.send(\"GET_IDENTITY_TOKEN\", { scopes }),\n /**\n * Fetch user profile data.\n * @param fields Optional list of specific fields to retrieve (e.g., ['fullName', 'username']).\n */\n getProfile: <T extends keyof IUserProfile>(\n fields?: T[],\n ): Promise<Partial<IUserProfile>> =>\n this.bridge.send(\"GET_USER_PROFILE\", { fields }),\n };\n\n /**\n * Explicit Permission Management.\n * Allows requesting access to sensitive device features or user data.\n */\n public permission = {\n /**\n * Explicitly request access to sensitive data.\n * @param type The type of permission to request ('location' or 'profile').\n * @param fields If requesting 'profile', the specific fields required.\n */\n request: ((type: \"location\" | \"profile\", fields?: string[]) => {\n return this.bridge.send(\"REQUEST_PERMISSION\", { fields, type });\n }) as {\n (type: \"location\"): Promise<boolean>;\n (type: \"profile\", fields: (keyof IUserProfile)[]): Promise<boolean>;\n },\n };\n\n /**\n * Payments integration.\n */\n public payment = {\n /**\n * Triggers the native payment flow.\n * @param payload Amount, currency, and itemized list for the payment.\n */\n request: (\n payload: IPaymentRequest,\n ): Promise<{ success: true; transactionId: string }> =>\n this.bridge.send(\"PAYMENT_REQUEST\", payload),\n };\n\n /**\n * Live Activities & Notifications.\n * Allows the Mini-App to display real-time updates in the host shell.\n */\n public activity = {\n /**\n * Starts a new live activity.\n * @param id Unique identifier for the activity.\n * @param title Display title for the activity.\n * @param status Initial status message.\n */\n start: (id: string, title: string, status: string): Promise<void> =>\n this.bridge.send(\"START_ACTIVITY\", { id, status, title }),\n };\n\n /**\n * Haptic feedback.\n */\n public haptic = {\n /**\n * Triggers a haptic vibration on the device.\n * @param style The style of haptic feedback (e.g., 'light', 'medium', 'heavy', 'success', 'warning', 'error').\n */\n trigger: (style: HapticStyleType): Promise<void> =>\n this.bridge.send(\"TRIGGER_HAPTIC\", { style }),\n };\n\n /**\n * Network Proxy.\n * Allows the Mini-App to make network requests through the host shell to bypass CORS or use host-level authentication.\n */\n public network = {\n /**\n * Performs a network request via the host shell.\n * @param options Request method, URL, headers, and body.\n */\n request: (options: INetworkOptions): Promise<INetworkResponse> =>\n this.bridge.send(\"NETWORK_REQUEST\", options),\n };\n\n /**\n * Fidelity & Rewards program integration.\n */\n public fidelity = {\n /** Returns current fidelity balance. */\n getFidelityBalance: (): Promise<IFidelityBalance> =>\n this.bridge.send(\"GET_FIDELITY_BALANCE\"),\n /**\n * Retrieves fidelity transaction history.\n * @param params Filtering and pagination parameters.\n */\n getFidelityHistory: (\n params?: IFidelityHistoryParams,\n ): Promise<IFidelityTransaction[]> =>\n this.bridge.send(\"GET_FIDELITY_HISTORY\", params),\n /**\n * Authorize spending fidelity points (FPoints) via Two-Phase Authorization.\n * @param intentUuid UUID generated by your backend for the transaction.\n */\n spendFPoints: (\n intentUuid: string,\n ): Promise<{ success: boolean; transactionId: string }> =>\n this.bridge.send(\"SPEND_FPOINTS\", { intentUuid }),\n };\n\n /**\n * UI and Navigation controls.\n */\n public ui = {\n /** Closes the Mini-App and returns to the host shell. */\n exit: (): Promise<void> => this.bridge.send(\"EXIT\"),\n /**\n * Configures native scroll behaviors like Pull-to-Refresh and Infinite Scroll.\n * @param config Scroll configuration for top/bottom detection.\n */\n setScrollConfig: (config: ScrollConfig): Promise<void> =>\n this.bridge.send(\"SET_SCROLL_CONFIG\", config),\n };\n\n /**\n * Debug controls\n */\n public debug = {\n /**\n * Log to the shell app\n * @param message\n */\n log: (...message: unknown[]) => this.bridge.send(\"DEBUG_LOG\", { message }),\n };\n\n /**\n * Registers a callback for a specific event from the native shell.\n * @param event The name of the event to listen for.\n * @param callback The function to execute when the event is triggered.\n * @returns A function to unregister the listener.\n */\n public on(event: SDKEvent, callback: (data: unknown) => void) {\n return this.bridge.on(event as string, callback);\n }\n\n /**\n * Unregisters a previously registered event listener.\n * @param event The name of the event.\n * @param callback The callback function to remove.\n */\n public off(event: SDKEvent, callback: (data: unknown) => void) {\n this.bridge.off(event as string, callback);\n }\n}\n\n/**\n * Singleton instance of the MiniAppSDK.\n */\nexport const sdk = new MiniAppSDK();\n","/**\n * UP Mini-App SDK Types\n */\n\n/**\n * Represents the user's profile information.\n */\nexport interface IUserProfile {\n /** Unique identifier for the user. */\n uuid: string;\n /** Full legal name of the user. */\n fullName: string;\n /** Primary email address. */\n email: string;\n /** Chosen username within the UP ecosystem. */\n username: string;\n /** ISO country code (e.g., \"FR\", \"US\"). */\n countryCode: string;\n /** Phone number without country code. */\n localNumber: string;\n}\n\n/**\n * Geographic location data.\n */\nexport interface ILocationData {\n coords: {\n /** Latitude in decimal degrees. */\n latitude: number;\n /** Longitude in decimal degrees. */\n longitude: number;\n /** Altitude in meters above the WGS 84 reference ellipsoid, or null if not available. */\n altitude: number | null;\n /** Accuracy of the latitude and longitude properties in meters. */\n accuracy: number | null;\n /** Accuracy of the altitude property in meters. */\n altitudeAccuracy: number | null;\n /** The direction in which the device is traveling, in degrees (0-360). */\n heading: number | null;\n /** The velocity of the device in meters per second. */\n speed: number | null;\n };\n /** The time at which the location was retrieved (Unix timestamp). */\n timestamp: number;\n}\n\n/**\n * Request payload for triggering a payment flow.\n */\nexport interface IPaymentRequest {\n /** The specific amount to charge. */\n amount: number;\n /** ISO currency code (e.g., \"EUR\", \"USD\"). */\n currency: string;\n /** Total amount including taxes/fees. */\n total: number;\n /** Itemized breakdown of the purchase. */\n items: Array<{\n /** Name or description of the item. */\n item: string;\n /** Price per unit. */\n price?: number;\n /** Number of units. */\n quantity?: number;\n }>;\n}\n\n/**\n * Style of haptic feedback.\n */\nexport type HapticStyleType =\n | \"light\"\n | \"medium\"\n | \"heavy\"\n | \"rigid\"\n | \"soft\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\n/**\n * Network Proxy Types\n */\n\n/**\n * The HTTP method to use as request method\n */\nexport type NetworkMethodType = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configuration for network proxy requests.\n */\nexport interface INetworkOptions {\n /** Full URL for the request. */\n url: string;\n /** HTTP method to use. */\n method: NetworkMethodType;\n /** Request body for POST/PUT/PATCH. */\n body?: unknown;\n /** Custom HTTP headers. */\n headers?: Record<string, string>;\n}\n\n/**\n * Response from a network proxy request.\n */\nexport interface INetworkResponse {\n /** HTTP status code. */\n status: number;\n /** Response data payload. */\n data: unknown;\n /** Response headers. */\n headers: Record<string, string>;\n}\n\n/**\n * Fidelity & Rewards Types\n */\n\n/**\n * Fidelity program balance information.\n */\nexport interface IFidelityBalance {\n /** Current point or currency balance. */\n balance: number;\n /** Name or symbol of the fidelity currency (e.g., \"FPoints\"). */\n currency: string;\n}\n\n/**\n * Parameters for retrieving fidelity transaction history.\n */\nexport interface IFidelityHistoryParams {\n /** Maximum number of records to return. */\n limit?: number;\n /** Number of records to skip. */\n offset?: number;\n}\n\n/** Type of transaction: credit (add) or debit (remove). */\nexport type FidelityTransactionTypeType = \"credit\" | \"debit\";\n\n/**\n * A single fidelity program transaction.\n */\nexport interface IFidelityTransaction {\n /** Unique identifier for the transaction. */\n id: string;\n /** Amount of the transaction. */\n amount: number;\n /** Human-readable description. */\n description: string;\n /** ISO 8601 date string. */\n date: string;\n /** Type of transaction */\n type: FidelityTransactionTypeType;\n}\n\n/**\n * The initialization options required to set up the Mini-App SDK.\n */\nexport type IInitializationOptions = {};\n\n/**\n * The post initialization response\n */\nexport interface IInitializationResponse {\n /** The name of the mini app */\n name: string;\n /** The uuid of the mini app */\n uuid: string;\n /** The description of the mini app */\n description: string;\n /** The authors of the mini app */\n authors?: string;\n /** The current version in the registry */\n version?: string;\n}\n\n/**\n * Events emitted by the UI module.\n */\nexport enum UIEvent {\n /** Triggered when the user performs a native \"Pull-to-Refresh\". */\n TOP_SCROLL_MORE = \"TOP_SCROLL_MORE\",\n /** Triggered when the user scrolls near the bottom of the page (within 200px threshold). */\n BOTTOM_SCROLL_MORE = \"BOTTOM_SCROLL_MORE\",\n}\n\n/**\n * Union type for all SDK events, allowing for both known enums and custom strings.\n * The (string & {}) pattern preserves IntelliSense for enum members.\n */\nexport type SDKEvent = UIEvent | (string & {});\n\n/**\n * Configuration for native scroll interactions managed by the Host Shell.\n */\nexport interface ScrollConfig {\n /** Configuration for Pull-to-Refresh (Top). */\n topScrollMore?: {\n /** Show/hide the native RefreshControl. */\n enabled: boolean;\n /** Set to true to show the loading spinner, false to hide it. */\n refreshing?: boolean;\n };\n /** Configuration for Infinite Scroll (Bottom). */\n bottomScrollMore?: {\n /** Enable/disable bottom scroll detection. */\n enabled: boolean;\n /** If false, detection stops and the indicator is hidden. */\n hasMore?: boolean;\n /** Set to true to show the bottom ActivityIndicator. */\n loadingMore?: boolean;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,SAAN,MAAa;AAAA,EACV,YAGJ,CAAC;AAAA,EACG,iBAA8D,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOvE,cAAc;AACZ,QAAI,OAAO,WAAW,aAAa;AAEjC,MAAC,OAAmD,kBAAkB;AAAA,QACpE,iBAAiB,CAAC,aAChB,KAAK,oBAAoB,QAAQ;AAAA,MACrC;AAGA,aAAO,iBAAiB,WAAW,CAAC,UAAU;AAC5C,YAAI;AACF,gBAAM,OACJ,OAAO,MAAM,SAAS,WAClB,KAAK,MAAM,MAAM,IAAI,IACrB,MAAM;AACZ,eAAK,oBAAoB,IAAI;AAAA,QAC/B,SAAS,IAAI;AAAA,QAEb;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASQ,oBAAoB,UAA2B;AACrD,QAAI,CAAC,YAAY,OAAO,aAAa,SAAU;AAG/C,QACE,SAAS,cACT,OAAO,SAAS,eAAe,YAC/B,KAAK,UAAU,SAAS,UAAU,GAClC;AACA,YAAM,EAAE,WAAW,IAAI;AACvB,YAAM,EAAE,SAAS,OAAO,IA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,CAClB,WAEA,KAAK,OAAO,KAAK,wBAAwB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKjD,cAAc,CACZ,eAEA,KAAK,OAAO,KAAK,iBAAiB,EAAE,WAAW,CAAC;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKO,KAAK;AAAA;AAAA,IAEV,MAAM,MAAqB,KAAK,OAAO,KAAK,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,IAKlD,iBAAiB,CAAC,WAChB,KAAK,OAAO,KAAK,qBAAqB,MAAM;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA,EAKO,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA,IAKb,KAAK,IAAI,YAAuB,KAAK,OAAO,KAAK,aAAa,EAAE,QAAQ,CAAC;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,GAAG,OAAiB,UAAmC;AAC5D,WAAO,KAAK,OAAO,GAAG,OAAiB,QAAQ;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,IAAI,OAAiB,UAAmC;AAC7D,SAAK,OAAO,IAAI,OAAiB,QAAQ;AAAA,EAC3C;AACF;AAKO,IAAM,MAAM,IAAI,WAAW;;;AC5D3B,IAAK,UAAL,kBAAKA,aAAL;AAEL,EAAAA,SAAA,qBAAkB;AAElB,EAAAA,SAAA,wBAAqB;AAJX,SAAAA;AAAA,GAAA;;;AHlLZ,IAAO,gBAAQ;","names":["UIEvent"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/bridge.ts","../src/sdk.ts","../src/types/types.ts"],"sourcesContent":["export { MiniAppSDK, sdk } from \"@miniapps-sdk/sdk\";\nexport * from \"@miniapps-sdk/types\";\n\nimport { sdk } from \"@miniapps-sdk/sdk\";\nexport default sdk;\n","import type { IBridgeEnvelope } from \"@miniapps-sdk/types\";\n\n/**\n * The Bridge handles low-level communication between the Mini-App WebView\n * and the Native Host Shell (iOS/Android).\n *\n * It manages asynchronous request-response cycles via callbacks and\n * supports subscription to pushed events from the native environment.\n */\nexport class Bridge {\n private callbacks: Record<\n string,\n { resolve: (val: unknown) => void; reject: (err: unknown) => void }\n > = {};\n private eventListeners: Record<string, ((data: unknown) => void)[]> = {};\n\n /**\n * Registers a global listener for messages coming from the native shell.\n * Also listens for standard browser `message` events to support multiple\n * communication channels (e.g., React Native WebView postMessage).\n */\n constructor() {\n if (typeof window !== \"undefined\") {\n // Set up the global bridge receiver for React Native WebView\n (window as unknown as { __MiniAppBridge: unknown }).__MiniAppBridge = {\n onNativeMessage: (envelope: IBridgeEnvelope) =>\n this.handleNativeMessage(envelope),\n };\n\n // Also listen for postMessage events\n window.addEventListener(\"message\", (event) => {\n try {\n const data =\n typeof event.data === \"string\"\n ? JSON.parse(event.data)\n : event.data;\n this.handleNativeMessage(data);\n } catch (_e) {\n // Ignore non-JSON messages\n }\n });\n }\n }\n\n /**\n * Internal handler for all incoming messages from the native shell.\n * Matches incoming payloads to either pending callbacks or event listeners.\n *\n * @internal\n * @param envelope The message envelope received from native code.\n */\n private handleNativeMessage(envelope: IBridgeEnvelope) {\n if (!envelope || typeof envelope !== \"object\") return;\n\n // 1. Handle Response Callbacks\n if (\n envelope.callbackId &&\n typeof envelope.callbackId === \"string\" &&\n this.callbacks[envelope.callbackId]\n ) {\n const { callbackId } = envelope;\n const { resolve, reject } = this.callbacks[callbackId];\n\n if (envelope.success === false || envelope.error) {\n reject(envelope.error || \"Unknown error\");\n } else {\n resolve(envelope.value ?? envelope.payload ?? envelope);\n }\n\n delete this.callbacks[callbackId];\n return;\n }\n\n // 2. Handle Pushed Events\n if (envelope.event && typeof envelope.event === \"string\") {\n const listeners = this.eventListeners[envelope.event];\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(envelope.payload || envelope.value);\n } catch (e) {\n console.error(`Error in event listener for ${envelope.event}:`, e);\n }\n }\n }\n }\n }\n\n /**\n * Subscribes to a pushed event from the native shell.\n *\n * @param event The event name to listen for.\n * @param callback Function to execute when the event occurs.\n * @returns An unsubscription function.\n */\n public on(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) {\n this.eventListeners[event] = [];\n }\n this.eventListeners[event].push(callback);\n return () => this.off(event, callback);\n }\n\n /**\n * Unsubscribes a specific callback from an event.\n *\n * @param event The event name.\n * @param callback The callback function to remove.\n */\n public off(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) return;\n this.eventListeners[event] = this.eventListeners[event].filter(\n (cb) => cb !== callback,\n );\n }\n\n /**\n * Sends a message to the native shell and waits for a response.\n *\n * @template T The expected response type.\n * @param type The action type (e.g., \"GET_LOCATION\").\n * @param payload Data associated with the action.\n * @returns A promise that resolves with the native response.\n */\n public send<T = unknown>(type: string, payload?: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const callbackId = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.callbacks[callbackId] = {\n reject,\n resolve: resolve as (val: unknown) => void,\n };\n\n const message = {\n callbackId,\n payload,\n type,\n };\n\n const win = window as unknown as {\n ReactNativeWebView?: { postMessage: (msg: string) => void };\n };\n\n if (win.ReactNativeWebView?.postMessage) {\n win.ReactNativeWebView.postMessage(JSON.stringify(message));\n } else {\n console.warn(\n \"UP Bridge not available. Are you running inside the UP Shell?\",\n );\n delete this.callbacks[callbackId];\n reject(new Error(\"Bridge not available\"));\n }\n });\n }\n}\n","import { Bridge } from \"@miniapps-sdk/bridge\";\nimport type {\n HapticStyleType,\n IFidelityBalance,\n IFidelityHistoryParams,\n IFidelityTransaction,\n IInitializationOptions,\n IInitializationResponse,\n ILocationData,\n INetworkOptions,\n INetworkResponse,\n IPaymentRequest,\n IUserProfile,\n ScrollConfig,\n SDKEvent,\n} from \"@miniapps-sdk/types/types\";\n\n/**\n * Main SDK for UP Mini-Apps.\n * Provides access to native device features, storage, identity, and shell UI.\n */\nexport class MiniAppSDK {\n private bridge: Bridge;\n\n constructor() {\n this.bridge = new Bridge();\n }\n\n /**\n * The starting point for the Mini-App. Must be called before any other SDK methods.\n * @param options The options to provide to the shell app\n */\n public initialize(\n options: IInitializationOptions,\n ): Promise<IInitializationResponse> {\n return this.bridge.send(\"INITIALIZE\", options);\n }\n\n /**\n * Local SQLite Storage.\n * Data is persisted on the device and is isolated per Mini-App.\n */\n public storage = {\n /** Retrieves a value by key. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"STORAGE_GET\", { key }),\n /** Retrieves all key-value pairs stored for this Mini-App. */\n getAll: (): Promise<Record<string, string>> =>\n this.bridge.send(\"STORAGE_GET_ALL\"),\n /** Sets a value for a specific key. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"STORAGE_SET\", { key, value }),\n };\n\n /**\n * Hardware-level Secure Storage.\n * Data is stored in the device's secure enclave (Keychain/Keystore) and is isolated per Mini-App.\n */\n public secureStore = {\n /** Retrieves a value by key from secure storage. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"SECURE_GET\", { key }),\n /** Sets a value for a specific key in secure storage. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"SECURE_SET\", { key, value }),\n };\n\n /**\n * Database Storage.\n * Access to user-app specific persistent database storage.\n */\n public database = {\n /** Retrieves the user data stored in the backend database. */\n getUserData: <T = unknown>(): Promise<T> =>\n this.bridge.send<T>(\"DATABASE_GET_USER_DATA\"),\n /** Updates the user data stored in the backend database. */\n setUserData: <T = unknown>(data: T): Promise<void> =>\n this.bridge.send<void>(\"DATABASE_SET_USER_DATA\", { data }),\n };\n\n /**\n * Device Location services.\n */\n public location = {\n /** Retrieves the current GPS position of the device. */\n getCurrentPosition: (): Promise<ILocationData> =>\n this.bridge.send(\"GET_LOCATION\"),\n };\n\n /**\n * Identity & Profile management.\n */\n public user = {\n /**\n * Fetch a short-lived Scoped Identity Token (JWT).\n * This token is signed by the UP Hub and can be verified by your backend.\n * @param scopes Optional list of scopes requested (e.g., ['profile', 'email']).\n */\n getIdentityToken: (scopes?: string[]): Promise<string> =>\n this.bridge.send(\"GET_IDENTITY_TOKEN\", { scopes }),\n /**\n * Fetch user profile data.\n * @param fields Optional list of specific fields to retrieve (e.g., ['fullName', 'username']).\n */\n getProfile: <T extends keyof IUserProfile>(\n fields?: T[],\n ): Promise<Partial<IUserProfile>> =>\n this.bridge.send(\"GET_USER_PROFILE\", { fields }),\n };\n\n /**\n * Explicit Permission Management.\n * Allows requesting access to sensitive device features or user data.\n */\n public permission = {\n /**\n * Explicitly request access to sensitive data.\n * @param type The type of permission to request ('location' or 'profile').\n * @param fields If requesting 'profile', the specific fields required.\n */\n request: ((type: \"location\" | \"profile\", fields?: string[]) => {\n return this.bridge.send(\"REQUEST_PERMISSION\", { fields, type });\n }) as {\n (type: \"location\"): Promise<boolean>;\n (type: \"profile\", fields: (keyof IUserProfile)[]): Promise<boolean>;\n },\n };\n\n /**\n * Payments integration.\n */\n public payment = {\n /**\n * Triggers the native payment flow.\n * @param payload Amount, currency, and itemized list for the payment.\n */\n request: (\n payload: IPaymentRequest,\n ): Promise<{ success: true; transactionId: string }> =>\n this.bridge.send(\"PAYMENT_REQUEST\", payload),\n };\n\n /**\n * Live Activities & Notifications.\n * Allows the Mini-App to display real-time updates in the host shell.\n */\n public activity = {\n /**\n * Starts a new live activity.\n * @param id Unique identifier for the activity.\n * @param title Display title for the activity.\n * @param status Initial status message.\n */\n start: (id: string, title: string, status: string): Promise<void> =>\n this.bridge.send(\"START_ACTIVITY\", { id, status, title }),\n };\n\n /**\n * Haptic feedback.\n */\n public haptic = {\n /**\n * Triggers a haptic vibration on the device.\n * @param style The style of haptic feedback (e.g., 'light', 'medium', 'heavy', 'success', 'warning', 'error').\n */\n trigger: (style: HapticStyleType): Promise<void> =>\n this.bridge.send(\"TRIGGER_HAPTIC\", { style }),\n };\n\n /**\n * Network Proxy.\n * Allows the Mini-App to make network requests through the host shell to bypass CORS or use host-level authentication.\n */\n public network = {\n /**\n * Performs a network request via the host shell.\n * @param options Request method, URL, headers, and body.\n */\n request: (options: INetworkOptions): Promise<INetworkResponse> =>\n this.bridge.send(\"NETWORK_REQUEST\", options),\n };\n\n /**\n * Fidelity & Rewards program integration.\n */\n public fidelity = {\n /** Returns current fidelity balance. */\n getFidelityBalance: (): Promise<IFidelityBalance> =>\n this.bridge.send(\"GET_FIDELITY_BALANCE\"),\n /**\n * Retrieves fidelity transaction history.\n * @param params Filtering and pagination parameters.\n */\n getFidelityHistory: (\n params?: IFidelityHistoryParams,\n ): Promise<IFidelityTransaction[]> =>\n this.bridge.send(\"GET_FIDELITY_HISTORY\", params),\n /**\n * Authorize spending fidelity points (FPoints) via Two-Phase Authorization.\n * @param intentUuid UUID generated by your backend for the transaction.\n */\n spendFPoints: (\n intentUuid: string,\n ): Promise<{ success: boolean; transactionId: string }> =>\n this.bridge.send(\"SPEND_FPOINTS\", { intentUuid }),\n };\n\n /**\n * UI and Navigation controls.\n */\n public ui = {\n /** Closes the Mini-App and returns to the host shell. */\n exit: (): Promise<void> => this.bridge.send(\"EXIT\"),\n /**\n * Configures native scroll behaviors like Pull-to-Refresh and Infinite Scroll.\n * @param config Scroll configuration for top/bottom detection.\n */\n setScrollConfig: (config: ScrollConfig): Promise<void> =>\n this.bridge.send(\"SET_SCROLL_CONFIG\", config),\n };\n\n /**\n * Debug controls\n */\n public debug = {\n /**\n * Log to the shell app\n * @param message\n */\n log: (...message: unknown[]) => this.bridge.send(\"DEBUG_LOG\", { message }),\n };\n\n /**\n * Registers a callback for a specific event from the native shell.\n * @param event The name of the event to listen for.\n * @param callback The function to execute when the event is triggered.\n * @returns A function to unregister the listener.\n */\n public on(event: SDKEvent, callback: (data: unknown) => void) {\n return this.bridge.on(event as string, callback);\n }\n\n /**\n * Unregisters a previously registered event listener.\n * @param event The name of the event.\n * @param callback The callback function to remove.\n */\n public off(event: SDKEvent, callback: (data: unknown) => void) {\n this.bridge.off(event as string, callback);\n }\n}\n\n/**\n * Singleton instance of the MiniAppSDK.\n */\nexport const sdk = new MiniAppSDK();\n","/**\n * UP Mini-App SDK Types\n */\n\n/**\n * Represents the user's profile information.\n */\nexport interface IUserProfile {\n /** Unique identifier for the user. */\n uuid: string;\n /** Full legal name of the user. */\n fullName: string;\n /** Primary email address. */\n email: string;\n /** Chosen username within the UP ecosystem. */\n username: string;\n /** ISO country code (e.g., \"FR\", \"US\"). */\n countryCode: string;\n /** Phone number without country code. */\n localNumber: string;\n}\n\n/**\n * Geographic location data.\n */\nexport interface ILocationData {\n coords: {\n /** Latitude in decimal degrees. */\n latitude: number;\n /** Longitude in decimal degrees. */\n longitude: number;\n /** Altitude in meters above the WGS 84 reference ellipsoid, or null if not available. */\n altitude: number | null;\n /** Accuracy of the latitude and longitude properties in meters. */\n accuracy: number | null;\n /** Accuracy of the altitude property in meters. */\n altitudeAccuracy: number | null;\n /** The direction in which the device is traveling, in degrees (0-360). */\n heading: number | null;\n /** The velocity of the device in meters per second. */\n speed: number | null;\n };\n /** The time at which the location was retrieved (Unix timestamp). */\n timestamp: number;\n}\n\n/**\n * Request payload for triggering a payment flow.\n */\nexport interface IPaymentRequest {\n /** The specific amount to charge. */\n amount: number;\n /** ISO currency code (e.g., \"EUR\", \"USD\"). */\n currency: string;\n /** Total amount including taxes/fees. */\n total: number;\n /** Itemized breakdown of the purchase. */\n items: Array<{\n /** Name or description of the item. */\n item: string;\n /** Price per unit. */\n price?: number;\n /** Number of units. */\n quantity?: number;\n }>;\n}\n\n/**\n * Style of haptic feedback.\n */\nexport type HapticStyleType =\n | \"light\"\n | \"medium\"\n | \"heavy\"\n | \"rigid\"\n | \"soft\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\n/**\n * Network Proxy Types\n */\n\n/**\n * The HTTP method to use as request method\n */\nexport type NetworkMethodType = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configuration for network proxy requests.\n */\nexport interface INetworkOptions {\n /** Full URL for the request. */\n url: string;\n /** HTTP method to use. */\n method: NetworkMethodType;\n /** Request body for POST/PUT/PATCH. */\n body?: unknown;\n /** Custom HTTP headers. */\n headers?: Record<string, string>;\n}\n\n/**\n * Response from a network proxy request.\n */\nexport interface INetworkResponse<T = unknown> {\n /** HTTP status code. */\n status: number;\n /** Response data payload. */\n data: T;\n /** Response headers. */\n headers: Headers;\n}\n\n/**\n * Fidelity & Rewards Types\n */\n\n/**\n * Fidelity program balance information.\n */\nexport interface IFidelityBalance {\n /** Current point or currency balance. */\n balance: number;\n /** Name or symbol of the fidelity currency (e.g., \"FPoints\"). */\n currency: string;\n}\n\n/**\n * Parameters for retrieving fidelity transaction history.\n */\nexport interface IFidelityHistoryParams {\n /** Maximum number of records to return. */\n limit?: number;\n\n /** Cursor for pagination; null for the first page. */\n cursor?: string | null;\n}\n\n/** Type of transaction: credit (add) or debit (remove). */\nexport type FidelityTransactionTypeType = \"credit\" | \"debit\";\n\n/**\n * A single fidelity program transaction.\n */\nexport interface IFidelityTransaction {\n /** Unique identifier for the transaction. */\n id: string;\n /** Amount of the transaction. */\n amount: number;\n /** Human-readable description. */\n description: string;\n /** ISO 8601 date string. */\n date: string;\n /** Type of transaction */\n type: FidelityTransactionTypeType;\n}\n\n/**\n * The initialization options required to set up the Mini-App SDK.\n */\nexport type IInitializationOptions = {};\n\n/**\n * The post initialization response\n */\nexport interface IInitializationResponse<\n Env extends Record<string, unknown> = Record<string, unknown>,\n UserData extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The name of the mini app */\n name: string;\n /** The uuid of the mini app */\n uuid: string;\n /** The description of the mini app */\n description: string;\n /** The authors of the mini app */\n authors?: string;\n /** The current version in the registry */\n version?: string;\n /** The identity token got from the shell's backend */\n identityToken: string;\n /** The scoped profile based on the requested fields during initialization or the getUserProfile call */\n profile: Partial<IUserProfile | null>;\n /** The environment variables defined for the mini app in the shell's backend */\n env: Env;\n /** The user data passed during the initialization or the setUserData call */\n userData: UserData;\n}\n\n/**\n * Events emitted by the UI module.\n */\nexport enum UIEvent {\n /** Triggered when the user performs a native \"Pull-to-Refresh\". */\n TOP_SCROLL_MORE = \"TOP_SCROLL_MORE\",\n /** Triggered when the user scrolls near the bottom of the page (within 200px threshold). */\n BOTTOM_SCROLL_MORE = \"BOTTOM_SCROLL_MORE\",\n}\n\n/**\n * Union type for all SDK events, allowing for both known enums and custom strings.\n * The (string & {}) pattern preserves IntelliSense for enum members.\n */\nexport type SDKEvent = UIEvent | (string & {});\n\n/**\n * Configuration for native scroll interactions managed by the Host Shell.\n */\nexport interface ScrollConfig {\n /** Configuration for Pull-to-Refresh (Top). */\n topScrollMore?: {\n /** Show/hide the native RefreshControl. */\n enabled: boolean;\n /** Set to true to show the loading spinner, false to hide it. */\n refreshing?: boolean;\n };\n /** Configuration for Infinite Scroll (Bottom). */\n bottomScrollMore?: {\n /** Enable/disable bottom scroll detection. */\n enabled: boolean;\n /** If false, detection stops and the indicator is hidden. */\n hasMore?: boolean;\n /** Set to true to show the bottom ActivityIndicator. */\n loadingMore?: boolean;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,SAAN,MAAa;AAAA,EACV,YAGJ,CAAC;AAAA,EACG,iBAA8D,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOvE,cAAc;AACZ,QAAI,OAAO,WAAW,aAAa;AAEjC,MAAC,OAAmD,kBAAkB;AAAA,QACpE,iBAAiB,CAAC,aAChB,KAAK,oBAAoB,QAAQ;AAAA,MACrC;AAGA,aAAO,iBAAiB,WAAW,CAAC,UAAU;AAC5C,YAAI;AACF,gBAAM,OACJ,OAAO,MAAM,SAAS,WAClB,KAAK,MAAM,MAAM,IAAI,IACrB,MAAM;AACZ,eAAK,oBAAoB,IAAI;AAAA,QAC/B,SAAS,IAAI;AAAA,QAEb;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASQ,oBAAoB,UAA2B;AACrD,QAAI,CAA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;;;AH9LZ,IAAO,gBAAQ;","names":["UIEvent"]}
package/dist/index.mjs CHANGED
@@ -36,9 +36,7 @@ var Bridge = class {
36
36
  if (envelope.success === false || envelope.error) {
37
37
  reject(envelope.error || "Unknown error");
38
38
  } else {
39
- resolve(
40
- envelope.value !== void 0 ? envelope.value : envelope.payload || envelope
41
- );
39
+ resolve(envelope.value ?? envelope.payload ?? envelope);
42
40
  }
43
41
  delete this.callbacks[callbackId];
44
42
  return;
@@ -151,6 +149,16 @@ var MiniAppSDK = class {
151
149
  /** Sets a value for a specific key in secure storage. */
152
150
  set: (key, value) => this.bridge.send("SECURE_SET", { key, value })
153
151
  };
152
+ /**
153
+ * Database Storage.
154
+ * Access to user-app specific persistent database storage.
155
+ */
156
+ database = {
157
+ /** Retrieves the user data stored in the backend database. */
158
+ getUserData: () => this.bridge.send("DATABASE_GET_USER_DATA"),
159
+ /** Updates the user data stored in the backend database. */
160
+ setUserData: (data) => this.bridge.send("DATABASE_SET_USER_DATA", { data })
161
+ };
154
162
  /**
155
163
  * Device Location services.
156
164
  */
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bridge.ts","../src/sdk.ts","../src/types/types.ts","../src/index.ts"],"sourcesContent":["import type { IBridgeEnvelope } from \"@miniapps-sdk/types\";\n\n/**\n * The Bridge handles low-level communication between the Mini-App WebView\n * and the Native Host Shell (iOS/Android).\n *\n * It manages asynchronous request-response cycles via callbacks and\n * supports subscription to pushed events from the native environment.\n */\nexport class Bridge {\n private callbacks: Record<\n string,\n { resolve: (val: unknown) => void; reject: (err: unknown) => void }\n > = {};\n private eventListeners: Record<string, ((data: unknown) => void)[]> = {};\n\n /**\n * Registers a global listener for messages coming from the native shell.\n * Also listens for standard browser `message` events to support multiple\n * communication channels (e.g., React Native WebView postMessage).\n */\n constructor() {\n if (typeof window !== \"undefined\") {\n // Set up the global bridge receiver for React Native WebView\n (window as unknown as { __MiniAppBridge: unknown }).__MiniAppBridge = {\n onNativeMessage: (envelope: IBridgeEnvelope) =>\n this.handleNativeMessage(envelope),\n };\n\n // Also listen for postMessage events\n window.addEventListener(\"message\", (event) => {\n try {\n const data =\n typeof event.data === \"string\"\n ? JSON.parse(event.data)\n : event.data;\n this.handleNativeMessage(data);\n } catch (_e) {\n // Ignore non-JSON messages\n }\n });\n }\n }\n\n /**\n * Internal handler for all incoming messages from the native shell.\n * Matches incoming payloads to either pending callbacks or event listeners.\n *\n * @internal\n * @param envelope The message envelope received from native code.\n */\n private handleNativeMessage(envelope: IBridgeEnvelope) {\n if (!envelope || typeof envelope !== \"object\") return;\n\n // 1. Handle Response Callbacks\n if (\n envelope.callbackId &&\n typeof envelope.callbackId === \"string\" &&\n this.callbacks[envelope.callbackId]\n ) {\n const { callbackId } = envelope;\n const { resolve, reject } = this.callbacks[callbackId];\n\n if (envelope.success === false || envelope.error) {\n reject(envelope.error || \"Unknown error\");\n } else {\n resolve(\n envelope.value !== undefined\n ? envelope.value\n : envelope.payload || envelope,\n );\n }\n\n delete this.callbacks[callbackId];\n return;\n }\n\n // 2. Handle Pushed Events\n if (envelope.event && typeof envelope.event === \"string\") {\n const listeners = this.eventListeners[envelope.event];\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(envelope.payload || envelope.value);\n } catch (e) {\n console.error(`Error in event listener for ${envelope.event}:`, e);\n }\n }\n }\n }\n }\n\n /**\n * Subscribes to a pushed event from the native shell.\n *\n * @param event The event name to listen for.\n * @param callback Function to execute when the event occurs.\n * @returns An unsubscription function.\n */\n public on(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) {\n this.eventListeners[event] = [];\n }\n this.eventListeners[event].push(callback);\n return () => this.off(event, callback);\n }\n\n /**\n * Unsubscribes a specific callback from an event.\n *\n * @param event The event name.\n * @param callback The callback function to remove.\n */\n public off(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) return;\n this.eventListeners[event] = this.eventListeners[event].filter(\n (cb) => cb !== callback,\n );\n }\n\n /**\n * Sends a message to the native shell and waits for a response.\n *\n * @template T The expected response type.\n * @param type The action type (e.g., \"GET_LOCATION\").\n * @param payload Data associated with the action.\n * @returns A promise that resolves with the native response.\n */\n public send<T = unknown>(type: string, payload?: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const callbackId = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.callbacks[callbackId] = {\n reject,\n resolve: resolve as (val: unknown) => void,\n };\n\n const message = {\n callbackId,\n payload,\n type,\n };\n\n const win = window as unknown as {\n ReactNativeWebView?: { postMessage: (msg: string) => void };\n };\n\n if (win.ReactNativeWebView?.postMessage) {\n win.ReactNativeWebView.postMessage(JSON.stringify(message));\n } else {\n console.warn(\n \"UP Bridge not available. Are you running inside the UP Shell?\",\n );\n delete this.callbacks[callbackId];\n reject(new Error(\"Bridge not available\"));\n }\n });\n }\n}\n","import { Bridge } from \"@miniapps-sdk/bridge\";\nimport type {\n HapticStyleType,\n IFidelityBalance,\n IFidelityHistoryParams,\n IFidelityTransaction,\n IInitializationOptions,\n IInitializationResponse,\n ILocationData,\n INetworkOptions,\n INetworkResponse,\n IPaymentRequest,\n IUserProfile,\n ScrollConfig,\n SDKEvent,\n} from \"@miniapps-sdk/types/types\";\n\n/**\n * Main SDK for UP Mini-Apps.\n * Provides access to native device features, storage, identity, and shell UI.\n */\nexport class MiniAppSDK {\n private bridge: Bridge;\n\n constructor() {\n this.bridge = new Bridge();\n }\n\n /**\n * The starting point for the Mini-App. Must be called before any other SDK methods.\n * @param options The options to provide to the shell app\n */\n public initialize(\n options: IInitializationOptions,\n ): Promise<IInitializationResponse> {\n return this.bridge.send(\"INITIALIZE\", options);\n }\n\n /**\n * Local SQLite Storage.\n * Data is persisted on the device and is isolated per Mini-App.\n */\n public storage = {\n /** Retrieves a value by key. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"STORAGE_GET\", { key }),\n /** Retrieves all key-value pairs stored for this Mini-App. */\n getAll: (): Promise<Record<string, string>> =>\n this.bridge.send(\"STORAGE_GET_ALL\"),\n /** Sets a value for a specific key. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"STORAGE_SET\", { key, value }),\n };\n\n /**\n * Hardware-level Secure Storage.\n * Data is stored in the device's secure enclave (Keychain/Keystore) and is isolated per Mini-App.\n */\n public secureStore = {\n /** Retrieves a value by key from secure storage. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"SECURE_GET\", { key }),\n /** Sets a value for a specific key in secure storage. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"SECURE_SET\", { key, value }),\n };\n\n /**\n * Device Location services.\n */\n public location = {\n /** Retrieves the current GPS position of the device. */\n getCurrentPosition: (): Promise<ILocationData> =>\n this.bridge.send(\"GET_LOCATION\"),\n };\n\n /**\n * Identity & Profile management.\n */\n public user = {\n /**\n * Fetch a short-lived Scoped Identity Token (JWT).\n * This token is signed by the UP Hub and can be verified by your backend.\n * @param scopes Optional list of scopes requested (e.g., ['profile', 'email']).\n */\n getIdentityToken: (scopes?: string[]): Promise<string> =>\n this.bridge.send(\"GET_IDENTITY_TOKEN\", { scopes }),\n /**\n * Fetch user profile data.\n * @param fields Optional list of specific fields to retrieve (e.g., ['fullName', 'username']).\n */\n getProfile: <T extends keyof IUserProfile>(\n fields?: T[],\n ): Promise<Partial<IUserProfile>> =>\n this.bridge.send(\"GET_USER_PROFILE\", { fields }),\n };\n\n /**\n * Explicit Permission Management.\n * Allows requesting access to sensitive device features or user data.\n */\n public permission = {\n /**\n * Explicitly request access to sensitive data.\n * @param type The type of permission to request ('location' or 'profile').\n * @param fields If requesting 'profile', the specific fields required.\n */\n request: ((type: \"location\" | \"profile\", fields?: string[]) => {\n return this.bridge.send(\"REQUEST_PERMISSION\", { fields, type });\n }) as {\n (type: \"location\"): Promise<boolean>;\n (type: \"profile\", fields: (keyof IUserProfile)[]): Promise<boolean>;\n },\n };\n\n /**\n * Payments integration.\n */\n public payment = {\n /**\n * Triggers the native payment flow.\n * @param payload Amount, currency, and itemized list for the payment.\n */\n request: (\n payload: IPaymentRequest,\n ): Promise<{ success: true; transactionId: string }> =>\n this.bridge.send(\"PAYMENT_REQUEST\", payload),\n };\n\n /**\n * Live Activities & Notifications.\n * Allows the Mini-App to display real-time updates in the host shell.\n */\n public activity = {\n /**\n * Starts a new live activity.\n * @param id Unique identifier for the activity.\n * @param title Display title for the activity.\n * @param status Initial status message.\n */\n start: (id: string, title: string, status: string): Promise<void> =>\n this.bridge.send(\"START_ACTIVITY\", { id, status, title }),\n };\n\n /**\n * Haptic feedback.\n */\n public haptic = {\n /**\n * Triggers a haptic vibration on the device.\n * @param style The style of haptic feedback (e.g., 'light', 'medium', 'heavy', 'success', 'warning', 'error').\n */\n trigger: (style: HapticStyleType): Promise<void> =>\n this.bridge.send(\"TRIGGER_HAPTIC\", { style }),\n };\n\n /**\n * Network Proxy.\n * Allows the Mini-App to make network requests through the host shell to bypass CORS or use host-level authentication.\n */\n public network = {\n /**\n * Performs a network request via the host shell.\n * @param options Request method, URL, headers, and body.\n */\n request: (options: INetworkOptions): Promise<INetworkResponse> =>\n this.bridge.send(\"NETWORK_REQUEST\", options),\n };\n\n /**\n * Fidelity & Rewards program integration.\n */\n public fidelity = {\n /** Returns current fidelity balance. */\n getFidelityBalance: (): Promise<IFidelityBalance> =>\n this.bridge.send(\"GET_FIDELITY_BALANCE\"),\n /**\n * Retrieves fidelity transaction history.\n * @param params Filtering and pagination parameters.\n */\n getFidelityHistory: (\n params?: IFidelityHistoryParams,\n ): Promise<IFidelityTransaction[]> =>\n this.bridge.send(\"GET_FIDELITY_HISTORY\", params),\n /**\n * Authorize spending fidelity points (FPoints) via Two-Phase Authorization.\n * @param intentUuid UUID generated by your backend for the transaction.\n */\n spendFPoints: (\n intentUuid: string,\n ): Promise<{ success: boolean; transactionId: string }> =>\n this.bridge.send(\"SPEND_FPOINTS\", { intentUuid }),\n };\n\n /**\n * UI and Navigation controls.\n */\n public ui = {\n /** Closes the Mini-App and returns to the host shell. */\n exit: (): Promise<void> => this.bridge.send(\"EXIT\"),\n /**\n * Configures native scroll behaviors like Pull-to-Refresh and Infinite Scroll.\n * @param config Scroll configuration for top/bottom detection.\n */\n setScrollConfig: (config: ScrollConfig): Promise<void> =>\n this.bridge.send(\"SET_SCROLL_CONFIG\", config),\n };\n\n /**\n * Debug controls\n */\n public debug = {\n /**\n * Log to the shell app\n * @param message\n */\n log: (...message: unknown[]) => this.bridge.send(\"DEBUG_LOG\", { message }),\n };\n\n /**\n * Registers a callback for a specific event from the native shell.\n * @param event The name of the event to listen for.\n * @param callback The function to execute when the event is triggered.\n * @returns A function to unregister the listener.\n */\n public on(event: SDKEvent, callback: (data: unknown) => void) {\n return this.bridge.on(event as string, callback);\n }\n\n /**\n * Unregisters a previously registered event listener.\n * @param event The name of the event.\n * @param callback The callback function to remove.\n */\n public off(event: SDKEvent, callback: (data: unknown) => void) {\n this.bridge.off(event as string, callback);\n }\n}\n\n/**\n * Singleton instance of the MiniAppSDK.\n */\nexport const sdk = new MiniAppSDK();\n","/**\n * UP Mini-App SDK Types\n */\n\n/**\n * Represents the user's profile information.\n */\nexport interface IUserProfile {\n /** Unique identifier for the user. */\n uuid: string;\n /** Full legal name of the user. */\n fullName: string;\n /** Primary email address. */\n email: string;\n /** Chosen username within the UP ecosystem. */\n username: string;\n /** ISO country code (e.g., \"FR\", \"US\"). */\n countryCode: string;\n /** Phone number without country code. */\n localNumber: string;\n}\n\n/**\n * Geographic location data.\n */\nexport interface ILocationData {\n coords: {\n /** Latitude in decimal degrees. */\n latitude: number;\n /** Longitude in decimal degrees. */\n longitude: number;\n /** Altitude in meters above the WGS 84 reference ellipsoid, or null if not available. */\n altitude: number | null;\n /** Accuracy of the latitude and longitude properties in meters. */\n accuracy: number | null;\n /** Accuracy of the altitude property in meters. */\n altitudeAccuracy: number | null;\n /** The direction in which the device is traveling, in degrees (0-360). */\n heading: number | null;\n /** The velocity of the device in meters per second. */\n speed: number | null;\n };\n /** The time at which the location was retrieved (Unix timestamp). */\n timestamp: number;\n}\n\n/**\n * Request payload for triggering a payment flow.\n */\nexport interface IPaymentRequest {\n /** The specific amount to charge. */\n amount: number;\n /** ISO currency code (e.g., \"EUR\", \"USD\"). */\n currency: string;\n /** Total amount including taxes/fees. */\n total: number;\n /** Itemized breakdown of the purchase. */\n items: Array<{\n /** Name or description of the item. */\n item: string;\n /** Price per unit. */\n price?: number;\n /** Number of units. */\n quantity?: number;\n }>;\n}\n\n/**\n * Style of haptic feedback.\n */\nexport type HapticStyleType =\n | \"light\"\n | \"medium\"\n | \"heavy\"\n | \"rigid\"\n | \"soft\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\n/**\n * Network Proxy Types\n */\n\n/**\n * The HTTP method to use as request method\n */\nexport type NetworkMethodType = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configuration for network proxy requests.\n */\nexport interface INetworkOptions {\n /** Full URL for the request. */\n url: string;\n /** HTTP method to use. */\n method: NetworkMethodType;\n /** Request body for POST/PUT/PATCH. */\n body?: unknown;\n /** Custom HTTP headers. */\n headers?: Record<string, string>;\n}\n\n/**\n * Response from a network proxy request.\n */\nexport interface INetworkResponse {\n /** HTTP status code. */\n status: number;\n /** Response data payload. */\n data: unknown;\n /** Response headers. */\n headers: Record<string, string>;\n}\n\n/**\n * Fidelity & Rewards Types\n */\n\n/**\n * Fidelity program balance information.\n */\nexport interface IFidelityBalance {\n /** Current point or currency balance. */\n balance: number;\n /** Name or symbol of the fidelity currency (e.g., \"FPoints\"). */\n currency: string;\n}\n\n/**\n * Parameters for retrieving fidelity transaction history.\n */\nexport interface IFidelityHistoryParams {\n /** Maximum number of records to return. */\n limit?: number;\n /** Number of records to skip. */\n offset?: number;\n}\n\n/** Type of transaction: credit (add) or debit (remove). */\nexport type FidelityTransactionTypeType = \"credit\" | \"debit\";\n\n/**\n * A single fidelity program transaction.\n */\nexport interface IFidelityTransaction {\n /** Unique identifier for the transaction. */\n id: string;\n /** Amount of the transaction. */\n amount: number;\n /** Human-readable description. */\n description: string;\n /** ISO 8601 date string. */\n date: string;\n /** Type of transaction */\n type: FidelityTransactionTypeType;\n}\n\n/**\n * The initialization options required to set up the Mini-App SDK.\n */\nexport type IInitializationOptions = {};\n\n/**\n * The post initialization response\n */\nexport interface IInitializationResponse {\n /** The name of the mini app */\n name: string;\n /** The uuid of the mini app */\n uuid: string;\n /** The description of the mini app */\n description: string;\n /** The authors of the mini app */\n authors?: string;\n /** The current version in the registry */\n version?: string;\n}\n\n/**\n * Events emitted by the UI module.\n */\nexport enum UIEvent {\n /** Triggered when the user performs a native \"Pull-to-Refresh\". */\n TOP_SCROLL_MORE = \"TOP_SCROLL_MORE\",\n /** Triggered when the user scrolls near the bottom of the page (within 200px threshold). */\n BOTTOM_SCROLL_MORE = \"BOTTOM_SCROLL_MORE\",\n}\n\n/**\n * Union type for all SDK events, allowing for both known enums and custom strings.\n * The (string & {}) pattern preserves IntelliSense for enum members.\n */\nexport type SDKEvent = UIEvent | (string & {});\n\n/**\n * Configuration for native scroll interactions managed by the Host Shell.\n */\nexport interface ScrollConfig {\n /** Configuration for Pull-to-Refresh (Top). */\n topScrollMore?: {\n /** Show/hide the native RefreshControl. */\n enabled: boolean;\n /** Set to true to show the loading spinner, false to hide it. */\n refreshing?: boolean;\n };\n /** Configuration for Infinite Scroll (Bottom). */\n bottomScrollMore?: {\n /** Enable/disable bottom scroll detection. */\n enabled: boolean;\n /** If false, detection stops and the indicator is hidden. */\n hasMore?: boolean;\n /** Set to true to show the bottom ActivityIndicator. */\n loadingMore?: boolean;\n };\n}\n","export { MiniAppSDK, sdk } from \"@miniapps-sdk/sdk\";\nexport * from \"@miniapps-sdk/types\";\n\nimport { sdk } from \"@miniapps-sdk/sdk\";\nexport default sdk;\n"],"mappings":";AASO,IAAM,SAAN,MAAa;AAAA,EACV,YAGJ,CAAC;AAAA,EACG,iBAA8D,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOvE,cAAc;AACZ,QAAI,OAAO,WAAW,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AA;AAAA;AAAA,EAOO,IAAI,OAAiB,UAAmC;AAC7D,SAAK,OAAO,IAAI,OAAiB,QAAQ;AAAA,EAC3C;AACF;AAKO,IAAM,MAAM,IAAI,WAAW;;;AC5D3B,IAAK,UAAL,kBAAKA,aAAL;AAEL,EAAAA,SAAA,qBAAkB;AAElB,EAAAA,SAAA,wBAAqB;AAJX,SAAAA;AAAA,GAAA;;;AClLZ,IAAO,gBAAQ;","names":["UIEvent"]}
1
+ {"version":3,"sources":["../src/bridge.ts","../src/sdk.ts","../src/types/types.ts","../src/index.ts"],"sourcesContent":["import type { IBridgeEnvelope } from \"@miniapps-sdk/types\";\n\n/**\n * The Bridge handles low-level communication between the Mini-App WebView\n * and the Native Host Shell (iOS/Android).\n *\n * It manages asynchronous request-response cycles via callbacks and\n * supports subscription to pushed events from the native environment.\n */\nexport class Bridge {\n private callbacks: Record<\n string,\n { resolve: (val: unknown) => void; reject: (err: unknown) => void }\n > = {};\n private eventListeners: Record<string, ((data: unknown) => void)[]> = {};\n\n /**\n * Registers a global listener for messages coming from the native shell.\n * Also listens for standard browser `message` events to support multiple\n * communication channels (e.g., React Native WebView postMessage).\n */\n constructor() {\n if (typeof window !== \"undefined\") {\n // Set up the global bridge receiver for React Native WebView\n (window as unknown as { __MiniAppBridge: unknown }).__MiniAppBridge = {\n onNativeMessage: (envelope: IBridgeEnvelope) =>\n this.handleNativeMessage(envelope),\n };\n\n // Also listen for postMessage events\n window.addEventListener(\"message\", (event) => {\n try {\n const data =\n typeof event.data === \"string\"\n ? JSON.parse(event.data)\n : event.data;\n this.handleNativeMessage(data);\n } catch (_e) {\n // Ignore non-JSON messages\n }\n });\n }\n }\n\n /**\n * Internal handler for all incoming messages from the native shell.\n * Matches incoming payloads to either pending callbacks or event listeners.\n *\n * @internal\n * @param envelope The message envelope received from native code.\n */\n private handleNativeMessage(envelope: IBridgeEnvelope) {\n if (!envelope || typeof envelope !== \"object\") return;\n\n // 1. Handle Response Callbacks\n if (\n envelope.callbackId &&\n typeof envelope.callbackId === \"string\" &&\n this.callbacks[envelope.callbackId]\n ) {\n const { callbackId } = envelope;\n const { resolve, reject } = this.callbacks[callbackId];\n\n if (envelope.success === false || envelope.error) {\n reject(envelope.error || \"Unknown error\");\n } else {\n resolve(envelope.value ?? envelope.payload ?? envelope);\n }\n\n delete this.callbacks[callbackId];\n return;\n }\n\n // 2. Handle Pushed Events\n if (envelope.event && typeof envelope.event === \"string\") {\n const listeners = this.eventListeners[envelope.event];\n if (listeners) {\n for (const listener of listeners) {\n try {\n listener(envelope.payload || envelope.value);\n } catch (e) {\n console.error(`Error in event listener for ${envelope.event}:`, e);\n }\n }\n }\n }\n }\n\n /**\n * Subscribes to a pushed event from the native shell.\n *\n * @param event The event name to listen for.\n * @param callback Function to execute when the event occurs.\n * @returns An unsubscription function.\n */\n public on(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) {\n this.eventListeners[event] = [];\n }\n this.eventListeners[event].push(callback);\n return () => this.off(event, callback);\n }\n\n /**\n * Unsubscribes a specific callback from an event.\n *\n * @param event The event name.\n * @param callback The callback function to remove.\n */\n public off(event: string, callback: (data: unknown) => void) {\n if (!this.eventListeners[event]) return;\n this.eventListeners[event] = this.eventListeners[event].filter(\n (cb) => cb !== callback,\n );\n }\n\n /**\n * Sends a message to the native shell and waits for a response.\n *\n * @template T The expected response type.\n * @param type The action type (e.g., \"GET_LOCATION\").\n * @param payload Data associated with the action.\n * @returns A promise that resolves with the native response.\n */\n public send<T = unknown>(type: string, payload?: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const callbackId = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n this.callbacks[callbackId] = {\n reject,\n resolve: resolve as (val: unknown) => void,\n };\n\n const message = {\n callbackId,\n payload,\n type,\n };\n\n const win = window as unknown as {\n ReactNativeWebView?: { postMessage: (msg: string) => void };\n };\n\n if (win.ReactNativeWebView?.postMessage) {\n win.ReactNativeWebView.postMessage(JSON.stringify(message));\n } else {\n console.warn(\n \"UP Bridge not available. Are you running inside the UP Shell?\",\n );\n delete this.callbacks[callbackId];\n reject(new Error(\"Bridge not available\"));\n }\n });\n }\n}\n","import { Bridge } from \"@miniapps-sdk/bridge\";\nimport type {\n HapticStyleType,\n IFidelityBalance,\n IFidelityHistoryParams,\n IFidelityTransaction,\n IInitializationOptions,\n IInitializationResponse,\n ILocationData,\n INetworkOptions,\n INetworkResponse,\n IPaymentRequest,\n IUserProfile,\n ScrollConfig,\n SDKEvent,\n} from \"@miniapps-sdk/types/types\";\n\n/**\n * Main SDK for UP Mini-Apps.\n * Provides access to native device features, storage, identity, and shell UI.\n */\nexport class MiniAppSDK {\n private bridge: Bridge;\n\n constructor() {\n this.bridge = new Bridge();\n }\n\n /**\n * The starting point for the Mini-App. Must be called before any other SDK methods.\n * @param options The options to provide to the shell app\n */\n public initialize(\n options: IInitializationOptions,\n ): Promise<IInitializationResponse> {\n return this.bridge.send(\"INITIALIZE\", options);\n }\n\n /**\n * Local SQLite Storage.\n * Data is persisted on the device and is isolated per Mini-App.\n */\n public storage = {\n /** Retrieves a value by key. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"STORAGE_GET\", { key }),\n /** Retrieves all key-value pairs stored for this Mini-App. */\n getAll: (): Promise<Record<string, string>> =>\n this.bridge.send(\"STORAGE_GET_ALL\"),\n /** Sets a value for a specific key. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"STORAGE_SET\", { key, value }),\n };\n\n /**\n * Hardware-level Secure Storage.\n * Data is stored in the device's secure enclave (Keychain/Keystore) and is isolated per Mini-App.\n */\n public secureStore = {\n /** Retrieves a value by key from secure storage. */\n get: (key: string): Promise<string | null> =>\n this.bridge.send(\"SECURE_GET\", { key }),\n /** Sets a value for a specific key in secure storage. */\n set: (key: string, value: string): Promise<void> =>\n this.bridge.send(\"SECURE_SET\", { key, value }),\n };\n\n /**\n * Database Storage.\n * Access to user-app specific persistent database storage.\n */\n public database = {\n /** Retrieves the user data stored in the backend database. */\n getUserData: <T = unknown>(): Promise<T> =>\n this.bridge.send<T>(\"DATABASE_GET_USER_DATA\"),\n /** Updates the user data stored in the backend database. */\n setUserData: <T = unknown>(data: T): Promise<void> =>\n this.bridge.send<void>(\"DATABASE_SET_USER_DATA\", { data }),\n };\n\n /**\n * Device Location services.\n */\n public location = {\n /** Retrieves the current GPS position of the device. */\n getCurrentPosition: (): Promise<ILocationData> =>\n this.bridge.send(\"GET_LOCATION\"),\n };\n\n /**\n * Identity & Profile management.\n */\n public user = {\n /**\n * Fetch a short-lived Scoped Identity Token (JWT).\n * This token is signed by the UP Hub and can be verified by your backend.\n * @param scopes Optional list of scopes requested (e.g., ['profile', 'email']).\n */\n getIdentityToken: (scopes?: string[]): Promise<string> =>\n this.bridge.send(\"GET_IDENTITY_TOKEN\", { scopes }),\n /**\n * Fetch user profile data.\n * @param fields Optional list of specific fields to retrieve (e.g., ['fullName', 'username']).\n */\n getProfile: <T extends keyof IUserProfile>(\n fields?: T[],\n ): Promise<Partial<IUserProfile>> =>\n this.bridge.send(\"GET_USER_PROFILE\", { fields }),\n };\n\n /**\n * Explicit Permission Management.\n * Allows requesting access to sensitive device features or user data.\n */\n public permission = {\n /**\n * Explicitly request access to sensitive data.\n * @param type The type of permission to request ('location' or 'profile').\n * @param fields If requesting 'profile', the specific fields required.\n */\n request: ((type: \"location\" | \"profile\", fields?: string[]) => {\n return this.bridge.send(\"REQUEST_PERMISSION\", { fields, type });\n }) as {\n (type: \"location\"): Promise<boolean>;\n (type: \"profile\", fields: (keyof IUserProfile)[]): Promise<boolean>;\n },\n };\n\n /**\n * Payments integration.\n */\n public payment = {\n /**\n * Triggers the native payment flow.\n * @param payload Amount, currency, and itemized list for the payment.\n */\n request: (\n payload: IPaymentRequest,\n ): Promise<{ success: true; transactionId: string }> =>\n this.bridge.send(\"PAYMENT_REQUEST\", payload),\n };\n\n /**\n * Live Activities & Notifications.\n * Allows the Mini-App to display real-time updates in the host shell.\n */\n public activity = {\n /**\n * Starts a new live activity.\n * @param id Unique identifier for the activity.\n * @param title Display title for the activity.\n * @param status Initial status message.\n */\n start: (id: string, title: string, status: string): Promise<void> =>\n this.bridge.send(\"START_ACTIVITY\", { id, status, title }),\n };\n\n /**\n * Haptic feedback.\n */\n public haptic = {\n /**\n * Triggers a haptic vibration on the device.\n * @param style The style of haptic feedback (e.g., 'light', 'medium', 'heavy', 'success', 'warning', 'error').\n */\n trigger: (style: HapticStyleType): Promise<void> =>\n this.bridge.send(\"TRIGGER_HAPTIC\", { style }),\n };\n\n /**\n * Network Proxy.\n * Allows the Mini-App to make network requests through the host shell to bypass CORS or use host-level authentication.\n */\n public network = {\n /**\n * Performs a network request via the host shell.\n * @param options Request method, URL, headers, and body.\n */\n request: (options: INetworkOptions): Promise<INetworkResponse> =>\n this.bridge.send(\"NETWORK_REQUEST\", options),\n };\n\n /**\n * Fidelity & Rewards program integration.\n */\n public fidelity = {\n /** Returns current fidelity balance. */\n getFidelityBalance: (): Promise<IFidelityBalance> =>\n this.bridge.send(\"GET_FIDELITY_BALANCE\"),\n /**\n * Retrieves fidelity transaction history.\n * @param params Filtering and pagination parameters.\n */\n getFidelityHistory: (\n params?: IFidelityHistoryParams,\n ): Promise<IFidelityTransaction[]> =>\n this.bridge.send(\"GET_FIDELITY_HISTORY\", params),\n /**\n * Authorize spending fidelity points (FPoints) via Two-Phase Authorization.\n * @param intentUuid UUID generated by your backend for the transaction.\n */\n spendFPoints: (\n intentUuid: string,\n ): Promise<{ success: boolean; transactionId: string }> =>\n this.bridge.send(\"SPEND_FPOINTS\", { intentUuid }),\n };\n\n /**\n * UI and Navigation controls.\n */\n public ui = {\n /** Closes the Mini-App and returns to the host shell. */\n exit: (): Promise<void> => this.bridge.send(\"EXIT\"),\n /**\n * Configures native scroll behaviors like Pull-to-Refresh and Infinite Scroll.\n * @param config Scroll configuration for top/bottom detection.\n */\n setScrollConfig: (config: ScrollConfig): Promise<void> =>\n this.bridge.send(\"SET_SCROLL_CONFIG\", config),\n };\n\n /**\n * Debug controls\n */\n public debug = {\n /**\n * Log to the shell app\n * @param message\n */\n log: (...message: unknown[]) => this.bridge.send(\"DEBUG_LOG\", { message }),\n };\n\n /**\n * Registers a callback for a specific event from the native shell.\n * @param event The name of the event to listen for.\n * @param callback The function to execute when the event is triggered.\n * @returns A function to unregister the listener.\n */\n public on(event: SDKEvent, callback: (data: unknown) => void) {\n return this.bridge.on(event as string, callback);\n }\n\n /**\n * Unregisters a previously registered event listener.\n * @param event The name of the event.\n * @param callback The callback function to remove.\n */\n public off(event: SDKEvent, callback: (data: unknown) => void) {\n this.bridge.off(event as string, callback);\n }\n}\n\n/**\n * Singleton instance of the MiniAppSDK.\n */\nexport const sdk = new MiniAppSDK();\n","/**\n * UP Mini-App SDK Types\n */\n\n/**\n * Represents the user's profile information.\n */\nexport interface IUserProfile {\n /** Unique identifier for the user. */\n uuid: string;\n /** Full legal name of the user. */\n fullName: string;\n /** Primary email address. */\n email: string;\n /** Chosen username within the UP ecosystem. */\n username: string;\n /** ISO country code (e.g., \"FR\", \"US\"). */\n countryCode: string;\n /** Phone number without country code. */\n localNumber: string;\n}\n\n/**\n * Geographic location data.\n */\nexport interface ILocationData {\n coords: {\n /** Latitude in decimal degrees. */\n latitude: number;\n /** Longitude in decimal degrees. */\n longitude: number;\n /** Altitude in meters above the WGS 84 reference ellipsoid, or null if not available. */\n altitude: number | null;\n /** Accuracy of the latitude and longitude properties in meters. */\n accuracy: number | null;\n /** Accuracy of the altitude property in meters. */\n altitudeAccuracy: number | null;\n /** The direction in which the device is traveling, in degrees (0-360). */\n heading: number | null;\n /** The velocity of the device in meters per second. */\n speed: number | null;\n };\n /** The time at which the location was retrieved (Unix timestamp). */\n timestamp: number;\n}\n\n/**\n * Request payload for triggering a payment flow.\n */\nexport interface IPaymentRequest {\n /** The specific amount to charge. */\n amount: number;\n /** ISO currency code (e.g., \"EUR\", \"USD\"). */\n currency: string;\n /** Total amount including taxes/fees. */\n total: number;\n /** Itemized breakdown of the purchase. */\n items: Array<{\n /** Name or description of the item. */\n item: string;\n /** Price per unit. */\n price?: number;\n /** Number of units. */\n quantity?: number;\n }>;\n}\n\n/**\n * Style of haptic feedback.\n */\nexport type HapticStyleType =\n | \"light\"\n | \"medium\"\n | \"heavy\"\n | \"rigid\"\n | \"soft\"\n | \"success\"\n | \"warning\"\n | \"error\";\n\n/**\n * Network Proxy Types\n */\n\n/**\n * The HTTP method to use as request method\n */\nexport type NetworkMethodType = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/**\n * Configuration for network proxy requests.\n */\nexport interface INetworkOptions {\n /** Full URL for the request. */\n url: string;\n /** HTTP method to use. */\n method: NetworkMethodType;\n /** Request body for POST/PUT/PATCH. */\n body?: unknown;\n /** Custom HTTP headers. */\n headers?: Record<string, string>;\n}\n\n/**\n * Response from a network proxy request.\n */\nexport interface INetworkResponse<T = unknown> {\n /** HTTP status code. */\n status: number;\n /** Response data payload. */\n data: T;\n /** Response headers. */\n headers: Headers;\n}\n\n/**\n * Fidelity & Rewards Types\n */\n\n/**\n * Fidelity program balance information.\n */\nexport interface IFidelityBalance {\n /** Current point or currency balance. */\n balance: number;\n /** Name or symbol of the fidelity currency (e.g., \"FPoints\"). */\n currency: string;\n}\n\n/**\n * Parameters for retrieving fidelity transaction history.\n */\nexport interface IFidelityHistoryParams {\n /** Maximum number of records to return. */\n limit?: number;\n\n /** Cursor for pagination; null for the first page. */\n cursor?: string | null;\n}\n\n/** Type of transaction: credit (add) or debit (remove). */\nexport type FidelityTransactionTypeType = \"credit\" | \"debit\";\n\n/**\n * A single fidelity program transaction.\n */\nexport interface IFidelityTransaction {\n /** Unique identifier for the transaction. */\n id: string;\n /** Amount of the transaction. */\n amount: number;\n /** Human-readable description. */\n description: string;\n /** ISO 8601 date string. */\n date: string;\n /** Type of transaction */\n type: FidelityTransactionTypeType;\n}\n\n/**\n * The initialization options required to set up the Mini-App SDK.\n */\nexport type IInitializationOptions = {};\n\n/**\n * The post initialization response\n */\nexport interface IInitializationResponse<\n Env extends Record<string, unknown> = Record<string, unknown>,\n UserData extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** The name of the mini app */\n name: string;\n /** The uuid of the mini app */\n uuid: string;\n /** The description of the mini app */\n description: string;\n /** The authors of the mini app */\n authors?: string;\n /** The current version in the registry */\n version?: string;\n /** The identity token got from the shell's backend */\n identityToken: string;\n /** The scoped profile based on the requested fields during initialization or the getUserProfile call */\n profile: Partial<IUserProfile | null>;\n /** The environment variables defined for the mini app in the shell's backend */\n env: Env;\n /** The user data passed during the initialization or the setUserData call */\n userData: UserData;\n}\n\n/**\n * Events emitted by the UI module.\n */\nexport enum UIEvent {\n /** Triggered when the user performs a native \"Pull-to-Refresh\". */\n TOP_SCROLL_MORE = \"TOP_SCROLL_MORE\",\n /** Triggered when the user scrolls near the bottom of the page (within 200px threshold). */\n BOTTOM_SCROLL_MORE = \"BOTTOM_SCROLL_MORE\",\n}\n\n/**\n * Union type for all SDK events, allowing for both known enums and custom strings.\n * The (string & {}) pattern preserves IntelliSense for enum members.\n */\nexport type SDKEvent = UIEvent | (string & {});\n\n/**\n * Configuration for native scroll interactions managed by the Host Shell.\n */\nexport interface ScrollConfig {\n /** Configuration for Pull-to-Refresh (Top). */\n topScrollMore?: {\n /** Show/hide the native RefreshControl. */\n enabled: boolean;\n /** Set to true to show the loading spinner, false to hide it. */\n refreshing?: boolean;\n };\n /** Configuration for Infinite Scroll (Bottom). */\n bottomScrollMore?: {\n /** Enable/disable bottom scroll detection. */\n enabled: boolean;\n /** If false, detection stops and the indicator is hidden. */\n hasMore?: boolean;\n /** Set to true to show the bottom ActivityIndicator. */\n loadingMore?: boolean;\n };\n}\n","export { MiniAppSDK, sdk } from \"@miniapps-sdk/sdk\";\nexport * from \"@miniapps-sdk/types\";\n\nimport { sdk } from \"@miniapps-sdk/sdk\";\nexport default sdk;\n"],"mappings":";AASO,IAAM,SAAN,MAAa;AAAA,EACV,YAGJ,CAAC;AAAA,EAC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Q;AAAA;AAAA;AAAA;AAAA;AAAA,IAKb,KAAK,IAAI,YAAuB,KAAK,OAAO,KAAK,aAAa,EAAE,QAAQ,CAAC;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,GAAG,OAAiB,UAAmC;AAC5D,WAAO,KAAK,OAAO,GAAG,OAAiB,QAAQ;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,IAAI,OAAiB,UAAmC;AAC7D,SAAK,OAAO,IAAI,OAAiB,QAAQ;AAAA,EAC3C;AACF;AAKO,IAAM,MAAM,IAAI,WAAW;;;AC7D3B,IAAK,UAAL,kBAAKA,aAAL;AAEL,EAAAA,SAAA,qBAAkB;AAElB,EAAAA,SAAA,wBAAqB;AAJX,SAAAA;AAAA,GAAA;;;AC9LZ,IAAO,gBAAQ;","names":["UIEvent"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudparse/up-miniapps-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "UP Mini-App SDK for bridge communication between WebView and Host Shell",
5
5
  "author": "CloudParse Team",
6
6
  "license": "MIT",
@@ -37,4 +37,4 @@
37
37
  "tsup": "^8.5.1",
38
38
  "typescript": "^5.0.0"
39
39
  }
40
- }
40
+ }