@cowprotocol/widget-lib 4.3.1 → 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
  }
@@ -0,0 +1,6 @@
1
+ import type * as CSS from 'csstype';
2
+ /**
3
+ * Assigns camelCase CSS properties to a DOM element's style.
4
+ * String values are applied as-is; numbers are stringified (e.g. `inset: 0` → `"0"`).
5
+ */
6
+ export declare function assignElementStyles(element: HTMLElement, styles: CSS.Properties | undefined): void;
@@ -1,3 +1,10 @@
1
+ /** `id` of the iframe element created by {@link createCowSwapWidget}. */
2
+ export declare const WIDGET_IFRAME_ID = "cowswap-widget-iframe";
3
+ /** Default `id` of the host container rendered by `@cowprotocol/widget-react`. */
4
+ export declare const WIDGET_CONTAINER_ID = "cowswap-widget";
5
+ export declare const DEFAULT_WIDGET_PARAMS: {
6
+ readonly appCode: "";
7
+ };
1
8
  /**
2
9
  * Iframe sandbox allowlist for the embedded CoW Swap app.
3
10
  * - allow-scripts + allow-same-origin: required for the SPA, storage, and same-origin API calls.
package/index.cjs CHANGED
@@ -1,53 +1,44 @@
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;
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
+ .${h} {
3
+ display: flex;
4
+ flex-direction: column;
5
+ gap: 16px;
6
+ align-items: center;
7
+ justify-content: center;
8
+ text-align: center;
9
+ box-sizing: border-box;
10
+ width: 100%;
11
+ height: 100%;
12
+ min-height: 200px;
13
+ padding: 24px;
14
+ background: #fff5f5;
15
+ color: #d32f2f;
16
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
17
+ font-size: 14px;
18
+ line-height: 1.5;
19
+ font-weight: 500;
20
+ }
13
21
 
14
- width: 100%;
15
- height: 100%;
22
+ .${h} p {
23
+ margin: 0;
24
+ }
16
25
 
17
- padding: 24px;
18
- box-sizing: border-box;
26
+ .${h} button {
27
+ padding: 8px 24px;
28
+ border-radius: 8px;
29
+ font: inherit;
30
+ cursor: pointer;
31
+ border: 1px solid #d32f2f;
32
+ background: transparent;
33
+ color: #d32f2f;
34
+ }
19
35
 
20
- background: #fff5f5;
21
- color: #d32f2f;
36
+ .${h} button:disabled {
37
+ cursor: progress;
38
+ opacity: 0.75;
39
+ }
22
40
 
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;
41
+ .${h} button:not(:disabled):hover {
42
+ background: #d32f2f;
43
+ color: #fff5f5;
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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createCowSwapWidget } from './cowSwapWidget';
2
- export { WIDGET_IFRAME_ALLOW, WIDGET_IFRAME_REFERRER_POLICY, WIDGET_IFRAME_SANDBOX } from './cowSwapWidget.constants';
2
+ export { WIDGET_CONTAINER_ID, WIDGET_IFRAME_ALLOW, WIDGET_IFRAME_ID, WIDGET_IFRAME_REFERRER_POLICY, WIDGET_IFRAME_SANDBOX, } from './cowSwapWidget.constants';
3
3
  export type { CowSwapWidgetHandler } from './cowSwapWidget';
4
4
  export { resolveFlexibleConfigValues } from './resolveFlexibleConfigValues';
5
5
  export { sanitizeWidgetBaseUrl, SHOULD_THROW_IF_INVALID_URL } from './urlUtils';
package/index.js CHANGED
@@ -1,6 +1,6 @@
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([
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,27 +27,41 @@ const V = /* @__PURE__ */ new Set([
27
27
  "tpoutside:",
28
28
  "bncus:",
29
29
  "bnc:"
30
- ]), $ = /* @__PURE__ */ new Set(["http:", "https:"]);
31
- function G(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 $.has(t) || V.has(t);
34
+ return te.has(t) || ee.has(t);
35
35
  } catch {
36
36
  return !1;
37
37
  }
