@cowprotocol/widget-lib 0.11.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ import { FlexibleConfig, PerNetworkConfig, PerTradeTypeConfig, TradeType } from './types';
2
+ import { SupportedChainId } from '@cowprotocol/cow-sdk';
3
+
4
+ export declare function resolveFlexibleConfig<T extends string | number>(config: FlexibleConfig<T>, chainId: SupportedChainId, tradeType: TradeType): T | undefined;
5
+ export declare function isPerTradeTypeConfig<T>(config: FlexibleConfig<T>): config is PerTradeTypeConfig<T>;
6
+ export declare function isPerNetworkConfig<T>(config: FlexibleConfig<T>): config is PerNetworkConfig<T>;
package/index.d.ts CHANGED
@@ -3,3 +3,4 @@ export type { CowSwapWidgetHandler } from './cowSwapWidget';
3
3
  export * from './types';
4
4
  export * from './messages';
5
5
  export * from './themeUtils';
6
+ export * from './flexibleConfig';
package/index.iife.js CHANGED
@@ -1 +1 @@
1
- var cowSwapWidget=function(o){"use strict";class L{constructor(){this.subscriptions={}}on(n){const{event:t,handler:i}=n;this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(i)}off(n){const{event:t,handler:i}=n;this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(s=>s!==i))}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(i=>i(t))}}const P="cowSwapWidget";function f(e,n,t){const s={key:P,method:n,...typeof t=="object"?t:{}};e.postMessage(s,"*")}function p(e,n,t){const i=s=>{!D(s.data)||s.data.key!==P||s.data.method!==n||t(s.data)};return e.addEventListener("message",i),i}function D(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function g(e,n,t){e.removeEventListener("message",t)}function w(e,n){e.removeEventListener("message",n)}var a=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(a||{}),E=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(E||{}),m=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(m||{});const O=["primary","background","paper","text","danger","warning","alert","info","success"];class U{constructor(n,t=[]){this.contentWindow=n,this.eventEmitter=new L,this.listeners=[],this.updateListeners(t),this.widgetListener=p(this.contentWindow,a.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload))}stopListeningIframe(){w(this.contentWindow,this.widgetListener)}updateListeners(n){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=n||[];for(const t of this.listeners)this.eventEmitter.on(t)}}const V=["connect","disconnect","close","chainChanged","accountsChanged"];class y{constructor(n){this.iframeWidow=n,this.ethereumProvider=null,this.requestWaitingForConnection={},this.processRpcCallFromWindow=({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)}}disconnect(){this.ethereumProvider=null,g(window,a.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():p(window,a.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),V.forEach(t=>{n.on(t,i=>this.onProviderEvent(t,i))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:i,method:s}=n;if(!this.ethereumProvider||!t)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:t,result:c}})).catch(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:t,error:c}}))}onProviderEvent(n,t){f(this.iframeWidow,E.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){f(this.iframeWidow,E.PROVIDER_RPC_RESPONSE,n)}}class H{constructor(n,t){this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=i=>{M(i.data)&&i.origin!==window.location.origin&&(b(i.data)?this.appWindow.parent.postMessage(i.data,"*"):F(i.data)&&this.iframeWidow.postMessage(i.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function M(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function b(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function F(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function R(e){return!!(e&&typeof e=="object")}const _="_";function N(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=A(e);return n+"/#"+t+"?"+W(e)}function A(e){const{chainId:n=1,sell:t,buy:i,tradeType:s=m.SWAP}=e,r=[(t==null?void 0:t.asset)||_,(i==null?void 0:i.asset)||_].map(encodeURIComponent).join("/");return`/${n}/widget/${s}/${r}`}function W(e){const n=new URLSearchParams;return G(k(n,e),e)}function k(e,n){const{sell:t,buy:i}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),i!=null&&i.amount&&e.append("buyAmount",i.amount),e}function G(e,n){const t=n.theme;return t?(R(t)?(e.append("palette",encodeURIComponent(JSON.stringify(t))),e.append("theme",t.baseTheme)):(e.append("palette","null"),e.append("theme",t)),e):(e.append("palette","null"),e)}const I="640px",Q="450px",$=20;function B(e,n){const{params:t,provider:i,listeners:s}=n;let r=i,c=t;const d=q(t);e.innerHTML="",e.appendChild(d);const{contentWindow:u}=d;if(!u)throw console.error("Iframe does not contain a window",d),new Error("Iframe does not contain a window!");const l=[];l.push(K(u,t.appCode)),l.push(...Y(d,t.height));const C=new U(window,s);let T=S(u,null,r);d.addEventListener("load",()=>v(u,c,r));const j=new H(window,u);return{updateParams:h=>{c=h,v(u,c,r)},updateListeners:h=>C.updateListeners(h),updateProvider:h=>{r=h,T=S(u,T,h)},destroy:()=>{T.disconnect(),C.stopListeningIframe(),l.forEach(h=>window.removeEventListener("message",h)),j.stopListening(),e.removeChild(d)}}}function S(e,n,t){n&&n.disconnect();const i=n||new y(e);return t&&i.onConnect(t),i}function q(e){const{width:n=Q,height:t=I}=e,i=document.createElement("iframe");return i.src=N(e),i.width=n,i.height=t,i.style.border="0",i}function v(e,n,t){const i=!!t,s=A(n),r=W(n).toString(),{theme:c,...d}=n;f(e,E.UPDATE_PARAMS,{urlParams:{pathname:s,search:r},appParams:d,hasProvider:i})}function K(e,n){const t=p(window,a.ACTIVATE,()=>{w(window,t),f(e,E.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})});return t}function Y(e,n=I){return[p(window,a.UPDATE_HEIGHT,t=>{e.style.height=t.height?`${t.height+$}px`:n}),p(window,a.SET_FULL_HEIGHT,({isUpToSmall:t})=>{e.style.height=t?n:`${document.body.offsetHeight}px`})]}return o.TradeType=m,o.WIDGET_PALETTE_COLORS=O,o.WidgetMethodsEmit=a,o.WidgetMethodsListen=E,o.createCowSwapWidget=B,o.isCowSwapWidgetPalette=R,o.listenToMessageFromWindow=p,o.postMessageToWindow=f,o.stopListeningToMessageFromWindow=g,o.stopListeningWindowListener=w,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
1
+ var cowSwapWidget=function(s){"use strict";var ne=Object.defineProperty;var ie=(s,r,u)=>r in s?ne(s,r,{enumerable:!0,configurable:!0,writable:!0,value:u}):s[r]=u;var d=(s,r,u)=>(ie(s,typeof r!="symbol"?r+"":r,u),u);class r{constructor(){d(this,"subscriptions",{})}on(t){const{event:n,handler:i}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(i)}off(t){const{event:n,handler:i}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(o=>o!==i))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(i=>i(n))}}const u="cowSwapWidget";function T(e,t,n){const o={key:u,method:t,...typeof n=="object"?n:{}};e.postMessage(o,"*")}function E(e,t,n){const i=o=>{!y(o.data)||o.data.key!==u||o.data.method!==t||n(o.data)};return e.addEventListener("message",i),i}function y(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function W(e,t,n){e.removeEventListener("message",n)}function C(e,t){e.removeEventListener("message",t)}var a=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.INTERCEPT_WINDOW_OPEN="INTERCEPT_WINDOW_OPEN",e))(a||{}),w=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(w||{}),m=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(m||{});const N=["primary","background","paper","text","danger","warning","alert","info","success"];class U{constructor(t,n=[]){d(this,"eventEmitter",new r);d(this,"listeners",[]);d(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=E(this.contentWindow,a.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload))}stopListeningIframe(){C(this.contentWindow,this.widgetListener)}updateListeners(t){for(const n of this.listeners)this.eventEmitter.off(n);this.listeners=t||[];for(const n of this.listeners)this.eventEmitter.on(n)}}const V=["connect","disconnect","close","chainChanged","accountsChanged"];class F{constructor(t){d(this,"ethereumProvider",null);d(this,"requestWaitingForConnection",{});d(this,"processRpcCallFromWindow",({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)});this.iframeWidow=t}disconnect(){this.ethereumProvider=null,W(window,a.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():E(window,a.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),V.forEach(n=>{t.on(n,i=>this.onProviderEvent(n,i))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:i,method:o}=t;if(!this.ethereumProvider||!n)return;(o==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(p=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:n,result:p}})).catch(p=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:n,error:p}}))}onProviderEvent(t,n){T(this.iframeWidow,w.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){T(this.iframeWidow,w.PROVIDER_RPC_RESPONSE,t)}}class H{constructor(t,n){d(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=i=>{M(i.data)&&i.origin!==window.location.origin&&(k(i.data)?this.appWindow.parent.postMessage(i.data,"*"):G(i.data)&&this.iframeWidow.postMessage(i.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function M(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function k(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function G(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function I(e){return!!(e&&typeof e=="object")}const v="_";function Q(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=A(e);return t+"/#"+n+"?"+S(e)}function A(e){const{chainId:t=1,sell:n,buy:i,tradeType:o=m.SWAP}=e,c=[(n==null?void 0:n.asset)||v,(i==null?void 0:i.asset)||v].map(encodeURIComponent).join("/");return`/${t}/widget/${o}/${c}`}function S(e){const t=new URLSearchParams;return $(j(t,e),e)}function j(e,t){const{sell:n,buy:i}=t;return n!=null&&n.amount&&e.append("sellAmount",n.amount),i!=null&&i.amount&&e.append("buyAmount",i.amount),e}function $(e,t){const n=t.theme;return n?(I(n)?(e.append("palette",encodeURIComponent(JSON.stringify(n))),e.append("theme",n.baseTheme)):(e.append("palette","null"),e.append("theme",n)),e):(e.append("palette","null"),e)}const L="640px",B="450px",q=20;function K(e,t){const{params:n,provider:i,listeners:o}=t;let c=i,p=n;const h=Y(n);e.innerHTML="",e.appendChild(h);const{contentWindow:l}=h;if(!l)throw console.error("Iframe does not contain a window",h),new Error("Iframe does not contain a window!");const P=[];P.push(z(l,n.appCode)),P.push(...X(h,n.height)),P.push(J());const b=new U(window,o);let g=O(l,null,c);h.addEventListener("load",()=>D(l,p,c));const te=new H(window,l);return{updateParams:f=>{p=f,D(l,p,c)},updateListeners:f=>b.updateListeners(f),updateProvider:f=>{c=f,g=O(l,g,f)},destroy:()=>{g.disconnect(),b.stopListeningIframe(),P.forEach(f=>window.removeEventListener("message",f)),te.stopListening(),e.removeChild(h)}}}function O(e,t,n){t&&t.disconnect();const i=t||new F(e);return n&&i.onConnect(n),i}function Y(e){const{width:t=B,height:n=L}=e,i=document.createElement("iframe");return i.src=Q(e),i.width=t,i.height=n,i.style.border="0",i.allow="clipboard-read; clipboard-write",i}function D(e,t,n){const i=!!n,o=A(t),c=S(t).toString(),{theme:p,...h}=t;T(e,w.UPDATE_PARAMS,{urlParams:{pathname:o,search:c},appParams:h,hasProvider:i})}function z(e,t){return E(window,a.ACTIVATE,()=>{T(e,w.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})})}function J(){return E(window,a.INTERCEPT_WINDOW_OPEN,({href:e,rel:t,target:n})=>{const i=e.toString();if(!i.startsWith("http")&&i.match(/^[a-zA-Z0-9]+:\/\//)){window.open(i,n,t);return}})}function X(e,t=L){return[E(window,a.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+q}px`:t}),E(window,a.SET_FULL_HEIGHT,({isUpToSmall:n})=>{e.style.height=n?t:`${document.body.offsetHeight}px`})]}const Z=Object.values(m);function x(e,t,n){if(_(e)){const i=e[n];return R(i)?i[t]:i}if(R(e)){const i=e[t];return _(i)?i[n]:i}return e}function _(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Z.includes(t))}const ee=/^\d+$/;function R(e){return typeof e!="object"?!1:Object.keys(e).every(t=>typeof t=="number"||ee.test(t))}return s.TradeType=m,s.WIDGET_PALETTE_COLORS=N,s.WidgetMethodsEmit=a,s.WidgetMethodsListen=w,s.createCowSwapWidget=K,s.isCowSwapWidgetPalette=I,s.isPerNetworkConfig=R,s.isPerTradeTypeConfig=_,s.listenToMessageFromWindow=E,s.postMessageToWindow=T,s.resolveFlexibleConfig=x,s.stopListeningToMessageFromWindow=W,s.stopListeningWindowListener=C,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),s}({});
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class L{constructor(){this.subscriptions={}}on(n){const{event:t,handler:i}=n;this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(i)}off(n){const{event:t,handler:i}=n;this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(s=>s!==i))}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(i=>i(t))}}const _="cowSwapWidget";function E(e,n,t){const s={key:_,method:n,...typeof t=="object"?t:{}};e.postMessage(s,"*")}function p(e,n,t){const i=s=>{!D(s.data)||s.data.key!==_||s.data.method!==n||t(s.data)};return e.addEventListener("message",i),i}function D(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function A(e,n,t){e.removeEventListener("message",t)}function m(e,n){e.removeEventListener("message",n)}var d=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(d||{}),u=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(u||{}),l=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(l||{});const O=["primary","background","paper","text","danger","warning","alert","info","success"];class U{constructor(n,t=[]){this.contentWindow=n,this.eventEmitter=new L,this.listeners=[],this.updateListeners(t),this.widgetListener=p(this.contentWindow,d.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload))}stopListeningIframe(){m(this.contentWindow,this.widgetListener)}updateListeners(n){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=n||[];for(const t of this.listeners)this.eventEmitter.on(t)}}const V=["connect","disconnect","close","chainChanged","accountsChanged"];class y{constructor(n){this.iframeWidow=n,this.ethereumProvider=null,this.requestWaitingForConnection={},this.processRpcCallFromWindow=({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)}}disconnect(){this.ethereumProvider=null,A(window,d.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():p(window,d.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),V.forEach(t=>{n.on(t,i=>this.onProviderEvent(t,i))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:i,method:s}=n;if(!this.ethereumProvider||!t)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(r=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:t,result:r}})).catch(r=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:t,error:r}}))}onProviderEvent(n,t){E(this.iframeWidow,u.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){E(this.iframeWidow,u.PROVIDER_RPC_RESPONSE,n)}}class H{constructor(n,t){this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=i=>{M(i.data)&&i.origin!==window.location.origin&&(b(i.data)?this.appWindow.parent.postMessage(i.data,"*"):F(i.data)&&this.iframeWidow.postMessage(i.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function M(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function b(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function F(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function I(e){return!!(e&&typeof e=="object")}const P="_";function N(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=W(e);return n+"/#"+t+"?"+S(e)}function W(e){const{chainId:n=1,sell:t,buy:i,tradeType:s=l.SWAP}=e,o=[(t==null?void 0:t.asset)||P,(i==null?void 0:i.asset)||P].map(encodeURIComponent).join("/");return`/${n}/widget/${s}/${o}`}function S(e){const n=new URLSearchParams;return G(k(n,e),e)}function k(e,n){const{sell:t,buy:i}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),i!=null&&i.amount&&e.append("buyAmount",i.amount),e}function G(e,n){const t=n.theme;return t?(I(t)?(e.append("palette",encodeURIComponent(JSON.stringify(t))),e.append("theme",t.baseTheme)):(e.append("palette","null"),e.append("theme",t)),e):(e.append("palette","null"),e)}const C="640px",Q="450px",x=20;function $(e,n){const{params:t,provider:i,listeners:s}=n;let o=i,r=t;const a=B(t);e.innerHTML="",e.appendChild(a);const{contentWindow:h}=a;if(!h)throw console.error("Iframe does not contain a window",a),new Error("Iframe does not contain a window!");const f=[];f.push(q(h,t.appCode)),f.push(...K(a,t.height));const T=new U(window,s);let w=g(h,null,o);a.addEventListener("load",()=>R(h,r,o));const v=new H(window,h);return{updateParams:c=>{r=c,R(h,r,o)},updateListeners:c=>T.updateListeners(c),updateProvider:c=>{o=c,w=g(h,w,c)},destroy:()=>{w.disconnect(),T.stopListeningIframe(),f.forEach(c=>window.removeEventListener("message",c)),v.stopListening(),e.removeChild(a)}}}function g(e,n,t){n&&n.disconnect();const i=n||new y(e);return t&&i.onConnect(t),i}function B(e){const{width:n=Q,height:t=C}=e,i=document.createElement("iframe");return i.src=N(e),i.width=n,i.height=t,i.style.border="0",i}function R(e,n,t){const i=!!t,s=W(n),o=S(n).toString(),{theme:r,...a}=n;E(e,u.UPDATE_PARAMS,{urlParams:{pathname:s,search:o},appParams:a,hasProvider:i})}function q(e,n){const t=p(window,d.ACTIVATE,()=>{m(window,t),E(e,u.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})});return t}function K(e,n=C){return[p(window,d.UPDATE_HEIGHT,t=>{e.style.height=t.height?`${t.height+x}px`:n}),p(window,d.SET_FULL_HEIGHT,({isUpToSmall:t})=>{e.style.height=t?n:`${document.body.offsetHeight}px`})]}exports.TradeType=l;exports.WIDGET_PALETTE_COLORS=O;exports.WidgetMethodsEmit=d;exports.WidgetMethodsListen=u;exports.createCowSwapWidget=$;exports.isCowSwapWidgetPalette=I;exports.listenToMessageFromWindow=p;exports.postMessageToWindow=E;exports.stopListeningToMessageFromWindow=A;exports.stopListeningWindowListener=m;
1
+ "use strict";var b=Object.defineProperty;var y=(e,t,n)=>t in e?b(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var r=(e,t,n)=>(y(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class N{constructor(){r(this,"subscriptions",{})}on(t){const{event:n,handler:i}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(i)}off(t){const{event:n,handler:i}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(s=>s!==i))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(i=>i(n))}}const W="cowSwapWidget";function E(e,t,n){const s={key:W,method:t,...typeof n=="object"?n:{}};e.postMessage(s,"*")}function h(e,t,n){const i=s=>{!U(s.data)||s.data.key!==W||s.data.method!==t||n(s.data)};return e.addEventListener("message",i),i}function U(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function I(e,t,n){e.removeEventListener("message",n)}function v(e,t){e.removeEventListener("message",t)}var a=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.INTERCEPT_WINDOW_OPEN="INTERCEPT_WINDOW_OPEN",e))(a||{}),f=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(f||{}),w=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(w||{});const V=["primary","background","paper","text","danger","warning","alert","info","success"];class F{constructor(t,n=[]){r(this,"eventEmitter",new N);r(this,"listeners",[]);r(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=h(this.contentWindow,a.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload))}stopListeningIframe(){v(this.contentWindow,this.widgetListener)}updateListeners(t){for(const n of this.listeners)this.eventEmitter.off(n);this.listeners=t||[];for(const n of this.listeners)this.eventEmitter.on(n)}}const H=["connect","disconnect","close","chainChanged","accountsChanged"];class M{constructor(t){r(this,"ethereumProvider",null);r(this,"requestWaitingForConnection",{});r(this,"processRpcCallFromWindow",({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)});this.iframeWidow=t}disconnect(){this.ethereumProvider=null,I(window,a.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():h(window,a.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),H.forEach(n=>{t.on(n,i=>this.onProviderEvent(n,i))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:i,method:s}=t;if(!this.ethereumProvider||!n)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:n,result:c}})).catch(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:i,id:n,error:c}}))}onProviderEvent(t,n){E(this.iframeWidow,f.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){E(this.iframeWidow,f.PROVIDER_RPC_RESPONSE,t)}}class k{constructor(t,n){r(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=i=>{G(i.data)&&i.origin!==window.location.origin&&(x(i.data)?this.appWindow.parent.postMessage(i.data,"*"):Q(i.data)&&this.iframeWidow.postMessage(i.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function G(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function x(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function Q(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function A(e){return!!(e&&typeof e=="object")}const R="_";function j(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=S(e);return t+"/#"+n+"?"+L(e)}function S(e){const{chainId:t=1,sell:n,buy:i,tradeType:s=w.SWAP}=e,o=[(n==null?void 0:n.asset)||R,(i==null?void 0:i.asset)||R].map(encodeURIComponent).join("/");return`/${t}/widget/${s}/${o}`}function L(e){const t=new URLSearchParams;return B($(t,e),e)}function $(e,t){const{sell:n,buy:i}=t;return n!=null&&n.amount&&e.append("sellAmount",n.amount),i!=null&&i.amount&&e.append("buyAmount",i.amount),e}function B(e,t){const n=t.theme;return n?(A(n)?(e.append("palette",encodeURIComponent(JSON.stringify(n))),e.append("theme",n.baseTheme)):(e.append("palette","null"),e.append("theme",n)),e):(e.append("palette","null"),e)}const O="640px",q="450px",K=20;function Y(e,t){const{params:n,provider:i,listeners:s}=t;let o=i,c=n;const d=z(n);e.innerHTML="",e.appendChild(d);const{contentWindow:u}=d;if(!u)throw console.error("Iframe does not contain a window",d),new Error("Iframe does not contain a window!");const l=[];l.push(J(u,n.appCode)),l.push(...Z(d,n.height)),l.push(X());const _=new F(window,s);let T=g(u,null,o);d.addEventListener("load",()=>C(u,c,o));const D=new k(window,u);return{updateParams:p=>{c=p,C(u,c,o)},updateListeners:p=>_.updateListeners(p),updateProvider:p=>{o=p,T=g(u,T,p)},destroy:()=>{T.disconnect(),_.stopListeningIframe(),l.forEach(p=>window.removeEventListener("message",p)),D.stopListening(),e.removeChild(d)}}}function g(e,t,n){t&&t.disconnect();const i=t||new M(e);return n&&i.onConnect(n),i}function z(e){const{width:t=q,height:n=O}=e,i=document.createElement("iframe");return i.src=j(e),i.width=t,i.height=n,i.style.border="0",i.allow="clipboard-read; clipboard-write",i}function C(e,t,n){const i=!!n,s=S(t),o=L(t).toString(),{theme:c,...d}=t;E(e,f.UPDATE_PARAMS,{urlParams:{pathname:s,search:o},appParams:d,hasProvider:i})}function J(e,t){return h(window,a.ACTIVATE,()=>{E(e,f.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})})}function X(){return h(window,a.INTERCEPT_WINDOW_OPEN,({href:e,rel:t,target:n})=>{const i=e.toString();if(!i.startsWith("http")&&i.match(/^[a-zA-Z0-9]+:\/\//)){window.open(i,n,t);return}})}function Z(e,t=O){return[h(window,a.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+K}px`:t}),h(window,a.SET_FULL_HEIGHT,({isUpToSmall:n})=>{e.style.height=n?t:`${document.body.offsetHeight}px`})]}const ee=Object.values(w);function te(e,t,n){if(m(e)){const i=e[n];return P(i)?i[t]:i}if(P(e)){const i=e[t];return m(i)?i[n]:i}return e}function m(e){return typeof e!="object"?!1:Object.keys(e).every(t=>ee.includes(t))}const ne=/^\d+$/;function P(e){return typeof e!="object"?!1:Object.keys(e).every(t=>typeof t=="number"||ne.test(t))}exports.TradeType=w;exports.WIDGET_PALETTE_COLORS=V;exports.WidgetMethodsEmit=a;exports.WidgetMethodsListen=f;exports.createCowSwapWidget=Y;exports.isCowSwapWidgetPalette=A;exports.isPerNetworkConfig=P;exports.isPerTradeTypeConfig=m;exports.listenToMessageFromWindow=h;exports.postMessageToWindow=E;exports.resolveFlexibleConfig=te;exports.stopListeningToMessageFromWindow=I;exports.stopListeningWindowListener=v;
package/index.mjs CHANGED
@@ -1,49 +1,52 @@
1
- class S {
1
+ var O = Object.defineProperty;
2
+ var D = (e, t, n) => t in e ? O(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var r = (e, t, n) => (D(e, typeof t != "symbol" ? t + "" : t, n), n);
4
+ class L {
2
5
  constructor() {
3
- this.subscriptions = {};
6
+ r(this, "subscriptions", {});
4
7
  }
5
- on(n) {
6
- const { event: t, handler: i } = n;
7
- this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(i);
8
+ on(t) {
9
+ const { event: n, handler: s } = t;
10
+ this.subscriptions[n] || (this.subscriptions[n] = []), this.subscriptions[n].push(s);
8
11
  }
9
- off(n) {
10
- const { event: t, handler: i } = n;
11
- this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((s) => s !== i));
12
+ off(t) {
13
+ const { event: n, handler: s } = t;
14
+ this.subscriptions[n] && (this.subscriptions[n] = this.subscriptions[n].filter((i) => i !== s));
12
15
  }
13
- emit(n, t) {
14
- this.subscriptions[n] && this.subscriptions[n].forEach((i) => i(t));
16
+ emit(t, n) {
17
+ this.subscriptions[t] && this.subscriptions[t].forEach((s) => s(n));
15
18
  }
16
19
  }
17
- const R = "cowSwapWidget";
18
- function E(e, n, t) {
19
- const s = {
20
- key: R,
21
- method: n,
22
- ...typeof t == "object" ? t : {}
20
+ const A = "cowSwapWidget";
21
+ function l(e, t, n) {
22
+ const i = {
23
+ key: A,
24
+ method: t,
25
+ ...typeof n == "object" ? n : {}
23
26
  };
24
27
  e.postMessage(
25
- s,
28
+ i,
26
29
  "*"
27
30
  // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
28
31
  );
29
32
  }
30
- function p(e, n, t) {
31
- const i = (s) => {
32
- !W(s.data) || s.data.key !== R || s.data.method !== n || t(s.data);
33
+ function h(e, t, n) {
34
+ const s = (i) => {
35
+ !b(i.data) || i.data.key !== A || i.data.method !== t || n(i.data);
33
36
  };
34
- return e.addEventListener("message", i), i;
37
+ return e.addEventListener("message", s), s;
35
38
  }
36
- function W(e) {
39
+ function b(e) {
37
40
  return typeof e == "object" && e !== null && "key" in e && "method" in e && typeof e.key == "string" && typeof e.method == "string";
38
41
  }
39
- function L(e, n, t) {
40
- e.removeEventListener("message", t);
41
- }
42
- function _(e, n) {
42
+ function N(e, t, n) {
43
43
  e.removeEventListener("message", n);
44
44
  }
45
- var h = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.SET_FULL_HEIGHT = "SET_FULL_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e))(h || {}), u = /* @__PURE__ */ ((e) => (e.UPDATE_PARAMS = "UPDATE_PARAMS", e.UPDATE_APP_DATA = "UPDATE_APP_DATA", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(u || {}), g = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(g || {});
46
- const q = [
45
+ function y(e, t) {
46
+ e.removeEventListener("message", t);
47
+ }
48
+ var u = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.SET_FULL_HEIGHT = "SET_FULL_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e.INTERCEPT_WINDOW_OPEN = "INTERCEPT_WINDOW_OPEN", e))(u || {}), f = /* @__PURE__ */ ((e) => (e.UPDATE_PARAMS = "UPDATE_PARAMS", e.UPDATE_APP_DATA = "UPDATE_APP_DATA", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(f || {}), m = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(m || {});
49
+ const te = [
47
50
  "primary",
48
51
  "background",
49
52
  "paper",
@@ -54,96 +57,108 @@ const q = [
54
57
  "info",
55
58
  "success"
56
59
  ];
57
- class D {
58
- constructor(n, t = []) {
59
- this.contentWindow = n, this.eventEmitter = new S(), this.listeners = [], this.updateListeners(t), this.widgetListener = p(
60
+ class U {
61
+ constructor(t, n = []) {
62
+ r(this, "eventEmitter", new L());
63
+ r(this, "listeners", []);
64
+ r(this, "widgetListener");
65
+ this.contentWindow = t, this.updateListeners(n), this.widgetListener = h(
60
66
  this.contentWindow,
61
- h.EMIT_COW_EVENT,
62
- (i) => this.eventEmitter.emit(i.event, i.payload)
67
+ u.EMIT_COW_EVENT,
68
+ (s) => this.eventEmitter.emit(s.event, s.payload)
63
69
  );
64
70
  }
65
71
  stopListeningIframe() {
66
- _(this.contentWindow, this.widgetListener);
72
+ y(this.contentWindow, this.widgetListener);
67
73
  }
68
- updateListeners(n) {
69
- for (const t of this.listeners)
70
- this.eventEmitter.off(t);
71
- this.listeners = n || [];
72
- for (const t of this.listeners)
73
- this.eventEmitter.on(t);
74
+ updateListeners(t) {
75
+ for (const n of this.listeners)
76
+ this.eventEmitter.off(n);
77
+ this.listeners = t || [];
78
+ for (const n of this.listeners)
79
+ this.eventEmitter.on(n);
74
80
  }
75
81
  }
76
- const O = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
77
- class U {
82
+ const V = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
83
+ class H {
78
84
  /**
79
85
  * Creates an instance of IframeRpcProviderBridge.
80
86
  * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
81
87
  * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
82
88
  */
83
- constructor(n) {
84
- this.iframeWidow = n, this.ethereumProvider = null, this.requestWaitingForConnection = {}, this.processRpcCallFromWindow = ({ rpcRequest: t }) => {
89
+ constructor(t) {
90
+ /**
91
+ * The Ethereum provider instance.
92
+ * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
93
+ * */
94
+ r(this, "ethereumProvider", null);
95
+ /** Stored JSON-RPC requests, to queue them when disconnected. */
96
+ r(this, "requestWaitingForConnection", {});
97
+ r(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
85
98
  if (!this.ethereumProvider) {
86
99
  t.id && (this.requestWaitingForConnection[t.id] = t);
87
100
  return;
88
101
  }
89
102
  this.processRpcRequest(t);
90
- };
103
+ });
104
+ this.iframeWidow = t;
91
105
  }
92
106
  /**
93
107
  * Disconnects the JSON-RPC bridge from the Ethereum provider.
94
108
  */
95
109
  disconnect() {
96
- this.ethereumProvider = null, L(window, h.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
110
+ this.ethereumProvider = null, N(window, u.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
97
111
  }
98
112
  /**
99
113
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
100
114
  * @param newProvider - The Ethereum provider to connect.
101
115
  */
102
- onConnect(n) {
103
- this.ethereumProvider ? this.disconnect() : p(window, h.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = n, this.processPendingRequests(), O.forEach((t) => {
104
- n.on(t, (i) => this.onProviderEvent(t, i));
116
+ onConnect(t) {
117
+ this.ethereumProvider ? this.disconnect() : h(window, u.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), V.forEach((n) => {
118
+ t.on(n, (s) => this.onProviderEvent(n, s));
105
119
  });
106
120
  }
107
121
  processPendingRequests() {
108
- Object.keys(this.requestWaitingForConnection).forEach((n) => {
109
- this.processRpcRequest(this.requestWaitingForConnection[n]);
122
+ Object.keys(this.requestWaitingForConnection).forEach((t) => {
123
+ this.processRpcRequest(this.requestWaitingForConnection[t]);
110
124
  }), this.requestWaitingForConnection = {};
111
125
  }
112
126
  /**
113
127
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
114
128
  * @param request - The JSON-RPC request to be processed.
115
129
  */
116
- processRpcRequest(n) {
117
- const { id: t, jsonrpc: i, method: s } = n;
118
- if (!this.ethereumProvider || !t)
130
+ processRpcRequest(t) {
131
+ const { id: n, jsonrpc: s, method: i } = t;
132
+ if (!this.ethereumProvider || !n)
119
133
  return;
120
- (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...n, id: t })).then(
121
- (r) => this.forwardRpcResponseToIframe({
122
- rpcResponse: { jsonrpc: i, id: t, result: r }
134
+ (i === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: n })).then(
135
+ (a) => this.forwardRpcResponseToIframe({
136
+ rpcResponse: { jsonrpc: s, id: n, result: a }
123
137
  })
124
138
  ).catch(
125
- (r) => this.forwardRpcResponseToIframe({
126
- rpcResponse: { jsonrpc: i, id: t, error: r }
139
+ (a) => this.forwardRpcResponseToIframe({
140
+ rpcResponse: { jsonrpc: s, id: n, error: a }
127
141
  })
128
142
  );
129
143
  }
130
- onProviderEvent(n, t) {
131
- E(this.iframeWidow, u.PROVIDER_ON_EVENT, {
132
- event: n,
133
- params: t
144
+ onProviderEvent(t, n) {
145
+ l(this.iframeWidow, f.PROVIDER_ON_EVENT, {
146
+ event: t,
147
+ params: n
134
148
  });
135
149
  }
136
150
  /**
137
151
  * Forward a JSON-RPC message to the content window.
138
152
  */
139
- forwardRpcResponseToIframe(n) {
140
- E(this.iframeWidow, u.PROVIDER_RPC_RESPONSE, n);
153
+ forwardRpcResponseToIframe(t) {
154
+ l(this.iframeWidow, f.PROVIDER_RPC_RESPONSE, t);
141
155
  }
142
156
  }
143
- class V {
144
- constructor(n, t) {
145
- this.appWindow = n, this.iframeWidow = t, this.forwardSdkMessage = (i) => {
146
- H(i.data) && i.origin !== window.location.origin && (y(i.data) ? this.appWindow.parent.postMessage(i.data, "*") : b(i.data) && this.iframeWidow.postMessage(i.data, "*"));
157
+ class F {
158
+ constructor(t, n) {
159
+ r(this, "forwardSdkMessage");
160
+ this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (s) => {
161
+ k(s.data) && s.origin !== window.location.origin && (M(s.data) ? this.appWindow.parent.postMessage(s.data, "*") : G(s.data) && this.iframeWidow.postMessage(s.data, "*"));
147
162
  }, this.startListening();
148
163
  }
149
164
  startListening() {
@@ -153,114 +168,144 @@ class V {
153
168
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
154
169
  }
155
170
  }
156
- function H(e) {
171
+ function k(e) {
157
172
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
158
173
  }
159
- function y(e) {
174
+ function M(e) {
160
175
  return "method" in e && typeof e.method == "string" && "params" in e && "env" in e && typeof e.env == "object" && e.env !== null && "sdkVersion" in e.env;
161
176
  }
162
- function b(e) {
177
+ function G(e) {
163
178
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
164
179
  }
165
- function F(e) {
180
+ function x(e) {
166
181
  return !!(e && typeof e == "object");
167
182
  }
168
- const l = "_";
169
- function N(e) {
170
- const n = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", t = A(e);
171
- return n + "/#" + t + "?" + I(e);
183
+ const T = "_";
184
+ function Q(e) {
185
+ const t = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", n = v(e);
186
+ return t + "/#" + n + "?" + C(e);
172
187
  }
173
- function A(e) {
174
- const { chainId: n = 1, sell: t, buy: i, tradeType: s = g.SWAP } = e, o = [(t == null ? void 0 : t.asset) || l, (i == null ? void 0 : i.asset) || l].map(encodeURIComponent).join("/");
175
- return `/${n}/widget/${s}/${o}`;
188
+ function v(e) {
189
+ const { chainId: t = 1, sell: n, buy: s, tradeType: i = m.SWAP } = e, o = [(n == null ? void 0 : n.asset) || T, (s == null ? void 0 : s.asset) || T].map(encodeURIComponent).join("/");
190
+ return `/${t}/widget/${i}/${o}`;
176
191
  }
177
- function I(e) {
178
- const n = new URLSearchParams();
179
- return k(M(n, e), e);
192
+ function C(e) {
193
+ const t = new URLSearchParams();
194
+ return j($(t, e), e);
180
195
  }
181
- function M(e, n) {
182
- const { sell: t, buy: i } = n;
183
- return t != null && t.amount && e.append("sellAmount", t.amount), i != null && i.amount && e.append("buyAmount", i.amount), e;
196
+ function $(e, t) {
197
+ const { sell: n, buy: s } = t;
198
+ return n != null && n.amount && e.append("sellAmount", n.amount), s != null && s.amount && e.append("buyAmount", s.amount), e;
184
199
  }
185
- function k(e, n) {
186
- const t = n.theme;
187
- return t ? (F(t) ? (e.append("palette", encodeURIComponent(JSON.stringify(t))), e.append("theme", t.baseTheme)) : (e.append("palette", "null"), e.append("theme", t)), e) : (e.append("palette", "null"), e);
200
+ function j(e, t) {
201
+ const n = t.theme;
202
+ return n ? (x(n) ? (e.append("palette", encodeURIComponent(JSON.stringify(n))), e.append("theme", n.baseTheme)) : (e.append("palette", "null"), e.append("theme", n)), e) : (e.append("palette", "null"), e);
188
203
  }
189
- const v = "640px", G = "450px", x = 20;
190
- function K(e, n) {
191
- const { params: t, provider: i, listeners: s } = n;
192
- let o = i, r = t;
193
- const a = Q(t);
194
- e.innerHTML = "", e.appendChild(a);
195
- const { contentWindow: d } = a;
196
- if (!d)
197
- throw console.error("Iframe does not contain a window", a), new Error("Iframe does not contain a window!");
198
- const f = [];
199
- f.push($(d, t.appCode)), f.push(...B(a, t.height));
200
- const w = new D(window, s);
201
- let m = P(d, null, o);
202
- a.addEventListener("load", () => T(d, r, o));
203
- const C = new V(window, d);
204
+ const W = "640px", B = "450px", q = 20;
205
+ function ne(e, t) {
206
+ const { params: n, provider: s, listeners: i } = t;
207
+ let o = s, a = n;
208
+ const c = K(n);
209
+ e.innerHTML = "", e.appendChild(c);
210
+ const { contentWindow: p } = c;
211
+ if (!p)
212
+ throw console.error("Iframe does not contain a window", c), new Error("Iframe does not contain a window!");
213
+ const E = [];
214
+ E.push(Y(p, n.appCode)), E.push(...J(c, n.height)), E.push(z());
215
+ const P = new U(window, i);
216
+ let w = _(p, null, o);
217
+ c.addEventListener("load", () => R(p, a, o));
218
+ const S = new F(window, p);
204
219
  return {
205
- updateParams: (c) => {
206
- r = c, T(d, r, o);
220
+ updateParams: (d) => {
221
+ a = d, R(p, a, o);
207
222
  },
208
- updateListeners: (c) => w.updateListeners(c),
209
- updateProvider: (c) => {
210
- o = c, m = P(d, m, c);
223
+ updateListeners: (d) => P.updateListeners(d),
224
+ updateProvider: (d) => {
225
+ o = d, w = _(p, w, d);
211
226
  },
212
227
  destroy: () => {
213
- m.disconnect(), w.stopListeningIframe(), f.forEach((c) => window.removeEventListener("message", c)), C.stopListening(), e.removeChild(a);
228
+ w.disconnect(), P.stopListeningIframe(), E.forEach((d) => window.removeEventListener("message", d)), S.stopListening(), e.removeChild(c);
214
229
  }
215
230
  };
216
231
  }
217
- function P(e, n, t) {
218
- n && n.disconnect();
219
- const i = n || new U(e);
220
- return t && i.onConnect(t), i;
232
+ function _(e, t, n) {
233
+ t && t.disconnect();
234
+ const s = t || new H(e);
235
+ return n && s.onConnect(n), s;
221
236
  }
222
- function Q(e) {
223
- const { width: n = G, height: t = v } = e, i = document.createElement("iframe");
224
- return i.src = N(e), i.width = n, i.height = t, i.style.border = "0", i;
237
+ function K(e) {
238
+ const { width: t = B, height: n = W } = e, s = document.createElement("iframe");
239
+ return s.src = Q(e), s.width = t, s.height = n, s.style.border = "0", s.allow = "clipboard-read; clipboard-write", s;
225
240
  }
226
- function T(e, n, t) {
227
- const i = !!t, s = A(n), o = I(n).toString(), { theme: r, ...a } = n;
228
- E(e, u.UPDATE_PARAMS, {
241
+ function R(e, t, n) {
242
+ const s = !!n, i = v(t), o = C(t).toString(), { theme: a, ...c } = t;
243
+ l(e, f.UPDATE_PARAMS, {
229
244
  urlParams: {
230
- pathname: s,
245
+ pathname: i,
231
246
  search: o
232
247
  },
233
- appParams: a,
234
- hasProvider: i
248
+ appParams: c,
249
+ hasProvider: s
235
250
  });
236
251
  }
237
- function $(e, n) {
238
- const t = p(window, h.ACTIVATE, () => {
239
- _(window, t), E(e, u.UPDATE_APP_DATA, {
240
- metaData: n ? { appCode: n } : void 0
252
+ function Y(e, t) {
253
+ return h(window, u.ACTIVATE, () => {
254
+ l(e, f.UPDATE_APP_DATA, {
255
+ metaData: t ? { appCode: t } : void 0
241
256
  });
242
257
  });
243
- return t;
244
258
  }
245
- function B(e, n = v) {
259
+ function z() {
260
+ return h(window, u.INTERCEPT_WINDOW_OPEN, ({ href: e, rel: t, target: n }) => {
261
+ const s = e.toString();
262
+ if (!s.startsWith("http") && s.match(/^[a-zA-Z0-9]+:\/\//)) {
263
+ window.open(s, n, t);
264
+ return;
265
+ }
266
+ });
267
+ }
268
+ function J(e, t = W) {
246
269
  return [
247
- p(window, h.UPDATE_HEIGHT, (t) => {
248
- e.style.height = t.height ? `${t.height + x}px` : n;
270
+ h(window, u.UPDATE_HEIGHT, (n) => {
271
+ e.style.height = n.height ? `${n.height + q}px` : t;
249
272
  }),
250
- p(window, h.SET_FULL_HEIGHT, ({ isUpToSmall: t }) => {
251
- e.style.height = t ? n : `${document.body.offsetHeight}px`;
273
+ h(window, u.SET_FULL_HEIGHT, ({ isUpToSmall: n }) => {
274
+ e.style.height = n ? t : `${document.body.offsetHeight}px`;
252
275
  })
253
276
  ];
254
277
  }
278
+ const X = Object.values(m);
279
+ function se(e, t, n) {
280
+ if (g(e)) {
281
+ const s = e[n];
282
+ return I(s) ? s[t] : s;
283
+ }
284
+ if (I(e)) {
285
+ const s = e[t];
286
+ return g(s) ? s[n] : s;
287
+ }
288
+ return e;
289
+ }
290
+ function g(e) {
291
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => X.includes(t));
292
+ }
293
+ const Z = /^\d+$/;
294
+ function I(e) {
295
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => typeof t == "number" || Z.test(t));
296
+ }
255
297
  export {
256
- g as TradeType,
257
- q as WIDGET_PALETTE_COLORS,
258
- h as WidgetMethodsEmit,
259
- u as WidgetMethodsListen,
260
- K as createCowSwapWidget,
261
- F as isCowSwapWidgetPalette,
262
- p as listenToMessageFromWindow,
263
- E as postMessageToWindow,
264
- L as stopListeningToMessageFromWindow,
265
- _ as stopListeningWindowListener
298
+ m as TradeType,
299
+ te as WIDGET_PALETTE_COLORS,
300
+ u as WidgetMethodsEmit,
301
+ f as WidgetMethodsListen,
302
+ ne as createCowSwapWidget,
303
+ x as isCowSwapWidgetPalette,
304
+ I as isPerNetworkConfig,
305
+ g as isPerTradeTypeConfig,
306
+ h as listenToMessageFromWindow,
307
+ l as postMessageToWindow,
308
+ se as resolveFlexibleConfig,
309
+ N as stopListeningToMessageFromWindow,
310
+ y as stopListeningWindowListener
266
311
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "0.11.1",
3
+ "version": "0.13.2",
4
4
  "type": "commonjs",
5
5
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your website.",
6
6
  "main": "index.js",
package/types.d.ts CHANGED
@@ -2,12 +2,16 @@ import { CowEventListeners, CowEventPayloadMap, CowEvents } from '../../events/s
2
2
  import { SupportedChainId } from '@cowprotocol/cow-sdk';
3
3
 
4
4
  export type { SupportedChainId } from '@cowprotocol/cow-sdk';
5
+ export type PerTradeTypeConfig<T> = Partial<Record<TradeType, T>>;
6
+ export type PerNetworkConfig<T> = Partial<Record<SupportedChainId, T>>;
7
+ export type FlexibleConfig<T> = T | PerNetworkConfig<T> | PerTradeTypeConfig<T> | PerTradeTypeConfig<PerNetworkConfig<T>> | PerNetworkConfig<PerTradeTypeConfig<T>>;
5
8
  export declare enum WidgetMethodsEmit {
6
9
  ACTIVATE = "ACTIVATE",
7
10
  UPDATE_HEIGHT = "UPDATE_HEIGHT",
8
11
  SET_FULL_HEIGHT = "SET_FULL_HEIGHT",
9
12
  EMIT_COW_EVENT = "EMIT_COW_EVENT",
10
- PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST"
13
+ PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST",
14
+ INTERCEPT_WINDOW_OPEN = "INTERCEPT_WINDOW_OPEN"
11
15
  }
12
16
  export declare enum WidgetMethodsListen {
13
17
  UPDATE_PARAMS = "UPDATE_PARAMS",
@@ -71,18 +75,16 @@ export declare enum TradeType {
71
75
  }
72
76
  /**
73
77
  * The partner fee
74
- *
75
- * Please contact https://cowprotocol.typeform.com/to/rONXaxHV
76
78
  */
77
79
  export interface PartnerFee {
78
80
  /**
79
81
  * The fee in basis points (BPS). One basis point is equivalent to 0.01% (1/100th of a percent)
80
82
  */
81
- bps: number;
83
+ bps: FlexibleConfig<number>;
82
84
  /**
83
85
  * The Ethereum address of the partner to receive the fee.
84
86
  */
85
- recipient: string | Record<SupportedChainId, string>;
87
+ recipient: FlexibleConfig<string>;
86
88
  }
87
89
  /**
88
90
  * ERC-20 token information
@@ -252,6 +254,7 @@ export interface WidgetMethodsEmitPayloadMap {
252
254
  [WidgetMethodsEmit.UPDATE_HEIGHT]: UpdateWidgetHeightPayload;
253
255
  [WidgetMethodsEmit.SET_FULL_HEIGHT]: SetWidgetFullHeightPayload;
254
256
  [WidgetMethodsEmit.PROVIDER_RPC_REQUEST]: ProviderRpcRequestPayload;
257
+ [WidgetMethodsEmit.INTERCEPT_WINDOW_OPEN]: WindowOpenPayload;
255
258
  }
256
259
  export interface WidgetMethodsListenPayloadMap {
257
260
  [WidgetMethodsListen.UPDATE_APP_DATA]: UpdateAppDataPayload;
@@ -293,6 +296,11 @@ export type WidgetMethodHandler<T extends WidgetMethodsEmit> = (payload: WidgetM
293
296
  export interface ProviderRpcRequestPayload {
294
297
  rpcRequest: JsonRpcRequestMessage;
295
298
  }
299
+ export interface WindowOpenPayload {
300
+ href: string | URL;
301
+ target: string;
302
+ rel: string;
303
+ }
296
304
  export interface JsonRpcRequestMessage {
297
305
  jsonrpc: '2.0';
298
306
  id?: number;