@capitalos/react 1.0.0-rc.5 → 1.0.0-rc.6

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/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use client";var X=Object.defineProperty,Y=Object.defineProperties;var Z=Object.getOwnPropertyDescriptors;var A=Object.getOwnPropertySymbols;var N=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var _=(e,t,n)=>t in e?X(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))N.call(t,n)&&_(e,n,t[n]);if(A)for(var n of A(t))j.call(t,n)&&_(e,n,t[n]);return e},c=(e,t)=>Y(e,Z(t));var b=(e,t)=>{var n={};for(var o in e)N.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&A)for(var o of A(e))t.indexOf(o)<0&&j.call(e,o)&&(n[o]=e[o]);return n};var B=(e,t,n)=>new Promise((o,r)=>{var i=p=>{try{a(n.next(p))}catch(m){r(m)}},s=p=>{try{a(n.throw(p))}catch(m){r(m)}},a=p=>p.done?o(p.value):Promise.resolve(p.value).then(i,s);a((n=n.apply(e,t)).next())});import u,{useMemo as f}from"react";import L,{useEffect as G,useMemo as ve,useRef as Q,useState as De,useCallback as Le}from"react";import S,{createContext as Pe,useContext as Ie,useState as D,useMemo as Ee,useCallback as U,useEffect as be}from"react";import ye,{useMemo as Te,useRef as ke}from"react";var h=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},O={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},P=class extends h{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:O.unauthorized}),this.name="CapitalOSInvalidTokenError"}};import{connectToChild as se}from"penpal";import{useEffect as ae,useMemo as de,useRef as V}from"react";var W="1.0.0-rc.5";function re(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function H(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new P}}function ie(e){try{return decodeURIComponent(e)}catch(t){return e}}function K({tokenData:e,renderingContext:t,theme:n,onError:o}){try{let r=t?c(d({},t),{referer:window.location.href}):null,i=r?re(r):null,s=new URL(e.baseUrl),a=ie(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,a):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(a)),s.searchParams.set("sdkVersion",W),i&&s.searchParams.set("renderingContext",i),n&&s.searchParams.set("theme",n),s.toString()}catch(r){o==null||o(new P);return}}function M(e){let n=H(e).path;if(!n||typeof n!="string")throw new P;return{token:e,tokenType:"oneTime",baseUrl:n,paramKey:"token",paramLocation:"search"}}var ce=1e4;function R({iframeRef:e,token:t,onError:n,methods:o}){ae(()=>{if(!e.current)return;let r=se({iframe:e.current,childOrigin:"*",debug:!0,timeout:ce,methods:o});return r.promise.catch(i=>{n==null||n(i)}),()=>{r.destroy()}},[t,e])}function z({tokenData:e,renderingContext:t,theme:n,onError:o}){let r=V(o),i=V(t);return de(()=>{if(e)return K({tokenData:e,renderingContext:i.current,theme:n,onError:r.current})},[e,n,r,i])}import{iframeResizer as pe}from"iframe-resizer";import me,{forwardRef as le,useEffect as ue,useImperativeHandle as fe,useRef as ge}from"react";var v=le((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=xe(e),i=ge(null);return ue(()=>{let s=i.current;return pe(d({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),fe(t,()=>i.current),me.createElement("iframe",c(d({},o),{title:n,ref:i}))});v.displayName="IframeResizer";var he=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],Ce=new Set(he);function xe(e){return Object.keys(e).reduce((n,o)=>(Ce.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function J(e){let{oneTimeToken:t,enableLogging:n,onExchangeComplete:o,onExchangeError:r}=e,i=ke(null),s=Te(()=>M(t),[t]),p=z({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return R({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:m=>{r==null||r(new h(m))},tokenExchange:{onLongLivedToken:o}}}),ye.createElement(v,{src:p,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var $=Pe({isLoading:!1,invalidateToken:()=>{}}),Oe=({getToken:e,enableLogging:t,children:n})=>{let[o,r]=D(void 0),[i,s]=D(void 0),[a,p]=D(void 0),[m,w]=D(!1),[I,x]=D(void 0),T=U(()=>B(void 0,null,function*(){w(!0);try{let g=yield e();r(g),x(void 0);let C=H(g),k=new URL(C.path);k.pathname="",s(k.toString())}catch(g){x(g)}finally{w(!1)}}),[e]),E=U(()=>{p(void 0)},[]);be(()=>{a||T()},[a,T]);let y=U(g=>{p(g),r(void 0),x(void 0)},[]),F=Ee(()=>{if(a&&!i)throw new h({message:"baseUrl is required for long lived tokens",code:O.unauthorized});return{tokenData:a?{token:a,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:m,error:I,invalidateToken:E}},[a,m,I,E,i]);return S.createElement(S.Fragment,null,S.createElement($.Provider,{value:F},n),o&&!a&&S.createElement(J,{oneTimeToken:o,onExchangeComplete:y,enableLogging:t,onExchangeError:x}))},q=()=>Ie($);function l(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:i,renderingContext:s,methods:a,theme:p}=e,{tokenData:m,error:w,invalidateToken:I}=q(),[x,T]=De(!1),E=Q(null);we(w,r);let y=ve(()=>t?M(t):m,[t,m]),F=Le(()=>{if(o&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new h({message:"Token expired. Cannot automatically refresh when using token prop.",code:O.unauthorized}));return}I(),T(!1)},[t,I,o,r]);G(()=>{t&&m&&o&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,m,o]);let g=z({tokenData:y,renderingContext:s,theme:p,onError:r});return R({iframeRef:E,token:y==null?void 0:y.token,onError:C=>{r==null||r(C),T(!0)},methods:d({onLoad:()=>T(!0),onError:C=>{let k=new h(C);r==null||r(k)},onTokenExpired:F},a)}),!y||!g?L.createElement(L.Fragment,null,i||null):L.createElement(L.Fragment,null,!x&&i,L.createElement(v,{src:g,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:E,hidden:!x,onResized:C=>{let k=`${parseInt(C.height)+12}px`;C.iframe.style.height=k}}))}function we(e,t){let n=Q(!1);G(()=>{e&&!n.current&&(t==null||t(e),n.current=!0)},[e,t])}function Ae(e){let t="cardsApp",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}var wt=Ae;function At(r){var i=r,{cardholder:e,onDone:t,onCancel:n}=i,o=b(i,["cardholder","onDone","onCancel"]);let s="createCard",a=f(()=>({entryPoint:s,cardholder:e}),[e]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{createCard:{onDone:t,onCancel:n}}}))}function Mt(r){var i=r,{transactionId:e,onDone:t,onCancel:n}=i,o=b(i,["transactionId","onDone","onCancel"]);let s="createDispute",a=f(()=>({entryPoint:s,transactionId:e}),[e]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{createDispute:{onDone:t,onCancel:n}}}))}function Rt(e){let t="billPayApp",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function zt(e){let t="cardDetails",n=f(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function St(e){let t="accountDetails",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ft(e){let t="accountActions",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ht(e){let t="insightsDashboard",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ut(e){let t="insightsWidget",{widget:n,hideTitle:o,height:r,width:i}=e,s=f(()=>({entryPoint:t,widget:n,hideTitle:o,height:r,width:i}),[t,n,o,r,i]);return u.createElement(l,c(d({},e),{renderingContext:s}))}function _t(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=b(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",a=f(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:n}),[s,t,n]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{onboarding:{onDone:e}}}))}function Nt(n){var o=n,{onDone:e}=o,t=b(o,["onDone"]);let r="makePayment",i=f(()=>({entryPoint:r}),[r]);return u.createElement(l,c(d({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}export{Ft as AccountActions,St as AccountDetails,wt as App,Rt as BillPayApp,Oe as CapitalOsAuthenticationProvider,zt as CardDetails,Ae as CardsApp,Mt as DisputeTransaction,Ht as InsightsDashboard,Ut as InsightsWidget,At as IssueCard,Nt as MakePayment,_t as Onboarding};
1
+ "use client";var Y=Object.defineProperty,Z=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var N=(e,t,n)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))j.call(t,n)&&N(e,n,t[n]);if(w)for(var n of w(t))B.call(t,n)&&N(e,n,t[n]);return e},c=(e,t)=>Z(e,ee(t));var E=(e,t)=>{var n={};for(var o in e)j.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&w)for(var o of w(e))t.indexOf(o)<0&&B.call(e,o)&&(n[o]=e[o]);return n};var W=(e,t,n)=>new Promise((o,r)=>{var i=p=>{try{a(n.next(p))}catch(m){r(m)}},s=p=>{try{a(n.throw(p))}catch(m){r(m)}},a=p=>p.done?o(p.value):Promise.resolve(p.value).then(i,s);a((n=n.apply(e,t)).next())});import u,{useMemo as f}from"react";import D,{useEffect as Q,useMemo as De,useRef as X,useState as Le,useCallback as we}from"react";import z,{createContext as Ie,useContext as Ee,useState as v,useMemo as be,useCallback as _,useEffect as Oe}from"react";import Te,{useMemo as ke,useRef as Pe}from"react";var h=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},b={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},k=class extends h{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:b.unauthorized}),this.name="CapitalOSInvalidTokenError"}};import{connectToChild as ae}from"penpal";import{useEffect as de,useMemo as ce,useRef as J}from"react";var K="1.0.0-rc.6";function ie(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function U(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new k}}function se(e){try{return decodeURIComponent(e)}catch(t){return e}}function V({tokenData:e,renderingContext:t,theme:n,onError:o}){try{let r=t?c(d({},t),{referer:window.location.href}):null,i=r?ie(r):null,s=new URL(e.baseUrl),a=se(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,a):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(a)),s.searchParams.set("sdkVersion",K),i&&s.searchParams.set("renderingContext",i),n&&s.searchParams.set("theme",n),s.toString()}catch(r){o==null||o(new k);return}}function A(e){let n=U(e).path;if(!n||typeof n!="string")throw new k;return{token:e,tokenType:"oneTime",baseUrl:n,paramKey:"token",paramLocation:"search"}}var pe=1e4;function M({iframeRef:e,token:t,onError:n,methods:o}){de(()=>{if(!e.current)return;let r=ae({iframe:e.current,childOrigin:"*",debug:!0,timeout:pe,methods:o});return r.promise.catch(i=>{n==null||n(i)}),()=>{r.destroy()}},[t,e])}function R({tokenData:e,renderingContext:t,theme:n,onError:o}){let r=J(o),i=J(t);return ce(()=>{if(e)return V({tokenData:e,renderingContext:i.current,theme:n,onError:r.current})},[e,n,r,i])}import{iframeResizer as me}from"iframe-resizer";import le,{forwardRef as ue,useEffect as fe,useImperativeHandle as ge,useRef as he}from"react";var O=ue((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=ye(e),i=he(null);return fe(()=>{let s=i.current;return me(d({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),ge(t,()=>i.current),le.createElement("iframe",c(d({},o),{title:n,ref:i}))});O.displayName="IframeResizer";var Ce=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],xe=new Set(Ce);function ye(e){return Object.keys(e).reduce((n,o)=>(xe.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function $(e){let{oneTimeToken:t,enableLogging:n,onExchangeComplete:o,onExchangeError:r}=e,i=Pe(null),s=ke(()=>A(t),[t]),p=R({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return M({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:m=>{r==null||r(new h(m))},tokenExchange:{onLongLivedToken:o}}}),Te.createElement(O,{src:p,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var q=Ie({isLoading:!1,invalidateToken:()=>{}}),ve=({getToken:e,enableLogging:t,children:n})=>{let[o,r]=v(void 0),[i,s]=v(void 0),[a,p]=v(void 0),[m,L]=v(!1),[P,x]=v(void 0),T=_(()=>W(void 0,null,function*(){L(!0);try{let g=yield e();r(g),x(void 0);let F=U(g),C=new URL(F.path);C.pathname="",s(C.toString())}catch(g){x(g)}finally{L(!1)}}),[e]),I=_(()=>{p(void 0)},[]);Oe(()=>{a||T()},[a,T]);let y=_(g=>{p(g),r(void 0),x(void 0)},[]),S=be(()=>{if(a&&!i)throw new h({message:"baseUrl is required for long lived tokens",code:b.unauthorized});return{tokenData:a?{token:a,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:m,error:P,invalidateToken:I}},[a,m,P,I,i]);return z.createElement(z.Fragment,null,z.createElement(q.Provider,{value:S},n),o&&!a&&z.createElement($,{oneTimeToken:o,onExchangeComplete:y,enableLogging:t,onExchangeError:x}))},G=()=>Ee(q);function l(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:i,renderingContext:s,methods:a,theme:p}=e,{tokenData:m,error:L,invalidateToken:P}=G(),[x,T]=Le(!1),I=X(null);Ae(L,r);let y=De(()=>t?A(t):m,[t,m]),S=we(()=>{if(o&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new h({message:"Token expired. Cannot automatically refresh when using token prop.",code:b.unauthorized}));return}P(),T(!1)},[t,P,o,r]);Q(()=>{t&&m&&o&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,m,o]);let g=R({tokenData:y,renderingContext:s,theme:p,onError:r});if(M({iframeRef:I,token:y==null?void 0:y.token,onError:C=>{r==null||r(C),T(!0)},methods:d({onLoad:()=>T(!0),onError:C=>{let H=new h(C);r==null||r(H)},onTokenExpired:S},a)}),!y||!g)return D.createElement(D.Fragment,null,i||null);let F=s.entryPoint!=="insightsWidget";return D.createElement(D.Fragment,null,!x&&i,D.createElement(O,{src:g,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:I,hidden:!x,onResized:C=>{if(!F)return;let H=`${parseInt(C.height)+12}px`;C.iframe.style.height=H}}))}function Ae(e,t){let n=X(!1);Q(()=>{e&&!n.current&&(t==null||t(e),n.current=!0)},[e,t])}function Me(e){let t="cardsApp",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}var At=Me;function Mt(r){var i=r,{cardholder:e,onDone:t,onCancel:n}=i,o=E(i,["cardholder","onDone","onCancel"]);let s="createCard",a=f(()=>({entryPoint:s,cardholder:e}),[e]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{createCard:{onDone:t,onCancel:n}}}))}function Rt(r){var i=r,{transactionId:e,onDone:t,onCancel:n}=i,o=E(i,["transactionId","onDone","onCancel"]);let s="createDispute",a=f(()=>({entryPoint:s,transactionId:e}),[e]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{createDispute:{onDone:t,onCancel:n}}}))}function zt(e){let t="billPayApp",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function St(e){let t="cardDetails",n=f(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ft(e){let t="accountDetails",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ht(e){let t="accountActions",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ut(e){let t="insightsDashboard",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function _t(e){let t="insightsWidget",{widget:n,hideTitle:o,height:r,width:i}=e,s=f(()=>({entryPoint:t,widget:n,hideTitle:o,height:r,width:i}),[t,n,o,r,i]);return u.createElement(l,c(d({},e),{renderingContext:s}))}function Nt(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=E(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",a=f(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:n}),[s,t,n]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{onboarding:{onDone:e}}}))}function jt(n){var o=n,{onDone:e}=o,t=E(o,["onDone"]);let r="makePayment",i=f(()=>({entryPoint:r}),[r]);return u.createElement(l,c(d({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}export{Ht as AccountActions,Ft as AccountDetails,At as App,zt as BillPayApp,ve as CapitalOsAuthenticationProvider,St as CardDetails,Me as CardsApp,Rt as DisputeTransaction,Ut as InsightsDashboard,_t as InsightsWidget,Mt as IssueCard,jt as MakePayment,Nt as Onboarding};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.tsx","../../src/capital-os.tsx","../../src/context/capital-os-authentication-context.tsx","../../src/common/token-exchange-iframe.tsx","../../src/error.ts","../../src/hooks.ts","../../package.json","../../src/utils.ts","../../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => setIsLoaded(true),\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.5\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = Object.keys(props).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n if (resizerOptionsSet.has(key)) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n"],"mappings":"yyBAEA,OAAOA,GAAS,WAAAC,MAAe,QCF/B,OAAOC,GAAS,aAAAC,EAAW,WAAAC,GAAS,UAAAC,EAAQ,YAAAC,GAAU,eAAAC,OAAmB,QCEzE,OAAOC,GAAS,iBAAAC,GAAe,cAAAC,GAAY,YAAAC,EAAU,WAAAC,GAAS,eAAAC,EAAa,aAAAC,OAAiB,QCF5F,OAAOC,IAAS,WAAAC,GAAS,UAAAC,OAAc,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S,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["React","useMemo","React","useEffect","useMemo","useRef","useState","useCallback","React","createContext","useContext","useState","useMemo","useCallback","useEffect","React","useMemo","useRef","CapitalOSError","message","code","ErrorCode","InvalidTokenError","connectToChild","useEffect","useMemo","useRef","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","useEffect","connection","connectToChild","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","useRef","renderingContextRef","useMemo","buildIframeUrl","iframeResizer","React","forwardRef","useEffect","useImperativeHandle","useRef","IframeResizer","forwardRef","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","useRef","useEffect","iframe","iframeResizer","__spreadValues","useImperativeHandle","React","__spreadProps","resizerOptionsSet","acc","key","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","useRef","tokenData","useMemo","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","createContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","useState","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","useCallback","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","useEffect","onExchangeComplete","jwtToken","contextValue","useMemo","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","useContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","useState","iframeRef","useRef","useErrorHandling","tokenData","useMemo","tokenDataFromOneTimeToken","handleTokenExpired","useCallback","CapitalOSError","ErrorCode","useEffect","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","IframeResizer","data","newHeight","errorFired","CardsApp","props","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
1
+ {"version":3,"sources":["../../src/index.tsx","../../src/capital-os.tsx","../../src/context/capital-os-authentication-context.tsx","../../src/common/token-exchange-iframe.tsx","../../src/error.ts","../../src/hooks.ts","../../package.json","../../src/utils.ts","../../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => setIsLoaded(true),\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n // insightsWidget does not need additional padding. also - it supports a height property that needs to be respected.\n const shouldAddPaddingBottom = renderingContext.entryPoint !== 'insightsWidget'\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n if (!shouldAddPaddingBottom) {\n return\n }\n\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.6\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = Object.keys(props).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n if (resizerOptionsSet.has(key)) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n"],"mappings":"2yBAEA,OAAOA,GAAS,WAAAC,MAAe,QCF/B,OAAOC,GAAS,aAAAC,EAAW,WAAAC,GAAS,UAAAC,EAAQ,YAAAC,GAAU,eAAAC,OAAmB,QCEzE,O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,EAAaI,EAAAC,EAAbL,EAAa,CAAX,WAC5B,IAAMM,EAAyB,cACzBC,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAOG,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcR,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["React","useMemo","React","useEffect","useMemo","useRef","useState","useCallback","React","createContext","useContext","useState","useMemo","useCallback","useEffect","React","useMemo","useRef","CapitalOSError","message","code","ErrorCode","InvalidTokenError","connectToChild","useEffect","useMemo","useRef","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","useEffect","connection","connectToChild","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","useRef","renderingContextRef","useMemo","buildIframeUrl","iframeResizer","React","forwardRef","useEffect","useImperativeHandle","useRef","IframeResizer","forwardRef","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","useRef","useEffect","iframe","iframeResizer","__spreadValues","useImperativeHandle","React","__spreadProps","resizerOptionsSet","acc","key","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","useRef","tokenData","useMemo","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","createContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","useState","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","useCallback","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","useEffect","onExchangeComplete","jwtToken","contextValue","useMemo","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","useContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","useState","iframeRef","useRef","useErrorHandling","tokenData","useMemo","tokenDataFromOneTimeToken","handleTokenExpired","useCallback","CapitalOSError","ErrorCode","useEffect","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","shouldAddPaddingBottom","IframeResizer","data","newHeight","errorFired","CardsApp","props","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";"use client";var te=Object.create;var L=Object.defineProperty,ne=Object.defineProperties,oe=Object.getOwnPropertyDescriptor,re=Object.getOwnPropertyDescriptors,ie=Object.getOwnPropertyNames,S=Object.getOwnPropertySymbols,se=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty,W=Object.prototype.propertyIsEnumerable;var B=(e,t,n)=>t in e?L(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,p=(e,t)=>{for(var n in t||(t={}))N.call(t,n)&&B(e,n,t[n]);if(S)for(var n of S(t))W.call(t,n)&&B(e,n,t[n]);return e},l=(e,t)=>ne(e,re(t));var w=(e,t)=>{var n={};for(var o in e)N.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&S)for(var o of S(e))t.indexOf(o)<0&&W.call(e,o)&&(n[o]=e[o]);return n};var ae=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},K=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ie(t))!N.call(e,r)&&r!==n&&L(e,r,{get:()=>t[r],enumerable:!(o=oe(t,r))||o.enumerable});return e};var A=(e,t,n)=>(n=e!=null?te(se(e)):{},K(t||!e||!e.__esModule?L(n,"default",{value:e,enumerable:!0}):n,e)),de=e=>K(L({},"__esModule",{value:!0}),e);var V=(e,t,n)=>new Promise((o,r)=>{var i=u=>{try{d(n.next(u))}catch(f){r(f)}},s=u=>{try{d(n.throw(u))}catch(f){r(f)}},d=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,s);d((n=n.apply(e,t)).next())});var Ae={};ae(Ae,{AccountActions:()=>Oe,AccountDetails:()=>be,App:()=>Te,BillPayApp:()=>Ie,CapitalOsAuthenticationProvider:()=>Y,CardDetails:()=>Ee,CardsApp:()=>ee,DisputeTransaction:()=>Pe,InsightsDashboard:()=>ve,InsightsWidget:()=>De,IssueCard:()=>ke,MakePayment:()=>we,Onboarding:()=>Le});module.exports=de(Ae);var a=A(require("react"));var m=A(require("react"));var c=A(require("react"));var O=A(require("react"));var C=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},M={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},b=class extends C{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:M.unauthorized}),this.name="CapitalOSInvalidTokenError"}};var q=require("penpal"),P=require("react");var J="1.0.0-rc.5";function ue(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function j(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new b}}function fe(e){try{return decodeURIComponent(e)}catch(t){return e}}function $({tokenData:e,renderingContext:t,theme:n,onError:o}){try{let r=t?l(p({},t),{referer:window.location.href}):null,i=r?ue(r):null,s=new URL(e.baseUrl),d=fe(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,d):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(d)),s.searchParams.set("sdkVersion",J),i&&s.searchParams.set("renderingContext",i),n&&s.searchParams.set("theme",n),s.toString()}catch(r){o==null||o(new b);return}}function F(e){let n=j(e).path;if(!n||typeof n!="string")throw new b;return{token:e,tokenType:"oneTime",baseUrl:n,paramKey:"token",paramLocation:"search"}}var ge=1e4;function H({iframeRef:e,token:t,onError:n,methods:o}){(0,P.useEffect)(()=>{if(!e.current)return;let r=(0,q.connectToChild)({iframe:e.current,childOrigin:"*",debug:!0,timeout:ge,methods:o});return r.promise.catch(i=>{n==null||n(i)}),()=>{r.destroy()}},[t,e])}function U({tokenData:e,renderingContext:t,theme:n,onError:o}){let r=(0,P.useRef)(o),i=(0,P.useRef)(t);return(0,P.useMemo)(()=>{if(e)return $({tokenData:e,renderingContext:i.current,theme:n,onError:r.current})},[e,n,r,i])}var G=require("iframe-resizer"),x=A(require("react"));var R=(0,x.forwardRef)((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=xe(e),i=(0,x.useRef)(null);return(0,x.useEffect)(()=>{let s=i.current;return(0,G.iframeResizer)(p({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),(0,x.useImperativeHandle)(t,()=>i.current),x.default.createElement("iframe",l(p({},o),{title:n,ref:i}))});R.displayName="IframeResizer";var he=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],Ce=new Set(he);function xe(e){return Object.keys(e).reduce((n,o)=>(Ce.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function Q(e){let{oneTimeToken:t,enableLogging:n,onExchangeComplete:o,onExchangeError:r}=e,i=(0,O.useRef)(null),s=(0,O.useMemo)(()=>F(t),[t]),u=U({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return H({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:f=>{r==null||r(new C(f))},tokenExchange:{onLongLivedToken:o}}}),O.default.createElement(R,{src:u,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var X=(0,c.createContext)({isLoading:!1,invalidateToken:()=>{}}),Y=({getToken:e,enableLogging:t,children:n})=>{let[o,r]=(0,c.useState)(void 0),[i,s]=(0,c.useState)(void 0),[d,u]=(0,c.useState)(void 0),[f,z]=(0,c.useState)(!1),[v,T]=(0,c.useState)(void 0),I=(0,c.useCallback)(()=>V(void 0,null,function*(){z(!0);try{let h=yield e();r(h),T(void 0);let y=j(h),E=new URL(y.path);E.pathname="",s(E.toString())}catch(h){T(h)}finally{z(!1)}}),[e]),D=(0,c.useCallback)(()=>{u(void 0)},[]);(0,c.useEffect)(()=>{d||I()},[d,I]);let k=(0,c.useCallback)(h=>{u(h),r(void 0),T(void 0)},[]),_=(0,c.useMemo)(()=>{if(d&&!i)throw new C({message:"baseUrl is required for long lived tokens",code:M.unauthorized});return{tokenData:d?{token:d,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:f,error:v,invalidateToken:D}},[d,f,v,D,i]);return c.default.createElement(c.default.Fragment,null,c.default.createElement(X.Provider,{value:_},n),o&&!d&&c.default.createElement(Q,{oneTimeToken:o,onExchangeComplete:k,enableLogging:t,onExchangeError:T}))},Z=()=>(0,c.useContext)(X);function g(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:i,renderingContext:s,methods:d,theme:u}=e,{tokenData:f,error:z,invalidateToken:v}=Z(),[T,I]=(0,m.useState)(!1),D=(0,m.useRef)(null);ye(z,r);let k=(0,m.useMemo)(()=>t?F(t):f,[t,f]),_=(0,m.useCallback)(()=>{if(o&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new C({message:"Token expired. Cannot automatically refresh when using token prop.",code:M.unauthorized}));return}v(),I(!1)},[t,v,o,r]);(0,m.useEffect)(()=>{t&&f&&o&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,f,o]);let h=U({tokenData:k,renderingContext:s,theme:u,onError:r});return H({iframeRef:D,token:k==null?void 0:k.token,onError:y=>{r==null||r(y),I(!0)},methods:p({onLoad:()=>I(!0),onError:y=>{let E=new C(y);r==null||r(E)},onTokenExpired:_},d)}),!k||!h?m.default.createElement(m.default.Fragment,null,i||null):m.default.createElement(m.default.Fragment,null,!T&&i,m.default.createElement(R,{src:h,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:D,hidden:!T,onResized:y=>{let E=`${parseInt(y.height)+12}px`;y.iframe.style.height=E}}))}function ye(e,t){let n=(0,m.useRef)(!1);(0,m.useEffect)(()=>{e&&!n.current&&(t==null||t(e),n.current=!0)},[e,t])}function ee(e){let t="cardsApp",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}var Te=ee;function ke(r){var i=r,{cardholder:e,onDone:t,onCancel:n}=i,o=w(i,["cardholder","onDone","onCancel"]);let s="createCard",d=(0,a.useMemo)(()=>({entryPoint:s,cardholder:e}),[e]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{createCard:{onDone:t,onCancel:n}}}))}function Pe(r){var i=r,{transactionId:e,onDone:t,onCancel:n}=i,o=w(i,["transactionId","onDone","onCancel"]);let s="createDispute",d=(0,a.useMemo)(()=>({entryPoint:s,transactionId:e}),[e]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{createDispute:{onDone:t,onCancel:n}}}))}function Ie(e){let t="billPayApp",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function Ee(e){let t="cardDetails",n=(0,a.useMemo)(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function be(e){let t="accountDetails",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function Oe(e){let t="accountActions",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function ve(e){let t="insightsDashboard",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function De(e){let t="insightsWidget",{widget:n,hideTitle:o,height:r,width:i}=e,s=(0,a.useMemo)(()=>({entryPoint:t,widget:n,hideTitle:o,height:r,width:i}),[t,n,o,r,i]);return a.default.createElement(g,l(p({},e),{renderingContext:s}))}function Le(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=w(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",d=(0,a.useMemo)(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:n}),[s,t,n]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{onboarding:{onDone:e}}}))}function we(n){var o=n,{onDone:e}=o,t=w(o,["onDone"]);let r="makePayment",i=(0,a.useMemo)(()=>({entryPoint:r}),[r]);return a.default.createElement(g,l(p({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}0&&(module.exports={AccountActions,AccountDetails,App,BillPayApp,CapitalOsAuthenticationProvider,CardDetails,CardsApp,DisputeTransaction,InsightsDashboard,InsightsWidget,IssueCard,MakePayment,Onboarding});
1
+ "use strict";"use client";var ne=Object.create;var D=Object.defineProperty,oe=Object.defineProperties,re=Object.getOwnPropertyDescriptor,ie=Object.getOwnPropertyDescriptors,se=Object.getOwnPropertyNames,z=Object.getOwnPropertySymbols,ae=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var W=(e,t,n)=>t in e?D(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,p=(e,t)=>{for(var n in t||(t={}))j.call(t,n)&&W(e,n,t[n]);if(z)for(var n of z(t))K.call(t,n)&&W(e,n,t[n]);return e},l=(e,t)=>oe(e,ie(t));var L=(e,t)=>{var n={};for(var o in e)j.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&z)for(var o of z(e))t.indexOf(o)<0&&K.call(e,o)&&(n[o]=e[o]);return n};var de=(e,t)=>{for(var n in t)D(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of se(t))!j.call(e,r)&&r!==n&&D(e,r,{get:()=>t[r],enumerable:!(o=re(t,r))||o.enumerable});return e};var w=(e,t,n)=>(n=e!=null?ne(ae(e)):{},V(t||!e||!e.__esModule?D(n,"default",{value:e,enumerable:!0}):n,e)),ce=e=>V(D({},"__esModule",{value:!0}),e);var J=(e,t,n)=>new Promise((o,r)=>{var i=u=>{try{d(n.next(u))}catch(f){r(f)}},s=u=>{try{d(n.throw(u))}catch(f){r(f)}},d=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,s);d((n=n.apply(e,t)).next())});var Me={};de(Me,{AccountActions:()=>ve,AccountDetails:()=>Oe,App:()=>ke,BillPayApp:()=>Ee,CapitalOsAuthenticationProvider:()=>Z,CardDetails:()=>be,CardsApp:()=>te,DisputeTransaction:()=>Ie,InsightsDashboard:()=>De,InsightsWidget:()=>Le,IssueCard:()=>Pe,MakePayment:()=>Ae,Onboarding:()=>we});module.exports=ce(Me);var a=w(require("react"));var m=w(require("react"));var c=w(require("react"));var b=w(require("react"));var C=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},A={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},E=class extends C{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:A.unauthorized}),this.name="CapitalOSInvalidTokenError"}};var G=require("penpal"),P=require("react");var $="1.0.0-rc.6";function fe(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function B(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new E}}function ge(e){try{return decodeURIComponent(e)}catch(t){return e}}function q({tokenData:e,renderingContext:t,theme:n,onError:o}){try{let r=t?l(p({},t),{referer:window.location.href}):null,i=r?fe(r):null,s=new URL(e.baseUrl),d=ge(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,d):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(d)),s.searchParams.set("sdkVersion",$),i&&s.searchParams.set("renderingContext",i),n&&s.searchParams.set("theme",n),s.toString()}catch(r){o==null||o(new E);return}}function S(e){let n=B(e).path;if(!n||typeof n!="string")throw new E;return{token:e,tokenType:"oneTime",baseUrl:n,paramKey:"token",paramLocation:"search"}}var he=1e4;function F({iframeRef:e,token:t,onError:n,methods:o}){(0,P.useEffect)(()=>{if(!e.current)return;let r=(0,G.connectToChild)({iframe:e.current,childOrigin:"*",debug:!0,timeout:he,methods:o});return r.promise.catch(i=>{n==null||n(i)}),()=>{r.destroy()}},[t,e])}function H({tokenData:e,renderingContext:t,theme:n,onError:o}){let r=(0,P.useRef)(o),i=(0,P.useRef)(t);return(0,P.useMemo)(()=>{if(e)return q({tokenData:e,renderingContext:i.current,theme:n,onError:r.current})},[e,n,r,i])}var Q=require("iframe-resizer"),x=w(require("react"));var M=(0,x.forwardRef)((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=ye(e),i=(0,x.useRef)(null);return(0,x.useEffect)(()=>{let s=i.current;return(0,Q.iframeResizer)(p({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),(0,x.useImperativeHandle)(t,()=>i.current),x.default.createElement("iframe",l(p({},o),{title:n,ref:i}))});M.displayName="IframeResizer";var Ce=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],xe=new Set(Ce);function ye(e){return Object.keys(e).reduce((n,o)=>(xe.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function X(e){let{oneTimeToken:t,enableLogging:n,onExchangeComplete:o,onExchangeError:r}=e,i=(0,b.useRef)(null),s=(0,b.useMemo)(()=>S(t),[t]),u=H({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return F({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:f=>{r==null||r(new C(f))},tokenExchange:{onLongLivedToken:o}}}),b.default.createElement(M,{src:u,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var Y=(0,c.createContext)({isLoading:!1,invalidateToken:()=>{}}),Z=({getToken:e,enableLogging:t,children:n})=>{let[o,r]=(0,c.useState)(void 0),[i,s]=(0,c.useState)(void 0),[d,u]=(0,c.useState)(void 0),[f,R]=(0,c.useState)(!1),[O,T]=(0,c.useState)(void 0),I=(0,c.useCallback)(()=>J(void 0,null,function*(){R(!0);try{let h=yield e();r(h),T(void 0);let _=B(h),y=new URL(_.path);y.pathname="",s(y.toString())}catch(h){T(h)}finally{R(!1)}}),[e]),v=(0,c.useCallback)(()=>{u(void 0)},[]);(0,c.useEffect)(()=>{d||I()},[d,I]);let k=(0,c.useCallback)(h=>{u(h),r(void 0),T(void 0)},[]),U=(0,c.useMemo)(()=>{if(d&&!i)throw new C({message:"baseUrl is required for long lived tokens",code:A.unauthorized});return{tokenData:d?{token:d,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:f,error:O,invalidateToken:v}},[d,f,O,v,i]);return c.default.createElement(c.default.Fragment,null,c.default.createElement(Y.Provider,{value:U},n),o&&!d&&c.default.createElement(X,{oneTimeToken:o,onExchangeComplete:k,enableLogging:t,onExchangeError:T}))},ee=()=>(0,c.useContext)(Y);function g(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:i,renderingContext:s,methods:d,theme:u}=e,{tokenData:f,error:R,invalidateToken:O}=ee(),[T,I]=(0,m.useState)(!1),v=(0,m.useRef)(null);Te(R,r);let k=(0,m.useMemo)(()=>t?S(t):f,[t,f]),U=(0,m.useCallback)(()=>{if(o&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new C({message:"Token expired. Cannot automatically refresh when using token prop.",code:A.unauthorized}));return}O(),I(!1)},[t,O,o,r]);(0,m.useEffect)(()=>{t&&f&&o&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,f,o]);let h=H({tokenData:k,renderingContext:s,theme:u,onError:r});if(F({iframeRef:v,token:k==null?void 0:k.token,onError:y=>{r==null||r(y),I(!0)},methods:p({onLoad:()=>I(!0),onError:y=>{let N=new C(y);r==null||r(N)},onTokenExpired:U},d)}),!k||!h)return m.default.createElement(m.default.Fragment,null,i||null);let _=s.entryPoint!=="insightsWidget";return m.default.createElement(m.default.Fragment,null,!T&&i,m.default.createElement(M,{src:h,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:v,hidden:!T,onResized:y=>{if(!_)return;let N=`${parseInt(y.height)+12}px`;y.iframe.style.height=N}}))}function Te(e,t){let n=(0,m.useRef)(!1);(0,m.useEffect)(()=>{e&&!n.current&&(t==null||t(e),n.current=!0)},[e,t])}function te(e){let t="cardsApp",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}var ke=te;function Pe(r){var i=r,{cardholder:e,onDone:t,onCancel:n}=i,o=L(i,["cardholder","onDone","onCancel"]);let s="createCard",d=(0,a.useMemo)(()=>({entryPoint:s,cardholder:e}),[e]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{createCard:{onDone:t,onCancel:n}}}))}function Ie(r){var i=r,{transactionId:e,onDone:t,onCancel:n}=i,o=L(i,["transactionId","onDone","onCancel"]);let s="createDispute",d=(0,a.useMemo)(()=>({entryPoint:s,transactionId:e}),[e]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{createDispute:{onDone:t,onCancel:n}}}))}function Ee(e){let t="billPayApp",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function be(e){let t="cardDetails",n=(0,a.useMemo)(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function Oe(e){let t="accountDetails",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function ve(e){let t="accountActions",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function De(e){let t="insightsDashboard",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function Le(e){let t="insightsWidget",{widget:n,hideTitle:o,height:r,width:i}=e,s=(0,a.useMemo)(()=>({entryPoint:t,widget:n,hideTitle:o,height:r,width:i}),[t,n,o,r,i]);return a.default.createElement(g,l(p({},e),{renderingContext:s}))}function we(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=L(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",d=(0,a.useMemo)(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:n}),[s,t,n]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{onboarding:{onDone:e}}}))}function Ae(n){var o=n,{onDone:e}=o,t=L(o,["onDone"]);let r="makePayment",i=(0,a.useMemo)(()=>({entryPoint:r}),[r]);return a.default.createElement(g,l(p({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}0&&(module.exports={AccountActions,AccountDetails,App,BillPayApp,CapitalOsAuthenticationProvider,CardDetails,CardsApp,DisputeTransaction,InsightsDashboard,InsightsWidget,IssueCard,MakePayment,Onboarding});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.tsx","../src/capital-os.tsx","../src/context/capital-os-authentication-context.tsx","../src/common/token-exchange-iframe.tsx","../src/error.ts","../src/hooks.ts","../package.json","../src/utils.ts","../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => setIsLoaded(true),\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.5\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = Object.keys(props).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n if (resizerOptionsSet.has(key)) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n"],"mappings":"2xCAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,oBAAAE,GAAA,mBAAAC,GAAA,QAAAC,GAAA,eAAAC,GAAA,oCAAAC,EAAA,gBAAAC,GAAA,aAAAC,GAAA,uBAAAC,GAAA,sBAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,gBAAAC,GAAA,eAAAC,KAAA,eAAAC,GAAAf,IAEA,IAAAgB,EAA+B,oBCF/B,IAAAC,EAAyE,oBCEzE,IAAAC,EAA4F,oBCF5F,IAAAC,EAAuC,oBCGhC,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE,MAAMD,CAAO,EACb,KAAK,KAAO,iBACZ,KAAK,KAAOC,CACd,CACF,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AC,CAAM,EAAIT,EACvCR,KAAmB,WACvB,KAAO,CAAE,WAAAD,EAAY,OAAAe,EAAQ,UAAAC,EAAW,OAAAC,EAAQ,MAAAC,CAAM,GACtD,CAAClB,EAAYe,EAAQC,EAAWC,EAAQC,CAAK,CAC/C,EAEA,OAAO,EAAAhB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBR,GAAkB,CACnE,CAgBO,SAASkB,GAA2C1B,EAKpC,CALoC,IAAAC,EAAAD,EACzD,QAAAG,EACA,WAAYwB,EACZ,UAAWC,CAhPb,EA6O2D3B,EAItDI,EAAAC,EAJsDL,EAItD,CAHH,SACA,aACA,cAMA,IAAMM,EAAyB,aACzBC,KAAmB,WACvB,KAAO,CAAE,WAAAD,EAAY,qBAAAoB,EAAsB,oBAAAC,CAAoB,GAC/D,CAACrB,EAAYoB,EAAsBC,CAAmB,CACxD,EAEA,OAAO,EAAAnB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G,CAcO,SAAS0B,GAAY7B,EAA8C,CAA9C,IAAAC,EAAAD,EAAE,QAAAG,CA3Q9B,EA2Q4BF,EAAaI,EAAAC,EAAbL,EAAa,CAAX,WAC5B,IAAMM,EAAyB,cACzBC,KAAmB,WAAQ,KAAO,CAAE,WAAAD,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAO,EAAAE,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["src_exports","__export","AccountActions","AccountDetails","App","BillPayApp","CapitalOsAuthenticationProvider","CardDetails","CardsApp","DisputeTransaction","InsightsDashboard","InsightsWidget","IssueCard","MakePayment","Onboarding","__toCommonJS","import_react","import_react","import_react","import_react","CapitalOSError","message","code","ErrorCode","InvalidTokenError","import_penpal","import_react","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","connection","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","renderingContextRef","buildIframeUrl","import_iframe_resizer","import_react","IframeResizer","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","iframe","__spreadValues","React","__spreadProps","resizerOptionsSet","acc","key","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","tokenData","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","onExchangeComplete","jwtToken","contextValue","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","iframeRef","useErrorHandling","tokenData","tokenDataFromOneTimeToken","handleTokenExpired","CapitalOSError","ErrorCode","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","IframeResizer","data","newHeight","errorFired","CardsApp","props","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
1
+ {"version":3,"sources":["../src/index.tsx","../src/capital-os.tsx","../src/context/capital-os-authentication-context.tsx","../src/common/token-exchange-iframe.tsx","../src/error.ts","../src/hooks.ts","../package.json","../src/utils.ts","../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => setIsLoaded(true),\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n // insightsWidget does not need additional padding. also - it supports a height property that needs to be respected.\n const shouldAddPaddingBottom = renderingContext.entryPoint !== 'insightsWidget'\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n if (!shouldAddPaddingBottom) {\n return\n }\n\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.6\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = Object.keys(props).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n if (resizerOptionsSet.has(key)) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n"],"mappings":"2xCAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,oBAAAE,GAAA,mBAAAC,GAAA,QAAAC,GAAA,eAAAC,GAAA,oCAAAC,EAAA,gBAAAC,GAAA,aAAAC,GAAA,uBAAAC,GAAA,sBAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,gBAAAC,GAAA,eAAAC,KAAA,eAAAC,GAAAf,IAEA,IAAAgB,EAA+B,oBCF/B,IAAAC,EAAyE,oBCEzE,IAAAC,EAA4F,oBCF5F,IAAAC,EAAuC,oBCGhC,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE,MAAMD,CAAO,EACb,KAAK,KAAO,iBACZ,KAAK,KA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L,EAA4B,CACzD,IAAMT,EAAyB,iBACzB,CAAE,OAAAe,EAAQ,UAAAC,EAAW,OAAAC,EAAQ,MAAAC,CAAM,EAAIT,EACvCR,KAAmB,WACvB,KAAO,CAAE,WAAAD,EAAY,OAAAe,EAAQ,UAAAC,EAAW,OAAAC,EAAQ,MAAAC,CAAM,GACtD,CAAClB,EAAYe,EAAQC,EAAWC,EAAQC,CAAK,CAC/C,EAEA,OAAO,EAAAhB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBR,GAAkB,CACnE,CAgBO,SAASkB,GAA2C1B,EAKpC,CALoC,IAAAC,EAAAD,EACzD,QAAAG,EACA,WAAYwB,EACZ,UAAWC,CAhPb,EA6O2D3B,EAItDI,EAAAC,EAJsDL,EAItD,CAHH,SACA,aACA,cAMA,IAAMM,EAAyB,aACzBC,KAAmB,WACvB,KAAO,CAAE,WAAAD,EAAY,qBAAAoB,EAAsB,oBAAAC,CAAoB,GAC/D,CAACrB,EAAYoB,EAAsBC,CAAmB,CACxD,EAEA,OAAO,EAAAnB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G,CAcO,SAAS0B,GAAY7B,EAA8C,CAA9C,IAAAC,EAAAD,EAAE,QAAAG,CA3Q9B,EA2Q4BF,EAAaI,EAAAC,EAAbL,EAAa,CAAX,WAC5B,IAAMM,EAAyB,cACzBC,KAAmB,WAAQ,KAAO,CAAE,WAAAD,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAO,EAAAE,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["src_exports","__export","AccountActions","AccountDetails","App","BillPayApp","CapitalOsAuthenticationProvider","CardDetails","CardsApp","DisputeTransaction","InsightsDashboard","InsightsWidget","IssueCard","MakePayment","Onboarding","__toCommonJS","import_react","import_react","import_react","import_react","CapitalOSError","message","code","ErrorCode","InvalidTokenError","import_penpal","import_react","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","connection","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","renderingContextRef","buildIframeUrl","import_iframe_resizer","import_react","IframeResizer","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","iframe","__spreadValues","React","__spreadProps","resizerOptionsSet","acc","key","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","tokenData","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","onExchangeComplete","jwtToken","contextValue","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","iframeRef","useErrorHandling","tokenData","tokenDataFromOneTimeToken","handleTokenExpired","CapitalOSError","ErrorCode","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","shouldAddPaddingBottom","IframeResizer","data","newHeight","errorFired","CardsApp","props","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capitalos/react",
3
- "version": "1.0.0-rc.5",
3
+ "version": "1.0.0-rc.6",
4
4
  "description": "integrate CapitalOS into your react app",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/esm/index.js",