@capitalos/react 1.0.0-rc.2 → 1.0.0-rc.3

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/README.md CHANGED
@@ -47,6 +47,6 @@ function MyComponent() {
47
47
  }
48
48
  ```
49
49
 
50
- ## Typecsript support
50
+ ## TypeScript support
51
51
 
52
52
  TypeScript definitions for `@capitalos/react` are built into the npm package and should be automatically picked up by your editor.
@@ -45,11 +45,37 @@ export declare function BillPayApp(props: BillPayAppProps): JSX.Element;
45
45
 
46
46
  export declare type BillPayAppProps = CommonProps;
47
47
 
48
+ /**
49
+ * Builds the iframe url from token data, rendering context, and theme.
50
+ */
51
+ export declare function buildIframeUrl({ tokenData, renderingContext, theme, onError, }: {
52
+ tokenData: TokenData;
53
+ renderingContext: CapitalOsRenderingContext;
54
+ theme?: ThemeColorScheme | undefined;
55
+ onError?: ((error: Error) => void) | undefined;
56
+ }): string | undefined;
57
+
48
58
  /**
49
59
  * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.
50
60
  * all user facing components are basically a syntactic sugar on top of this.
51
61
  */
52
- export declare function CapitalOS<T extends RenderingContext_2>(props: CapitalOsProps<T>): JSX.Element;
62
+ export declare function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>): JSX.Element;
63
+
64
+ declare type CapitalOsAuthenticationContextType = {
65
+ tokenData?: TokenData | undefined;
66
+ isLoading: boolean;
67
+ error?: Error | undefined;
68
+ /**
69
+ * Invalidates the current token..
70
+ * This is used when the iframe signals that the token has expired.
71
+ * The authentication flow will automatically refresh the token after invalidation.
72
+ */
73
+ invalidateToken: () => void;
74
+ };
75
+
76
+ declare const CapitalOsAuthenticationProvider: React_2.FC<ProviderProps>;
77
+ export { CapitalOsAuthenticationProvider }
78
+ export { CapitalOsAuthenticationProvider as CapitalOsAuthenticationProvider_alias_1 }
53
79
 
54
80
  /**
55
81
  * Base class for all SDK errors
@@ -62,11 +88,16 @@ export declare class CapitalOSError extends Error {
62
88
  });
63
89
  }
64
90
 
65
- declare type CapitalOsProps<T extends RenderingContext_2> = CommonProps & {
91
+ declare type CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {
66
92
  renderingContext: T;
67
93
  methods?: Partial<IframeConnectionMethods>;
68
94
  };
69
95
 
96
+ export declare type CapitalOsRenderingContext = {
97
+ entryPoint?: EntryPoint;
98
+ referer?: string;
99
+ };
100
+
70
101
  export declare type CardApiDto = z_2.infer<typeof cardApiDtoSchema>;
71
102
 
72
103
  declare const cardApiDtoSchema: z_2.ZodObject<{
@@ -401,7 +432,7 @@ export declare type CommonProps = {
401
432
  /**
402
433
  * The token provided by initiate-login.
403
434
  */
404
- token: string;
435
+ token?: string;
405
436
  /**
406
437
  * Optional CSS class name for the component.
407
438
  */
@@ -419,12 +450,12 @@ export declare type CommonProps = {
419
450
  */
420
451
  loadingComponent?: ReactNode;
421
452
  /**
422
- * Optional theme to apply to the app or component.
453
+ * Optional theme color scheme to apply to the app or component.
423
454
  */
424
- theme?: 'light' | 'dark' | 'system';
455
+ theme?: ThemeColorScheme;
425
456
  };
426
457
 
427
- export declare function decodeToken(token: string): any;
458
+ export declare function decodeOneTimeToken(token: string): any;
428
459
 
429
460
  /**
430
461
  * Renders the CapitalOS Dispute Transaction experience.
@@ -451,12 +482,13 @@ export declare type DisputeTransactionProps = CommonProps & {
451
482
  */
452
483
  export declare function encodeRenderingContext<T>(renderingContext: NonNullable<T>): string;
453
484
 
454
- export declare type EntryPoint = RenderingContext_3['entryPoint'];
485
+ export declare type EntryPoint = RenderingContext_2['entryPoint'];
455
486
 
456
487
  export declare const ErrorCode: {
457
488
  readonly unauthorized: "unauthorized";
458
489
  readonly invalid_account_status: "invalid_account_status";
459
490
  readonly unsupported_entry_point: "unsupported_entry_point";
491
+ readonly internal_error: "internal_error";
460
492
  };
461
493
 
462
494
  export declare type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
@@ -464,6 +496,12 @@ export declare type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
464
496
  export declare type IframeConnectionMethods = {
465
497
  onLoad: () => void;
466
498
  onError: (error: RawErrorDetails) => void;
499
+ /**
500
+ * Called when the iframe detects that the JWT token has expired.
501
+ * This triggers the token refresh flow, which will obtain a new token
502
+ * and reload the iframe with the fresh token.
503
+ */
504
+ onTokenExpired?: () => void;
467
505
  createCard?: {
468
506
  onDone?: () => void;
469
507
  onCancel?: () => void;
@@ -475,6 +513,12 @@ export declare type IframeConnectionMethods = {
475
513
  onboarding?: {
476
514
  onDone?: (account: Account) => void;
477
515
  };
516
+ tokenExchange?: {
517
+ onLongLivedToken?: (jwtToken: string) => void;
518
+ };
519
+ makePayment?: {
520
+ onDone?: () => void;
521
+ };
478
522
  };
479
523
 
480
524
  export declare const IframeResizer: React_2.ForwardRefExoticComponent<Omit<IFrameOptions, "closedCallback" | "scrollCallback" | "resizedCallback" | "messageCallback" | "initCallback"> & {
@@ -508,7 +552,7 @@ export declare type InsightsWidgetProps = CommonProps & {
508
552
  * Represents an error that occurs when an invalid token is encountered.
509
553
  */
510
554
  export declare class InvalidTokenError extends CapitalOSError {
511
- constructor();
555
+ constructor(message?: string);
512
556
  }
513
557
 
514
558
  /**
@@ -555,6 +599,18 @@ export declare type IssueCardProps = CommonProps & {
555
599
  onCancel: () => void;
556
600
  };
557
601
 
602
+ /**
603
+ * Renders the CapitalOS Make a Payment experience.
604
+ */
605
+ export declare function MakePayment({ onDone, ...restOfProps }: MakePaymentProps): JSX.Element;
606
+
607
+ export declare type MakePaymentProps = CommonProps & {
608
+ /**
609
+ * Callback to invoke when the payment was made successfully.
610
+ */
611
+ onDone: () => void;
612
+ };
613
+
558
614
  export declare function Onboarding<T extends OnboardingEntryPoint>({ onDone, entryPoint: onboardingEntryPoint, exitPoint: onboardingExitPoint, ...restOfProps }: OnboardingProps<T>): JSX.Element;
559
615
 
560
616
  declare type OnboardingEntryPoint = keyof AllowedExitPoints;
@@ -565,6 +621,12 @@ declare type OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps &
565
621
  onDone: (account: Account) => void;
566
622
  };
567
623
 
624
+ declare type ProviderProps = {
625
+ getToken: () => Promise<string>;
626
+ enableLogging?: boolean | undefined;
627
+ children: React_2.ReactNode;
628
+ };
629
+
568
630
  /**
569
631
  * An error type providing a reason code and message.
570
632
  * Penpal only passes plain objects, so this does not inherit from Error.
@@ -574,12 +636,7 @@ export declare type RawErrorDetails = {
574
636
  message: string;
575
637
  };
576
638
 
577
- declare type RenderingContext_2 = {
578
- entryPoint?: EntryPoint;
579
- referer?: string;
580
- };
581
-
582
- declare type RenderingContext_3 = z.infer<typeof renderingContextSchema>;
639
+ declare type RenderingContext_2 = z.infer<typeof renderingContextSchema>;
583
640
 
584
641
  declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<"entryPoint", [z.ZodObject<{
585
642
  entryPoint: z.ZodLiteral<"createCard">;
@@ -692,6 +749,18 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
692
749
  entryPoint: "cardsApp";
693
750
  }, {
694
751
  entryPoint: "cardsApp";
752
+ }>, z.ZodObject<{
753
+ entryPoint: z.ZodLiteral<"tokenExchange">;
754
+ }, "strip", z.ZodTypeAny, {
755
+ entryPoint: "tokenExchange";
756
+ }, {
757
+ entryPoint: "tokenExchange";
758
+ }>, z.ZodObject<{
759
+ entryPoint: z.ZodLiteral<"makePayment">;
760
+ }, "strip", z.ZodTypeAny, {
761
+ entryPoint: "makePayment";
762
+ }, {
763
+ entryPoint: "makePayment";
695
764
  }>]>, z.ZodObject<{
696
765
  referer: z.ZodOptional<z.ZodNullable<z.ZodString>>;
697
766
  }, "strip", z.ZodTypeAny, {
@@ -700,14 +769,80 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
700
769
  referer?: string | null | undefined;
701
770
  }>>;
702
771
 
772
+ /**
773
+ * Safely decodes a URL component, handling potential errors
774
+ */
775
+ export declare function safeDecodeURIComponent(str: string): string;
776
+
777
+ export declare type ThemeColorScheme = 'light' | 'dark' | 'system';
778
+
779
+ export declare type TokenData = {
780
+ token: string;
781
+ tokenType: TokenType;
782
+ baseUrl: string;
783
+ paramKey: TokenParamKey;
784
+ paramLocation: TokenParamLocation;
785
+ };
786
+
787
+ export declare function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData;
788
+
789
+ /**
790
+ * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.
791
+ *
792
+ * The token exchange process works as follows:
793
+ * 1. Component renders a hidden iframe with the one-time token in the URL
794
+ * 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
795
+ * 3. The iframe passes the long-lived token to the parent via postMessage
796
+ * 4. onExchangeComplete callback is triggered with the new JWT
797
+ *
798
+ * If any errors occur during this process, they are passed to onExchangeError.
799
+ */
800
+ export declare function TokenExchangeIframe(props: TokenExchangeIframeProps): JSX.Element;
801
+
802
+ export declare interface TokenExchangeIframeProps {
803
+ oneTimeToken: string;
804
+ enableLogging?: boolean | undefined;
805
+ onExchangeComplete: (jwtToken: string) => void;
806
+ onExchangeError?: (error: Error) => void;
807
+ }
808
+
809
+ export declare enum TokenParamKey {
810
+ token = "token",
811
+ accessToken = "access_token"
812
+ }
813
+
814
+ export declare enum TokenParamLocation {
815
+ search = "search",
816
+ hash = "hash"
817
+ }
818
+
819
+ export declare class TokenRefreshError extends CapitalOSError {
820
+ constructor(originalError?: Error);
821
+ }
822
+
823
+ export declare enum TokenType {
824
+ oneTime = "oneTime",
825
+ longLived = "longLived"
826
+ }
827
+
828
+ export declare const useCapitalOsAuthContext: () => CapitalOsAuthenticationContextType;
829
+
703
830
  /**
704
831
  * connects to child iframe and returns whether the iframe is loaded or not.
832
+ * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.
705
833
  */
706
834
  export declare function useIframeConnection({ iframeRef, token, onError, methods, }: {
707
835
  iframeRef: React.RefObject<HTMLIFrameElement>;
708
- token: string;
836
+ token: string | undefined;
709
837
  onError: ((error: Error) => void) | undefined | null;
710
838
  methods: IframeConnectionMethods;
711
839
  }): void;
712
840
 
841
+ export declare function useIframeUrl({ tokenData, renderingContext, theme, onError, }: {
842
+ tokenData: TokenData | undefined;
843
+ renderingContext: CapitalOsRenderingContext;
844
+ theme?: ThemeColorScheme | undefined;
845
+ onError?: ((error: Error) => void) | undefined;
846
+ }): string | undefined;
847
+
713
848
  export { }
@@ -45,11 +45,37 @@ export declare function BillPayApp(props: BillPayAppProps): JSX.Element;
45
45
 
46
46
  export declare type BillPayAppProps = CommonProps;
47
47
 
48
+ /**
49
+ * Builds the iframe url from token data, rendering context, and theme.
50
+ */
51
+ export declare function buildIframeUrl({ tokenData, renderingContext, theme, onError, }: {
52
+ tokenData: TokenData;
53
+ renderingContext: CapitalOsRenderingContext;
54
+ theme?: ThemeColorScheme | undefined;
55
+ onError?: ((error: Error) => void) | undefined;
56
+ }): string | undefined;
57
+
48
58
  /**
49
59
  * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.
50
60
  * all user facing components are basically a syntactic sugar on top of this.
51
61
  */
52
- export declare function CapitalOS<T extends RenderingContext_2>(props: CapitalOsProps<T>): JSX.Element;
62
+ export declare function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>): JSX.Element;
63
+
64
+ declare type CapitalOsAuthenticationContextType = {
65
+ tokenData?: TokenData | undefined;
66
+ isLoading: boolean;
67
+ error?: Error | undefined;
68
+ /**
69
+ * Invalidates the current token..
70
+ * This is used when the iframe signals that the token has expired.
71
+ * The authentication flow will automatically refresh the token after invalidation.
72
+ */
73
+ invalidateToken: () => void;
74
+ };
75
+
76
+ declare const CapitalOsAuthenticationProvider: React_2.FC<ProviderProps>;
77
+ export { CapitalOsAuthenticationProvider }
78
+ export { CapitalOsAuthenticationProvider as CapitalOsAuthenticationProvider_alias_1 }
53
79
 
54
80
  /**
55
81
  * Base class for all SDK errors
@@ -62,11 +88,16 @@ export declare class CapitalOSError extends Error {
62
88
  });
63
89
  }
64
90
 
65
- declare type CapitalOsProps<T extends RenderingContext_2> = CommonProps & {
91
+ declare type CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {
66
92
  renderingContext: T;
67
93
  methods?: Partial<IframeConnectionMethods>;
68
94
  };
69
95
 
96
+ export declare type CapitalOsRenderingContext = {
97
+ entryPoint?: EntryPoint;
98
+ referer?: string;
99
+ };
100
+
70
101
  export declare type CardApiDto = z_2.infer<typeof cardApiDtoSchema>;
71
102
 
72
103
  declare const cardApiDtoSchema: z_2.ZodObject<{
@@ -401,7 +432,7 @@ export declare type CommonProps = {
401
432
  /**
402
433
  * The token provided by initiate-login.
403
434
  */
404
- token: string;
435
+ token?: string;
405
436
  /**
406
437
  * Optional CSS class name for the component.
407
438
  */
@@ -419,12 +450,12 @@ export declare type CommonProps = {
419
450
  */
420
451
  loadingComponent?: ReactNode;
421
452
  /**
422
- * Optional theme to apply to the app or component.
453
+ * Optional theme color scheme to apply to the app or component.
423
454
  */
424
- theme?: 'light' | 'dark' | 'system';
455
+ theme?: ThemeColorScheme;
425
456
  };
426
457
 
427
- export declare function decodeToken(token: string): any;
458
+ export declare function decodeOneTimeToken(token: string): any;
428
459
 
429
460
  /**
430
461
  * Renders the CapitalOS Dispute Transaction experience.
@@ -451,12 +482,13 @@ export declare type DisputeTransactionProps = CommonProps & {
451
482
  */
452
483
  export declare function encodeRenderingContext<T>(renderingContext: NonNullable<T>): string;
453
484
 
454
- export declare type EntryPoint = RenderingContext_3['entryPoint'];
485
+ export declare type EntryPoint = RenderingContext_2['entryPoint'];
455
486
 
456
487
  export declare const ErrorCode: {
457
488
  readonly unauthorized: "unauthorized";
458
489
  readonly invalid_account_status: "invalid_account_status";
459
490
  readonly unsupported_entry_point: "unsupported_entry_point";
491
+ readonly internal_error: "internal_error";
460
492
  };
461
493
 
462
494
  export declare type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
@@ -464,6 +496,12 @@ export declare type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
464
496
  export declare type IframeConnectionMethods = {
465
497
  onLoad: () => void;
466
498
  onError: (error: RawErrorDetails) => void;
499
+ /**
500
+ * Called when the iframe detects that the JWT token has expired.
501
+ * This triggers the token refresh flow, which will obtain a new token
502
+ * and reload the iframe with the fresh token.
503
+ */
504
+ onTokenExpired?: () => void;
467
505
  createCard?: {
468
506
  onDone?: () => void;
469
507
  onCancel?: () => void;
@@ -475,6 +513,12 @@ export declare type IframeConnectionMethods = {
475
513
  onboarding?: {
476
514
  onDone?: (account: Account) => void;
477
515
  };
516
+ tokenExchange?: {
517
+ onLongLivedToken?: (jwtToken: string) => void;
518
+ };
519
+ makePayment?: {
520
+ onDone?: () => void;
521
+ };
478
522
  };
479
523
 
480
524
  export declare const IframeResizer: React_2.ForwardRefExoticComponent<Omit<IFrameOptions, "closedCallback" | "scrollCallback" | "resizedCallback" | "messageCallback" | "initCallback"> & {
@@ -508,7 +552,7 @@ export declare type InsightsWidgetProps = CommonProps & {
508
552
  * Represents an error that occurs when an invalid token is encountered.
509
553
  */
510
554
  export declare class InvalidTokenError extends CapitalOSError {
511
- constructor();
555
+ constructor(message?: string);
512
556
  }
513
557
 
514
558
  /**
@@ -555,6 +599,18 @@ export declare type IssueCardProps = CommonProps & {
555
599
  onCancel: () => void;
556
600
  };
557
601
 
602
+ /**
603
+ * Renders the CapitalOS Make a Payment experience.
604
+ */
605
+ export declare function MakePayment({ onDone, ...restOfProps }: MakePaymentProps): JSX.Element;
606
+
607
+ export declare type MakePaymentProps = CommonProps & {
608
+ /**
609
+ * Callback to invoke when the payment was made successfully.
610
+ */
611
+ onDone: () => void;
612
+ };
613
+
558
614
  export declare function Onboarding<T extends OnboardingEntryPoint>({ onDone, entryPoint: onboardingEntryPoint, exitPoint: onboardingExitPoint, ...restOfProps }: OnboardingProps<T>): JSX.Element;
559
615
 
560
616
  declare type OnboardingEntryPoint = keyof AllowedExitPoints;
@@ -565,6 +621,12 @@ declare type OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps &
565
621
  onDone: (account: Account) => void;
566
622
  };
567
623
 
624
+ declare type ProviderProps = {
625
+ getToken: () => Promise<string>;
626
+ enableLogging?: boolean | undefined;
627
+ children: React_2.ReactNode;
628
+ };
629
+
568
630
  /**
569
631
  * An error type providing a reason code and message.
570
632
  * Penpal only passes plain objects, so this does not inherit from Error.
@@ -574,12 +636,7 @@ export declare type RawErrorDetails = {
574
636
  message: string;
575
637
  };
576
638
 
577
- declare type RenderingContext_2 = {
578
- entryPoint?: EntryPoint;
579
- referer?: string;
580
- };
581
-
582
- declare type RenderingContext_3 = z.infer<typeof renderingContextSchema>;
639
+ declare type RenderingContext_2 = z.infer<typeof renderingContextSchema>;
583
640
 
584
641
  declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<"entryPoint", [z.ZodObject<{
585
642
  entryPoint: z.ZodLiteral<"createCard">;
@@ -692,6 +749,18 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
692
749
  entryPoint: "cardsApp";
693
750
  }, {
694
751
  entryPoint: "cardsApp";
752
+ }>, z.ZodObject<{
753
+ entryPoint: z.ZodLiteral<"tokenExchange">;
754
+ }, "strip", z.ZodTypeAny, {
755
+ entryPoint: "tokenExchange";
756
+ }, {
757
+ entryPoint: "tokenExchange";
758
+ }>, z.ZodObject<{
759
+ entryPoint: z.ZodLiteral<"makePayment">;
760
+ }, "strip", z.ZodTypeAny, {
761
+ entryPoint: "makePayment";
762
+ }, {
763
+ entryPoint: "makePayment";
695
764
  }>]>, z.ZodObject<{
696
765
  referer: z.ZodOptional<z.ZodNullable<z.ZodString>>;
697
766
  }, "strip", z.ZodTypeAny, {
@@ -700,14 +769,80 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
700
769
  referer?: string | null | undefined;
701
770
  }>>;
702
771
 
772
+ /**
773
+ * Safely decodes a URL component, handling potential errors
774
+ */
775
+ export declare function safeDecodeURIComponent(str: string): string;
776
+
777
+ export declare type ThemeColorScheme = 'light' | 'dark' | 'system';
778
+
779
+ export declare type TokenData = {
780
+ token: string;
781
+ tokenType: TokenType;
782
+ baseUrl: string;
783
+ paramKey: TokenParamKey;
784
+ paramLocation: TokenParamLocation;
785
+ };
786
+
787
+ export declare function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData;
788
+
789
+ /**
790
+ * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.
791
+ *
792
+ * The token exchange process works as follows:
793
+ * 1. Component renders a hidden iframe with the one-time token in the URL
794
+ * 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
795
+ * 3. The iframe passes the long-lived token to the parent via postMessage
796
+ * 4. onExchangeComplete callback is triggered with the new JWT
797
+ *
798
+ * If any errors occur during this process, they are passed to onExchangeError.
799
+ */
800
+ export declare function TokenExchangeIframe(props: TokenExchangeIframeProps): JSX.Element;
801
+
802
+ export declare interface TokenExchangeIframeProps {
803
+ oneTimeToken: string;
804
+ enableLogging?: boolean | undefined;
805
+ onExchangeComplete: (jwtToken: string) => void;
806
+ onExchangeError?: (error: Error) => void;
807
+ }
808
+
809
+ export declare enum TokenParamKey {
810
+ token = "token",
811
+ accessToken = "access_token"
812
+ }
813
+
814
+ export declare enum TokenParamLocation {
815
+ search = "search",
816
+ hash = "hash"
817
+ }
818
+
819
+ export declare class TokenRefreshError extends CapitalOSError {
820
+ constructor(originalError?: Error);
821
+ }
822
+
823
+ export declare enum TokenType {
824
+ oneTime = "oneTime",
825
+ longLived = "longLived"
826
+ }
827
+
828
+ export declare const useCapitalOsAuthContext: () => CapitalOsAuthenticationContextType;
829
+
703
830
  /**
704
831
  * connects to child iframe and returns whether the iframe is loaded or not.
832
+ * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.
705
833
  */
706
834
  export declare function useIframeConnection({ iframeRef, token, onError, methods, }: {
707
835
  iframeRef: React.RefObject<HTMLIFrameElement>;
708
- token: string;
836
+ token: string | undefined;
709
837
  onError: ((error: Error) => void) | undefined | null;
710
838
  methods: IframeConnectionMethods;
711
839
  }): void;
712
840
 
841
+ export declare function useIframeUrl({ tokenData, renderingContext, theme, onError, }: {
842
+ tokenData: TokenData | undefined;
843
+ renderingContext: CapitalOsRenderingContext;
844
+ theme?: ThemeColorScheme | undefined;
845
+ onError?: ((error: Error) => void) | undefined;
846
+ }): string | undefined;
847
+
713
848
  export { }
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use client";var H=Object.defineProperty,S=Object.defineProperties;var _=Object.getOwnPropertyDescriptors;var y=Object.getOwnPropertySymbols;var A=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable;var D=(e,t,n)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,i=(e,t)=>{for(var n in t||(t={}))A.call(t,n)&&D(e,n,t[n]);if(y)for(var n of y(t))v.call(t,n)&&D(e,n,t[n]);return e},a=(e,t)=>S(e,_(t));var x=(e,t)=>{var n={};for(var o in e)A.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&y)for(var o of y(e))t.indexOf(o)<0&&v.call(e,o)&&(n[o]=e[o]);return n};import m,{useMemo as l}from"react";import P,{useMemo as Z,useRef as ee,useState as te}from"react";var M="1.0.0-rc.2";var C=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},W={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point"},g=class extends C{constructor(){super({message:"Invalid token",code:W.unauthorized}),this.name="CapitalOSInvalidTokenError"}};import{connectToChild as j}from"penpal";import{useEffect as B}from"react";var $=1e4;function w({iframeRef:e,token:t,onError:n,methods:o}){B(()=>{let r=j({iframe:e.current,childOrigin:"*",debug:!0,timeout:$,methods:o});return r.promise.catch(s=>{n==null||n(s)}),()=>{r.destroy()}},[t])}import{iframeResizer as V}from"iframe-resizer";import J,{forwardRef as U,useEffect as q,useImperativeHandle as G,useRef as K}from"react";var h=U((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=Y(e),s=K(null);return q(()=>{let d=s.current;return V(i({},r),d),()=>d.iFrameResizer&&d.iFrameResizer.removeListeners()}),G(t,()=>s.current),J.createElement("iframe",a(i({},o),{title:n,ref:s}))});h.displayName="IframeResizer";var Q=["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"],X=new Set(Q);function Y(e){return Object.keys(e).reduce((n,o)=>(X.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function k(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function z(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new g}}function c(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:s,renderingContext:d,methods:u,theme:I}=e,[b,E]=te(!1),O=ee(null),L=Z(()=>{try{let p=d?a(i({},d),{referer:window.location.href}):null,f=p?k(p):null,F=z(t),{path:T}=F;if(!T)throw new g;let R=I?`&theme=${I}`:"";return`${T}?token=${t}&sdkVersion=${M}&renderingContext=${f!=null?f:""}${R}`}catch(p){r==null||r(new g);return}},[t,r]);return w({iframeRef:O,token:t,onError:p=>{r==null||r(p),E(!0)},methods:i({onLoad:()=>E(!0),onError:p=>{let f=new C(p);r==null||r(f)}},u)}),P.createElement(P.Fragment,null,!b&&s,P.createElement(h,{src:L,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:O,hidden:!b,onResized:p=>{let f=`${parseInt(p.height)+12}px`;p.iframe.style.height=f}}))}function ne(e){let t="cardsApp",n=l(()=>({entryPoint:t}),[t]);return m.createElement(c,a(i({},e),{renderingContext:n}))}var ze=ne;function Le(r){var s=r,{cardholder:e,onDone:t,onCancel:n}=s,o=x(s,["cardholder","onDone","onCancel"]);let d="createCard",u=l(()=>({entryPoint:d,cardholder:e}),[e]);return m.createElement(c,a(i({},o),{renderingContext:u,methods:{createCard:{onDone:t,onCancel:n}}}))}function Fe(r){var s=r,{transactionId:e,onDone:t,onCancel:n}=s,o=x(s,["transactionId","onDone","onCancel"]);let d="createDispute",u=l(()=>({entryPoint:d,transactionId:e}),[e]);return m.createElement(c,a(i({},o),{renderingContext:u,methods:{createDispute:{onDone:t,onCancel:n}}}))}function Re(e){let t="billPayApp",n=l(()=>({entryPoint:t}),[t]);return m.createElement(c,a(i({},e),{renderingContext:n}))}function He(e){let t="cardDetails",n=l(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return m.createElement(c,a(i({},e),{renderingContext:n}))}function Se(e){let t="accountDetails",n=l(()=>({entryPoint:t}),[t]);return m.createElement(c,a(i({},e),{renderingContext:n}))}function _e(e){let t="accountActions",n=l(()=>({entryPoint:t}),[t]);return m.createElement(c,a(i({},e),{renderingContext:n}))}function Ne(e){let t="insightsDashboard",n=l(()=>({entryPoint:t}),[t]);return m.createElement(c,a(i({},e),{renderingContext:n}))}function We(e){let t="insightsWidget",n=e.widget,o=l(()=>({entryPoint:t,widget:n}),[t,n]);return m.createElement(c,a(i({},e),{renderingContext:o}))}function je(r){var s=r,{onDone:e,entryPoint:t,exitPoint:n}=s,o=x(s,["onDone","entryPoint","exitPoint"]);let d="onboarding",u=l(()=>({entryPoint:d,onboardingEntryPoint:t,onboardingExitPoint:n}),[d,t,n]);return m.createElement(c,a(i({},o),{renderingContext:u,methods:{onboarding:{onDone:e}}}))}export{_e as AccountActions,Se as AccountDetails,ze as App,Re as BillPayApp,He as CardDetails,ne as CardsApp,Fe as DisputeTransaction,Ne as InsightsDashboard,We as InsightsWidget,Le as IssueCard,je as Onboarding};
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 O=(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 Oe}from"react";import ye,{useMemo as ke,useRef as Te}from"react";var C=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"},P=class extends C{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:b.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.3";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 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"],he=new Set(Ce);function xe(e){return Object.keys(e).reduce((n,o)=>(he.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=Te(null),s=ke(()=>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 C(m))},tokenExchange:{onLongLivedToken:o}}}),ye.createElement(v,{src:p,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var $=Pe({isLoading:!1,invalidateToken:()=>{}}),be=({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),k=U(()=>B(void 0,null,function*(){w(!0);try{let g=yield e();r(g),x(void 0);let h=H(g),T=new URL(h.path);T.pathname="",s(T.toString())}catch(g){x(g)}finally{w(!1)}}),[e]),E=U(()=>{p(void 0)},[]);Oe(()=>{a||k()},[a,k]);let y=U(g=>{p(g),r(void 0),x(void 0)},[]),F=Ee(()=>{if(a&&!i)throw new C({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: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,k]=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 C({message:"Token expired. Cannot automatically refresh when using token prop.",code:b.unauthorized}));return}I(),k(!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:h=>{r==null||r(h),k(!0)},methods:d({onLoad:()=>k(!0),onError:h=>{let T=new C(h);r==null||r(T)},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:h=>{let T=`${parseInt(h.height)+12}px`;h.iframe.style.height=T}}))}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=O(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=O(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",n=e.widget,o=f(()=>({entryPoint:t,widget:n}),[t,n]);return u.createElement(l,c(d({},e),{renderingContext:o}))}function _t(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=O(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=O(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,be 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};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.tsx","../../src/capital-os.tsx","../../package.json","../../src/error.ts","../../src/hooks.ts","../../src/iframe-resizer.tsx","../../src/utils.ts"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\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 */\n widget: 'cards-by-month' | 'top-spenders'\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const widget = props.widget\n const renderingContext = useMemo(() => ({ entryPoint, widget }), [entryPoint, widget])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding Types\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","import React, { useMemo, useRef, useState } from 'react'\n\nimport { version as sdkVersion } from '../package.json'\nimport { CapitalOSError, InvalidTokenError } from './error'\nimport { EntryPoint } from './external-types'\nimport { IframeConnectionMethods, useIframeConnection } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps } from './types'\nimport { decodeToken, encodeRenderingContext } from './utils'\n\ntype RenderingContext = {\n entryPoint?: EntryPoint\n referer?: string\n}\n\ntype CapitalOsProps<T extends RenderingContext> = 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 RenderingContext>(props: CapitalOsProps<T>) {\n const {\n token,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n // memoize the url based on the token so we don't redo the computation on each render.\n const url = useMemo(() => {\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 tokenObject = decodeToken(token)\n\n const { path } = tokenObject\n if (!path) {\n throw new InvalidTokenError()\n }\n const themeChunk = theme ? `&theme=${theme}` : ''\n return `${path}?token=${token}&sdkVersion=${sdkVersion}&renderingContext=${encodedRenderingContext ?? ''}${themeChunk}`\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 // renderingContext is not part of the dependencies since we do not want to reload the iframe unless the token changes.\n }, [token, onError])\n\n useIframeConnection({\n iframeRef,\n 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 ...methods,\n },\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 \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.2\",\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","/**\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} 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() {\n super({ message: 'Invalid token', code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account } from './types'\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 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}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\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])\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","import { InvalidTokenError } from './error'\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 decodeToken(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"],"mappings":"4lBAEA,OAAOA,GAAS,WAAAC,MAAe,QCF/B,OAAOC,GAAS,WAAAC,EAAS,UAAAC,GAAQ,YAAAC,OAAgB,QCE/C,IAAAC,EAAW,aCCN,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE,MAAMD,CAAO,EACb,KAAK,KAAO,iBACZ,KAAK,KAAOC,CACd,CACF,EAEaC,EAAY,CACvB,aAAc,eACd,uBAAwB,yBACxB,wBAAyB,yBAC3B,EAOaC,EAAN,cAAgCJ,CAAe,CACpD,aAAc,CACZ,MAAM,CAAE,QAAS,gBAAiB,KAAMG,EAAU,YAAa,CAAC,EAChE,KAAK,KAAO,4BACd,CACF,EC5BA,OAAS,kBAAAE,MAAsB,SAC/B,OAAS,aAAAC,MAAiB,QAK1B,IAAMC,EAAyC,IA8BxC,SAASC,EAAoB,CAClC,UAA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,CACzD,IAAMV,EAAyB,iBACzBC,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAOG,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBT,GAAkB,CACnE,CASO,SAASa,GAAkBJ,EAA+B,CAC/D,IAAMV,EAAyB,oBACzBC,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAOG,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBT,GAAkB,CACnE,CAcO,SAASc,GAAeL,EAA4B,CACzD,IAAMV,EAAyB,iBACzBgB,EAASN,EAAM,OACfT,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,EAAY,OAAAgB,CAAO,GAAI,CAAChB,EAAYgB,CAAM,CAAC,EAErF,OAAOb,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBT,GAAkB,CACnE,CAgBO,SAASgB,GAA2CxB,EAKpC,CALoC,IAAAC,EAAAD,EACzD,QAAAG,EACA,WAAYsB,EACZ,UAAWC,CAnNb,EAgN2DzB,EAItDI,EAAAC,EAJsDL,EAItD,CAHH,SACA,aACA,cAMA,IAAMM,EAAyB,aACzBC,EAAmBC,EACvB,KAAO,CAAE,WAAAF,EAAY,qBAAAkB,EAAsB,oBAAAC,CAAoB,GAC/D,CAACnB,EAAYkB,EAAsBC,CAAmB,CACxD,EAEA,OAAOhB,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcR,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G","names":["React","useMemo","React","useMemo","useRef","useState","version","CapitalOSError","message","code","ErrorCode","InvalidTokenError","connectToChild","useEffect","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","connection","error","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","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","CapitalOS","props","token","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","isLoaded","setIsLoaded","useState","iframeRef","useRef","url","useMemo","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","encodeRenderingContext","tokenObject","decodeToken","path","InvalidTokenError","themeChunk","version","error","useIframeConnection","err","CapitalOSError","React","IframeResizer","data","newHeight","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","Onboarding","onboardingEntryPoint","onboardingExitPoint"]}
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 */\n widget: 'cards-by-month' | 'top-spenders'\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const widget = props.widget\n const renderingContext = useMemo(() => ({ entryPoint, widget }), [entryPoint, widget])\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","import 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.3\",\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,QCAzE,OAAOC,GAAS,iBAAAC,GAAe,cAAAC,GAAY,YAAAC,EAAU,WAAAC,GAAS,eAAAC,EAAa,aAAAC,OAAiB,QCA5F,OAAOC,IAAS,WAAAC,GAAS,UAAAC,OAAc,QCGhC,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE,MAAMD,CAAO,EACb,KAAK,KAAO,iBACZ,KAAK,KAAOC,CACd,CACF,EAEaC,EAAY,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iBACzBgB,EAASN,EAAM,OACfT,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,EAAY,OAAAgB,CAAO,GAAI,CAAChB,EAAYgB,CAAM,CAAC,EAErF,OAAOb,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBT,GAAkB,CACnE,CAgBO,SAASgB,GAA2CxB,EAKpC,CALoC,IAAAC,EAAAD,EACzD,QAAAG,EACA,WAAYsB,EACZ,UAAWC,CApNb,EAiN2DzB,EAItDI,EAAAC,EAJsDL,EAItD,CAHH,SACA,aACA,cAMA,IAAMM,EAAyB,aACzBC,EAAmBC,EACvB,KAAO,CAAE,WAAAF,EAAY,qBAAAkB,EAAsB,oBAAAC,CAAoB,GAC/D,CAACnB,EAAYkB,EAAsBC,CAAmB,CACxD,EAEA,OAAOhB,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcR,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G,CAcO,SAASwB,GAAY3B,EAA8C,CAA9C,IAAAC,EAAAD,EAAE,QAAAG,CA/O9B,EA+O4BF,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","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","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";"use client";var $=Object.create;var y=Object.defineProperty,V=Object.defineProperties,J=Object.getOwnPropertyDescriptor,U=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertyNames,h=Object.getOwnPropertySymbols,G=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;var M=(e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,s=(e,t)=>{for(var n in t||(t={}))I.call(t,n)&&M(e,n,t[n]);if(h)for(var n of h(t))w.call(t,n)&&M(e,n,t[n]);return e},d=(e,t)=>V(e,U(t));var P=(e,t)=>{var n={};for(var o in e)I.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&h)for(var o of h(e))t.indexOf(o)<0&&w.call(e,o)&&(n[o]=e[o]);return n};var K=(e,t)=>{for(var n in t)y(e,n,{get:t[n],enumerable:!0})},k=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of q(t))!I.call(e,r)&&r!==n&&y(e,r,{get:()=>t[r],enumerable:!(o=J(t,r))||o.enumerable});return e};var b=(e,t,n)=>(n=e!=null?$(G(e)):{},k(t||!e||!e.__esModule?y(n,"default",{value:e,enumerable:!0}):n,e)),Q=e=>k(y({},"__esModule",{value:!0}),e);var ue={};K(ue,{AccountActions:()=>ce,AccountDetails:()=>de,App:()=>oe,BillPayApp:()=>se,CardDetails:()=>ae,CardsApp:()=>N,DisputeTransaction:()=>ie,InsightsDashboard:()=>pe,InsightsWidget:()=>me,IssueCard:()=>re,Onboarding:()=>le});module.exports=Q(ue);var i=b(require("react"));var u=b(require("react"));var z="1.0.0-rc.2";var x=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},Y={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point"},C=class extends x{constructor(){super({message:"Invalid token",code:Y.unauthorized}),this.name="CapitalOSInvalidTokenError"}};var L=require("penpal"),F=require("react"),Z=1e4;function R({iframeRef:e,token:t,onError:n,methods:o}){(0,F.useEffect)(()=>{let r=(0,L.connectToChild)({iframe:e.current,childOrigin:"*",debug:!0,timeout:Z,methods:o});return r.promise.catch(a=>{n==null||n(a)}),()=>{r.destroy()}},[t])}var H=require("iframe-resizer"),l=b(require("react"));var E=(0,l.forwardRef)((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=ne(e),a=(0,l.useRef)(null);return(0,l.useEffect)(()=>{let c=a.current;return(0,H.iframeResizer)(s({},r),c),()=>c.iFrameResizer&&c.iFrameResizer.removeListeners()}),(0,l.useImperativeHandle)(t,()=>a.current),l.default.createElement("iframe",d(s({},o),{title:n,ref:a}))});E.displayName="IframeResizer";var ee=["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"],te=new Set(ee);function ne(e){return Object.keys(e).reduce((n,o)=>(te.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function S(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function _(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new C}}function p(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:a,renderingContext:c,methods:f,theme:O}=e,[T,D]=(0,u.useState)(!1),A=(0,u.useRef)(null),W=(0,u.useMemo)(()=>{try{let m=c?d(s({},c),{referer:window.location.href}):null,g=m?S(m):null,j=_(t),{path:v}=j;if(!v)throw new C;let B=O?`&theme=${O}`:"";return`${v}?token=${t}&sdkVersion=${z}&renderingContext=${g!=null?g:""}${B}`}catch(m){r==null||r(new C);return}},[t,r]);return R({iframeRef:A,token:t,onError:m=>{r==null||r(m),D(!0)},methods:s({onLoad:()=>D(!0),onError:m=>{let g=new x(m);r==null||r(g)}},f)}),u.default.createElement(u.default.Fragment,null,!T&&a,u.default.createElement(E,{src:W,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:A,hidden:!T,onResized:m=>{let g=`${parseInt(m.height)+12}px`;m.iframe.style.height=g}}))}function N(e){let t="cardsApp",n=(0,i.useMemo)(()=>({entryPoint:t}),[t]);return i.default.createElement(p,d(s({},e),{renderingContext:n}))}var oe=N;function re(r){var a=r,{cardholder:e,onDone:t,onCancel:n}=a,o=P(a,["cardholder","onDone","onCancel"]);let c="createCard",f=(0,i.useMemo)(()=>({entryPoint:c,cardholder:e}),[e]);return i.default.createElement(p,d(s({},o),{renderingContext:f,methods:{createCard:{onDone:t,onCancel:n}}}))}function ie(r){var a=r,{transactionId:e,onDone:t,onCancel:n}=a,o=P(a,["transactionId","onDone","onCancel"]);let c="createDispute",f=(0,i.useMemo)(()=>({entryPoint:c,transactionId:e}),[e]);return i.default.createElement(p,d(s({},o),{renderingContext:f,methods:{createDispute:{onDone:t,onCancel:n}}}))}function se(e){let t="billPayApp",n=(0,i.useMemo)(()=>({entryPoint:t}),[t]);return i.default.createElement(p,d(s({},e),{renderingContext:n}))}function ae(e){let t="cardDetails",n=(0,i.useMemo)(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return i.default.createElement(p,d(s({},e),{renderingContext:n}))}function de(e){let t="accountDetails",n=(0,i.useMemo)(()=>({entryPoint:t}),[t]);return i.default.createElement(p,d(s({},e),{renderingContext:n}))}function ce(e){let t="accountActions",n=(0,i.useMemo)(()=>({entryPoint:t}),[t]);return i.default.createElement(p,d(s({},e),{renderingContext:n}))}function pe(e){let t="insightsDashboard",n=(0,i.useMemo)(()=>({entryPoint:t}),[t]);return i.default.createElement(p,d(s({},e),{renderingContext:n}))}function me(e){let t="insightsWidget",n=e.widget,o=(0,i.useMemo)(()=>({entryPoint:t,widget:n}),[t,n]);return i.default.createElement(p,d(s({},e),{renderingContext:o}))}function le(r){var a=r,{onDone:e,entryPoint:t,exitPoint:n}=a,o=P(a,["onDone","entryPoint","exitPoint"]);let c="onboarding",f=(0,i.useMemo)(()=>({entryPoint:c,onboardingEntryPoint:t,onboardingExitPoint:n}),[c,t,n]);return i.default.createElement(p,d(s({},o),{renderingContext:f,methods:{onboarding:{onDone:e}}}))}0&&(module.exports={AccountActions,AccountDetails,App,BillPayApp,CardDetails,CardsApp,DisputeTransaction,InsightsDashboard,InsightsWidget,IssueCard,Onboarding});
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:()=>be,AccountDetails:()=>Oe,App:()=>ke,BillPayApp:()=>Ie,CapitalOsAuthenticationProvider:()=>Y,CardDetails:()=>Ee,CardsApp:()=>ee,DisputeTransaction:()=>Pe,InsightsDashboard:()=>ve,InsightsWidget:()=>De,IssueCard:()=>Te,MakePayment:()=>we,Onboarding:()=>Le});module.exports=de(Ae);var a=A(require("react"));var m=A(require("react"));var c=A(require("react"));var b=A(require("react"));var h=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"},O=class extends h{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.3";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 O}}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 O);return}}function F(e){let n=j(e).path;if(!n||typeof n!="string")throw new O;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 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"],he=new Set(Ce);function xe(e){return Object.keys(e).reduce((n,o)=>(he.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,b.useRef)(null),s=(0,b.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 h(f))},tokenExchange:{onLongLivedToken:o}}}),b.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,k]=(0,c.useState)(void 0),I=(0,c.useCallback)(()=>V(void 0,null,function*(){z(!0);try{let C=yield e();r(C),k(void 0);let y=j(C),E=new URL(y.path);E.pathname="",s(E.toString())}catch(C){k(C)}finally{z(!1)}}),[e]),D=(0,c.useCallback)(()=>{u(void 0)},[]);(0,c.useEffect)(()=>{d||I()},[d,I]);let T=(0,c.useCallback)(C=>{u(C),r(void 0),k(void 0)},[]),_=(0,c.useMemo)(()=>{if(d&&!i)throw new h({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:T,enableLogging:t,onExchangeError:k}))},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(),[k,I]=(0,m.useState)(!1),D=(0,m.useRef)(null);ye(z,r);let T=(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 h({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 C=U({tokenData:T,renderingContext:s,theme:u,onError:r});return H({iframeRef:D,token:T==null?void 0:T.token,onError:y=>{r==null||r(y),I(!0)},methods:p({onLoad:()=>I(!0),onError:y=>{let E=new h(y);r==null||r(E)},onTokenExpired:_},d)}),!T||!C?m.default.createElement(m.default.Fragment,null,i||null):m.default.createElement(m.default.Fragment,null,!k&&i,m.default.createElement(R,{src:C,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:D,hidden:!k,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 ke=ee;function Te(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 Oe(e){let t="accountDetails",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function be(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",n=e.widget,o=(0,a.useMemo)(()=>({entryPoint:t,widget:n}),[t,n]);return a.default.createElement(g,l(p({},e),{renderingContext:o}))}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});
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","../package.json","../src/error.ts","../src/hooks.ts","../src/iframe-resizer.tsx","../src/utils.ts"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\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 */\n widget: 'cards-by-month' | 'top-spenders'\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const widget = props.widget\n const renderingContext = useMemo(() => ({ entryPoint, widget }), [entryPoint, widget])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding Types\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","import React, { useMemo, useRef, useState } from 'react'\n\nimport { version as sdkVersion } from '../package.json'\nimport { CapitalOSError, InvalidTokenError } from './error'\nimport { EntryPoint } from './external-types'\nimport { IframeConnectionMethods, useIframeConnection } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps } from './types'\nimport { decodeToken, encodeRenderingContext } from './utils'\n\ntype RenderingContext = {\n entryPoint?: EntryPoint\n referer?: string\n}\n\ntype CapitalOsProps<T extends RenderingContext> = 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 RenderingContext>(props: CapitalOsProps<T>) {\n const {\n token,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n // memoize the url based on the token so we don't redo the computation on each render.\n const url = useMemo(() => {\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 tokenObject = decodeToken(token)\n\n const { path } = tokenObject\n if (!path) {\n throw new InvalidTokenError()\n }\n const themeChunk = theme ? `&theme=${theme}` : ''\n return `${path}?token=${token}&sdkVersion=${sdkVersion}&renderingContext=${encodedRenderingContext ?? ''}${themeChunk}`\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 // renderingContext is not part of the dependencies since we do not want to reload the iframe unless the token changes.\n }, [token, onError])\n\n useIframeConnection({\n iframeRef,\n 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 ...methods,\n },\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 \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.2\",\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","/**\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} 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() {\n super({ message: 'Invalid token', code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account } from './types'\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 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}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\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])\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","import { InvalidTokenError } from './error'\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 decodeToken(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"],"mappings":"gkCAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,oBAAAE,GAAA,mBAAAC,GAAA,QAAAC,GAAA,eAAAC,GAAA,gBAAAC,GAAA,aAAAC,EAAA,uBAAAC,GAAA,sBAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,eAAAC,KAAA,eAAAC,EAAAb,IAEA,IAAAc,EAA+B,oBCF/B,IAAAC,EAAiD,oBCE/C,IAAAC,EAAW,aCCN,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE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B,CACxD,EAEA,OAAO,EAAAhB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G","names":["src_exports","__export","AccountActions","AccountDetails","App","BillPayApp","CardDetails","CardsApp","DisputeTransaction","InsightsDashboard","InsightsWidget","IssueCard","Onboarding","__toCommonJS","import_react","import_react","version","CapitalOSError","message","code","ErrorCode","InvalidTokenError","import_penpal","import_react","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","connection","error","import_iframe_resizer","import_react","IframeResizer","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","iframe","__spreadValues","React","__spreadProps","resizerOptionsSet","acc","key","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","CapitalOS","props","token","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","isLoaded","setIsLoaded","iframeRef","url","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","encodeRenderingContext","tokenObject","decodeToken","path","InvalidTokenError","themeChunk","version","error","useIframeConnection","err","CapitalOSError","React","IframeResizer","data","newHeight","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","Onboarding","onboardingEntryPoint","onboardingExitPoint"]}
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 */\n widget: 'cards-by-month' | 'top-spenders'\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const widget = props.widget\n const renderingContext = useMemo(() => ({ entryPoint, widget }), [entryPoint, widget])\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","import 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.3\",\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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AAa,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","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
@@ -8,6 +8,7 @@ export { AccountActions } from '../_tsup-dts-rollup';
8
8
  export { InsightsDashboard } from '../_tsup-dts-rollup';
9
9
  export { InsightsWidget } from '../_tsup-dts-rollup';
10
10
  export { Onboarding } from '../_tsup-dts-rollup';
11
+ export { MakePayment } from '../_tsup-dts-rollup';
11
12
  export { App } from '../_tsup-dts-rollup';
12
13
  export { IssueCardProps } from '../_tsup-dts-rollup';
13
14
  export { DisputeTransactionProps } from '../_tsup-dts-rollup';
@@ -17,3 +18,5 @@ export { AccountDetailsProps } from '../_tsup-dts-rollup';
17
18
  export { AccountActionsProps } from '../_tsup-dts-rollup';
18
19
  export { InsightsDashboardProps } from '../_tsup-dts-rollup';
19
20
  export { InsightsWidgetProps } from '../_tsup-dts-rollup';
21
+ export { MakePaymentProps } from '../_tsup-dts-rollup';
22
+ export { CapitalOsAuthenticationProvider } from '../_tsup-dts-rollup';
@@ -8,6 +8,7 @@ export { AccountActions } from '../_tsup-dts-rollup';
8
8
  export { InsightsDashboard } from '../_tsup-dts-rollup';
9
9
  export { InsightsWidget } from '../_tsup-dts-rollup';
10
10
  export { Onboarding } from '../_tsup-dts-rollup';
11
+ export { MakePayment } from '../_tsup-dts-rollup';
11
12
  export { App } from '../_tsup-dts-rollup';
12
13
  export { IssueCardProps } from '../_tsup-dts-rollup';
13
14
  export { DisputeTransactionProps } from '../_tsup-dts-rollup';
@@ -17,3 +18,5 @@ export { AccountDetailsProps } from '../_tsup-dts-rollup';
17
18
  export { AccountActionsProps } from '../_tsup-dts-rollup';
18
19
  export { InsightsDashboardProps } from '../_tsup-dts-rollup';
19
20
  export { InsightsWidgetProps } from '../_tsup-dts-rollup';
21
+ export { MakePaymentProps } from '../_tsup-dts-rollup';
22
+ export { CapitalOsAuthenticationProvider } from '../_tsup-dts-rollup';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capitalos/react",
3
- "version": "1.0.0-rc.2",
3
+ "version": "1.0.0-rc.3",
4
4
  "description": "integrate CapitalOS into your react app",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/esm/index.js",