@cowprotocol/widget-react 0.9.0 → 0.9.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.
package/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export * from './lib/CowSwapWidget';
2
- export * from '@cowprotocol/widget-lib';
2
+ export * from '../../widget-lib/src/index.ts';
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 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=_;
1
+ "use strict";var M=Object.defineProperty;var V=(e,n,t)=>n in e?M(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var l=(e,n,t)=>(V(e,typeof n!="symbol"?n+"":n,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("react/jsx-runtime"),f=require("react");class b{constructor(){l(this,"subscriptions",{})}on(n){const{event:t,handler:r}=n;this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(r)}off(n){const{event:t,handler:r}=n;this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(s=>s!==r))}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(r=>r(t))}}const L="cowSwapWidget";function T(e,n,t){const s={key:L,method:n,...typeof t=="object"?t:{}};e.postMessage(s,"*")}function m(e,n,t){const r=s=>{!F(s.data)||s.data.key!==L||s.data.method!==n||t(s.data)};return e.addEventListener("message",r),r}function F(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function D(e,n,t){e.removeEventListener("message",t)}function _(e,n){e.removeEventListener("message",n)}var w=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e))(w||{}),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))(g||{}),S=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(S||{});const N=["primary","background","paper","text","danger","warning","alert","info","success"];class k{constructor(n,t=[]){l(this,"eventEmitter",new b);l(this,"listeners",[]);l(this,"widgetListener");this.contentWindow=n,this.updateListeners(t),this.widgetListener=m(this.contentWindow,w.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){_(this.contentWindow,this.widgetListener)}updateListeners(n){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=n||[];for(const t of this.listeners)this.eventEmitter.on(t)}}const G=["connect","disconnect","close","chainChanged","accountsChanged"];class x{constructor(n){l(this,"ethereumProvider",null);l(this,"requestWaitingForConnection",{});l(this,"processRpcCallFromWindow",({rpcRequest:n})=>{if(!this.ethereumProvider){n.id&&(this.requestWaitingForConnection[n.id]=n);return}this.processRpcRequest(n)});this.iframeWidow=n}disconnect(){this.ethereumProvider=null,D(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():m(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),G.forEach(t=>{n.on(t,r=>this.onProviderEvent(t,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:r,method:s}=n;if(!this.ethereumProvider||!t)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(d=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,result:d}})).catch(d=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,error:d}}))}onProviderEvent(n,t){T(this.iframeWidow,g.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){T(this.iframeWidow,g.PROVIDER_RPC_RESPONSE,n)}}class ${constructor(n,t){l(this,"forwardSdkMessage");this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=r=>{Q(r.data)&&r.origin!==window.location.origin&&(j(r.data)?this.appWindow.parent.postMessage(r.data,"*"):q(r.data)&&this.iframeWidow.postMessage(r.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function Q(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function 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 q(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function O(e){return!!(e&&typeof e=="object")}const A="_";function B(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=y(e);return n+"/#"+t+"?"+U(e)}function y(e){const{chainId:n=1,sell:t,buy:r,tradeType:s=S.SWAP}=e,c=[(t==null?void 0:t.asset)||A,(r==null?void 0:r.asset)||A].map(encodeURIComponent).join("/");return`/${n}/widget/${s}/${c}`}function U(e){const n=new URLSearchParams;return K(J(n,e),e)}function J(e,n){const{sell:t,buy:r}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),r!=null&&r.amount&&e.append("buyAmount",r.amount),e}function K(e,n){const t=n.theme;return t?(O(t)?(e.append("palette",encodeURIComponent(JSON.stringify(t))),e.append("theme",t.baseTheme)):(e.append("palette","null"),e.append("theme",t)),e):(e.append("palette","null"),e)}const H="640px",Y="450px",z=20;function P(e,n){const{params:t,provider:r,listeners:s}=n;let c=r,d=t;const o=X(t);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,t.appCode)),E.push(...ee(o,t.height));const u=new k(window,s);let h=C(p,null,c);o.addEventListener("load",()=>I(p,d,c));const a=new $(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,n,t){n&&n.disconnect();const r=n||new x(e);return t&&r.onConnect(t),r}function X(e){const{width:n=Y,height:t=H}=e,r=document.createElement("iframe");return r.src=B(e),r.width=n,r.height=t,r.style.border="0",r}function I(e,n,t){const r=!!t,s=y(n),c=U(n).toString(),{theme:d,...o}=n;T(e,g.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:o,hasProvider:r})}function Z(e,n){const t=m(window,w.ACTIVATE,()=>{_(window,t),T(e,g.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})});return t}function ee(e,n=H){return[m(window,w.UPDATE_HEIGHT,t=>{e.style.height=t.height?`${t.height+z}px`:n}),m(window,w.SET_FULL_HEIGHT,({isUpToSmall:t})=>{e.style.height=t?n:`${document.body.offsetHeight}px`})]}function te(e){const{params:n,provider:t,listeners:r}=e,[s,c]=f.useState(null),d=f.useRef(null),o=f.useRef(t),p=f.useRef(r),E=f.useRef(null),u=f.useRef(null),h=f.useCallback((a,i)=>{try{console.log(`[WIDGET] ${a}`),i()}catch(v){const W=`Error ${a.toLowerCase()}`;console.error(`[WIDGET] ${W}`,v),c({message:W,error:v})}},[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(n))return;const a=E.current,i=u.current;d.current=n,i===null?h("Creating a new widget",()=>{u.current=P(a,{params:n,provider:o.current,listeners:r}),p.current=r}):h("Updating the widget",()=>i.updateParams(n))},[n]),f.useEffect(()=>{if(!u.current||o.current===t)return;o.current=t;const a=E.current;a&&h("Updating the provider",()=>{var i;(i=u.current)==null||i.destroy(),u.current=P(a,{params:n,provider:o.current,listeners:r})})},[t]),f.useEffect(()=>{if(!u.current||p.current===r)return;const a=u.current;h("Updating the listeners",()=>a.updateListeners(r))},[r]),s?R.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&R.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):R.jsx("div",{ref:E,style:{width:"100%"}})}exports.CowSwapWidget=te;exports.TradeType=S;exports.WIDGET_PALETTE_COLORS=N;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=g;exports.createCowSwapWidget=P;exports.isCowSwapWidgetPalette=O;exports.listenToMessageFromWindow=m;exports.postMessageToWindow=T;exports.stopListeningToMessageFromWindow=D;exports.stopListeningWindowListener=_;
package/index.mjs CHANGED
@@ -1,14 +1,30 @@
1
- var V = Object.defineProperty;
2
- var N = (e, t, n) => t in e ? V(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var h = (e, t, n) => (N(e, typeof t != "symbol" ? t + "" : t, n), n);
1
+ var H = Object.defineProperty;
2
+ var V = (e, n, t) => n in e ? H(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
+ var f = (e, n, t) => (V(e, typeof n != "symbol" ? n + "" : n, t), t);
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 g } from "react";
5
+ import { useState as N, useRef as m, useCallback as F, useEffect as P } from "react";
6
+ class M {
7
+ constructor() {
8
+ f(this, "subscriptions", {});
9
+ }
10
+ on(n) {
11
+ const { event: t, handler: r } = n;
12
+ this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(r);
13
+ }
14
+ off(n) {
15
+ const { event: t, handler: r } = n;
16
+ this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((s) => s !== r));
17
+ }
18
+ emit(n, t) {
19
+ this.subscriptions[n] && this.subscriptions[n].forEach((r) => r(t));
20
+ }
21
+ }
6
22
  const W = "cowSwapWidget";
7
- function P(e, t, n) {
23
+ function R(e, n, t) {
8
24
  const s = {
9
25
  key: W,
10
- method: t,
11
- ...typeof n == "object" ? n : {}
26
+ method: n,
27
+ ...typeof t == "object" ? t : {}
12
28
  };
13
29
  e.postMessage(
14
30
  s,
@@ -16,22 +32,22 @@ function P(e, t, n) {
16
32
  // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
17
33
  );
18
34
  }
19
- function R(e, t, n) {
35
+ function w(e, n, t) {
20
36
  const r = (s) => {
21
- !F(s.data) || s.data.key !== W || s.data.method !== t || n(s.data);
37
+ !k(s.data) || s.data.key !== W || s.data.method !== n || t(s.data);
22
38
  };
23
39
  return e.addEventListener("message", r), r;
24
40
  }
25
- function F(e) {
41
+ function k(e) {
26
42
  return typeof e == "object" && e !== null && "key" in e && "method" in e && typeof e.key == "string" && typeof e.method == "string";
27
43
  }
28
- function k(e, t, n) {
29
- e.removeEventListener("message", n);
30
- }
31
- function D(e, t) {
44
+ function G(e, n, t) {
32
45
  e.removeEventListener("message", t);
33
46
  }
34
- var E = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e))(E || {}), w = /* @__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))(w || {}), O = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(O || {});
47
+ function L(e, n) {
48
+ e.removeEventListener("message", n);
49
+ }
50
+ var E = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.SET_FULL_HEIGHT = "SET_FULL_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e))(E || {}), g = /* @__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))(g || {}), D = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(D || {});
35
51
  const ae = [
36
52
  "primary",
37
53
  "background",
@@ -42,148 +58,109 @@ const ae = [
42
58
  "alert",
43
59
  "info",
44
60
  "success"
45
- ], G = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
61
+ ];
46
62
  class x {
63
+ constructor(n, t = []) {
64
+ f(this, "eventEmitter", new M());
65
+ f(this, "listeners", []);
66
+ f(this, "widgetListener");
67
+ this.contentWindow = n, this.updateListeners(t), this.widgetListener = w(
68
+ this.contentWindow,
69
+ E.EMIT_COW_EVENT,
70
+ (r) => this.eventEmitter.emit(r.event, r.payload)
71
+ );
72
+ }
73
+ stopListeningIframe() {
74
+ L(this.contentWindow, this.widgetListener);
75
+ }
76
+ updateListeners(n) {
77
+ for (const t of this.listeners)
78
+ this.eventEmitter.off(t);
79
+ this.listeners = n || [];
80
+ for (const t of this.listeners)
81
+ this.eventEmitter.on(t);
82
+ }
83
+ }
84
+ const $ = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
85
+ class Q {
47
86
  /**
48
87
  * Creates an instance of IframeRpcProviderBridge.
49
88
  * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
50
89
  * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
51
90
  */
52
- constructor(t) {
91
+ constructor(n) {
53
92
  /**
54
93
  * The Ethereum provider instance.
55
94
  * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
56
95
  * */
57
- h(this, "ethereumProvider", null);
96
+ f(this, "ethereumProvider", null);
58
97
  /** Stored JSON-RPC requests, to queue them when disconnected. */
59
- h(this, "requestWaitingForConnection", {});
60
- h(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
98
+ f(this, "requestWaitingForConnection", {});
99
+ f(this, "processRpcCallFromWindow", ({ rpcRequest: n }) => {
61
100
  if (!this.ethereumProvider) {
62
- t.id && (this.requestWaitingForConnection[t.id] = t);
101
+ n.id && (this.requestWaitingForConnection[n.id] = n);
63
102
  return;
64
103
  }
65
- this.processRpcRequest(t);
104
+ this.processRpcRequest(n);
66
105
  });
67
- this.iframeWidow = t;
106
+ this.iframeWidow = n;
68
107
  }
69
108
  /**
70
109
  * Disconnects the JSON-RPC bridge from the Ethereum provider.
71
110
  */
72
111
  disconnect() {
73
- this.ethereumProvider = null, k(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
112
+ this.ethereumProvider = null, G(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
74
113
  }
75
114
  /**
76
115
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
77
116
  * @param newProvider - The Ethereum provider to connect.
78
117
  */
79
- onConnect(t) {
80
- this.ethereumProvider ? this.disconnect() : R(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), G.forEach((n) => {
81
- t.on(n, (r) => this.onProviderEvent(n, r));
118
+ onConnect(n) {
119
+ this.ethereumProvider ? this.disconnect() : w(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = n, this.processPendingRequests(), $.forEach((t) => {
120
+ n.on(t, (r) => this.onProviderEvent(t, r));
82
121
  });
83
122
  }
84
123
  processPendingRequests() {
85
- Object.keys(this.requestWaitingForConnection).forEach((t) => {
86
- this.processRpcRequest(this.requestWaitingForConnection[t]);
124
+ Object.keys(this.requestWaitingForConnection).forEach((n) => {
125
+ this.processRpcRequest(this.requestWaitingForConnection[n]);
87
126
  }), this.requestWaitingForConnection = {};
88
127
  }
89
128
  /**
90
129
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
91
130
  * @param request - The JSON-RPC request to be processed.
92
131
  */
93
- processRpcRequest(t) {
94
- const { id: n, jsonrpc: r, method: s } = t;
95
- if (!this.ethereumProvider || !n)
132
+ processRpcRequest(n) {
133
+ const { id: t, jsonrpc: r, method: s } = n;
134
+ if (!this.ethereumProvider || !t)
96
135
  return;
97
- (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: n })).then(
136
+ (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...n, id: t })).then(
98
137
  (d) => this.forwardRpcResponseToIframe({
99
- rpcResponse: { jsonrpc: r, id: n, result: d }
138
+ rpcResponse: { jsonrpc: r, id: t, result: d }
100
139
  })
101
140
  ).catch(
102
141
  (d) => this.forwardRpcResponseToIframe({
103
- rpcResponse: { jsonrpc: r, id: n, error: d }
142
+ rpcResponse: { jsonrpc: r, id: t, error: d }
104
143
  })
105
144
  );
106
145
  }
107
- onProviderEvent(t, n) {
108
- P(this.iframeWidow, w.PROVIDER_ON_EVENT, {
109
- event: t,
110
- params: n
146
+ onProviderEvent(n, t) {
147
+ R(this.iframeWidow, g.PROVIDER_ON_EVENT, {
148
+ event: n,
149
+ params: t
111
150
  });
112
151
  }
113
152
  /**
114
153
  * Forward a JSON-RPC message to the content window.
115
154
  */
116
- forwardRpcResponseToIframe(t) {
117
- P(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, t);
155
+ forwardRpcResponseToIframe(n) {
156
+ R(this.iframeWidow, g.PROVIDER_RPC_RESPONSE, n);
118
157
  }
119
158
  }
120
- function Q(e) {
121
- return !!(e && typeof e == "object");
122
- }
123
- const A = "_";
124
- function $(e) {
125
- const t = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", n = L(e);
126
- return t + "/#" + n + "?" + y(e);
127
- }
128
- function L(e) {
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
- }
132
- function y(e) {
133
- const t = new URLSearchParams();
134
- return q(B(t, e), e);
135
- }
136
- function B(e, t) {
137
- const { sell: n, buy: r } = t;
138
- return n != null && n.amount && e.append("sellAmount", n.amount), r != null && r.amount && e.append("buyAmount", r.amount), e;
139
- }
140
- function q(e, t) {
141
- const n = t.theme;
142
- return n ? (Q(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);
143
- }
144
- class J {
145
- constructor() {
146
- h(this, "subscriptions", {});
147
- }
148
- on(t) {
149
- const { event: n, handler: r } = t;
150
- this.subscriptions[n] || (this.subscriptions[n] = []), this.subscriptions[n].push(r);
151
- }
152
- off(t) {
153
- const { event: n, handler: r } = t;
154
- this.subscriptions[n] && (this.subscriptions[n] = this.subscriptions[n].filter((s) => s !== r));
155
- }
156
- emit(t, n) {
157
- this.subscriptions[t] && this.subscriptions[t].forEach((r) => r(n));
158
- }
159
- }
160
- class j {
161
- constructor(t, n = []) {
162
- h(this, "eventEmitter", new J());
163
- h(this, "listeners", []);
164
- h(this, "widgetListener");
165
- this.contentWindow = t, this.updateListeners(n), this.widgetListener = R(
166
- this.contentWindow,
167
- E.EMIT_COW_EVENT,
168
- (r) => this.eventEmitter.emit(r.event, r.payload)
169
- );
170
- }
171
- stopListeningIframe() {
172
- D(this.contentWindow, this.widgetListener);
173
- }
174
- updateListeners(t) {
175
- for (const n of this.listeners)
176
- this.eventEmitter.off(n);
177
- this.listeners = t || [];
178
- for (const n of this.listeners)
179
- this.eventEmitter.on(n);
180
- }
181
- }
182
- class K {
183
- constructor(t, n) {
184
- h(this, "forwardSdkMessage");
185
- this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (r) => {
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, "*"));
159
+ class B {
160
+ constructor(n, t) {
161
+ f(this, "forwardSdkMessage");
162
+ this.appWindow = n, this.iframeWidow = t, this.forwardSdkMessage = (r) => {
163
+ q(r.data) && r.origin !== window.location.origin && (J(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : j(r.data) && this.iframeWidow.postMessage(r.data, "*"));
187
164
  }, this.startListening();
188
165
  }
189
166
  startListening() {
@@ -193,55 +170,79 @@ class K {
193
170
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
194
171
  }
195
172
  }
196
- function Y(e) {
173
+ function q(e) {
197
174
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
198
175
  }
199
- function z(e) {
176
+ function J(e) {
200
177
  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;
201
178
  }
202
- function X(e) {
179
+ function j(e) {
203
180
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
204
181
  }
182
+ function K(e) {
183
+ return !!(e && typeof e == "object");
184
+ }
185
+ const A = "_";
186
+ function Y(e) {
187
+ const n = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", t = O(e);
188
+ return n + "/#" + t + "?" + y(e);
189
+ }
190
+ function O(e) {
191
+ const { chainId: n = 1, sell: t, buy: r, tradeType: s = D.SWAP } = e, c = [(t == null ? void 0 : t.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
192
+ return `/${n}/widget/${s}/${c}`;
193
+ }
194
+ function y(e) {
195
+ const n = new URLSearchParams();
196
+ return X(z(n, e), e);
197
+ }
198
+ function z(e, n) {
199
+ const { sell: t, buy: r } = n;
200
+ return t != null && t.amount && e.append("sellAmount", t.amount), r != null && r.amount && e.append("buyAmount", r.amount), e;
201
+ }
202
+ function X(e, n) {
203
+ const t = n.theme;
204
+ return t ? (K(t) ? (e.append("palette", encodeURIComponent(JSON.stringify(t))), e.append("theme", t.baseTheme)) : (e.append("palette", "null"), e.append("theme", t)), e) : (e.append("palette", "null"), e);
205
+ }
205
206
  const U = "640px", Z = "450px", ee = 20;
206
- function C(e, t) {
207
- const { params: n, provider: r, listeners: s } = t;
208
- let c = r, d = n;
209
- const o = te(n);
207
+ function I(e, n) {
208
+ const { params: t, provider: r, listeners: s } = n;
209
+ let c = r, d = t;
210
+ const o = te(t);
210
211
  e.innerHTML = "", e.appendChild(o);
211
212
  const { contentWindow: p } = o;
212
213
  if (!p)
213
214
  throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
214
215
  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);
216
+ l.push(ne(p, t.appCode)), l.push(...re(o, t.height));
217
+ const u = new x(window, s);
218
+ let h = S(p, null, c);
219
+ o.addEventListener("load", () => C(p, d, c));
220
+ const a = new B(window, p);
220
221
  return {
221
222
  updateParams: (i) => {
222
- d = i, S(p, d, c);
223
+ d = i, C(p, d, c);
223
224
  },
224
225
  updateListeners: (i) => u.updateListeners(i),
225
226
  updateProvider: (i) => {
226
- c = i, f = I(p, f, i);
227
+ c = i, h = S(p, h, i);
227
228
  },
228
229
  destroy: () => {
229
- f.disconnect(), u.stopListeningIframe(), l.forEach((i) => window.removeEventListener("message", i)), a.stopListening(), e.removeChild(o);
230
+ h.disconnect(), u.stopListeningIframe(), l.forEach((i) => window.removeEventListener("message", i)), a.stopListening(), e.removeChild(o);
230
231
  }
231
232
  };
232
233
  }
233
- function I(e, t, n) {
234
- t && t.disconnect();
235
- const r = t || new x(e);
236
- return n && r.onConnect(n), r;
234
+ function S(e, n, t) {
235
+ n && n.disconnect();
236
+ const r = n || new Q(e);
237
+ return t && r.onConnect(t), r;
237
238
  }
238
239
  function te(e) {
239
- const { width: t = Z, height: n = U } = e, r = document.createElement("iframe");
240
- return r.src = $(e), r.width = t, r.height = n, r.style.border = "0", r;
240
+ const { width: n = Z, height: t = U } = e, r = document.createElement("iframe");
241
+ return r.src = Y(e), r.width = n, r.height = t, r.style.border = "0", r;
241
242
  }
242
- function S(e, t, n) {
243
- const r = !!n, s = L(t), c = y(t).toString(), { theme: d, ...o } = t;
244
- P(e, w.UPDATE_PARAMS, {
243
+ function C(e, n, t) {
244
+ const r = !!t, s = O(n), c = y(n).toString(), { theme: d, ...o } = n;
245
+ R(e, g.UPDATE_PARAMS, {
245
246
  urlParams: {
246
247
  pathname: s,
247
248
  search: c
@@ -250,21 +251,26 @@ function S(e, t, n) {
250
251
  hasProvider: r
251
252
  });
252
253
  }
253
- function ne(e, t) {
254
- const n = R(window, E.ACTIVATE, () => {
255
- D(window, n), P(e, w.UPDATE_APP_DATA, {
256
- metaData: t ? { appCode: t } : void 0
254
+ function ne(e, n) {
255
+ const t = w(window, E.ACTIVATE, () => {
256
+ L(window, t), R(e, g.UPDATE_APP_DATA, {
257
+ metaData: n ? { appCode: n } : void 0
257
258
  });
258
259
  });
259
- return n;
260
+ return t;
260
261
  }
261
- function re(e, t = U) {
262
- return R(window, E.UPDATE_HEIGHT, (n) => {
263
- e.style.height = n.height ? `${n.height + ee}px` : t;
264
- });
262
+ function re(e, n = U) {
263
+ return [
264
+ w(window, E.UPDATE_HEIGHT, (t) => {
265
+ e.style.height = t.height ? `${t.height + ee}px` : n;
266
+ }),
267
+ w(window, E.SET_FULL_HEIGHT, ({ isUpToSmall: t }) => {
268
+ e.style.height = t ? n : `${document.body.offsetHeight}px`;
269
+ })
270
+ ];
265
271
  }
266
272
  function ce(e) {
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(
273
+ const { params: n, provider: t, listeners: r } = e, [s, c] = N(null), d = m(null), o = m(t), p = m(r), l = m(null), u = m(null), h = F(
268
274
  (a, i) => {
269
275
  try {
270
276
  console.log(`[WIDGET] ${a}`), i();
@@ -275,31 +281,31 @@ function ce(e) {
275
281
  },
276
282
  [c]
277
283
  );
278
- return g(() => () => {
284
+ return P(() => () => {
279
285
  d.current = null, o.current = void 0, p.current = void 0;
280
286
  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))
287
+ a && (h("💥 Destroy widget", () => a.destroy()), u.current = null);
288
+ }, []), P(() => {
289
+ if (!l.current || JSON.stringify(d.current) === JSON.stringify(n))
284
290
  return;
285
291
  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)
292
+ d.current = n, i === null ? h("Creating a new widget", () => {
293
+ u.current = I(a, { params: n, provider: o.current, listeners: r }), p.current = r;
294
+ }) : h("Updating the widget", () => i.updateParams(n));
295
+ }, [n]), P(() => {
296
+ if (!u.current || o.current === t)
291
297
  return;
292
- o.current = n;
298
+ o.current = t;
293
299
  const a = l.current;
294
- a && f("Updating the provider", () => {
300
+ a && h("Updating the provider", () => {
295
301
  var i;
296
- (i = u.current) == null || i.destroy(), u.current = C(a, { params: t, provider: o.current, listeners: r });
302
+ (i = u.current) == null || i.destroy(), u.current = I(a, { params: n, provider: o.current, listeners: r });
297
303
  });
298
- }, [n]), g(() => {
304
+ }, [t]), P(() => {
299
305
  if (!u.current || p.current === r)
300
306
  return;
301
307
  const a = u.current;
302
- f("Updating the listeners", () => a.updateListeners(r));
308
+ h("Updating the listeners", () => a.updateListeners(r));
303
309
  }, [r]), s ? /* @__PURE__ */ b("div", { style: { color: "#ff3a3a" }, children: [
304
310
  s.message,
305
311
  s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
@@ -307,14 +313,14 @@ function ce(e) {
307
313
  }
308
314
  export {
309
315
  ce as CowSwapWidget,
310
- O as TradeType,
316
+ D as TradeType,
311
317
  ae as WIDGET_PALETTE_COLORS,
312
318
  E as WidgetMethodsEmit,
313
- w as WidgetMethodsListen,
314
- C as createCowSwapWidget,
315
- Q as isCowSwapWidgetPalette,
316
- R as listenToMessageFromWindow,
317
- P as postMessageToWindow,
318
- k as stopListeningToMessageFromWindow,
319
- D as stopListeningWindowListener
319
+ g as WidgetMethodsListen,
320
+ I as createCowSwapWidget,
321
+ K as isCowSwapWidgetPalette,
322
+ w as listenToMessageFromWindow,
323
+ R as postMessageToWindow,
324
+ G as stopListeningToMessageFromWindow,
325
+ L as stopListeningWindowListener
320
326
  };
@@ -1,2 +1,3 @@
1
- import { CowSwapWidgetProps } from '@cowprotocol/widget-lib';
1
+ import { CowSwapWidgetProps } from '../../../widget-lib/src/index.ts';
2
+
2
3
  export declare function CowSwapWidget(props: CowSwapWidgetProps): import("react/jsx-runtime").JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
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.11.0"
25
+ "@cowprotocol/widget-lib": "^0.11.1"
26
26
  }
27
- }
27
+ }