@nevermined-io/ui-widgets 0.5.15 → 0.5.16

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/dist/index.js CHANGED
@@ -1 +1 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.NeverminedWidgets={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=[`local`,`sandbox`,`live`,`staging_sandbox`,`staging_live`],n={local:`http://localhost:3001`,sandbox:`https://api.sandbox.nevermined.app`,live:`https://api.live.nevermined.app`,staging_sandbox:`https://api.sandbox.nevermined.dev`,staging_live:`https://api.live.nevermined.dev`},r={local:`http://localhost:4200`,sandbox:`https://nevermined.app`,live:`https://nevermined.app`,staging_sandbox:`https://nevermined.dev`,staging_live:`https://nevermined.dev`};function i(e){return n[e]}function a(e){return r[e]}var o={MISSING_SESSION:{numericCode:`WDG.0001`,message:`session is required — pass the WidgetSession returned by createWidgetSession on the backend`},INVALID_ENVIRONMENT:{numericCode:`WDG.0002`,message:`environment must be one of: sandbox, live, staging_sandbox, staging_live, local`},INVALID_SESSION:{numericCode:`WDG.0003`,message:`session is missing required fields`},SESSION_EXPIRED:{numericCode:`WDG.0006`,message:`Widget session has expired`}},s=class extends Error{code;constructor(e,t,n){super(t??o[e].message,{cause:n}),this.code=e,this.name=`WidgetInitError`}},c=class extends Error{code=`SESSION_EXPIRED`;constructor(){super(o.SESSION_EXPIRED.message),this.name=`WidgetSessionExpiredError`}},l=class extends Error{status;apiCode;constructor(e,t,n){super(e),this.status=t,this.apiCode=n,this.name=`WidgetApiError`}},u=.8,d=class{session;expiresMs;timer=null;constructor(e){this.session=e,this.expiresMs=new Date(e.expiresAt).getTime(),Number.isNaN(this.expiresMs)&&console.warn(`[SessionManager] malformed expiresAt, session will be treated as expired:`,e.expiresAt)}isValid(){return!Number.isNaN(this.expiresMs)&&this.expiresMs>Date.now()}getToken(){return this.session.sessionToken}getSession(){return this.session}startAutoRefresh(e,t){if(this.stopAutoRefresh(),!this.isValid()){t();return}let n=Math.max(0,Math.floor((this.expiresMs-Date.now())*u));this.timer=setTimeout(()=>{this.timer=null,e().then(n=>{if(this.session=n,this.expiresMs=new Date(n.expiresAt).getTime(),!this.isValid()){t();return}this.startAutoRefresh(e,t)},e=>{console.error(`[SessionManager] session refresh failed:`,e),t()})},n)}stopAutoRefresh(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},f=class{listeners=new Map;on(e,t){let n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),this}off(e,t){let n=this.listeners.get(e);return n?(n.delete(t),n.size===0&&this.listeners.delete(e),this):this}once(e,t){let n=r=>{this.off(e,n),t(r)};return this.on(e,n)}removeAllListeners(e){return e===void 0?this.listeners.clear():this.listeners.delete(e),this}emit(e,t){let n=this.listeners.get(e);n&&[...n].forEach(e=>{try{e(t)}catch(e){console.error(`[TypedEventEmitter] Handler threw:`,e)}})}},p=function(e){return e.INIT=`nvm:init`,e.CLOSE=`nvm:close`,e.BOOTED=`nvm:booted`,e.READY=`nvm:ready`,e.RESIZE=`nvm:resize`,e.SUCCESS=`nvm:success`,e.ERROR=`nvm:error`,e.CARD_ACTION=`nvm:card-action`,e}({}),m=`1`,h=`1`;function g(e){return typeof e==`string`&&Object.values(p).includes(e)}function _(e,t){return{type:e,version:h,payload:t}}function v(e){if(typeof e!=`object`||!e)return{ok:!1,reason:`not an object`};let t=e;return g(t.type)?t.version===h?{ok:!0,message:{type:t.type,version:t.version,payload:t.payload}}:{ok:!1,reason:`version mismatch: received "${t.version}", expected "${h}"`}:{ok:!1,reason:typeof t.type==`string`&&t.type.startsWith(`nvm:`)?`unknown nvm: type "${t.type}"`:`missing or unknown type`}}function y(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}var b=class{expectedOrigin;iframe=null;messageHandlers=new Set;protocolErrorHandlers=new Set;messageListener=null;destroyed=!1;constructor(e){if(this.expectedOrigin=e,e===`*`)throw Error(`[IframeManager] Wildcard origin "*" is not allowed — pass an explicit origin`)}create(e,t){this.iframe?.remove();let n=document.createElement(`iframe`);if(n.src=e,n.style.display=`block`,n.setAttribute(`allow`,`payment *`),n.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation`),!t?.container)n.style.width=`100%`,n.style.height=`100%`,n.style.border=`none`,n.style.position=`fixed`,n.style.top=`0`,n.style.left=`0`,n.style.right=`0`,n.style.bottom=`0`,n.style.zIndex=`9999`;else{let e=y(t.width??480,440,720),r=y(t.height??720,640,960);n.style.width=`${e}px`,n.style.height=`${r}px`,n.style.border=`1px solid #e5e7eb`,n.style.borderRadius=`8px`,n.style.boxSizing=`border-box`}return t?.style&&Object.assign(n.style,t.style),(t?.container??document.body).appendChild(n),this.iframe=n,n}destroy(){this.destroyed=!0,this.messageListener&&=(window.removeEventListener(`message`,this.messageListener),null),this.messageHandlers.clear(),this.protocolErrorHandlers.clear(),this.iframe?.remove(),this.iframe=null}postMessage(e){this.destroyed||this.iframe?.contentWindow?.postMessage(e,this.expectedOrigin)}onMessage(e){return this.destroyed?()=>void 0:(this.messageHandlers.add(e),this.ensureListener(),()=>this.messageHandlers.delete(e))}onProtocolError(e){return this.destroyed?()=>void 0:(this.protocolErrorHandlers.add(e),this.ensureListener(),()=>this.protocolErrorHandlers.delete(e))}ensureListener(){this.messageListener||(this.messageListener=e=>{if(e.origin!==this.expectedOrigin)return;let t=v(e.data);if(!t.ok){console.warn(`[IframeManager] Discarding message from ${this.expectedOrigin}: ${t.reason}`),this.protocolErrorHandlers.forEach(e=>{try{e(t.reason)}catch(e){console.error(`[IframeManager] Protocol error handler threw:`,e)}});return}this.messageHandlers.forEach(e=>{try{e(t.message)}catch(e){console.error(`[IframeManager] Message handler threw:`,e)}})},window.addEventListener(`message`,this.messageListener))}},x={code:`UNKNOWN`,message:`Unknown widget error`},S=class{session;webappBase;manager=null;destroyed=!1;constructor(e,t){this.session=e,this.webappBase=t}start(e){if(this.destroyed)throw Error(`[CheckoutWidget] cannot start: instance has been destroyed`);if(!e.did||typeof e.did!=`string`)throw Error(`[CheckoutWidget] did is required`);let t=new URL(`/embed/checkout/${encodeURIComponent(e.did)}`,this.webappBase);e.planId&&t.searchParams.set(`planId`,e.planId),this.mount(t,e,t=>({did:t.did??e.did,planId:t.planId??e.planId,txHash:t.txHash}),e.onSuccess)}startPlan(e){if(this.destroyed)throw Error(`[CheckoutWidget] cannot start: instance has been destroyed`);if(!e.planId||typeof e.planId!=`string`)throw Error(`[CheckoutWidget] planId is required`);let t=new URL(`/embed/checkout/plan/${encodeURIComponent(e.planId)}`,this.webappBase);this.mount(t,e,t=>({planId:t.planId??e.planId,txHash:t.txHash}),e.onSuccess)}destroy(){this.destroyed=!0,this.manager?.destroy(),this.manager=null}closeFromIframe(e,t){this.destroyed||this.manager!==t||(this.destroy(),e.onClose?.())}buildSuccessHandle(e,t){return{close:()=>this.closeFromIframe(e,t)}}mount(e,t,n,r){this.manager?.destroy();let i=new URL(this.webappBase).origin;e.searchParams.set(`parentOrigin`,window.location.origin);let a=new b(i);this.manager=a,a.create(e.toString(),{container:t.container,width:t.width,height:t.height}),a.onMessage(e=>this.handleMessage(e,t,a,n,r))}handleMessage(e,t,n,r,i){switch(e.type){case p.BOOTED:this.manager?.postMessage(_(p.INIT,{sessionToken:this.session.getToken()})),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.SUCCESS:{let a=r(e.payload!=null&&typeof e.payload==`object`?e.payload:{});i?.({result:a,handle:this.buildSuccessHandle(t,n)});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??x);return}case p.CLOSE:this.closeFromIframe(t,n);return;default:return}}},C={code:`UNKNOWN`,message:`Unknown widget error`},w={code:`UNKNOWN`,message:`Malformed nvm:success payload — paymentMethodId missing or invalid`},T={code:`UNKNOWN`,message:`Malformed nvm:success payload — delegationId missing or invalid`},E=class{session;webappBase;apiBase;manager=null;destroyed=!1;constructor(e,t,n){this.session=e,this.webappBase=t,this.apiBase=n}enrollCard(e){this.assertAlive(`enrollCard`);let t=e.provider??`stripe`,n=this.mountIframe(`/embed/cards/enroll`,e.container,{provider:t},{width:e.width,height:e.height});n.onMessage(t=>this.handleEnrollMessage(t,e,n))}listCards(e){this.assertAlive(`listCards`);let t=this.mountIframe(`/embed/cards/list`,e.container,void 0,{width:e.width,height:e.height});t.onMessage(n=>this.handleListMessage(n,e,t))}createDelegation(e){if(this.assertAlive(`createDelegation`),typeof e.paymentMethodId!=`string`||e.paymentMethodId.length===0)throw Error(`[DelegationsWidget] createDelegation: paymentMethodId is required`);let t=this.mountIframe(`/embed/cards/delegate`,e.container,{paymentMethodId:e.paymentMethodId},{width:e.width,height:e.height});t.onMessage(n=>this.handleCreateDelegationMessage(n,e,t))}async revokeCard(e){if(typeof e!=`string`||e.length===0)throw Error(`[DelegationsWidget] revokeCard: paymentMethodId is required`);await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/payment-methods/${encodeURIComponent(e)}`,`Failed to revoke payment method`)}async revokeDelegation(e){if(typeof e!=`string`||e.length===0)throw Error(`[DelegationsWidget] revokeDelegation: delegationId is required`);await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/delegation/${encodeURIComponent(e)}`,`Failed to revoke delegation`)}destroy(){this.destroyed=!0,this.manager?.destroy(),this.manager=null}assertAlive(e){if(this.destroyed)throw Error(`[DelegationsWidget] cannot ${e}: instance has been destroyed`)}mountIframe(e,t,n={},r={}){this.manager?.destroy();let i=new URL(this.webappBase).origin,a=window.location.origin,o=new URL(e,this.webappBase);o.searchParams.set(`parentOrigin`,a);for(let[e,t]of Object.entries(n))o.searchParams.set(e,t);let s=new b(i);return this.manager=s,s.create(o.toString(),{container:t,width:r.width,height:r.height}),s}postInitOnBooted(){this.manager?.postMessage(_(p.INIT,{sessionToken:this.session.getToken()}))}handleEnrollMessage(e,t,n){switch(e.type){case p.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.SUCCESS:{let r=(e.payload??{}).paymentMethodId;if(typeof r!=`string`||r.length===0){t.onError?.(w);return}t.onSuccess?.({result:{paymentMethodId:r},handle:this.buildSuccessHandle(t,n)});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??C);return}case p.CLOSE:this.closeFromIframe(t,n);return;default:return}}handleListMessage(e,t,n){switch(e.type){case p.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.CARD_ACTION:{let n=e.payload??{};if(n.action!==`delegate`&&n.action!==`revoked`||typeof n.paymentMethodId!=`string`||n.paymentMethodId.length===0)return;t.onCardAction?.({action:n.action,paymentMethodId:n.paymentMethodId});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??C);return}case p.CLOSE:this.closeFromIframe(t,n);return;default:return}}handleCreateDelegationMessage(e,t,n){switch(e.type){case p.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case p.READY:t.onReady?.();return;case p.SUCCESS:{let r=(e.payload??{}).delegationId;if(typeof r!=`string`||r.length===0){t.onError?.(T);return}t.onSuccess?.({result:{delegationId:r,paymentMethodId:t.paymentMethodId},handle:this.buildSuccessHandle(t,n)});return}case p.ERROR:{let n=e.payload;t.onError?.(n?.error??C);return}case p.CLOSE:this.closeFromIframe(t,n);return;default:return}}closeFromIframe(e,t){this.destroyed||this.manager!==t||(this.destroy(),e.onClose?.())}buildSuccessHandle(e,t){return{close:()=>this.closeFromIframe(e,t)}}async deleteWithSession(e,t){let n;try{n=await fetch(e,{method:`DELETE`,headers:{Authorization:`Bearer ${this.session.getToken()}`,Accept:`application/json`}})}catch(e){throw new l(e instanceof Error&&e.message?e.message:t)}if(n.ok)return;let r,i=t;try{let e=await n.json();typeof e?.message==`string`&&e.message.length>0&&(i=e.message),typeof e?.code==`string`&&(r=e.code)}catch{}throw new l(i,n.status,r)}};function D(e){if(typeof e!=`object`||!e)return!1;let t=e;return[`sessionToken`,`userId`,`expiresAt`,`apiKeyHash`].every(e=>typeof t[e]==`string`)&&typeof t.userWallet==`string`&&t.userWallet.startsWith(`0x`)}var O=class e{sessionManager;_account;environment;_checkout=null;_delegations=null;events=new f;constructor(e,t,n){this.sessionManager=e,this._account=t,this.environment=n}static async initialize(n){let{session:r,environment:i}=n;if(!r||typeof r!=`object`)throw new s(`MISSING_SESSION`);if(!i||!t.includes(i))throw new s(`INVALID_ENVIRONMENT`);if(!D(r))throw new s(`INVALID_SESSION`);let a=new d(r),o=new e(a,{userId:r.userId,userWallet:r.userWallet},i);return a.startAutoRefresh(()=>o.refreshSession(),()=>o.events.emit(`session-expired`,void 0)),o}async refreshSession(){let e=await fetch(`${i(this.environment)}/api/v1/widgets/session/refresh`,{method:`POST`,headers:{Authorization:`Bearer ${this.sessionManager.getToken()}`}});if(!e.ok)throw Error(`Session refresh failed with status ${e.status}`);let t=await e.json();if(!D(t))throw Error(`Session refresh returned an invalid response`);return t}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}get account(){return this._account}get hasValidSession(){return this.sessionManager.isValid()}getSessionToken(){if(!this.sessionManager.isValid())throw new c;return this.sessionManager.getToken()}get checkout(){return this._checkout||=new S(this.sessionManager,a(this.environment)),this._checkout}get delegations(){return this._delegations||=new E(this.sessionManager,a(this.environment),i(this.environment)),this._delegations}destroy(){this.sessionManager.stopAutoRefresh(),this._checkout?.destroy(),this._checkout=null,this._delegations?.destroy(),this._delegations=null,this.events.removeAllListeners()}};e.CheckoutWidget=S,e.DelegationsWidget=E,e.IframeManager=b,e.NeverminedWidgets=O,e.SessionManager=d,e.TypedEventEmitter=f,e.WIDGET_MESSAGE_VERSION=m,e.WidgetApiError=l,e.WidgetInitError=s,e.WidgetMessageType=p,e.WidgetSessionExpiredError=c,e.createMessage=_,e.parseMessage=v});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.NeverminedWidgets={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=[`local`,`sandbox`,`live`,`staging_sandbox`,`staging_live`],n={local:`http://localhost:3001`,sandbox:`https://api.sandbox.nevermined.app`,live:`https://api.live.nevermined.app`,staging_sandbox:`https://api.sandbox.nevermined.dev`,staging_live:`https://api.live.nevermined.dev`},r={local:`http://localhost:4250`,sandbox:`https://embed.nevermined.app`,live:`https://embed.nevermined.app`,staging_sandbox:`https://embed.nevermined.dev`,staging_live:`https://embed.nevermined.dev`};function i(e){return n[e]}function a(e){return r[e]}var o={local:`sandbox`,sandbox:`sandbox`,live:`live`,staging_sandbox:`sandbox`,staging_live:`live`};function s(e){return o[e]}var c={MISSING_SESSION:{numericCode:`WDG.0001`,message:`session is required — pass the WidgetSession returned by createWidgetSession on the backend`},INVALID_ENVIRONMENT:{numericCode:`WDG.0002`,message:`environment must be one of: sandbox, live, staging_sandbox, staging_live, local`},INVALID_SESSION:{numericCode:`WDG.0003`,message:`session is missing required fields`},SESSION_EXPIRED:{numericCode:`WDG.0006`,message:`Widget session has expired`}},l=class extends Error{code;constructor(e,t,n){super(t??c[e].message,{cause:n}),this.code=e,this.name=`WidgetInitError`}},u=class extends Error{code=`SESSION_EXPIRED`;constructor(){super(c.SESSION_EXPIRED.message),this.name=`WidgetSessionExpiredError`}},d=class extends Error{status;apiCode;constructor(e,t,n){super(e),this.status=t,this.apiCode=n,this.name=`WidgetApiError`}},f=.8,p=class{session;expiresMs;timer=null;constructor(e){this.session=e,this.expiresMs=new Date(e.expiresAt).getTime(),Number.isNaN(this.expiresMs)&&console.warn(`[SessionManager] malformed expiresAt, session will be treated as expired:`,e.expiresAt)}isValid(){return!Number.isNaN(this.expiresMs)&&this.expiresMs>Date.now()}getToken(){return this.session.sessionToken}getSession(){return this.session}startAutoRefresh(e,t){if(this.stopAutoRefresh(),!this.isValid()){t();return}let n=Math.max(0,Math.floor((this.expiresMs-Date.now())*f));this.timer=setTimeout(()=>{this.timer=null,e().then(n=>{if(this.session=n,this.expiresMs=new Date(n.expiresAt).getTime(),!this.isValid()){t();return}this.startAutoRefresh(e,t)},e=>{console.error(`[SessionManager] session refresh failed:`,e),t()})},n)}stopAutoRefresh(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}},m=class{listeners=new Map;on(e,t){let n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),this}off(e,t){let n=this.listeners.get(e);return n?(n.delete(t),n.size===0&&this.listeners.delete(e),this):this}once(e,t){let n=r=>{this.off(e,n),t(r)};return this.on(e,n)}removeAllListeners(e){return e===void 0?this.listeners.clear():this.listeners.delete(e),this}emit(e,t){let n=this.listeners.get(e);n&&[...n].forEach(e=>{try{e(t)}catch(e){console.error(`[TypedEventEmitter] Handler threw:`,e)}})}},h=function(e){return e.INIT=`nvm:init`,e.CLOSE=`nvm:close`,e.BOOTED=`nvm:booted`,e.READY=`nvm:ready`,e.RESIZE=`nvm:resize`,e.SUCCESS=`nvm:success`,e.ERROR=`nvm:error`,e.CARD_ACTION=`nvm:card-action`,e}({}),g=`1`,_=`1`;function v(e){return typeof e==`string`&&Object.values(h).includes(e)}function y(e,t){return{type:e,version:_,payload:t}}function b(e){if(typeof e!=`object`||!e)return{ok:!1,reason:`not an object`};let t=e;return v(t.type)?t.version===_?{ok:!0,message:{type:t.type,version:t.version,payload:t.payload}}:{ok:!1,reason:`version mismatch: received "${t.version}", expected "${_}"`}:{ok:!1,reason:typeof t.type==`string`&&t.type.startsWith(`nvm:`)?`unknown nvm: type "${t.type}"`:`missing or unknown type`}}function x(e,t,n){return Math.max(t,Math.min(n,Math.round(e)))}var S=class{expectedOrigin;iframe=null;messageHandlers=new Set;protocolErrorHandlers=new Set;messageListener=null;destroyed=!1;constructor(e){if(this.expectedOrigin=e,e===`*`)throw Error(`[IframeManager] Wildcard origin "*" is not allowed — pass an explicit origin`)}create(e,t){this.iframe?.remove();let n=document.createElement(`iframe`);if(n.src=e,n.style.display=`block`,n.setAttribute(`allow`,`payment *`),n.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation`),!t?.container)n.style.width=`100%`,n.style.height=`100%`,n.style.border=`none`,n.style.position=`fixed`,n.style.top=`0`,n.style.left=`0`,n.style.right=`0`,n.style.bottom=`0`,n.style.zIndex=`9999`;else{let e=x(t.width??480,440,720),r=x(t.height??720,640,960);n.style.width=`${e}px`,n.style.height=`${r}px`,n.style.border=`1px solid #e5e7eb`,n.style.borderRadius=`8px`,n.style.boxSizing=`border-box`}return t?.style&&Object.assign(n.style,t.style),(t?.container??document.body).appendChild(n),this.iframe=n,n}destroy(){this.destroyed=!0,this.messageListener&&=(window.removeEventListener(`message`,this.messageListener),null),this.messageHandlers.clear(),this.protocolErrorHandlers.clear(),this.iframe?.remove(),this.iframe=null}postMessage(e){this.destroyed||this.iframe?.contentWindow?.postMessage(e,this.expectedOrigin)}onMessage(e){return this.destroyed?()=>void 0:(this.messageHandlers.add(e),this.ensureListener(),()=>this.messageHandlers.delete(e))}onProtocolError(e){return this.destroyed?()=>void 0:(this.protocolErrorHandlers.add(e),this.ensureListener(),()=>this.protocolErrorHandlers.delete(e))}ensureListener(){this.messageListener||(this.messageListener=e=>{if(e.origin!==this.expectedOrigin)return;let t=b(e.data);if(!t.ok){console.warn(`[IframeManager] Discarding message from ${this.expectedOrigin}: ${t.reason}`),this.protocolErrorHandlers.forEach(e=>{try{e(t.reason)}catch(e){console.error(`[IframeManager] Protocol error handler threw:`,e)}});return}this.messageHandlers.forEach(e=>{try{e(t.message)}catch(e){console.error(`[IframeManager] Message handler threw:`,e)}})},window.addEventListener(`message`,this.messageListener))}},C={code:`UNKNOWN`,message:`Unknown widget error`},w=class{session;embedBase;embedNetwork;manager=null;destroyed=!1;constructor(e,t,n){this.session=e,this.embedBase=t,this.embedNetwork=n}start(e){if(this.destroyed)throw Error(`[CheckoutWidget] cannot start: instance has been destroyed`);if(!e.did||typeof e.did!=`string`)throw Error(`[CheckoutWidget] did is required`);let t=new URL(`/checkout/${encodeURIComponent(e.did)}`,this.embedBase);e.planId&&t.searchParams.set(`planId`,e.planId),this.mount(t,e,t=>({did:t.did??e.did,planId:t.planId??e.planId,txHash:t.txHash}),e.onSuccess)}startPlan(e){if(this.destroyed)throw Error(`[CheckoutWidget] cannot start: instance has been destroyed`);if(!e.planId||typeof e.planId!=`string`)throw Error(`[CheckoutWidget] planId is required`);let t=new URL(`/checkout/plan/${encodeURIComponent(e.planId)}`,this.embedBase);this.mount(t,e,t=>({planId:t.planId??e.planId,txHash:t.txHash}),e.onSuccess)}destroy(){this.destroyed=!0,this.manager?.destroy(),this.manager=null}closeFromIframe(e,t){this.destroyed||this.manager!==t||(this.destroy(),e.onClose?.())}buildSuccessHandle(e,t){return{close:()=>this.closeFromIframe(e,t)}}mount(e,t,n,r){this.manager?.destroy();let i=new URL(this.embedBase).origin;e.searchParams.set(`parentOrigin`,window.location.origin),e.searchParams.set(`network`,this.embedNetwork);let a=new S(i);this.manager=a,a.create(e.toString(),{container:t.container,width:t.width,height:t.height}),a.onMessage(e=>this.handleMessage(e,t,a,n,r))}handleMessage(e,t,n,r,i){switch(e.type){case h.BOOTED:this.manager?.postMessage(y(h.INIT,{sessionToken:this.session.getToken()})),t.onBooted?.();return;case h.READY:t.onReady?.();return;case h.SUCCESS:{let a=r(e.payload!=null&&typeof e.payload==`object`?e.payload:{});i?.({result:a,handle:this.buildSuccessHandle(t,n)});return}case h.ERROR:{let n=e.payload;t.onError?.(n?.error??C);return}case h.CLOSE:this.closeFromIframe(t,n);return;default:return}}},T={code:`UNKNOWN`,message:`Unknown widget error`},E={code:`UNKNOWN`,message:`Malformed nvm:success payload — paymentMethodId missing or invalid`},D={code:`UNKNOWN`,message:`Malformed nvm:success payload — delegationId missing or invalid`},O=/^0x[a-fA-F0-9]{40}$/;function k(e){return e&&O.test(e)?`crypto`:`card`}var A=class{session;embedBase;apiBase;embedNetwork;manager=null;destroyed=!1;constructor(e,t,n,r){this.session=e,this.embedBase=t,this.apiBase=n,this.embedNetwork=r}enrollCard(e){this.assertAlive(`enrollCard`);let t=e.provider??`stripe`,n=this.mountIframe(`/cards/enroll`,e.container,{provider:t},{width:e.width,height:e.height});n.onMessage(t=>this.handleEnrollMessage(t,e,n))}listCards(e){this.assertAlive(`listCards`);let t=this.mountIframe(`/cards/list`,e.container,void 0,{width:e.width,height:e.height});t.onMessage(n=>this.handleListMessage(n,e,t))}createDelegation(e){this.assertAlive(`createDelegation`);let t=e.provider??k(e.paymentMethodId);if(t===`card`&&(typeof e.paymentMethodId!=`string`||e.paymentMethodId.length===0))throw Error(`[DelegationsWidget] createDelegation: paymentMethodId is required for provider 'card'`);let n=this.mountIframe(`/cards/delegate`,e.container,{provider:t,...t===`card`&&e.paymentMethodId?{paymentMethodId:e.paymentMethodId}:{}},{width:e.width,height:e.height});n.onMessage(t=>this.handleCreateDelegationMessage(t,e,n))}async revokeCard(e){if(typeof e!=`string`||e.length===0)throw Error(`[DelegationsWidget] revokeCard: paymentMethodId is required`);await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/payment-methods/${encodeURIComponent(e)}`,`Failed to revoke payment method`)}async revokeDelegation(e){if(typeof e!=`string`||e.length===0)throw Error(`[DelegationsWidget] revokeDelegation: delegationId is required`);await this.deleteWithSession(`${this.apiBase}/api/v1/widgets/delegation/${encodeURIComponent(e)}`,`Failed to revoke delegation`)}destroy(){this.destroyed=!0,this.manager?.destroy(),this.manager=null}assertAlive(e){if(this.destroyed)throw Error(`[DelegationsWidget] cannot ${e}: instance has been destroyed`)}mountIframe(e,t,n={},r={}){this.manager?.destroy();let i=new URL(this.embedBase).origin,a=window.location.origin,o=new URL(e,this.embedBase);o.searchParams.set(`parentOrigin`,a),o.searchParams.set(`network`,this.embedNetwork);for(let[e,t]of Object.entries(n))o.searchParams.set(e,t);let s=new S(i);return this.manager=s,s.create(o.toString(),{container:t,width:r.width,height:r.height}),s}postInitOnBooted(){this.manager?.postMessage(y(h.INIT,{sessionToken:this.session.getToken()}))}handleEnrollMessage(e,t,n){switch(e.type){case h.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case h.READY:t.onReady?.();return;case h.SUCCESS:{let r=(e.payload??{}).paymentMethodId;if(typeof r!=`string`||r.length===0){t.onError?.(E);return}t.onSuccess?.({result:{paymentMethodId:r},handle:this.buildSuccessHandle(t,n)});return}case h.ERROR:{let n=e.payload;t.onError?.(n?.error??T);return}case h.CLOSE:this.closeFromIframe(t,n);return;default:return}}handleListMessage(e,t,n){switch(e.type){case h.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case h.READY:t.onReady?.();return;case h.CARD_ACTION:{let n=e.payload??{};if(n.action!==`delegate`&&n.action!==`revoked`||typeof n.paymentMethodId!=`string`||n.paymentMethodId.length===0)return;t.onCardAction?.({action:n.action,paymentMethodId:n.paymentMethodId});return}case h.ERROR:{let n=e.payload;t.onError?.(n?.error??T);return}case h.CLOSE:this.closeFromIframe(t,n);return;default:return}}handleCreateDelegationMessage(e,t,n){switch(e.type){case h.BOOTED:this.postInitOnBooted(),t.onBooted?.();return;case h.READY:t.onReady?.();return;case h.SUCCESS:{let r=(e.payload??{}).delegationId;if(typeof r!=`string`||r.length===0){t.onError?.(D);return}t.onSuccess?.({result:{delegationId:r,paymentMethodId:t.paymentMethodId},handle:this.buildSuccessHandle(t,n)});return}case h.ERROR:{let n=e.payload;t.onError?.(n?.error??T);return}case h.CLOSE:this.closeFromIframe(t,n);return;default:return}}closeFromIframe(e,t){this.destroyed||this.manager!==t||(this.destroy(),e.onClose?.())}buildSuccessHandle(e,t){return{close:()=>this.closeFromIframe(e,t)}}async deleteWithSession(e,t){let n;try{n=await fetch(e,{method:`DELETE`,headers:{Authorization:`Bearer ${this.session.getToken()}`,Accept:`application/json`}})}catch(e){throw new d(e instanceof Error&&e.message?e.message:t)}if(n.ok)return;let r,i=t;try{let e=await n.json();typeof e?.message==`string`&&e.message.length>0&&(i=e.message),typeof e?.code==`string`&&(r=e.code)}catch{}throw new d(i,n.status,r)}};function j(e){if(typeof e!=`object`||!e)return!1;let t=e;return[`sessionToken`,`userId`,`expiresAt`,`apiKeyHash`].every(e=>typeof t[e]==`string`)&&typeof t.userWallet==`string`&&t.userWallet.startsWith(`0x`)}var M=class e{sessionManager;_account;environment;_checkout=null;_delegations=null;events=new m;constructor(e,t,n){this.sessionManager=e,this._account=t,this.environment=n}static async initialize(n){let{session:r,environment:i}=n;if(!r||typeof r!=`object`)throw new l(`MISSING_SESSION`);if(!i||!t.includes(i))throw new l(`INVALID_ENVIRONMENT`);if(!j(r))throw new l(`INVALID_SESSION`);let a=new p(r),o=new e(a,{userId:r.userId,userWallet:r.userWallet},i);return a.startAutoRefresh(()=>o.refreshSession(),()=>o.events.emit(`session-expired`,void 0)),o}async refreshSession(){let e=await fetch(`${i(this.environment)}/api/v1/widgets/session/refresh`,{method:`POST`,headers:{Authorization:`Bearer ${this.sessionManager.getToken()}`}});if(!e.ok)throw Error(`Session refresh failed with status ${e.status}`);let t=await e.json();if(!j(t))throw Error(`Session refresh returned an invalid response`);return t}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}get account(){return this._account}get hasValidSession(){return this.sessionManager.isValid()}getSessionToken(){if(!this.sessionManager.isValid())throw new u;return this.sessionManager.getToken()}get checkout(){return this._checkout||=new w(this.sessionManager,a(this.environment),s(this.environment)),this._checkout}get delegations(){return this._delegations||=new A(this.sessionManager,a(this.environment),i(this.environment),s(this.environment)),this._delegations}destroy(){this.sessionManager.stopAutoRefresh(),this._checkout?.destroy(),this._checkout=null,this._delegations?.destroy(),this._delegations=null,this.events.removeAllListeners()}};e.CheckoutWidget=w,e.DelegationsWidget=A,e.IframeManager=S,e.NeverminedWidgets=M,e.SessionManager=p,e.TypedEventEmitter=m,e.WIDGET_MESSAGE_VERSION=g,e.WidgetApiError=d,e.WidgetInitError=l,e.WidgetMessageType=h,e.WidgetSessionExpiredError=u,e.createMessage=y,e.parseMessage=b});
package/dist/index.mjs CHANGED
@@ -12,11 +12,11 @@ var e = [
12
12
  staging_sandbox: "https://api.sandbox.nevermined.dev",
13
13
  staging_live: "https://api.live.nevermined.dev"
14
14
  }, n = {
15
- local: "http://localhost:4200",
16
- sandbox: "https://nevermined.app",
17
- live: "https://nevermined.app",
18
- staging_sandbox: "https://nevermined.dev",
19
- staging_live: "https://nevermined.dev"
15
+ local: "http://localhost:4250",
16
+ sandbox: "https://embed.nevermined.app",
17
+ live: "https://embed.nevermined.app",
18
+ staging_sandbox: "https://embed.nevermined.dev",
19
+ staging_live: "https://embed.nevermined.dev"
20
20
  };
21
21
  function r(e) {
22
22
  return t[e];
@@ -24,9 +24,19 @@ function r(e) {
24
24
  function i(e) {
25
25
  return n[e];
26
26
  }
27
+ var a = {
28
+ local: "sandbox",
29
+ sandbox: "sandbox",
30
+ live: "live",
31
+ staging_sandbox: "sandbox",
32
+ staging_live: "live"
33
+ };
34
+ function o(e) {
35
+ return a[e];
36
+ }
27
37
  //#endregion
28
38
  //#region src/utils/errors.ts
29
- var a = {
39
+ var s = {
30
40
  MISSING_SESSION: {
31
41
  numericCode: "WDG.0001",
32
42
  message: "session is required — pass the WidgetSession returned by createWidgetSession on the backend"
@@ -43,23 +53,23 @@ var a = {
43
53
  numericCode: "WDG.0006",
44
54
  message: "Widget session has expired"
45
55
  }
46
- }, o = class extends Error {
56
+ }, c = class extends Error {
47
57
  code;
48
58
  constructor(e, t, n) {
49
- super(t ?? a[e].message, { cause: n }), this.code = e, this.name = "WidgetInitError";
59
+ super(t ?? s[e].message, { cause: n }), this.code = e, this.name = "WidgetInitError";
50
60
  }
51
- }, s = class extends Error {
61
+ }, l = class extends Error {
52
62
  code = "SESSION_EXPIRED";
53
63
  constructor() {
54
- super(a.SESSION_EXPIRED.message), this.name = "WidgetSessionExpiredError";
64
+ super(s.SESSION_EXPIRED.message), this.name = "WidgetSessionExpiredError";
55
65
  }
56
- }, c = class extends Error {
66
+ }, u = class extends Error {
57
67
  status;
58
68
  apiCode;
59
69
  constructor(e, t, n) {
60
70
  super(e), this.status = t, this.apiCode = n, this.name = "WidgetApiError";
61
71
  }
62
- }, l = .8, u = class {
72
+ }, d = .8, f = class {
63
73
  session;
64
74
  expiresMs;
65
75
  timer = null;
@@ -80,7 +90,7 @@ var a = {
80
90
  t();
81
91
  return;
82
92
  }
83
- let n = Math.max(0, Math.floor((this.expiresMs - Date.now()) * l));
93
+ let n = Math.max(0, Math.floor((this.expiresMs - Date.now()) * d));
84
94
  this.timer = setTimeout(() => {
85
95
  this.timer = null, e().then((n) => {
86
96
  if (this.session = n, this.expiresMs = new Date(n.expiresAt).getTime(), !this.isValid()) {
@@ -96,7 +106,7 @@ var a = {
96
106
  stopAutoRefresh() {
97
107
  this.timer !== null && (clearTimeout(this.timer), this.timer = null);
98
108
  }
99
- }, d = class {
109
+ }, p = class {
100
110
  listeners = /* @__PURE__ */ new Map();
101
111
  on(e, t) {
102
112
  let n = this.listeners.get(e) ?? /* @__PURE__ */ new Set();
@@ -125,26 +135,26 @@ var a = {
125
135
  }
126
136
  });
127
137
  }
128
- }, f = /* @__PURE__ */ function(e) {
138
+ }, m = /* @__PURE__ */ function(e) {
129
139
  return e.INIT = "nvm:init", e.CLOSE = "nvm:close", e.BOOTED = "nvm:booted", e.READY = "nvm:ready", e.RESIZE = "nvm:resize", e.SUCCESS = "nvm:success", e.ERROR = "nvm:error", e.CARD_ACTION = "nvm:card-action", e;
130
- }({}), p = "1", m = "1";
131
- function h(e) {
132
- return typeof e == "string" && Object.values(f).includes(e);
140
+ }({}), h = "1", g = "1";
141
+ function _(e) {
142
+ return typeof e == "string" && Object.values(m).includes(e);
133
143
  }
134
- function g(e, t) {
144
+ function v(e, t) {
135
145
  return {
136
146
  type: e,
137
- version: m,
147
+ version: g,
138
148
  payload: t
139
149
  };
140
150
  }
141
- function _(e) {
151
+ function y(e) {
142
152
  if (typeof e != "object" || !e) return {
143
153
  ok: !1,
144
154
  reason: "not an object"
145
155
  };
146
156
  let t = e;
147
- return h(t.type) ? t.version === m ? {
157
+ return _(t.type) ? t.version === g ? {
148
158
  ok: !0,
149
159
  message: {
150
160
  type: t.type,
@@ -153,16 +163,16 @@ function _(e) {
153
163
  }
154
164
  } : {
155
165
  ok: !1,
156
- reason: `version mismatch: received "${t.version}", expected "${m}"`
166
+ reason: `version mismatch: received "${t.version}", expected "${g}"`
157
167
  } : {
158
168
  ok: !1,
159
169
  reason: typeof t.type == "string" && t.type.startsWith("nvm:") ? `unknown nvm: type "${t.type}"` : "missing or unknown type"
160
170
  };
161
171
  }
162
- function v(e, t, n) {
172
+ function b(e, t, n) {
163
173
  return Math.max(t, Math.min(n, Math.round(e)));
164
174
  }
165
- var y = class {
175
+ var x = class {
166
176
  expectedOrigin;
167
177
  iframe = null;
168
178
  messageHandlers = /* @__PURE__ */ new Set();
@@ -177,7 +187,7 @@ var y = class {
177
187
  let n = document.createElement("iframe");
178
188
  if (n.src = e, n.style.display = "block", n.setAttribute("allow", "payment *"), n.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"), !t?.container) n.style.width = "100%", n.style.height = "100%", n.style.border = "none", n.style.position = "fixed", n.style.top = "0", n.style.left = "0", n.style.right = "0", n.style.bottom = "0", n.style.zIndex = "9999";
179
189
  else {
180
- let e = v(t.width ?? 480, 440, 720), r = v(t.height ?? 720, 640, 960);
190
+ let e = b(t.width ?? 480, 440, 720), r = b(t.height ?? 720, 640, 960);
181
191
  n.style.width = `${e}px`, n.style.height = `${r}px`, n.style.border = "1px solid #e5e7eb", n.style.borderRadius = "8px", n.style.boxSizing = "border-box";
182
192
  }
183
193
  return t?.style && Object.assign(n.style, t.style), (t?.container ?? document.body).appendChild(n), this.iframe = n, n;
@@ -197,7 +207,7 @@ var y = class {
197
207
  ensureListener() {
198
208
  this.messageListener || (this.messageListener = (e) => {
199
209
  if (e.origin !== this.expectedOrigin) return;
200
- let t = _(e.data);
210
+ let t = y(e.data);
201
211
  if (!t.ok) {
202
212
  console.warn(`[IframeManager] Discarding message from ${this.expectedOrigin}: ${t.reason}`), this.protocolErrorHandlers.forEach((e) => {
203
213
  try {
@@ -217,21 +227,22 @@ var y = class {
217
227
  });
218
228
  }, window.addEventListener("message", this.messageListener));
219
229
  }
220
- }, b = {
230
+ }, S = {
221
231
  code: "UNKNOWN",
222
232
  message: "Unknown widget error"
223
- }, x = class {
233
+ }, C = class {
224
234
  session;
225
- webappBase;
235
+ embedBase;
236
+ embedNetwork;
226
237
  manager = null;
227
238
  destroyed = !1;
228
- constructor(e, t) {
229
- this.session = e, this.webappBase = t;
239
+ constructor(e, t, n) {
240
+ this.session = e, this.embedBase = t, this.embedNetwork = n;
230
241
  }
231
242
  start(e) {
232
243
  if (this.destroyed) throw Error("[CheckoutWidget] cannot start: instance has been destroyed");
233
244
  if (!e.did || typeof e.did != "string") throw Error("[CheckoutWidget] did is required");
234
- let t = new URL(`/embed/checkout/${encodeURIComponent(e.did)}`, this.webappBase);
245
+ let t = new URL(`/checkout/${encodeURIComponent(e.did)}`, this.embedBase);
235
246
  e.planId && t.searchParams.set("planId", e.planId), this.mount(t, e, (t) => ({
236
247
  did: t.did ?? e.did,
237
248
  planId: t.planId ?? e.planId,
@@ -241,7 +252,7 @@ var y = class {
241
252
  startPlan(e) {
242
253
  if (this.destroyed) throw Error("[CheckoutWidget] cannot start: instance has been destroyed");
243
254
  if (!e.planId || typeof e.planId != "string") throw Error("[CheckoutWidget] planId is required");
244
- let t = new URL(`/embed/checkout/plan/${encodeURIComponent(e.planId)}`, this.webappBase);
255
+ let t = new URL(`/checkout/plan/${encodeURIComponent(e.planId)}`, this.embedBase);
245
256
  this.mount(t, e, (t) => ({
246
257
  planId: t.planId ?? e.planId,
247
258
  txHash: t.txHash
@@ -258,9 +269,9 @@ var y = class {
258
269
  }
259
270
  mount(e, t, n, r) {
260
271
  this.manager?.destroy();
261
- let i = new URL(this.webappBase).origin;
262
- e.searchParams.set("parentOrigin", window.location.origin);
263
- let a = new y(i);
272
+ let i = new URL(this.embedBase).origin;
273
+ e.searchParams.set("parentOrigin", window.location.origin), e.searchParams.set("network", this.embedNetwork);
274
+ let a = new x(i);
264
275
  this.manager = a, a.create(e.toString(), {
265
276
  container: t.container,
266
277
  width: t.width,
@@ -269,13 +280,13 @@ var y = class {
269
280
  }
270
281
  handleMessage(e, t, n, r, i) {
271
282
  switch (e.type) {
272
- case f.BOOTED:
273
- this.manager?.postMessage(g(f.INIT, { sessionToken: this.session.getToken() })), t.onBooted?.();
283
+ case m.BOOTED:
284
+ this.manager?.postMessage(v(m.INIT, { sessionToken: this.session.getToken() })), t.onBooted?.();
274
285
  return;
275
- case f.READY:
286
+ case m.READY:
276
287
  t.onReady?.();
277
288
  return;
278
- case f.SUCCESS: {
289
+ case m.SUCCESS: {
279
290
  let a = r(e.payload != null && typeof e.payload == "object" ? e.payload : {});
280
291
  i?.({
281
292
  result: a,
@@ -283,38 +294,43 @@ var y = class {
283
294
  });
284
295
  return;
285
296
  }
286
- case f.ERROR: {
297
+ case m.ERROR: {
287
298
  let n = e.payload;
288
- t.onError?.(n?.error ?? b);
299
+ t.onError?.(n?.error ?? S);
289
300
  return;
290
301
  }
291
- case f.CLOSE:
302
+ case m.CLOSE:
292
303
  this.closeFromIframe(t, n);
293
304
  return;
294
305
  default: return;
295
306
  }
296
307
  }
297
- }, S = {
308
+ }, w = {
298
309
  code: "UNKNOWN",
299
310
  message: "Unknown widget error"
300
- }, C = {
311
+ }, T = {
301
312
  code: "UNKNOWN",
302
313
  message: "Malformed nvm:success payload — paymentMethodId missing or invalid"
303
- }, w = {
314
+ }, E = {
304
315
  code: "UNKNOWN",
305
316
  message: "Malformed nvm:success payload — delegationId missing or invalid"
306
- }, T = class {
317
+ }, D = /^0x[a-fA-F0-9]{40}$/;
318
+ function O(e) {
319
+ return e && D.test(e) ? "crypto" : "card";
320
+ }
321
+ var k = class {
307
322
  session;
308
- webappBase;
323
+ embedBase;
309
324
  apiBase;
325
+ embedNetwork;
310
326
  manager = null;
311
327
  destroyed = !1;
312
- constructor(e, t, n) {
313
- this.session = e, this.webappBase = t, this.apiBase = n;
328
+ constructor(e, t, n, r) {
329
+ this.session = e, this.embedBase = t, this.apiBase = n, this.embedNetwork = r;
314
330
  }
315
331
  enrollCard(e) {
316
332
  this.assertAlive("enrollCard");
317
- let t = e.provider ?? "stripe", n = this.mountIframe("/embed/cards/enroll", e.container, { provider: t }, {
333
+ let t = e.provider ?? "stripe", n = this.mountIframe("/cards/enroll", e.container, { provider: t }, {
318
334
  width: e.width,
319
335
  height: e.height
320
336
  });
@@ -322,19 +338,24 @@ var y = class {
322
338
  }
323
339
  listCards(e) {
324
340
  this.assertAlive("listCards");
325
- let t = this.mountIframe("/embed/cards/list", e.container, void 0, {
341
+ let t = this.mountIframe("/cards/list", e.container, void 0, {
326
342
  width: e.width,
327
343
  height: e.height
328
344
  });
329
345
  t.onMessage((n) => this.handleListMessage(n, e, t));
330
346
  }
331
347
  createDelegation(e) {
332
- if (this.assertAlive("createDelegation"), typeof e.paymentMethodId != "string" || e.paymentMethodId.length === 0) throw Error("[DelegationsWidget] createDelegation: paymentMethodId is required");
333
- let t = this.mountIframe("/embed/cards/delegate", e.container, { paymentMethodId: e.paymentMethodId }, {
348
+ this.assertAlive("createDelegation");
349
+ let t = e.provider ?? O(e.paymentMethodId);
350
+ if (t === "card" && (typeof e.paymentMethodId != "string" || e.paymentMethodId.length === 0)) throw Error("[DelegationsWidget] createDelegation: paymentMethodId is required for provider 'card'");
351
+ let n = this.mountIframe("/cards/delegate", e.container, {
352
+ provider: t,
353
+ ...t === "card" && e.paymentMethodId ? { paymentMethodId: e.paymentMethodId } : {}
354
+ }, {
334
355
  width: e.width,
335
356
  height: e.height
336
357
  });
337
- t.onMessage((n) => this.handleCreateDelegationMessage(n, e, t));
358
+ n.onMessage((t) => this.handleCreateDelegationMessage(t, e, n));
338
359
  }
339
360
  async revokeCard(e) {
340
361
  if (typeof e != "string" || e.length === 0) throw Error("[DelegationsWidget] revokeCard: paymentMethodId is required");
@@ -352,10 +373,10 @@ var y = class {
352
373
  }
353
374
  mountIframe(e, t, n = {}, r = {}) {
354
375
  this.manager?.destroy();
355
- let i = new URL(this.webappBase).origin, a = window.location.origin, o = new URL(e, this.webappBase);
356
- o.searchParams.set("parentOrigin", a);
376
+ let i = new URL(this.embedBase).origin, a = window.location.origin, o = new URL(e, this.embedBase);
377
+ o.searchParams.set("parentOrigin", a), o.searchParams.set("network", this.embedNetwork);
357
378
  for (let [e, t] of Object.entries(n)) o.searchParams.set(e, t);
358
- let s = new y(i);
379
+ let s = new x(i);
359
380
  return this.manager = s, s.create(o.toString(), {
360
381
  container: t,
361
382
  width: r.width,
@@ -363,20 +384,20 @@ var y = class {
363
384
  }), s;
364
385
  }
365
386
  postInitOnBooted() {
366
- this.manager?.postMessage(g(f.INIT, { sessionToken: this.session.getToken() }));
387
+ this.manager?.postMessage(v(m.INIT, { sessionToken: this.session.getToken() }));
367
388
  }
368
389
  handleEnrollMessage(e, t, n) {
369
390
  switch (e.type) {
370
- case f.BOOTED:
391
+ case m.BOOTED:
371
392
  this.postInitOnBooted(), t.onBooted?.();
372
393
  return;
373
- case f.READY:
394
+ case m.READY:
374
395
  t.onReady?.();
375
396
  return;
376
- case f.SUCCESS: {
397
+ case m.SUCCESS: {
377
398
  let r = (e.payload ?? {}).paymentMethodId;
378
399
  if (typeof r != "string" || r.length === 0) {
379
- t.onError?.(C);
400
+ t.onError?.(T);
380
401
  return;
381
402
  }
382
403
  t.onSuccess?.({
@@ -385,12 +406,12 @@ var y = class {
385
406
  });
386
407
  return;
387
408
  }
388
- case f.ERROR: {
409
+ case m.ERROR: {
389
410
  let n = e.payload;
390
- t.onError?.(n?.error ?? S);
411
+ t.onError?.(n?.error ?? w);
391
412
  return;
392
413
  }
393
- case f.CLOSE:
414
+ case m.CLOSE:
394
415
  this.closeFromIframe(t, n);
395
416
  return;
396
417
  default: return;
@@ -398,13 +419,13 @@ var y = class {
398
419
  }
399
420
  handleListMessage(e, t, n) {
400
421
  switch (e.type) {
401
- case f.BOOTED:
422
+ case m.BOOTED:
402
423
  this.postInitOnBooted(), t.onBooted?.();
403
424
  return;
404
- case f.READY:
425
+ case m.READY:
405
426
  t.onReady?.();
406
427
  return;
407
- case f.CARD_ACTION: {
428
+ case m.CARD_ACTION: {
408
429
  let n = e.payload ?? {};
409
430
  if (n.action !== "delegate" && n.action !== "revoked" || typeof n.paymentMethodId != "string" || n.paymentMethodId.length === 0) return;
410
431
  t.onCardAction?.({
@@ -413,12 +434,12 @@ var y = class {
413
434
  });
414
435
  return;
415
436
  }
416
- case f.ERROR: {
437
+ case m.ERROR: {
417
438
  let n = e.payload;
418
- t.onError?.(n?.error ?? S);
439
+ t.onError?.(n?.error ?? w);
419
440
  return;
420
441
  }
421
- case f.CLOSE:
442
+ case m.CLOSE:
422
443
  this.closeFromIframe(t, n);
423
444
  return;
424
445
  default: return;
@@ -426,16 +447,16 @@ var y = class {
426
447
  }
427
448
  handleCreateDelegationMessage(e, t, n) {
428
449
  switch (e.type) {
429
- case f.BOOTED:
450
+ case m.BOOTED:
430
451
  this.postInitOnBooted(), t.onBooted?.();
431
452
  return;
432
- case f.READY:
453
+ case m.READY:
433
454
  t.onReady?.();
434
455
  return;
435
- case f.SUCCESS: {
456
+ case m.SUCCESS: {
436
457
  let r = (e.payload ?? {}).delegationId;
437
458
  if (typeof r != "string" || r.length === 0) {
438
- t.onError?.(w);
459
+ t.onError?.(E);
439
460
  return;
440
461
  }
441
462
  t.onSuccess?.({
@@ -447,12 +468,12 @@ var y = class {
447
468
  });
448
469
  return;
449
470
  }
450
- case f.ERROR: {
471
+ case m.ERROR: {
451
472
  let n = e.payload;
452
- t.onError?.(n?.error ?? S);
473
+ t.onError?.(n?.error ?? w);
453
474
  return;
454
475
  }
455
- case f.CLOSE:
476
+ case m.CLOSE:
456
477
  this.closeFromIframe(t, n);
457
478
  return;
458
479
  default: return;
@@ -475,7 +496,7 @@ var y = class {
475
496
  }
476
497
  });
477
498
  } catch (e) {
478
- throw new c(e instanceof Error && e.message ? e.message : t);
499
+ throw new u(e instanceof Error && e.message ? e.message : t);
479
500
  }
480
501
  if (n.ok) return;
481
502
  let r, i = t;
@@ -483,12 +504,12 @@ var y = class {
483
504
  let e = await n.json();
484
505
  typeof e?.message == "string" && e.message.length > 0 && (i = e.message), typeof e?.code == "string" && (r = e.code);
485
506
  } catch {}
486
- throw new c(i, n.status, r);
507
+ throw new u(i, n.status, r);
487
508
  }
488
509
  };
489
510
  //#endregion
490
511
  //#region src/nevermined-widgets.ts
491
- function E(e) {
512
+ function A(e) {
492
513
  if (typeof e != "object" || !e) return !1;
493
514
  let t = e;
494
515
  return [
@@ -498,26 +519,26 @@ function E(e) {
498
519
  "apiKeyHash"
499
520
  ].every((e) => typeof t[e] == "string") && typeof t.userWallet == "string" && t.userWallet.startsWith("0x");
500
521
  }
501
- var D = class t {
522
+ var j = class t {
502
523
  sessionManager;
503
524
  _account;
504
525
  environment;
505
526
  _checkout = null;
506
527
  _delegations = null;
507
- events = new d();
528
+ events = new p();
508
529
  constructor(e, t, n) {
509
530
  this.sessionManager = e, this._account = t, this.environment = n;
510
531
  }
511
532
  static async initialize(n) {
512
533
  let { session: r, environment: i } = n;
513
- if (!r || typeof r != "object") throw new o("MISSING_SESSION");
514
- if (!i || !e.includes(i)) throw new o("INVALID_ENVIRONMENT");
515
- if (!E(r)) throw new o("INVALID_SESSION");
516
- let a = new u(r), s = new t(a, {
534
+ if (!r || typeof r != "object") throw new c("MISSING_SESSION");
535
+ if (!i || !e.includes(i)) throw new c("INVALID_ENVIRONMENT");
536
+ if (!A(r)) throw new c("INVALID_SESSION");
537
+ let a = new f(r), o = new t(a, {
517
538
  userId: r.userId,
518
539
  userWallet: r.userWallet
519
540
  }, i);
520
- return a.startAutoRefresh(() => s.refreshSession(), () => s.events.emit("session-expired", void 0)), s;
541
+ return a.startAutoRefresh(() => o.refreshSession(), () => o.events.emit("session-expired", void 0)), o;
521
542
  }
522
543
  async refreshSession() {
523
544
  let e = await fetch(`${r(this.environment)}/api/v1/widgets/session/refresh`, {
@@ -526,7 +547,7 @@ var D = class t {
526
547
  });
527
548
  if (!e.ok) throw Error(`Session refresh failed with status ${e.status}`);
528
549
  let t = await e.json();
529
- if (!E(t)) throw Error("Session refresh returned an invalid response");
550
+ if (!A(t)) throw Error("Session refresh returned an invalid response");
530
551
  return t;
531
552
  }
532
553
  on(e, t) {
@@ -542,18 +563,18 @@ var D = class t {
542
563
  return this.sessionManager.isValid();
543
564
  }
544
565
  getSessionToken() {
545
- if (!this.sessionManager.isValid()) throw new s();
566
+ if (!this.sessionManager.isValid()) throw new l();
546
567
  return this.sessionManager.getToken();
547
568
  }
548
569
  get checkout() {
549
- return this._checkout ||= new x(this.sessionManager, i(this.environment)), this._checkout;
570
+ return this._checkout ||= new C(this.sessionManager, i(this.environment), o(this.environment)), this._checkout;
550
571
  }
551
572
  get delegations() {
552
- return this._delegations ||= new T(this.sessionManager, i(this.environment), r(this.environment)), this._delegations;
573
+ return this._delegations ||= new k(this.sessionManager, i(this.environment), r(this.environment), o(this.environment)), this._delegations;
553
574
  }
554
575
  destroy() {
555
576
  this.sessionManager.stopAutoRefresh(), this._checkout?.destroy(), this._checkout = null, this._delegations?.destroy(), this._delegations = null, this.events.removeAllListeners();
556
577
  }
557
578
  };
558
579
  //#endregion
559
- export { x as CheckoutWidget, T as DelegationsWidget, y as IframeManager, D as NeverminedWidgets, u as SessionManager, d as TypedEventEmitter, p as WIDGET_MESSAGE_VERSION, c as WidgetApiError, o as WidgetInitError, f as WidgetMessageType, s as WidgetSessionExpiredError, g as createMessage, _ as parseMessage };
580
+ export { C as CheckoutWidget, k as DelegationsWidget, x as IframeManager, j as NeverminedWidgets, f as SessionManager, p as TypedEventEmitter, h as WIDGET_MESSAGE_VERSION, u as WidgetApiError, c as WidgetInitError, m as WidgetMessageType, l as WidgetSessionExpiredError, v as createMess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export declare function getApiBaseUrl(environment: Environment): string;
3
3
  export declare function getWebappBaseUrl(environment: Environment): string;
4
+ export declare function getEmbedBaseUrl(environment: Environment): string;
5
+ export declare function getEmbedNetwork(environment: Environment): 'sandbox' | 'live';
4
6
  //# sourceMappingURL=environment.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../../src/utils/environment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAkB9C,wBAAgB,aAAa,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAE9D;AAED,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAEjE"}
1
+ {"version":3,"file":"environment.d.ts","sourceRoot":"","sources":["../../src/utils/environment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AA8B9C,wBAAgB,aAAa,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAE9D;AAED,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAEjE;AAED,wBAAgB,eAAe,CAAC,WAAW,EAAE,WAAW,GAAG,MAAM,CAEhE;AAkBD,wBAAgB,eAAe,CAAC,WAAW,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,CAE5E"}
@@ -58,10 +58,11 @@ export interface PlanCheckoutOptions {
58
58
  */
59
59
  export declare class CheckoutWidget {
60
60
  private readonly session;
61
- private readonly webappBase;
61
+ private readonly embedBase;
62
+ private readonly embedNetwork;
62
63
  private manager;
63
64
  private destroyed;
64
- constructor(session: SessionManager, webappBase: string);
65
+ constructor(session: SessionManager, embedBase: string, embedNetwork: 'sandbox' | 'live');
65
66
  /**
66
67
  * Mounts the checkout iframe into `options.container`.
67
68
  * Throws if called after `destroy()` (including the implicit destroy on
@@ -1 +1 @@
1
- {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../../src/widgets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;IAqB7C,OAAO,IAAI,IAAI;IAMf;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,KAAK;IAyBb,OAAO,CAAC,aAAa;CAgDtB"}
@@ -52,12 +52,25 @@ export interface ListCardsOptions {
52
52
  onError?: (error: EmbedError) => void;
53
53
  onClose?: () => void;
54
54
  }
55
+ /**
56
+ * Which delegation the create-delegation iframe should create:
57
+ * - `'card'` (default): a card delegation backed by an enrolled payment method
58
+ * (`paymentMethodId` is required and scopes the delegation to that card).
59
+ * - `'crypto'`: an on-chain (ERC-4337) delegation that lets the agent spend
60
+ * USDC from the session user's smart account. There is no card, so
61
+ * `paymentMethodId` is not used.
62
+ */
63
+ export type DelegationProvider = 'card' | 'crypto';
55
64
  export interface CreateDelegationResult {
56
65
  delegationId: string;
57
- paymentMethodId: string;
66
+ /** The card this delegation is scoped to. Absent for crypto delegations. */
67
+ paymentMethodId?: string;
58
68
  }
59
69
  export interface CreateDelegationOptions {
60
- paymentMethodId: string;
70
+ /** Required for `provider: 'card'`; ignored for `provider: 'crypto'`. */
71
+ paymentMethodId?: string;
72
+ /** See `DelegationProvider`. Defaults to `'card'`. */
73
+ provider?: DelegationProvider;
61
74
  container?: HTMLElement;
62
75
  /** See `CheckoutOptions.width`. */
63
76
  width?: number;
@@ -89,28 +102,39 @@ export interface CreateDelegationOptions {
89
102
  */
90
103
  export declare class DelegationsWidget {
91
104
  private readonly session;
92
- private readonly webappBase;
105
+ private readonly embedBase;
93
106
  private readonly apiBase;
107
+ private readonly embedNetwork;
94
108
  private manager;
95
109
  private destroyed;
96
- constructor(session: SessionManager, webappBase: string, apiBase: string);
110
+ constructor(session: SessionManager, embedBase: string, apiBase: string, embedNetwork: 'sandbox' | 'live');
97
111
  /**
98
- * Mounts the enrollment iframe at `/embed/cards/enroll`.
112
+ * Mounts the enrollment iframe at `/cards/enroll`.
99
113
  * Throws if called after `destroy()` (including the implicit destroy on
100
114
  * `nvm:close` — see class JSDoc).
101
115
  */
102
116
  enrollCard(options: EnrollCardOptions): void;
103
117
  /**
104
- * Mounts the cards-list iframe at `/embed/cards/list`. Per-row actions
118
+ * Mounts the cards-list iframe at `/cards/list`. Per-row actions
105
119
  * ("Create Delegation" → `'delegate'`, "Remove Card" → `'revoked'`) are
106
120
  * forwarded via `onCardAction` so the host can react (mount a follow-up
107
121
  * widget, refresh its own list, etc.). See `CardAction`.
108
122
  */
109
123
  listCards(options: ListCardsOptions): void;
110
124
  /**
111
- * Mounts the delegation creation iframe at `/embed/cards/delegate` for a
112
- * specific payment method. The `paymentMethodId` is required and is passed
113
- * as a search param so the embed route can scope the form to that card.
125
+ * Mounts the delegation creation iframe at `/cards/delegate`.
126
+ *
127
+ * The delegation kind is taken from `options.provider` when set; otherwise it
128
+ * is inferred from `paymentMethodId` — a `0x…` wallet address means a crypto
129
+ * (ERC-4337) delegation that spends USDC from the session user's smart
130
+ * account, anything else is a card payment-method id. So callers can simply
131
+ * pass whatever id they hold (a card's pm id, or the user's wallet address)
132
+ * without choosing a provider explicitly.
133
+ *
134
+ * For `'card'` a `paymentMethodId` is required and is forwarded so the embed
135
+ * form scopes the delegation to that card. For `'crypto'` no card is
136
+ * involved, so `paymentMethodId` is not forwarded. The resolved provider is
137
+ * always forwarded as a search param so the form builds the correct payload.
114
138
  */
115
139
  createDelegation(options: CreateDelegationOptions): void;
116
140
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"delegations.d.ts","sourceRoot":"","sources":["../../src/widgets/delegations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAE9C,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAGjE,MAAM,WAAW,gBAAgB;IAC/B,eAAe,EAAE,MAAM,CAAA;CACxB;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,kBAAkB,GAAG,QAAQ,GAAG,WAAW,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Q,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,YAAY;IAP/B,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,SAAS,CAAQ;gBAGN,OAAO,EAAE,cAAc,EACvB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,SAAS,GAAG,MAAM;IAGnD;;;;OAIG;IACH,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI;IAY5C;;;;;OAKG;IACH,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI;IAS1C;;;;;;;;;;;;;;OAcG;IACH,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IA8BxD;;;;OAIG;IACG,UAAU,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUxD;;;;OAIG;IACG,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAU3D,OAAO,IAAI,IAAI;IAMf,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,WAAW;IAwBnB,OAAO,CAAC,gBAAgB;IAMxB,OAAO,CAAC,mBAAmB;IA4C3B,OAAO,CAAC,iBAAiB;IAgDzB,OAAO,CAAC,6BAA6B;IA4CrC;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,kBAAkB;YAMZ,iBAAiB;CAgChC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nevermined-io/ui-widgets",
3
- "version": "0.5.15",
3
+ "version": "0.5.16",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",