38
38
  }
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 {
39
+ function oe(e, t) {
40
+ if (t) {
41
+ e.removeAttribute("style");
42
+ for (const n of Object.keys(t)) {
43
+ const o = n, r = t[o];
44
+ if (r == null || typeof r != "string" && typeof r != "number")
45
+ continue;
46
+ const i = `${r}`;
47
+ e.style[o] = i;
48
+ }
49
+ }
50
+ }
51
+ const re = "cowswap-widget-iframe", Qe = "cowswap-widget", ie = {
52
+ appCode: ""
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 {
43
57
  constructor(t, n, o, r = []) {
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);
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);
45
59
  }
46
- eventEmitter = new M();
60
+ eventEmitter = new q();
47
61
  listeners = [];
48
62
  widgetListener;
49
63
  stopListeningIframe() {
50
- c.stopListeningWindowListener(this.contentWindow, this.widgetListener);
64
+ p.stopListeningWindowListener(this.contentWindow, this.widgetListener);
51
65
  }
52
66
  updateListeners(t) {
53
67
  for (const n of this.listeners)
@@ -57,10 +71,10 @@ class Y {
57
71
  this.eventEmitter.on(n);
58
72
  }
59
73
  }
60
- class z {
61
- constructor(t, n) {
62
- this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (o) => {
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, "*")));
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));
64
78
  }, this.startListening();
65
79
  }
66
80
  forwardSdkMessage;
@@ -70,181 +84,187 @@ class z {
70
84
  stopListening() {
71
85
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
72
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
+ }
73
93
  }
