@cowprotocol/widget-lib 4.4.0 → 4.4.1

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,8 +1,12 @@
1
1
  export declare class IframeSafeSdkBridge {
2
2
  private appWindow;
3
- private iframeWidow;
3
+ private iframeWindow;
4
+ private iframeOrigin;
5
+ private parentOrigin;
4
6
  forwardSdkMessage: (event: MessageEvent<unknown>) => void;
5
- constructor(appWindow: Window, iframeWidow: Window);
7
+ constructor(appWindow: Window, iframeWindow: Window, iframeOrigin: string, parentOrigin: string | null);
6
8
  private startListening;
7
9
  stopListening(): void;
10
+ private forwardRequest;
11
+ private forwardResponse;
8
12
  }
package/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("@cowprotocol/iframe-transport"),oe=require("@cowprotocol/events"),re=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:"]),ie=new Set(["http:","https:"]);function se(e){try{const t=new URL(e).protocol;return ie.has(t)||re.has(t)}catch{return!1}}function ae(e,t){if(t){e.removeAttribute("style");for(const n of Object.keys(t)){const o=n,r=t[o];if(r==null||typeof r!="string"&&typeof r!="number")continue;const i=`${r}`;e.style[o]=i}}}const K="cowswap-widget-iframe",le="cowswap-widget",de={appCode:""},Y="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",Q="strict-origin-when-cross-origin",z="clipboard-read; clipboard-write";var w=(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||{}),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.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))(_||{}),L=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(L||{});const ce=["primary","background","paper","text","danger","warning","alert","info","success"],p=new j.IframeTransport("cowSwapWidget");class ue{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=p.listenToMessageFromWindow(this.contentWindow,o,w.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new oe.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){p.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 pe{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=o=>{fe(o.data)&&(typeof window<"u"&&o.origin===window.location.origin||(Ee(o.data)?this.appWindow.parent.postMessage(o.data,"*"):we(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 fe(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 we(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function he(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function _e(...e){process.env.NODE_ENV!=="test"&&he("Widget","#47aba8",...e)}function D(e){return!!(e&&typeof e=="object")}const X="https://swap.cow.fi",x="_",ge="CoW Swap widget: invalid baseUrl.",J=!1;function Re(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function v(e,t){const n=`${ge} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),X}function Z(e,t=J){const n=typeof e=="string"?e.trim():"";if(!n)return X;let o;try{o=new URL(n)}catch{return v(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return v("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&Re(o.hostname);if(!r&&!i)return v(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const f=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${f}`}function me(e){const t=Z(e.baseUrl),n=q(e);return t+"/#"+n+"?"+ee(e)}function q(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=L.SWAP}=e,i=[n?.asset||x,o?.asset||x].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function ee(e){const t=new URLSearchParams;return Ae(ye(Te(Se(Oe(t,e),e),e),e),e)}function Oe(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 Se(e,t){const n=t.theme;return n?(D(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 Te(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ye(e,t){return t.locale&&e.append("lng",t.locale),e}function Ae(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 Ce=3e4,h="cow-widget-loading-error",B=`data-${h}`;function Ie(e,t,n,o,r){const i=t.src;let f=!1,E=null;function c(){r?.(),t.style.display="none",Pe();const l=document.createElement("div"),s=document.createElement("button"),d=document.createElement("p");s.innerText="Reload",s.addEventListener("click",()=>{e.removeChild(l),o(!0),t.src="about:blank",t.style.display="",setTimeout(()=>{t.src=i,n()},100)}),d.innerText="Couldn't load the page. Please, try again later",l.classList.add(h),l.appendChild(d),l.appendChild(s),e.appendChild(l)}return t.addEventListener("error",l=>{f||(console.error("Could not load iframe",l),c())}),E=window.setTimeout(()=>{f||c()},Ce),{onWidgetReady(){E&&clearTimeout(E);const l=document.getElementsByClassName(h)[0];l&&e.removeChild(l)},cancelWidgetLoading(){f=!0}}}let m=null;function Pe(){if(!(typeof document>"u")){if(ve()){m||(m=new CSSStyleSheet,m.replaceSync(k)),document.adoptedStyleSheets.includes(m)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,m]);return}if(!document.head.querySelector(`style[${B}]`)){const e=document.createElement("style");e.setAttribute(B,""),e.textContent=k,document.head.appendChild(e)}}}function ve(){return typeof document<"u"&&"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet=="function"&&typeof CSSStyleSheet.prototype.replaceSync=="function"}const k=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@cowprotocol/iframe-transport"),oe=require("@cowprotocol/events"),re=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:"]),ie=new Set(["http:","https:"]);function se(e){try{const t=new URL(e).protocol;return ie.has(t)||re.has(t)}catch{return!1}}function ae(e,t){if(t){e.removeAttribute("style");for(const n of Object.keys(t)){const o=n,r=t[o];if(r==null||typeof r!="string"&&typeof r!="number")continue;const i=`${r}`;e.style[o]=i}}}const K="cowswap-widget-iframe",de="cowswap-widget",le={appCode:""},Y="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",Q="strict-origin-when-cross-origin",z="clipboard-read; clipboard-write";var w=(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||{}),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||{}),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))(g||{}),L=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(L||{});const ce=["primary","background","paper","text","danger","warning","alert","info","success"],p=new D.IframeTransport("cowSwapWidget");class ue{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=p.listenToMessageFromWindow(this.contentWindow,o,w.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new oe.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){p.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 pe{constructor(t,n,o,r){this.appWindow=t,this.iframeWindow=n,this.iframeOrigin=o,this.parentOrigin=r,this.forwardSdkMessage=i=>{fe(i.data)&&(Ee(i.data)?this.forwardRequest(i,i.data):we(i.data)&&this.forwardResponse(i,i.data))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}forwardRequest(t,n){!this.parentOrigin||this.appWindow.parent===this.appWindow||t.source!==this.iframeWindow||t.origin!==this.iframeOrigin||this.appWindow.parent.postMessage(n,this.parentOrigin)}forwardResponse(t,n){this.appWindow.parent!==this.appWindow&&(t.source!==this.appWindow.parent||t.origin!==this.parentOrigin||this.iframeWindow.postMessage(n,this.iframeOrigin))}}function fe(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 we(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function he(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function ge(...e){process.env.NODE_ENV!=="test"&&he("Widget","#47aba8",...e)}function b(e){return!!(e&&typeof e=="object")}const X="https://swap.cow.fi",B="_",_e="CoW Swap widget: invalid baseUrl.",J=!1;function Re(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function W(e,t){const n=`${_e} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),X}function Z(e,t=J){const n=typeof e=="string"?e.trim():"";if(!n)return X;let o;try{o=new URL(n)}catch{return W(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return W("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&Re(o.hostname);if(!r&&!i)return W(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const f=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${f}`}function me(e){const t=Z(e.baseUrl),n=q(e);return t+"/#"+n+"?"+ee(e)}function q(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=L.SWAP}=e,i=[n?.asset||B,o?.asset||B].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function ee(e){const t=new URLSearchParams;return Ae(ye(Te(Se(Oe(t,e),e),e),e),e)}function Oe(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 Se(e,t){const n=t.theme;return n?(b(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 Te(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ye(e,t){return t.locale&&e.append("lng",t.locale),e}function Ae(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 Ce=3e4,h="cow-widget-loading-error",k=`data-${h}`;function Ie(e,t,n,o,r){const i=t.src;let f=!1,E=null;function c(){r?.(),t.style.display="none",Pe();const l=document.createElement("div"),s=document.createElement("button"),d=document.createElement("p");s.innerText="Reload",s.addEventListener("click",()=>{e.removeChild(l),o(!0),t.src="about:blank",t.style.display="",setTimeout(()=>{t.src=i,n()},100)}),d.innerText="Couldn't load the page. Please, try again later",l.classList.add(h),l.appendChild(d),l.appendChild(s),e.appendChild(l)}return t.addEventListener("error",l=>{f||(console.error("Could not load iframe",l),c())}),E=window.setTimeout(()=>{f||c()},Ce),{onWidgetReady(){E&&clearTimeout(E);const l=document.getElementsByClassName(h)[0];l&&e.removeChild(l)},cancelWidgetLoading(){f=!0}}}let m=null;function Pe(){if(!(typeof document>"u")){if(We()){m||(m=new CSSStyleSheet,m.replaceSync(M)),document.adoptedStyleSheets.includes(m)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,m]);return}if(!document.head.querySelector(`style[${k}]`)){const e=document.createElement("style");e.setAttribute(k,""),e.textContent=M,document.head.appendChild(e)}}}function We(){return typeof document<"u"&&"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet=="function"&&typeof CSSStyleSheet.prototype.replaceSync=="function"}const M=`
2
2
  .${h} {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -41,4 +41,4 @@
41
41
  .${h} button:not(:disabled):hover {
42
42
  background: #d32f2f;
43
43
  color: #fff5f5;
44
- }`,We={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function De(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:f=!0}=t;let E=o,c=M(n),l="";if(typeof window>"u")return We;const s=be(c),d=Ne(s);_e("Resolved trusted iframe origin",{iframeOrigin:d});const y=[];e.innerHTML="",e.appendChild(s),$(e,c);let a=null,C=()=>{},I=()=>{},b=()=>{},P=null,A=null,N=null,U=[],R=null;function H(){if(a=s.contentWindow,!a)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");y.push(He(a,d,()=>{i?.(),te()})),y.push(Ue(a,d,c.appCode)),U=ke(e,s,d,ne=>{l=ne});let u=null;C=()=>{a&&(u&&window.removeEventListener("message",u),!c.disableWindowOpen&&(u=Fe(d,a),y.push(u)))},I=()=>{a&&(R&&window.removeEventListener("message",R),R=$e(a,d,c.hooks))},C(),I(),P=new ue(window,d,a,r),A=V(a,d,null,E),s.addEventListener("load",()=>{a&&G(a,d,c,E)}),N=f?new pe(window,a):null;const g=Ie(e,s,H,F,t.onLoadingError);b=g.cancelWidgetLoading;const te=g.onWidgetReady}function F(u=!1){A?.disconnect(),P?.stopListeningIframe(),U.forEach(g=>window.removeEventListener("message",g)),y.forEach(g=>window.removeEventListener("message",g)),R&&window.removeEventListener("message",R),N?.stopListening(),!u&&s&&s.parentNode===e&&e.removeChild(s),b?.()}return H(),{iframe:s,updateParams:u=>{a&&(c=M(u),$(e,c,l),G(a,d,c,E),C(),I())},updateListeners:u=>P?.updateListeners(u),updateProvider:u=>{a&&(E=u,A=V(a,d,A,u))},destroy:F}}function M(e){const t={...de,...e};if(typeof t.appCode!="string"||t.appCode.trim().length===0)throw new Error("Required param `appCode` is missing");return t}function V(e,t,n,o){n&&n.disconnect();const r=n||new j.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function be(e){const t=document.createElement("iframe");return t.id=K,t.src=me(e),t.setAttribute("sandbox",Y),t.referrerPolicy=Q,t.allow=z,t.style.width="100%",t.style.height="100%",t.style.border="0",t.style.display="block",t}function $(e,t,n){ae(e,t.rootStyle),[{name:"params.width",value:t.width,replacementName:"rootStyle.width",replacementValue:t.rootStyle?.width,applyDeprecated:()=>t.width?e.style.width=t.width:void 0},{name:"params.height",value:t.height,replacementName:"rootStyle.height",replacementValue:t.rootStyle?.height,applyDeprecated:()=>t.height?e.style.height=t.height:void 0},{name:"params.maxHeight",value:t.maxHeight,replacementName:"rootStyle.maxHeight",replacementValue:t.rootStyle?.maxHeight,applyDeprecated:()=>t.maxHeight?e.style.maxHeight=`${t.maxHeight}px`:void 0},{name:"params.theme.boxShadow",value:D(t.theme)?t.theme.boxShadow:void 0,replacementName:"cardStyle.boxShadow",replacementValue:t.cardStyle?.boxShadow,applyDeprecated:()=>{}}].filter(r=>!!r.value).forEach(r=>{r.replacementValue?console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`):(console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`),r.applyDeprecated())}),n&&e.style.setProperty(W,n)}function Ne(e){return new URL(e.src).origin}function G(e,t,n,o){const r=!!o,i=q(n),f=ee(n).toString(),{theme:E,hooks:c,rootStyle:l,...s}=n;p.postMessageToWindow(e,T.UPDATE_PARAMS,{urlParams:{pathname:i,search:f},appParams:s,hasProvider:r},t)}function Ue(e,t,n){return p.listenToMessageFromWindow(window,e,w.ACTIVATE,()=>{p.postMessageToWindow(e,T.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function He(e,t,n){let o=!1;return p.listenToMessageFromWindow(window,e,w.READY,()=>{o||(o=!0,n())},t)}function Fe(e,t){return p.listenToMessageFromWindow(window,t,w.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=xe(n.toString(),e);i&&se(i)&&window.open(i,r,o)},e)}function xe(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}const W="--dynamicHeight",Be=0;function ke(e,t,n,o){return t.contentWindow?[p.listenToMessageFromWindow(window,t.contentWindow,w.UPDATE_HEIGHT,r=>{const i=`${(r?.height??0)+Be}px`;e.style.setProperty(W,i),o(i)},n),p.listenToMessageFromWindow(window,t.contentWindow,w.SET_FULL_HEIGHT,()=>{e.style.setProperty(W,"100dvh"),o("100dvh")},n)]:[]}const Me={[_.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 Ve(e,t){return Me[e.event](e.payload,t)}function $e(e,t,n){return p.listenToMessageFromWindow(window,e,w.PROCESS_HOOK,async o=>{let r=!1;try{r=await Ve(o,n)}catch{}p.postMessageToWindow(e,T.HOOK_RESULT,{id:o.id,result:r},t)},t)}const Ge=Object.values(L);function je(e,t,n){if(O(e)){const o=e[n];return S(o)?o[t]:o}if(S(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=>Ge.includes(t))}const Ke=/^\d+$/;function S(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Ke.test(t))}function Ye(e){return O(e)?Object.values(e).flatMap(t=>S(t)?Object.values(t):[t]):S(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=J;exports.TradeType=L;exports.WIDGET_CONTAINER_ID=le;exports.WIDGET_IFRAME_ALLOW=z;exports.WIDGET_IFRAME_ID=K;exports.WIDGET_IFRAME_REFERRER_POLICY=Q;exports.WIDGET_IFRAME_SANDBOX=Y;exports.WIDGET_PALETTE_COLORS=ce;exports.WidgetHookEvents=_;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=De;exports.isCowSwapWidgetPalette=D;exports.isPerNetworkConfig=S;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=je;exports.resolveFlexibleConfigValues=Ye;exports.sanitizeWidgetBaseUrl=Z;exports.widgetIframeTransport=p;
44
+ }`,ve={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function De(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:f=!0}=t;let E=o,c=V(n),l="";if(typeof window>"u")return ve;const s=Ne(c),d=Ue(s);ge("Resolved trusted iframe origin",{iframeOrigin:d});const y=[];e.innerHTML="",e.appendChild(s),G(e,c);let a=null,C=()=>{},I=()=>{},N=()=>{},P=null,A=null,U=null,H=[],R=null;function F(){if(a=s.contentWindow,!a)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");y.push(Fe(a,d,()=>{i?.(),te()})),y.push(He(a,d,c.appCode)),H=Me(e,s,d,ne=>{l=ne});let u=null;C=()=>{a&&(u&&window.removeEventListener("message",u),!c.disableWindowOpen&&(u=xe(d,a),y.push(u)))},I=()=>{a&&(R&&window.removeEventListener("message",R),R=Ge(a,d,c.hooks))},C(),I(),P=new ue(window,d,a,r),A=$(a,d,null,E),s.addEventListener("load",()=>{a&&j(a,d,c,E)}),U=be(f,window,a,d);const _=Ie(e,s,F,x,t.onLoadingError);N=_.cancelWidgetLoading;const te=_.onWidgetReady}function x(u=!1){A?.disconnect(),P?.stopListeningIframe(),H.forEach(_=>window.removeEventListener("message",_)),y.forEach(_=>window.removeEventListener("message",_)),R&&window.removeEventListener("message",R),U?.stopListening(),!u&&s&&s.parentNode===e&&e.removeChild(s),N?.()}return F(),{iframe:s,updateParams:u=>{a&&(c=V(u),G(e,c,l),j(a,d,c,E),C(),I())},updateListeners:u=>P?.updateListeners(u),updateProvider:u=>{a&&(E=u,A=$(a,d,A,u))},destroy:x}}function be(e,t,n,o){return e?new pe(t,n,o,D.getParentOrigin()||null):null}function V(e){const t={...le,...e};if(typeof t.appCode!="string"||t.appCode.trim().length===0)throw new Error("Required param `appCode` is missing");return t}function $(e,t,n,o){n&&n.disconnect();const r=n||new D.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function Ne(e){const t=document.createElement("iframe");return t.id=K,t.src=me(e),t.setAttribute("sandbox",Y),t.referrerPolicy=Q,t.allow=z,t.style.width="100%",t.style.height="100%",t.style.border="0",t.style.display="block",t}function G(e,t,n){ae(e,t.rootStyle),[{name:"params.width",value:t.width,replacementName:"rootStyle.width",replacementValue:t.rootStyle?.width,applyDeprecated:()=>t.width?e.style.width=t.width:void 0},{name:"params.height",value:t.height,replacementName:"rootStyle.height",replacementValue:t.rootStyle?.height,applyDeprecated:()=>t.height?e.style.height=t.height:void 0},{name:"params.maxHeight",value:t.maxHeight,replacementName:"rootStyle.maxHeight",replacementValue:t.rootStyle?.maxHeight,applyDeprecated:()=>t.maxHeight?e.style.maxHeight=`${t.maxHeight}px`:void 0},{name:"params.theme.boxShadow",value:b(t.theme)?t.theme.boxShadow:void 0,replacementName:"cardStyle.boxShadow",replacementValue:t.cardStyle?.boxShadow,applyDeprecated:()=>{}}].filter(r=>!!r.value).forEach(r=>{r.replacementValue?console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`):(console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`),r.applyDeprecated())}),n&&e.style.setProperty(v,n)}function Ue(e){return new URL(e.src).origin}function j(e,t,n,o){const r=!!o,i=q(n),f=ee(n).toString(),{theme:E,hooks:c,rootStyle:l,...s}=n;p.postMessageToWindow(e,T.UPDATE_PARAMS,{urlParams:{pathname:i,search:f},appParams:s,hasProvider:r},t)}function He(e,t,n){return p.listenToMessageFromWindow(window,e,w.ACTIVATE,()=>{p.postMessageToWindow(e,T.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function Fe(e,t,n){let o=!1;return p.listenToMessageFromWindow(window,e,w.READY,()=>{o||(o=!0,n())},t)}function xe(e,t){return p.listenToMessageFromWindow(window,t,w.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=Be(n.toString(),e);i&&se(i)&&window.open(i,r,o)},e)}function Be(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}const v="--dynamicHeight",ke=0;function Me(e,t,n,o){return t.contentWindow?[p.listenToMessageFromWindow(window,t.contentWindow,w.UPDATE_HEIGHT,r=>{const i=`${(r?.height??0)+ke}px`;e.style.setProperty(v,i),o(i)},n),p.listenToMessageFromWindow(window,t.contentWindow,w.SET_FULL_HEIGHT,()=>{e.style.setProperty(v,"100dvh"),o("100dvh")},n)]:[]}const Ve={[g.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[g.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[g.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[g.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[g.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function $e(e,t){return Ve[e.event](e.payload,t)}function Ge(e,t,n){return p.listenToMessageFromWindow(window,e,w.PROCESS_HOOK,async o=>{let r=!1;try{r=await $e(o,n)}catch{}p.postMessageToWindow(e,T.HOOK_RESULT,{id:o.id,result:r},t)},t)}const je=Object.values(L);function Ke(e,t,n){if(O(e)){const o=e[n];return S(o)?o[t]:o}if(S(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=>je.includes(t))}const Ye=/^\d+$/;function S(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Ye.test(t))}function Qe(e){return O(e)?Object.values(e).flatMap(t=>S(t)?Object.values(t):[t]):S(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=J;exports.TradeType=L;exports.WIDGET_CONTAINER_ID=de;exports.WIDGET_IFRAME_ALLOW=z;exports.WIDGET_IFRAME_ID=K;exports.WIDGET_IFRAME_REFERRER_POLICY=Q;exports.WIDGET_IFRAME_SANDBOX=Y;exports.WIDGET_PALETTE_COLORS=ce;exports.WidgetHookEvents=g;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=De;exports.isCowSwapWidgetPalette=b;exports.isPerNetworkConfig=S;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=Ke;exports.resolveFlexibleConfigValues=Qe;exports.sanitizeWidgetBaseUrl=Z;exports.widgetIframeTransport=p;
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { IframeTransport as X, IframeRpcProviderBridge as J } from "@cowprotocol/iframe-transport";
2
- import { SimpleCowEventEmitter as Z } from "@cowprotocol/events";
3
- const q = /* @__PURE__ */ new Set([
1
+ import { IframeTransport as X, IframeRpcProviderBridge as J, getParentOrigin as Z } from "@cowprotocol/iframe-transport";
2
+ import { SimpleCowEventEmitter as q } from "@cowprotocol/events";
3
+ const ee = /* @__PURE__ */ new Set([
4
4
  "wc:",
5
5
  // default Wallet-connect protocol
6
6
  "metamask:",
@@ -27,16 +27,16 @@ const q = /* @__PURE__ */ new Set([
27
27
  "tpoutside:",
28
28
  "bncus:",
29
29
  "bnc:"
30
- ]), ee = /* @__PURE__ */ new Set(["http:", "https:"]);
31
- function te(e) {
30
+ ]), te = /* @__PURE__ */ new Set(["http:", "https:"]);
31
+ function ne(e) {
32
32
  try {
33
33
  const t = new URL(e).protocol;
34
- return ee.has(t) || q.has(t);
34
+ return te.has(t) || ee.has(t);
35
35
  } catch {
36
36
  return !1;
37
37
  }
38
38
  }
39
- function ne(e, t) {
39
+ function oe(e, t) {
40
40
  if (t) {
41
41
  e.removeAttribute("style");
42
42
  for (const n of Object.keys(t)) {
@@ -48,16 +48,16 @@ function ne(e, t) {
48
48
  }
49
49
  }
50
50
  }
51
- const oe = "cowswap-widget-iframe", Ke = "cowswap-widget", re = {
51
+ const re = "cowswap-widget-iframe", Qe = "cowswap-widget", ie = {
52
52
  appCode: ""
53
- }, ie = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", se = "strict-origin-when-cross-origin", ae = "clipboard-read; clipboard-write";
54
- var h = /* @__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))(h || {}), 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 || {}), g = /* @__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))(g || {}), b = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(b || {});
55
- const Ye = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], p = new X("cowSwapWidget");
56
- class le {
53
+ }, se = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", ae = "strict-origin-when-cross-origin", le = "clipboard-read; clipboard-write";
54
+ 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 || {}), m = /* @__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))(m || {}), W = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(W || {});
55
+ const ze = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], p = new X("cowSwapWidget");
56
+ class de {
57
57
  constructor(t, n, o, r = []) {
58
- this.contentWindow = t, this.updateListeners(r), this.widgetListener = p.listenToMessageFromWindow(this.contentWindow, o, h.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
58
+ this.contentWindow = t, this.updateListeners(r), this.widgetListener = p.listenToMessageFromWindow(this.contentWindow, o, w.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
59
59
  }
60
- eventEmitter = new Z();
60
+ eventEmitter = new q();
61
61
  listeners = [];
62
62
  widgetListener;
63
63
  stopListeningIframe() {
@@ -71,10 +71,10 @@ class le {
71
71
  this.eventEmitter.on(n);
72
72
  }
73
73
  }
74
- class de {
75
- constructor(t, n) {
76
- this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (o) => {
77
- ce(o.data) && (typeof window < "u" && o.origin === window.location.origin || (ue(o.data) ? this.appWindow.parent.postMessage(o.data, "*") : pe(o.data) && this.iframeWidow.postMessage(o.data, "*")));
74
+ class ce {
75
+ constructor(t, n, o, r) {
76
+ this.appWindow = t, this.iframeWindow = n, this.iframeOrigin = o, this.parentOrigin = r, this.forwardSdkMessage = (i) => {
77
+ ue(i.data) && (pe(i.data) ? this.forwardRequest(i, i.data) : fe(i.data) && this.forwardResponse(i, i.data));
78
78
  }, this.startListening();
79
79
  }
80
80
  forwardSdkMessage;
@@ -84,26 +84,32 @@ class de {
84
84
  stopListening() {
85
85
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
86
86
  }
87
+ forwardRequest(t, n) {
88
+ !this.parentOrigin || this.appWindow.parent === this.appWindow || t.source !== this.iframeWindow || t.origin !== this.iframeOrigin || this.appWindow.parent.postMessage(n, this.parentOrigin);
89
+ }
90
+ forwardResponse(t, n) {
91
+ this.appWindow.parent !== this.appWindow && (t.source !== this.appWindow.parent || t.origin !== this.parentOrigin || this.iframeWindow.postMessage(n, this.iframeOrigin));
92
+ }
87
93
  }
88
- function ce(e) {
94
+ function ue(e) {
89
95
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
90
96
  }
91
- function ue(e) {
97
+ function pe(e) {
92
98
  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;
93
99
  }
94
- function pe(e) {
100
+ function fe(e) {
95
101
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
96
102
  }
97
- function fe(e = "Default", t = "#1c5dbf", ...n) {
103
+ function Ee(e = "Default", t = "#1c5dbf", ...n) {
98
104
  console.debug(`%c [COW][${e}]`, `font-weight: bold; color: ${t}`, ...n);
99
105
  }
100
- function Ee(...e) {
101
- process.env.NODE_ENV !== "test" && fe("Widget", "#47aba8", ...e);
106
+ function he(...e) {
107
+ process.env.NODE_ENV !== "test" && Ee("Widget", "#47aba8", ...e);
102
108
  }
103
109
  function G(e) {
104
110
  return !!(e && typeof e == "object");
105
111
  }
106
- const j = "https://swap.cow.fi", x = "_", we = "CoW Swap widget: invalid baseUrl.", he = !1;
112
+ const j = "https://swap.cow.fi", x = "_", we = "CoW Swap widget: invalid baseUrl.", ge = !1;
107
113
  function me(e) {
108
114
  return e === "localhost" || e === "127.0.0.1" || e === "::1" || e.endsWith(".localhost");
109
115
  }
@@ -113,7 +119,7 @@ function v(e, t) {
113
119
  throw new Error(n);
114
120
  return console.error("[CoW Widget]", n), j;
115
121
  }
116
- function ge(e, t = he) {
122
+ function _e(e, t = ge) {
117
123
  const n = typeof e == "string" ? e.trim() : "";
118
124
  if (!n)
119
125
  return j;
@@ -131,8 +137,8 @@ function ge(e, t = he) {
131
137
  const f = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
132
138
  return `${o.origin}${f}`;
133
139
  }
134
- function _e(e) {
135
- const t = ge(e.baseUrl), n = K(e);
140
+ function Oe(e) {
141
+ const t = _e(e.baseUrl), n = K(e);
136
142
  return t + "/#" + n + "?" + Y(e);
137
143
  }
138
144
  function K(e) {
@@ -140,13 +146,13 @@ function K(e) {
140
146
  chainId: t = 1,
141
147
  sell: n,
142
148
  buy: o,
143
- tradeType: r = b.SWAP
149
+ tradeType: r = W.SWAP
144
150
  } = e, i = [n?.asset || x, o?.asset || x].map(encodeURIComponent).join("/");
145
151
  return `/${t}/widget/${r}/${i}`;
146
152
  }
147
153
  function Y(e) {
148
154
  const t = new URLSearchParams();
149
- return Te(ye(Se(Oe(Re(t, e), e), e), e), e);
155
+ return Ae(Te(ye(Se(Re(t, e), e), e), e), e);
150
156
  }
151
157
  function Re(e, t) {
152
158
  const {
@@ -155,55 +161,55 @@ function Re(e, t) {
155
161
  } = t;
156
162
  return n?.amount && e.append("sellAmount", n.amount), o?.amount && e.append("buyAmount", o.amount), e;
157
163
  }
158
- function Oe(e, t) {
164
+ function Se(e, t) {
159
165
  const n = t.theme;
160
166
  return n ? (G(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);
161
167
  }
162
- function Se(e, t) {
168
+ function ye(e, t) {
163
169
  return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
164
170
  }
165
- function ye(e, t) {
171
+ function Te(e, t) {
166
172
  return t.locale && e.append("lng", t.locale), e;
167
173
  }
168
- function Te(e, t) {
169
- return Ae(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
174
+ function Ae(e, t) {
175
+ return Le(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
170
176
  }
171
- function Ae(e) {
177
+ function Le(e) {
172
178
  return !!e && Object.values(e).some(Boolean);
173
179
  }
174
- const Le = 3e4, w = "cow-widget-loading-error", B = `data-${w}`;
175
- function Ce(e, t, n, o, r) {
180
+ const Ce = 3e4, h = "cow-widget-loading-error", B = `data-${h}`;
181
+ function Pe(e, t, n, o, r) {
176
182
  const i = t.src;
177
183
  let f = !1, E = null;
178
184
  function c() {
179
- r?.(), t.style.display = "none", Pe();
180
- const l = document.createElement("div"), s = document.createElement("button"), d = document.createElement("p");
185
+ r?.(), t.style.display = "none", ve();
186
+ const d = document.createElement("div"), s = document.createElement("button"), l = document.createElement("p");
181
187
  s.innerText = "Reload", s.addEventListener("click", () => {
182
- e.removeChild(l), o(!0), t.src = "about:blank", t.style.display = "", setTimeout(() => {
188
+ e.removeChild(d), o(!0), t.src = "about:blank", t.style.display = "", setTimeout(() => {
183
189
  t.src = i, n();
184
190
  }, 100);
185
- }), d.innerText = "Couldn't load the page. Please, try again later", l.classList.add(w), l.appendChild(d), l.appendChild(s), e.appendChild(l);
191
+ }), l.innerText = "Couldn't load the page. Please, try again later", d.classList.add(h), d.appendChild(l), d.appendChild(s), e.appendChild(d);
186
192
  }
187
- return t.addEventListener("error", (l) => {
188
- f || (console.error("Could not load iframe", l), c());
193
+ return t.addEventListener("error", (d) => {
194
+ f || (console.error("Could not load iframe", d), c());
189
195
  }), E = window.setTimeout(() => {
190
196
  f || c();
191
- }, Le), {
197
+ }, Ce), {
192
198
  onWidgetReady() {
193
199
  E && clearTimeout(E);
194
- const l = document.getElementsByClassName(w)[0];
195
- l && e.removeChild(l);
200
+ const d = document.getElementsByClassName(h)[0];
201
+ d && e.removeChild(d);
196
202
  },
197
203
  cancelWidgetLoading() {
198
204
  f = !0;
199
205
  }
200
206
  };
201
207
  }
202
- let R = null;
203
- function Pe() {
208
+ let O = null;
209
+ function ve() {
204
210
  if (!(typeof document > "u")) {
205
- if (ve()) {
206
- R || (R = new CSSStyleSheet(), R.replaceSync(k)), document.adoptedStyleSheets.includes(R) || (document.adoptedStyleSheets = [...document.adoptedStyleSheets, R]);
211
+ if (Ie()) {
212
+ O || (O = new CSSStyleSheet(), O.replaceSync(k)), document.adoptedStyleSheets.includes(O) || (document.adoptedStyleSheets = [...document.adoptedStyleSheets, O]);
207
213
  return;
208
214
  }
209
215
  if (!document.head.querySelector(`style[${B}]`)) {
@@ -212,11 +218,11 @@ function Pe() {
212
218
  }
213
219
  }
214
220
  }
215
- function ve() {
221
+ function Ie() {
216
222
  return typeof document < "u" && "adoptedStyleSheets" in Document.prototype && typeof CSSStyleSheet == "function" && typeof CSSStyleSheet.prototype.replaceSync == "function";
217
223
  }
218
224
  const k = `
219
- .${w} {
225
+ .${h} {
220
226
  display: flex;
221
227
  flex-direction: column;
222
228
  gap: 16px;
@@ -236,11 +242,11 @@ const k = `
236
242
  font-weight: 500;
237
243
  }
238
244
 
239
- .${w} p {
245
+ .${h} p {
240
246
  margin: 0;
241
247
  }
242
248
 
243
- .${w} button {
249
+ .${h} button {
244
250
  padding: 8px 24px;
245
251
  border-radius: 8px;
246
252
  font: inherit;
@@ -250,15 +256,15 @@ const k = `
250
256
  color: #d32f2f;
251
257
  }
252
258
 
253
- .${w} button:disabled {
259
+ .${h} button:disabled {
254
260
  cursor: progress;
255
261
  opacity: 0.75;
256
262
  }
257
263
 
258
- .${w} button:not(:disabled):hover {
264
+ .${h} button:not(:disabled):hover {
259
265
  background: #d32f2f;
260
266
  color: #fff5f5;
261
- }`, Ie = {
267
+ }`, We = {
262
268
  iframe: null,
263
269
  updateParams: () => {
264
270
  },
@@ -269,7 +275,7 @@ const k = `
269
275
  destroy: () => {
270
276
  }
271
277
  };
272
- function Qe(e, t) {
278
+ function Xe(e, t) {
273
279
  const {
274
280
  params: n,
275
281
  provider: o,
@@ -277,56 +283,59 @@ function Qe(e, t) {
277
283
  onReady: i,
278
284
  enableSafeSdkBridge: f = !0
279
285
  } = t;
280
- let E = o, c = F(n), l = "";
281
- if (typeof window > "u") return Ie;
282
- const s = be(c), d = De(s);
283
- Ee("Resolved trusted iframe origin", {
284
- iframeOrigin: d
286
+ let E = o, c = F(n), d = "";
287
+ if (typeof window > "u") return We;
288
+ const s = De(c), l = Ne(s);
289
+ he("Resolved trusted iframe origin", {
290
+ iframeOrigin: l
285
291
  });
286
- const O = [];
292
+ const R = [];
287
293
  e.innerHTML = "", e.appendChild(s), M(e, c);
288
294
  let a = null, L = () => {
289
295
  }, C = () => {
290
- }, D = () => {
291
- }, P = null, S = null, N = null, W = [], _ = null;
296
+ }, b = () => {
297
+ }, P = null, S = null, D = null, N = [], _ = null;
292
298
  function U() {
293
299
  if (a = s.contentWindow, !a)
294
300
  throw console.error("Iframe does not contain a window", s), new Error("Iframe does not contain a window!");
295
- O.push(We(a, d, () => {
301
+ R.push(He(a, l, () => {
296
302
  i?.(), Q();
297
- })), O.push(Ne(a, d, c.appCode)), W = Be(e, s, d, (z) => {
298
- l = z;
303
+ })), R.push(Ue(a, l, c.appCode)), N = Fe(e, s, l, (z) => {
304
+ d = z;
299
305
  });
300
306
  let u = null;
301
307
  L = () => {
302
- a && (u && window.removeEventListener("message", u), !c.disableWindowOpen && (u = Ue(d, a), O.push(u)));
308
+ a && (u && window.removeEventListener("message", u), !c.disableWindowOpen && (u = xe(l, a), R.push(u)));
303
309
  }, C = () => {
304
- a && (_ && window.removeEventListener("message", _), _ = Ve(a, d, c.hooks));
305
- }, L(), C(), P = new le(window, d, a, r), S = V(a, d, null, E), s.addEventListener("load", () => {
306
- a && $(a, d, c, E);
307
- }), N = f ? new de(window, a) : null;
308
- const m = Ce(e, s, U, H, t.onLoadingError);
309
- D = m.cancelWidgetLoading;
310
- const Q = m.onWidgetReady;
310
+ a && (_ && window.removeEventListener("message", _), _ = $e(a, l, c.hooks));
311
+ }, L(), C(), P = new de(window, l, a, r), S = V(a, l, null, E), s.addEventListener("load", () => {
312
+ a && $(a, l, c, E);
313
+ }), D = be(f, window, a, l);
314
+ const g = Pe(e, s, U, H, t.onLoadingError);
315
+ b = g.cancelWidgetLoading;
316
+ const Q = g.onWidgetReady;
311
317
  }
312
318
  function H(u = !1) {
313
- S?.disconnect(), P?.stopListeningIframe(), W.forEach((m) => window.removeEventListener("message", m)), O.forEach((m) => window.removeEventListener("message", m)), _ && window.removeEventListener("message", _), N?.stopListening(), !u && s && s.parentNode === e && e.removeChild(s), D?.();
319
+ S?.disconnect(), P?.stopListeningIframe(), N.forEach((g) => window.removeEventListener("message", g)), R.forEach((g) => window.removeEventListener("message", g)), _ && window.removeEventListener("message", _), D?.stopListening(), !u && s && s.parentNode === e && e.removeChild(s), b?.();
314
320
  }
315
321
  return U(), {
316
322
  iframe: s,
317
323
  updateParams: (u) => {
318
- a && (c = F(u), M(e, c, l), $(a, d, c, E), L(), C());
324
+ a && (c = F(u), M(e, c, d), $(a, l, c, E), L(), C());
319
325
  },
320
326
  updateListeners: (u) => P?.updateListeners(u),
321
327
  updateProvider: (u) => {
322
- a && (E = u, S = V(a, d, S, u));
328
+ a && (E = u, S = V(a, l, S, u));
323
329
  },
324
330
  destroy: H
325
331
  };
326
332
  }
333
+ function be(e, t, n, o) {
334
+ return e ? new ce(t, n, o, Z() || null) : null;
335
+ }
327
336
  function F(e) {
328
337
  const t = {
329
- ...re,
338
+ ...ie,
330
339
  ...e
331
340
  };
332
341
  if (typeof t.appCode != "string" || t.appCode.trim().length === 0)
@@ -338,12 +347,12 @@ function V(e, t, n, o) {
338
347
  const r = n || new J(e, t);
339
348
  return o && r.onConnect(o), r;
340
349
  }
341
- function be(e) {
350
+ function De(e) {
342
351
  const t = document.createElement("iframe");
343
- return t.id = oe, t.src = _e(e), t.setAttribute("sandbox", ie), t.referrerPolicy = se, t.allow = ae, t.style.width = "100%", t.style.height = "100%", t.style.border = "0", t.style.display = "block", t;
352
+ return t.id = re, t.src = Oe(e), t.setAttribute("sandbox", se), t.referrerPolicy = ae, t.allow = le, t.style.width = "100%", t.style.height = "100%", t.style.border = "0", t.style.display = "block", t;
344
353
  }
345
354
  function M(e, t, n) {
346
- ne(e, t.rootStyle), [{
355
+ oe(e, t.rootStyle), [{
347
356
  name: "params.width",
348
357
  value: t.width,
349
358
  replacementName: "rootStyle.width",
@@ -372,14 +381,14 @@ function M(e, t, n) {
372
381
  r.replacementValue ? console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`) : (console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`), r.applyDeprecated());
373
382
  }), n && e.style.setProperty(I, n);
374
383
  }
375
- function De(e) {
384
+ function Ne(e) {
376
385
  return new URL(e.src).origin;
377
386
  }
378
387
  function $(e, t, n, o) {
379
388
  const r = !!o, i = K(n), f = Y(n).toString(), {
380
389
  theme: E,
381
390
  hooks: c,
382
- rootStyle: l,
391
+ rootStyle: d,
383
392
  ...s
384
393
  } = n;
385
394
  p.postMessageToWindow(e, A.UPDATE_PARAMS, {
@@ -391,8 +400,8 @@ function $(e, t, n, o) {
391
400
  hasProvider: r
392
401
  }, t);
393
402
  }
394
- function Ne(e, t, n) {
395
- return p.listenToMessageFromWindow(window, e, h.ACTIVATE, () => {
403
+ function Ue(e, t, n) {
404
+ return p.listenToMessageFromWindow(window, e, w.ACTIVATE, () => {
396
405
  p.postMessageToWindow(e, A.UPDATE_APP_DATA, {
397
406
  metaData: n ? {
398
407
  appCode: n
@@ -400,23 +409,23 @@ function Ne(e, t, n) {
400
409
  }, t);
401
410
  }, t);
402
411
  }
403
- function We(e, t, n) {
412
+ function He(e, t, n) {
404
413
  let o = !1;
405
- return p.listenToMessageFromWindow(window, e, h.READY, () => {
414
+ return p.listenToMessageFromWindow(window, e, w.READY, () => {
406
415
  o || (o = !0, n());
407
416
  }, t);
408
417
  }
409
- function Ue(e, t) {
410
- return p.listenToMessageFromWindow(window, t, h.INTERCEPT_WINDOW_OPEN, ({
418
+ function xe(e, t) {
419
+ return p.listenToMessageFromWindow(window, t, w.INTERCEPT_WINDOW_OPEN, ({
411
420
  href: n,
412
421
  rel: o,
413
422
  target: r
414
423
  }) => {
415
- const i = He(n.toString(), e);
416
- i && te(i) && window.open(i, r, o);
424
+ const i = Be(n.toString(), e);
425
+ i && ne(i) && window.open(i, r, o);
417
426
  }, e);
418
427
  }
419
- function He(e, t) {
428
+ function Be(e, t) {
420
429
  const n = e.trim();
421
430
  if (!n)
422
431
  return null;
@@ -426,30 +435,30 @@ function He(e, t) {
426
435
  return null;
427
436
  }
428
437
  }
429
- const I = "--dynamicHeight", xe = 0;
430
- function Be(e, t, n, o) {
431
- return t.contentWindow ? [p.listenToMessageFromWindow(window, t.contentWindow, h.UPDATE_HEIGHT, (r) => {
432
- const i = `${(r?.height ?? 0) + xe}px`;
438
+ const I = "--dynamicHeight", ke = 0;
439
+ function Fe(e, t, n, o) {
440
+ return t.contentWindow ? [p.listenToMessageFromWindow(window, t.contentWindow, w.UPDATE_HEIGHT, (r) => {
441
+ const i = `${(r?.height ?? 0) + ke}px`;
433
442
  e.style.setProperty(I, i), o(i);
434
- }, n), p.listenToMessageFromWindow(window, t.contentWindow, h.SET_FULL_HEIGHT, () => {
443
+ }, n), p.listenToMessageFromWindow(window, t.contentWindow, w.SET_FULL_HEIGHT, () => {
435
444
  e.style.setProperty(I, "100dvh"), o("100dvh");
436
445
  }, n)] : [];
437
446
  }
438
- const ke = {
439
- [g.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
440
- [g.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
441
- [g.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
442
- [g.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
443
- [g.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
447
+ const Ve = {
448
+ [m.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
449
+ [m.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
450
+ [m.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
451
+ [m.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
452
+ [m.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
444
453
  };
445
- function Fe(e, t) {
446
- return ke[e.event](e.payload, t);
454
+ function Me(e, t) {
455
+ return Ve[e.event](e.payload, t);
447
456
  }
448
- function Ve(e, t, n) {
449
- return p.listenToMessageFromWindow(window, e, h.PROCESS_HOOK, async (o) => {
457
+ function $e(e, t, n) {
458
+ return p.listenToMessageFromWindow(window, e, w.PROCESS_HOOK, async (o) => {
450
459
  let r = !1;
451
460
  try {
452
- r = await Fe(o, n);
461
+ r = await Me(o, n);
453
462
  } catch {
454
463
  }
455
464
  p.postMessageToWindow(e, A.HOOK_RESULT, {
@@ -458,8 +467,8 @@ function Ve(e, t, n) {
458
467
  }, t);
459
468
  }, t);
460
469
  }
461
- const Me = Object.values(b);
462
- function ze(e, t, n) {
470
+ const Ge = Object.values(W);
471
+ function Je(e, t, n) {
463
472
  if (y(e)) {
464
473
  const o = e[n];
465
474
  return T(o) ? o[t] : o;
@@ -471,33 +480,33 @@ function ze(e, t, n) {
471
480
  return e;
472
481
  }
473
482
  function y(e) {
474
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => Me.includes(t));
483
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => Ge.includes(t));
475
484
  }
476
- const $e = /^\d+$/;
485
+ const je = /^\d+$/;
477
486
  function T(e) {
478
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => $e.test(t));
487
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => je.test(t));
479
488
  }
480
- function Xe(e) {
489
+ function Ze(e) {
481
490
  return y(e) ? Object.values(e).flatMap((t) => T(t) ? Object.values(t) : [t]) : T(e) ? Object.values(e).flatMap((t) => y(t) ? Object.values(t) : [t]) : [e];
482
491
  }
483
492
  export {
484
- he as SHOULD_THROW_IF_INVALID_URL,
485
- b as TradeType,
486
- Ke as WIDGET_CONTAINER_ID,
487
- ae as WIDGET_IFRAME_ALLOW,
488
- oe as WIDGET_IFRAME_ID,
489
- se as WIDGET_IFRAME_REFERRER_POLICY,
490
- ie as WIDGET_IFRAME_SANDBOX,
491
- Ye as WIDGET_PALETTE_COLORS,
492
- g as WidgetHookEvents,
493
- h as WidgetMethodsEmit,
493
+ ge as SHOULD_THROW_IF_INVALID_URL,
494
+ W as TradeType,
495
+ Qe as WIDGET_CONTAINER_ID,
496
+ le as WIDGET_IFRAME_ALLOW,
497
+ re as WIDGET_IFRAME_ID,
498
+ ae as WIDGET_IFRAME_REFERRER_POLICY,
499
+ se as WIDGET_IFRAME_SANDBOX,
500
+ ze as WIDGET_PALETTE_COLORS,
501
+ m as WidgetHookEvents,
502
+ w as WidgetMethodsEmit,
494
503
  A as WidgetMethodsListen,
495
- Qe as createCowSwapWidget,
504
+ Xe as createCowSwapWidget,
496
505
  G as isCowSwapWidgetPalette,
497
506
  T as isPerNetworkConfig,
498
507
  y as isPerTradeTypeConfig,
499
- ze as resolveFlexibleConfig,
500
- Xe as resolveFlexibleConfigValues,
501
- ge as sanitizeWidgetBaseUrl,
508
+ Je as resolveFlexibleConfig,
509
+ Ze as resolveFlexibleConfigValues,
510
+ _e as sanitizeWidgetBaseUrl,
502
511
  p as widgetIframeTransport
503
512
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "4.4.0",
3
+ "version": "4.4.1",
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",