@getalby/sdk
Advanced tools
Comparing version 3.8.0 to 3.8.1
@@ -1,1 +0,1 @@ | ||
import e from"emittery";import{generatePrivateKey as t,relayInit as n,nip19 as s,getPublicKey as i,finishEvent as r,getEventHash as o,nip04 as a}from"nostr-tools";function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},c.apply(this,arguments)}function l(e,t){if(null==e)return{};var n,s,i={},r=Object.keys(e);for(s=0;s<r.length;s++)t.indexOf(n=r[s])>=0||(i[n]=e[n]);return i}function u(e){return Object.entries(e).map(([e,t])=>e&&t?`${e}=${t}`:"").filter(e=>e).join("&")}function h(e,t){return`Basic ${btoa(`${e}:${t}`)}`}const d=e=>e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"");class p extends Error{constructor(e,t,n,s){let i=e.toString();t&&(i+=` ${t}`),i+=": ",i+=s.message?s.message:JSON.stringify(s),super(i),this.status=void 0,this.statusText=void 0,this.headers=void 0,this.error=void 0,this.status=e,this.statusText=t,this.headers=n,this.error=s}}var y={__proto__:null,OAuthClient:class{},AuthClient:class{},AlbyResponseError:p};const m=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],w="https://api.getalby.com";async function g(e,t,n=0){const s=await fetch(e,t);if(429===s.status&&n>0){const i=Number(s.headers.get("x-rate-limit-reset")),r=Number(s.headers.get("x-rate-limit-remaining")),o=1e3*i-Date.now();let a=1e3;return 0===r&&(a=o),await new Promise(e=>setTimeout(e,a)),g(e,t,n-1)}return s}async function f(e){let{auth:t,endpoint:n,params:s={},request_body:i,method:r,max_retries:o,base_url:a=w,user_agent:h,headers:d}=e,y=l(e,m);const f=new URL(a+n);f.search=u(s);const b="POST"===r&&!!i,v=t?await t.getAuthHeader(f.href,r):void 0,_=await g(f.toString(),c({headers:c({},b?{"Content-Type":"application/json; charset=utf-8"}:void 0,v,d,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:r,body:b?JSON.stringify(i):void 0},y),o);if(!_.ok){const e=await _.json();throw new p(_.status,_.statusText,_.headers,e)}return _}async function b(e){return(await f(e)).json()}const v=["expires_in"],_=["token"];function k(e){const{expires_in:t}=e;return c({},l(e,v),!!t&&{expires_at:Date.now()+1e3*t})}class E{constructor(e){this.bearer_token=void 0,this.bearer_token=e}getAuthHeader(){return{Authorization:`Bearer ${this.bearer_token}`}}}var P={__proto__:null,OAuth2User:class{constructor(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;const{token:n}=t,s=l(t,_);this.options=c({client_secret:""},s),this.token=n,this._refreshAccessTokenPromise=null}on(e,t){this._tokenEvents.on(e,t)}async refreshAccessToken(){var e=this;return this._refreshAccessTokenPromise||(this._refreshAccessTokenPromise=new Promise(async function(t,n){try{var s;const n=null==(s=e.token)?void 0:s.refresh_token,{client_id:i,client_secret:r,request_options:o,user_agent:a}=e.options;if(!i)throw new Error("client_id is required");if(!n)throw new Error("refresh_token is required");const l=k(await b(c({},o,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:n},user_agent:a,method:"POST",headers:c({},null==o?void 0:o.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:h(i,r)})})));e.token=l,t({token:l}),e._tokenEvents.emit("tokenRefreshed",e.token)}catch(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)}finally{e._refreshAccessTokenPromise=null}})),this._refreshAccessTokenPromise}isAccessTokenExpired(){var e,t;const n=null==(e=this.token)?void 0:e.refresh_token,s=null==(t=this.token)?void 0:t.expires_at;return!s||!!n&&s<=Date.now()+1e3}async requestAccessToken(e){const{client_id:t,client_secret:n,callback:s,request_options:i,user_agent:r}=this.options,o=this.code_verifier;if(!t)throw new Error("client_id is required");if(!n&&!o)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!s)throw new Error("callback is required");const a={code:e,grant_type:"authorization_code",code_verifier:o,client_id:t,redirect_uri:s},l=k(await b(c({},i,{endpoint:"/oauth/token",params:a,user_agent:r,method:"POST",headers:c({},null==i?void 0:i.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:h(t,n)})})));return this.token=l,{token:l}}async generateAuthURL(e){e||(e={});const{client_id:t,callback:n,scopes:s}=this.options;if(!n)throw new Error("callback required");if(!s)throw new Error("scopes required");let i;"S256"===e.code_challenge_method?(await this._generateS256Challenge(),i="S256"):"plain"===e.code_challenge_method&&e.code_challenge&&(this.code_challenge=e.code_challenge,this.code_verifier=e.code_challenge,i="plain");const r=this.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=u(c({},e,{client_id:t,scope:s.join(" "),response_type:"code",redirect_uri:n,code_challenge_method:i,code_challenge:r})),o.toString()}async getAuthHeader(){var e;if(null==(e=this.token)||!e.access_token)throw new Error("access_token is required");return this.isAccessTokenExpired()&&await this.refreshAccessToken(),{Authorization:`Bearer ${this.token.access_token}`}}async _generateS256Challenge(){const e=crypto.getRandomValues(new Uint8Array(64));this.code_verifier=d(e);const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(this.code_verifier)),n=new Uint8Array(t);this.code_challenge=btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},OAuth2Bearer:E};class T extends Error{constructor(e,t){super(e),this.error=void 0,this.code=void 0,this.error=e,this.code=t}}class N extends T{}class q extends T{}class A extends q{}class R extends q{}class x extends T{}class S extends T{}class U extends T{}class O extends T{}class I extends T{}const C={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}};class W{static parseWalletConnectUrl(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://").replace("nostrwalletconnect:","http://").replace("nostr+walletconnect:","http://");const t=new URL(e),n=t.searchParams.get("relay");if(!n)throw new Error("No relay URL found in connection string");const s={walletPubkey:t.host,relayUrl:n},i=t.searchParams.get("secret");i&&(s.secret=i);const r=t.searchParams.get("lud16");return r&&(s.lud16=r),s}static withNewSecret(e){return(e=e||{}).secret=t(),new W(e)}constructor(e){var t;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.lud16=void 0,this.walletPubkey=void 0,this.options=void 0,e&&e.nostrWalletConnectUrl&&(e=c({},W.parseWalletConnectUrl(e.nostrWalletConnectUrl),e));const i=C[(null==(t=e)?void 0:t.providerName)||"alby"];this.options=c({},i,e||{}),this.relayUrl=this.options.relayUrl,this.relay=n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?s.decode(this.options.secret).data:this.options.secret),this.lud16=this.options.lud16,this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?s.decode(this.options.walletPubkey).data:this.options.walletPubkey,void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}get nostrWalletConnectUrl(){return this.getNostrWalletConnectUrl()}getNostrWalletConnectUrl(e=!0){let t=`nostr+walletconnect://${this.walletPubkey}?relay=${this.relayUrl}&pubkey=${this.publicKey}`;return e&&(t=`${t}&secret=${this.secret}`),t}get connected(){return 1===this.relay.status}get publicKey(){if(!this.secret)throw new Error("Missing secret key");return i(this.secret)}getPublicKey(){return Promise.resolve(this.publicKey)}signEvent(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(r(e,this.secret))}getEventHash(e){return o(e)}close(){return this.relay.close()}async encrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.encrypt(this.secret,e,t)}async decrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.decrypt(this.secret,e,t)}getAuthorizationUrl(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");const t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t}initNWC(e={}){e.name||(e.name=document.location.host);const t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,s=window.outerWidth/2+window.screenX-200;return new Promise((e,i)=>{const r=window.open(t.toString(),`${document.title} - Wallet Connect`,`height=600,width=400,top=${n},left=${s}`);if(!r)return void i(new Error("failed to execute window.open"));const o=n=>{const s=n.data;s&&"nwc:success"===s.type&&n.origin===`${t.protocol}//${t.host}`&&(e(s),clearInterval(a),window.removeEventListener("message",o),r&&r.close())},a=setInterval(()=>{r&&r.closed&&(clearInterval(a),window.removeEventListener("message",o),i(new Error("Popup closed")))},500);window.addEventListener("message",o)})}async getWalletServiceSupportedMethods(){return console.warn("getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead."),(await this.getWalletServiceInfo()).capabilities}async getWalletServiceInfo(){var e;await this._checkConnected();const t=await this.relay.list([{kinds:[13194],limit:1,authors:[this.walletPubkey]}],{eoseSubTimeout:1e4});if(!t.length)throw new Error("no info event (kind 13194) returned from relay");const n=t[0].content,s=t[0].tags.find(e=>"notifications"===e[0]);return{capabilities:n.split(/[ |,]/g),notifications:(null==s||null==(e=s[1])?void 0:e.split(" "))||[]}}async getInfo(){try{return await this.executeNip47Request("get_info",{},e=>!!e.methods)}catch(e){throw console.error("Failed to request get_info",e),e}}async getBudget(){try{return await this.executeNip47Request("get_budget",{},e=>void 0!==e)}catch(e){throw console.error("Failed to request get_budget",e),e}}async getBalance(){try{return await this.executeNip47Request("get_balance",{},e=>void 0!==e.balance)}catch(e){throw console.error("Failed to request get_balance",e),e}}async payInvoice(e){try{return await this.executeNip47Request("pay_invoice",e,e=>!!e.preimage)}catch(e){throw console.error("Failed to request pay_invoice",e),e}}async payKeysend(e){try{return await this.executeNip47Request("pay_keysend",e,e=>!!e.preimage)}catch(e){throw console.error("Failed to request pay_keysend",e),e}}async signMessage(e){try{return await this.executeNip47Request("sign_message",e,t=>t.message===e.message&&!!t.signature)}catch(e){throw console.error("Failed to request sign_message",e),e}}async multiPayInvoice(e){try{return{invoices:await this.executeMultiNip47Request("multi_pay_invoice",e,e.invoices.length,e=>!!e.preimage),errors:[]}}catch(e){throw console.error("Failed to request multi_pay_invoice",e),e}}async multiPayKeysend(e){try{return{keysends:await this.executeMultiNip47Request("multi_pay_keysend",e,e.keysends.length,e=>!!e.preimage),errors:[]}}catch(e){throw console.error("Failed to request multi_pay_keysend",e),e}}async makeInvoice(e){try{if(!e.amount)throw new Error("No amount specified");return await this.executeNip47Request("make_invoice",e,e=>!!e.invoice)}catch(e){throw console.error("Failed to request make_invoice",e),e}}async lookupInvoice(e){try{return await this.executeNip47Request("lookup_invoice",e,e=>!!e.invoice)}catch(e){throw console.error("Failed to request lookup_invoice",e),e}}async listTransactions(e){try{return await this.executeNip47Request("list_transactions",e,e=>!!e.transactions)}catch(e){throw console.error("Failed to request list_transactions",e),e}}async subscribeNotifications(e,t){var n=this;let s,i,r,o=!0;return async function(){for(;o;){try{await n._checkConnected(),r=n.relay.sub([{kinds:[23196],authors:[n.walletPubkey],"#p":[n.publicKey]}]),console.info("subscribed to relay"),r.on("event",async function(s){const i=await n.decrypt(n.walletPubkey,s.content);let r;try{r=JSON.parse(i)}catch(e){return void console.error("Failed to parse decrypted event content",e)}r.notification?(!t||t.indexOf(r.notification_type)>-1)&&e(r):console.error("No notification in response",r)}),await new Promise(e=>{s=()=>{e()},i=()=>{console.info("relay disconnected"),null==s||s()},n.relay.on("disconnect",i)}),void 0!==i&&n.relay.off("disconnect",i)}catch(e){console.error("error subscribing to notifications",e||"unknown relay error")}o&&await new Promise(e=>setTimeout(e,1e3))}}(),()=>{var e;o=!1,null==s||s(),null==(e=r)||e.unsub()}}async executeNip47Request(e,t,n){var s=this;return await this._checkConnected(),new Promise((i,r)=>{!async function(){const o={method:e,params:t},a=await s.encrypt(s.walletPubkey,JSON.stringify(o)),c={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",s.walletPubkey]],content:a,pubkey:s.publicKey},l=await s.signEvent(c),u=s.relay.sub([{kinds:[23195],authors:[s.walletPubkey],"#e":[l.id]}]),h=setTimeout(function(){u.unsub(),r(new R(`reply timeout: event ${l.id}`,"INTERNAL"))},6e4);u.on("event",async function(e){clearTimeout(h),u.unsub();const t=await s.decrypt(s.walletPubkey,e.content);let o;try{o=JSON.parse(t)}catch(e){return clearTimeout(h),u.unsub(),void r(new S("failed to deserialize response","INTERNAL"))}var a,c;o.result?n(o.result)?i(o.result):(clearTimeout(h),u.unsub(),r(new U("response from NWC failed validation: "+JSON.stringify(o.result),"INTERNAL"))):(clearTimeout(h),u.unsub(),r(new N((null==(a=o.error)?void 0:a.message)||"unknown Error",(null==(c=o.error)?void 0:c.code)||"INTERNAL")))});const d=setTimeout(function(){u.unsub(),r(new A(`publish timeout: ${l.id}`,"INTERNAL"))},5e3);try{await s.relay.publish(l),clearTimeout(d)}catch(e){clearTimeout(d),r(new x(`failed to publish: ${e}`,"INTERNAL"))}}()})}async executeMultiNip47Request(e,t,n,s){var i=this;await this._checkConnected();const r=[];return new Promise((o,a)=>{!async function(){const l={method:e,params:t},u=await i.encrypt(i.walletPubkey,JSON.stringify(l)),h={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",i.walletPubkey]],content:u,pubkey:i.publicKey},d=await i.signEvent(h),p=i.relay.sub([{kinds:[23195],authors:[i.walletPubkey],"#e":[d.id]}]),y=setTimeout(function(){p.unsub(),a(new R(`reply timeout: event ${d.id}`,"INTERNAL"))},6e4);p.on("event",async function(e){const t=await i.decrypt(i.walletPubkey,e.content);let l;try{l=JSON.parse(t)}catch(e){clearTimeout(y),p.unsub(),a(new S("failed to deserialize response","INTERNAL"))}if(l.result){var u;if(!s(l.result))return clearTimeout(y),p.unsub(),void a(new U("Response from NWC failed validation: "+JSON.stringify(l.result),"INTERNAL"));const t=null==(u=e.tags.find(e=>"d"===e[0]))?void 0:u[1];if(void 0===t)return clearTimeout(y),p.unsub(),void a(new U("No d tag found in response event","INTERNAL"));r.push(c({},l.result,{dTag:t})),r.length===n&&(clearTimeout(y),p.unsub(),o(r))}else{var h,d;clearTimeout(y),p.unsub(),a(new O(null==(h=l.error)?void 0:h.message,null==(d=l.error)?void 0:d.code))}});const m=setTimeout(function(){p.unsub(),a(new A(`Publish timeout: ${d.id}`,"INTERNAL"))},5e3);try{await i.relay.publish(d),clearTimeout(m)}catch(e){clearTimeout(m),a(new x(`Failed to publish: ${e}`,"INTERNAL"))}}()})}async _checkConnected(){if(!this.secret)throw new Error("Missing secret key");try{await this.relay.connect()}catch(e){throw console.error("failed to connect to relay",this.relayUrl),new I("Failed to connect to "+this.relayUrl,"OTHER")}}}var M={__proto__:null,Nip47Error:T,Nip47WalletError:N,Nip47TimeoutError:q,Nip47PublishTimeoutError:A,Nip47ReplyTimeoutError:R,Nip47PublishError:x,Nip47ResponseDecodingError:S,Nip47ResponseValidationError:U,Nip47UnexpectedResponseError:O,Nip47NetworkError:I,NWCs:C,NWCClient:W};const $={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions",multi_pay_invoice:"sendMultiPayment",multi_pay_keysend:"multiKeysend",sign_message:"signMessage"};class L{get relay(){return console.warn("relay is deprecated. Please use client.relay instead."),this.client.relay}get relayUrl(){return console.warn("relayUrl is deprecated. Please use client.relayUrl instead."),this.client.relayUrl}get walletPubkey(){return console.warn("walletPubkey is deprecated. Please use client.walletPubkey instead."),this.client.walletPubkey}get options(){return this.client.options}get secret(){return console.warn("secret is deprecated. Please use client.secret instead."),this.client.secret}static withNewSecret(e){return(e=e||{}).secret=t(),new L(e)}constructor(e){this._enabled=!1,this.client=void 0,this.subscribers=void 0,this.client=new W(e),this.subscribers={}}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}getNostrWalletConnectUrl(e=!0){return console.warn("getNostrWalletConnectUrl is deprecated. Please use client.getNostrWalletConnectUrl instead."),this.client.getNostrWalletConnectUrl(e)}get nostrWalletConnectUrl(){return console.warn("nostrWalletConnectUrl is deprecated. Please use client.nostrWalletConnectUrl instead."),this.client.nostrWalletConnectUrl}get connected(){return console.warn("connected is deprecated. Please use client.connected instead."),this.client.connected}get publicKey(){return console.warn("publicKey is deprecated. Please use client.publicKey instead."),this.client.publicKey}getPublicKey(){return this.client.getPublicKey()}signEvent(e){return this.client.signEvent(e)}getEventHash(e){return console.warn("getEventHash is deprecated. Please use client.getEventHash instead."),this.client.getEventHash(e)}async enable(){this._enabled=!0}close(){return this.client.close()}async encrypt(e,t){return console.warn("encrypt is deprecated. Please use client.encrypt instead."),this.client.encrypt(e,t)}async decrypt(e,t){return console.warn("decrypt is deprecated. Please use client.decrypt instead."),this.client.decrypt(e,t)}getAuthorizationUrl(e){return console.warn("getAuthorizationUrl is deprecated. Please use client.getAuthorizationUrl instead."),this.client.getAuthorizationUrl(e)}initNWC(e={}){return console.warn("initNWC is deprecated. Please use client.initNWC instead."),this.client.initNWC(e)}async getInfo(){await this.checkEnabled();const e=["lightning","nostr"],t="Alby JS SDK";try{const n=await this.client.getInfo(),s={methods:n.methods.map(e=>$[e]),node:{alias:n.alias,pubkey:n.pubkey,color:n.color},supports:e,version:t};return this.notify("getInfo",s),s}catch(n){return console.error("Using minimal getInfo",n),{methods:["sendPayment"],node:{},supports:e,version:t}}}async getBalance(){await this.checkEnabled();const e=await this.client.getBalance(),t={balance:Math.floor(e.balance/1e3),currency:"sats"};return this.notify("getBalance",t),t}async sendPayment(e){await this.checkEnabled();const t={preimage:(await this.client.payInvoice({invoice:e})).preimage};return this.notify("sendPayment",t),t}async sendPaymentAsync(e){return await this.checkEnabled(),this.client.payInvoice({invoice:e}),this.notify("sendPaymentAsync",{}),{}}async keysend(e){await this.checkEnabled();const t={preimage:(await this.client.payKeysend(z(e))).preimage};return this.notify("keysend",t),t}async signMessage(e){await this.checkEnabled();const t=await this.client.signMessage({message:e}),n={message:t.message,signature:t.signature};return this.notify("keysend",n),n}async makeInvoice(e){var t;await this.checkEnabled();const n="object"==typeof e?e:void 0,s=+(null!=(t=null==n?void 0:n.amount)?t:e);if(!s)throw new Error("No amount specified");const i={paymentRequest:(await this.client.makeInvoice({amount:1e3*s,description:null==n?void 0:n.defaultMemo})).invoice};return this.notify("makeInvoice",i),i}async lookupInvoice(e){await this.checkEnabled();const t=await this.client.lookupInvoice({invoice:e.paymentRequest,payment_hash:e.paymentHash}),n={preimage:t.preimage,paymentRequest:t.invoice,paid:!!t.settled_at};return this.notify("lookupInvoice",n),n}async listTransactions(e){await this.checkEnabled();const t={transactions:(await this.client.listTransactions(e)).transactions.map(K)};return this.notify("listTransactions",t),t}async sendMultiPayment(e){await this.checkEnabled();const t=await this.client.multiPayInvoice({invoices:e.map((e,t)=>({invoice:e,id:t.toString()}))}),n={payments:t.invoices.map(t=>{const n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find paymentRequest matching response d tag");return{paymentRequest:n,preimage:t.preimage}}),errors:[]};return this.notify("sendMultiPayment",n),n}async multiKeysend(e){await this.checkEnabled();const t=await this.client.multiPayKeysend({keysends:e.map((e,t)=>c({},z(e),{id:t.toString()}))}),n={keysends:t.keysends.map(t=>{const n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find keysend matching response d tag");return{keysend:n,preimage:t.preimage}}),errors:[]};return this.notify("multiKeysend",n),n}lnurl(e){throw new Error("Method not implemented.")}request(e,t){throw new Error("Method not implemented.")}verifyMessage(e,t){throw new Error("Method not implemented.")}async checkEnabled(){if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function")}}function K(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}function z(e){return{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(e=>({type:parseInt(e[0]),value:d((new TextEncoder).encode(e[1]))})):[]}}const B=L;function F(e){const t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,custom_records:t}}class j{constructor(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new E(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}accountBalance(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))}accountSummary(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))}accountInformation(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))}accountValue4Value(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))}incomingInvoices(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))}outgoingInvoices(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))}invoices(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))}getInvoice(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/invoices/${e}`,method:"GET"}))}decodeInvoice(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/decode/bolt11/${e}`,method:"GET"}))}createInvoice(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))}keysend(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e.map(e=>c({},e,{custom_records:e.customRecords}))}):(n="/payments/keysend",s=c({},e,{custom_records:e.customRecords})),b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendPayment(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))}sendBoostagram(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e.map(e=>F(e))}):(n="/payments/keysend",s=F(e)),b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendToAlbyAccount(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)}sendBoostagramToAlbyAccount(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",custom_records:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))}createWebhookEndpoint(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))}deleteWebhookEndpoint(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/webhook_endpoints/${e}`,method:"DELETE"}))}getSwapInfo(e){return b(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))}createSwap(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))}}var H={__proto__:null,NostrWebLNProvider:L,NWC:B,OauthWeblnProvider:class{constructor(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new j(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}async enable(){var e;if(!this.isExecuting){if(null!=(e=this.auth.token)&&e.access_token)return{enabled:!0};if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");try{this.isExecuting=!0,await this.openAuthorization()}finally{this.isExecuting=!1}}}async sendPayment(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.sendPayment({invoice:e});return this.notify("sendPayment",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async keysend(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.keysend(e);return this.notify("keysend",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async getInfo(){return{alias:"Alby"}}async makeInvoice(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo});return this.notify("makeInvoice",t),{paymentRequest:t.payment_request}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async openAuthorization(){var e=this;const t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,s=await this.auth.generateAuthURL({code_challenge_method:"S256"});return new Promise((i,r)=>{const o=window.open(s,`${document.title} - WebLN enable`,`height=700,width=600,top=${t},left=${n}`);let a=!1;window.addEventListener("message",async function(t){const n=t.data;if(n&&"alby:oauth:success"===n.type&&t.origin===`${document.location.protocol}//${document.location.host}`&&!a){a=!0,console.info("Processing OAuth code response");const t=n.payload.code;try{await e.auth.requestAccessToken(t),e.client=new j(e.auth),o&&o.close(),e.notify("enable"),i({enabled:!0})}catch(e){console.error(e),r({enabled:!1})}}})})}}};export{j as Client,P as auth,M as nwc,y as types,H as webln}; | ||
import e from"emittery";import{generateSecretKey as t,Relay as n,nip19 as s,getPublicKey as r,finalizeEvent as i,getEventHash as o,nip04 as a}from"nostr-tools";function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},c.apply(this,arguments)}function l(e,t){if(null==e)return{};var n,s,r={},i=Object.keys(e);for(s=0;s<i.length;s++)t.indexOf(n=i[s])>=0||(r[n]=e[n]);return r}function u(e){return Object.entries(e).map(([e,t])=>e&&t?`${e}=${t}`:"").filter(e=>e).join("&")}function h(e,t){return`Basic ${btoa(`${e}:${t}`)}`}const d=e=>e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"");class p extends Error{constructor(e,t,n,s){let r=e.toString();t&&(r+=` ${t}`),r+=": ",r+=s.message?s.message:JSON.stringify(s),super(r),this.status=void 0,this.statusText=void 0,this.headers=void 0,this.error=void 0,this.status=e,this.statusText=t,this.headers=n,this.error=s}}var y={__proto__:null,OAuthClient:class{},AuthClient:class{},AlbyResponseError:p};const w=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],m="https://api.getalby.com";async function g(e,t,n=0){const s=await fetch(e,t);if(429===s.status&&n>0){const r=Number(s.headers.get("x-rate-limit-reset")),i=Number(s.headers.get("x-rate-limit-remaining")),o=1e3*r-Date.now();let a=1e3;return 0===i&&(a=o),await new Promise(e=>setTimeout(e,a)),g(e,t,n-1)}return s}async function f(e){let{auth:t,endpoint:n,params:s={},request_body:r,method:i,max_retries:o,base_url:a=m,user_agent:h,headers:d}=e,y=l(e,w);const f=new URL(a+n);f.search=u(s);const v="POST"===i&&!!r,b=t?await t.getAuthHeader(f.href,i):void 0,_=await g(f.toString(),c({headers:c({},v?{"Content-Type":"application/json; charset=utf-8"}:void 0,b,d,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:i,body:v?JSON.stringify(r):void 0},y),o);if(!_.ok){const e=await _.json();throw new p(_.status,_.statusText,_.headers,e)}return _}async function v(e){return(await f(e)).json()}const b=["expires_in"],_=["token"];function k(e){const{expires_in:t}=e;return c({},l(e,b),!!t&&{expires_at:Date.now()+1e3*t})}class E{constructor(e){this.bearer_token=void 0,this.bearer_token=e}getAuthHeader(){return{Authorization:`Bearer ${this.bearer_token}`}}}var P={__proto__:null,OAuth2User:class{constructor(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;const{token:n}=t,s=l(t,_);this.options=c({client_secret:""},s),this.token=n,this._refreshAccessTokenPromise=null}on(e,t){this._tokenEvents.on(e,t)}async refreshAccessToken(){var e=this;return this._refreshAccessTokenPromise||(this._refreshAccessTokenPromise=new Promise(async function(t,n){try{var s;const n=null==(s=e.token)?void 0:s.refresh_token,{client_id:r,client_secret:i,request_options:o,user_agent:a}=e.options;if(!r)throw new Error("client_id is required");if(!n)throw new Error("refresh_token is required");const l=k(await v(c({},o,{endpoint:"/oauth/token",params:{client_id:r,grant_type:"refresh_token",refresh_token:n},user_agent:a,method:"POST",headers:c({},null==o?void 0:o.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:h(r,i)})})));e.token=l,t({token:l}),e._tokenEvents.emit("tokenRefreshed",e.token)}catch(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)}finally{e._refreshAccessTokenPromise=null}})),this._refreshAccessTokenPromise}isAccessTokenExpired(){var e,t;const n=null==(e=this.token)?void 0:e.refresh_token,s=null==(t=this.token)?void 0:t.expires_at;return!s||!!n&&s<=Date.now()+1e3}async requestAccessToken(e){const{client_id:t,client_secret:n,callback:s,request_options:r,user_agent:i}=this.options,o=this.code_verifier;if(!t)throw new Error("client_id is required");if(!n&&!o)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!s)throw new Error("callback is required");const a={code:e,grant_type:"authorization_code",code_verifier:o,client_id:t,redirect_uri:s},l=k(await v(c({},r,{endpoint:"/oauth/token",params:a,user_agent:i,method:"POST",headers:c({},null==r?void 0:r.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:h(t,n)})})));return this.token=l,{token:l}}async generateAuthURL(e){e||(e={});const{client_id:t,callback:n,scopes:s}=this.options;if(!n)throw new Error("callback required");if(!s)throw new Error("scopes required");let r;"S256"===e.code_challenge_method?(await this._generateS256Challenge(),r="S256"):"plain"===e.code_challenge_method&&e.code_challenge&&(this.code_challenge=e.code_challenge,this.code_verifier=e.code_challenge,r="plain");const i=this.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=u(c({},e,{client_id:t,scope:s.join(" "),response_type:"code",redirect_uri:n,code_challenge_method:r,code_challenge:i})),o.toString()}async getAuthHeader(){var e;if(null==(e=this.token)||!e.access_token)throw new Error("access_token is required");return this.isAccessTokenExpired()&&await this.refreshAccessToken(),{Authorization:`Bearer ${this.token.access_token}`}}async _generateS256Challenge(){const e=crypto.getRandomValues(new Uint8Array(64));this.code_verifier=d(e);const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(this.code_verifier)),n=new Uint8Array(t);this.code_challenge=btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},OAuth2Bearer:E};if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");const N=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function T(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=N[e[n]];return t}function A(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let t=0;t<n.length;t++){const s=2*t,r=e.slice(s,s+2),i=Number.parseInt(r,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[t]=i}return n}class q extends Error{constructor(e,t){super(e),this.error=void 0,this.code=void 0,this.error=e,this.code=t}}class R extends q{}class x extends q{}class U extends x{}class S extends x{}class I extends q{}class O extends q{}class C extends q{}class W extends q{}class M extends q{}const $={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}};class L{static parseWalletConnectUrl(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://").replace("nostrwalletconnect:","http://").replace("nostr+walletconnect:","http://");const t=new URL(e),n=t.searchParams.get("relay");if(!n)throw new Error("No relay URL found in connection string");const s={walletPubkey:t.host,relayUrl:n},r=t.searchParams.get("secret");r&&(s.secret=r);const i=t.searchParams.get("lud16");return i&&(s.lud16=i),s}static withNewSecret(e){return(e=e||{}).secret=T(t()),new L(e)}constructor(e){var t;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.lud16=void 0,this.walletPubkey=void 0,this.options=void 0,e&&e.nostrWalletConnectUrl&&(e=c({},L.parseWalletConnectUrl(e.nostrWalletConnectUrl),e));const r=$[(null==(t=e)?void 0:t.providerName)||"alby"];this.options=c({},r,e||{}),this.relayUrl=this.options.relayUrl,this.relay=new n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?s.decode(this.options.secret).data:this.options.secret),this.lud16=this.options.lud16,this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?s.decode(this.options.walletPubkey).data:this.options.walletPubkey,void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}get nostrWalletConnectUrl(){return this.getNostrWalletConnectUrl()}getNostrWalletConnectUrl(e=!0){let t=`nostr+walletconnect://${this.walletPubkey}?relay=${this.relayUrl}&pubkey=${this.publicKey}`;return e&&(t=`${t}&secret=${this.secret}`),t}get connected(){return this.relay.connected}get publicKey(){if(!this.secret)throw new Error("Missing secret key");return r(A(this.secret))}getPublicKey(){return Promise.resolve(this.publicKey)}signEvent(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(i(e,A(this.secret)))}getEventHash(e){return o(e)}close(){return this.relay.close()}async encrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.encrypt(this.secret,e,t)}async decrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.decrypt(this.secret,e,t)}getAuthorizationUrl(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");const t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t}initNWC(e={}){e.name||(e.name=document.location.host);const t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,s=window.outerWidth/2+window.screenX-200;return new Promise((e,r)=>{const i=window.open(t.toString(),`${document.title} - Wallet Connect`,`height=600,width=400,top=${n},left=${s}`);if(!i)return void r(new Error("failed to execute window.open"));const o=n=>{const s=n.data;s&&"nwc:success"===s.type&&n.origin===`${t.protocol}//${t.host}`&&(e(s),clearInterval(a),window.removeEventListener("message",o),i&&i.close())},a=setInterval(()=>{i&&i.closed&&(clearInterval(a),window.removeEventListener("message",o),r(new Error("Popup closed")))},500);window.addEventListener("message",o)})}async getWalletServiceSupportedMethods(){return console.warn("getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead."),(await this.getWalletServiceInfo()).capabilities}async getWalletServiceInfo(){var e;await this._checkConnected();const t=await new Promise((e,t)=>{const n=[],s=this.relay.subscribe([{kinds:[13194],limit:1,authors:[this.walletPubkey]}],{eoseTimeout:1e4});s.onevent=e=>{n.push(e)},s.oneose=()=>{s.close(),e(n)}});if(!t.length)throw new Error("no info event (kind 13194) returned from relay");const n=t[0].content,s=t[0].tags.find(e=>"notifications"===e[0]);return{capabilities:n.split(/[ |,]/g),notifications:(null==s||null==(e=s[1])?void 0:e.split(" "))||[]}}async getInfo(){try{return await this.executeNip47Request("get_info",{},e=>!!e.methods)}catch(e){throw console.error("Failed to request get_info",e),e}}async getBudget(){try{return await this.executeNip47Request("get_budget",{},e=>void 0!==e)}catch(e){throw console.error("Failed to request get_budget",e),e}}async getBalance(){try{return await this.executeNip47Request("get_balance",{},e=>void 0!==e.balance)}catch(e){throw console.error("Failed to request get_balance",e),e}}async payInvoice(e){try{return await this.executeNip47Request("pay_invoice",e,e=>!!e.preimage)}catch(e){throw console.error("Failed to request pay_invoice",e),e}}async payKeysend(e){try{return await this.executeNip47Request("pay_keysend",e,e=>!!e.preimage)}catch(e){throw console.error("Failed to request pay_keysend",e),e}}async signMessage(e){try{return await this.executeNip47Request("sign_message",e,t=>t.message===e.message&&!!t.signature)}catch(e){throw console.error("Failed to request sign_message",e),e}}async multiPayInvoice(e){try{return{invoices:await this.executeMultiNip47Request("multi_pay_invoice",e,e.invoices.length,e=>!!e.preimage),errors:[]}}catch(e){throw console.error("Failed to request multi_pay_invoice",e),e}}async multiPayKeysend(e){try{return{keysends:await this.executeMultiNip47Request("multi_pay_keysend",e,e.keysends.length,e=>!!e.preimage),errors:[]}}catch(e){throw console.error("Failed to request multi_pay_keysend",e),e}}async makeInvoice(e){try{if(!e.amount)throw new Error("No amount specified");return await this.executeNip47Request("make_invoice",e,e=>!!e.invoice)}catch(e){throw console.error("Failed to request make_invoice",e),e}}async lookupInvoice(e){try{return await this.executeNip47Request("lookup_invoice",e,e=>!!e.invoice)}catch(e){throw console.error("Failed to request lookup_invoice",e),e}}async listTransactions(e){try{return await this.executeNip47Request("list_transactions",e,e=>!!e.transactions)}catch(e){throw console.error("Failed to request list_transactions",e),e}}async subscribeNotifications(e,t){var n=this;let s,r,i,o=!0;return async function(){for(;o;){try{await n._checkConnected(),i=n.relay.subscribe([{kinds:[23196],authors:[n.walletPubkey],"#p":[n.publicKey]}],{}),console.info("subscribed to relay"),i.onevent=async function(s){const r=await n.decrypt(n.walletPubkey,s.content);let i;try{i=JSON.parse(r)}catch(e){return void console.error("Failed to parse decrypted event content",e)}i.notification?(!t||t.indexOf(i.notification_type)>-1)&&e(i):console.error("No notification in response",i)},await new Promise(e=>{s=()=>{e()},r=()=>{console.info("relay disconnected"),null==s||s()},n.relay.onclose=r}),void 0!==r&&(n.relay.onclose=null)}catch(e){console.error("error subscribing to notifications",e||"unknown relay error")}o&&await new Promise(e=>setTimeout(e,1e3))}}(),()=>{var e;o=!1,null==s||s(),null==(e=i)||e.close()}}async executeNip47Request(e,t,n){var s=this;return await this._checkConnected(),new Promise((r,i)=>{!async function(){const o={method:e,params:t},a=await s.encrypt(s.walletPubkey,JSON.stringify(o)),c={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",s.walletPubkey]],content:a},l=await s.signEvent(c),u=s.relay.subscribe([{kinds:[23195],authors:[s.walletPubkey],"#e":[l.id]}],{}),h=setTimeout(function(){u.close(),i(new S(`reply timeout: event ${l.id}`,"INTERNAL"))},6e4);u.onevent=async function(e){clearTimeout(h),u.close();const t=await s.decrypt(s.walletPubkey,e.content);let o;try{o=JSON.parse(t)}catch(e){return clearTimeout(h),u.close(),void i(new O("failed to deserialize response","INTERNAL"))}var a,c;o.result?n(o.result)?r(o.result):(clearTimeout(h),u.close(),i(new C("response from NWC failed validation: "+JSON.stringify(o.result),"INTERNAL"))):(clearTimeout(h),u.close(),i(new R((null==(a=o.error)?void 0:a.message)||"unknown Error",(null==(c=o.error)?void 0:c.code)||"INTERNAL")))};const d=setTimeout(function(){u.close(),i(new U(`publish timeout: ${l.id}`,"INTERNAL"))},5e3);try{await s.relay.publish(l),clearTimeout(d)}catch(e){clearTimeout(d),i(new I(`failed to publish: ${e}`,"INTERNAL"))}}()})}async executeMultiNip47Request(e,t,n,s){var r=this;await this._checkConnected();const i=[];return new Promise((o,a)=>{!async function(){const l={method:e,params:t},u=await r.encrypt(r.walletPubkey,JSON.stringify(l)),h={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",r.walletPubkey]],content:u},d=await r.signEvent(h),p=r.relay.subscribe([{kinds:[23195],authors:[r.walletPubkey],"#e":[d.id]}],{}),y=setTimeout(function(){p.close(),a(new S(`reply timeout: event ${d.id}`,"INTERNAL"))},6e4);p.onevent=async function(e){const t=await r.decrypt(r.walletPubkey,e.content);let l;try{l=JSON.parse(t)}catch(e){clearTimeout(y),p.close(),a(new O("failed to deserialize response","INTERNAL"))}if(l.result){var u;if(!s(l.result))return clearTimeout(y),p.close(),void a(new C("Response from NWC failed validation: "+JSON.stringify(l.result),"INTERNAL"));const t=null==(u=e.tags.find(e=>"d"===e[0]))?void 0:u[1];if(void 0===t)return clearTimeout(y),p.close(),void a(new C("No d tag found in response event","INTERNAL"));i.push(c({},l.result,{dTag:t})),i.length===n&&(clearTimeout(y),p.close(),o(i))}else{var h,d;clearTimeout(y),p.close(),a(new W(null==(h=l.error)?void 0:h.message,null==(d=l.error)?void 0:d.code))}};const w=setTimeout(function(){p.close(),a(new U(`Publish timeout: ${d.id}`,"INTERNAL"))},5e3);try{await r.relay.publish(d),clearTimeout(w)}catch(e){clearTimeout(w),a(new I(`Failed to publish: ${e}`,"INTERNAL"))}}()})}async _checkConnected(){if(!this.secret)throw new Error("Missing secret key");if(!this.relayUrl)throw new Error("Missing relay url");try{this.relay.connected||await this.relay.connect()}catch(e){throw console.error("failed to connect to relay",this.relayUrl),new M("Failed to connect to "+this.relayUrl,"OTHER")}}}var K={__proto__:null,Nip47Error:q,Nip47WalletError:R,Nip47TimeoutError:x,Nip47PublishTimeoutError:U,Nip47ReplyTimeoutError:S,Nip47PublishError:I,Nip47ResponseDecodingError:O,Nip47ResponseValidationError:C,Nip47UnexpectedResponseError:W,Nip47NetworkError:M,NWCs:$,NWCClient:L};const z={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions",multi_pay_invoice:"sendMultiPayment",multi_pay_keysend:"multiKeysend",sign_message:"signMessage"};class B{get relay(){return console.warn("relay is deprecated. Please use client.relay instead."),this.client.relay}get relayUrl(){return console.warn("relayUrl is deprecated. Please use client.relayUrl instead."),this.client.relayUrl}get walletPubkey(){return console.warn("walletPubkey is deprecated. Please use client.walletPubkey instead."),this.client.walletPubkey}get options(){return this.client.options}get secret(){return console.warn("secret is deprecated. Please use client.secret instead."),this.client.secret}static withNewSecret(e){return(e=e||{}).secret=T(t()),new B(e)}constructor(e){this._enabled=!1,this.client=void 0,this.subscribers=void 0,this.client=new L(e),this.subscribers={}}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}getNostrWalletConnectUrl(e=!0){return console.warn("getNostrWalletConnectUrl is deprecated. Please use client.getNostrWalletConnectUrl instead."),this.client.getNostrWalletConnectUrl(e)}get nostrWalletConnectUrl(){return console.warn("nostrWalletConnectUrl is deprecated. Please use client.nostrWalletConnectUrl instead."),this.client.nostrWalletConnectUrl}get connected(){return console.warn("connected is deprecated. Please use client.connected instead."),this.client.connected}get publicKey(){return console.warn("publicKey is deprecated. Please use client.publicKey instead."),this.client.publicKey}getPublicKey(){return this.client.getPublicKey()}signEvent(e){return this.client.signEvent(e)}getEventHash(e){return console.warn("getEventHash is deprecated. Please use client.getEventHash instead."),this.client.getEventHash(e)}async enable(){this._enabled=!0}close(){return this.client.close()}async encrypt(e,t){return console.warn("encrypt is deprecated. Please use client.encrypt instead."),this.client.encrypt(e,t)}async decrypt(e,t){return console.warn("decrypt is deprecated. Please use client.decrypt instead."),this.client.decrypt(e,t)}getAuthorizationUrl(e){return console.warn("getAuthorizationUrl is deprecated. Please use client.getAuthorizationUrl instead."),this.client.getAuthorizationUrl(e)}initNWC(e={}){return console.warn("initNWC is deprecated. Please use client.initNWC instead."),this.client.initNWC(e)}async getInfo(){await this.checkEnabled();const e=["lightning","nostr"],t="Alby JS SDK";try{const n=await this.client.getInfo(),s={methods:n.methods.map(e=>z[e]),node:{alias:n.alias,pubkey:n.pubkey,color:n.color},supports:e,version:t};return this.notify("getInfo",s),s}catch(n){return console.error("Using minimal getInfo",n),{methods:["sendPayment"],node:{},supports:e,version:t}}}async getBalance(){await this.checkEnabled();const e=await this.client.getBalance(),t={balance:Math.floor(e.balance/1e3),currency:"sats"};return this.notify("getBalance",t),t}async sendPayment(e){await this.checkEnabled();const t={preimage:(await this.client.payInvoice({invoice:e})).preimage};return this.notify("sendPayment",t),t}async sendPaymentAsync(e){return await this.checkEnabled(),this.client.payInvoice({invoice:e}),this.notify("sendPaymentAsync",{}),{}}async keysend(e){await this.checkEnabled();const t={preimage:(await this.client.payKeysend(j(e))).preimage};return this.notify("keysend",t),t}async signMessage(e){await this.checkEnabled();const t=await this.client.signMessage({message:e}),n={message:t.message,signature:t.signature};return this.notify("keysend",n),n}async makeInvoice(e){var t;await this.checkEnabled();const n="object"==typeof e?e:void 0,s=+(null!=(t=null==n?void 0:n.amount)?t:e);if(!s)throw new Error("No amount specified");const r={paymentRequest:(await this.client.makeInvoice({amount:1e3*s,description:null==n?void 0:n.defaultMemo})).invoice};return this.notify("makeInvoice",r),r}async lookupInvoice(e){await this.checkEnabled();const t=await this.client.lookupInvoice({invoice:e.paymentRequest,payment_hash:e.paymentHash}),n={preimage:t.preimage,paymentRequest:t.invoice,paid:!!t.settled_at};return this.notify("lookupInvoice",n),n}async listTransactions(e){await this.checkEnabled();const t={transactions:(await this.client.listTransactions(e)).transactions.map(F)};return this.notify("listTransactions",t),t}async sendMultiPayment(e){await this.checkEnabled();const t=await this.client.multiPayInvoice({invoices:e.map((e,t)=>({invoice:e,id:t.toString()}))}),n={payments:t.invoices.map(t=>{const n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find paymentRequest matching response d tag");return{paymentRequest:n,preimage:t.preimage}}),errors:[]};return this.notify("sendMultiPayment",n),n}async multiKeysend(e){await this.checkEnabled();const t=await this.client.multiPayKeysend({keysends:e.map((e,t)=>c({},j(e),{id:t.toString()}))}),n={keysends:t.keysends.map(t=>{const n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find keysend matching response d tag");return{keysend:n,preimage:t.preimage}}),errors:[]};return this.notify("multiKeysend",n),n}lnurl(e){throw new Error("Method not implemented.")}request(e,t){throw new Error("Method not implemented.")}verifyMessage(e,t){throw new Error("Method not implemented.")}async checkEnabled(){if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function")}}function F(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}function j(e){return{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(e=>({type:parseInt(e[0]),value:d((new TextEncoder).encode(e[1]))})):[]}}const H=B;function J(e){const t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,custom_records:t}}class G{constructor(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new E(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}accountBalance(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))}accountSummary(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))}accountInformation(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))}accountValue4Value(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))}incomingInvoices(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))}outgoingInvoices(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))}invoices(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))}getInvoice(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/invoices/${e}`,method:"GET"}))}decodeInvoice(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/decode/bolt11/${e}`,method:"GET"}))}createInvoice(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))}keysend(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e.map(e=>c({},e,{custom_records:e.customRecords}))}):(n="/payments/keysend",s=c({},e,{custom_records:e.customRecords})),v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendPayment(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))}sendBoostagram(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e.map(e=>J(e))}):(n="/payments/keysend",s=J(e)),v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendToAlbyAccount(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)}sendBoostagramToAlbyAccount(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",custom_records:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))}createWebhookEndpoint(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))}deleteWebhookEndpoint(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/webhook_endpoints/${e}`,method:"DELETE"}))}getSwapInfo(e){return v(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))}createSwap(e,t){return v(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))}}var D={__proto__:null,NostrWebLNProvider:B,NWC:H,OauthWeblnProvider:class{constructor(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new G(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}async enable(){var e;if(!this.isExecuting){if(null!=(e=this.auth.token)&&e.access_token)return{enabled:!0};if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");try{this.isExecuting=!0,await this.openAuthorization()}finally{this.isExecuting=!1}}}async sendPayment(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.sendPayment({invoice:e});return this.notify("sendPayment",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async keysend(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.keysend(e);return this.notify("keysend",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async getInfo(){return{alias:"Alby"}}async makeInvoice(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo});return this.notify("makeInvoice",t),{paymentRequest:t.payment_request}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async openAuthorization(){var e=this;const t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,s=await this.auth.generateAuthURL({code_challenge_method:"S256"});return new Promise((r,i)=>{const o=window.open(s,`${document.title} - WebLN enable`,`height=700,width=600,top=${t},left=${n}`);let a=!1;window.addEventListener("message",async function(t){const n=t.data;if(n&&"alby:oauth:success"===n.type&&t.origin===`${document.location.protocol}//${document.location.host}`&&!a){a=!0,console.info("Processing OAuth code response");const t=n.payload.code;try{await e.auth.requestAccessToken(t),e.client=new G(e.auth),o&&o.close(),e.notify("enable"),r({enabled:!0})}catch(e){console.error(e),i({enabled:!1})}}})})}}};export{G as Client,P as auth,K as nwc,y as types,D as webln}; |
@@ -1,1 +0,1 @@ | ||
import e from"emittery";import{generatePrivateKey as t,relayInit as n,nip19 as r,finishEvent as o,getEventHash as i,nip04 as s,getPublicKey as u}from"nostr-tools";function c(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function a(e,t,n){return t&&c(e.prototype,t),n&&c(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(this,arguments)}function h(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function f(e){return f=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},f(e)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function m(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function v(e,t,n){return v=m()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&d(o,n.prototype),o},v.apply(null,arguments)}function p(e){var t="function"==typeof Map?new Map:void 0;return p=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return v(e,arguments,f(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},p(e)}function y(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function g(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function P(e,t){return"Basic "+btoa(e+":"+t)}var w=function(e){return e.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},"")},b=/*#__PURE__*/function(e){function t(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return h(t,e),t}(/*#__PURE__*/p(Error)),k={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:b},_=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],E=function(e){return Promise.resolve(T(e)).then(function(e){return e.json()})},T=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,u=e.max_retries,c=e.base_url,a=void 0===c?R:c,h=e.user_agent,f=e.headers,d=y(e,_);try{var m=function(e){return Promise.resolve(N(v.toString(),l({headers:l({},p?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,f,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:s,body:p?JSON.stringify(i):void 0},d),u)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new b(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},v=new URL(a+n);v.search=g(o);var p="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(v.href,s)).then(m):m(void 0))}catch(e){return Promise.reject(e)}},N=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),u=Number(o.headers.get("x-rate-limit-remaining")),c=1e3*s-Date.now(),a=1e3;return 0===u&&(a=c),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},R="https://api.getalby.com",j=["expires_in"],q=["token"];function A(e){var t=e.expires_in;return l({},y(e,j),!!t&&{expires_at:Date.now()+1e3*t})}var O=/*#__PURE__*/function(){function t(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;var n=t.token,r=y(t,q);this.options=l({client_secret:""},r),this.token=n,this._refreshAccessTokenPromise=null}var n=t.prototype;return n.on=function(e,t){this._tokenEvents.on(e,t)},n.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var i=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,i=o.client_id,s=o.client_secret,u=o.request_options,c=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(E(l({},u,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:c,method:"POST",headers:l({},null==u?void 0:u.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:P(i,s)})}))).then(function(n){var r=A(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},n.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},n.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,i=n.callback,s=n.request_options,u=n.user_agent,c=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!c)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!i)throw new Error("callback is required");return Promise.resolve(E(l({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:c,client_id:r,redirect_uri:i},user_agent:u,method:"POST",headers:l({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:P(r,o)})}))).then(function(e){var n=A(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},n.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=g(l({},e,{client_id:i,scope:u.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,i=o.client_id,s=o.callback,u=o.scopes;if(!s)throw new Error("callback required");if(!u)throw new Error("scopes required");var c=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(c&&c.then?c.then(t):t())}catch(e){return Promise.reject(e)}},n.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},n._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=w(t),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},t}(),S=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),x={__proto__:null,OAuth2User:O,OAuth2Bearer:S};function U(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function I(e,t,n){if(!e.s){if(n instanceof C){if(!n.s)return void(n.o=I.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(I.bind(null,e,t),I.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var C=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,o=this.s;if(o){var i=1&o?t:n;if(i){try{I(r,1,i(this.v))}catch(e){I(r,2,e)}return r}return this}return this.o=function(e){try{var o=e.v;1&e.s?I(r,1,t?t(o):o):n?I(r,1,n(o)):I(r,2,o)}catch(e){I(r,2,e)}},r},e}();function W(e){return e instanceof C&&1&e.s}var M=/*#__PURE__*/function(e){function t(t,n){var r;return(r=e.call(this,t)||this).error=void 0,r.code=void 0,r.error=t,r.code=n,r}return h(t,e),t}(/*#__PURE__*/p(Error)),L=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),K=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),z=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(K),B=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(K),F=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),H=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),J=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),G=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),D=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(M),V={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},X=/*#__PURE__*/function(){function e(t){var o;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.lud16=void 0,this.walletPubkey=void 0,this.options=void 0,t&&t.nostrWalletConnectUrl&&(t=l({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var i=V[(null==(o=t)?void 0:o.providerName)||"alby"];this.options=l({},i,t||{}),this.relayUrl=this.options.relayUrl,this.relay=n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?r.decode(this.options.secret).data:this.options.secret),this.lud16=this.options.lud16,this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?r.decode(this.options.walletPubkey).data:this.options.walletPubkey,void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://").replace("nostrwalletconnect:","http://").replace("nostr+walletconnect:","http://");var t=new URL(e),n=t.searchParams.get("relay");if(!n)throw new Error("No relay URL found in connection string");var r={walletPubkey:t.host,relayUrl:n},o=t.searchParams.get("secret");o&&(r.secret=o);var i=t.searchParams.get("lud16");return i&&(r.lud16=i),r},e.withNewSecret=function(n){return(n=n||{}).secret=t(),new e(n)};var c=e.prototype;return c.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},c.getPublicKey=function(){return Promise.resolve(this.publicKey)},c.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(o(e,this.secret))},c.getEventHash=function(e){return i(e)},c.close=function(){return this.relay.close()},c.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},c.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},c.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t},c.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(u),window.removeEventListener("message",n),i&&i.close())},u=setInterval(function(){i&&i.closed&&(clearInterval(u),window.removeEventListener("message",s),o(new Error("Popup closed")))},500);window.addEventListener("message",s)}else o(new Error("failed to execute window.open"))})},c.getWalletServiceSupportedMethods=function(){try{return console.warn("getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead."),Promise.resolve(this.getWalletServiceInfo()).then(function(e){return e.capabilities})}catch(e){return Promise.reject(e)}},c.getWalletServiceInfo=function(){try{var e=this;return Promise.resolve(e._checkConnected()).then(function(){return Promise.resolve(e.relay.list([{kinds:[13194],limit:1,authors:[e.walletPubkey]}],{eoseSubTimeout:1e4})).then(function(e){var t;if(!e.length)throw new Error("no info event (kind 13194) returned from relay");var n=e[0].content,r=e[0].tags.find(function(e){return"notifications"===e[0]});return{capabilities:n.split(/[ |,]/g),notifications:(null==r||null==(t=r[1])?void 0:t.split(" "))||[]}})})}catch(e){return Promise.reject(e)}},c.getInfo=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(e.executeNip47Request("get_info",{},function(e){return!!e.methods}))},function(e){throw console.error("Failed to request get_info",e),e}))}catch(e){return Promise.reject(e)}},c.getBudget=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(e.executeNip47Request("get_budget",{},function(e){return void 0!==e}))},function(e){throw console.error("Failed to request get_budget",e),e}))}catch(e){return Promise.reject(e)}},c.getBalance=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(e.executeNip47Request("get_balance",{},function(e){return void 0!==e.balance}))},function(e){throw console.error("Failed to request get_balance",e),e}))}catch(e){return Promise.reject(e)}},c.payInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("pay_invoice",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},c.payKeysend=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("pay_keysend",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},c.signMessage=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("sign_message",e,function(t){return t.message===e.message&&!!t.signature}))},function(e){throw console.error("Failed to request sign_message",e),e}))}catch(e){return Promise.reject(e)}},c.multiPayInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_invoice",e,e.invoices.length,function(e){return!!e.preimage})).then(function(e){return{invoices:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},c.multiPayKeysend=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_keysend",e,e.keysends.length,function(e){return!!e.preimage})).then(function(e){return{keysends:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},c.makeInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){if(!e.amount)throw new Error("No amount specified");return Promise.resolve(t.executeNip47Request("make_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request make_invoice",e),e}))}catch(e){return Promise.reject(e)}},c.lookupInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("lookup_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request lookup_invoice",e),e}))}catch(e){return Promise.reject(e)}},c.listTransactions=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions}))},function(e){throw console.error("Failed to request list_transactions",e),e}))}catch(e){return Promise.reject(e)}},c.subscribeNotifications=function(e,t){try{var n,r,o,i=this,s=!0;return function(){try{var u=function(e,t,n){for(var r;;){var o=e();if(W(o)&&(o=o.v),!o)return i;if(o.then){r=0;break}var i=n();if(i&&i.then){if(!W(i)){r=1;break}i=i.s}}var s=new C,u=I.bind(null,s,2);return(0===r?o.then(a):1===r?i.then(c):(void 0).then(function(){(o=e())?o.then?o.then(a).then(void 0,u):a(o):I(s,1,i)})).then(void 0,u),s;function c(t){i=t;do{if(!(o=e())||W(o)&&!o.v)return void I(s,1,i);if(o.then)return void o.then(a).then(void 0,u);W(i=n())&&(i=i.v)}while(!i||!i.then);i.then(c).then(void 0,u)}function a(e){e?(i=n())&&i.then?i.then(c).then(void 0,u):c(i):I(s,1,i)}}(function(){return!!s},0,function(){function u(){var e=function(){if(s)return Promise.resolve(new Promise(function(e){return setTimeout(e,1e3)})).then(function(){})}();if(e&&e.then)return e.then(function(){})}var c=U(function(){return Promise.resolve(i._checkConnected()).then(function(){return o=i.relay.sub([{kinds:[23196],authors:[i.walletPubkey],"#p":[i.publicKey]}]),console.info("subscribed to relay"),o.on("event",function(n){try{return Promise.resolve(i.decrypt(i.walletPubkey,n.content)).then(function(n){var r;try{r=JSON.parse(n)}catch(e){return void console.error("Failed to parse decrypted event content",e)}r.notification?(!t||t.indexOf(r.notification_type)>-1)&&e(r):console.error("No notification in response",r)})}catch(e){return Promise.reject(e)}}),Promise.resolve(new Promise(function(e){n=function(){e()},i.relay.on("disconnect",r=function(){console.info("relay disconnected"),null==n||n()})})).then(function(){void 0!==r&&i.relay.off("disconnect",r)})})},function(e){console.error("error subscribing to notifications",e||"unknown relay error")});return c&&c.then?c.then(u):u()});u&&u.then&&u.then(function(){})}catch(e){Promise.reject(e)}}(),Promise.resolve(function(){var e;s=!1,null==n||n(),null==(e=o)||e.unsub()})}catch(e){return Promise.reject(e)}},c.executeNip47Request=function(e,t,n){try{var r=this;return Promise.resolve(r._checkConnected()).then(function(){return new Promise(function(o,i){try{return Promise.resolve(r.encrypt(r.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",r.walletPubkey]],content:e,pubkey:r.publicKey};return Promise.resolve(r.signEvent(t)).then(function(e){var t=r.relay.sub([{kinds:[23195],authors:[r.walletPubkey],"#e":[e.id]}]),s=setTimeout(function(){t.unsub(),i(new B("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.on("event",function(e){try{return clearTimeout(s),t.unsub(),Promise.resolve(r.decrypt(r.walletPubkey,e.content)).then(function(e){var r,u,c;try{r=JSON.parse(e)}catch(e){return clearTimeout(s),t.unsub(),void i(new H("failed to deserialize response","INTERNAL"))}r.result?n(r.result)?o(r.result):(clearTimeout(s),t.unsub(),i(new J("response from NWC failed validation: "+JSON.stringify(r.result),"INTERNAL"))):(clearTimeout(s),t.unsub(),i(new L((null==(u=r.error)?void 0:u.message)||"unknown Error",(null==(c=r.error)?void 0:c.code)||"INTERNAL")))})}catch(e){return Promise.reject(e)}});var u=setTimeout(function(){t.unsub(),i(new z("publish timeout: "+e.id,"INTERNAL"))},5e3),c=U(function(){return Promise.resolve(r.relay.publish(e)).then(function(){clearTimeout(u)})},function(e){clearTimeout(u),i(new F("failed to publish: "+e,"INTERNAL"))});if(c&&c.then)return c.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},c.executeMultiNip47Request=function(e,t,n,r){try{var o=this;return Promise.resolve(o._checkConnected()).then(function(){var i=[];return new Promise(function(s,u){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e,pubkey:o.publicKey};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){t.unsub(),u(new B("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.on("event",function(e){try{return Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(o){var a;try{a=JSON.parse(o)}catch(e){clearTimeout(c),t.unsub(),u(new H("failed to deserialize response","INTERNAL"))}if(a.result){var h;if(!r(a.result))return clearTimeout(c),t.unsub(),void u(new J("Response from NWC failed validation: "+JSON.stringify(a.result),"INTERNAL"));var f=null==(h=e.tags.find(function(e){return"d"===e[0]}))?void 0:h[1];if(void 0===f)return clearTimeout(c),t.unsub(),void u(new J("No d tag found in response event","INTERNAL"));i.push(l({},a.result,{dTag:f})),i.length===n&&(clearTimeout(c),t.unsub(),s(i))}else{var d,m;clearTimeout(c),t.unsub(),u(new G(null==(d=a.error)?void 0:d.message,null==(m=a.error)?void 0:m.code))}})}catch(e){return Promise.reject(e)}});var a=setTimeout(function(){t.unsub(),u(new z("Publish timeout: "+e.id,"INTERNAL"))},5e3),h=U(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(a)})},function(e){clearTimeout(a),u(new F("Failed to publish: "+e,"INTERNAL"))});if(h&&h.then)return h.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},c._checkConnected=function(){try{var e=this;if(!e.secret)throw new Error("Missing secret key");return Promise.resolve(U(function(){return Promise.resolve(e.relay.connect()).then(function(){})},function(){throw console.error("failed to connect to relay",e.relayUrl),new D("Failed to connect to "+e.relayUrl,"OTHER")}))}catch(e){return Promise.reject(e)}},a(e,[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return 1===this.relay.status}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return u(this.secret)}}]),e}(),Y={__proto__:null,Nip47Error:M,Nip47WalletError:L,Nip47TimeoutError:K,Nip47PublishTimeoutError:z,Nip47ReplyTimeoutError:B,Nip47PublishError:F,Nip47ResponseDecodingError:H,Nip47ResponseValidationError:J,Nip47UnexpectedResponseError:G,Nip47NetworkError:D,NWCs:V,NWCClient:X},$={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions",multi_pay_invoice:"sendMultiPayment",multi_pay_keysend:"multiKeysend",sign_message:"signMessage"},Q=/*#__PURE__*/function(){function e(e){this._enabled=!1,this.client=void 0,this.subscribers=void 0,this.client=new X(e),this.subscribers={}}e.withNewSecret=function(n){return(n=n||{}).secret=t(),new e(n)};var n=e.prototype;return n.on=function(e,t){this.subscribers[e]=t},n.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},n.getNostrWalletConnectUrl=function(e){return void 0===e&&(e=!0),console.warn("getNostrWalletConnectUrl is deprecated. Please use client.getNostrWalletConnectUrl instead."),this.client.getNostrWalletConnectUrl(e)},n.getPublicKey=function(){return this.client.getPublicKey()},n.signEvent=function(e){return this.client.signEvent(e)},n.getEventHash=function(e){return console.warn("getEventHash is deprecated. Please use client.getEventHash instead."),this.client.getEventHash(e)},n.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},n.close=function(){return this.client.close()},n.encrypt=function(e,t){try{return console.warn("encrypt is deprecated. Please use client.encrypt instead."),Promise.resolve(this.client.encrypt(e,t))}catch(e){return Promise.reject(e)}},n.decrypt=function(e,t){try{return console.warn("decrypt is deprecated. Please use client.decrypt instead."),Promise.resolve(this.client.decrypt(e,t))}catch(e){return Promise.reject(e)}},n.getAuthorizationUrl=function(e){return console.warn("getAuthorizationUrl is deprecated. Please use client.getAuthorizationUrl instead."),this.client.getAuthorizationUrl(e)},n.initNWC=function(e){return void 0===e&&(e={}),console.warn("initNWC is deprecated. Please use client.initNWC instead."),this.client.initNWC(e)},n.getInfo=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return function(r,o){try{var i=Promise.resolve(e.client.getInfo()).then(function(r){var o={methods:r.methods.map(function(e){return $[e]}),node:{alias:r.alias,pubkey:r.pubkey,color:r.color},supports:t,version:n};return e.notify("getInfo",o),o})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(e){return console.error("Using minimal getInfo",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},n.getBalance=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){return Promise.resolve(e.client.getBalance()).then(function(t){var n={balance:Math.floor(t.balance/1e3),currency:"sats"};return e.notify("getBalance",n),n})})}catch(e){return Promise.reject(e)}},n.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payInvoice({invoice:e})).then(function(e){var n={preimage:e.preimage};return t.notify("sendPayment",n),n})})}catch(e){return Promise.reject(e)}},n.sendPaymentAsync=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return t.client.payInvoice({invoice:e}),t.notify("sendPaymentAsync",{}),{}})}catch(e){return Promise.reject(e)}},n.keysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payKeysend(ee(e))).then(function(e){var n={preimage:e.preimage};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},n.signMessage=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.signMessage({message:e})).then(function(e){var n={message:e.message,signature:e.signature};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},n.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return Promise.resolve(t.client.makeInvoice({amount:1e3*o,description:null==r?void 0:r.defaultMemo})).then(function(e){var n={paymentRequest:e.invoice};return t.notify("makeInvoice",n),n})})}catch(e){return Promise.reject(e)}},n.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.lookupInvoice({invoice:e.paymentRequest,payment_hash:e.paymentHash})).then(function(e){var n={preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at};return t.notify("lookupInvoice",n),n})})}catch(e){return Promise.reject(e)}},n.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.listTransactions(e)).then(function(e){var n={transactions:e.transactions.map(Z)};return t.notify("listTransactions",n),n})})}catch(e){return Promise.reject(e)}},n.sendMultiPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayInvoice({invoices:e.map(function(e,t){return{invoice:e,id:t.toString()}})})).then(function(n){var r={payments:n.invoices.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find paymentRequest matching response d tag");return{paymentRequest:n,preimage:t.preimage}}),errors:[]};return t.notify("sendMultiPayment",r),r})})}catch(e){return Promise.reject(e)}},n.multiKeysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayKeysend({keysends:e.map(function(e,t){return l({},ee(e),{id:t.toString()})})})).then(function(n){var r={keysends:n.keysends.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find keysend matching response d tag");return{keysend:n,preimage:t.preimage}}),errors:[]};return t.notify("multiKeysend",r),r})})}catch(e){return Promise.reject(e)}},n.lnurl=function(e){throw new Error("Method not implemented.")},n.request=function(e,t){throw new Error("Method not implemented.")},n.verifyMessage=function(e,t){throw new Error("Method not implemented.")},n.checkEnabled=function(){try{if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function");return Promise.resolve()}catch(e){return Promise.reject(e)}},a(e,[{key:"relay",get:function(){return console.warn("relay is deprecated. Please use client.relay instead."),this.client.relay}},{key:"relayUrl",get:function(){return console.warn("relayUrl is deprecated. Please use client.relayUrl instead."),this.client.relayUrl}},{key:"walletPubkey",get:function(){return console.warn("walletPubkey is deprecated. Please use client.walletPubkey instead."),this.client.walletPubkey}},{key:"options",get:function(){return this.client.options}},{key:"secret",get:function(){return console.warn("secret is deprecated. Please use client.secret instead."),this.client.secret}},{key:"nostrWalletConnectUrl",get:function(){return console.warn("nostrWalletConnectUrl is deprecated. Please use client.nostrWalletConnectUrl instead."),this.client.nostrWalletConnectUrl}},{key:"connected",get:function(){return console.warn("connected is deprecated. Please use client.connected instead."),this.client.connected}},{key:"publicKey",get:function(){return console.warn("publicKey is deprecated. Please use client.publicKey instead."),this.client.publicKey}}]),e}();function Z(e){return l({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}function ee(e){return{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:w((new TextEncoder).encode(e[1]))}}):[]}}var te=Q;function ne(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,custom_records:t}}var re=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new S(e):e,this.defaultRequestOptions=l({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return l({},e,{custom_records:e.customRecords})})}):(n="/payments/keysend",r=l({},e,{custom_records:e.customRecords})),E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return ne(e)})}):(n="/payments/keysend",r=ne(e)),E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",custom_records:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return E(l({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function oe(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function ie(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var se={__proto__:null,NostrWebLNProvider:Q,NWC:te,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new re(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=oe(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(oe(function(){return ie(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(oe(function(){return ie(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(oe(function(){return ie(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),u=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!u){u=!0,console.info("Processing OAuth code response");var r=n.payload.code,c=ie(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new re(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(c&&c.then)return c.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};export{re as Client,x as auth,Y as nwc,k as types,se as webln}; | ||
import e from"emittery";import{generateSecretKey as t,Relay as n,nip19 as r,finalizeEvent as o,getEventHash as i,nip04 as s,getPublicKey as c}from"nostr-tools";function u(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function a(e,t,n){return t&&u(e.prototype,t),n&&u(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(this,arguments)}function h(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,d(e,t)}function f(e){return f=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},f(e)}function d(e,t){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},d(e,t)}function m(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function p(e,t,n){return p=m()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&d(o,n.prototype),o},p.apply(null,arguments)}function v(e){var t="function"==typeof Map?new Map:void 0;return v=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return p(e,arguments,f(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,e)},v(e)}function y(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function g(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function P(e,t){return"Basic "+btoa(e+":"+t)}var w=function(e){return e.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},"")},b=/*#__PURE__*/function(e){function t(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return h(t,e),t}(/*#__PURE__*/v(Error)),_={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:b},k=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],E=function(e){return Promise.resolve(T(e)).then(function(e){return e.json()})},T=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,c=e.max_retries,u=e.base_url,a=void 0===u?A:u,h=e.user_agent,f=e.headers,d=y(e,k);try{var m=function(e){return Promise.resolve(N(p.toString(),l({headers:l({},v?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,f,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:s,body:v?JSON.stringify(i):void 0},d),c)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new b(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},p=new URL(a+n);p.search=g(o);var v="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(p.href,s)).then(m):m(void 0))}catch(e){return Promise.reject(e)}},N=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),c=Number(o.headers.get("x-rate-limit-remaining")),u=1e3*s-Date.now(),a=1e3;return 0===c&&(a=u),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},A="https://api.getalby.com",R=["expires_in"],j=["token"];function q(e){var t=e.expires_in;return l({},y(e,R),!!t&&{expires_at:Date.now()+1e3*t})}var O=/*#__PURE__*/function(){function t(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;var n=t.token,r=y(t,j);this.options=l({client_secret:""},r),this.token=n,this._refreshAccessTokenPromise=null}var n=t.prototype;return n.on=function(e,t){this._tokenEvents.on(e,t)},n.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var i=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,i=o.client_id,s=o.client_secret,c=o.request_options,u=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(E(l({},c,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:u,method:"POST",headers:l({},null==c?void 0:c.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:P(i,s)})}))).then(function(n){var r=q(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},n.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},n.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,i=n.callback,s=n.request_options,c=n.user_agent,u=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!u)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!i)throw new Error("callback is required");return Promise.resolve(E(l({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:u,client_id:r,redirect_uri:i},user_agent:c,method:"POST",headers:l({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:P(r,o)})}))).then(function(e){var n=q(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},n.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=g(l({},e,{client_id:i,scope:c.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,i=o.client_id,s=o.callback,c=o.scopes;if(!s)throw new Error("callback required");if(!c)throw new Error("scopes required");var u=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(e){return Promise.reject(e)}},n.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},n._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=w(t),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},t}(),x=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),U={__proto__:null,OAuth2User:O,OAuth2Bearer:x};if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");const S=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function I(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=S[e[n]];return t}function C(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let t=0;t<n.length;t++){const r=2*t,o=e.slice(r,r+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[t]=i}return n}function W(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function M(e,t,n){if(!e.s){if(n instanceof L){if(!n.s)return void(n.o=M.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(M.bind(null,e,t),M.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var L=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,o=this.s;if(o){var i=1&o?t:n;if(i){try{M(r,1,i(this.v))}catch(e){M(r,2,e)}return r}return this}return this.o=function(e){try{var o=e.v;1&e.s?M(r,1,t?t(o):o):n?M(r,1,n(o)):M(r,2,o)}catch(e){M(r,2,e)}},r},e}();function K(e){return e instanceof L&&1&e.s}var z=/*#__PURE__*/function(e){function t(t,n){var r;return(r=e.call(this,t)||this).error=void 0,r.code=void 0,r.error=t,r.code=n,r}return h(t,e),t}(/*#__PURE__*/v(Error)),B=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),F=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),H=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(F),J=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(F),G=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),D=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),V=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),X=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),Y=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return h(t,e),t}(z),$={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},Q=/*#__PURE__*/function(){function e(t){var o;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.lud16=void 0,this.walletPubkey=void 0,this.options=void 0,t&&t.nostrWalletConnectUrl&&(t=l({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var i=$[(null==(o=t)?void 0:o.providerName)||"alby"];this.options=l({},i,t||{}),this.relayUrl=this.options.relayUrl,this.relay=new n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?r.decode(this.options.secret).data:this.options.secret),this.lud16=this.options.lud16,this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?r.decode(this.options.walletPubkey).data:this.options.walletPubkey,void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://").replace("nostrwalletconnect:","http://").replace("nostr+walletconnect:","http://");var t=new URL(e),n=t.searchParams.get("relay");if(!n)throw new Error("No relay URL found in connection string");var r={walletPubkey:t.host,relayUrl:n},o=t.searchParams.get("secret");o&&(r.secret=o);var i=t.searchParams.get("lud16");return i&&(r.lud16=i),r},e.withNewSecret=function(n){return(n=n||{}).secret=I(t()),new e(n)};var u=e.prototype;return u.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},u.getPublicKey=function(){return Promise.resolve(this.publicKey)},u.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(o(e,C(this.secret)))},u.getEventHash=function(e){return i(e)},u.close=function(){return this.relay.close()},u.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},u.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},u.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t},u.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(c),window.removeEventListener("message",n),i&&i.close())},c=setInterval(function(){i&&i.closed&&(clearInterval(c),window.removeEventListener("message",s),o(new Error("Popup closed")))},500);window.addEventListener("message",s)}else o(new Error("failed to execute window.open"))})},u.getWalletServiceSupportedMethods=function(){try{return console.warn("getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead."),Promise.resolve(this.getWalletServiceInfo()).then(function(e){return e.capabilities})}catch(e){return Promise.reject(e)}},u.getWalletServiceInfo=function(){try{var e=this;return Promise.resolve(e._checkConnected()).then(function(){return Promise.resolve(new Promise(function(t,n){var r=[],o=e.relay.subscribe([{kinds:[13194],limit:1,authors:[e.walletPubkey]}],{eoseTimeout:1e4});o.onevent=function(e){r.push(e)},o.oneose=function(){o.close(),t(r)}})).then(function(e){var t;if(!e.length)throw new Error("no info event (kind 13194) returned from relay");var n=e[0].content,r=e[0].tags.find(function(e){return"notifications"===e[0]});return{capabilities:n.split(/[ |,]/g),notifications:(null==r||null==(t=r[1])?void 0:t.split(" "))||[]}})})}catch(e){return Promise.reject(e)}},u.getInfo=function(){try{var e=this;return Promise.resolve(W(function(){return Promise.resolve(e.executeNip47Request("get_info",{},function(e){return!!e.methods}))},function(e){throw console.error("Failed to request get_info",e),e}))}catch(e){return Promise.reject(e)}},u.getBudget=function(){try{var e=this;return Promise.resolve(W(function(){return Promise.resolve(e.executeNip47Request("get_budget",{},function(e){return void 0!==e}))},function(e){throw console.error("Failed to request get_budget",e),e}))}catch(e){return Promise.reject(e)}},u.getBalance=function(){try{var e=this;return Promise.resolve(W(function(){return Promise.resolve(e.executeNip47Request("get_balance",{},function(e){return void 0!==e.balance}))},function(e){throw console.error("Failed to request get_balance",e),e}))}catch(e){return Promise.reject(e)}},u.payInvoice=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeNip47Request("pay_invoice",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},u.payKeysend=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeNip47Request("pay_keysend",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},u.signMessage=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeNip47Request("sign_message",e,function(t){return t.message===e.message&&!!t.signature}))},function(e){throw console.error("Failed to request sign_message",e),e}))}catch(e){return Promise.reject(e)}},u.multiPayInvoice=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_invoice",e,e.invoices.length,function(e){return!!e.preimage})).then(function(e){return{invoices:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},u.multiPayKeysend=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_keysend",e,e.keysends.length,function(e){return!!e.preimage})).then(function(e){return{keysends:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},u.makeInvoice=function(e){try{var t=this;return Promise.resolve(W(function(){if(!e.amount)throw new Error("No amount specified");return Promise.resolve(t.executeNip47Request("make_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request make_invoice",e),e}))}catch(e){return Promise.reject(e)}},u.lookupInvoice=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeNip47Request("lookup_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request lookup_invoice",e),e}))}catch(e){return Promise.reject(e)}},u.listTransactions=function(e){try{var t=this;return Promise.resolve(W(function(){return Promise.resolve(t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions}))},function(e){throw console.error("Failed to request list_transactions",e),e}))}catch(e){return Promise.reject(e)}},u.subscribeNotifications=function(e,t){try{var n,r,o,i=this,s=!0;return function(){try{var c=function(e,t,n){for(var r;;){var o=e();if(K(o)&&(o=o.v),!o)return i;if(o.then){r=0;break}var i=n();if(i&&i.then){if(!K(i)){r=1;break}i=i.s}}var s=new L,c=M.bind(null,s,2);return(0===r?o.then(a):1===r?i.then(u):(void 0).then(function(){(o=e())?o.then?o.then(a).then(void 0,c):a(o):M(s,1,i)})).then(void 0,c),s;function u(t){i=t;do{if(!(o=e())||K(o)&&!o.v)return void M(s,1,i);if(o.then)return void o.then(a).then(void 0,c);K(i=n())&&(i=i.v)}while(!i||!i.then);i.then(u).then(void 0,c)}function a(e){e?(i=n())&&i.then?i.then(u).then(void 0,c):u(i):M(s,1,i)}}(function(){return!!s},0,function(){function c(){var e=function(){if(s)return Promise.resolve(new Promise(function(e){return setTimeout(e,1e3)})).then(function(){})}();if(e&&e.then)return e.then(function(){})}var u=W(function(){return Promise.resolve(i._checkConnected()).then(function(){return o=i.relay.subscribe([{kinds:[23196],authors:[i.walletPubkey],"#p":[i.publicKey]}],{}),console.info("subscribed to relay"),o.onevent=function(n){try{return Promise.resolve(i.decrypt(i.walletPubkey,n.content)).then(function(n){var r;try{r=JSON.parse(n)}catch(e){return void console.error("Failed to parse decrypted event content",e)}r.notification?(!t||t.indexOf(r.notification_type)>-1)&&e(r):console.error("No notification in response",r)})}catch(e){return Promise.reject(e)}},Promise.resolve(new Promise(function(e){n=function(){e()},i.relay.onclose=r=function(){console.info("relay disconnected"),null==n||n()}})).then(function(){void 0!==r&&(i.relay.onclose=null)})})},function(e){console.error("error subscribing to notifications",e||"unknown relay error")});return u&&u.then?u.then(c):c()});c&&c.then&&c.then(function(){})}catch(e){Promise.reject(e)}}(),Promise.resolve(function(){var e;s=!1,null==n||n(),null==(e=o)||e.close()})}catch(e){return Promise.reject(e)}},u.executeNip47Request=function(e,t,n){try{var r=this;return Promise.resolve(r._checkConnected()).then(function(){return new Promise(function(o,i){try{return Promise.resolve(r.encrypt(r.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",r.walletPubkey]],content:e};return Promise.resolve(r.signEvent(t)).then(function(e){var t=r.relay.subscribe([{kinds:[23195],authors:[r.walletPubkey],"#e":[e.id]}],{}),s=setTimeout(function(){t.close(),i(new J("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.onevent=function(e){try{return clearTimeout(s),t.close(),Promise.resolve(r.decrypt(r.walletPubkey,e.content)).then(function(e){var r,c,u;try{r=JSON.parse(e)}catch(e){return clearTimeout(s),t.close(),void i(new D("failed to deserialize response","INTERNAL"))}r.result?n(r.result)?o(r.result):(clearTimeout(s),t.close(),i(new V("response from NWC failed validation: "+JSON.stringify(r.result),"INTERNAL"))):(clearTimeout(s),t.close(),i(new B((null==(c=r.error)?void 0:c.message)||"unknown Error",(null==(u=r.error)?void 0:u.code)||"INTERNAL")))})}catch(e){return Promise.reject(e)}};var c=setTimeout(function(){t.close(),i(new H("publish timeout: "+e.id,"INTERNAL"))},5e3),u=W(function(){return Promise.resolve(r.relay.publish(e)).then(function(){clearTimeout(c)})},function(e){clearTimeout(c),i(new G("failed to publish: "+e,"INTERNAL"))});if(u&&u.then)return u.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},u.executeMultiNip47Request=function(e,t,n,r){try{var o=this;return Promise.resolve(o._checkConnected()).then(function(){var i=[];return new Promise(function(s,c){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.subscribe([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}],{}),u=setTimeout(function(){t.close(),c(new J("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.onevent=function(e){try{return Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(o){var a;try{a=JSON.parse(o)}catch(e){clearTimeout(u),t.close(),c(new D("failed to deserialize response","INTERNAL"))}if(a.result){var h;if(!r(a.result))return clearTimeout(u),t.close(),void c(new V("Response from NWC failed validation: "+JSON.stringify(a.result),"INTERNAL"));var f=null==(h=e.tags.find(function(e){return"d"===e[0]}))?void 0:h[1];if(void 0===f)return clearTimeout(u),t.close(),void c(new V("No d tag found in response event","INTERNAL"));i.push(l({},a.result,{dTag:f})),i.length===n&&(clearTimeout(u),t.close(),s(i))}else{var d,m;clearTimeout(u),t.close(),c(new X(null==(d=a.error)?void 0:d.message,null==(m=a.error)?void 0:m.code))}})}catch(e){return Promise.reject(e)}};var a=setTimeout(function(){t.close(),c(new H("Publish timeout: "+e.id,"INTERNAL"))},5e3),h=W(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(a)})},function(e){clearTimeout(a),c(new G("Failed to publish: "+e,"INTERNAL"))});if(h&&h.then)return h.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},u._checkConnected=function(){try{var e=this;if(!e.secret)throw new Error("Missing secret key");if(!e.relayUrl)throw new Error("Missing relay url");return Promise.resolve(W(function(){var t=function(){if(!e.relay.connected)return Promise.resolve(e.relay.connect()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(){throw console.error("failed to connect to relay",e.relayUrl),new Y("Failed to connect to "+e.relayUrl,"OTHER")}))}catch(e){return Promise.reject(e)}},a(e,[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return this.relay.connected}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return c(C(this.secret))}}]),e}(),Z={__proto__:null,Nip47Error:z,Nip47WalletError:B,Nip47TimeoutError:F,Nip47PublishTimeoutError:H,Nip47ReplyTimeoutError:J,Nip47PublishError:G,Nip47ResponseDecodingError:D,Nip47ResponseValidationError:V,Nip47UnexpectedResponseError:X,Nip47NetworkError:Y,NWCs:$,NWCClient:Q},ee={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions",multi_pay_invoice:"sendMultiPayment",multi_pay_keysend:"multiKeysend",sign_message:"signMessage"},te=/*#__PURE__*/function(){function e(e){this._enabled=!1,this.client=void 0,this.subscribers=void 0,this.client=new Q(e),this.subscribers={}}e.withNewSecret=function(n){return(n=n||{}).secret=I(t()),new e(n)};var n=e.prototype;return n.on=function(e,t){this.subscribers[e]=t},n.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},n.getNostrWalletConnectUrl=function(e){return void 0===e&&(e=!0),console.warn("getNostrWalletConnectUrl is deprecated. Please use client.getNostrWalletConnectUrl instead."),this.client.getNostrWalletConnectUrl(e)},n.getPublicKey=function(){return this.client.getPublicKey()},n.signEvent=function(e){return this.client.signEvent(e)},n.getEventHash=function(e){return console.warn("getEventHash is deprecated. Please use client.getEventHash instead."),this.client.getEventHash(e)},n.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},n.close=function(){return this.client.close()},n.encrypt=function(e,t){try{return console.warn("encrypt is deprecated. Please use client.encrypt instead."),Promise.resolve(this.client.encrypt(e,t))}catch(e){return Promise.reject(e)}},n.decrypt=function(e,t){try{return console.warn("decrypt is deprecated. Please use client.decrypt instead."),Promise.resolve(this.client.decrypt(e,t))}catch(e){return Promise.reject(e)}},n.getAuthorizationUrl=function(e){return console.warn("getAuthorizationUrl is deprecated. Please use client.getAuthorizationUrl instead."),this.client.getAuthorizationUrl(e)},n.initNWC=function(e){return void 0===e&&(e={}),console.warn("initNWC is deprecated. Please use client.initNWC instead."),this.client.initNWC(e)},n.getInfo=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return function(r,o){try{var i=Promise.resolve(e.client.getInfo()).then(function(r){var o={methods:r.methods.map(function(e){return ee[e]}),node:{alias:r.alias,pubkey:r.pubkey,color:r.color},supports:t,version:n};return e.notify("getInfo",o),o})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(e){return console.error("Using minimal getInfo",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},n.getBalance=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){return Promise.resolve(e.client.getBalance()).then(function(t){var n={balance:Math.floor(t.balance/1e3),currency:"sats"};return e.notify("getBalance",n),n})})}catch(e){return Promise.reject(e)}},n.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payInvoice({invoice:e})).then(function(e){var n={preimage:e.preimage};return t.notify("sendPayment",n),n})})}catch(e){return Promise.reject(e)}},n.sendPaymentAsync=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return t.client.payInvoice({invoice:e}),t.notify("sendPaymentAsync",{}),{}})}catch(e){return Promise.reject(e)}},n.keysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payKeysend(re(e))).then(function(e){var n={preimage:e.preimage};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},n.signMessage=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.signMessage({message:e})).then(function(e){var n={message:e.message,signature:e.signature};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},n.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return Promise.resolve(t.client.makeInvoice({amount:1e3*o,description:null==r?void 0:r.defaultMemo})).then(function(e){var n={paymentRequest:e.invoice};return t.notify("makeInvoice",n),n})})}catch(e){return Promise.reject(e)}},n.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.lookupInvoice({invoice:e.paymentRequest,payment_hash:e.paymentHash})).then(function(e){var n={preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at};return t.notify("lookupInvoice",n),n})})}catch(e){return Promise.reject(e)}},n.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.listTransactions(e)).then(function(e){var n={transactions:e.transactions.map(ne)};return t.notify("listTransactions",n),n})})}catch(e){return Promise.reject(e)}},n.sendMultiPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayInvoice({invoices:e.map(function(e,t){return{invoice:e,id:t.toString()}})})).then(function(n){var r={payments:n.invoices.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find paymentRequest matching response d tag");return{paymentRequest:n,preimage:t.preimage}}),errors:[]};return t.notify("sendMultiPayment",r),r})})}catch(e){return Promise.reject(e)}},n.multiKeysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayKeysend({keysends:e.map(function(e,t){return l({},re(e),{id:t.toString()})})})).then(function(n){var r={keysends:n.keysends.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find keysend matching response d tag");return{keysend:n,preimage:t.preimage}}),errors:[]};return t.notify("multiKeysend",r),r})})}catch(e){return Promise.reject(e)}},n.lnurl=function(e){throw new Error("Method not implemented.")},n.request=function(e,t){throw new Error("Method not implemented.")},n.verifyMessage=function(e,t){throw new Error("Method not implemented.")},n.checkEnabled=function(){try{if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function");return Promise.resolve()}catch(e){return Promise.reject(e)}},a(e,[{key:"relay",get:function(){return console.warn("relay is deprecated. Please use client.relay instead."),this.client.relay}},{key:"relayUrl",get:function(){return console.warn("relayUrl is deprecated. Please use client.relayUrl instead."),this.client.relayUrl}},{key:"walletPubkey",get:function(){return console.warn("walletPubkey is deprecated. Please use client.walletPubkey instead."),this.client.walletPubkey}},{key:"options",get:function(){return this.client.options}},{key:"secret",get:function(){return console.warn("secret is deprecated. Please use client.secret instead."),this.client.secret}},{key:"nostrWalletConnectUrl",get:function(){return console.warn("nostrWalletConnectUrl is deprecated. Please use client.nostrWalletConnectUrl instead."),this.client.nostrWalletConnectUrl}},{key:"connected",get:function(){return console.warn("connected is deprecated. Please use client.connected instead."),this.client.connected}},{key:"publicKey",get:function(){return console.warn("publicKey is deprecated. Please use client.publicKey instead."),this.client.publicKey}}]),e}();function ne(e){return l({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}function re(e){return{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:w((new TextEncoder).encode(e[1]))}}):[]}}var oe=te;function ie(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,custom_records:t}}var se=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new x(e):e,this.defaultRequestOptions=l({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return l({},e,{custom_records:e.customRecords})})}):(n="/payments/keysend",r=l({},e,{custom_records:e.customRecords})),E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return ie(e)})}):(n="/payments/keysend",r=ie(e)),E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",custom_records:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return E(l({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return E(l({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function ce(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function ue(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var ae={__proto__:null,NostrWebLNProvider:te,NWC:oe,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new se(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=ce(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(ce(function(){return ue(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(ce(function(){return ue(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(ce(function(){return ue(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),c=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!c){c=!0,console.info("Processing OAuth code response");var r=n.payload.code,u=ue(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new se(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(u&&u.then)return u.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};export{se as Client,U as auth,Z as nwc,_ as types,ae as webln}; |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("emittery"),require("nostr-tools")):"function"==typeof define&&define.amd?define(["exports","emittery","nostr-tools"],t):t((e||self).sdk={},e.emittery,e.nostrTools)}(this,function(e,t,n){function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/r(t);function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function s(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u.apply(this,arguments)}function c(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,l(e,t)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function l(e,t){return l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},l(e,t)}function h(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function f(e,t,n){return f=h()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&l(o,n.prototype),o},f.apply(null,arguments)}function d(e){var t="function"==typeof Map?new Map:void 0;return d=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return f(e,arguments,a(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),l(n,e)},d(e)}function m(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function p(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function v(e,t){return"Basic "+btoa(e+":"+t)}var y=function(e){return e.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},"")},g=/*#__PURE__*/function(e){function t(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return c(t,e),t}(/*#__PURE__*/d(Error)),P={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:g},w=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],b=function(e){return Promise.resolve(k(e)).then(function(e){return e.json()})},k=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,c=e.max_retries,a=e.base_url,l=void 0===a?E:a,h=e.user_agent,f=e.headers,d=m(e,w);try{var v=function(e){return Promise.resolve(_(y.toString(),u({headers:u({},P?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,f,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:s,body:P?JSON.stringify(i):void 0},d),c)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new g(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},y=new URL(l+n);y.search=p(o);var P="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(y.href,s)).then(v):v(void 0))}catch(e){return Promise.reject(e)}},_=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),u=Number(o.headers.get("x-rate-limit-remaining")),c=1e3*s-Date.now(),a=1e3;return 0===u&&(a=c),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},E="https://api.getalby.com",T=["expires_in"],N=["token"];function j(e){var t=e.expires_in;return u({},m(e,T),!!t&&{expires_at:Date.now()+1e3*t})}var R=/*#__PURE__*/function(){function e(e){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new o.default;var t=e.token,n=m(e,N);this.options=u({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}var t=e.prototype;return t.on=function(e,t){this._tokenEvents.on(e,t)},t.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var i=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,i=o.client_id,s=o.client_secret,c=o.request_options,a=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(b(u({},c,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:u({},null==c?void 0:c.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:v(i,s)})}))).then(function(n){var r=j(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},t.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},t.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,i=n.callback,s=n.request_options,c=n.user_agent,a=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!a)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!i)throw new Error("callback is required");return Promise.resolve(b(u({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:i},user_agent:c,method:"POST",headers:u({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:v(r,o)})}))).then(function(e){var n=j(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},t.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=p(u({},e,{client_id:i,scope:c.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,i=o.client_id,s=o.callback,c=o.scopes;if(!s)throw new Error("callback required");if(!c)throw new Error("scopes required");var a=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},t.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},t._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=y(t),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},e}(),q=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),A={__proto__:null,OAuth2User:R,OAuth2Bearer:q};function O(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function x(e,t,n){if(!e.s){if(n instanceof S){if(!n.s)return void(n.o=x.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(x.bind(null,e,t),x.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var S=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,o=this.s;if(o){var i=1&o?t:n;if(i){try{x(r,1,i(this.v))}catch(e){x(r,2,e)}return r}return this}return this.o=function(e){try{var o=e.v;1&e.s?x(r,1,t?t(o):o):n?x(r,1,n(o)):x(r,2,o)}catch(e){x(r,2,e)}},r},e}();function U(e){return e instanceof S&&1&e.s}var I=/*#__PURE__*/function(e){function t(t,n){var r;return(r=e.call(this,t)||this).error=void 0,r.code=void 0,r.error=t,r.code=n,r}return c(t,e),t}(/*#__PURE__*/d(Error)),C=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),W=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),M=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(W),K=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(W),L=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),z=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),B=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),F=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),H=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return c(t,e),t}(I),J={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},G=/*#__PURE__*/function(){function e(t){var r;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.lud16=void 0,this.walletPubkey=void 0,this.options=void 0,t&&t.nostrWalletConnectUrl&&(t=u({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var o=J[(null==(r=t)?void 0:r.providerName)||"alby"];this.options=u({},o,t||{}),this.relayUrl=this.options.relayUrl,this.relay=n.relayInit(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?n.nip19.decode(this.options.secret).data:this.options.secret),this.lud16=this.options.lud16,this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?n.nip19.decode(this.options.walletPubkey).data:this.options.walletPubkey,void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://").replace("nostrwalletconnect:","http://").replace("nostr+walletconnect:","http://");var t=new URL(e),n=t.searchParams.get("relay");if(!n)throw new Error("No relay URL found in connection string");var r={walletPubkey:t.host,relayUrl:n},o=t.searchParams.get("secret");o&&(r.secret=o);var i=t.searchParams.get("lud16");return i&&(r.lud16=i),r},e.withNewSecret=function(t){return(t=t||{}).secret=n.generatePrivateKey(),new e(t)};var t=e.prototype;return t.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},t.getPublicKey=function(){return Promise.resolve(this.publicKey)},t.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(n.finishEvent(e,this.secret))},t.getEventHash=function(e){return n.getEventHash(e)},t.close=function(){return this.relay.close()},t.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},t.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},t.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t},t.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(u),window.removeEventListener("message",n),i&&i.close())},u=setInterval(function(){i&&i.closed&&(clearInterval(u),window.removeEventListener("message",s),o(new Error("Popup closed")))},500);window.addEventListener("message",s)}else o(new Error("failed to execute window.open"))})},t.getWalletServiceSupportedMethods=function(){try{return console.warn("getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead."),Promise.resolve(this.getWalletServiceInfo()).then(function(e){return e.capabilities})}catch(e){return Promise.reject(e)}},t.getWalletServiceInfo=function(){try{var e=this;return Promise.resolve(e._checkConnected()).then(function(){return Promise.resolve(e.relay.list([{kinds:[13194],limit:1,authors:[e.walletPubkey]}],{eoseSubTimeout:1e4})).then(function(e){var t;if(!e.length)throw new Error("no info event (kind 13194) returned from relay");var n=e[0].content,r=e[0].tags.find(function(e){return"notifications"===e[0]});return{capabilities:n.split(/[ |,]/g),notifications:(null==r||null==(t=r[1])?void 0:t.split(" "))||[]}})})}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{var e=this;return Promise.resolve(O(function(){return Promise.resolve(e.executeNip47Request("get_info",{},function(e){return!!e.methods}))},function(e){throw console.error("Failed to request get_info",e),e}))}catch(e){return Promise.reject(e)}},t.getBudget=function(){try{var e=this;return Promise.resolve(O(function(){return Promise.resolve(e.executeNip47Request("get_budget",{},function(e){return void 0!==e}))},function(e){throw console.error("Failed to request get_budget",e),e}))}catch(e){return Promise.reject(e)}},t.getBalance=function(){try{var e=this;return Promise.resolve(O(function(){return Promise.resolve(e.executeNip47Request("get_balance",{},function(e){return void 0!==e.balance}))},function(e){throw console.error("Failed to request get_balance",e),e}))}catch(e){return Promise.reject(e)}},t.payInvoice=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeNip47Request("pay_invoice",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.payKeysend=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeNip47Request("pay_keysend",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},t.signMessage=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeNip47Request("sign_message",e,function(t){return t.message===e.message&&!!t.signature}))},function(e){throw console.error("Failed to request sign_message",e),e}))}catch(e){return Promise.reject(e)}},t.multiPayInvoice=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_invoice",e,e.invoices.length,function(e){return!!e.preimage})).then(function(e){return{invoices:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.multiPayKeysend=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_keysend",e,e.keysends.length,function(e){return!!e.preimage})).then(function(e){return{keysends:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return Promise.resolve(O(function(){if(!e.amount)throw new Error("No amount specified");return Promise.resolve(t.executeNip47Request("make_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request make_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.lookupInvoice=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeNip47Request("lookup_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request lookup_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.listTransactions=function(e){try{var t=this;return Promise.resolve(O(function(){return Promise.resolve(t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions}))},function(e){throw console.error("Failed to request list_transactions",e),e}))}catch(e){return Promise.reject(e)}},t.subscribeNotifications=function(e,t){try{var n,r,o,i=this,s=!0;return function(){try{var u=function(e,t,n){for(var r;;){var o=e();if(U(o)&&(o=o.v),!o)return i;if(o.then){r=0;break}var i=n();if(i&&i.then){if(!U(i)){r=1;break}i=i.s}}var s=new S,u=x.bind(null,s,2);return(0===r?o.then(a):1===r?i.then(c):(void 0).then(function(){(o=e())?o.then?o.then(a).then(void 0,u):a(o):x(s,1,i)})).then(void 0,u),s;function c(t){i=t;do{if(!(o=e())||U(o)&&!o.v)return void x(s,1,i);if(o.then)return void o.then(a).then(void 0,u);U(i=n())&&(i=i.v)}while(!i||!i.then);i.then(c).then(void 0,u)}function a(e){e?(i=n())&&i.then?i.then(c).then(void 0,u):c(i):x(s,1,i)}}(function(){return!!s},0,function(){function u(){var e=function(){if(s)return Promise.resolve(new Promise(function(e){return setTimeout(e,1e3)})).then(function(){})}();if(e&&e.then)return e.then(function(){})}var c=O(function(){return Promise.resolve(i._checkConnected()).then(function(){return o=i.relay.sub([{kinds:[23196],authors:[i.walletPubkey],"#p":[i.publicKey]}]),console.info("subscribed to relay"),o.on("event",function(n){try{return Promise.resolve(i.decrypt(i.walletPubkey,n.content)).then(function(n){var r;try{r=JSON.parse(n)}catch(e){return void console.error("Failed to parse decrypted event content",e)}r.notification?(!t||t.indexOf(r.notification_type)>-1)&&e(r):console.error("No notification in response",r)})}catch(e){return Promise.reject(e)}}),Promise.resolve(new Promise(function(e){n=function(){e()},i.relay.on("disconnect",r=function(){console.info("relay disconnected"),null==n||n()})})).then(function(){void 0!==r&&i.relay.off("disconnect",r)})})},function(e){console.error("error subscribing to notifications",e||"unknown relay error")});return c&&c.then?c.then(u):u()});u&&u.then&&u.then(function(){})}catch(e){Promise.reject(e)}}(),Promise.resolve(function(){var e;s=!1,null==n||n(),null==(e=o)||e.unsub()})}catch(e){return Promise.reject(e)}},t.executeNip47Request=function(e,t,n){try{var r=this;return Promise.resolve(r._checkConnected()).then(function(){return new Promise(function(o,i){try{return Promise.resolve(r.encrypt(r.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",r.walletPubkey]],content:e,pubkey:r.publicKey};return Promise.resolve(r.signEvent(t)).then(function(e){var t=r.relay.sub([{kinds:[23195],authors:[r.walletPubkey],"#e":[e.id]}]),s=setTimeout(function(){t.unsub(),i(new K("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.on("event",function(e){try{return clearTimeout(s),t.unsub(),Promise.resolve(r.decrypt(r.walletPubkey,e.content)).then(function(e){var r,u,c;try{r=JSON.parse(e)}catch(e){return clearTimeout(s),t.unsub(),void i(new z("failed to deserialize response","INTERNAL"))}r.result?n(r.result)?o(r.result):(clearTimeout(s),t.unsub(),i(new B("response from NWC failed validation: "+JSON.stringify(r.result),"INTERNAL"))):(clearTimeout(s),t.unsub(),i(new C((null==(u=r.error)?void 0:u.message)||"unknown Error",(null==(c=r.error)?void 0:c.code)||"INTERNAL")))})}catch(e){return Promise.reject(e)}});var u=setTimeout(function(){t.unsub(),i(new M("publish timeout: "+e.id,"INTERNAL"))},5e3),c=O(function(){return Promise.resolve(r.relay.publish(e)).then(function(){clearTimeout(u)})},function(e){clearTimeout(u),i(new L("failed to publish: "+e,"INTERNAL"))});if(c&&c.then)return c.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},t.executeMultiNip47Request=function(e,t,n,r){try{var o=this;return Promise.resolve(o._checkConnected()).then(function(){var i=[];return new Promise(function(s,c){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e,pubkey:o.publicKey};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}]),a=setTimeout(function(){t.unsub(),c(new K("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.on("event",function(e){try{return Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(o){var l;try{l=JSON.parse(o)}catch(e){clearTimeout(a),t.unsub(),c(new z("failed to deserialize response","INTERNAL"))}if(l.result){var h;if(!r(l.result))return clearTimeout(a),t.unsub(),void c(new B("Response from NWC failed validation: "+JSON.stringify(l.result),"INTERNAL"));var f=null==(h=e.tags.find(function(e){return"d"===e[0]}))?void 0:h[1];if(void 0===f)return clearTimeout(a),t.unsub(),void c(new B("No d tag found in response event","INTERNAL"));i.push(u({},l.result,{dTag:f})),i.length===n&&(clearTimeout(a),t.unsub(),s(i))}else{var d,m;clearTimeout(a),t.unsub(),c(new F(null==(d=l.error)?void 0:d.message,null==(m=l.error)?void 0:m.code))}})}catch(e){return Promise.reject(e)}});var l=setTimeout(function(){t.unsub(),c(new M("Publish timeout: "+e.id,"INTERNAL"))},5e3),h=O(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(l)})},function(e){clearTimeout(l),c(new L("Failed to publish: "+e,"INTERNAL"))});if(h&&h.then)return h.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},t._checkConnected=function(){try{var e=this;if(!e.secret)throw new Error("Missing secret key");return Promise.resolve(O(function(){return Promise.resolve(e.relay.connect()).then(function(){})},function(){throw console.error("failed to connect to relay",e.relayUrl),new H("Failed to connect to "+e.relayUrl,"OTHER")}))}catch(e){return Promise.reject(e)}},s(e,[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return 1===this.relay.status}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return n.getPublicKey(this.secret)}}]),e}(),D={__proto__:null,Nip47Error:I,Nip47WalletError:C,Nip47TimeoutError:W,Nip47PublishTimeoutError:M,Nip47ReplyTimeoutError:K,Nip47PublishError:L,Nip47ResponseDecodingError:z,Nip47ResponseValidationError:B,Nip47UnexpectedResponseError:F,Nip47NetworkError:H,NWCs:J,NWCClient:G},V={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions",multi_pay_invoice:"sendMultiPayment",multi_pay_keysend:"multiKeysend",sign_message:"signMessage"},X=/*#__PURE__*/function(){function e(e){this._enabled=!1,this.client=void 0,this.subscribers=void 0,this.client=new G(e),this.subscribers={}}e.withNewSecret=function(t){return(t=t||{}).secret=n.generatePrivateKey(),new e(t)};var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.getNostrWalletConnectUrl=function(e){return void 0===e&&(e=!0),console.warn("getNostrWalletConnectUrl is deprecated. Please use client.getNostrWalletConnectUrl instead."),this.client.getNostrWalletConnectUrl(e)},t.getPublicKey=function(){return this.client.getPublicKey()},t.signEvent=function(e){return this.client.signEvent(e)},t.getEventHash=function(e){return console.warn("getEventHash is deprecated. Please use client.getEventHash instead."),this.client.getEventHash(e)},t.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},t.close=function(){return this.client.close()},t.encrypt=function(e,t){try{return console.warn("encrypt is deprecated. Please use client.encrypt instead."),Promise.resolve(this.client.encrypt(e,t))}catch(e){return Promise.reject(e)}},t.decrypt=function(e,t){try{return console.warn("decrypt is deprecated. Please use client.decrypt instead."),Promise.resolve(this.client.decrypt(e,t))}catch(e){return Promise.reject(e)}},t.getAuthorizationUrl=function(e){return console.warn("getAuthorizationUrl is deprecated. Please use client.getAuthorizationUrl instead."),this.client.getAuthorizationUrl(e)},t.initNWC=function(e){return void 0===e&&(e={}),console.warn("initNWC is deprecated. Please use client.initNWC instead."),this.client.initNWC(e)},t.getInfo=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return function(r,o){try{var i=Promise.resolve(e.client.getInfo()).then(function(r){var o={methods:r.methods.map(function(e){return V[e]}),node:{alias:r.alias,pubkey:r.pubkey,color:r.color},supports:t,version:n};return e.notify("getInfo",o),o})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(e){return console.error("Using minimal getInfo",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},t.getBalance=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){return Promise.resolve(e.client.getBalance()).then(function(t){var n={balance:Math.floor(t.balance/1e3),currency:"sats"};return e.notify("getBalance",n),n})})}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payInvoice({invoice:e})).then(function(e){var n={preimage:e.preimage};return t.notify("sendPayment",n),n})})}catch(e){return Promise.reject(e)}},t.sendPaymentAsync=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return t.client.payInvoice({invoice:e}),t.notify("sendPaymentAsync",{}),{}})}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payKeysend($(e))).then(function(e){var n={preimage:e.preimage};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},t.signMessage=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.signMessage({message:e})).then(function(e){var n={message:e.message,signature:e.signature};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return Promise.resolve(t.client.makeInvoice({amount:1e3*o,description:null==r?void 0:r.defaultMemo})).then(function(e){var n={paymentRequest:e.invoice};return t.notify("makeInvoice",n),n})})}catch(e){return Promise.reject(e)}},t.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.lookupInvoice({invoice:e.paymentRequest,payment_hash:e.paymentHash})).then(function(e){var n={preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at};return t.notify("lookupInvoice",n),n})})}catch(e){return Promise.reject(e)}},t.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.listTransactions(e)).then(function(e){var n={transactions:e.transactions.map(Y)};return t.notify("listTransactions",n),n})})}catch(e){return Promise.reject(e)}},t.sendMultiPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayInvoice({invoices:e.map(function(e,t){return{invoice:e,id:t.toString()}})})).then(function(n){var r={payments:n.invoices.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find paymentRequest matching response d tag");return{paymentRequest:n,preimage:t.preimage}}),errors:[]};return t.notify("sendMultiPayment",r),r})})}catch(e){return Promise.reject(e)}},t.multiKeysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayKeysend({keysends:e.map(function(e,t){return u({},$(e),{id:t.toString()})})})).then(function(n){var r={keysends:n.keysends.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find keysend matching response d tag");return{keysend:n,preimage:t.preimage}}),errors:[]};return t.notify("multiKeysend",r),r})})}catch(e){return Promise.reject(e)}},t.lnurl=function(e){throw new Error("Method not implemented.")},t.request=function(e,t){throw new Error("Method not implemented.")},t.verifyMessage=function(e,t){throw new Error("Method not implemented.")},t.checkEnabled=function(){try{if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function");return Promise.resolve()}catch(e){return Promise.reject(e)}},s(e,[{key:"relay",get:function(){return console.warn("relay is deprecated. Please use client.relay instead."),this.client.relay}},{key:"relayUrl",get:function(){return console.warn("relayUrl is deprecated. Please use client.relayUrl instead."),this.client.relayUrl}},{key:"walletPubkey",get:function(){return console.warn("walletPubkey is deprecated. Please use client.walletPubkey instead."),this.client.walletPubkey}},{key:"options",get:function(){return this.client.options}},{key:"secret",get:function(){return console.warn("secret is deprecated. Please use client.secret instead."),this.client.secret}},{key:"nostrWalletConnectUrl",get:function(){return console.warn("nostrWalletConnectUrl is deprecated. Please use client.nostrWalletConnectUrl instead."),this.client.nostrWalletConnectUrl}},{key:"connected",get:function(){return console.warn("connected is deprecated. Please use client.connected instead."),this.client.connected}},{key:"publicKey",get:function(){return console.warn("publicKey is deprecated. Please use client.publicKey instead."),this.client.publicKey}}]),e}();function Y(e){return u({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}function $(e){return{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:y((new TextEncoder).encode(e[1]))}}):[]}}var Q=X;function Z(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,custom_records:t}}var ee=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new q(e):e,this.defaultRequestOptions=u({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return u({},e,{custom_records:e.customRecords})})}):(n="/payments/keysend",r=u({},e,{custom_records:e.customRecords})),b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return Z(e)})}):(n="/payments/keysend",r=Z(e)),b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",custom_records:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return b(u({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return b(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function te(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function ne(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var re={__proto__:null,NostrWebLNProvider:X,NWC:Q,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new ee(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=te(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(te(function(){return ne(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(te(function(){return ne(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(te(function(){return ne(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),u=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!u){u=!0,console.info("Processing OAuth code response");var r=n.payload.code,c=ne(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new ee(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(c&&c.then)return c.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};e.Client=ee,e.auth=A,e.nwc=D,e.types=P,e.webln=re}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("emittery"),require("nostr-tools")):"function"==typeof define&&define.amd?define(["exports","emittery","nostr-tools"],t):t((e||self).sdk={},e.emittery,e.nostrTools)}(this,function(e,t,n){function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/r(t);function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function s(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(this,arguments)}function u(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,l(e,t)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function l(e,t){return l=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},l(e,t)}function h(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function f(e,t,n){return f=h()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&l(o,n.prototype),o},f.apply(null,arguments)}function d(e){var t="function"==typeof Map?new Map:void 0;return d=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return f(e,arguments,a(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),l(n,e)},d(e)}function m(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function p(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function v(e,t){return"Basic "+btoa(e+":"+t)}var y=function(e){return e.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},"")},g=/*#__PURE__*/function(e){function t(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return u(t,e),t}(/*#__PURE__*/d(Error)),P={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:g},w=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],b=function(e){return Promise.resolve(k(e)).then(function(e){return e.json()})},k=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,u=e.max_retries,a=e.base_url,l=void 0===a?E:a,h=e.user_agent,f=e.headers,d=m(e,w);try{var v=function(e){return Promise.resolve(_(y.toString(),c({headers:c({},P?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,f,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:s,body:P?JSON.stringify(i):void 0},d),u)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new g(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},y=new URL(l+n);y.search=p(o);var P="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(y.href,s)).then(v):v(void 0))}catch(e){return Promise.reject(e)}},_=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),c=Number(o.headers.get("x-rate-limit-remaining")),u=1e3*s-Date.now(),a=1e3;return 0===c&&(a=u),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},E="https://api.getalby.com",T=["expires_in"],N=["token"];function j(e){var t=e.expires_in;return c({},m(e,T),!!t&&{expires_at:Date.now()+1e3*t})}var A=/*#__PURE__*/function(){function e(e){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new o.default;var t=e.token,n=m(e,N);this.options=c({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}var t=e.prototype;return t.on=function(e,t){this._tokenEvents.on(e,t)},t.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var i=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,i=o.client_id,s=o.client_secret,u=o.request_options,a=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(b(c({},u,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:c({},null==u?void 0:u.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:v(i,s)})}))).then(function(n){var r=j(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},t.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},t.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,i=n.callback,s=n.request_options,u=n.user_agent,a=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!a)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!i)throw new Error("callback is required");return Promise.resolve(b(c({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:i},user_agent:u,method:"POST",headers:c({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:v(r,o)})}))).then(function(e){var n=j(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},t.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=p(c({},e,{client_id:i,scope:u.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,i=o.client_id,s=o.callback,u=o.scopes;if(!s)throw new Error("callback required");if(!u)throw new Error("scopes required");var a=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},t.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},t._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=y(t),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},e}(),R=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),q={__proto__:null,OAuth2User:A,OAuth2Bearer:R};if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");const O=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function x(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=O[e[n]];return t}function S(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let t=0;t<n.length;t++){const r=2*t,o=e.slice(r,r+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[t]=i}return n}function U(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function I(e,t,n){if(!e.s){if(n instanceof C){if(!n.s)return void(n.o=I.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(I.bind(null,e,t),I.bind(null,e,2));e.s=t,e.v=n;var r=e.o;r&&r(e)}}var C=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,o=this.s;if(o){var i=1&o?t:n;if(i){try{I(r,1,i(this.v))}catch(e){I(r,2,e)}return r}return this}return this.o=function(e){try{var o=e.v;1&e.s?I(r,1,t?t(o):o):n?I(r,1,n(o)):I(r,2,o)}catch(e){I(r,2,e)}},r},e}();function W(e){return e instanceof C&&1&e.s}var M=/*#__PURE__*/function(e){function t(t,n){var r;return(r=e.call(this,t)||this).error=void 0,r.code=void 0,r.error=t,r.code=n,r}return u(t,e),t}(/*#__PURE__*/d(Error)),L=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),K=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),z=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(K),B=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(K),F=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),H=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),J=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),G=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),D=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return u(t,e),t}(M),V={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},X=/*#__PURE__*/function(){function e(t){var r;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.lud16=void 0,this.walletPubkey=void 0,this.options=void 0,t&&t.nostrWalletConnectUrl&&(t=c({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var o=V[(null==(r=t)?void 0:r.providerName)||"alby"];this.options=c({},o,t||{}),this.relayUrl=this.options.relayUrl,this.relay=new n.Relay(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?n.nip19.decode(this.options.secret).data:this.options.secret),this.lud16=this.options.lud16,this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?n.nip19.decode(this.options.walletPubkey).data:this.options.walletPubkey,void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://").replace("nostrwalletconnect:","http://").replace("nostr+walletconnect:","http://");var t=new URL(e),n=t.searchParams.get("relay");if(!n)throw new Error("No relay URL found in connection string");var r={walletPubkey:t.host,relayUrl:n},o=t.searchParams.get("secret");o&&(r.secret=o);var i=t.searchParams.get("lud16");return i&&(r.lud16=i),r},e.withNewSecret=function(t){return(t=t||{}).secret=x(n.generateSecretKey()),new e(t)};var t=e.prototype;return t.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},t.getPublicKey=function(){return Promise.resolve(this.publicKey)},t.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(n.finalizeEvent(e,S(this.secret)))},t.getEventHash=function(e){return n.getEventHash(e)},t.close=function(){return this.relay.close()},t.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},t.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},t.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t},t.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(c),window.removeEventListener("message",n),i&&i.close())},c=setInterval(function(){i&&i.closed&&(clearInterval(c),window.removeEventListener("message",s),o(new Error("Popup closed")))},500);window.addEventListener("message",s)}else o(new Error("failed to execute window.open"))})},t.getWalletServiceSupportedMethods=function(){try{return console.warn("getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead."),Promise.resolve(this.getWalletServiceInfo()).then(function(e){return e.capabilities})}catch(e){return Promise.reject(e)}},t.getWalletServiceInfo=function(){try{var e=this;return Promise.resolve(e._checkConnected()).then(function(){return Promise.resolve(new Promise(function(t,n){var r=[],o=e.relay.subscribe([{kinds:[13194],limit:1,authors:[e.walletPubkey]}],{eoseTimeout:1e4});o.onevent=function(e){r.push(e)},o.oneose=function(){o.close(),t(r)}})).then(function(e){var t;if(!e.length)throw new Error("no info event (kind 13194) returned from relay");var n=e[0].content,r=e[0].tags.find(function(e){return"notifications"===e[0]});return{capabilities:n.split(/[ |,]/g),notifications:(null==r||null==(t=r[1])?void 0:t.split(" "))||[]}})})}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(e.executeNip47Request("get_info",{},function(e){return!!e.methods}))},function(e){throw console.error("Failed to request get_info",e),e}))}catch(e){return Promise.reject(e)}},t.getBudget=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(e.executeNip47Request("get_budget",{},function(e){return void 0!==e}))},function(e){throw console.error("Failed to request get_budget",e),e}))}catch(e){return Promise.reject(e)}},t.getBalance=function(){try{var e=this;return Promise.resolve(U(function(){return Promise.resolve(e.executeNip47Request("get_balance",{},function(e){return void 0!==e.balance}))},function(e){throw console.error("Failed to request get_balance",e),e}))}catch(e){return Promise.reject(e)}},t.payInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("pay_invoice",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.payKeysend=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("pay_keysend",e,function(e){return!!e.preimage}))},function(e){throw console.error("Failed to request pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},t.signMessage=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("sign_message",e,function(t){return t.message===e.message&&!!t.signature}))},function(e){throw console.error("Failed to request sign_message",e),e}))}catch(e){return Promise.reject(e)}},t.multiPayInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_invoice",e,e.invoices.length,function(e){return!!e.preimage})).then(function(e){return{invoices:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.multiPayKeysend=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeMultiNip47Request("multi_pay_keysend",e,e.keysends.length,function(e){return!!e.preimage})).then(function(e){return{keysends:e,errors:[]}})},function(e){throw console.error("Failed to request multi_pay_keysend",e),e}))}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){if(!e.amount)throw new Error("No amount specified");return Promise.resolve(t.executeNip47Request("make_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request make_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.lookupInvoice=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("lookup_invoice",e,function(e){return!!e.invoice}))},function(e){throw console.error("Failed to request lookup_invoice",e),e}))}catch(e){return Promise.reject(e)}},t.listTransactions=function(e){try{var t=this;return Promise.resolve(U(function(){return Promise.resolve(t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions}))},function(e){throw console.error("Failed to request list_transactions",e),e}))}catch(e){return Promise.reject(e)}},t.subscribeNotifications=function(e,t){try{var n,r,o,i=this,s=!0;return function(){try{var c=function(e,t,n){for(var r;;){var o=e();if(W(o)&&(o=o.v),!o)return i;if(o.then){r=0;break}var i=n();if(i&&i.then){if(!W(i)){r=1;break}i=i.s}}var s=new C,c=I.bind(null,s,2);return(0===r?o.then(a):1===r?i.then(u):(void 0).then(function(){(o=e())?o.then?o.then(a).then(void 0,c):a(o):I(s,1,i)})).then(void 0,c),s;function u(t){i=t;do{if(!(o=e())||W(o)&&!o.v)return void I(s,1,i);if(o.then)return void o.then(a).then(void 0,c);W(i=n())&&(i=i.v)}while(!i||!i.then);i.then(u).then(void 0,c)}function a(e){e?(i=n())&&i.then?i.then(u).then(void 0,c):u(i):I(s,1,i)}}(function(){return!!s},0,function(){function c(){var e=function(){if(s)return Promise.resolve(new Promise(function(e){return setTimeout(e,1e3)})).then(function(){})}();if(e&&e.then)return e.then(function(){})}var u=U(function(){return Promise.resolve(i._checkConnected()).then(function(){return o=i.relay.subscribe([{kinds:[23196],authors:[i.walletPubkey],"#p":[i.publicKey]}],{}),console.info("subscribed to relay"),o.onevent=function(n){try{return Promise.resolve(i.decrypt(i.walletPubkey,n.content)).then(function(n){var r;try{r=JSON.parse(n)}catch(e){return void console.error("Failed to parse decrypted event content",e)}r.notification?(!t||t.indexOf(r.notification_type)>-1)&&e(r):console.error("No notification in response",r)})}catch(e){return Promise.reject(e)}},Promise.resolve(new Promise(function(e){n=function(){e()},i.relay.onclose=r=function(){console.info("relay disconnected"),null==n||n()}})).then(function(){void 0!==r&&(i.relay.onclose=null)})})},function(e){console.error("error subscribing to notifications",e||"unknown relay error")});return u&&u.then?u.then(c):c()});c&&c.then&&c.then(function(){})}catch(e){Promise.reject(e)}}(),Promise.resolve(function(){var e;s=!1,null==n||n(),null==(e=o)||e.close()})}catch(e){return Promise.reject(e)}},t.executeNip47Request=function(e,t,n){try{var r=this;return Promise.resolve(r._checkConnected()).then(function(){return new Promise(function(o,i){try{return Promise.resolve(r.encrypt(r.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",r.walletPubkey]],content:e};return Promise.resolve(r.signEvent(t)).then(function(e){var t=r.relay.subscribe([{kinds:[23195],authors:[r.walletPubkey],"#e":[e.id]}],{}),s=setTimeout(function(){t.close(),i(new B("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.onevent=function(e){try{return clearTimeout(s),t.close(),Promise.resolve(r.decrypt(r.walletPubkey,e.content)).then(function(e){var r,c,u;try{r=JSON.parse(e)}catch(e){return clearTimeout(s),t.close(),void i(new H("failed to deserialize response","INTERNAL"))}r.result?n(r.result)?o(r.result):(clearTimeout(s),t.close(),i(new J("response from NWC failed validation: "+JSON.stringify(r.result),"INTERNAL"))):(clearTimeout(s),t.close(),i(new L((null==(c=r.error)?void 0:c.message)||"unknown Error",(null==(u=r.error)?void 0:u.code)||"INTERNAL")))})}catch(e){return Promise.reject(e)}};var c=setTimeout(function(){t.close(),i(new z("publish timeout: "+e.id,"INTERNAL"))},5e3),u=U(function(){return Promise.resolve(r.relay.publish(e)).then(function(){clearTimeout(c)})},function(e){clearTimeout(c),i(new F("failed to publish: "+e,"INTERNAL"))});if(u&&u.then)return u.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},t.executeMultiNip47Request=function(e,t,n,r){try{var o=this;return Promise.resolve(o._checkConnected()).then(function(){var i=[];return new Promise(function(s,u){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.subscribe([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}],{}),a=setTimeout(function(){t.close(),u(new B("reply timeout: event "+e.id,"INTERNAL"))},6e4);t.onevent=function(e){try{return Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(o){var l;try{l=JSON.parse(o)}catch(e){clearTimeout(a),t.close(),u(new H("failed to deserialize response","INTERNAL"))}if(l.result){var h;if(!r(l.result))return clearTimeout(a),t.close(),void u(new J("Response from NWC failed validation: "+JSON.stringify(l.result),"INTERNAL"));var f=null==(h=e.tags.find(function(e){return"d"===e[0]}))?void 0:h[1];if(void 0===f)return clearTimeout(a),t.close(),void u(new J("No d tag found in response event","INTERNAL"));i.push(c({},l.result,{dTag:f})),i.length===n&&(clearTimeout(a),t.close(),s(i))}else{var d,m;clearTimeout(a),t.close(),u(new G(null==(d=l.error)?void 0:d.message,null==(m=l.error)?void 0:m.code))}})}catch(e){return Promise.reject(e)}};var l=setTimeout(function(){t.close(),u(new z("Publish timeout: "+e.id,"INTERNAL"))},5e3),h=U(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(l)})},function(e){clearTimeout(l),u(new F("Failed to publish: "+e,"INTERNAL"))});if(h&&h.then)return h.then(function(){})})})}catch(e){Promise.reject(e)}})})}catch(e){return Promise.reject(e)}},t._checkConnected=function(){try{var e=this;if(!e.secret)throw new Error("Missing secret key");if(!e.relayUrl)throw new Error("Missing relay url");return Promise.resolve(U(function(){var t=function(){if(!e.relay.connected)return Promise.resolve(e.relay.connect()).then(function(){})}();if(t&&t.then)return t.then(function(){})},function(){throw console.error("failed to connect to relay",e.relayUrl),new D("Failed to connect to "+e.relayUrl,"OTHER")}))}catch(e){return Promise.reject(e)}},s(e,[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return this.relay.connected}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return n.getPublicKey(S(this.secret))}}]),e}(),Y={__proto__:null,Nip47Error:M,Nip47WalletError:L,Nip47TimeoutError:K,Nip47PublishTimeoutError:z,Nip47ReplyTimeoutError:B,Nip47PublishError:F,Nip47ResponseDecodingError:H,Nip47ResponseValidationError:J,Nip47UnexpectedResponseError:G,Nip47NetworkError:D,NWCs:V,NWCClient:X},$={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions",multi_pay_invoice:"sendMultiPayment",multi_pay_keysend:"multiKeysend",sign_message:"signMessage"},Q=/*#__PURE__*/function(){function e(e){this._enabled=!1,this.client=void 0,this.subscribers=void 0,this.client=new X(e),this.subscribers={}}e.withNewSecret=function(t){return(t=t||{}).secret=x(n.generateSecretKey()),new e(t)};var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.getNostrWalletConnectUrl=function(e){return void 0===e&&(e=!0),console.warn("getNostrWalletConnectUrl is deprecated. Please use client.getNostrWalletConnectUrl instead."),this.client.getNostrWalletConnectUrl(e)},t.getPublicKey=function(){return this.client.getPublicKey()},t.signEvent=function(e){return this.client.signEvent(e)},t.getEventHash=function(e){return console.warn("getEventHash is deprecated. Please use client.getEventHash instead."),this.client.getEventHash(e)},t.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},t.close=function(){return this.client.close()},t.encrypt=function(e,t){try{return console.warn("encrypt is deprecated. Please use client.encrypt instead."),Promise.resolve(this.client.encrypt(e,t))}catch(e){return Promise.reject(e)}},t.decrypt=function(e,t){try{return console.warn("decrypt is deprecated. Please use client.decrypt instead."),Promise.resolve(this.client.decrypt(e,t))}catch(e){return Promise.reject(e)}},t.getAuthorizationUrl=function(e){return console.warn("getAuthorizationUrl is deprecated. Please use client.getAuthorizationUrl instead."),this.client.getAuthorizationUrl(e)},t.initNWC=function(e){return void 0===e&&(e={}),console.warn("initNWC is deprecated. Please use client.initNWC instead."),this.client.initNWC(e)},t.getInfo=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return function(r,o){try{var i=Promise.resolve(e.client.getInfo()).then(function(r){var o={methods:r.methods.map(function(e){return $[e]}),node:{alias:r.alias,pubkey:r.pubkey,color:r.color},supports:t,version:n};return e.notify("getInfo",o),o})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(e){return console.error("Using minimal getInfo",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},t.getBalance=function(){try{var e=this;return Promise.resolve(e.checkEnabled()).then(function(){return Promise.resolve(e.client.getBalance()).then(function(t){var n={balance:Math.floor(t.balance/1e3),currency:"sats"};return e.notify("getBalance",n),n})})}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payInvoice({invoice:e})).then(function(e){var n={preimage:e.preimage};return t.notify("sendPayment",n),n})})}catch(e){return Promise.reject(e)}},t.sendPaymentAsync=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return t.client.payInvoice({invoice:e}),t.notify("sendPaymentAsync",{}),{}})}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.payKeysend(ee(e))).then(function(e){var n={preimage:e.preimage};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},t.signMessage=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.signMessage({message:e})).then(function(e){var n={message:e.message,signature:e.signature};return t.notify("keysend",n),n})})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return Promise.resolve(t.client.makeInvoice({amount:1e3*o,description:null==r?void 0:r.defaultMemo})).then(function(e){var n={paymentRequest:e.invoice};return t.notify("makeInvoice",n),n})})}catch(e){return Promise.reject(e)}},t.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.lookupInvoice({invoice:e.paymentRequest,payment_hash:e.paymentHash})).then(function(e){var n={preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at};return t.notify("lookupInvoice",n),n})})}catch(e){return Promise.reject(e)}},t.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.listTransactions(e)).then(function(e){var n={transactions:e.transactions.map(Z)};return t.notify("listTransactions",n),n})})}catch(e){return Promise.reject(e)}},t.sendMultiPayment=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayInvoice({invoices:e.map(function(e,t){return{invoice:e,id:t.toString()}})})).then(function(n){var r={payments:n.invoices.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find paymentRequest matching response d tag");return{paymentRequest:n,preimage:t.preimage}}),errors:[]};return t.notify("sendMultiPayment",r),r})})}catch(e){return Promise.reject(e)}},t.multiKeysend=function(e){try{var t=this;return Promise.resolve(t.checkEnabled()).then(function(){return Promise.resolve(t.client.multiPayKeysend({keysends:e.map(function(e,t){return c({},ee(e),{id:t.toString()})})})).then(function(n){var r={keysends:n.keysends.map(function(t){var n=e[parseInt(t.dTag)];if(!n)throw new Error("Could not find keysend matching response d tag");return{keysend:n,preimage:t.preimage}}),errors:[]};return t.notify("multiKeysend",r),r})})}catch(e){return Promise.reject(e)}},t.lnurl=function(e){throw new Error("Method not implemented.")},t.request=function(e,t){throw new Error("Method not implemented.")},t.verifyMessage=function(e,t){throw new Error("Method not implemented.")},t.checkEnabled=function(){try{if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function");return Promise.resolve()}catch(e){return Promise.reject(e)}},s(e,[{key:"relay",get:function(){return console.warn("relay is deprecated. Please use client.relay instead."),this.client.relay}},{key:"relayUrl",get:function(){return console.warn("relayUrl is deprecated. Please use client.relayUrl instead."),this.client.relayUrl}},{key:"walletPubkey",get:function(){return console.warn("walletPubkey is deprecated. Please use client.walletPubkey instead."),this.client.walletPubkey}},{key:"options",get:function(){return this.client.options}},{key:"secret",get:function(){return console.warn("secret is deprecated. Please use client.secret instead."),this.client.secret}},{key:"nostrWalletConnectUrl",get:function(){return console.warn("nostrWalletConnectUrl is deprecated. Please use client.nostrWalletConnectUrl instead."),this.client.nostrWalletConnectUrl}},{key:"connected",get:function(){return console.warn("connected is deprecated. Please use client.connected instead."),this.client.connected}},{key:"publicKey",get:function(){return console.warn("publicKey is deprecated. Please use client.publicKey instead."),this.client.publicKey}}]),e}();function Z(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}function ee(e){return{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:y((new TextEncoder).encode(e[1]))}}):[]}}var te=Q;function ne(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,custom_records:t}}var re=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new R(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return c({},e,{custom_records:e.customRecords})})}):(n="/payments/keysend",r=c({},e,{custom_records:e.customRecords})),b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return ne(e)})}):(n="/payments/keysend",r=ne(e)),b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",custom_records:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return b(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function oe(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function ie(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var se={__proto__:null,NostrWebLNProvider:Q,NWC:te,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new re(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=oe(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(oe(function(){return ie(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(oe(function(){return ie(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(oe(function(){return ie(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),c=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!c){c=!0,console.info("Processing OAuth code response");var r=n.payload.code,u=ie(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new re(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(u&&u.then)return u.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};e.Client=re,e.auth=q,e.nwc=Y,e.types=P,e.webln=se}); |
@@ -1,2 +0,2 @@ | ||
import { Relay, Event, UnsignedEvent } from "nostr-tools"; | ||
import { Event, EventTemplate, Relay } from "nostr-tools"; | ||
import { NWCAuthorizationUrlOptions } from "./types"; | ||
@@ -178,3 +178,3 @@ type WithDTag = { | ||
getPublicKey(): Promise<string>; | ||
signEvent(event: UnsignedEvent): Promise<Event>; | ||
signEvent(event: EventTemplate): Promise<Event>; | ||
getEventHash(event: Event): string; | ||
@@ -181,0 +181,0 @@ close(): void; |
{ | ||
"name": "@getalby/sdk", | ||
"version": "3.8.0", | ||
"version": "3.8.1", | ||
"description": "The SDK to integrate with Nostr Wallet Connect and the Alby API", | ||
@@ -42,3 +42,3 @@ "repository": "https://github.com/getAlby/js-sdk.git", | ||
"emittery": "^1.0.3", | ||
"nostr-tools": "^1.17.0" | ||
"nostr-tools": "2.9.4" | ||
}, | ||
@@ -45,0 +45,0 @@ "devDependencies": { |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
199114
1320
+ Added@noble/ciphers@0.5.3(transitive)
+ Added@noble/curves@1.2.0(transitive)
+ Added@noble/hashes@1.3.2(transitive)
+ Addednostr-tools@2.9.4(transitive)
- Removed@noble/ciphers@0.2.0(transitive)
- Removednostr-tools@1.17.0(transitive)
Updatednostr-tools@2.9.4