universal-portability
Version:
Universal Portability Framework for Web3 Applications
3 lines (2 loc) • 13.1 kB
JavaScript
;Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("react-native"),t=require("react-native-webview");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=n(e),o=function(){return o=Object.assign||function(e){for(var r,t=1,n=arguments.length;t<n;t++)for(var a in r=arguments[t])Object.prototype.hasOwnProperty.call(r,a)&&(e[a]=r[a]);return e},o.apply(this,arguments)};function s(e,r,t,n){return new(t||(t=Promise))((function(a,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function i(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var r;e.done?a(e.value):(r=e.value,r instanceof t?r:new t((function(e){e(r)}))).then(s,i)}c((n=n.apply(e,r||[])).next())}))}function i(e,r){var t,n,a,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=i(0),s.throw=i(1),s.return=i(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(i){return function(c){return function(i){if(t)throw new TypeError("Generator is already executing.");for(;s&&(s=0,i[0]&&(o=0)),o;)try{if(t=1,n&&(a=2&i[0]?n.return:i[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,i[1])).done)return a;switch(n=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=r.call(e,o)}catch(e){i=[6,e],n=0}finally{t=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}function c(e,r,t){if(t||2===arguments.length)for(var n,a=0,o=r.length;a<o;a++)!n&&a in r||(n||(n=Array.prototype.slice.call(r,0,a)),n[a]=r[a]);return e.concat(n||Array.prototype.slice.call(r))}"function"==typeof SuppressedError&&SuppressedError;var u=function(){return"undefined"!=typeof navigator&&"ReactNative"===navigator.product},l=function(e,r,t){void 0===r&&(r="*");try{if(u()){if(null==t?void 0:t.current){var n=JSON.stringify(e).replace(/"/g,'\\"');t.current.injectJavaScript("\n (function() {\n window.postMessage(".concat(n,", '*');\n return true;\n })();\n "))}}else window.parent.postMessage(e,r)}catch(e){console.error("Failed to send message:",e)}},d={encode:function(e){try{return u()?"function"==typeof global.btoa?global.btoa(e):function(e){for(var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="",n=0,a=[],o=0;o<e.length;o++){var s=e.charCodeAt(o);if(s<128)a.push(s);else if(s<2048)a.push(192|s>>6,128|63&s);else if(s<55296||s>=57344)a.push(224|s>>12,128|s>>6&63,128|63&s);else{o++;var i=65536+((1023&s)<<10|1023&e.charCodeAt(o));a.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}}for(n=0;n<a.length;n+=3)for(var c=a[n]<<16|a[n+1]<<8|a[n+2],u=0;u<4;u++)n+.75*u<a.length?t+=r[c>>6*(3-u)&63]:t+="=";return t}(e):window.btoa(e)}catch(e){return console.error("Base64 encoding error:",e),""}},decode:function(e){try{return u()?"function"==typeof global.atob?global.atob(e):function(e){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";e=e.replace(/[^A-Za-z0-9+/=]/g,"");var t="",n=0,a=[];for(n=0;n<e.length;n+=4){var o=r.indexOf(e.charAt(n)),s=r.indexOf(e.charAt(n+1)),i=r.indexOf(e.charAt(n+2)),c=r.indexOf(e.charAt(n+3)),u=o<<2|s>>4,l=(15&s)<<4|i>>2,d=(3&i)<<6|c;a.push(u),64!==i&&a.push(l),64!==c&&a.push(d)}var f=0;for(;f<a.length;){var p=a[f++];p<128?t+=String.fromCharCode(p):p>191&&p<224?(p=(31&p)<<6|63&a[f++],t+=String.fromCharCode(p)):p>223&&p<240?(p=(15&p)<<12|(63&a[f++])<<6|63&a[f++],t+=String.fromCharCode(p)):(p=(7&p)<<18|(63&a[f++])<<12|(63&a[f++])<<6|63&a[f++],p-=65536,t+=String.fromCharCode(p>>10|55296,1023&p|56320))}return t}(e):window.atob(e)}catch(e){return console.error("Base64 decoding error:",e),""}}};var f=function(e,r){try{if(!e.current)return void console.warn("WebView reference is not available");l(r,"*",e)}catch(e){console.error("Failed to send message to WebView:",e)}},p=function(e){try{return"string"==typeof e.nativeEvent.data?JSON.parse(e.nativeEvent.data):null}catch(e){return console.error("Failed to parse WebView message:",e),null}},g=function(n){var s=n.source,i=n.address,c=n.rpcUrl,u=n.chainId,l=n.style,d=n.onMessage,p=n.onLoad,g=n.onError,w=n.injectedJavaScript,v=function(e,r){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(n=Object.getOwnPropertySymbols(e);a<n.length;a++)r.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(t[n[a]]=e[n[a]])}return t}(n,["source","address","rpcUrl","chainId","style","onMessage","onLoad","onError","injectedJavaScript"]),b=e.useRef(null),y='\n window.ethereum = {\n isMetaMask: true,\n address: "'.concat(i||"",'",\n chainId: ').concat(u||1,',\n rpcUrl: "').concat(c||"","\",\n // Add placeholder methods that will be replaced by message handlers\n request: function(payload) {\n return new Promise((resolve, reject) => {\n window.postMessage(\n {\n type: 'RPC_REQUEST',\n payload,\n id: Date.now().toString()\n },\n '*'\n );\n });\n }\n };\n\n // Let the host know the WebView is ready\n window.postMessage(\n { \n type: 'WALLET_WEBVIEW_READY', \n payload: {}, \n id: Date.now().toString() \n }, \n '*'\n );\n true;\n "),E="\n ".concat(y,"\n ").concat(w||"","\n "),S=e.useCallback((function(e){try{var r=JSON.parse(e.nativeEvent.data);if("INTERSPACE_CONNECT_REQUEST"===r.type)if(i&&u){var t={type:"INTERSPACE_CONNECT_RESPONSE",payload:{address:i,chainId:u,isConnected:!0},id:r.id||Date.now().toString()};f(b,t)}d&&d(e)}catch(e){console.error("Error handling WebView message:",e)}}),[i,u,d]),C=e.useCallback((function(e){f(b,e)}),[]);return e.useEffect((function(){b.current&&(b.current.sendMessageToWebView=C)}),[C]),a.default.createElement(r.View,{style:[h.container,l]},a.default.createElement(t.WebView,o({ref:b,source:s,onMessage:S,onLoad:p,onError:g,injectedJavaScript:E,javaScriptEnabled:!0,domStorageEnabled:!0,startInLoadingState:!0,allowFileAccess:!0,allowUniversalAccessFromFileURLs:!0,allowFileAccessFromFileURLs:!0},v)))},h=r.StyleSheet.create({container:{flex:1,overflow:"hidden"}}),w=e.createContext({sendMessageToWebView:function(){},registerWebView:function(){},unregisterWebView:function(){},webViews:[],isConnected:!1,walletAddress:null,chainId:null}),v=function(t){var n=t.children,o=t.walletAddress,s=t.chainId,i=t.isConnected,u=void 0!==i&&i,l=t.onError,d=t.config,f=void 0===d?{allowedOrigins:["*"],debug:!1}:d,p=e.useState(o||null),g=p[0],h=p[1],v=e.useState(s||null),b=v[0],y=v[1],E=e.useState(u),S=E[0],C=E[1],A=e.useRef([]),T=e.useRef(r.AppState.currentState),m=e.useCallback((function(e,r){f.debug&&console.log("[NativePortability]: ".concat(e),r||"")}),[f.debug]),I=e.useCallback((function(e,r){try{r.current&&r.current.sendMessageToWebView?(r.current.sendMessageToWebView(e),m("Sent message to WebView",e)):m("WebView reference is not available",r)}catch(e){m("Failed to send message to WebView",e),null==l||l(e instanceof Error?e:new Error("Failed to send message to WebView"))}}),[m,l]),N=e.useCallback((function(e){A.current.forEach((function(r){I(e,r)}))}),[I]),O=e.useCallback((function(e){A.current.includes(e)||(A.current=c(c([],A.current,!0),[e],!1),m("WebView registered",A.current.length))}),[m]),V=e.useCallback((function(e){A.current=A.current.filter((function(r){return r!==e})),m("WebView unregistered",A.current.length)}),[m]),x=e.useCallback((function(e){T.current.match(/inactive|background/)&&"active"===e&&(m("App has come to foreground, refreshing WebViews"),S&&g&&b&&N({type:"WALLET_INFO",payload:{address:g,chainId:b,isConnected:S},id:Date.now().toString()})),T.current=e}),[S,g,b,m,N]);e.useEffect((function(){g!==o&&o&&h(o),b!==s&&s&&y(s),S!==u&&C(u)}),[o,s,u,g,b,S]),e.useEffect((function(){g&&b&&S&&N({type:"WALLET_INFO",payload:{address:g,chainId:b,isConnected:S},id:Date.now().toString()})}),[g,b,S,N]),e.useEffect((function(){var e=r.AppState.addEventListener("change",x);return function(){e.remove()}}),[x]);var R={sendMessageToWebView:I,registerWebView:O,unregisterWebView:V,webViews:A.current,isConnected:S,walletAddress:g,chainId:b};return a.default.createElement(w.Provider,{value:R},n)},b=function(){return e.useContext(w)};function y(r){var t=this,n=r.walletAddress,a=r.chainId,o=r.signer,c=b().sendMessageToWebView,u=e.useRef(null),l=e.useCallback((function(e,r,t){u.current&&c({type:e,payload:r,id:t},u)}),[c]);return{handleWebViewMessage:e.useCallback((function(e){return s(t,void 0,void 0,(function(){var r,t,s,c,u,d,f,g,h,w,v;return i(this,(function(i){switch(i.label){case 0:if(i.trys.push([0,12,,13]),!(r=p(e)))return[2];switch(t=r.type,s=r.payload,c=r.id,t){case"INTERSPACE_CONNECT_REQUEST":return[3,1];case"SIGN_MESSAGE_REQUEST":return[3,2];case"TRANSACTION_REQUEST":return[3,6];case"SWITCH_CHAIN_REQUEST":return[3,10]}return[3,11];case 1:return l("INTERSPACE_CONNECT_RESPONSE",{address:n,chainId:a,isConnected:!0},c),[3,11];case 2:if(i.trys.push([2,4,,5]),!o)throw new Error("Signer is not available");return u=s,[4,o.signMessage(u.message)];case 3:return d=i.sent(),l("SIGNATURE_RESPONSE",{signature:d,success:!0},c),[3,5];case 4:return f=i.sent(),l("SIGNATURE_RESPONSE",{error:f.message,success:!1},c),[3,5];case 5:case 9:case 10:return[3,11];case 6:if(i.trys.push([6,8,,9]),!o)throw new Error("Signer is not available");return l("TRANSACTION_INITIATED",{txId:c,status:"pending"},c),g=s,[4,o.sendTransaction({to:g.to,data:g.data,value:g.value,chainId:g.chainId||a})];case 7:return h=i.sent(),l("TRANSACTION_SIGNED",{txId:c,hash:h.hash,status:"success"},c),[3,9];case 8:return w=i.sent(),l("TRANSACTION_SIGNED",{txId:c,error:w.message,status:"error"},c),[3,9];case 11:return[3,13];case 12:return v=i.sent(),console.error("Error handling WebView message:",v),[3,13];case 13:return[2]}}))}))}),[n,a,o,l]),webViewRef:u}}var E=function(e,r){if(!r)return e;if("string"==typeof r)return"popular"===r?e.sort((function(e,r){return new Date(r.createdAt).getTime()-new Date(e.createdAt).getTime()})).slice(0,10):e.filter((function(e){return e.category.includes(r)||e.developer===r}));if(Array.isArray(r))return e.filter((function(e){return r.includes(e.slug)||r.includes(e.name.toLowerCase())}));switch(r.type){case"category":return e.filter((function(e){return"string"==typeof r.value?e.category.includes(r.value):r.value.some((function(r){return e.category.includes(r)}))}));case"wallet":return e.filter((function(e){return"string"==typeof r.value?e.developer===r.value:r.value.includes(e.developer)}));case"popular":return e.sort((function(e,r){return new Date(r.createdAt).getTime()-new Date(e.createdAt).getTime()})).slice(0,Number(r.value)||10);case"apps":return e.filter((function(e){return"string"==typeof r.value?e.slug===r.value||e.name.toLowerCase()===r.value.toLowerCase():r.value.includes(e.slug)||r.value.some((function(r){return e.name.toLowerCase()===r.toLowerCase()}))}));default:return e}};exports.NativePort=g,exports.NativePortabilityProvider=v,exports.PORTABILITY_VERSION="1.0.0",exports.Port=g,exports.UniversalPortabilityProvider=v,exports.base64=d,exports.isReactNative=u,exports.parseWebViewMessage=p,exports.postMessageSafe=l,exports.sendPortabilityMessageToWebView=f,exports.useMessageHandler=y,exports.usePortHandler=function(e){void 0===e&&(e={});var r=e.address,t=e.chainId,n=y({walletAddress:r||"",chainId:t||1,signer:e.signer});return{handleWebViewMessage:n.handleWebViewMessage,webViewRef:n.webViewRef,isReady:Boolean(r&&t)}},exports.usePortableApps=function(r){var t=e.useState([]),n=t[0],a=t[1],o=e.useState(!0),c=o[0],u=o[1],l=e.useState(null),d=l[0],f=l[1];return e.useEffect((function(){s(void 0,void 0,void 0,(function(){var e,t,n,o;return i(this,(function(s){switch(s.label){case 0:return s.trys.push([0,3,4,5]),u(!0),[4,fetch("https://api.intersend.io/v1/intersend/interspace/apps",{headers:{"x-api-key":"Yeu1WVC1qOCYVOaVsusFlgal5m1i7e8B8duMJsix8WxnDauvo70cZ8soQfGqrfwyw69PsjUidM8FQBTUSfSAYx2COVD1a0elJXGKccv4D9eYx6f4U4vPhRAbvVFbhD6P","Content-Type":"application/json",Accept:"application/json"},method:"GET"})];case 1:if(!(e=s.sent()).ok)throw new Error("Failed to fetch apps: ".concat(e.status));return[4,e.json()];case 2:return t=s.sent(),n=E(t,r),a(n),[3,5];case 3:return o=s.sent(),f(o instanceof Error?o:new Error("Unknown error occurred")),console.error("Error fetching portable apps:",o),[3,5];case 4:return u(!1),[7];case 5:return[2]}}))}))}),[r]),{apps:n,loading:c,error:d}},exports.useUniversalPortability=b;
//# sourceMappingURL=native.js.map