@cowprotocol/widget-lib 4.1.0 → 4.2.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.
package/index.cjs CHANGED
@@ -1 +1,53 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("@cowprotocol/iframe-transport"),$=require("@cowprotocol/events"),x=new Set(["wc:","metamask:","imtokenv2:","trustassetapp:","okex:","ledgerlive:","rainbow:","argent:","exodus:","zerion:","okxwallet:","uniswap:","robinhood-wallet:","krakenwallet:","bitpay:","oneinch:","safe:","backpack:","tangem:","mathwallet:","keplrwallet:","coin98:","tpoutside:","bncus:","bnc:"]),j=new Set(["http:","https:"]);function K(e){try{const t=new URL(e).protocol;return j.has(t)||x.has(t)}catch{return!1}}const v="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",U="strict-origin-when-cross-origin",b="clipboard-read; clipboard-write";var c=(e=>(e.ACTIVATE="ACTIVATE",e.READY="READY",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.PROCESS_HOOK="PROCESS_HOOK",e))(c||{}),T=(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.HOOK_RESULT="HOOK_RESULT",e))(T||{}),E=(e=>(e.ON_BEFORE_APPROVAL="ON_BEFORE_APPROVAL",e.ON_BEFORE_TRADE="ON_BEFORE_TRADE",e.ON_BEFORE_WRAP_UNWRAP="ON_BEFORE_WRAP_UNWRAP",e.ON_BEFORE_ORDER_CANCEL="ON_BEFORE_ORDER_CANCEL",e.ON_BEFORE_ORDERS_CANCEL="ON_BEFORE_ORDERS_CANCEL",e))(E||{}),g=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(g||{});const Q=["primary","background","paper","text","danger","warning","alert","info","success"],a=new N.IframeTransport("cowSwapWidget");class Y{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=a.listenToMessageFromWindow(this.contentWindow,o,c.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new $.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){a.stopListeningWindowListener(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)}}class X{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=o=>{z(o.data)&&(typeof window<"u"&&o.origin===window.location.origin||(J(o.data)?this.appWindow.parent.postMessage(o.data,"*"):Z(o.data)&&this.iframeWidow.postMessage(o.data,"*")))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function z(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function J(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 Z(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function q(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function ee(...e){process.env.NODE_ENV!=="test"&&q("Widget","#47aba8",...e)}const F="https://swap.cow.fi";function H(e){return!!(e&&typeof e=="object")}const C="_",te="CoW Swap widget: invalid baseUrl.",y=!1;function ne(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function P(e,t){const n=`${te} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),F}function B(e,t=y){const n=typeof e=="string"?e.trim():"";if(!n)return F;let o;try{o=new URL(n)}catch{return P(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return P("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&ne(o.hostname);if(!r&&!i)return P(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const w=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${w}`}function oe(e){const t=B(e.baseUrl),n=k(e);return t+"/#"+n+"?"+M(e)}function k(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=g.SWAP}=e,i=[n?.asset||C,o?.asset||C].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function M(e){const t=new URLSearchParams;return de(ae(se(ie(re(t,e),e),e),e),e)}function re(e,t){const{sell:n,buy:o}=t;return n?.amount&&e.append("sellAmount",n.amount),o?.amount&&e.append("buyAmount",o.amount),e}function ie(e,t){const n=t.theme;return n?(H(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)}function se(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ae(e,t){return t.locale&&e.append("lng",t.locale),e}function de(e,t){return le(t.hooks)?e.append("hooksEnabled","true"):e.delete("hooksEnabled"),e}function le(e){return!!e&&Object.values(e).some(Boolean)}const V="640px",ce="450px",ue=20,Ee={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function pe(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:w=!0}=t;let _=o,p=n;if(typeof window>"u")return Ee;const l=fe(n),d=we(l);ee("Resolved trusted iframe origin",{iframeOrigin:d});const f=[];e.innerHTML="",e.appendChild(l);const{contentWindow:s}=l;if(!s)throw console.error("Iframe does not contain a window",l),new Error("Iframe does not contain a window!");i&&f.push(Oe(s,d,i)),f.push(_e(s,d,n.appCode)),f.push(...he(l,d,n.height,n.maxHeight));let h=null;function I(){s&&(h&&window.removeEventListener("message",h),!p.disableWindowOpen&&(h=Re(d,s),f.push(h)))}let A=null;function m(){s&&(A&&window.removeEventListener("message",A),A=Le(s,d,p.hooks),f.push(A))}I(),m();const W=new Y(window,d,s,r);let L=S(s,d,null,_);l.addEventListener("load",()=>{D(s,d,p,_)});const G=w?new X(window,s):null;return{iframe:l,updateParams:u=>{p=u,D(s,d,p,_),I(),m()},updateListeners:u=>W.updateListeners(u),updateProvider:u=>{_=u,L=S(s,d,L,u)},destroy:()=>{L.disconnect(),W.stopListeningIframe(),f.forEach(u=>window.removeEventListener("message",u)),G?.stopListening(),e.removeChild(l)}}}function S(e,t,n,o){n&&n.disconnect();const r=n||new N.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function fe(e){const{width:t=ce,height:n=V}=e,o=document.createElement("iframe");return o.src=oe(e),o.width=t,o.height=n,o.style.border="0",o.setAttribute("sandbox",v),o.referrerPolicy=U,o.allow=b,o}function we(e){return new URL(e.src).origin}function D(e,t,n,o){const r=!!o,i=k(n),w=M(n).toString(),{theme:_,hooks:p,...l}=n;a.postMessageToWindow(e,T.UPDATE_PARAMS,{urlParams:{pathname:i,search:w},appParams:l,hasProvider:r},t)}function _e(e,t,n){return a.listenToMessageFromWindow(window,e,c.ACTIVATE,()=>{a.postMessageToWindow(e,T.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function Oe(e,t,n){let o=!1;return a.listenToMessageFromWindow(window,e,c.READY,()=>{o||(o=!0,n())},t)}function Re(e,t){return a.listenToMessageFromWindow(window,t,c.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=Te(n.toString(),e);i&&K(i)&&window.open(i,r,o)},e)}function Te(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}function he(e,t,n=V,o){return e.contentWindow?[a.listenToMessageFromWindow(window,e.contentWindow,c.UPDATE_HEIGHT,r=>{const i=r.height?r.height+ue:void 0;e.style.height=i?`${o?Math.min(i,o):i}px`:n},t),a.listenToMessageFromWindow(window,e.contentWindow,c.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?n:`${o||document.body.offsetHeight}px`},t)]:[]}const Ae={[E.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[E.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[E.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[E.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[E.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function ge(e,t){return Ae[e.event](e.payload,t)}function Le(e,t,n){return a.listenToMessageFromWindow(window,e,c.PROCESS_HOOK,async o=>{let r=!1;try{r=await ge(o,n)}catch{}a.postMessageToWindow(e,T.HOOK_RESULT,{id:o.id,result:r},t)},t)}const Pe=Object.values(g);function Ie(e,t,n){if(O(e)){const o=e[n];return R(o)?o[t]:o}if(R(e)){const o=e[t];return O(o)?o[n]:o}return e}function O(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Pe.includes(t))}const me=/^\d+$/;function R(e){return typeof e!="object"?!1:Object.keys(e).every(t=>me.test(t))}function We(e){return O(e)?Object.values(e).flatMap(t=>R(t)?Object.values(t):[t]):R(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=y;exports.TradeType=g;exports.WIDGET_IFRAME_ALLOW=b;exports.WIDGET_IFRAME_REFERRER_POLICY=U;exports.WIDGET_IFRAME_SANDBOX=v;exports.WIDGET_PALETTE_COLORS=Q;exports.WidgetHookEvents=E;exports.WidgetMethodsEmit=c;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=pe;exports.isCowSwapWidgetPalette=H;exports.isPerNetworkConfig=R;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=Ie;exports.resolveFlexibleConfigValues=We;exports.sanitizeWidgetBaseUrl=B;exports.widgetIframeTransport=a;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("@cowprotocol/iframe-transport"),K=require("@cowprotocol/events"),Q=new Set(["wc:","metamask:","imtokenv2:","trustassetapp:","okex:","ledgerlive:","rainbow:","argent:","exodus:","zerion:","okxwallet:","uniswap:","robinhood-wallet:","krakenwallet:","bitpay:","oneinch:","safe:","backpack:","tangem:","mathwallet:","keplrwallet:","coin98:","tpoutside:","bncus:","bnc:"]),Y=new Set(["http:","https:"]);function z(e){try{const t=new URL(e).protocol;return Y.has(t)||Q.has(t)}catch{return!1}}const U="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",F="strict-origin-when-cross-origin",B="clipboard-read; clipboard-write";var f=(e=>(e.ACTIVATE="ACTIVATE",e.READY="READY",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.PROCESS_HOOK="PROCESS_HOOK",e))(f||{}),g=(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.HOOK_RESULT="HOOK_RESULT",e))(g||{}),_=(e=>(e.ON_BEFORE_APPROVAL="ON_BEFORE_APPROVAL",e.ON_BEFORE_TRADE="ON_BEFORE_TRADE",e.ON_BEFORE_WRAP_UNWRAP="ON_BEFORE_WRAP_UNWRAP",e.ON_BEFORE_ORDER_CANCEL="ON_BEFORE_ORDER_CANCEL",e.ON_BEFORE_ORDERS_CANCEL="ON_BEFORE_ORDERS_CANCEL",e))(_||{}),P=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(P||{});const X=["primary","background","paper","text","danger","warning","alert","info","success"],c=new y.IframeTransport("cowSwapWidget");class J{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=c.listenToMessageFromWindow(this.contentWindow,o,f.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new K.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){c.stopListeningWindowListener(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)}}class Z{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=o=>{q(o.data)&&(typeof window<"u"&&o.origin===window.location.origin||(ee(o.data)?this.appWindow.parent.postMessage(o.data,"*"):te(o.data)&&this.iframeWidow.postMessage(o.data,"*")))},this.startListening()}forwardSdkMessage;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 ee(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 te(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function ne(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function oe(...e){process.env.NODE_ENV!=="test"&&ne("Widget","#47aba8",...e)}const H="https://swap.cow.fi";function k(e){return!!(e&&typeof e=="object")}const v="_",re="CoW Swap widget: invalid baseUrl.",M=!1;function ie(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function C(e,t){const n=`${re} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),H}function x(e,t=M){const n=typeof e=="string"?e.trim():"";if(!n)return H;let o;try{o=new URL(n)}catch{return C(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return C("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&ie(o.hostname);if(!r&&!i)return C(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const u=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${u}`}function se(e){const t=x(e.baseUrl),n=V(e);return t+"/#"+n+"?"+$(e)}function V(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=P.SWAP}=e,i=[n?.asset||v,o?.asset||v].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function $(e){const t=new URLSearchParams;return ue(ce(le(de(ae(t,e),e),e),e),e)}function ae(e,t){const{sell:n,buy:o}=t;return n?.amount&&e.append("sellAmount",n.amount),o?.amount&&e.append("buyAmount",o.amount),e}function de(e,t){const n=t.theme;return n?(k(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)}function le(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ce(e,t){return t.locale&&e.append("lng",t.locale),e}function ue(e,t){return pe(t.hooks)?e.append("hooksEnabled","true"):e.delete("hooksEnabled"),e}function pe(e){return!!e&&Object.values(e).some(Boolean)}const fe=3e4,m="coWWidgetContentReloadButton";function Ee(e,t,n){const o=e.src;let r=!1,i=!1,u;function E(){e.srcdoc=we,t?.()}function p(){clearTimeout(u),u=setTimeout(()=>{r||i||E()},fe)}function s(){r||i||(e.removeAttribute("srcdoc"),e.src=o,p())}function a(){if(r)return;const d=e.contentDocument,T=d?.querySelector(`.${m}`);if(!(!d||!T)&&(T.addEventListener("click",s),n)){const h=d.createElement("style");h.textContent=n,d.head.appendChild(h)}}return e.addEventListener("error",d=>{r||(console.error("Could not load iframe",d),E())}),e.addEventListener("load",a),p(),{cancelWidgetLoading(){r=!0,clearTimeout(u),e.removeEventListener("load",a)},onWidgetReady(){i=!0,clearTimeout(u)}}}const we=`<!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <style>
5
+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; }
6
+ .errorContent {
7
+ display: flex;
8
+ flex-direction: column;
9
+ gap: 16px;
10
+ align-items: center;
11
+ justify-content: center;
12
+ text-align: center;
13
+
14
+ width: 100%;
15
+ height: 100%;
16
+
17
+ padding: 24px;
18
+ box-sizing: border-box;
19
+
20
+ background: #fff5f5;
21
+ color: #d32f2f;
22
+
23
+ border: 1px solid #f5c2c7;
24
+ border-radius: 12px;
25
+
26
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
27
+ font-size: 14px;
28
+ line-height: 1.5;
29
+ font-weight: 500;
30
+ }
31
+ .${m} {
32
+ padding: 8px 24px;
33
+ border: 1px solid #d32f2f;
34
+ border-radius: 8px;
35
+ background: transparent;
36
+ color: #d32f2f;
37
+ font: inherit;
38
+ cursor: pointer;
39
+ }
40
+ .${m}:hover {
41
+ background: #d32f2f;
42
+ color: #fff5f5;
43
+ }
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <div class="errorContent">
48
+ <span>Couldn't load the widget. Please try again later.</span>
49
+
50
+ <button class="${m}">Retry</button>
51
+ </div>
52
+ </body>
53
+ </html>`,G="640px",_e="450px",Oe=20,Re={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function ge(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:u=!0}=t;let E=o,p=n;if(typeof window>"u")return Re;const s=Te(n),a=he(s);oe("Resolved trusted iframe origin",{iframeOrigin:a});const d=[];e.innerHTML="",e.appendChild(s);const{cancelWidgetLoading:T,onWidgetReady:h}=Ee(s,t.onLoadingError,t.loadingErrorStyles),{contentWindow:l}=s;if(!l)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");d.push(Ae(l,a,()=>{i?.(),h()})),d.push(Le(l,a,n.appCode)),d.push(...Ie(s,a,n.height,n.maxHeight));let L=null;function W(){l&&(L&&window.removeEventListener("message",L),!p.disableWindowOpen&&(L=me(a,l),d.push(L)))}let A=null;function S(){l&&(A&&window.removeEventListener("message",A),A=Se(l,a,p.hooks),d.push(A))}W(),S();const D=new J(window,a,l,r);let I=b(l,a,null,E);s.addEventListener("load",()=>{N(l,a,p,E)});const j=u?new Z(window,l):null;return{iframe:s,updateParams:w=>{p=w,N(l,a,p,E),W(),S()},updateListeners:w=>D.updateListeners(w),updateProvider:w=>{E=w,I=b(l,a,I,w)},destroy:()=>{I.disconnect(),D.stopListeningIframe(),d.forEach(w=>window.removeEventListener("message",w)),j?.stopListening(),s&&s.parentNode===e&&e.removeChild(s),T()}}}function b(e,t,n,o){n&&n.disconnect();const r=n||new y.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function Te(e){const{width:t=_e,height:n=G}=e,o=document.createElement("iframe");return o.src=se(e),o.width=t,o.height=n,o.style.border="0",o.setAttribute("sandbox",U),o.referrerPolicy=F,o.allow=B,o}function he(e){return new URL(e.src).origin}function N(e,t,n,o){const r=!!o,i=V(n),u=$(n).toString(),{theme:E,hooks:p,...s}=n;c.postMessageToWindow(e,g.UPDATE_PARAMS,{urlParams:{pathname:i,search:u},appParams:s,hasProvider:r},t)}function Le(e,t,n){return c.listenToMessageFromWindow(window,e,f.ACTIVATE,()=>{c.postMessageToWindow(e,g.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function Ae(e,t,n){let o=!1;return c.listenToMessageFromWindow(window,e,f.READY,()=>{o||(o=!0,n())},t)}function me(e,t){return c.listenToMessageFromWindow(window,t,f.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=Pe(n.toString(),e);i&&z(i)&&window.open(i,r,o)},e)}function Pe(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}function Ie(e,t,n=G,o){return e.contentWindow?[c.listenToMessageFromWindow(window,e.contentWindow,f.UPDATE_HEIGHT,r=>{const i=r.height?r.height+Oe:void 0;e.style.height=i?`${o?Math.min(i,o):i}px`:n},t),c.listenToMessageFromWindow(window,e.contentWindow,f.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?n:`${o||document.body.offsetHeight}px`},t)]:[]}const Ce={[_.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[_.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[_.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[_.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[_.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function We(e,t){return Ce[e.event](e.payload,t)}function Se(e,t,n){return c.listenToMessageFromWindow(window,e,f.PROCESS_HOOK,async o=>{let r=!1;try{r=await We(o,n)}catch{}c.postMessageToWindow(e,g.HOOK_RESULT,{id:o.id,result:r},t)},t)}const De=Object.values(P);function ve(e,t,n){if(O(e)){const o=e[n];return R(o)?o[t]:o}if(R(e)){const o=e[t];return O(o)?o[n]:o}return e}function O(e){return typeof e!="object"?!1:Object.keys(e).every(t=>De.includes(t))}const be=/^\d+$/;function R(e){return typeof e!="object"?!1:Object.keys(e).every(t=>be.test(t))}function Ne(e){return O(e)?Object.values(e).flatMap(t=>R(t)?Object.values(t):[t]):R(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=M;exports.TradeType=P;exports.WIDGET_IFRAME_ALLOW=B;exports.WIDGET_IFRAME_REFERRER_POLICY=F;exports.WIDGET_IFRAME_SANDBOX=U;exports.WIDGET_PALETTE_COLORS=X;exports.WidgetHookEvents=_;exports.WidgetMethodsEmit=f;exports.WidgetMethodsListen=g;exports.createCowSwapWidget=ge;exports.isCowSwapWidgetPalette=k;exports.isPerNetworkConfig=R;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=ve;exports.resolveFlexibleConfigValues=Ne;exports.sanitizeWidgetBaseUrl=x;exports.widgetIframeTransport=c;
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { IframeTransport as y, IframeRpcProviderBridge as B } from "@cowprotocol/iframe-transport";
2
- import { SimpleCowEventEmitter as F } from "@cowprotocol/events";
3
- const k = /* @__PURE__ */ new Set([
1
+ import { IframeTransport as k, IframeRpcProviderBridge as x } from "@cowprotocol/iframe-transport";
2
+ import { SimpleCowEventEmitter as M } from "@cowprotocol/events";
3
+ const V = /* @__PURE__ */ new Set([
4
4
  "wc:",
5
5
  // default Wallet-connect protocol
6
6
  "metamask:",
@@ -27,27 +27,27 @@ const k = /* @__PURE__ */ new Set([
27
27
  "tpoutside:",
28
28
  "bncus:",
29
29
  "bnc:"
30
- ]), M = /* @__PURE__ */ new Set(["http:", "https:"]);
31
- function V(e) {
30
+ ]), $ = /* @__PURE__ */ new Set(["http:", "https:"]);
31
+ function G(e) {
32
32
  try {
33
33
  const t = new URL(e).protocol;
34
- return M.has(t) || k.has(t);
34
+ return $.has(t) || V.has(t);
35
35
  } catch {
36
36
  return !1;
37
37
  }
38
38
  }
39
- const $ = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", x = "strict-origin-when-cross-origin", G = "clipboard-read; clipboard-write";
40
- var u = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.READY = "READY", 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.PROCESS_HOOK = "PROCESS_HOOK", e))(u || {}), A = /* @__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.HOOK_RESULT = "HOOK_RESULT", e))(A || {}), f = /* @__PURE__ */ ((e) => (e.ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL", e.ON_BEFORE_TRADE = "ON_BEFORE_TRADE", e.ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP", e.ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL", e.ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL", e))(f || {}), m = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(m || {});
41
- const Se = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], d = new y("cowSwapWidget");
42
- class j {
39
+ const j = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", K = "strict-origin-when-cross-origin", Q = "clipboard-read; clipboard-write";
40
+ var w = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.READY = "READY", 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.PROCESS_HOOK = "PROCESS_HOOK", e))(w || {}), A = /* @__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.HOOK_RESULT = "HOOK_RESULT", e))(A || {}), _ = /* @__PURE__ */ ((e) => (e.ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL", e.ON_BEFORE_TRADE = "ON_BEFORE_TRADE", e.ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP", e.ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL", e.ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL", e))(_ || {}), I = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(I || {});
41
+ const Ne = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], c = new k("cowSwapWidget");
42
+ class Y {
43
43
  constructor(t, n, o, r = []) {
44
- this.contentWindow = t, this.updateListeners(r), this.widgetListener = d.listenToMessageFromWindow(this.contentWindow, o, u.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
44
+ this.contentWindow = t, this.updateListeners(r), this.widgetListener = c.listenToMessageFromWindow(this.contentWindow, o, w.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
45
45
  }
46
- eventEmitter = new F();
46
+ eventEmitter = new M();
47
47
  listeners = [];
48
48
  widgetListener;
49
49
  stopListeningIframe() {
50
- d.stopListeningWindowListener(this.contentWindow, this.widgetListener);
50
+ c.stopListeningWindowListener(this.contentWindow, this.widgetListener);
51
51
  }
52
52
  updateListeners(t) {
53
53
  for (const n of this.listeners)
@@ -57,10 +57,10 @@ class j {
57
57
  this.eventEmitter.on(n);
58
58
  }
59
59
  }
60
- class K {
60
+ class z {
61
61
  constructor(t, n) {
62
62
  this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (o) => {
63
- Q(o.data) && (typeof window < "u" && o.origin === window.location.origin || (Y(o.data) ? this.appWindow.parent.postMessage(o.data, "*") : X(o.data) && this.iframeWidow.postMessage(o.data, "*")));
63
+ X(o.data) && (typeof window < "u" && o.origin === window.location.origin || (J(o.data) ? this.appWindow.parent.postMessage(o.data, "*") : Z(o.data) && this.iframeWidow.postMessage(o.data, "*")));
64
64
  }, this.startListening();
65
65
  }
66
66
  forwardSdkMessage;
@@ -71,94 +71,180 @@ class K {
71
71
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
72
72
  }
73
73
  }
74
- function Q(e) {
74
+ function X(e) {
75
75
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
76
76
  }
77
- function Y(e) {
77
+ function J(e) {
78
78
  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;
79
79
  }
80
- function X(e) {
80
+ function Z(e) {
81
81
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
82
82
  }
83
- function z(e = "Default", t = "#1c5dbf", ...n) {
83
+ function q(e = "Default", t = "#1c5dbf", ...n) {
84
84
  console.debug(`%c [COW][${e}]`, `font-weight: bold; color: ${t}`, ...n);
85
85
  }
86
- function J(...e) {
87
- process.env.NODE_ENV !== "test" && z("Widget", "#47aba8", ...e);
86
+ function ee(...e) {
87
+ process.env.NODE_ENV !== "test" && q("Widget", "#47aba8", ...e);
88
88
  }
89
- const N = "https://swap.cow.fi";
90
- function Z(e) {
89
+ const y = "https://swap.cow.fi";
90
+ function te(e) {
91
91
  return !!(e && typeof e == "object");
92
92
  }
93
- const C = "_", q = "CoW Swap widget: invalid baseUrl.", ee = !1;
94
- function te(e) {
93
+ const v = "_", ne = "CoW Swap widget: invalid baseUrl.", oe = !1;
94
+ function re(e) {
95
95
  return e === "localhost" || e === "127.0.0.1" || e === "::1" || e.endsWith(".localhost");
96
96
  }
97
- function L(e, t) {
98
- const n = `${q} ${e}`;
97
+ function C(e, t) {
98
+ const n = `${ne} ${e}`;
99
99
  if (t)
100
100
  throw new Error(n);
101
- return console.error("[CoW Widget]", n), N;
101
+ return console.error("[CoW Widget]", n), y;
102
102
  }
103
- function ne(e, t = ee) {
103
+ function ie(e, t = oe) {
104
104
  const n = typeof e == "string" ? e.trim() : "";
105
105
  if (!n)
106
- return N;
106
+ return y;
107
107
  let o;
108
108
  try {
109
109
  o = new URL(n);
110
110
  } catch {
111
- return L(`Not a valid URL: ${JSON.stringify(n)}`, t);
111
+ return C(`Not a valid URL: ${JSON.stringify(n)}`, t);
112
112
  }
113
113
  if (o.username || o.password)
114
- return L("Userinfo (username/password) in URL is not allowed.", t);
115
- const r = o.protocol === "https:", i = o.protocol === "http:" && te(o.hostname);
114
+ return C("Userinfo (username/password) in URL is not allowed.", t);
115
+ const r = o.protocol === "https:", i = o.protocol === "http:" && re(o.hostname);
116
116
  if (!r && !i)
117
- return L(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
118
- const w = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
119
- return `${o.origin}${w}`;
117
+ return C(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
118
+ const u = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
119
+ return `${o.origin}${u}`;
120
120
  }
121
- function oe(e) {
122
- const t = ne(e.baseUrl), n = v(e);
123
- return t + "/#" + n + "?" + U(e);
121
+ function se(e) {
122
+ const t = ie(e.baseUrl), n = U(e);
123
+ return t + "/#" + n + "?" + B(e);
124
124
  }
125
- function v(e) {
125
+ function U(e) {
126
126
  const {
127
127
  chainId: t = 1,
128
128
  sell: n,
129
129
  buy: o,
130
- tradeType: r = m.SWAP
131
- } = e, i = [n?.asset || C, o?.asset || C].map(encodeURIComponent).join("/");
130
+ tradeType: r = I.SWAP
131
+ } = e, i = [n?.asset || v, o?.asset || v].map(encodeURIComponent).join("/");
132
132
  return `/${t}/widget/${r}/${i}`;
133
133
  }
134
- function U(e) {
134
+ function B(e) {
135
135
  const t = new URLSearchParams();
136
- return de(ae(se(ie(re(t, e), e), e), e), e);
136
+ return ue(ce(le(de(ae(t, e), e), e), e), e);
137
137
  }
138
- function re(e, t) {
138
+ function ae(e, t) {
139
139
  const {
140
140
  sell: n,
141
141
  buy: o
142
142
  } = t;
143
143
  return n?.amount && e.append("sellAmount", n.amount), o?.amount && e.append("buyAmount", o.amount), e;
144
144
  }
145
- function ie(e, t) {
145
+ function de(e, t) {
146
146
  const n = t.theme;
147
- return n ? (Z(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);
147
+ return n ? (te(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);
148
148
  }
149
- function se(e, t) {
149
+ function le(e, t) {
150
150
  return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
151
151
  }
152
- function ae(e, t) {
152
+ function ce(e, t) {
153
153
  return t.locale && e.append("lng", t.locale), e;
154
154
  }
155
- function de(e, t) {
156
- return le(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
155
+ function ue(e, t) {
156
+ return pe(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
157
157
  }
158
- function le(e) {
158
+ function pe(e) {
159
159
  return !!e && Object.values(e).some(Boolean);
160
160
  }
161
- const b = "640px", ce = "450px", ue = 20, pe = {
161
+ const fe = 3e4, T = "coWWidgetContentReloadButton";
162
+ function Ee(e, t, n) {
163
+ const o = e.src;
164
+ let r = !1, i = !1, u;
165
+ function f() {
166
+ e.srcdoc = we, t?.();
167
+ }
168
+ function p() {
169
+ clearTimeout(u), u = setTimeout(() => {
170
+ r || i || f();
171
+ }, fe);
172
+ }
173
+ function s() {
174
+ r || i || (e.removeAttribute("srcdoc"), e.src = o, p());
175
+ }
176
+ function a() {
177
+ if (r) return;
178
+ const d = e.contentDocument, O = d?.querySelector(`.${T}`);
179
+ if (!(!d || !O) && (O.addEventListener("click", s), n)) {
180
+ const R = d.createElement("style");
181
+ R.textContent = n, d.head.appendChild(R);
182
+ }
183
+ }
184
+ return e.addEventListener("error", (d) => {
185
+ r || (console.error("Could not load iframe", d), f());
186
+ }), e.addEventListener("load", a), p(), {
187
+ cancelWidgetLoading() {
188
+ r = !0, clearTimeout(u), e.removeEventListener("load", a);
189
+ },
190
+ onWidgetReady() {
191
+ i = !0, clearTimeout(u);
192
+ }
193
+ };
194
+ }
195
+ const we = `<!DOCTYPE html>
196
+ <html lang="en">
197
+ <head>
198
+ <style>
199
+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; }
200
+ .errorContent {
201
+ display: flex;
202
+ flex-direction: column;
203
+ gap: 16px;
204
+ align-items: center;
205
+ justify-content: center;
206
+ text-align: center;
207
+
208
+ width: 100%;
209
+ height: 100%;
210
+
211
+ padding: 24px;
212
+ box-sizing: border-box;
213
+
214
+ background: #fff5f5;
215
+ color: #d32f2f;
216
+
217
+ border: 1px solid #f5c2c7;
218
+ border-radius: 12px;
219
+
220
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
221
+ font-size: 14px;
222
+ line-height: 1.5;
223
+ font-weight: 500;
224
+ }
225
+ .${T} {
226
+ padding: 8px 24px;
227
+ border: 1px solid #d32f2f;
228
+ border-radius: 8px;
229
+ background: transparent;
230
+ color: #d32f2f;
231
+ font: inherit;
232
+ cursor: pointer;
233
+ }
234
+ .${T}:hover {
235
+ background: #d32f2f;
236
+ color: #fff5f5;
237
+ }
238
+ </style>
239
+ </head>
240
+ <body>
241
+ <div class="errorContent">
242
+ <span>Couldn't load the widget. Please try again later.</span>
243
+
244
+ <button class="${T}">Retry</button>
245
+ </div>
246
+ </body>
247
+ </html>`, F = "640px", _e = "450px", Oe = 20, Re = {
162
248
  iframe: null,
163
249
  updateParams: () => {
164
250
  },
@@ -169,113 +255,118 @@ const b = "640px", ce = "450px", ue = 20, pe = {
169
255
  destroy: () => {
170
256
  }
171
257
  };
172
- function Ce(e, t) {
258
+ function ye(e, t) {
173
259
  const {
174
260
  params: n,
175
261
  provider: o,
176
262
  listeners: r,
177
263
  onReady: i,
178
- enableSafeSdkBridge: w = !0
264
+ enableSafeSdkBridge: u = !0
179
265
  } = t;
180
- let _ = o, p = n;
181
- if (typeof window > "u") return pe;
182
- const l = Ee(n), a = fe(l);
183
- J("Resolved trusted iframe origin", {
266
+ let f = o, p = n;
267
+ if (typeof window > "u") return Re;
268
+ const s = he(n), a = ge(s);
269
+ ee("Resolved trusted iframe origin", {
184
270
  iframeOrigin: a
185
271
  });
186
- const E = [];
187
- e.innerHTML = "", e.appendChild(l);
272
+ const d = [];
273
+ e.innerHTML = "", e.appendChild(s);
188
274
  const {
189
- contentWindow: s
190
- } = l;
191
- if (!s)
192
- throw console.error("Iframe does not contain a window", l), new Error("Iframe does not contain a window!");
193
- i && E.push(_e(s, a, i)), E.push(we(s, a, n.appCode)), E.push(...Te(l, a, n.height, n.maxHeight));
194
- let O = null;
195
- function g() {
196
- s && (O && window.removeEventListener("message", O), !p.disableWindowOpen && (O = Oe(a, s), E.push(O)));
275
+ cancelWidgetLoading: O,
276
+ onWidgetReady: R
277
+ } = Ee(s, t.onLoadingError, t.loadingErrorStyles), {
278
+ contentWindow: l
279
+ } = s;
280
+ if (!l)
281
+ throw console.error("Iframe does not contain a window", s), new Error("Iframe does not contain a window!");
282
+ d.push(me(l, a, () => {
283
+ i?.(), R();
284
+ })), d.push(Te(l, a, n.appCode)), d.push(...Pe(s, a, n.height, n.maxHeight));
285
+ let h = null;
286
+ function S() {
287
+ l && (h && window.removeEventListener("message", h), !p.disableWindowOpen && (h = Le(a, l), d.push(h)));
197
288
  }
198
- let R = null;
199
- function I() {
200
- s && (R && window.removeEventListener("message", R), R = Pe(s, a, p.hooks), E.push(R));
289
+ let g = null;
290
+ function W() {
291
+ l && (g && window.removeEventListener("message", g), g = Se(l, a, p.hooks), d.push(g));
201
292
  }
202
- g(), I();
203
- const S = new j(window, a, s, r);
204
- let P = W(s, a, null, _);
205
- l.addEventListener("load", () => {
206
- D(s, a, p, _);
293
+ S(), W();
294
+ const D = new Y(window, a, l, r);
295
+ let P = b(l, a, null, f);
296
+ s.addEventListener("load", () => {
297
+ N(l, a, p, f);
207
298
  });
208
- const H = w ? new K(window, s) : null;
299
+ const H = u ? new z(window, l) : null;
209
300
  return {
210
- iframe: l,
211
- updateParams: (c) => {
212
- p = c, D(s, a, p, _), g(), I();
301
+ iframe: s,
302
+ updateParams: (E) => {
303
+ p = E, N(l, a, p, f), S(), W();
213
304
  },
214
- updateListeners: (c) => S.updateListeners(c),
215
- updateProvider: (c) => {
216
- _ = c, P = W(s, a, P, c);
305
+ updateListeners: (E) => D.updateListeners(E),
306
+ updateProvider: (E) => {
307
+ f = E, P = b(l, a, P, E);
217
308
  },
218
309
  destroy: () => {
219
- P.disconnect(), S.stopListeningIframe(), E.forEach((c) => window.removeEventListener("message", c)), H?.stopListening(), e.removeChild(l);
310
+ P.disconnect(), D.stopListeningIframe(), d.forEach((E) => window.removeEventListener("message", E)), H?.stopListening(), s && s.parentNode === e && e.removeChild(s), O();
220
311
  }
221
312
  };
222
313
  }
223
- function W(e, t, n, o) {
314
+ function b(e, t, n, o) {
224
315
  n && n.disconnect();
225
- const r = n || new B(e, t);
316
+ const r = n || new x(e, t);
226
317
  return o && r.onConnect(o), r;
227
318
  }
228
- function Ee(e) {
319
+ function he(e) {
229
320
  const {
230
- width: t = ce,
231
- height: n = b
321
+ width: t = _e,
322
+ height: n = F
232
323
  } = e, o = document.createElement("iframe");
233
- return o.src = oe(e), o.width = t, o.height = n, o.style.border = "0", o.setAttribute("sandbox", $), o.referrerPolicy = x, o.allow = G, o;
324
+ return o.src = se(e), o.width = t, o.height = n, o.style.border = "0", o.setAttribute("sandbox", j), o.referrerPolicy = K, o.allow = Q, o;
234
325
  }
235
- function fe(e) {
326
+ function ge(e) {
236
327
  return new URL(e.src).origin;
237
328
  }
238
- function D(e, t, n, o) {
239
- const r = !!o, i = v(n), w = U(n).toString(), {
240
- theme: _,
329
+ function N(e, t, n, o) {
330
+ const r = !!o, i = U(n), u = B(n).toString(), {
331
+ theme: f,
241
332
  hooks: p,
242
- ...l
333
+ ...s
243
334
  } = n;
244
- d.postMessageToWindow(e, A.UPDATE_PARAMS, {
335
+ c.postMessageToWindow(e, A.UPDATE_PARAMS, {
245
336
  urlParams: {
246
337
  pathname: i,
247
- search: w
338
+ search: u
248
339
  },
249
- appParams: l,
340
+ appParams: s,
250
341
  hasProvider: r
251
342
  }, t);
252
343
  }
253
- function we(e, t, n) {
254
- return d.listenToMessageFromWindow(window, e, u.ACTIVATE, () => {
255
- d.postMessageToWindow(e, A.UPDATE_APP_DATA, {
344
+ function Te(e, t, n) {
345
+ return c.listenToMessageFromWindow(window, e, w.ACTIVATE, () => {
346
+ c.postMessageToWindow(e, A.UPDATE_APP_DATA, {
256
347
  metaData: n ? {
257
348
  appCode: n
258
349
  } : void 0
259
350
  }, t);
260
351
  }, t);
261
352
  }
262
- function _e(e, t, n) {
353
+ function me(e, t, n) {
263
354
  let o = !1;
264
- return d.listenToMessageFromWindow(window, e, u.READY, () => {
355
+ return c.listenToMessageFromWindow(window, e, w.READY, () => {
265
356
  o || (o = !0, n());
266
357
  }, t);
267
358
  }
268
- function Oe(e, t) {
269
- return d.listenToMessageFromWindow(window, t, u.INTERCEPT_WINDOW_OPEN, ({
359
+ function Le(e, t) {
360
+ return c.listenToMessageFromWindow(window, t, w.INTERCEPT_WINDOW_OPEN, ({
270
361
  href: n,
271
362
  rel: o,
272
363
  target: r
273
364
  }) => {
274
- const i = Re(n.toString(), e);
275
- i && V(i) && window.open(i, r, o);
365
+ const i = Ae(n.toString(), e);
366
+ i && G(i) && window.open(i, r, o);
276
367
  }, e);
277
368
  }
278
- function Re(e, t) {
369
+ function Ae(e, t) {
279
370
  const n = e.trim();
280
371
  if (!n)
281
372
  return null;
@@ -285,77 +376,77 @@ function Re(e, t) {
285
376
  return null;
286
377
  }
287
378
  }
288
- function Te(e, t, n = b, o) {
289
- return e.contentWindow ? [d.listenToMessageFromWindow(window, e.contentWindow, u.UPDATE_HEIGHT, (r) => {
290
- const i = r.height ? r.height + ue : void 0;
379
+ function Pe(e, t, n = F, o) {
380
+ return e.contentWindow ? [c.listenToMessageFromWindow(window, e.contentWindow, w.UPDATE_HEIGHT, (r) => {
381
+ const i = r.height ? r.height + Oe : void 0;
291
382
  e.style.height = i ? `${o ? Math.min(i, o) : i}px` : n;
292
- }, t), d.listenToMessageFromWindow(window, e.contentWindow, u.SET_FULL_HEIGHT, ({
383
+ }, t), c.listenToMessageFromWindow(window, e.contentWindow, w.SET_FULL_HEIGHT, ({
293
384
  isUpToSmall: r
294
385
  }) => {
295
386
  e.style.height = r ? n : `${o || document.body.offsetHeight}px`;
296
387
  }, t)] : [];
297
388
  }
298
- const he = {
299
- [f.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
300
- [f.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
301
- [f.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
302
- [f.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
303
- [f.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
389
+ const Ce = {
390
+ [_.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
391
+ [_.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
392
+ [_.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
393
+ [_.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
394
+ [_.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
304
395
  };
305
- function Ae(e, t) {
306
- return he[e.event](e.payload, t);
396
+ function Ie(e, t) {
397
+ return Ce[e.event](e.payload, t);
307
398
  }
308
- function Pe(e, t, n) {
309
- return d.listenToMessageFromWindow(window, e, u.PROCESS_HOOK, async (o) => {
399
+ function Se(e, t, n) {
400
+ return c.listenToMessageFromWindow(window, e, w.PROCESS_HOOK, async (o) => {
310
401
  let r = !1;
311
402
  try {
312
- r = await Ae(o, n);
403
+ r = await Ie(o, n);
313
404
  } catch {
314
405
  }
315
- d.postMessageToWindow(e, A.HOOK_RESULT, {
406
+ c.postMessageToWindow(e, A.HOOK_RESULT, {
316
407
  id: o.id,
317
408
  result: r
318
409
  }, t);
319
410
  }, t);
320
411
  }
321
- const Le = Object.values(m);
322
- function We(e, t, n) {
323
- if (T(e)) {
412
+ const We = Object.values(I);
413
+ function Ue(e, t, n) {
414
+ if (m(e)) {
324
415
  const o = e[n];
325
- return h(o) ? o[t] : o;
416
+ return L(o) ? o[t] : o;
326
417
  }
327
- if (h(e)) {
418
+ if (L(e)) {
328
419
  const o = e[t];
329
- return T(o) ? o[n] : o;
420
+ return m(o) ? o[n] : o;
330
421
  }
331
422
  return e;
332
423
  }
333
- function T(e) {
334
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => Le.includes(t));
424
+ function m(e) {
425
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => We.includes(t));
335
426
  }
336
- const me = /^\d+$/;
337
- function h(e) {
338
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => me.test(t));
427
+ const De = /^\d+$/;
428
+ function L(e) {
429
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => De.test(t));
339
430
  }
340
- function De(e) {
341
- return T(e) ? Object.values(e).flatMap((t) => h(t) ? Object.values(t) : [t]) : h(e) ? Object.values(e).flatMap((t) => T(t) ? Object.values(t) : [t]) : [e];
431
+ function Be(e) {
432
+ return m(e) ? Object.values(e).flatMap((t) => L(t) ? Object.values(t) : [t]) : L(e) ? Object.values(e).flatMap((t) => m(t) ? Object.values(t) : [t]) : [e];
342
433
  }
343
434
  export {
344
- ee as SHOULD_THROW_IF_INVALID_URL,
345
- m as TradeType,
346
- G as WIDGET_IFRAME_ALLOW,
347
- x as WIDGET_IFRAME_REFERRER_POLICY,
348
- $ as WIDGET_IFRAME_SANDBOX,
349
- Se as WIDGET_PALETTE_COLORS,
350
- f as WidgetHookEvents,
351
- u as WidgetMethodsEmit,
435
+ oe as SHOULD_THROW_IF_INVALID_URL,
436
+ I as TradeType,
437
+ Q as WIDGET_IFRAME_ALLOW,
438
+ K as WIDGET_IFRAME_REFERRER_POLICY,
439
+ j as WIDGET_IFRAME_SANDBOX,
440
+ Ne as WIDGET_PALETTE_COLORS,
441
+ _ as WidgetHookEvents,
442
+ w as WidgetMethodsEmit,
352
443
  A as WidgetMethodsListen,
353
- Ce as createCowSwapWidget,
354
- Z as isCowSwapWidgetPalette,
355
- h as isPerNetworkConfig,
356
- T as isPerTradeTypeConfig,
357
- We as resolveFlexibleConfig,
358
- De as resolveFlexibleConfigValues,
359
- ne as sanitizeWidgetBaseUrl,
360
- d as widgetIframeTransport
444
+ ye as createCowSwapWidget,
445
+ te as isCowSwapWidgetPalette,
446
+ L as isPerNetworkConfig,
447
+ m as isPerTradeTypeConfig,
448
+ Ue as resolveFlexibleConfig,
449
+ Be as resolveFlexibleConfigValues,
450
+ ie as sanitizeWidgetBaseUrl,
451
+ c as widgetIframeTransport
361
452
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
4
4
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your website.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@cowprotocol/cow-sdk": "9.1.2",
19
- "@cowprotocol/events": "^4.5.0",
19
+ "@cowprotocol/events": "^4.6.0",
20
20
  "@cowprotocol/iframe-transport": "^2.3.0"
21
21
  },
22
22
  "exports": {
package/types.d.ts CHANGED
@@ -75,6 +75,12 @@ export interface CowSwapWidgetProps {
75
75
  provider?: EthereumProvider;
76
76
  listeners?: CowWidgetEventListeners;
77
77
  onReady?(): void;
78
+ onLoadingError?(): void;
79
+ /**
80
+ * Custom CSS appended to the error document displayed inside the iframe when the widget fails to load.
81
+ * Use it to override the default look (`.errorContent` and `.reloadButton` classes).
82
+ */
83
+ loadingErrorStyles?: string;
78
84
  enableSafeSdkBridge?: boolean;
79
85
  }
80
86
  export interface JsonRpcRequest {
@@ -305,11 +311,33 @@ export interface CowSwapWidgetParams {
305
311
  * Defaults to false.
306
312
  */
307
313
  disableCrossChainSwap?: boolean;
314
+ /**
315
+ * Disable setting custom recipient for all trading widgets (swap,limit,twap)
316
+ * Important! Cross-chain swaps are based on custom recipient functionality!
317
+ * If you want always having recipient === order owner, then set disableCrossChainSwap=true as well
318
+ */
319
+ disableCustomRecipient?: boolean;
308
320
  /**
309
321
  * Disables adding custom tokens and custom token lists.
310
322
  * Defaults to false.
311
323
  */
312
324
  disableTokenImport?: boolean;
325
+ /**
326
+ * Disables the EIP-2612 permit signing flow. When `true`, the widget will
327
+ * never sign an off-chain permit and will always send an on-chain approval
328
+ * transaction — even for tokens that support permit.
329
+ *
330
+ * Defaults to false.
331
+ */
332
+ disableEIP2612Permits?: boolean;
333
+ /**
334
+ * Disables infinite (MAX_UINT256) ERC-20 approvals. When `true`, every
335
+ * approval transaction approves only the exact trade-size amount, and the
336
+ * "Partial approval" toggle in Settings is shown but locked on.
337
+ *
338
+ * Defaults to false.
339
+ */
340
+ disableInfiniteApprove?: boolean;
313
341
  /**
314
342
  * Disables showing the confirmation modal you get after posting an order.
315
343
  * Defaults to false.
@@ -0,0 +1,6 @@
1
+ type IframeLoadingState = {
2
+ cancelWidgetLoading: () => void;
3
+ onWidgetReady: () => void;
4
+ };
5
+ export declare function widgetIframeLoading(iframe: HTMLIFrameElement, onWidgetLoadingError?: () => void, customErrorStyles?: string): IframeLoadingState;
6
+ export {};