74
- function X(e) {
94
+ function ue(e) {
75
95
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
76
96
  }
77
- function J(e) {
97
+ function pe(e) {
78
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;
79
99
  }
80
- function Z(e) {
100
+ function fe(e) {
81
101
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
82
102
  }
83
- function q(e = "Default", t = "#1c5dbf", ...n) {
103
+ function Ee(e = "Default", t = "#1c5dbf", ...n) {
84
104
  console.debug(`%c [COW][${e}]`, `font-weight: bold; color: ${t}`, ...n);
85
105
  }
86
- function ee(...e) {
87
- process.env.NODE_ENV !== "test" && q("Widget", "#47aba8", ...e);
106
+ function he(...e) {
107
+ process.env.NODE_ENV !== "test" && Ee("Widget", "#47aba8", ...e);
88
108
  }
89
- const y = "https://swap.cow.fi";
90
- function te(e) {
109
+ function G(e) {
91
110
  return !!(e && typeof e == "object");
92
111
  }
93
- const v = "_", ne = "CoW Swap widget: invalid baseUrl.", oe = !1;
94
- function re(e) {
112
+ const j = "https://swap.cow.fi", x = "_", we = "CoW Swap widget: invalid baseUrl.", ge = !1;
113
+ function me(e) {
95
114
  return e === "localhost" || e === "127.0.0.1" || e === "::1" || e.endsWith(".localhost");
96
115
  }
97
- function C(e, t) {
98
- const n = `${ne} ${e}`;
116
+ function v(e, t) {
117
+ const n = `${we} ${e}`;
99
118
  if (t)
100
119
  throw new Error(n);
101
- return console.error("[CoW Widget]", n), y;
120
+ return console.error("[CoW Widget]", n), j;
102
121
  }
103
- function ie(e, t = oe) {
122
+ function _e(e, t = ge) {
104
123
  const n = typeof e == "string" ? e.trim() : "";
105
124
  if (!n)
106
- return y;
125
+ return j;
107
126
  let o;
108
127
  try {
109
128
  o = new URL(n);
110
129
  } catch {
111
- return C(`Not a valid URL: ${JSON.stringify(n)}`, t);
130
+ return v(`Not a valid URL: ${JSON.stringify(n)}`, t);
112
131
  }
113
132
  if (o.username || o.password)
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);
133
+ return v("Userinfo (username/password) in URL is not allowed.", t);
134
+ const r = o.protocol === "https:", i = o.protocol === "http:" && me(o.hostname);
116
135
  if (!r && !i)
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}`;
136
+ return v(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
137
+ const f = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
138
+ return `${o.origin}${f}`;
120
139
  }
121
- function se(e) {
122
- const t = ie(e.baseUrl), n = U(e);
123
- return t + "/#" + n + "?" + B(e);
140
+ function Oe(e) {
141
+ const t = _e(e.baseUrl), n = K(e);
142
+ return t + "/#" + n + "?" + Y(e);
124
143
  }
125
- function U(e) {
144
+ function K(e) {
126
145
  const {
127
146
  chainId: t = 1,
128
147
  sell: n,
129
148
  buy: o,
130
- tradeType: r = I.SWAP
131
- } = e, i = [n?.asset || v, o?.asset || v].map(encodeURIComponent).join("/");
149
+ tradeType: r = W.SWAP
150
+ } = e, i = [n?.asset || x, o?.asset || x].map(encodeURIComponent).join("/");
132
151
  return `/${t}/widget/${r}/${i}`;
133
152
  }
134
- function B(e) {
153
+ function Y(e) {
135
154
  const t = new URLSearchParams();
136
- return ue(ce(le(de(ae(t, e), e), e), e), e);
155
+ return Ae(Te(ye(Se(Re(t, e), e), e), e), e);
137
156
  }
138
- function ae(e, t) {
157
+ function Re(e, t) {
139
158
  const {
140
159
  sell: n,
141
160
  buy: o
142
161
  } = t;
143
162
  return n?.amount && e.append("sellAmount", n.amount), o?.amount && e.append("buyAmount", o.amount), e;
144
163
  }
145
- function de(e, t) {
164
+ function Se(e, t) {
146
165
  const n = t.theme;
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);
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);
148
167
  }
149
- function le(e, t) {
168
+ function ye(e, t) {
150
169
  return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
151
170
  }
152
- function ce(e, t) {
171
+ function Te(e, t) {
153
172
  return t.locale && e.append("lng", t.locale), e;
154
173
  }
155
- function ue(e, t) {
156
- return pe(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;
157
176
  }
158
- function pe(e) {
177
+ function Le(e) {
159
178
  return !!e && Object.values(e).some(Boolean);
160
179
  }
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?.();
180
+ const Ce = 3e4, h = "cow-widget-loading-error", B = `data-${h}`;
181
+ function Pe(e, t, n, o, r) {
182
+ const i = t.src;
183
+ let f = !1, E = null;
184
+ function c() {
185
+ r?.(), t.style.display = "none", ve();
186
+ const d = document.createElement("div"), s = document.createElement("button"), l = document.createElement("p");
187
+ s.innerText = "Reload", s.addEventListener("click", () => {
188
+ e.removeChild(d), o(!0), t.src = "about:blank", t.style.display = "", setTimeout(() => {
189
+ t.src = i, n();
190
+ }, 100);
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);
167
192
  }
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
- },
193
+ return t.addEventListener("error", (d) => {
194
+ f || (console.error("Could not load iframe", d), c());
195
+ }), E = window.setTimeout(() => {
196
+ f || c();
197
+ }, Ce), {
190
198
  onWidgetReady() {
191
- i = !0, clearTimeout(u);
199
+ E && clearTimeout(E);
200
+ const d = document.getElementsByClassName(h)[0];
201
+ d && e.removeChild(d);
202
+ },
203
+ cancelWidgetLoading() {
204
+ f = !0;
192
205
  }
193
206
  };
194
207
  }
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;
208
+ let O = null;
209
+ function ve() {
210
+ if (!(typeof document > "u")) {
211
+ if (Ie()) {
212
+ O || (O = new CSSStyleSheet(), O.replaceSync(k)), document.adoptedStyleSheets.includes(O) || (document.adoptedStyleSheets = [...document.adoptedStyleSheets, O]);
213
+ return;
214
+ }
215
+ if (!document.head.querySelector(`style[${B}]`)) {
216
+ const e = document.createElement("style");
217
+ e.setAttribute(B, ""), e.textContent = k, document.head.appendChild(e);
218
+ }
219
+ }
220
+ }
221
+ function Ie() {
222
+ return typeof document < "u" && "adoptedStyleSheets" in Document.prototype && typeof CSSStyleSheet == "function" && typeof CSSStyleSheet.prototype.replaceSync == "function";
223
+ }
224
+ const k = `
225
+ .${h} {
226
+ display: flex;
227
+ flex-direction: column;
228
+ gap: 16px;
229
+ align-items: center;
230
+ justify-content: center;
231
+ text-align: center;
232
+ box-sizing: border-box;
233
+ width: 100%;
234
+ height: 100%;
235
+ min-height: 200px;
236
+ padding: 24px;
237
+ background: #fff5f5;
238
+ color: #d32f2f;
239
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
240
+ font-size: 14px;
241
+ line-height: 1.5;
242
+ font-weight: 500;
243
+ }
213
244
 
214
- background: #fff5f5;
215
- color: #d32f2f;
245
+ .${h} p {
246
+ margin: 0;
247
+ }
216
248
 
217
- border: 1px solid #f5c2c7;
218
- border-radius: 12px;
249
+ .${h} button {
250
+ padding: 8px 24px;
251
+ border-radius: 8px;
252
+ font: inherit;
253
+ cursor: pointer;
254
+ border: 1px solid #d32f2f;
255
+ background: transparent;
256
+ color: #d32f2f;
257
+ }
219
258
 
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>
259
+ .${h} button:disabled {
260
+ cursor: progress;
261
+ opacity: 0.75;
262
+ }
243
263
 
244
- <button class="${T}">Retry</button>
245
- </div>
246
- </body>
247
- </html>`, F = "640px", _e = "450px", Oe = 20, Re = {
264
+ .${h} button:not(:disabled):hover {
265
+ background: #d32f2f;
266
+ color: #fff5f5;
267
+ }`, We = {
248
268
  iframe: null,
249
269
  updateParams: () => {
250
270
  },
@@ -255,118 +275,157 @@ const we = `<!DOCTYPE html>
255
275
  destroy: () => {
256
276
  }
257
277
  };
258
- function ye(e, t) {
278
+ function Xe(e, t) {
259
279
  const {
260
280
  params: n,
261
281
  provider: o,
262
282
  listeners: r,
263
283
  onReady: i,
264
- enableSafeSdkBridge: u = !0
284
+ enableSafeSdkBridge: f = !0
265
285
  } = t;
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", {
270
- iframeOrigin: a
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
271
291
  });
272
- const d = [];
273
- e.innerHTML = "", e.appendChild(s);
274
- const {
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)));
292
+ const R = [];
293
+ e.innerHTML = "", e.appendChild(s), M(e, c);
294
+ let a = null, L = () => {
295
+ }, C = () => {
296
+ }, b = () => {
297
+ }, P = null, S = null, D = null, N = [], _ = null;
298
+ function U() {
299
+ if (a = s.contentWindow, !a)
300
+ throw console.error("Iframe does not contain a window", s), new Error("Iframe does not contain a window!");
301
+ R.push(He(a, l, () => {
302
+ i?.(), Q();
303
+ })), R.push(Ue(a, l, c.appCode)), N = Fe(e, s, l, (z) => {
304
+ d = z;
305
+ });
306
+ let u = null;
307
+ L = () => {
308
+ a && (u && window.removeEventListener("message", u), !c.disableWindowOpen && (u = xe(l, a), R.push(u)));
309
+ }, C = () => {
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;
288
317
  }
289
- let g = null;
290
- function W() {
291
- l && (g && window.removeEventListener("message", g), g = Se(l, a, p.hooks), d.push(g));
318
+ function H(u = !1) {
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?.();
292
320
  }
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);
298
- });
299
- const H = u ? new z(window, l) : null;
300
- return {
321
+ return U(), {
301
322
  iframe: s,
302
- updateParams: (E) => {
303
- p = E, N(l, a, p, f), S(), W();
323
+ updateParams: (u) => {
324
+ a && (c = F(u), M(e, c, d), $(a, l, c, E), L(), C());
304
325
  },
305
- updateListeners: (E) => D.updateListeners(E),
306
- updateProvider: (E) => {
307
- f = E, P = b(l, a, P, E);
326
+ updateListeners: (u) => P?.updateListeners(u),
327
+ updateProvider: (u) => {
328
+ a && (E = u, S = V(a, l, S, u));
308
329
  },
309
- destroy: () => {
310
- P.disconnect(), D.stopListeningIframe(), d.forEach((E) => window.removeEventListener("message", E)), H?.stopListening(), s && s.parentNode === e && e.removeChild(s), O();
311
- }
330
+ destroy: H
312
331
  };
313
332
  }
314
- function b(e, t, n, o) {
333
+ function be(e, t, n, o) {
334
+ return e ? new ce(t, n, o, Z() || null) : null;
335
+ }
336
+ function F(e) {
337
+ const t = {
338
+ ...ie,
339
+ ...e
340
+ };
341
+ if (typeof t.appCode != "string" || t.appCode.trim().length === 0)
342
+ throw new Error("Required param `appCode` is missing");
343
+ return t;
344
+ }
345
+ function V(e, t, n, o) {
315
346
  n && n.disconnect();
316
- const r = n || new x(e, t);
347
+ const r = n || new J(e, t);
317
348
  return o && r.onConnect(o), r;
318
349
  }
319
- function he(e) {
320
- const {
321
- width: t = _e,
322
- height: n = F
323
- } = e, o = document.createElement("iframe");
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;
350
+ function De(e) {
351
+ const t = document.createElement("iframe");
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;
353
+ }
354
+ function M(e, t, n) {
355
+ oe(e, t.rootStyle), [{
356
+ name: "params.width",
357
+ value: t.width,
358
+ replacementName: "rootStyle.width",
359
+ replacementValue: t.rootStyle?.width,
360
+ applyDeprecated: () => t.width ? e.style.width = t.width : void 0
361
+ }, {
362
+ name: "params.height",
363
+ value: t.height,
364
+ replacementName: "rootStyle.height",
365
+ replacementValue: t.rootStyle?.height,
366
+ applyDeprecated: () => t.height ? e.style.height = t.height : void 0
367
+ }, {
368
+ name: "params.maxHeight",
369
+ value: t.maxHeight,
370
+ replacementName: "rootStyle.maxHeight",
371
+ replacementValue: t.rootStyle?.maxHeight,
372
+ applyDeprecated: () => t.maxHeight ? e.style.maxHeight = `${t.maxHeight}px` : void 0
373
+ }, {
374
+ name: "params.theme.boxShadow",
375
+ value: G(t.theme) ? t.theme.boxShadow : void 0,
376
+ replacementName: "cardStyle.boxShadow",
377
+ replacementValue: t.cardStyle?.boxShadow,
378
+ applyDeprecated: () => {
379
+ }
380
+ }].filter((r) => !!r.value).forEach((r) => {
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());
382
+ }), n && e.style.setProperty(I, n);
325
383
  }
326
- function ge(e) {
384
+ function Ne(e) {
327
385
  return new URL(e.src).origin;
328
386
  }
329
- function N(e, t, n, o) {
330
- const r = !!o, i = U(n), u = B(n).toString(), {
331
- theme: f,
332
- hooks: p,
387
+ function $(e, t, n, o) {
388
+ const r = !!o, i = K(n), f = Y(n).toString(), {
389
+ theme: E,
390
+ hooks: c,
391
+ rootStyle: d,
333
392
  ...s
334
393
  } = n;
335
- c.postMessageToWindow(e, A.UPDATE_PARAMS, {
394
+ p.postMessageToWindow(e, A.UPDATE_PARAMS, {
336
395
  urlParams: {
337
396
  pathname: i,
338
- search: u
397
+ search: f
339
398
  },
340
399
  appParams: s,
341
400
  hasProvider: r
342
401
  }, t);
343
402
  }
344
- function Te(e, t, n) {
345
- return c.listenToMessageFromWindow(window, e, w.ACTIVATE, () => {
346
- c.postMessageToWindow(e, A.UPDATE_APP_DATA, {
403
+ function Ue(e, t, n) {
404
+ return p.listenToMessageFromWindow(window, e, w.ACTIVATE, () => {
405
+ p.postMessageToWindow(e, A.UPDATE_APP_DATA, {
347
406
  metaData: n ? {
348
407
  appCode: n
349
408
  } : void 0
350
409
  }, t);
351
410
  }, t);
352
411
  }
353
- function me(e, t, n) {
412
+ function He(e, t, n) {
354
413
  let o = !1;
355
- return c.listenToMessageFromWindow(window, e, w.READY, () => {
414
+ return p.listenToMessageFromWindow(window, e, w.READY, () => {
356
415
  o || (o = !0, n());
357
416
  }, t);
358
417
  }
359
- function Le(e, t) {
360
- return c.listenToMessageFromWindow(window, t, w.INTERCEPT_WINDOW_OPEN, ({
418
+ function xe(e, t) {
419
+ return p.listenToMessageFromWindow(window, t, w.INTERCEPT_WINDOW_OPEN, ({
361
420
  href: n,
362
421
  rel: o,
363
422
  target: r
364
423
  }) => {
365
- const i = Ae(n.toString(), e);
366
- i && G(i) && window.open(i, r, o);
424
+ const i = Be(n.toString(), e);
425
+ i && ne(i) && window.open(i, r, o);
367
426
  }, e);
368
427
  }
369
- function Ae(e, t) {
428
+ function Be(e, t) {
370
429
  const n = e.trim();
371
430
  if (!n)
372
431
  return null;
@@ -376,77 +435,78 @@ function Ae(e, t) {
376
435
  return null;
377
436
  }
378
437
  }
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;
382
- e.style.height = i ? `${o ? Math.min(i, o) : i}px` : n;
383
- }, t), c.listenToMessageFromWindow(window, e.contentWindow, w.SET_FULL_HEIGHT, ({
384
- isUpToSmall: r
385
- }) => {
386
- e.style.height = r ? n : `${o || document.body.offsetHeight}px`;
387
- }, t)] : [];
388
- }
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
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`;
442
+ e.style.setProperty(I, i), o(i);
443
+ }, n), p.listenToMessageFromWindow(window, t.contentWindow, w.SET_FULL_HEIGHT, () => {
444
+ e.style.setProperty(I, "100dvh"), o("100dvh");
445
+ }, n)] : [];
446
+ }
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
395
453
  };
396
- function Ie(e, t) {
397
- return Ce[e.event](e.payload, t);
454
+ function Me(e, t) {
455
+ return Ve[e.event](e.payload, t);
398
456
  }
399
- function Se(e, t, n) {
400
- return c.listenToMessageFromWindow(window, e, w.PROCESS_HOOK, async (o) => {
457
+ function $e(e, t, n) {
458
+ return p.listenToMessageFromWindow(window, e, w.PROCESS_HOOK, async (o) => {
401
459
  let r = !1;
402
460
  try {
403
- r = await Ie(o, n);
461
+ r = await Me(o, n);
404
462
  } catch {
405
463
  }
406
- c.postMessageToWindow(e, A.HOOK_RESULT, {
464
+ p.postMessageToWindow(e, A.HOOK_RESULT, {
407
465
  id: o.id,
408
466
  result: r
409
467
  }, t);
410
468
  }, t);
411
469
  }
412
- const We = Object.values(I);
413
- function Ue(e, t, n) {
414
- if (m(e)) {
470
+ const Ge = Object.values(W);
471
+ function Je(e, t, n) {
472
+ if (y(e)) {
415
473
  const o = e[n];
416
- return L(o) ? o[t] : o;
474
+ return T(o) ? o[t] : o;
417
475
  }
418
- if (L(e)) {
476
+ if (T(e)) {
419
477
  const o = e[t];
420
- return m(o) ? o[n] : o;
478
+ return y(o) ? o[n] : o;
421
479
  }
422
480
  return e;
423
481
  }
424
- function m(e) {
425
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => We.includes(t));
482
+ function y(e) {
483
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => Ge.includes(t));
426
484
  }
427
- const De = /^\d+$/;
428
- function L(e) {
429
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => De.test(t));
485
+ const je = /^\d+$/;
486
+ function T(e) {
487
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => je.test(t));
430
488
  }
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];
489
+ function Ze(e) {
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];
433
491
  }
434
492
  export {
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,
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,
442
502
  w as WidgetMethodsEmit,
443
503
  A as WidgetMethodsListen,
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
504
+ Xe as createCowSwapWidget,
505
+ G as isCowSwapWidgetPalette,
506
+ T as isPerNetworkConfig,
507
+ y as isPerTradeTypeConfig,
508
+ Je as resolveFlexibleConfig,
509
+ Ze as resolveFlexibleConfigValues,
510
+ _e as sanitizeWidgetBaseUrl,
511
+ p as widgetIframeTransport
452
512
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "4.3.1",
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",
@@ -19,6 +19,9 @@
19
19
  "@cowprotocol/events": "^4.7.1",
20
20
  "@cowprotocol/iframe-transport": "^2.3.2"
21
21
  },
22
+ "devDependencies": {
23
+ "csstype": "3.1.3"
24
+ },
22
25
  "exports": {
23
26
  ".": {
24
27
  "types": "./index.d.ts",
package/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { EnrichedOrder, SupportedChainId } from '@cowprotocol/cow-sdk';
2
2
  import { CowWidgetEventListeners, CowWidgetEventPayloadMap, CowWidgetEvents, OnTradeParamsPayload } from '@cowprotocol/events';
3
+ import type * as CSS from 'csstype';
3
4
  export type { SupportedChainId } from '@cowprotocol/cow-sdk';
4
5
  export type { OnTradeParamsPayload } from '@cowprotocol/events';
5
6
  export type PerTradeTypeConfig<T> = Partial<Record<TradeType, T>>;
@@ -76,11 +77,6 @@ export interface CowSwapWidgetProps {
76
77
  listeners?: CowWidgetEventListeners;
77
78
  onReady?(): void;
78
79
  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;
84
80
  enableSafeSdkBridge?: boolean;
85
81
  }
86
82
  export interface JsonRpcRequest {
@@ -163,6 +159,8 @@ export type CowSwapWidgetPalette = {
163
159
  /**
164
160
  * Overrides the main widget card shadow.
165
161
  * Accepts any valid CSS box-shadow value, for example `none` or `0 12px 24px rgba(0, 0, 0, 0.12)`.
162
+ *
163
+ * @deprecated Use cardStyle.boxShadow instead.
166
164
  */
167
165
  boxShadow?: string;
168
166
  } & CowSwapWidgetPaletteParams;
@@ -210,17 +208,39 @@ export interface CowSwapWidgetParams {
210
208
  */
211
209
  appCode: string;
212
210
  /**
213
- * The width of the widget in pixels. Default: 400px
211
+ * The width of the outer iframe element. Accepts CSS width values such as `450px` or `100%`.
212
+ * Default: `450px`
213
+ *
214
+ * @deprecated Use rootStyle.width instead.
214
215
  */
215
216
  width?: string;
216
217
  /**
217
- * The height of the widget in pixels. Default: 600px
218
+ * The height of the outer iframe element. Accepts CSS height values such as `640px`.
219
+ * Default: `640px`
220
+ *
221
+ * @deprecated Use rootStyle.height instead.
218
222
  */
219
223
  height?: string;
220
224
  /**
221
225
  * The maximum height of the widget in pixels. Default: body.offsetHeight
226
+ *
227
+ * @deprecated Use rootStyle.maxHeight instead.
222
228
  */
223
229
  maxHeight?: number;
230
+ /**
231
+ * Extra inline styles for the outer container element (host page only; not sent into the iframe app).
232
+ * Applied after width/height attributes. Use e.g. `backgroundColor`, `borderRadius`, `boxShadow`, `border`.
233
+ * The injected iframe fills this container. Use `height: 'var(--dynamicHeight)'` here for dynamic height.
234
+ */
235
+ rootStyle?: CSS.Properties;
236
+ /**
237
+ * Inline styles for the body wrapper (inside the iframe).
238
+ */
239
+ bodyWrapperStyle?: CSS.Properties;
240
+ /**
241
+ * Inline styles for the main trade widget card (inside the iframe).
242
+ */
243
+ cardStyle?: CSS.Properties;
224
244
  /**
225
245
  * Network ID.
226
246
  */
@@ -351,6 +371,17 @@ export interface CowSwapWidgetParams {
351
371
  * Defaults to false.
352
372
  */
353
373
  disableProgressBar?: boolean;
374
+ /**
375
+ * Disabled switching tokens places by clicking to the arrow between them
376
+ */
377
+ disableSwitchingTokens?: boolean;
378
+ /**
379
+ * Hides scrollbars inside the widget iframe (`overflow: hidden` on the document).
380
+ * Only use when the host iframe height is driven by `var(--dynamicHeight)` and not constrained (e.g. no max-height).
381
+ *
382
+ * Defaults to false.
383
+ */
384
+ disableScrollbars?: boolean;
354
385
  /**
355
386
  * Disables CoW Swap educational tips shown after a trade completes when no surplus message is available.
356
387
  * Defaults to false.
@@ -441,7 +472,7 @@ export interface WidgetMethodsEmitPayloadMap {
441
472
  [WidgetMethodsEmit.READY]: void;
442
473
  [WidgetMethodsEmit.EMIT_COW_EVENT]: EmitCowEventPayload<CowWidgetEvents>;
443
474
  [WidgetMethodsEmit.UPDATE_HEIGHT]: UpdateWidgetHeightPayload;
444
- [WidgetMethodsEmit.SET_FULL_HEIGHT]: SetWidgetFullHeightPayload;
475
+ [WidgetMethodsEmit.SET_FULL_HEIGHT]: void;
445
476
  [WidgetMethodsEmit.PROVIDER_RPC_REQUEST]: ProviderRpcRequestPayload;
446
477
  [WidgetMethodsEmit.INTERCEPT_WINDOW_OPEN]: WindowOpenPayload;
447
478
  [WidgetMethodsEmit.PROCESS_HOOK]: WidgetHookPayload<WidgetHookEvents>;
@@ -456,7 +487,7 @@ export interface WidgetMethodsListenPayloadMap {
456
487
  export type WidgetEventsPayloadMap = WidgetMethodsEmitPayloadMap & WidgetMethodsListenPayloadMap;
457
488
  export type WidgetMethodsEmitPayloads = WidgetMethodsEmitPayloadMap[WidgetMethodsEmit];
458
489
  export type WidgetMethodsListenPayloads = WidgetMethodsListenPayloadMap[WidgetMethodsListen];
459
- export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme' | 'hooks'>;
490
+ export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme' | 'hooks' | 'rootStyle'>;
460
491
  export interface UpdateParamsPayload {
461
492
  urlParams: {
462
493
  pathname: string;
@@ -473,9 +504,6 @@ export interface UpdateAppDataPayload {
473
504
  export interface UpdateWidgetHeightPayload {
474
505
  height?: number;
475
506
  }
476
- export interface SetWidgetFullHeightPayload {
477
- isUpToSmall?: boolean;
478
- }
479
507
  export type WidgetHookId = string;
480
508
  export interface WidgetHookPayload<T extends WidgetHookEvents> {
481
509
  id: WidgetHookId;
@@ -1,6 +1,6 @@
1
- type IframeLoadingState = {
2
- cancelWidgetLoading: () => void;
3
- onWidgetReady: () => void;
4
- };
5
- export declare function widgetIframeLoading(iframe: HTMLIFrameElement, onWidgetLoadingError?: () => void, customErrorStyles?: string): IframeLoadingState;
1
+ interface WidgetIframeLoadingContext {
2
+ cancelWidgetLoading(): void;
3
+ onWidgetReady(): void;
4
+ }
5
+ export declare function widgetIframeLoading(container: HTMLElement, iframe: HTMLIFrameElement, setup: () => void, destroy: (skipIframeDestroy?: boolean) => void, onWidgetLoadingError?: () => void): WidgetIframeLoadingContext;
6
6
  export {};