@cowprotocol/widget-lib 0.14.0 → 0.15.0

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.
@@ -1,11 +1,10 @@
1
- import { CowEventListeners } from '../../events/src/index.ts';
2
-
1
+ import { CowWidgetEventListeners } from '@cowprotocol/events';
3
2
  export declare class IframeCowEventEmitter {
4
3
  private contentWindow;
5
4
  private eventEmitter;
6
5
  private listeners;
7
6
  private widgetListener;
8
- constructor(contentWindow: Window, listeners?: CowEventListeners);
7
+ constructor(contentWindow: Window, listeners?: CowWidgetEventListeners);
9
8
  stopListeningIframe(): void;
10
- updateListeners(listeners?: CowEventListeners): void;
9
+ updateListeners(listeners?: CowWidgetEventListeners): void;
11
10
  }
@@ -1,12 +1,11 @@
1
+ import { CowWidgetEventListeners } from '@cowprotocol/events';
1
2
  import { CowSwapWidgetParams, CowSwapWidgetProps, EthereumProvider } from './types';
2
- import { CowEventListeners } from '../../events/src/index.ts';
3
-
4
3
  /**
5
4
  * Callback function signature for updating the CoW Swap Widget.
6
5
  */
7
6
  export interface CowSwapWidgetHandler {
8
7
  updateParams: (params: CowSwapWidgetParams) => void;
9
- updateListeners: (newListeners?: CowEventListeners) => void;
8
+ updateListeners: (newListeners?: CowWidgetEventListeners) => void;
10
9
  updateProvider: (newProvider?: EthereumProvider) => void;
11
10
  destroy: () => void;
12
11
  }
@@ -1,6 +1,5 @@
1
- import { FlexibleConfig, PerNetworkConfig, PerTradeTypeConfig, TradeType } from './types';
2
1
  import { SupportedChainId } from '@cowprotocol/cow-sdk';
3
-
2
+ import { FlexibleConfig, PerNetworkConfig, PerTradeTypeConfig, TradeType } from './types';
4
3
  export declare function resolveFlexibleConfig<T extends string | number>(config: FlexibleConfig<T>, chainId: SupportedChainId, tradeType: TradeType): T | undefined;
5
4
  export declare function isPerTradeTypeConfig<T>(config: FlexibleConfig<T>): config is PerTradeTypeConfig<T>;
6
5
  export declare function isPerNetworkConfig<T>(config: FlexibleConfig<T>): config is PerNetworkConfig<T>;
package/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { createCowSwapWidget } from './cowSwapWidget';
2
+ export { widgetIframeTransport } from './widgetIframeTransport';
2
3
  export type { CowSwapWidgetHandler } from './cowSwapWidget';
3
4
  export * from './types';
4
- export * from './messages';
5
5
  export * from './themeUtils';
6
6
  export * from './flexibleConfig';
