@cowprotocol/widget-react 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +1 -1
  2. package/index.mjs +61 -57
  3. package/package.json +2 -2
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var V=Object.defineProperty;var b=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var h=(e,t,n)=>(b(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("react/jsx-runtime"),f=require("react"),L="cowSwapWidget";function g(e,t,n){const r={key:L,method:t,...typeof n=="object"?n:{}};e.postMessage(r,"*")}function R(e,t,n){const s=r=>{!N(r.data)||r.data.key!==L||r.data.method!==t||n(r.data)};return e.addEventListener("message",s),s}function N(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function D(e,t,n){e.removeEventListener("message",n)}function _(e,t){e.removeEventListener("message",t)}var w=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(w||{}),m=(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))(m||{}),W=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(W||{});const F=["primary","background","paper","text","danger","warning","alert","info","success"],H=["connect","disconnect","close","chainChanged","accountsChanged"];class k{constructor(t){h(this,"ethereumProvider",null);h(this,"requestWaitingForConnection",{});h(this,"processRpcCallFromWindow",({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)});this.iframeWidow=t}disconnect(){this.ethereumProvider=null,D(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():R(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),H.forEach(n=>{t.on(n,s=>this.onProviderEvent(n,s))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:s,method:r}=t;if(!this.ethereumProvider||!n)return;(r==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:n,result:c}})).catch(c=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:s,id:n,error:c}}))}onProviderEvent(t,n){g(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){g(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,t)}}function O(e){return!!(e&&typeof e=="object")}const A="_";function G(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=y(e);return t+"/#"+n+"?"+U(e)}function y(e){const{chainId:t=1,sell:n,buy:s,tradeType:r=W.SWAP}=e,a=[(n==null?void 0:n.asset)||A,(s==null?void 0:s.asset)||A].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${a}`}function U(e){const t=new URLSearchParams;return Q(x(t,e),e)}function x(e,t){const{sell:n,buy:s}=t;return n!=null&&n.amount&&e.append("sellAmount",n.amount),s!=null&&s.amount&&e.append("buyAmount",s.amount),e}function Q(e,t){const n=t.theme;return n?(O(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)}class ${constructor(){h(this,"subscriptions",{})}on(t){const{event:n,handler:s}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(s)}off(t){const{event:n,handler:s}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(r=>r!==s))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(s=>s(n))}}class j{constructor(t,n=[]){h(this,"eventEmitter",new $);h(this,"listeners",[]);h(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=R(this.contentWindow,w.EMIT_COW_EVENT,s=>this.eventEmitter.emit(s.event,s.payload))}stopListeningIframe(){_(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 q{constructor(t,n){h(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=s=>{B(s.data)&&(J(s.data)?this.appWindow.parent.postMessage(s.data,"*"):K(s.data)&&this.iframeWidow.postMessage(s.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function B(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function J(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function K(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}const M="640px",Y="450px",z=20;function T(e,t){const{params:n,provider:s,listeners:r}=t;let a=s,c=n;const o=X(n);e.innerHTML="",e.appendChild(o);const{contentWindow:u}=o;if(!u)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const l=[];l.push(Z(u,n.appCode)),l.push(ee(o,n.height));const p=new j(window,r);let E=C(u,null,a);o.addEventListener("load",()=>I(u,c,a));const d=new q(window,u);return{updateParams:i=>{c=i,I(u,c,a)},updateListeners:i=>p.updateListeners(i),updateProvider:i=>{a=i,E=C(u,E,i)},destroy:()=>{E.disconnect(),p.stopListeningIframe(),l.forEach(i=>window.removeEventListener("message",i)),d.stopListening(),e.removeChild(o)}}}function C(e,t,n){t&&t.disconnect();const s=t||new k(e);return n&&s.onConnect(n),s}function X(e){const{width:t=Y,height:n=M}=e,s=document.createElement("iframe");return s.src=G(e),s.width=t,s.height=n,s.style.border="0",s}function I(e,t,n){const s=!!n,r=y(t),a=U(t).toString(),{theme:c,...o}=t;g(e,m.UPDATE_PARAMS,{urlParams:{pathname:r,search:a},appParams:o,hasProvider:s})}function Z(e,t){const n=R(window,w.ACTIVATE,()=>{_(window,n),g(e,m.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})});return n}function ee(e,t=M){return R(window,w.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+z}px`:t})}function te(e){const{params:t,provider:n,listeners:s}=e,[r,a]=f.useState(null),c=f.useRef(null),o=f.useRef(n),u=f.useRef(s),l=f.useRef(null),p=f.useRef(null),E=f.useCallback((d,i)=>{try{console.log(`[WIDGET] ${d}`),i()}catch(v){const S=`Error ${d.toLowerCase()}`;console.error(`[WIDGET] ${S}`,v),a({message:S,error:v})}},[a]);return f.useEffect(()=>{if(!l.current||JSON.stringify(c.current)===JSON.stringify(t))return;const d=l.current,i=p.current;c.current=t,i===null?E("Creating a new widget",()=>{p.current=T(d,{params:t,provider:o.current,listeners:s}),u.current=s}):E("Updating the widget",()=>i.updateParams(t))},[t]),f.useEffect(()=>{if(!p.current||o.current===n)return;o.current=n;const d=l.current;d&&E("Updating the provider",()=>{var i;(i=p.current)==null||i.destroy(),p.current=T(d,{params:t,provider:o.current,listeners:s})})},[n]),f.useEffect(()=>{if(!p.current||u.current===s)return;const d=p.current;E("Updating the listeners",()=>d.updateListeners(s))},[s]),r?P.jsxs("div",{style:{color:"#ff3a3a"},children:[r.message,r.error.message&&P.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:r.error.message})]}):P.jsx("div",{ref:l,style:{width:"100%"}})}exports.CowSwapWidget=te;exports.TradeType=W;exports.WIDGET_PALETTE_COLORS=F;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.isCowSwapWidgetPalette=O;exports.listenToMessageFromWindow=R;exports.postMessageToWindow=g;exports.stopListeningToMessageFromWindow=D;exports.stopListeningWindowListener=_;
1
+ "use strict";var V=Object.defineProperty;var b=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var l=(e,t,n)=>(b(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("react/jsx-runtime"),f=require("react"),D="cowSwapWidget";function g(e,t,n){const s={key:D,method:t,...typeof n=="object"?n:{}};e.postMessage(s,"*")}function R(e,t,n){const r=s=>{!N(s.data)||s.data.key!==D||s.data.method!==t||n(s.data)};return e.addEventListener("message",r),r}function N(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function L(e,t,n){e.removeEventListener("message",n)}function _(e,t){e.removeEventListener("message",t)}var w=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(w||{}),m=(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))(m||{}),v=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(v||{});const F=["primary","background","paper","text","danger","warning","alert","info","success"],H=["connect","disconnect","close","chainChanged","accountsChanged"];class k{constructor(t){l(this,"ethereumProvider",null);l(this,"requestWaitingForConnection",{});l(this,"processRpcCallFromWindow",({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)});this.iframeWidow=t}disconnect(){this.ethereumProvider=null,L(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():R(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),H.forEach(n=>{t.on(n,r=>this.onProviderEvent(n,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:r,method:s}=t;if(!this.ethereumProvider||!n)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(d=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,result:d}})).catch(d=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,error:d}}))}onProviderEvent(t,n){g(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){g(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,t)}}function O(e){return!!(e&&typeof e=="object")}const A="_";function G(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=y(e);return t+"/#"+n+"?"+U(e)}function y(e){const{chainId:t=1,sell:n,buy:r,tradeType:s=v.SWAP}=e,c=[(n==null?void 0:n.asset)||A,(r==null?void 0:r.asset)||A].map(encodeURIComponent).join("/");return`/${t}/widget/${s}/${c}`}function U(e){const t=new URLSearchParams;return Q(x(t,e),e)}function x(e,t){const{sell:n,buy:r}=t;return n!=null&&n.amount&&e.append("sellAmount",n.amount),r!=null&&r.amount&&e.append("buyAmount",r.amount),e}function Q(e,t){const n=t.theme;return n?(O(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)}class ${constructor(){l(this,"subscriptions",{})}on(t){const{event:n,handler:r}=t;this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(r)}off(t){const{event:n,handler:r}=t;this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(s=>s!==r))}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(r=>r(n))}}class j{constructor(t,n=[]){l(this,"eventEmitter",new $);l(this,"listeners",[]);l(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=R(this.contentWindow,w.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){_(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 q{constructor(t,n){l(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=r=>{B(r.data)&&r.origin!==window.location.origin&&(J(r.data)?this.appWindow.parent.postMessage(r.data,"*"):K(r.data)&&this.iframeWidow.postMessage(r.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function B(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function J(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function K(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}const M="640px",Y="450px",z=20;function T(e,t){const{params:n,provider:r,listeners:s}=t;let c=r,d=n;const o=X(n);e.innerHTML="",e.appendChild(o);const{contentWindow:p}=o;if(!p)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const E=[];E.push(Z(p,n.appCode)),E.push(ee(o,n.height));const u=new j(window,s);let h=C(p,null,c);o.addEventListener("load",()=>I(p,d,c));const a=new q(window,p);return{updateParams:i=>{d=i,I(p,d,c)},updateListeners:i=>u.updateListeners(i),updateProvider:i=>{c=i,h=C(p,h,i)},destroy:()=>{h.disconnect(),u.stopListeningIframe(),E.forEach(i=>window.removeEventListener("message",i)),a.stopListening(),e.removeChild(o)}}}function C(e,t,n){t&&t.disconnect();const r=t||new k(e);return n&&r.onConnect(n),r}function X(e){const{width:t=Y,height:n=M}=e,r=document.createElement("iframe");return r.src=G(e),r.width=t,r.height=n,r.style.border="0",r}function I(e,t,n){const r=!!n,s=y(t),c=U(t).toString(),{theme:d,...o}=t;g(e,m.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:o,hasProvider:r})}function Z(e,t){const n=R(window,w.ACTIVATE,()=>{_(window,n),g(e,m.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})});return n}function ee(e,t=M){return R(window,w.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+z}px`:t})}function te(e){const{params:t,provider:n,listeners:r}=e,[s,c]=f.useState(null),d=f.useRef(null),o=f.useRef(n),p=f.useRef(r),E=f.useRef(null),u=f.useRef(null),h=f.useCallback((a,i)=>{try{console.log(`[WIDGET] ${a}`),i()}catch(W){const S=`Error ${a.toLowerCase()}`;console.error(`[WIDGET] ${S}`,W),c({message:S,error:W})}},[c]);return f.useEffect(()=>()=>{d.current=null,o.current=void 0,p.current=void 0;const a=u.current;a&&(h("💥 Destroy widget",()=>a.destroy()),u.current=null)},[]),f.useEffect(()=>{if(!E.current||JSON.stringify(d.current)===JSON.stringify(t))return;const a=E.current,i=u.current;d.current=t,i===null?h("Creating a new widget",()=>{u.current=T(a,{params:t,provider:o.current,listeners:r}),p.current=r}):h("Updating the widget",()=>i.updateParams(t))},[t]),f.useEffect(()=>{if(!u.current||o.current===n)return;o.current=n;const a=E.current;a&&h("Updating the provider",()=>{var i;(i=u.current)==null||i.destroy(),u.current=T(a,{params:t,provider:o.current,listeners:r})})},[n]),f.useEffect(()=>{if(!u.current||p.current===r)return;const a=u.current;h("Updating the listeners",()=>a.updateListeners(r))},[r]),s?P.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&P.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):P.jsx("div",{ref:E,style:{width:"100%"}})}exports.CowSwapWidget=te;exports.TradeType=v;exports.WIDGET_PALETTE_COLORS=F;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.isCowSwapWidgetPalette=O;exports.listenToMessageFromWindow=R;exports.postMessageToWindow=g;exports.stopListeningToMessageFromWindow=L;exports.stopListeningWindowListener=_;
package/index.mjs CHANGED
@@ -2,9 +2,9 @@ var V = Object.defineProperty;
2
2
  var N = (e, t, n) => t in e ? V(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
3
  var h = (e, t, n) => (N(e, typeof t != "symbol" ? t + "" : t, n), n);
4
4
  import { jsxs as b, jsx as v } from "react/jsx-runtime";
5
- import { useState as M, useRef as m, useCallback as H, useEffect as R } from "react";
5
+ import { useState as M, useRef as m, useCallback as H, useEffect as g } from "react";
6
6
  const W = "cowSwapWidget";
7
- function g(e, t, n) {
7
+ function P(e, t, n) {
8
8
  const s = {
9
9
  key: W,
10
10
  method: t,
@@ -16,7 +16,7 @@ function g(e, t, n) {
16
16
  // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
17
17
  );
18
18
  }
19
- function P(e, t, n) {
19
+ function R(e, t, n) {
20
20
  const r = (s) => {
21
21
  !F(s.data) || s.data.key !== W || s.data.method !== t || n(s.data);
22
22
  };
@@ -77,7 +77,7 @@ class x {
77
77
  * @param newProvider - The Ethereum provider to connect.
78
78
  */
79
79
  onConnect(t) {
80
- this.ethereumProvider ? this.disconnect() : P(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), G.forEach((n) => {
80
+ this.ethereumProvider ? this.disconnect() : R(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), G.forEach((n) => {
81
81
  t.on(n, (r) => this.onProviderEvent(n, r));
82
82
  });
83
83
  }
@@ -95,17 +95,17 @@ class x {
95
95
  if (!this.ethereumProvider || !n)
96
96
  return;
97
97
  (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: n })).then(
98
- (c) => this.forwardRpcResponseToIframe({
99
- rpcResponse: { jsonrpc: r, id: n, result: c }
98
+ (d) => this.forwardRpcResponseToIframe({
99
+ rpcResponse: { jsonrpc: r, id: n, result: d }
100
100
  })
101
101
  ).catch(
102
- (c) => this.forwardRpcResponseToIframe({
103
- rpcResponse: { jsonrpc: r, id: n, error: c }
102
+ (d) => this.forwardRpcResponseToIframe({
103
+ rpcResponse: { jsonrpc: r, id: n, error: d }
104
104
  })
105
105
  );
106
106
  }
107
107
  onProviderEvent(t, n) {
108
- g(this.iframeWidow, w.PROVIDER_ON_EVENT, {
108
+ P(this.iframeWidow, w.PROVIDER_ON_EVENT, {
109
109
  event: t,
110
110
  params: n
111
111
  });
@@ -114,7 +114,7 @@ class x {
114
114
  * Forward a JSON-RPC message to the content window.
115
115
  */
116
116
  forwardRpcResponseToIframe(t) {
117
- g(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, t);
117
+ P(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, t);
118
118
  }
119
119
  }
120
120
  function Q(e) {
@@ -126,8 +126,8 @@ function $(e) {
126
126
  return t + "/#" + n + "?" + y(e);
127
127
  }
128
128
  function L(e) {
129
- const { chainId: t = 1, sell: n, buy: r, tradeType: s = O.SWAP } = e, a = [(n == null ? void 0 : n.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
130
- return `/${t}/widget/${s}/${a}`;
129
+ const { chainId: t = 1, sell: n, buy: r, tradeType: s = O.SWAP } = e, c = [(n == null ? void 0 : n.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
130
+ return `/${t}/widget/${s}/${c}`;
131
131
  }
132
132
  function y(e) {
133
133
  const t = new URLSearchParams();
@@ -162,7 +162,7 @@ class j {
162
162
  h(this, "eventEmitter", new J());
163
163
  h(this, "listeners", []);
164
164
  h(this, "widgetListener");
165
- this.contentWindow = t, this.updateListeners(n), this.widgetListener = P(
165
+ this.contentWindow = t, this.updateListeners(n), this.widgetListener = R(
166
166
  this.contentWindow,
167
167
  E.EMIT_COW_EVENT,
168
168
  (r) => this.eventEmitter.emit(r.event, r.payload)
@@ -183,7 +183,7 @@ class K {
183
183
  constructor(t, n) {
184
184
  h(this, "forwardSdkMessage");
185
185
  this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (r) => {
186
- Y(r.data) && (z(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : X(r.data) && this.iframeWidow.postMessage(r.data, "*"));
186
+ Y(r.data) && r.origin !== window.location.origin && (z(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : X(r.data) && this.iframeWidow.postMessage(r.data, "*"));
187
187
  }, this.startListening();
188
188
  }
189
189
  startListening() {
@@ -205,28 +205,28 @@ function X(e) {
205
205
  const U = "640px", Z = "450px", ee = 20;
206
206
  function C(e, t) {
207
207
  const { params: n, provider: r, listeners: s } = t;
208
- let a = r, c = n;
208
+ let c = r, d = n;
209
209
  const o = te(n);
210
210
  e.innerHTML = "", e.appendChild(o);
211
- const { contentWindow: u } = o;
212
- if (!u)
211
+ const { contentWindow: p } = o;
212
+ if (!p)
213
213
  throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
214
- const f = [];
215
- f.push(ne(u, n.appCode)), f.push(re(o, n.height));
216
- const p = new j(window, s);
217
- let l = I(u, null, a);
218
- o.addEventListener("load", () => S(u, c, a));
219
- const d = new K(window, u);
214
+ const l = [];
215
+ l.push(ne(p, n.appCode)), l.push(re(o, n.height));
216
+ const u = new j(window, s);
217
+ let f = I(p, null, c);
218
+ o.addEventListener("load", () => S(p, d, c));
219
+ const a = new K(window, p);
220
220
  return {
221
221
  updateParams: (i) => {
222
- c = i, S(u, c, a);
222
+ d = i, S(p, d, c);
223
223
  },
224
- updateListeners: (i) => p.updateListeners(i),
224
+ updateListeners: (i) => u.updateListeners(i),
225
225
  updateProvider: (i) => {
226
- a = i, l = I(u, l, i);
226
+ c = i, f = I(p, f, i);
227
227
  },
228
228
  destroy: () => {
229
- l.disconnect(), p.stopListeningIframe(), f.forEach((i) => window.removeEventListener("message", i)), d.stopListening(), e.removeChild(o);
229
+ f.disconnect(), u.stopListeningIframe(), l.forEach((i) => window.removeEventListener("message", i)), a.stopListening(), e.removeChild(o);
230
230
  }
231
231
  };
232
232
  }
@@ -240,66 +240,70 @@ function te(e) {
240
240
  return r.src = $(e), r.width = t, r.height = n, r.style.border = "0", r;
241
241
  }
242
242
  function S(e, t, n) {
243
- const r = !!n, s = L(t), a = y(t).toString(), { theme: c, ...o } = t;
244
- g(e, w.UPDATE_PARAMS, {
243
+ const r = !!n, s = L(t), c = y(t).toString(), { theme: d, ...o } = t;
244
+ P(e, w.UPDATE_PARAMS, {
245
245
  urlParams: {
246
246
  pathname: s,
247
- search: a
247
+ search: c
248
248
  },
249
249
  appParams: o,
250
250
  hasProvider: r
251
251
  });
252
252
  }
253
253
  function ne(e, t) {
254
- const n = P(window, E.ACTIVATE, () => {
255
- D(window, n), g(e, w.UPDATE_APP_DATA, {
254
+ const n = R(window, E.ACTIVATE, () => {
255
+ D(window, n), P(e, w.UPDATE_APP_DATA, {
256
256
  metaData: t ? { appCode: t } : void 0
257
257
  });
258
258
  });
259
259
  return n;
260
260
  }
261
261
  function re(e, t = U) {
262
- return P(window, E.UPDATE_HEIGHT, (n) => {
262
+ return R(window, E.UPDATE_HEIGHT, (n) => {
263
263
  e.style.height = n.height ? `${n.height + ee}px` : t;
264
264
  });
265
265
  }
266
266
  function ce(e) {
267
- const { params: t, provider: n, listeners: r } = e, [s, a] = M(null), c = m(null), o = m(n), u = m(r), f = m(null), p = m(null), l = H(
268
- (d, i) => {
267
+ const { params: t, provider: n, listeners: r } = e, [s, c] = M(null), d = m(null), o = m(n), p = m(r), l = m(null), u = m(null), f = H(
268
+ (a, i) => {
269
269
  try {
270
- console.log(`[WIDGET] ${d}`), i();
270
+ console.log(`[WIDGET] ${a}`), i();
271
271
  } catch (T) {
272
- const _ = `Error ${d.toLowerCase()}`;
273
- console.error(`[WIDGET] ${_}`, T), a({ message: _, error: T });
272
+ const _ = `Error ${a.toLowerCase()}`;
273
+ console.error(`[WIDGET] ${_}`, T), c({ message: _, error: T });
274
274
  }
275
275
  },
276
- [a]
276
+ [c]
277
277
  );
278
- return R(() => {
279
- if (!f.current || JSON.stringify(c.current) === JSON.stringify(t))
278
+ return g(() => () => {
279
+ d.current = null, o.current = void 0, p.current = void 0;
280
+ const a = u.current;
281
+ a && (f("💥 Destroy widget", () => a.destroy()), u.current = null);
282
+ }, []), g(() => {
283
+ if (!l.current || JSON.stringify(d.current) === JSON.stringify(t))
280
284
  return;
281
- const d = f.current, i = p.current;
282
- c.current = t, i === null ? l("Creating a new widget", () => {
283
- p.current = C(d, { params: t, provider: o.current, listeners: r }), u.current = r;
284
- }) : l("Updating the widget", () => i.updateParams(t));
285
- }, [t]), R(() => {
286
- if (!p.current || o.current === n)
285
+ const a = l.current, i = u.current;
286
+ d.current = t, i === null ? f("Creating a new widget", () => {
287
+ u.current = C(a, { params: t, provider: o.current, listeners: r }), p.current = r;
288
+ }) : f("Updating the widget", () => i.updateParams(t));
289
+ }, [t]), g(() => {
290
+ if (!u.current || o.current === n)
287
291
  return;
288
292
  o.current = n;
289
- const d = f.current;
290
- d && l("Updating the provider", () => {
293
+ const a = l.current;
294
+ a && f("Updating the provider", () => {
291
295
  var i;
292
- (i = p.current) == null || i.destroy(), p.current = C(d, { params: t, provider: o.current, listeners: r });
296
+ (i = u.current) == null || i.destroy(), u.current = C(a, { params: t, provider: o.current, listeners: r });
293
297
  });
294
- }, [n]), R(() => {
295
- if (!p.current || u.current === r)
298
+ }, [n]), g(() => {
299
+ if (!u.current || p.current === r)
296
300
  return;
297
- const d = p.current;
298
- l("Updating the listeners", () => d.updateListeners(r));
301
+ const a = u.current;
302
+ f("Updating the listeners", () => a.updateListeners(r));
299
303
  }, [r]), s ? /* @__PURE__ */ b("div", { style: { color: "#ff3a3a" }, children: [
300
304
  s.message,
301
305
  s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
302
- ] }) : /* @__PURE__ */ v("div", { ref: f, style: { width: "100%" } });
306
+ ] }) : /* @__PURE__ */ v("div", { ref: l, style: { width: "100%" } });
303
307
  }
304
308
  export {
305
309
  ce as CowSwapWidget,
@@ -309,8 +313,8 @@ export {
309
313
  w as WidgetMethodsListen,
310
314
  C as createCowSwapWidget,
311
315
  Q as isCowSwapWidgetPalette,
312
- P as listenToMessageFromWindow,
313
- g as postMessageToWindow,
316
+ R as listenToMessageFromWindow,
317
+ P as postMessageToWindow,
314
318
  k as stopListeningToMessageFromWindow,
315
319
  D as stopListeningWindowListener
316
320
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "type": "commonjs",
5
5
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.",
6
6
  "main": "index.js",
@@ -22,6 +22,6 @@
22
22
  "react"
23
23
  ],
24
24
  "dependencies": {
25
- "@cowprotocol/widget-lib": "^0.10.0"
25
+ "@cowprotocol/widget-lib": "^0.10.1"
26
26
  }
27
27
  }