@capitalos/react 0.1.1-beta.2 → 0.2.0

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.
@@ -1,3 +1,5 @@
1
+ /// <reference types="react" />
2
+
1
3
  import { IFrameComponent } from 'iframe-resizer';
2
4
  import { IFrameMessageData } from 'iframe-resizer';
3
5
  import { IFrameOptions } from 'iframe-resizer';
@@ -5,11 +7,195 @@ import { IFrameResizedData } from 'iframe-resizer';
5
7
  import { IFrameScrollData } from 'iframe-resizer';
6
8
  import { default as React_2 } from 'react';
7
9
  import { ReactNode } from 'react';
10
+ import * as z from 'zod';
11
+ import { z as z_2 } from 'zod';
8
12
 
9
13
  /**
10
14
  * Renders the CapitalOS App.
11
15
  */
12
- export declare function App(props: {
16
+ export declare function App(props: CommonProps): JSX.Element;
17
+
18
+ /**
19
+ * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.
20
+ * all user facing components are basically a syntactic sugar on top of this.
21
+ */
22
+ export declare function CapitalOS<T>(props: CapitalOsProps<T>): JSX.Element;
23
+
24
+ /**
25
+ * Base class for all SDK errors
26
+ */
27
+ export declare class CapitalOSError extends Error {
28
+ constructor(message: string);
29
+ }
30
+
31
+ declare type CapitalOsProps<T> = CommonProps & {
32
+ renderingContext?: T | undefined;
33
+ methods?: Partial<IframeConnectionMethods>;
34
+ };
35
+
36
+ export declare type CardApiDto = z.infer<typeof cardApiDtoSchema>;
37
+
38
+ declare const cardApiDtoSchema: z.ZodObject<{
39
+ accountUserId: z.ZodNullable<z.ZodString>;
40
+ status: z.ZodEnum<["active", "inactive", "canceled", "frozen"]>;
41
+ id: z.ZodString;
42
+ last4: z.ZodString;
43
+ platformId: z.ZodString;
44
+ cardholderFirstName: z.ZodString;
45
+ cardholderLastName: z.ZodString;
46
+ cardholderPhoneNumber: z.ZodEffects<z.ZodString, string, string>;
47
+ nickname: z.ZodOptional<z.ZodNullable<z.ZodString>>;
48
+ spend: z.ZodObject<{
49
+ daily: z.ZodObject<{
50
+ limit: z.ZodOptional<z.ZodNumber>;
51
+ amount: z.ZodNumber;
52
+ }, "strip", z.ZodTypeAny, {
53
+ amount: number;
54
+ limit?: number | undefined;
55
+ }, {
56
+ amount: number;
57
+ limit?: number | undefined;
58
+ }>;
59
+ weekly: z.ZodObject<{
60
+ limit: z.ZodOptional<z.ZodNumber>;
61
+ amount: z.ZodNumber;
62
+ }, "strip", z.ZodTypeAny, {
63
+ amount: number;
64
+ limit?: number | undefined;
65
+ }, {
66
+ amount: number;
67
+ limit?: number | undefined;
68
+ }>;
69
+ monthly: z.ZodObject<{
70
+ limit: z.ZodOptional<z.ZodNumber>;
71
+ amount: z.ZodNumber;
72
+ }, "strip", z.ZodTypeAny, {
73
+ amount: number;
74
+ limit?: number | undefined;
75
+ }, {
76
+ amount: number;
77
+ limit?: number | undefined;
78
+ }>;
79
+ lifetime: z.ZodObject<{
80
+ limit: z.ZodOptional<z.ZodNumber>;
81
+ amount: z.ZodNumber;
82
+ }, "strip", z.ZodTypeAny, {
83
+ amount: number;
84
+ limit?: number | undefined;
85
+ }, {
86
+ amount: number;
87
+ limit?: number | undefined;
88
+ }>;
89
+ }, "strip", z.ZodTypeAny, {
90
+ daily: {
91
+ amount: number;
92
+ limit?: number | undefined;
93
+ };
94
+ weekly: {
95
+ amount: number;
96
+ limit?: number | undefined;
97
+ };
98
+ monthly: {
99
+ amount: number;
100
+ limit?: number | undefined;
101
+ };
102
+ lifetime: {
103
+ amount: number;
104
+ limit?: number | undefined;
105
+ };
106
+ }, {
107
+ daily: {
108
+ amount: number;
109
+ limit?: number | undefined;
110
+ };
111
+ weekly: {
112
+ amount: number;
113
+ limit?: number | undefined;
114
+ };
115
+ monthly: {
116
+ amount: number;
117
+ limit?: number | undefined;
118
+ };
119
+ lifetime: {
120
+ amount: number;
121
+ limit?: number | undefined;
122
+ };
123
+ }>;
124
+ allowedSpendCategories: z.ZodArray<z.ZodEnum<["airlines", "carRental", "carService", "education", "electronics", "gasPump", "gasStation", "generalMerchandise", "government", "hardwareAndConstruction", "insurance", "legal", "lodging", "medical", "other", "parking", "phoneAndInternet", "professionalServices", "recreationAndEntertainment", "restaurants", "shipping", "software", "taxisAndRideshare", "transportation", "travelMisc", "utilities"]>, "many">;
125
+ physicalCard: z.ZodOptional<z.ZodNullable<z.ZodObject<{
126
+ id: z.ZodString;
127
+ }, "strip", z.ZodTypeAny, {
128
+ id: string;
129
+ }, {
130
+ id: string;
131
+ }>>>;
132
+ }, "strip", z.ZodTypeAny, {
133
+ id: string;
134
+ status: "active" | "inactive" | "canceled" | "frozen";
135
+ platformId: string;
136
+ accountUserId: string | null;
137
+ last4: string;
138
+ cardholderFirstName: string;
139
+ cardholderLastName: string;
140
+ cardholderPhoneNumber: string;
141
+ spend: {
142
+ daily: {
143
+ amount: number;
144
+ limit?: number | undefined;
145
+ };
146
+ weekly: {
147
+ amount: number;
148
+ limit?: number | undefined;
149
+ };
150
+ monthly: {
151
+ amount: number;
152
+ limit?: number | undefined;
153
+ };
154
+ lifetime: {
155
+ amount: number;
156
+ limit?: number | undefined;
157
+ };
158
+ };
159
+ allowedSpendCategories: ("other" | "airlines" | "carRental" | "carService" | "education" | "electronics" | "gasPump" | "gasStation" | "generalMerchandise" | "government" | "hardwareAndConstruction" | "insurance" | "legal" | "lodging" | "medical" | "parking" | "phoneAndInternet" | "professionalServices" | "recreationAndEntertainment" | "restaurants" | "shipping" | "software" | "taxisAndRideshare" | "transportation" | "travelMisc" | "utilities")[];
160
+ nickname?: string | null | undefined;
161
+ physicalCard?: {
162
+ id: string;
163
+ } | null | undefined;
164
+ }, {
165
+ id: string;
166
+ status: "active" | "inactive" | "canceled" | "frozen";
167
+ platformId: string;
168
+ accountUserId: string | null;
169
+ last4: string;
170
+ cardholderFirstName: string;
171
+ cardholderLastName: string;
172
+ cardholderPhoneNumber: string;
173
+ spend: {
174
+ daily: {
175
+ amount: number;
176
+ limit?: number | undefined;
177
+ };
178
+ weekly: {
179
+ amount: number;
180
+ limit?: number | undefined;
181
+ };
182
+ monthly: {
183
+ amount: number;
184
+ limit?: number | undefined;
185
+ };
186
+ lifetime: {
187
+ amount: number;
188
+ limit?: number | undefined;
189
+ };
190
+ };
191
+ allowedSpendCategories: ("other" | "airlines" | "carRental" | "carService" | "education" | "electronics" | "gasPump" | "gasStation" | "generalMerchandise" | "government" | "hardwareAndConstruction" | "insurance" | "legal" | "lodging" | "medical" | "parking" | "phoneAndInternet" | "professionalServices" | "recreationAndEntertainment" | "restaurants" | "shipping" | "software" | "taxisAndRideshare" | "transportation" | "travelMisc" | "utilities")[];
192
+ nickname?: string | null | undefined;
193
+ physicalCard?: {
194
+ id: string;
195
+ } | null | undefined;
196
+ }>;
197
+
198
+ export declare type CommonProps = {
13
199
  /**
14
200
  * The token provided by initiate-login.
15
201
  */
@@ -30,14 +216,48 @@ export declare function App(props: {
30
216
  * Optional component to render while the app is loading.
31
217
  */
32
218
  loadingComponent?: ReactNode;
33
- }): JSX.Element;
219
+ };
220
+
221
+ export declare function decodeToken(token: string): any;
34
222
 
35
223
  /**
36
- * Base class for all SDK errors
224
+ * Renders the CapitalOS Dispute Transaction experience.
37
225
  */
38
- export declare class CapitalOSError extends Error {
39
- constructor(message: string);
40
- }
226
+ export declare function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps): JSX.Element;
227
+
228
+ export declare type DisputeTransactionProps = CommonProps & {
229
+ /**
230
+ * The ID of the transaction to dispute.
231
+ */
232
+ transactionId: string;
233
+ /**
234
+ * Callback to invoke when the dispute was successfully submitted.
235
+ */
236
+ onDone: () => void;
237
+ /**
238
+ * Callback to invoke when the user cancels the dispute submission.
239
+ */
240
+ onCancel: () => void;
241
+ };
242
+
243
+ /**
244
+ * Encodes the rendering context as base64 and then URI encodes it.
245
+ */
246
+ export declare function encodeRenderingContext<T>(renderingContext: NonNullable<T>): string;
247
+
248
+ export declare type EntryPoint = RenderingContext_2['entryPoint'];
249
+
250
+ export declare type IframeConnectionMethods = {
251
+ onLoad: () => void;
252
+ createCard?: {
253
+ onDone?: () => void;
254
+ onCancel?: () => void;
255
+ };
256
+ createDispute?: {
257
+ onDone?: () => void;
258
+ onCancel?: () => void;
259
+ };
260
+ };
41
261
 
42
262
  export declare const IframeResizer: React_2.ForwardRefExoticComponent<Omit<IFrameOptions, "closedCallback" | "scrollCallback" | "resizedCallback" | "messageCallback" | "initCallback"> & {
43
263
  onClosed?(iframeId: string): void;
@@ -54,4 +274,134 @@ export declare class InvalidTokenError extends CapitalOSError {
54
274
  constructor();
55
275
  }
56
276
 
277
+ /**
278
+ * Renders the CapitalOS Issue Card experience.
279
+ */
280
+ export declare function IssueCard({ defaultValues, onDone, onCancel, ...restOfProps }: IssueCardProps): JSX.Element;
281
+
282
+ export declare type IssueCardDefaultValues = z_2.infer<typeof issueCardDefaultValuesSchema>;
283
+
284
+ declare const issueCardDefaultValuesSchema: z_2.ZodIntersection<z_2.ZodUnion<[z_2.ZodObject<{
285
+ firstName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
286
+ lastName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
287
+ phone: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
288
+ userId: z_2.ZodOptional<z_2.ZodUndefined>;
289
+ }, "strip", z_2.ZodTypeAny, {
290
+ firstName?: string | null | undefined;
291
+ lastName?: string | null | undefined;
292
+ phone?: string | null | undefined;
293
+ userId?: undefined;
294
+ }, {
295
+ firstName?: string | null | undefined;
296
+ lastName?: string | null | undefined;
297
+ phone?: string | null | undefined;
298
+ userId?: undefined;
299
+ }>, z_2.ZodObject<{
300
+ userId: z_2.ZodString;
301
+ }, "strip", z_2.ZodTypeAny, {
302
+ userId: string;
303
+ }, {
304
+ userId: string;
305
+ }>]>, z_2.ZodObject<{
306
+ nickname: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
307
+ }, "strip", z_2.ZodTypeAny, {
308
+ nickname?: string | null | undefined;
309
+ }, {
310
+ nickname?: string | null | undefined;
311
+ }>>;
312
+
313
+ export declare type IssueCardProps = CommonProps & {
314
+ /**
315
+ * Default values to prefill the form with.
316
+ *
317
+ * 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.
318
+ */
319
+ defaultValues?: IssueCardDefaultValues;
320
+ /**
321
+ * Callback to invoke when the card was created successfully.
322
+ */
323
+ onDone: () => void;
324
+ /**
325
+ * Callback to invoke when the card creation was cancelled by the user.
326
+ */
327
+ onCancel: () => void;
328
+ };
329
+
330
+ declare type RenderingContext_2 = z_2.infer<typeof renderingContextSchema>;
331
+
332
+ declare const renderingContextSchema: z_2.ZodDiscriminatedUnion<"entryPoint", [z_2.ZodObject<{
333
+ entryPoint: z_2.ZodLiteral<"createCard">;
334
+ defaultValues: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodIntersection<z_2.ZodUnion<[z_2.ZodObject<{
335
+ firstName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
336
+ lastName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
337
+ phone: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
338
+ userId: z_2.ZodOptional<z_2.ZodUndefined>;
339
+ }, "strip", z_2.ZodTypeAny, {
340
+ firstName?: string | null | undefined;
341
+ lastName?: string | null | undefined;
342
+ phone?: string | null | undefined;
343
+ userId?: undefined;
344
+ }, {
345
+ firstName?: string | null | undefined;
346
+ lastName?: string | null | undefined;
347
+ phone?: string | null | undefined;
348
+ userId?: undefined;
349
+ }>, z_2.ZodObject<{
350
+ userId: z_2.ZodString;
351
+ }, "strip", z_2.ZodTypeAny, {
352
+ userId: string;
353
+ }, {
354
+ userId: string;
355
+ }>]>, z_2.ZodObject<{
356
+ nickname: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
357
+ }, "strip", z_2.ZodTypeAny, {
358
+ nickname?: string | null | undefined;
359
+ }, {
360
+ nickname?: string | null | undefined;
361
+ }>>>>;
362
+ }, "strip", z_2.ZodTypeAny, {
363
+ entryPoint: "createCard";
364
+ defaultValues?: (({
365
+ firstName?: string | null | undefined;
366
+ lastName?: string | null | undefined;
367
+ phone?: string | null | undefined;
368
+ userId?: undefined;
369
+ } | {
370
+ userId: string;
371
+ }) & {
372
+ nickname?: string | null | undefined;
373
+ }) | null | undefined;
374
+ }, {
375
+ entryPoint: "createCard";
376
+ defaultValues?: (({
377
+ firstName?: string | null | undefined;
378
+ lastName?: string | null | undefined;
379
+ phone?: string | null | undefined;
380
+ userId?: undefined;
381
+ } | {
382
+ userId: string;
383
+ }) & {
384
+ nickname?: string | null | undefined;
385
+ }) | null | undefined;
386
+ }>, z_2.ZodObject<{
387
+ entryPoint: z_2.ZodLiteral<"createDispute">;
388
+ transactionId: z_2.ZodString;
389
+ }, "strip", z_2.ZodTypeAny, {
390
+ entryPoint: "createDispute";
391
+ transactionId: string;
392
+ }, {
393
+ entryPoint: "createDispute";
394
+ transactionId: string;
395
+ }>]>;
396
+
397
+ /**
398
+ * connects to child iframe and returns whether the iframe is loaded or not.
399
+ */
400
+ export declare function useIframeConnection({ iframeRef, token, onError, methods, }: {
401
+ iframeRef: React.RefObject<HTMLIFrameElement>;
402
+ token: string;
403
+ onError: ((error: Error) => void) | undefined | null;
404
+ methods: IframeConnectionMethods;
405
+ }): void;
406
+
57
407
  export { }
@@ -1,3 +1,5 @@
1
+ /// <reference types="react" />
2
+
1
3
  import { IFrameComponent } from 'iframe-resizer';
2
4
  import { IFrameMessageData } from 'iframe-resizer';
3
5
  import { IFrameOptions } from 'iframe-resizer';
@@ -5,11 +7,195 @@ import { IFrameResizedData } from 'iframe-resizer';
5
7
  import { IFrameScrollData } from 'iframe-resizer';
6
8
  import { default as React_2 } from 'react';
7
9
  import { ReactNode } from 'react';
10
+ import * as z from 'zod';
11
+ import { z as z_2 } from 'zod';
8
12
 
9
13
  /**
10
14
  * Renders the CapitalOS App.
11
15
  */
12
- export declare function App(props: {
16
+ export declare function App(props: CommonProps): JSX.Element;
17
+
18
+ /**
19
+ * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.
20
+ * all user facing components are basically a syntactic sugar on top of this.
21
+ */
22
+ export declare function CapitalOS<T>(props: CapitalOsProps<T>): JSX.Element;
23
+
24
+ /**
25
+ * Base class for all SDK errors
26
+ */
27
+ export declare class CapitalOSError extends Error {
28
+ constructor(message: string);
29
+ }
30
+
31
+ declare type CapitalOsProps<T> = CommonProps & {
32
+ renderingContext?: T | undefined;
33
+ methods?: Partial<IframeConnectionMethods>;
34
+ };
35
+
36
+ export declare type CardApiDto = z.infer<typeof cardApiDtoSchema>;
37
+
38
+ declare const cardApiDtoSchema: z.ZodObject<{
39
+ accountUserId: z.ZodNullable<z.ZodString>;
40
+ status: z.ZodEnum<["active", "inactive", "canceled", "frozen"]>;
41
+ id: z.ZodString;
42
+ last4: z.ZodString;
43
+ platformId: z.ZodString;
44
+ cardholderFirstName: z.ZodString;
45
+ cardholderLastName: z.ZodString;
46
+ cardholderPhoneNumber: z.ZodEffects<z.ZodString, string, string>;
47
+ nickname: z.ZodOptional<z.ZodNullable<z.ZodString>>;
48
+ spend: z.ZodObject<{
49
+ daily: z.ZodObject<{
50
+ limit: z.ZodOptional<z.ZodNumber>;
51
+ amount: z.ZodNumber;
52
+ }, "strip", z.ZodTypeAny, {
53
+ amount: number;
54
+ limit?: number | undefined;
55
+ }, {
56
+ amount: number;
57
+ limit?: number | undefined;
58
+ }>;
59
+ weekly: z.ZodObject<{
60
+ limit: z.ZodOptional<z.ZodNumber>;
61
+ amount: z.ZodNumber;
62
+ }, "strip", z.ZodTypeAny, {
63
+ amount: number;
64
+ limit?: number | undefined;
65
+ }, {
66
+ amount: number;
67
+ limit?: number | undefined;
68
+ }>;
69
+ monthly: z.ZodObject<{
70
+ limit: z.ZodOptional<z.ZodNumber>;
71
+ amount: z.ZodNumber;
72
+ }, "strip", z.ZodTypeAny, {
73
+ amount: number;
74
+ limit?: number | undefined;
75
+ }, {
76
+ amount: number;
77
+ limit?: number | undefined;
78
+ }>;
79
+ lifetime: z.ZodObject<{
80
+ limit: z.ZodOptional<z.ZodNumber>;
81
+ amount: z.ZodNumber;
82
+ }, "strip", z.ZodTypeAny, {
83
+ amount: number;
84
+ limit?: number | undefined;
85
+ }, {
86
+ amount: number;
87
+ limit?: number | undefined;
88
+ }>;
89
+ }, "strip", z.ZodTypeAny, {
90
+ daily: {
91
+ amount: number;
92
+ limit?: number | undefined;
93
+ };
94
+ weekly: {
95
+ amount: number;
96
+ limit?: number | undefined;
97
+ };
98
+ monthly: {
99
+ amount: number;
100
+ limit?: number | undefined;
101
+ };
102
+ lifetime: {
103
+ amount: number;
104
+ limit?: number | undefined;
105
+ };
106
+ }, {
107
+ daily: {
108
+ amount: number;
109
+ limit?: number | undefined;
110
+ };
111
+ weekly: {
112
+ amount: number;
113
+ limit?: number | undefined;
114
+ };
115
+ monthly: {
116
+ amount: number;
117
+ limit?: number | undefined;
118
+ };
119
+ lifetime: {
120
+ amount: number;
121
+ limit?: number | undefined;
122
+ };
123
+ }>;
124
+ allowedSpendCategories: z.ZodArray<z.ZodEnum<["airlines", "carRental", "carService", "education", "electronics", "gasPump", "gasStation", "generalMerchandise", "government", "hardwareAndConstruction", "insurance", "legal", "lodging", "medical", "other", "parking", "phoneAndInternet", "professionalServices", "recreationAndEntertainment", "restaurants", "shipping", "software", "taxisAndRideshare", "transportation", "travelMisc", "utilities"]>, "many">;
125
+ physicalCard: z.ZodOptional<z.ZodNullable<z.ZodObject<{
126
+ id: z.ZodString;
127
+ }, "strip", z.ZodTypeAny, {
128
+ id: string;
129
+ }, {
130
+ id: string;
131
+ }>>>;
132
+ }, "strip", z.ZodTypeAny, {
133
+ id: string;
134
+ status: "active" | "inactive" | "canceled" | "frozen";
135
+ platformId: string;
136
+ accountUserId: string | null;
137
+ last4: string;
138
+ cardholderFirstName: string;
139
+ cardholderLastName: string;
140
+ cardholderPhoneNumber: string;
141
+ spend: {
142
+ daily: {
143
+ amount: number;
144
+ limit?: number | undefined;
145
+ };
146
+ weekly: {
147
+ amount: number;
148
+ limit?: number | undefined;
149
+ };
150
+ monthly: {
151
+ amount: number;
152
+ limit?: number | undefined;
153
+ };
154
+ lifetime: {
155
+ amount: number;
156
+ limit?: number | undefined;
157
+ };
158
+ };
159
+ allowedSpendCategories: ("other" | "airlines" | "carRental" | "carService" | "education" | "electronics" | "gasPump" | "gasStation" | "generalMerchandise" | "government" | "hardwareAndConstruction" | "insurance" | "legal" | "lodging" | "medical" | "parking" | "phoneAndInternet" | "professionalServices" | "recreationAndEntertainment" | "restaurants" | "shipping" | "software" | "taxisAndRideshare" | "transportation" | "travelMisc" | "utilities")[];
160
+ nickname?: string | null | undefined;
161
+ physicalCard?: {
162
+ id: string;
163
+ } | null | undefined;
164
+ }, {
165
+ id: string;
166
+ status: "active" | "inactive" | "canceled" | "frozen";
167
+ platformId: string;
168
+ accountUserId: string | null;
169
+ last4: string;
170
+ cardholderFirstName: string;
171
+ cardholderLastName: string;
172
+ cardholderPhoneNumber: string;
173
+ spend: {
174
+ daily: {
175
+ amount: number;
176
+ limit?: number | undefined;
177
+ };
178
+ weekly: {
179
+ amount: number;
180
+ limit?: number | undefined;
181
+ };
182
+ monthly: {
183
+ amount: number;
184
+ limit?: number | undefined;
185
+ };
186
+ lifetime: {
187
+ amount: number;
188
+ limit?: number | undefined;
189
+ };
190
+ };
191
+ allowedSpendCategories: ("other" | "airlines" | "carRental" | "carService" | "education" | "electronics" | "gasPump" | "gasStation" | "generalMerchandise" | "government" | "hardwareAndConstruction" | "insurance" | "legal" | "lodging" | "medical" | "parking" | "phoneAndInternet" | "professionalServices" | "recreationAndEntertainment" | "restaurants" | "shipping" | "software" | "taxisAndRideshare" | "transportation" | "travelMisc" | "utilities")[];
192
+ nickname?: string | null | undefined;
193
+ physicalCard?: {
194
+ id: string;
195
+ } | null | undefined;
196
+ }>;
197
+
198
+ export declare type CommonProps = {
13
199
  /**
14
200
  * The token provided by initiate-login.
15
201
  */
@@ -30,14 +216,48 @@ export declare function App(props: {
30
216
  * Optional component to render while the app is loading.
31
217
  */
32
218
  loadingComponent?: ReactNode;
33
- }): JSX.Element;
219
+ };
220
+
221
+ export declare function decodeToken(token: string): any;
34
222
 
35
223
  /**
36
- * Base class for all SDK errors
224
+ * Renders the CapitalOS Dispute Transaction experience.
37
225
  */
38
- export declare class CapitalOSError extends Error {
39
- constructor(message: string);
40
- }
226
+ export declare function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps): JSX.Element;
227
+
228
+ export declare type DisputeTransactionProps = CommonProps & {
229
+ /**
230
+ * The ID of the transaction to dispute.
231
+ */
232
+ transactionId: string;
233
+ /**
234
+ * Callback to invoke when the dispute was successfully submitted.
235
+ */
236
+ onDone: () => void;
237
+ /**
238
+ * Callback to invoke when the user cancels the dispute submission.
239
+ */
240
+ onCancel: () => void;
241
+ };
242
+
243
+ /**
244
+ * Encodes the rendering context as base64 and then URI encodes it.
245
+ */
246
+ export declare function encodeRenderingContext<T>(renderingContext: NonNullable<T>): string;
247
+
248
+ export declare type EntryPoint = RenderingContext_2['entryPoint'];
249
+
250
+ export declare type IframeConnectionMethods = {
251
+ onLoad: () => void;
252
+ createCard?: {
253
+ onDone?: () => void;
254
+ onCancel?: () => void;
255
+ };
256
+ createDispute?: {
257
+ onDone?: () => void;
258
+ onCancel?: () => void;
259
+ };
260
+ };
41
261
 
42
262
  export declare const IframeResizer: React_2.ForwardRefExoticComponent<Omit<IFrameOptions, "closedCallback" | "scrollCallback" | "resizedCallback" | "messageCallback" | "initCallback"> & {
43
263
  onClosed?(iframeId: string): void;
@@ -54,4 +274,134 @@ export declare class InvalidTokenError extends CapitalOSError {
54
274
  constructor();
55
275
  }
56
276
 
277
+ /**
278
+ * Renders the CapitalOS Issue Card experience.
279
+ */
280
+ export declare function IssueCard({ defaultValues, onDone, onCancel, ...restOfProps }: IssueCardProps): JSX.Element;
281
+
282
+ export declare type IssueCardDefaultValues = z_2.infer<typeof issueCardDefaultValuesSchema>;
283
+
284
+ declare const issueCardDefaultValuesSchema: z_2.ZodIntersection<z_2.ZodUnion<[z_2.ZodObject<{
285
+ firstName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
286
+ lastName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
287
+ phone: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
288
+ userId: z_2.ZodOptional<z_2.ZodUndefined>;
289
+ }, "strip", z_2.ZodTypeAny, {
290
+ firstName?: string | null | undefined;
291
+ lastName?: string | null | undefined;
292
+ phone?: string | null | undefined;
293
+ userId?: undefined;
294
+ }, {
295
+ firstName?: string | null | undefined;
296
+ lastName?: string | null | undefined;
297
+ phone?: string | null | undefined;
298
+ userId?: undefined;
299
+ }>, z_2.ZodObject<{
300
+ userId: z_2.ZodString;
301
+ }, "strip", z_2.ZodTypeAny, {
302
+ userId: string;
303
+ }, {
304
+ userId: string;
305
+ }>]>, z_2.ZodObject<{
306
+ nickname: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
307
+ }, "strip", z_2.ZodTypeAny, {
308
+ nickname?: string | null | undefined;
309
+ }, {
310
+ nickname?: string | null | undefined;
311
+ }>>;
312
+
313
+ export declare type IssueCardProps = CommonProps & {
314
+ /**
315
+ * Default values to prefill the form with.
316
+ *
317
+ * 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.
318
+ */
319
+ defaultValues?: IssueCardDefaultValues;
320
+ /**
321
+ * Callback to invoke when the card was created successfully.
322
+ */
323
+ onDone: () => void;
324
+ /**
325
+ * Callback to invoke when the card creation was cancelled by the user.
326
+ */
327
+ onCancel: () => void;
328
+ };
329
+
330
+ declare type RenderingContext_2 = z_2.infer<typeof renderingContextSchema>;
331
+
332
+ declare const renderingContextSchema: z_2.ZodDiscriminatedUnion<"entryPoint", [z_2.ZodObject<{
333
+ entryPoint: z_2.ZodLiteral<"createCard">;
334
+ defaultValues: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodIntersection<z_2.ZodUnion<[z_2.ZodObject<{
335
+ firstName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
336
+ lastName: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
337
+ phone: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
338
+ userId: z_2.ZodOptional<z_2.ZodUndefined>;
339
+ }, "strip", z_2.ZodTypeAny, {
340
+ firstName?: string | null | undefined;
341
+ lastName?: string | null | undefined;
342
+ phone?: string | null | undefined;
343
+ userId?: undefined;
344
+ }, {
345
+ firstName?: string | null | undefined;
346
+ lastName?: string | null | undefined;
347
+ phone?: string | null | undefined;
348
+ userId?: undefined;
349
+ }>, z_2.ZodObject<{
350
+ userId: z_2.ZodString;
351
+ }, "strip", z_2.ZodTypeAny, {
352
+ userId: string;
353
+ }, {
354
+ userId: string;
355
+ }>]>, z_2.ZodObject<{
356
+ nickname: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
357
+ }, "strip", z_2.ZodTypeAny, {
358
+ nickname?: string | null | undefined;
359
+ }, {
360
+ nickname?: string | null | undefined;
361
+ }>>>>;
362
+ }, "strip", z_2.ZodTypeAny, {
363
+ entryPoint: "createCard";
364
+ defaultValues?: (({
365
+ firstName?: string | null | undefined;
366
+ lastName?: string | null | undefined;
367
+ phone?: string | null | undefined;
368
+ userId?: undefined;
369
+ } | {
370
+ userId: string;
371
+ }) & {
372
+ nickname?: string | null | undefined;
373
+ }) | null | undefined;
374
+ }, {
375
+ entryPoint: "createCard";
376
+ defaultValues?: (({
377
+ firstName?: string | null | undefined;
378
+ lastName?: string | null | undefined;
379
+ phone?: string | null | undefined;
380
+ userId?: undefined;
381
+ } | {
382
+ userId: string;
383
+ }) & {
384
+ nickname?: string | null | undefined;
385
+ }) | null | undefined;
386
+ }>, z_2.ZodObject<{
387
+ entryPoint: z_2.ZodLiteral<"createDispute">;
388
+ transactionId: z_2.ZodString;
389
+ }, "strip", z_2.ZodTypeAny, {
390
+ entryPoint: "createDispute";
391
+ transactionId: string;
392
+ }, {
393
+ entryPoint: "createDispute";
394
+ transactionId: string;
395
+ }>]>;
396
+
397
+ /**
398
+ * connects to child iframe and returns whether the iframe is loaded or not.
399
+ */
400
+ export declare function useIframeConnection({ iframeRef, token, onError, methods, }: {
401
+ iframeRef: React.RefObject<HTMLIFrameElement>;
402
+ token: string;
403
+ onError: ((error: Error) => void) | undefined | null;
404
+ methods: IframeConnectionMethods;
405
+ }): void;
406
+
57
407
  export { }
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use client";var z=Object.defineProperty,T=Object.defineProperties;var O=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var R=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var L=(t,e,r)=>e in t?z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,d=(t,e)=>{for(var r in e||(e={}))R.call(e,r)&&L(t,r,e[r]);if(h)for(var r of h(e))H.call(e,r)&&L(t,r,e[r]);return t},M=(t,e)=>T(t,O(e));import{connectToChild as A}from"penpal";import l,{useEffect as D,useMemo as P}from"react";var f=class extends Error{constructor(e){super(e),this.name="CapitalOSError"}},m=class extends f{constructor(){super("Invalid token"),this.name="CapitalOSInvalidTokenError"}};import{iframeResizer as k}from"iframe-resizer";import C,{forwardRef as E,useEffect as y,useImperativeHandle as v,useRef as N}from"react";var p=E((t,e)=>{let r=t.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:i}=x(t),a=N(null);return y(()=>{let n=a.current;return k(d({},i),n),()=>n.iFrameResizer&&n.iFrameResizer.removeListeners()}),v(e,()=>a.current),C.createElement("iframe",M(d({},o),{title:r,ref:a}))});p.displayName="IframeResizer";var S=["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"],w=new Set(S);function x(t){return Object.keys(t).reduce((r,o)=>(w.has(o)?r.resizerOptions[o]=t[o]:r.iframeHTMLAttributes[o]=t[o],r),{resizerOptions:{},iframeHTMLAttributes:{}})}var W=1e4;function oe(t){let{token:e,className:r,enableLogging:o,onError:i,loadingComponent:a}=t,n=l.useRef(null),[u,I]=l.useState(!1),F=P(()=>{try{let s=decodeURIComponent(e),c=atob(s),b=JSON.parse(c),{path:g}=b;if(!g)throw new m;return`${g}?token=${e}`}catch(s){i==null||i(new m);return}},[e,i]);return D(()=>{let s=A({iframe:n.current,childOrigin:"*",debug:!0,timeout:W,methods:{onLoad:()=>{I(!0)}}});return s.promise.catch(c=>{i==null||i(c),I(!0)}),()=>{s.destroy()}},[e]),l.createElement(l.Fragment,null,!u&&a,l.createElement(p,{src:F,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:r,log:!!o,ref:n,hidden:!u}))}export{oe as App};
1
+ "use client";var H=Object.defineProperty,v=Object.defineProperties;var D=Object.getOwnPropertyDescriptors;var p=Object.getOwnPropertySymbols;var L=Object.prototype.hasOwnProperty,b=Object.prototype.propertyIsEnumerable;var y=(e,t,o)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,a=(e,t)=>{for(var o in t||(t={}))L.call(t,o)&&y(e,o,t[o]);if(p)for(var o of p(t))b.call(t,o)&&y(e,o,t[o]);return e},l=(e,t)=>v(e,D(t));var u=(e,t)=>{var o={};for(var r in e)L.call(e,r)&&t.indexOf(r)<0&&(o[r]=e[r]);if(e!=null&&p)for(var r of p(e))t.indexOf(r)<0&&b.call(e,r)&&(o[r]=e[r]);return o};import h,{useMemo as P}from"react";import g,{useMemo as q,useRef as G,useState as K}from"react";var I=class extends Error{constructor(t){super(t),this.name="CapitalOSError"}},m=class extends I{constructor(){super("Invalid token"),this.name="CapitalOSInvalidTokenError"}};import{connectToChild as S}from"penpal";import{useEffect as w}from"react";var N=1e4;function F({iframeRef:e,token:t,onError:o,methods:r}){w(()=>{let n=S({iframe:e.current,childOrigin:"*",debug:!0,timeout:N,methods:r});return n.promise.catch(i=>{o==null||o(i)}),()=>{n.destroy()}},[t])}import{iframeResizer as A}from"iframe-resizer";import B,{forwardRef as W,useEffect as _,useImperativeHandle as j,useRef as J}from"react";var C=W((e,t)=>{let o=e.title||"iframe",{iframeHTMLAttributes:r,resizerOptions:n}=$(e),i=J(null);return _(()=>{let s=i.current;return A(a({},n),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),j(t,()=>i.current),B.createElement("iframe",l(a({},r),{title:o,ref:i}))});C.displayName="IframeResizer";var U=["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"],V=new Set(U);function $(e){return Object.keys(e).reduce((o,r)=>(V.has(r)?o.resizerOptions[r]=e[r]:o.iframeHTMLAttributes[r]=e[r],o),{resizerOptions:{},iframeHTMLAttributes:{}})}function z(e){let t=JSON.stringify(e),o=btoa(t);return encodeURIComponent(o)}function R(e){try{let t=decodeURIComponent(e),o=atob(t);return JSON.parse(o)}catch(t){throw new m}}function f(e){let{token:t,className:o,enableLogging:r,onError:n,loadingComponent:i,renderingContext:s,methods:c}=e,[T,M]=K(!1),x=G(null),k=q(()=>{try{let d=s?z(s):null,E=R(t),{path:O}=E;if(!O)throw new m;return`${O}?token=${t}&renderingContext=${d!=null?d:""}`}catch(d){n==null||n(new m);return}},[t,n]);return F({iframeRef:x,token:t,onError:d=>{n==null||n(d),M(!0)},methods:a({onLoad:()=>M(!0)},c)}),g.createElement(g.Fragment,null,!T&&i,g.createElement(C,{src:k,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:o,log:!!r,ref:x,hidden:!T}))}function ye(e){return h.createElement(f,a({},e))}function Le(n){var i=n,{defaultValues:e,onDone:t,onCancel:o}=i,r=u(i,["defaultValues","onDone","onCancel"]);let s="createCard",c=P(()=>({entryPoint:s,defaultValues:e}),[e]);return h.createElement(f,l(a({},r),{renderingContext:c,methods:{createCard:{onDone:t,onCancel:o}}}))}function be(n){var i=n,{transactionId:e,onDone:t,onCancel:o}=i,r=u(i,["transactionId","onDone","onCancel"]);let s="createDispute",c=P(()=>({entryPoint:s,transactionId:e}),[e]);return h.createElement(f,l(a({},r),{renderingContext:c,methods:{createDispute:{onDone:t,onCancel:o}}}))}export{ye as App,be as DisputeTransaction,Le as IssueCard};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.tsx","../../src/error.ts","../../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport { connectToChild } from 'penpal'\nimport React, { ReactNode, useEffect, useMemo } from 'react'\n\nimport { InvalidTokenError } from './error'\nimport { IframeResizer } from './iframe-resizer'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * Renders the CapitalOS App.\n */\nexport function App(props: {\n /**\n * The token provided by initiate-login.\n */\n token: string\n /**\n * Optional CSS class name for the component.\n */\n className?: string\n /**\n * Optional flag indicating whether to log events to the console.\n */\n enableLogging?: boolean\n\n /**\n * Optional callback for when the app encounters an error.\n */\n onError?: (error: Error) => void\n\n /**\n * Optional component to render while the app is loading.\n */\n loadingComponent?: ReactNode\n}) {\n const { token, className, enableLogging, onError, loadingComponent: LoadingComponent } = props\n\n const iframeRef = React.useRef<HTMLIFrameElement>(null)\n\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = React.useState(false)\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 urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n const jsonToken = JSON.parse(base64DecodedToken)\n const { path } = jsonToken\n if (!path) {\n throw new InvalidTokenError()\n }\n return `${path}?token=${token}`\n } catch (error) {\n onError?.(new InvalidTokenError())\n return undefined\n }\n }, [token, onError])\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 onLoad: () => {\n setIsLoaded(true)\n },\n },\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n\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\n return () => {\n connection.destroy()\n }\n }, [token])\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 />\n </>\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CapitalOSError'\n }\n}\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor() {\n super('Invalid token')\n this.name = 'CapitalOSInvalidTokenError'\n }\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":"0bAEA,OAAS,kBAAAA,MAAsB,SAC/B,OAAOC,GAAoB,aAAAC,EAAW,WAAAC,MAAe,QCA9C,IAAMC,EAAN,cAA6B,KAAM,CACxC,YAAYC,EAAiB,CAC3B,MAAMA,CAAO,EACb,KAAK,KAAO,gBACd,CACF,EAKaC,EAAN,cAAgCF,CAAe,CACpD,aAAc,CACZ,MAAM,eAAe,EACrB,KAAK,KAAO,4BACd,CACF,EClBA,OAME,iBAAAG,MACK,iBACP,OAAOC,GAA+B,cAAAC,EAAY,aAAAC,EAAW,uBAAAC,EAAqB,UAAAC,MAAc,QAiBzF,IAAMC,EAAgBC,EAAW,CAACC,EAA2BC,IAAsC,CACxG,IAAMC,EAAQF,EAAM,OAAS,SACvB,CAAE,qBAAAG,EAAsB,eAAAC,CAAe,EAAIC,EAAWL,CAAK,EAC3DM,EAAYC,EAA0B,IAAI,EAEhD,OAAAC,EAAU,IAAM,CAEd,IAAMC,EAASH,EAAU,QAEzB,OAAAI,EAAcC,EAAA,GAAKP,GAAkBK,CAAM,EAEpC,IAAMA,EAAO,eAAiBA,EAAO,cAAc,gBAAgB,CAC5E,CAAC,EAGDG,EAAoBX,EAAK,IAAMK,EAAU,OAA4B,EAE9DO,EAAA,cAAC,SAAAC,EAAAH,EAAA,GAAWR,GAAX,CAAiC,MAAOD,EAAO,IAAKI,GAAW,CACzE,CAAC,EAEDR,EAAc,YAAc,gBAE5B,IAAMM,EAAiB,CACrB,aACA,iBACA,aACA,cACA,cACA,cACA,0BACA,WACA,MACA,YACA,WACA,YACA,WACA,aACA,YACA,aACA,YACA,iBACA,YACA,yBACA,WACA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,CACF,EAAG,CAAClB,CAAK,CAAC,EAGRM,EAAA,cAAAA,EAAA,cAEG,CAACC,GAAYH,EAEdE,EAAA,cAACc,EAAA,CACC,IAAKX,EACL,MAAM,kBACN,YAAa,GACb,MAAO,CAAE,MAAO,MAAO,OAAQ,MAAO,SAAU,MAAO,EACvD,UAAWR,EACX,IAAK,CAAC,CAACC,EACP,IAAKG,EACL,OAAQ,CAACE,EACX,CACF,CAEJ","names":["connectToChild","React","useEffect","useMemo","CapitalOSError","message","InvalidTokenError","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","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","App","props","token","className","enableLogging","onError","LoadingComponent","iframeRef","React","isLoaded","setIsLoaded","url","useMemo","urlDecodedToken","base64DecodedToken","jsonToken","path","InvalidTokenError","error","useEffect","connection","connectToChild","IframeResizer"]}
1
+ {"version":3,"sources":["../../src/index.tsx","../../src/capital-os.tsx","../../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 { CommonProps } from './types'\n\n/**\n * Renders the CapitalOS App.\n */\nexport function App(props: CommonProps) {\n return <CapitalOS {...props} />\n}\n\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 defaultValues?: 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({ defaultValues, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n defaultValues: defaultValues,\n }),\n [defaultValues],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n\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","import React, { useMemo, useRef, useState } from 'react'\n\nimport { InvalidTokenError } from './error'\nimport { IframeConnectionMethods, useIframeConnection } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps } from './types'\nimport { decodeToken, encodeRenderingContext } from './utils'\n\ntype CapitalOsProps<T> = CommonProps & {\n renderingContext?: T | undefined\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>(props: CapitalOsProps<T>) {\n const {\n token,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\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 encodedRenderingContext = renderingContext ? encodeRenderingContext(renderingContext) : null\n\n const tokenObject = decodeToken(token)\n\n const { path } = tokenObject\n if (!path) {\n throw new InvalidTokenError()\n }\n return `${path}?token=${token}&renderingContext=${encodedRenderingContext ?? ''}`\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: { onLoad: () => setIsLoaded(true), ...methods },\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 />\n </>\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CapitalOSError'\n }\n}\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor() {\n super('Invalid token')\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect } from 'react'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => 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: 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,MA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Q,SAAAC,CAxE5D,EAwEmCH,EAAsCI,EAAAC,EAAtCL,EAAsC,CAApC,gBAAe,SAAQ,aAC1D,IAAMM,EAAyB,gBACzBC,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,EAAY,cAAAK,CAAc,GAAI,CAACA,CAAa,CAAC,EAEvF,OACEhB,EAAA,cAACC,EAAAa,EAAAZ,EAAA,GAAcO,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,cAAe,CAAE,OAAAL,EAAQ,SAAAC,CAAS,CAAE,GAAG,CAEtH","names":["React","useMemo","React","useMemo","useRef","useState","CapitalOSError","message","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","isLoaded","setIsLoaded","useState","iframeRef","useRef","url","useMemo","encodedRenderingContext","encodeRenderingContext","tokenObject","decodeToken","path","InvalidTokenError","error","useIframeConnection","__spreadValues","React","IframeResizer","App","props","React","CapitalOS","__spreadValues","IssueCard","_a","_b","defaultValues","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","useMemo","__spreadProps","DisputeTransaction","transactionId"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";"use client";var E=Object.create;var c=Object.defineProperty,y=Object.defineProperties,v=Object.getOwnPropertyDescriptor,N=Object.getOwnPropertyDescriptors,S=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,w=Object.getPrototypeOf,b=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var F=(e,t,r)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,p=(e,t)=>{for(var r in t||(t={}))b.call(t,r)&&F(e,r,t[r]);if(M)for(var r of M(t))x.call(t,r)&&F(e,r,t[r]);return e},z=(e,t)=>y(e,N(t));var A=(e,t)=>{for(var r in t)c(e,r,{get:t[r],enumerable:!0})},T=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of S(t))!b.call(e,o)&&o!==r&&c(e,o,{get:()=>t[o],enumerable:!(i=v(t,o))||i.enumerable});return e};var O=(e,t,r)=>(r=e!=null?E(w(e)):{},T(t||!e||!e.__esModule?c(r,"default",{value:e,enumerable:!0}):r,e)),D=e=>T(c({},"__esModule",{value:!0}),e);var U={};A(U,{App:()=>j});module.exports=D(U);var H=require("penpal"),a=O(require("react"));var u=class extends Error{constructor(t){super(t),this.name="CapitalOSError"}},d=class extends u{constructor(){super("Invalid token"),this.name="CapitalOSInvalidTokenError"}};var R=require("iframe-resizer"),n=O(require("react"));var I=(0,n.forwardRef)((e,t)=>{let r=e.title||"iframe",{iframeHTMLAttributes:i,resizerOptions:o}=_(e),m=(0,n.useRef)(null);return(0,n.useEffect)(()=>{let s=m.current;return(0,R.iframeResizer)(p({},o),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),(0,n.useImperativeHandle)(t,()=>m.current),n.default.createElement("iframe",z(p({},i),{title:r,ref:m}))});I.displayName="IframeResizer";var P=["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"],W=new Set(P);function _(e){return Object.keys(e).reduce((r,i)=>(W.has(i)?r.resizerOptions[i]=e[i]:r.iframeHTMLAttributes[i]=e[i],r),{resizerOptions:{},iframeHTMLAttributes:{}})}var B=1e4;function j(e){let{token:t,className:r,enableLogging:i,onError:o,loadingComponent:m}=e,s=a.default.useRef(null),[g,h]=a.default.useState(!1),k=(0,a.useMemo)(()=>{try{let l=decodeURIComponent(t),f=atob(l),C=JSON.parse(f),{path:L}=C;if(!L)throw new d;return`${L}?token=${t}`}catch(l){o==null||o(new d);return}},[t,o]);return(0,a.useEffect)(()=>{let l=(0,H.connectToChild)({iframe:s.current,childOrigin:"*",debug:!0,timeout:B,methods:{onLoad:()=>{h(!0)}}});return l.promise.catch(f=>{o==null||o(f),h(!0)}),()=>{l.destroy()}},[t]),a.default.createElement(a.default.Fragment,null,!g&&m,a.default.createElement(I,{src:k,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:r,log:!!i,ref:s,hidden:!g}))}0&&(module.exports={App});
1
+ "use strict";"use client";var A=Object.create;var u=Object.defineProperty,B=Object.defineProperties,W=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertyNames,C=Object.getOwnPropertySymbols,J=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable;var z=(e,t,o)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,d=(e,t)=>{for(var o in t||(t={}))h.call(t,o)&&z(e,o,t[o]);if(C)for(var o of C(t))R.call(t,o)&&z(e,o,t[o]);return e},I=(e,t)=>B(e,_(t));var T=(e,t)=>{var o={};for(var r in e)h.call(e,r)&&t.indexOf(r)<0&&(o[r]=e[r]);if(e!=null&&C)for(var r of C(e))t.indexOf(r)<0&&R.call(e,r)&&(o[r]=e[r]);return o};var U=(e,t)=>{for(var o in t)u(e,o,{get:t[o],enumerable:!0})},P=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of j(t))!h.call(e,n)&&n!==o&&u(e,n,{get:()=>t[n],enumerable:!(r=W(t,n))||r.enumerable});return e};var M=(e,t,o)=>(o=e!=null?A(J(e)):{},P(t||!e||!e.__esModule?u(o,"default",{value:e,enumerable:!0}):o,e)),V=e=>P(u({},"__esModule",{value:!0}),e);var Z={};U(Z,{App:()=>Q,DisputeTransaction:()=>Y,IssueCard:()=>X});module.exports=V(Z);var l=M(require("react"));var m=M(require("react"));var x=class extends Error{constructor(t){super(t),this.name="CapitalOSError"}},c=class extends x{constructor(){super("Invalid token"),this.name="CapitalOSInvalidTokenError"}};var k=require("penpal"),E=require("react"),$=1e4;function H({iframeRef:e,token:t,onError:o,methods:r}){(0,E.useEffect)(()=>{let n=(0,k.connectToChild)({iframe:e.current,childOrigin:"*",debug:!0,timeout:$,methods:r});return n.promise.catch(i=>{o==null||o(i)}),()=>{n.destroy()}},[t])}var v=require("iframe-resizer"),a=M(require("react"));var O=(0,a.forwardRef)((e,t)=>{let o=e.title||"iframe",{iframeHTMLAttributes:r,resizerOptions:n}=K(e),i=(0,a.useRef)(null);return(0,a.useEffect)(()=>{let s=i.current;return(0,v.iframeResizer)(d({},n),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),(0,a.useImperativeHandle)(t,()=>i.current),a.default.createElement("iframe",I(d({},r),{title:o,ref:i}))});O.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"],G=new Set(q);function K(e){return Object.keys(e).reduce((o,r)=>(G.has(r)?o.resizerOptions[r]=e[r]:o.iframeHTMLAttributes[r]=e[r],o),{resizerOptions:{},iframeHTMLAttributes:{}})}function D(e){let t=JSON.stringify(e),o=btoa(t);return encodeURIComponent(o)}function S(e){try{let t=decodeURIComponent(e),o=atob(t);return JSON.parse(o)}catch(t){throw new c}}function g(e){let{token:t,className:o,enableLogging:r,onError:n,loadingComponent:i,renderingContext:s,methods:f}=e,[y,L]=(0,m.useState)(!1),b=(0,m.useRef)(null),w=(0,m.useMemo)(()=>{try{let p=s?D(s):null,N=S(t),{path:F}=N;if(!F)throw new c;return`${F}?token=${t}&renderingContext=${p!=null?p:""}`}catch(p){n==null||n(new c);return}},[t,n]);return H({iframeRef:b,token:t,onError:p=>{n==null||n(p),L(!0)},methods:d({onLoad:()=>L(!0)},f)}),m.default.createElement(m.default.Fragment,null,!y&&i,m.default.createElement(O,{src:w,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:o,log:!!r,ref:b,hidden:!y}))}function Q(e){return l.default.createElement(g,d({},e))}function X(n){var i=n,{defaultValues:e,onDone:t,onCancel:o}=i,r=T(i,["defaultValues","onDone","onCancel"]);let s="createCard",f=(0,l.useMemo)(()=>({entryPoint:s,defaultValues:e}),[e]);return l.default.createElement(g,I(d({},r),{renderingContext:f,methods:{createCard:{onDone:t,onCancel:o}}}))}function Y(n){var i=n,{transactionId:e,onDone:t,onCancel:o}=i,r=T(i,["transactionId","onDone","onCancel"]);let s="createDispute",f=(0,l.useMemo)(()=>({entryPoint:s,transactionId:e}),[e]);return l.default.createElement(g,I(d({},r),{renderingContext:f,methods:{createDispute:{onDone:t,onCancel:o}}}))}0&&(module.exports={App,DisputeTransaction,IssueCard});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.tsx","../src/error.ts","../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport { connectToChild } from 'penpal'\nimport React, { ReactNode, useEffect, useMemo } from 'react'\n\nimport { InvalidTokenError } from './error'\nimport { IframeResizer } from './iframe-resizer'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * Renders the CapitalOS App.\n */\nexport function App(props: {\n /**\n * The token provided by initiate-login.\n */\n token: string\n /**\n * Optional CSS class name for the component.\n */\n className?: string\n /**\n * Optional flag indicating whether to log events to the console.\n */\n enableLogging?: boolean\n\n /**\n * Optional callback for when the app encounters an error.\n */\n onError?: (error: Error) => void\n\n /**\n * Optional component to render while the app is loading.\n */\n loadingComponent?: ReactNode\n}) {\n const { token, className, enableLogging, onError, loadingComponent: LoadingComponent } = props\n\n const iframeRef = React.useRef<HTMLIFrameElement>(null)\n\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = React.useState(false)\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 urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n const jsonToken = JSON.parse(base64DecodedToken)\n const { path } = jsonToken\n if (!path) {\n throw new InvalidTokenError()\n }\n return `${path}?token=${token}`\n } catch (error) {\n onError?.(new InvalidTokenError())\n return undefined\n }\n }, [token, onError])\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 onLoad: () => {\n setIsLoaded(true)\n },\n },\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n\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\n return () => {\n connection.destroy()\n }\n }, [token])\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 />\n </>\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CapitalOSError'\n }\n}\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor() {\n super('Invalid token')\n this.name = 'CapitalOSInvalidTokenError'\n }\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":"85BAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,IAAA,eAAAC,EAAAH,GAEA,IAAAI,EAA+B,kBAC/BC,EAAqD,oBCA9C,IAAMC,EAAN,cAA6B,KAAM,CACxC,YAAYC,EAAiB,CAC3B,MAAMA,CAAO,EACb,KAAK,KAAO,gBACd,CACF,EAKaC,EAAN,cAAgCF,CAAe,CACpD,aAAc,CACZ,MAAM,eAAe,EACrB,KAAK,KAAO,4BACd,CACF,EClBA,IAAAG,EAOO,0BACPC,EAAgG,oBAiBzF,IAAMC,KAAgB,cAAW,CAACC,EAA2BC,IAAsC,CACxG,IAAMC,EAAQF,EAAM,OAAS,SACvB,CAAE,qBAAAG,EAAsB,eAAAC,CAAe,EAAIC,EAAWL,CAAK,EAC3DM,KAAY,UAA0B,IAAI,EAEhD,sBAAU,IAAM,CAEd,IAAMC,EAASD,EAAU,QAEzB,0BAAcE,EAAA,GAAKJ,GAAkBG,CAAM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AAA,EAAU,IAAIW,GACd,MACF,CACF,EAAG,CAACd,EAAOG,CAAO,CAAC,EAGnB,sBAAU,IAAM,CACd,IAAMa,KAAa,kBAAe,CAChC,OAAQX,EAAU,QAClB,YAAa,IACb,MAAO,GACP,QAASR,EACT,QAAS,CACP,OAAQ,IAAM,CACZW,EAAY,EAAI,CAClB,CACF,CACF,CAAC,EAED,OAAAQ,EAAW,QAAQ,MAAOD,GAAU,CAClCZ,GAAA,MAAAA,EAAUY,GAIVP,EAAY,EAAI,CAClB,CAAC,EAEM,IAAM,CACXQ,EAAW,QAAQ,CACrB,CACF,EAAG,CAAChB,CAAK,CAAC,EAGR,EAAAM,QAAA,gBAAAA,QAAA,cAEG,CAACC,GAAYH,EAEd,EAAAE,QAAA,cAACW,EAAA,CACC,IAAKR,EACL,MAAM,kBACN,YAAa,GACb,MAAO,CAAE,MAAO,MAAO,OAAQ,MAAO,SAAU,MAAO,EACvD,UAAWR,EACX,IAAK,CAAC,CAACC,EACP,IAAKG,EACL,OAAQ,CAACE,EACX,CACF,CAEJ","names":["src_exports","__export","App","__toCommonJS","import_penpal","import_react","CapitalOSError","message","InvalidTokenError","import_iframe_resizer","import_react","IframeResizer","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","iframe","__spreadValues","React","__spreadProps","resizerOptionsSet","acc","key","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","App","props","token","className","enableLogging","onError","LoadingComponent","iframeRef","React","isLoaded","setIsLoaded","url","urlDecodedToken","base64DecodedToken","jsonToken","path","InvalidTokenError","error","connection","IframeResizer"]}
1
+ {"version":3,"sources":["../src/index.tsx","../src/capital-os.tsx","../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 { CommonProps } from './types'\n\n/**\n * Renders the CapitalOS App.\n */\nexport function App(props: CommonProps) {\n return <CapitalOS {...props} />\n}\n\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 defaultValues?: 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({ defaultValues, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n defaultValues: defaultValues,\n }),\n [defaultValues],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n\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","import React, { useMemo, useRef, useState } from 'react'\n\nimport { InvalidTokenError } from './error'\nimport { IframeConnectionMethods, useIframeConnection } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps } from './types'\nimport { decodeToken, encodeRenderingContext } from './utils'\n\ntype CapitalOsProps<T> = CommonProps & {\n renderingContext?: T | undefined\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>(props: CapitalOsProps<T>) {\n const {\n token,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\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 encodedRenderingContext = renderingContext ? encodeRenderingContext(renderingContext) : null\n\n const tokenObject = decodeToken(token)\n\n const { path } = tokenObject\n if (!path) {\n throw new InvalidTokenError()\n }\n return `${path}?token=${token}&renderingContext=${encodedRenderingContext ?? ''}`\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: { onLoad: () => setIsLoaded(true), ...methods },\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 />\n </>\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CapitalOSError'\n }\n}\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor() {\n super('Invalid token')\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect } from 'react'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => 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: 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,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,uBAAAC,EAAA,cAAAC,IAAA,eAAAC,EAAAL,GAEA,IAAAM,EAA+B,oBCF/B,IAAAC,EAAiD,oBCG1C,IAAMC,EAAN,cAA6B,KAAM,CACxC,YAAYC,EAAiB,CAC3B,MAAMA,CAAO,EACb,KAAK,KAAO,gBACd,CACF,EAKaC,EAAN,cAAgCF,CAAe,CACpD,aAAc,CACZ,MAAM,eAAe,EACrB,KAAK,KAAO,4BACd,CACF,EClBA,IAAAG,EAA+B,kBAC/BC,EAA0B,iBAEpBC,EAAyC,IAiBxC,SAASC,EAAoB,CAClC,UAAAC,EACA,MAAAC,EACA,QAAAC,EACA,QAAAC,CACF,EAKG,IAED,aAAU,IAAM,CACd,IAAMC,KAAa,kBAAe,CAChC,OAAQJ,EAAU,QAClB,YAAa,IACb,MAAO,GACP,QAASF,EACT,QAASK,CACX,CAAC,EAED,OAAAC,EAAW,QAAQ,MAAOC,GAAU,CAClCH,GAAA,MAAAA,EAAUG,EACZ,CAAC,EAEM,IAAM,CACXD,EAAW,QAAQ,CACrB,CACF,EAAG,CAACH,CAAK,CAAC,CACZ,CCjDA,IAAAK,EAOO,0BACPC,EAAgG,oBAiBzF,IAAMC,KAAgB,cAAW,CAACC,EAA2BC,IAAsC,CACxG,IAAMC,EAAQF,EAAM,OAAS,SACvB,CAAE,qBAAAG,EAAsB,eAAAC,CAAe,EAAIC,EAAWL,CAAK,EAC3DM,KAAY,UAA0B,IAAI,EAEhD,sBAAU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A,CAAa,CAChB,EAEA,OACE,EAAAN,QAAA,cAACC,EAAAY,EAAAX,EAAA,GAAcO,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,EAAQ,SAAAC,CAAS,CAAE,GAAG,CAEnH,CAsBO,SAASM,EAAmBV,EAA8E,CAA9E,IAAAC,EAAAD,EAAE,eAAAW,EAAe,OAAAR,EAAQ,SAAAC,CAxE5D,EAwEmCH,EAAsCI,EAAAC,EAAtCL,EAAsC,CAApC,gBAAe,SAAQ,aAC1D,IAAMM,EAAyB,gBACzBC,KAAmB,WAAQ,KAAO,CAAE,WAAAD,EAAY,cAAAI,CAAc,GAAI,CAACA,CAAa,CAAC,EAEvF,OACE,EAAAf,QAAA,cAACC,EAAAY,EAAAX,EAAA,GAAcO,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,cAAe,CAAE,OAAAL,EAAQ,SAAAC,CAAS,CAAE,GAAG,CAEtH","names":["src_exports","__export","App","DisputeTransaction","IssueCard","__toCommonJS","import_react","import_react","CapitalOSError","message","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","isLoaded","setIsLoaded","iframeRef","url","encodedRenderingContext","encodeRenderingContext","tokenObject","decodeToken","path","InvalidTokenError","error","useIframeConnection","__spreadValues","React","IframeResizer","App","props","React","CapitalOS","__spreadValues","IssueCard","_a","_b","defaultValues","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","__spreadProps","DisputeTransaction","transactionId"]}
@@ -1 +1,5 @@
1
1
  export { App } from '../_tsup-dts-rollup';
2
+ export { IssueCard } from '../_tsup-dts-rollup';
3
+ export { DisputeTransaction } from '../_tsup-dts-rollup';
4
+ export { IssueCardProps } from '../_tsup-dts-rollup';
5
+ export { DisputeTransactionProps } from '../_tsup-dts-rollup';
@@ -1 +1,5 @@
1
1
  export { App } from '../_tsup-dts-rollup';
2
+ export { IssueCard } from '../_tsup-dts-rollup';
3
+ export { DisputeTransaction } from '../_tsup-dts-rollup';
4
+ export { IssueCardProps } from '../_tsup-dts-rollup';
5
+ export { DisputeTransactionProps } from '../_tsup-dts-rollup';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capitalos/react",
3
- "version": "0.1.1-beta.2",
3
+ "version": "0.2.0",
4
4
  "description": "integrate CapitalOS into your react app",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/esm/index.js",