package/index.iife.js CHANGED
@@ -1 +1 @@
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;return this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(i),t}off(t){const{event:n,handler:i}=t;return this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(o=>o!==i)),t}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}({});
1
+ var cowSwapWidget=function(l){"use strict";var fe=Object.defineProperty;var de=(l,T,R)=>T in l?fe(l,T,{enumerable:!0,configurable:!0,writable:!0,value:R}):l[T]=R;var v=(l,T,R)=>(de(l,typeof T!="symbol"?T+"":T,R),R);class T{constructor(n){this.key=n}postMessageToWindow(n,t,s){const E=typeof s=="object"?s:{},h={key:this.key,method:t,...E};n.postMessage(h,"*")}listenToMessageFromWindow(n,t,s){const E=h=>{!R(h.data)||h.data.key!==this.key||h.data.method!==t||s(h.data)};return n.addEventListener("message",E),E}stopListeningToMessageFromWindow(n,t,s){n.removeEventListener("message",s)}stopListeningWindowListener(n,t){n.removeEventListener("message",t)}}function R(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var O=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(O||{});const W=new T("cowSwapIframeRpcProviderTransport"),H=["connect","disconnect","close","chainChanged","accountsChanged"];class x{constructor(n){v(this,"ethereumProvider",null);v(this,"requestWaitingForConnection",{});v(this,"processRpcCallFromWindow",({rpcRequest:n})=>{if(!this.ethereumProvider){n.id&&(this.requestWaitingForConnection[n.id]=n);return}this.processRpcRequest(n)});this.iframeWidow=n}disconnect(){this.ethereumProvider=null,W.stopListeningToMessageFromWindow(window,O.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():W.listenToMessageFromWindow(window,O.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),H.forEach(t=>{n.on(t,s=>this.onProviderEvent(t,s))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:s,method:E}=n;if(!this.ethereumProvider||!t)return;(E==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(_=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:t,result:_}})).catch(_=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:t,error:_}}))}onProviderEvent(n,t){W.postMessageToWindow(this.iframeWidow,O.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){W.postMessageToWindow(this.iframeWidow,O.PROVIDER_RPC_RESPONSE,n)}}var G={exports:{}};(function(e){var n=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function E(c,r,i){this.fn=c,this.context=r,this.once=i||!1}function h(c,r,i,o,w){if(typeof i!="function")throw new TypeError("The listener must be a function");var f=new E(i,o||c,w),d=t?t+r:r;return c._events[d]?c._events[d].fn?c._events[d]=[c._events[d],f]:c._events[d].push(f):(c._events[d]=f,c._eventsCount++),c}function _(c,r){--c._eventsCount===0?c._events=new s:delete c._events[r]}function u(){this._events=new s,this._eventsCount=0}u.prototype.eventNames=function(){var r=[],i,o;if(this._eventsCount===0)return r;for(o in i=this._events)n.call(i,o)&&r.push(t?o.slice(1):o);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(i)):r},u.prototype.listeners=function(r){var i=t?t+r:r,o=this._events[i];if(!o)return[];if(o.fn)return[o.fn];for(var w=0,f=o.length,d=new Array(f);w<f;w++)d[w]=o[w].fn;return d},u.prototype.listenerCount=function(r){var i=t?t+r:r,o=this._events[i];return o?o.fn?1:o.length:0},u.prototype.emit=function(r,i,o,w,f,d){var P=t?t+r:r;if(!this._events[P])return!1;var a=this._events[P],g=arguments.length,y,p;if(a.fn){switch(a.once&&this.removeListener(r,a.fn,void 0,!0),g){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,i),!0;case 3:return a.fn.call(a.context,i,o),!0;case 4:return a.fn.call(a.context,i,o,w),!0;case 5:return a.fn.call(a.context,i,o,w,f),!0;case 6:return a.fn.call(a.context,i,o,w,f,d),!0}for(p=1,y=new Array(g-1);p<g;p++)y[p-1]=arguments[p];a.fn.apply(a.context,y)}else{var ue=a.length,I;for(p=0;p<ue;p++)switch(a[p].once&&this.removeListener(r,a[p].fn,void 0,!0),g){case 1:a[p].fn.call(a[p].context);break;case 2:a[p].fn.call(a[p].context,i);break;case 3:a[p].fn.call(a[p].context,i,o);break;case 4:a[p].fn.call(a[p].context,i,o,w);break;default:if(!y)for(I=1,y=new Array(g-1);I<g;I++)y[I-1]=arguments[I];a[p].fn.apply(a[p].context,y)}}return!0},u.prototype.on=function(r,i,o){return h(this,r,i,o,!1)},u.prototype.once=function(r,i,o){return h(this,r,i,o,!0)},u.prototype.removeListener=function(r,i,o,w){var f=t?t+r:r;if(!this._events[f])return this;if(!i)return _(this,f),this;var d=this._events[f];if(d.fn)d.fn===i&&(!w||d.once)&&(!o||d.context===o)&&_(this,f);else{for(var P=0,a=[],g=d.length;P<g;P++)(d[P].fn!==i||w&&!d[P].once||o&&d[P].context!==o)&&a.push(d[P]);a.length?this._events[f]=a.length===1?a[0]:a:_(this,f)}return this},u.prototype.removeAllListeners=function(r){var i;return r?(i=t?t+r:r,this._events[i]&&_(this,i)):(this._events=new s,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=t,u.EventEmitter=u,e.exports=u})(G);class Q{constructor(){v(this,"subscriptions",{})}on(n){const{event:t,handler:s}=n;return this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(s),n}off(n){const{event:t,handler:s}=n;return this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(E=>E!==s)),n}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(s=>s(t))}}var C=(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))(C||{}),S=(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))(S||{}),A=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(A||{});const j=["primary","background","paper","text","danger","warning","alert","info","success"],m=new T("cowSwapWidget");class ${constructor(n,t=[]){v(this,"eventEmitter",new Q);v(this,"listeners",[]);v(this,"widgetListener");this.contentWindow=n,this.updateListeners(t),this.widgetListener=m.listenToMessageFromWindow(this.contentWindow,C.EMIT_COW_EVENT,s=>this.eventEmitter.emit(s.event,s.payload))}stopListeningIframe(){m.stopListeningWindowListener(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)}}class B{constructor(n,t){v(this,"forwardSdkMessage");this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=s=>{q(s.data)&&s.origin!==window.location.origin&&(z(s.data)?this.appWindow.parent.postMessage(s.data,"*"):J(s.data)&&this.iframeWidow.postMessage(s.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function q(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function z(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 J(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function b(e){return!!(e&&typeof e=="object")}const N="_";function K(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=V(e);return n+"/#"+t+"?"+M(e)}function V(e){const{chainId:n=1,sell:t,buy:s,tradeType:E=A.SWAP}=e,h=[(t==null?void 0:t.asset)||N,(s==null?void 0:s.asset)||N].map(encodeURIComponent).join("/");return`/${n}/widget/${E}/${h}`}function M(e){const n=new URLSearchParams;return Y(X(n,e),e)}function X(e,n){const{sell:t,buy:s}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),s!=null&&s.amount&&e.append("buyAmount",s.amount),e}function Y(e,n){const t=n.theme;return t?(b(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 F="640px",Z="450px",ee=20;function te(e,n){const{params:t,provider:s,listeners:E}=n;let h=s,_=t;const u=ne(t);e.innerHTML="",e.appendChild(u);const{contentWindow:c}=u;if(!c)throw console.error("Iframe does not contain a window",u),new Error("Iframe does not contain a window!");const r=[];r.push(se(c,t.appCode)),r.push(...ie(u,t.height)),r.push(re());const i=new $(window,E);let o=U(c,null,h);u.addEventListener("load",()=>k(c,_,h));const w=new B(window,c);return{updateParams:f=>{_=f,k(c,_,h)},updateListeners:f=>i.updateListeners(f),updateProvider:f=>{h=f,o=U(c,o,f)},destroy:()=>{o.disconnect(),i.stopListeningIframe(),r.forEach(f=>window.removeEventListener("message",f)),w.stopListening(),e.removeChild(u)}}}function U(e,n,t){n&&n.disconnect();const s=n||new x(e);return t&&s.onConnect(t),s}function ne(e){const{width:n=Z,height:t=F}=e,s=document.createElement("iframe");return s.src=K(e),s.width=n,s.height=t,s.style.border="0",s.allow="clipboard-read; clipboard-write",s}function k(e,n,t){const s=!!t,E=V(n),h=M(n).toString(),{theme:_,...u}=n;m.postMessageToWindow(e,S.UPDATE_PARAMS,{urlParams:{pathname:E,search:h},appParams:u,hasProvider:s})}function se(e,n){return m.listenToMessageFromWindow(window,C.ACTIVATE,()=>{m.postMessageToWindow(e,S.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})})}function re(){return m.listenToMessageFromWindow(window,C.INTERCEPT_WINDOW_OPEN,({href:e,rel:n,target:t})=>{const s=e.toString();if(!s.startsWith("http")&&s.match(/^[a-zA-Z0-9]+:\/\//)){window.open(s,t,n);return}})}function ie(e,n=F){return[m.listenToMessageFromWindow(window,C.UPDATE_HEIGHT,t=>{e.style.height=t.height?`${t.height+ee}px`:n}),m.listenToMessageFromWindow(window,C.SET_FULL_HEIGHT,({isUpToSmall:t})=>{e.style.height=t?n:`${document.body.offsetHeight}px`})]}const oe=Object.values(A);function ae(e,n,t){if(L(e)){const s=e[t];return D(s)?s[n]:s}if(D(e)){const s=e[n];return L(s)?s[t]:s}return e}function L(e){return typeof e!="object"?!1:Object.keys(e).every(n=>oe.includes(n))}const ce=/^\d+$/;function D(e){return typeof e!="object"?!1:Object.keys(e).every(n=>typeof n=="number"||ce.test(n))}return l.TradeType=A,l.WIDGET_PALETTE_COLORS=j,l.WidgetMethodsEmit=C,l.WidgetMethodsListen=S,l.createCowSwapWidget=te,l.isCowSwapWidgetPalette=b,l.isPerNetworkConfig=D,l.isPerTradeTypeConfig=L,l.resolveFlexibleConfig=ae,l.widgetIframeTransport=m,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l}({});
package/index.js CHANGED
@@ -1 +1 @@
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;return this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(i),t}off(t){const{event:n,handler:i}=t;return this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(s=>s!==i)),t}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;
1
+ "use strict";var k=Object.defineProperty;var x=(e,n,t)=>n in e?k(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var T=(e,n,t)=>(x(e,typeof n!="symbol"?n+"":n,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class b{constructor(n){this.key=n}postMessageToWindow(n,t,s){const l=typeof s=="object"?s:{},h={key:this.key,method:t,...l};n.postMessage(h,"*")}listenToMessageFromWindow(n,t,s){const l=h=>{!H(h.data)||h.data.key!==this.key||h.data.method!==t||s(h.data)};return n.addEventListener("message",l),l}stopListeningToMessageFromWindow(n,t,s){n.removeEventListener("message",s)}stopListeningWindowListener(n,t){n.removeEventListener("message",t)}}function H(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var C=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(C||{});const y=new b("cowSwapIframeRpcProviderTransport"),G=["connect","disconnect","close","chainChanged","accountsChanged"];class Q{constructor(n){T(this,"ethereumProvider",null);T(this,"requestWaitingForConnection",{});T(this,"processRpcCallFromWindow",({rpcRequest:n})=>{if(!this.ethereumProvider){n.id&&(this.requestWaitingForConnection[n.id]=n);return}this.processRpcRequest(n)});this.iframeWidow=n}disconnect(){this.ethereumProvider=null,y.stopListeningToMessageFromWindow(window,C.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():y.listenToMessageFromWindow(window,C.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),G.forEach(t=>{n.on(t,s=>this.onProviderEvent(t,s))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:s,method:l}=n;if(!this.ethereumProvider||!t)return;(l==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:t,result:w}})).catch(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:t,error:w}}))}onProviderEvent(n,t){y.postMessageToWindow(this.iframeWidow,C.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){y.postMessageToWindow(this.iframeWidow,C.PROVIDER_RPC_RESPONSE,n)}}var j={exports:{}};(function(e){var n=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function l(c,r,o){this.fn=c,this.context=r,this.once=o||!1}function h(c,r,o,i,E){if(typeof o!="function")throw new TypeError("The listener must be a function");var f=new l(o,i||c,E),p=t?t+r:r;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],f]:c._events[p].push(f):(c._events[p]=f,c._eventsCount++),c}function w(c,r){--c._eventsCount===0?c._events=new s:delete c._events[r]}function u(){this._events=new s,this._eventsCount=0}u.prototype.eventNames=function(){var r=[],o,i;if(this._eventsCount===0)return r;for(i in o=this._events)n.call(o,i)&&r.push(t?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(o)):r},u.prototype.listeners=function(r){var o=t?t+r:r,i=this._events[o];if(!i)return[];if(i.fn)return[i.fn];for(var E=0,f=i.length,p=new Array(f);E<f;E++)p[E]=i[E].fn;return p},u.prototype.listenerCount=function(r){var o=t?t+r:r,i=this._events[o];return i?i.fn?1:i.length:0},u.prototype.emit=function(r,o,i,E,f,p){var _=t?t+r:r;if(!this._events[_])return!1;var a=this._events[_],P=arguments.length,v,d;if(a.fn){switch(a.once&&this.removeListener(r,a.fn,void 0,!0),P){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,o),!0;case 3:return a.fn.call(a.context,o,i),!0;case 4:return a.fn.call(a.context,o,i,E),!0;case 5:return a.fn.call(a.context,o,i,E,f),!0;case 6:return a.fn.call(a.context,o,i,E,f,p),!0}for(d=1,v=new Array(P-1);d<P;d++)v[d-1]=arguments[d];a.fn.apply(a.context,v)}else{var U=a.length,R;for(d=0;d<U;d++)switch(a[d].once&&this.removeListener(r,a[d].fn,void 0,!0),P){case 1:a[d].fn.call(a[d].context);break;case 2:a[d].fn.call(a[d].context,o);break;case 3:a[d].fn.call(a[d].context,o,i);break;case 4:a[d].fn.call(a[d].context,o,i,E);break;default:if(!v)for(R=1,v=new Array(P-1);R<P;R++)v[R-1]=arguments[R];a[d].fn.apply(a[d].context,v)}}return!0},u.prototype.on=function(r,o,i){return h(this,r,o,i,!1)},u.prototype.once=function(r,o,i){return h(this,r,o,i,!0)},u.prototype.removeListener=function(r,o,i,E){var f=t?t+r:r;if(!this._events[f])return this;if(!o)return w(this,f),this;var p=this._events[f];if(p.fn)p.fn===o&&(!E||p.once)&&(!i||p.context===i)&&w(this,f);else{for(var _=0,a=[],P=p.length;_<P;_++)(p[_].fn!==o||E&&!p[_].once||i&&p[_].context!==i)&&a.push(p[_]);a.length?this._events[f]=a.length===1?a[0]:a:w(this,f)}return this},u.prototype.removeAllListeners=function(r){var o;return r?(o=t?t+r:r,this._events[o]&&w(this,o)):(this._events=new s,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=t,u.EventEmitter=u,e.exports=u})(j);class ${constructor(){T(this,"subscriptions",{})}on(n){const{event:t,handler:s}=n;return this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(s),n}off(n){const{event:t,handler:s}=n;return this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(l=>l!==s)),n}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(s=>s(t))}}var g=(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))(g||{}),O=(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))(O||{}),I=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(I||{});const B=["primary","background","paper","text","danger","warning","alert","info","success"],m=new b("cowSwapWidget");class q{constructor(n,t=[]){T(this,"eventEmitter",new $);T(this,"listeners",[]);T(this,"widgetListener");this.contentWindow=n,this.updateListeners(t),this.widgetListener=m.listenToMessageFromWindow(this.contentWindow,g.EMIT_COW_EVENT,s=>this.eventEmitter.emit(s.event,s.payload))}stopListeningIframe(){m.stopListeningWindowListener(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)}}class z{constructor(n,t){T(this,"forwardSdkMessage");this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=s=>{J(s.data)&&s.origin!==window.location.origin&&(K(s.data)?this.appWindow.parent.postMessage(s.data,"*"):X(s.data)&&this.iframeWidow.postMessage(s.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function J(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 X(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function N(e){return!!(e&&typeof e=="object")}const A="_";function Y(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=V(e);return n+"/#"+t+"?"+M(e)}function V(e){const{chainId:n=1,sell:t,buy:s,tradeType:l=I.SWAP}=e,h=[(t==null?void 0:t.asset)||A,(s==null?void 0:s.asset)||A].map(encodeURIComponent).join("/");return`/${n}/widget/${l}/${h}`}function M(e){const n=new URLSearchParams;return ee(Z(n,e),e)}function Z(e,n){const{sell:t,buy:s}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),s!=null&&s.amount&&e.append("buyAmount",s.amount),e}function ee(e,n){const t=n.theme;return t?(N(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 F="640px",te="450px",ne=20;function se(e,n){const{params:t,provider:s,listeners:l}=n;let h=s,w=t;const u=re(t);e.innerHTML="",e.appendChild(u);const{contentWindow:c}=u;if(!c)throw console.error("Iframe does not contain a window",u),new Error("Iframe does not contain a window!");const r=[];r.push(oe(c,t.appCode)),r.push(...ae(u,t.height)),r.push(ie());const o=new q(window,l);let i=L(c,null,h);u.addEventListener("load",()=>D(c,w,h));const E=new z(window,c);return{updateParams:f=>{w=f,D(c,w,h)},updateListeners:f=>o.updateListeners(f),updateProvider:f=>{h=f,i=L(c,i,f)},destroy:()=>{i.disconnect(),o.stopListeningIframe(),r.forEach(f=>window.removeEventListener("message",f)),E.stopListening(),e.removeChild(u)}}}function L(e,n,t){n&&n.disconnect();const s=n||new Q(e);return t&&s.onConnect(t),s}function re(e){const{width:n=te,height:t=F}=e,s=document.createElement("iframe");return s.src=Y(e),s.width=n,s.height=t,s.style.border="0",s.allow="clipboard-read; clipboard-write",s}function D(e,n,t){const s=!!t,l=V(n),h=M(n).toString(),{theme:w,...u}=n;m.postMessageToWindow(e,O.UPDATE_PARAMS,{urlParams:{pathname:l,search:h},appParams:u,hasProvider:s})}function oe(e,n){return m.listenToMessageFromWindow(window,g.ACTIVATE,()=>{m.postMessageToWindow(e,O.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})})}function ie(){return m.listenToMessageFromWindow(window,g.INTERCEPT_WINDOW_OPEN,({href:e,rel:n,target:t})=>{const s=e.toString();if(!s.startsWith("http")&&s.match(/^[a-zA-Z0-9]+:\/\//)){window.open(s,t,n);return}})}function ae(e,n=F){return[m.listenToMessageFromWindow(window,g.UPDATE_HEIGHT,t=>{e.style.height=t.height?`${t.height+ne}px`:n}),m.listenToMessageFromWindow(window,g.SET_FULL_HEIGHT,({isUpToSmall:t})=>{e.style.height=t?n:`${document.body.offsetHeight}px`})]}const ce=Object.values(I);function ue(e,n,t){if(W(e)){const s=e[t];return S(s)?s[n]:s}if(S(e)){const s=e[n];return W(s)?s[t]:s}return e}function W(e){return typeof e!="object"?!1:Object.keys(e).every(n=>ce.includes(n))}const fe=/^\d+$/;function S(e){return typeof e!="object"?!1:Object.keys(e).every(n=>typeof n=="number"||fe.test(n))}exports.TradeType=I;exports.WIDGET_PALETTE_COLORS=B;exports.WidgetMethodsEmit=g;exports.WidgetMethodsListen=O;exports.createCowSwapWidget=se;exports.isCowSwapWidgetPalette=N;exports.isPerNetworkConfig=S;exports.isPerTradeTypeConfig=W;exports.resolveFlexibleConfig=ue;exports.widgetIframeTransport=m;
package/index.mjs CHANGED
@@ -1,164 +1,294 @@
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 {
5
- constructor() {
6
- r(this, "subscriptions", {});
1
+ var M = Object.defineProperty;
2
+ var x = (e, n, t) => n in e ? M(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
+ var m = (e, n, t) => (x(e, typeof n != "symbol" ? n + "" : n, t), t);
4
+ class b {
5
+ constructor(n) {
6
+ this.key = n;
7
7
  }
8
- on(t) {
9
- const { event: n, handler: s } = t;
10
- return this.subscriptions[n] || (this.subscriptions[n] = []), this.subscriptions[n].push(s), t;
8
+ postMessageToWindow(n, t, s) {
9
+ const l = typeof s == "object" ? s : {}, h = {
10
+ key: this.key,
11
+ method: t,
12
+ ...l
13
+ };
14
+ n.postMessage(
15
+ h,
16
+ "*"
17
+ // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
18
+ );
11
19
  }
12
- off(t) {
13
- const { event: n, handler: s } = t;
14
- return this.subscriptions[n] && (this.subscriptions[n] = this.subscriptions[n].filter((i) => i !== s)), t;
20
+ listenToMessageFromWindow(n, t, s) {
21
+ const l = (h) => {
22
+ !k(h.data) || h.data.key !== this.key || h.data.method !== t || s(h.data);
23
+ };
24
+ return n.addEventListener("message", l), l;
15
25
  }
16
- emit(t, n) {
17
- this.subscriptions[t] && this.subscriptions[t].forEach((s) => s(n));
26
+ stopListeningToMessageFromWindow(n, t, s) {
27
+ n.removeEventListener("message", s);
28
+ }
29
+ stopListeningWindowListener(n, t) {
30
+ n.removeEventListener("message", t);
18
31
  }
19
32
  }
20
- const A = "cowSwapWidget";
21
- function l(e, t, n) {
22
- const i = {
23
- key: A,
24
- method: t,
25
- ...typeof n == "object" ? n : {}
26
- };
27
- e.postMessage(
28
- i,
29
- "*"
30
- // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
31
- );
32
- }
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);
36
- };
37
- return e.addEventListener("message", s), s;
38
- }
39
- function b(e) {
33
+ function k(e) {
40
34
  return typeof e == "object" && e !== null && "key" in e && "method" in e && typeof e.key == "string" && typeof e.method == "string";
41
35
  }
42
- function N(e, t, n) {
43
- e.removeEventListener("message", n);
44
- }
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 = [
50
- "primary",
51
- "background",
52
- "paper",
53
- "text",
54
- "danger",
55
- "warning",
56
- "alert",
57
- "info",
58
- "success"
59
- ];
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(
66
- this.contentWindow,
67
- u.EMIT_COW_EVENT,
68
- (s) => this.eventEmitter.emit(s.event, s.payload)
69
- );
70
- }
71
- stopListeningIframe() {
72
- y(this.contentWindow, this.widgetListener);
73
- }
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);
80
- }
81
- }
82
- const V = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
83
- class H {
36
+ var O = /* @__PURE__ */ ((e) => (e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(O || {});
37
+ const y = new b(
38
+ "cowSwapIframeRpcProviderTransport"
39
+ ), H = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
40
+ class G {
84
41
  /**
85
42
  * Creates an instance of IframeRpcProviderBridge.
86
43
  * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
87
44
  * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
88
45
  */
89
- constructor(t) {
46
+ constructor(n) {
90
47
  /**
91
48
  * The Ethereum provider instance.
92
49
  * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
93
50
  * */
94
- r(this, "ethereumProvider", null);
51
+ m(this, "ethereumProvider", null);
95
52
  /** Stored JSON-RPC requests, to queue them when disconnected. */
96
- r(this, "requestWaitingForConnection", {});
97
- r(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
53
+ m(this, "requestWaitingForConnection", {});
54
+ m(this, "processRpcCallFromWindow", ({ rpcRequest: n }) => {
98
55
  if (!this.ethereumProvider) {
99
- t.id && (this.requestWaitingForConnection[t.id] = t);
56
+ n.id && (this.requestWaitingForConnection[n.id] = n);
100
57
  return;
101
58
  }
102
- this.processRpcRequest(t);
59
+ this.processRpcRequest(n);
103
60
  });
104
- this.iframeWidow = t;
61
+ this.iframeWidow = n;
105
62
  }
106
63
  /**
107
64
  * Disconnects the JSON-RPC bridge from the Ethereum provider.
108
65
  */
109
66
  disconnect() {
110
- this.ethereumProvider = null, N(window, u.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
67
+ this.ethereumProvider = null, y.stopListeningToMessageFromWindow(
68
+ window,
69
+ O.PROVIDER_RPC_REQUEST,
70
+ this.processRpcCallFromWindow
71
+ );
111
72
  }
112
73
  /**
113
74
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
114
75
  * @param newProvider - The Ethereum provider to connect.
115
76
  */
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));
77
+ onConnect(n) {
78
+ this.ethereumProvider ? this.disconnect() : y.listenToMessageFromWindow(
79
+ window,
80
+ O.PROVIDER_RPC_REQUEST,
81
+ this.processRpcCallFromWindow
82
+ ), this.ethereumProvider = n, this.processPendingRequests(), H.forEach((t) => {
83
+ n.on(t, (s) => this.onProviderEvent(t, s));
119
84
  });
120
85
  }
121
86
  processPendingRequests() {
122
- Object.keys(this.requestWaitingForConnection).forEach((t) => {
123
- this.processRpcRequest(this.requestWaitingForConnection[t]);
87
+ Object.keys(this.requestWaitingForConnection).forEach((n) => {
88
+ this.processRpcRequest(this.requestWaitingForConnection[n]);
124
89
  }), this.requestWaitingForConnection = {};
125
90
  }
126
91
  /**
127
92
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
128
93
  * @param request - The JSON-RPC request to be processed.
129
94
  */
130
- processRpcRequest(t) {
131
- const { id: n, jsonrpc: s, method: i } = t;
132
- if (!this.ethereumProvider || !n)
95
+ processRpcRequest(n) {
96
+ const { id: t, jsonrpc: s, method: l } = n;
97
+ if (!this.ethereumProvider || !t)
133
98
  return;
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 }
99
+ (l === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...n, id: t })).then(
100
+ (w) => this.forwardRpcResponseToIframe({
101
+ rpcResponse: { jsonrpc: s, id: t, result: w }
137
102
  })
138
103
  ).catch(
139
- (a) => this.forwardRpcResponseToIframe({
140
- rpcResponse: { jsonrpc: s, id: n, error: a }
104
+ (w) => this.forwardRpcResponseToIframe({
105
+ rpcResponse: { jsonrpc: s, id: t, error: w }
141
106
  })
142
107
  );
143
108
  }
144
- onProviderEvent(t, n) {
145
- l(this.iframeWidow, f.PROVIDER_ON_EVENT, {
146
- event: t,
147
- params: n
109
+ onProviderEvent(n, t) {
110
+ y.postMessageToWindow(this.iframeWidow, O.PROVIDER_ON_EVENT, {
111
+ event: n,
112
+ params: t
148
113
  });
149
114
  }
150
115
  /**
151
116
  * Forward a JSON-RPC message to the content window.
152
117
  */
153
- forwardRpcResponseToIframe(t) {
154
- l(this.iframeWidow, f.PROVIDER_RPC_RESPONSE, t);
118
+ forwardRpcResponseToIframe(n) {
119
+ y.postMessageToWindow(
120
+ this.iframeWidow,
121
+ O.PROVIDER_RPC_RESPONSE,
122
+ n
123
+ );
155
124
  }
156
125
  }
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, "*"));
126
+ var Q = { exports: {} };
127
+ (function(e) {
128
+ var n = Object.prototype.hasOwnProperty, t = "~";
129
+ function s() {
130
+ }
131
+ Object.create && (s.prototype = /* @__PURE__ */ Object.create(null), new s().__proto__ || (t = !1));
132
+ function l(c, r, o) {
133
+ this.fn = c, this.context = r, this.once = o || !1;
134
+ }
135
+ function h(c, r, o, i, E) {
136
+ if (typeof o != "function")
137
+ throw new TypeError("The listener must be a function");
138
+ var f = new l(o, i || c, E), p = t ? t + r : r;
139
+ return c._events[p] ? c._events[p].fn ? c._events[p] = [c._events[p], f] : c._events[p].push(f) : (c._events[p] = f, c._eventsCount++), c;
140
+ }
141
+ function w(c, r) {
142
+ --c._eventsCount === 0 ? c._events = new s() : delete c._events[r];
143
+ }
144
+ function u() {
145
+ this._events = new s(), this._eventsCount = 0;
146
+ }
147
+ u.prototype.eventNames = function() {
148
+ var r = [], o, i;
149
+ if (this._eventsCount === 0)
150
+ return r;
151
+ for (i in o = this._events)
152
+ n.call(o, i) && r.push(t ? i.slice(1) : i);
153
+ return Object.getOwnPropertySymbols ? r.concat(Object.getOwnPropertySymbols(o)) : r;
154
+ }, u.prototype.listeners = function(r) {
155
+ var o = t ? t + r : r, i = this._events[o];
156
+ if (!i)
157
+ return [];
158
+ if (i.fn)
159
+ return [i.fn];
160
+ for (var E = 0, f = i.length, p = new Array(f); E < f; E++)
161
+ p[E] = i[E].fn;
162
+ return p;
163
+ }, u.prototype.listenerCount = function(r) {
164
+ var o = t ? t + r : r, i = this._events[o];
165
+ return i ? i.fn ? 1 : i.length : 0;
166
+ }, u.prototype.emit = function(r, o, i, E, f, p) {
167
+ var _ = t ? t + r : r;
168
+ if (!this._events[_])
169
+ return !1;
170
+ var a = this._events[_], T = arguments.length, P, d;
171
+ if (a.fn) {
172
+ switch (a.once && this.removeListener(r, a.fn, void 0, !0), T) {
173
+ case 1:
174
+ return a.fn.call(a.context), !0;
175
+ case 2:
176
+ return a.fn.call(a.context, o), !0;
177
+ case 3:
178
+ return a.fn.call(a.context, o, i), !0;
179
+ case 4:
180
+ return a.fn.call(a.context, o, i, E), !0;
181
+ case 5:
182
+ return a.fn.call(a.context, o, i, E, f), !0;
183
+ case 6:
184
+ return a.fn.call(a.context, o, i, E, f, p), !0;
185
+ }
186
+ for (d = 1, P = new Array(T - 1); d < T; d++)
187
+ P[d - 1] = arguments[d];
188
+ a.fn.apply(a.context, P);
189
+ } else {
190
+ var F = a.length, g;
191
+ for (d = 0; d < F; d++)
192
+ switch (a[d].once && this.removeListener(r, a[d].fn, void 0, !0), T) {
193
+ case 1:
194
+ a[d].fn.call(a[d].context);
195
+ break;
196
+ case 2:
197
+ a[d].fn.call(a[d].context, o);
198
+ break;
199
+ case 3:
200
+ a[d].fn.call(a[d].context, o, i);
201
+ break;
202
+ case 4:
203
+ a[d].fn.call(a[d].context, o, i, E);
204
+ break;
205
+ default:
206
+ if (!P)
207
+ for (g = 1, P = new Array(T - 1); g < T; g++)
208
+ P[g - 1] = arguments[g];
209
+ a[d].fn.apply(a[d].context, P);
210
+ }
211
+ }
212
+ return !0;
213
+ }, u.prototype.on = function(r, o, i) {
214
+ return h(this, r, o, i, !1);
215
+ }, u.prototype.once = function(r, o, i) {
216
+ return h(this, r, o, i, !0);
217
+ }, u.prototype.removeListener = function(r, o, i, E) {
218
+ var f = t ? t + r : r;
219
+ if (!this._events[f])
220
+ return this;
221
+ if (!o)
222
+ return w(this, f), this;
223
+ var p = this._events[f];
224
+ if (p.fn)
225
+ p.fn === o && (!E || p.once) && (!i || p.context === i) && w(this, f);
226
+ else {
227
+ for (var _ = 0, a = [], T = p.length; _ < T; _++)
228
+ (p[_].fn !== o || E && !p[_].once || i && p[_].context !== i) && a.push(p[_]);
229
+ a.length ? this._events[f] = a.length === 1 ? a[0] : a : w(this, f);
230
+ }
231
+ return this;
232
+ }, u.prototype.removeAllListeners = function(r) {
233
+ var o;
234
+ return r ? (o = t ? t + r : r, this._events[o] && w(this, o)) : (this._events = new s(), this._eventsCount = 0), this;
235
+ }, u.prototype.off = u.prototype.removeListener, u.prototype.addListener = u.prototype.on, u.prefixed = t, u.EventEmitter = u, e.exports = u;
236
+ })(Q);
237
+ class j {
238
+ constructor() {
239
+ m(this, "subscriptions", {});
240
+ }
241
+ on(n) {
242
+ const { event: t, handler: s } = n;
243
+ return this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(s), n;
244
+ }
245
+ off(n) {
246
+ const { event: t, handler: s } = n;
247
+ return this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((l) => l !== s)), n;
248
+ }
249
+ emit(n, t) {
250
+ this.subscriptions[n] && this.subscriptions[n].forEach((s) => s(t));
251
+ }
252
+ }
253
+ var R = /* @__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))(R || {}), C = /* @__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))(C || {}), I = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(I || {});
254
+ const ue = [
255
+ "primary",
256
+ "background",
257
+ "paper",
258
+ "text",
259
+ "danger",
260
+ "warning",
261
+ "alert",
262
+ "info",
263
+ "success"
264
+ ], v = new b("cowSwapWidget");
265
+ class $ {
266
+ constructor(n, t = []) {
267
+ m(this, "eventEmitter", new j());
268
+ m(this, "listeners", []);
269
+ m(this, "widgetListener");
270
+ this.contentWindow = n, this.updateListeners(t), this.widgetListener = v.listenToMessageFromWindow(
271
+ this.contentWindow,
272
+ R.EMIT_COW_EVENT,
273
+ (s) => this.eventEmitter.emit(s.event, s.payload)
274
+ );
275
+ }
276
+ stopListeningIframe() {
277
+ v.stopListeningWindowListener(this.contentWindow, this.widgetListener);
278
+ }
279
+ updateListeners(n) {
280
+ for (const t of this.listeners)
281
+ this.eventEmitter.off(t);
282
+ this.listeners = n || [];
283
+ for (const t of this.listeners)
284
+ this.eventEmitter.on(t);
285
+ }
286
+ }
287
+ class B {
288
+ constructor(n, t) {
289
+ m(this, "forwardSdkMessage");
290
+ this.appWindow = n, this.iframeWidow = t, this.forwardSdkMessage = (s) => {
291
+ q(s.data) && s.origin !== window.location.origin && (z(s.data) ? this.appWindow.parent.postMessage(s.data, "*") : J(s.data) && this.iframeWidow.postMessage(s.data, "*"));
162
292
  }, this.startListening();
163
293
  }
164
294
  startListening() {
@@ -168,144 +298,145 @@ class F {
168
298
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
169
299
  }
170
300
  }
171
- function k(e) {
301
+ function q(e) {
172
302
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
173
303
  }
174
- function M(e) {
304
+ function z(e) {
175
305
  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;
176
306
  }
177
- function G(e) {
307
+ function J(e) {
178
308
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
179
309
  }
180
- function x(e) {
310
+ function K(e) {
181
311
  return !!(e && typeof e == "object");
182
312
  }
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);
313
+ const A = "_";
314
+ function X(e) {
315
+ const n = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", t = N(e);
316
+ return n + "/#" + t + "?" + V(e);
187
317
  }
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}`;
318
+ function N(e) {
319
+ const { chainId: n = 1, sell: t, buy: s, tradeType: l = I.SWAP } = e, h = [(t == null ? void 0 : t.asset) || A, (s == null ? void 0 : s.asset) || A].map(encodeURIComponent).join("/");
320
+ return `/${n}/widget/${l}/${h}`;
191
321
  }
192
- function C(e) {
193
- const t = new URLSearchParams();
194
- return j($(t, e), e);
322
+ function V(e) {
323
+ const n = new URLSearchParams();
324
+ return Z(Y(n, e), e);
195
325
  }
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;
326
+ function Y(e, n) {
327
+ const { sell: t, buy: s } = n;
328
+ return t != null && t.amount && e.append("sellAmount", t.amount), s != null && s.amount && e.append("buyAmount", s.amount), e;
199
329
  }
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);
330
+ function Z(e, n) {
331
+ const t = n.theme;
332
+ return t ? (K(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);
203
333
  }
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);
334
+ const U = "640px", ee = "450px", te = 20;
335
+ function fe(e, n) {
336
+ const { params: t, provider: s, listeners: l } = n;
337
+ let h = s, w = t;
338
+ const u = ne(t);
339
+ e.innerHTML = "", e.appendChild(u);
340
+ const { contentWindow: c } = u;
341
+ if (!c)
342
+ throw console.error("Iframe does not contain a window", u), new Error("Iframe does not contain a window!");
343
+ const r = [];
344
+ r.push(se(c, t.appCode)), r.push(...oe(u, t.height)), r.push(re());
345
+ const o = new $(window, l);
346
+ let i = W(c, null, h);
347
+ u.addEventListener("load", () => S(c, w, h));
348
+ const E = new B(window, c);
219
349
  return {
220
- updateParams: (d) => {
221
- a = d, R(p, a, o);
350
+ updateParams: (f) => {
351
+ w = f, S(c, w, h);
222
352
  },
223
- updateListeners: (d) => P.updateListeners(d),
224
- updateProvider: (d) => {
225
- o = d, w = _(p, w, d);
353
+ updateListeners: (f) => o.updateListeners(f),
354
+ updateProvider: (f) => {
355
+ h = f, i = W(c, i, f);
226
356
  },
227
357
  destroy: () => {
228
- w.disconnect(), P.stopListeningIframe(), E.forEach((d) => window.removeEventListener("message", d)), S.stopListening(), e.removeChild(c);
358
+ i.disconnect(), o.stopListeningIframe(), r.forEach((f) => window.removeEventListener("message", f)), E.stopListening(), e.removeChild(u);
229
359
  }
230
360
  };
231
361
  }
232
- function _(e, t, n) {
233
- t && t.disconnect();
234
- const s = t || new H(e);
235
- return n && s.onConnect(n), s;
362
+ function W(e, n, t) {
363
+ n && n.disconnect();
364
+ const s = n || new G(e);
365
+ return t && s.onConnect(t), s;
236
366
  }
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;
367
+ function ne(e) {
368
+ const { width: n = ee, height: t = U } = e, s = document.createElement("iframe");
369
+ return s.src = X(e), s.width = n, s.height = t, s.style.border = "0", s.allow = "clipboard-read; clipboard-write", s;
240
370
  }
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, {
371
+ function S(e, n, t) {
372
+ const s = !!t, l = N(n), h = V(n).toString(), { theme: w, ...u } = n;
373
+ v.postMessageToWindow(e, C.UPDATE_PARAMS, {
244
374
  urlParams: {
245
- pathname: i,
246
- search: o
375
+ pathname: l,
376
+ search: h
247
377
  },
248
- appParams: c,
378
+ appParams: u,
249
379
  hasProvider: s
250
380
  });
251
381
  }
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
382
+ function se(e, n) {
383
+ return v.listenToMessageFromWindow(window, R.ACTIVATE, () => {
384
+ v.postMessageToWindow(e, C.UPDATE_APP_DATA, {
385
+ metaData: n ? { appCode: n } : void 0
256
386
  });
257
387
  });
258
388
  }
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;
389
+ function re() {
390
+ return v.listenToMessageFromWindow(
391
+ window,
392
+ R.INTERCEPT_WINDOW_OPEN,
393
+ ({ href: e, rel: n, target: t }) => {
394
+ const s = e.toString();
395
+ if (!s.startsWith("http") && s.match(/^[a-zA-Z0-9]+:\/\//)) {
396
+ window.open(s, t, n);
397
+ return;
398
+ }
265
399
  }
266
- });
400
+ );
267
401
  }
268
- function J(e, t = W) {
402
+ function oe(e, n = U) {
269
403
  return [
270
- h(window, u.UPDATE_HEIGHT, (n) => {
271
- e.style.height = n.height ? `${n.height + q}px` : t;
404
+ v.listenToMessageFromWindow(window, R.UPDATE_HEIGHT, (t) => {
405
+ e.style.height = t.height ? `${t.height + te}px` : n;
272
406
  }),
273
- h(window, u.SET_FULL_HEIGHT, ({ isUpToSmall: n }) => {
274
- e.style.height = n ? t : `${document.body.offsetHeight}px`;
407
+ v.listenToMessageFromWindow(window, R.SET_FULL_HEIGHT, ({ isUpToSmall: t }) => {
408
+ e.style.height = t ? n : `${document.body.offsetHeight}px`;
275
409
  })
276
410
  ];
277
411
  }
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)) {
412
+ const ie = Object.values(I);
413
+ function pe(e, n, t) {
414
+ if (L(e)) {
285
415
  const s = e[t];
286
- return g(s) ? s[n] : s;
416
+ return D(s) ? s[n] : s;
417
+ }
418
+ if (D(e)) {
419
+ const s = e[n];
420
+ return L(s) ? s[t] : s;
287
421
  }
288
422
  return e;
289
423
  }
290
- function g(e) {
291
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => X.includes(t));
424
+ function L(e) {
425
+ return typeof e != "object" ? !1 : Object.keys(e).every((n) => ie.includes(n));
292
426
  }
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));
427
+ const ae = /^\d+$/;
428
+ function D(e) {
429
+ return typeof e != "object" ? !1 : Object.keys(e).every((n) => typeof n == "number" || ae.test(n));
296
430
  }
297
431
  export {
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
432
+ I as TradeType,
433
+ ue as WIDGET_PALETTE_COLORS,
434
+ R as WidgetMethodsEmit,
435
+ C as WidgetMethodsListen,
436
+ fe as createCowSwapWidget,
437
+ K as isCowSwapWidgetPalette,
438
+ D as isPerNetworkConfig,
439
+ L as isPerTradeTypeConfig,
440
+ pe as resolveFlexibleConfig,
441
+ v as widgetIframeTransport
311
442
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
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",
@@ -21,6 +21,7 @@
21
21
  "widget-lib"
22
22
  ],
23
23
  "dependencies": {
24
- "@cowprotocol/events": "^1.3.0"
24
+ "@cowprotocol/events": "^1.5.0",
25
+ "@cowprotocol/iframe-transport": "^1.1.0"
25
26
  }
26
27
  }
package/themeUtils.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  import { CowSwapTheme, CowSwapWidgetPalette } from './types';
2
-
3
2
  export declare function isCowSwapWidgetPalette(palette: CowSwapTheme | CowSwapWidgetPalette | undefined): palette is CowSwapWidgetPalette;
package/types.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { CowEventListeners, CowEventPayloadMap, CowEvents } from '../../events/src/index.ts';
2
1
  import { SupportedChainId } from '@cowprotocol/cow-sdk';
3
-
2
+ import { CowWidgetEventListeners, CowWidgetEventPayloadMap, CowWidgetEvents } from '@cowprotocol/events';
4
3
  export type { SupportedChainId } from '@cowprotocol/cow-sdk';
5
4
  export type PerTradeTypeConfig<T> = Partial<Record<TradeType, T>>;
6
5
  export type PerNetworkConfig<T> = Partial<Record<SupportedChainId, T>>;
@@ -22,7 +21,7 @@ export declare enum WidgetMethodsListen {
22
21
  export interface CowSwapWidgetProps {
23
22
  params: CowSwapWidgetParams;
24
23
  provider?: EthereumProvider;
25
- listeners?: CowEventListeners;
24
+ listeners?: CowWidgetEventListeners;
26
25
  }
27
26
  export interface JsonRpcRequest {
28
27
  id: number;
@@ -258,7 +257,7 @@ export interface CowSwapWidgetParams {
258
257
  }
259
258
  export interface WidgetMethodsEmitPayloadMap {
260
259
  [WidgetMethodsEmit.ACTIVATE]: void;
261
- [WidgetMethodsEmit.EMIT_COW_EVENT]: EmitCowEventPayload<CowEvents>;
260
+ [WidgetMethodsEmit.EMIT_COW_EVENT]: EmitCowEventPayload<CowWidgetEvents>;
262
261
  [WidgetMethodsEmit.UPDATE_HEIGHT]: UpdateWidgetHeightPayload;
263
262
  [WidgetMethodsEmit.SET_FULL_HEIGHT]: SetWidgetFullHeightPayload;
264
263
  [WidgetMethodsEmit.PROVIDER_RPC_REQUEST]: ProviderRpcRequestPayload;
@@ -270,6 +269,7 @@ export interface WidgetMethodsListenPayloadMap {
270
269
  [WidgetMethodsListen.PROVIDER_RPC_RESPONSE]: ProviderRpcResponsePayload;
271
270
  [WidgetMethodsListen.PROVIDER_ON_EVENT]: ProviderOnEventPayload;
272
271
  }
272
+ export type WidgetEventsPayloadMap = WidgetMethodsEmitPayloadMap & WidgetMethodsListenPayloadMap;
273
273
  export type WidgetMethodsEmitPayloads = WidgetMethodsEmitPayloadMap[WidgetMethodsEmit];
274
274
  export type WidgetMethodsListenPayloads = WidgetMethodsListenPayloadMap[WidgetMethodsListen];
275
275
  export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme'>;
@@ -292,9 +292,9 @@ export interface UpdateWidgetHeightPayload {
292
292
  export interface SetWidgetFullHeightPayload {
293
293
  isUpToSmall?: boolean;
294
294
  }
295
- export interface EmitCowEventPayload<T extends CowEvents> {
295
+ export interface EmitCowEventPayload<T extends CowWidgetEvents> {
296
296
  event: T;
297
- payload: CowEventPayloadMap[T];
297
+ payload: CowWidgetEventPayloadMap[T];
298
298
  }
299
299
  export type WidgetMethodsEmitListener<T extends WidgetMethodsEmit> = T extends WidgetMethodsEmit ? {
300
300
  event: T;
@@ -338,3 +338,4 @@ export interface ProviderOnEventPayload {
338
338
  event: string;
339
339
  params: unknown;
340
340
  }
341
+ export type WindowListener = (event: MessageEvent<unknown>) => void;
package/urlUtils.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { CowSwapWidgetParams } from './types';
2
-
3
2
  export declare function buildWidgetUrl(params: Partial<CowSwapWidgetParams>): string;
4
3
  export declare function buildWidgetPath(params: Partial<CowSwapWidgetParams>): string;
5
4
  export declare function buildWidgetUrlQuery(params: Partial<CowSwapWidgetParams>): URLSearchParams;
@@ -0,0 +1,3 @@
1
+ import { IframeTransport } from '@cowprotocol/iframe-transport';
2
+ import { WidgetEventsPayloadMap } from './types';
3
+ export declare const widgetIframeTransport: IframeTransport<WidgetEventsPayloadMap>;
@@ -1,45 +0,0 @@
1
- import { EthereumProvider, JsonRpcRequestMessage } from './types';
2
-
3
- /**
4
- * Handles JSON-RPC request comming from an iFrame by delegating to a given Ethereum provider.
5
- * The result will be passed back to the iFrame.
6
- *
7
- * Additionally, it will forward some special events from the wallet, to the iFrame window, for example connect/disconnect/chainChanged
8
- */
9
- export declare class IframeRpcProviderBridge {
10
- private iframeWidow;
11
- /**
12
- * The Ethereum provider instance.
13
- * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
14
- * */
15
- private ethereumProvider;
16
- /** Stored JSON-RPC requests, to queue them when disconnected. */
17
- private requestWaitingForConnection;
18
- /**
19
- * Creates an instance of IframeRpcProviderBridge.
20
- * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
21
- * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
22
- */
23
- constructor(iframeWidow: Window);
24
- /**
25
- * Disconnects the JSON-RPC bridge from the Ethereum provider.
26
- */
27
- disconnect(): void;
28
- /**
29
- * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
30
- * @param newProvider - The Ethereum provider to connect.
31
- */
32
- onConnect(newProvider: EthereumProvider): void;
33
- private processPendingRequests;
34
- /**
35
- * Processes a JSON-RPC request and sends appropriate response or error via the content window.
36
- * @param request - The JSON-RPC request to be processed.
37
- */
38
- processRpcRequest(request: JsonRpcRequestMessage): void;
39
- private processRpcCallFromWindow;
40
- private onProviderEvent;
41
- /**
42
- * Forward a JSON-RPC message to the content window.
43
- */
44
- private forwardRpcResponseToIframe;
45
- }
package/messages.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import { WidgetMethodsEmit, WidgetMethodsEmitPayloadMap, WidgetMethodsListen, WidgetMethodsListenPayloadMap } from './types';
2
-
3
- export declare function postMessageToWindow<T extends WidgetMethodsEmit>(contentWindow: Window, method: T, payload: WidgetMethodsEmitPayloadMap[T]): void;
4
- export declare function postMessageToWindow<T extends WidgetMethodsListen>(contentWindow: Window, method: T, payload: WidgetMethodsListenPayloadMap[T]): void;
5
- export type WindowListener = (event: MessageEvent<unknown>) => void;
6
- export declare function listenToMessageFromWindow<T extends WidgetMethodsListen>(contentWindow: Window, method: T, callback: (payload: WidgetMethodsListenPayloadMap[T]) => void): WindowListener;
7
- export declare function listenToMessageFromWindow<T extends WidgetMethodsEmit>(contentWindow: Window, method: T, callback: (payload: WidgetMethodsEmitPayloadMap[T]) => void): WindowListener;
8
- export declare function stopListeningToMessageFromWindow<T extends WidgetMethodsListen>(contentWindow: Window, method: T, callback: (payload: WidgetMethodsListenPayloadMap[T]) => void): void;
9
- export declare function stopListeningToMessageFromWindow<T extends WidgetMethodsEmit>(contentWindow: Window, method: T, callback: (payload: WidgetMethodsEmitPayloadMap[T]) => void): void;
10
- export declare function stopListeningWindowListener(contentWindow: Window, callback: WindowListener): void;