@dev-fastn-ai/react-core 2.3.6 → 2.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,1662 +1,9 @@
1
1
  import { jsx } from 'react/jsx-runtime';
2
2
  import { createContext, useMemo, useContext, useEffect, useState, useCallback } from 'react';
3
3
  import { QueryClientProvider, QueryClient, useQuery, useQueryClient, useInfiniteQuery } from '@tanstack/react-query';
4
+ import { Fastn } from '@dev-fastn-ai/core';
4
5
  export * from '@dev-fastn-ai/core';
5
6
 
6
- const REQUEST_TRACE_ID_HEADER_KEY = 'x-fastn-request-trace-id';
7
- const PROJECT_ID_HEADER_KEY = 'x-fastn-space-id';
8
- const TENANT_ID_HEADER_KEY = 'x-fastn-space-tenantid';
9
- const REALM = 'fastn';
10
- const DEFAULT_BASE_URL = 'https://live.fastn.ai/api';
11
- const PROD_OAUTH_REDIRECT_URL = 'https://oauth.live.fastn.ai';
12
- const CUSTOM_AUTH_CONTEXT_HEADER_KEY = 'x-fastn-custom-auth-context';
13
- const CUSTOM_AUTH_HEADER_KEY = 'x-fastn-custom-auth';
14
- const GOOGLE_FILES_PICKER_API_KEY = "AIzaSyClOJ0PYR0NJJkE79VLpKGOjgABbhjj9x4";
15
- const ACTIVATE_CONNECTOR_ACCESS_KEY = "7e9456eb-5fa1-44ca-8464-d63eb4a1c9a8";
16
- const ACTIVATE_CONNECTOR_PROJECT_ID = "e9289c72-9c15-42af-98e5-8bc6114a362f";
17
- const ACTIVATE_CONNECTOR_URL = "/api/v1/ActivateConnector";
18
-
19
- let config;
20
- function setConfig(userConfig) {
21
- var _a;
22
- config = {
23
- baseUrl: userConfig.baseUrl || DEFAULT_BASE_URL,
24
- environment: userConfig.environment || 'DRAFT',
25
- flowsEnvironment: userConfig.flowsEnvironment || 'LIVE',
26
- authToken: userConfig.authToken,
27
- tenantId: userConfig.tenantId,
28
- spaceId: userConfig.spaceId,
29
- customAuth: (_a = userConfig.customAuth) !== null && _a !== void 0 ? _a : true,
30
- };
31
- }
32
- function getConfig() {
33
- if (!config)
34
- throw new Error('Fastn not initialized.');
35
- return config;
36
- }
37
-
38
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
39
- // require the crypto API and do not support built-in fallback to lower quality random number
40
- // generators (like Math.random()).
41
- let getRandomValues;
42
- const rnds8 = new Uint8Array(16);
43
- function rng() {
44
- // lazy load so that environments that need to polyfill have a chance to do so
45
- if (!getRandomValues) {
46
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
47
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
48
-
49
- if (!getRandomValues) {
50
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
51
- }
52
- }
53
-
54
- return getRandomValues(rnds8);
55
- }
56
-
57
- /**
58
- * Convert array of 16 byte values to UUID string format of the form:
59
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
60
- */
61
-
62
- const byteToHex = [];
63
-
64
- for (let i = 0; i < 256; ++i) {
65
- byteToHex.push((i + 0x100).toString(16).slice(1));
66
- }
67
-
68
- function unsafeStringify(arr, offset = 0) {
69
- // Note: Be careful editing this code! It's been tuned for performance
70
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
71
- return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
72
- }
73
-
74
- const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
75
- var native = {
76
- randomUUID
77
- };
78
-
79
- function v4(options, buf, offset) {
80
- if (native.randomUUID && true && !options) {
81
- return native.randomUUID();
82
- }
83
-
84
- options = options || {};
85
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
86
-
87
- rnds[6] = rnds[6] & 0x0f | 0x40;
88
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
89
-
90
- return unsafeStringify(rnds);
91
- }
92
-
93
- /**
94
- * Supported field types for connector forms.
95
- */
96
- var ConnectorFieldType;
97
- (function (ConnectorFieldType) {
98
- ConnectorFieldType["TEXT"] = "text";
99
- ConnectorFieldType["NUMBER"] = "number";
100
- ConnectorFieldType["CHECKBOX"] = "checkbox";
101
- ConnectorFieldType["DATE"] = "date";
102
- ConnectorFieldType["DATETIME"] = "datetime";
103
- ConnectorFieldType["TIME"] = "time";
104
- ConnectorFieldType["DATETIME_LOCAL"] = "datetime-local";
105
- ConnectorFieldType["MULTI_SELECT"] = "multi-select";
106
- ConnectorFieldType["SELECT"] = "select";
107
- ConnectorFieldType["GOOGLE_FILES_PICKER_SELECT"] = "google-files-picker-select";
108
- ConnectorFieldType["GOOGLE_FILES_PICKER_MULTI_SELECT"] = "google-files-picker-multi-select";
109
- })(ConnectorFieldType || (ConnectorFieldType = {}));
110
- /**
111
- * Supported action types for connectors and configurations.
112
- */
113
- var ConnectorActionType;
114
- (function (ConnectorActionType) {
115
- ConnectorActionType["ACTIVATION"] = "ACTIVATION";
116
- ConnectorActionType["DEACTIVATION"] = "DEACTIVATION";
117
- ConnectorActionType["NONE"] = "NONE";
118
- ConnectorActionType["ENABLE"] = "ENABLE";
119
- ConnectorActionType["DISABLE"] = "DISABLE";
120
- ConnectorActionType["DELETE"] = "DELETE";
121
- })(ConnectorActionType || (ConnectorActionType = {}));
122
- /**
123
- * Status of a connector.
124
- */
125
- var ConnectorStatus;
126
- (function (ConnectorStatus) {
127
- ConnectorStatus["ACTIVE"] = "ACTIVE";
128
- ConnectorStatus["INACTIVE"] = "INACTIVE";
129
- ConnectorStatus["ALL"] = "ALL";
130
- })(ConnectorStatus || (ConnectorStatus = {}));
131
- /**
132
- * Supported resource actions for connectors and configurations.
133
- */
134
- var ResourceAction;
135
- (function (ResourceAction) {
136
- ResourceAction["ACTIVATION"] = "ACTIVATION";
137
- ResourceAction["DEACTIVATION"] = "DEACTIVATION";
138
- ResourceAction["CONFIGURE"] = "CONFIGURE";
139
- ResourceAction["UNCONFIGURE"] = "UNCONFIGURE";
140
- ResourceAction["FLOW_EXECUTION"] = "FLOW_EXECUTION";
141
- ResourceAction["QUERY"] = "QUERY";
142
- ResourceAction["ENABLE_CONFIGURATION"] = "ENABLE_CONFIGURATION";
143
- ResourceAction["UPDATE_CONFIGURATION"] = "UPDATE_CONFIGURATION";
144
- ResourceAction["DISABLE_CONFIGURATION"] = "DISABLE_CONFIGURATION";
145
- ResourceAction["DELETE_CONFIGURATION"] = "DELETE_CONFIGURATION";
146
- })(ResourceAction || (ResourceAction = {}));
147
-
148
- const getCustomAuthContextValue = (operationName, variables) => {
149
- var _a;
150
- try {
151
- if (!operationName)
152
- return "";
153
- return btoa(JSON.stringify(getCustomAuthContext(operationName, (_a = variables === null || variables === void 0 ? void 0 : variables.input) !== null && _a !== void 0 ? _a : {})));
154
- }
155
- catch (error) {
156
- console.error("Error getting custom auth context value:", error);
157
- return "";
158
- }
159
- };
160
- const getCustomAuthContext = (operationName, input) => {
161
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
162
- if (!operationName)
163
- return {};
164
- try {
165
- let action = ResourceAction.QUERY;
166
- let resourceId = "";
167
- switch (operationName) {
168
- case "metadata":
169
- case "connectors":
170
- case "api":
171
- case "tenantflow":
172
- case "generateaccesstoken":
173
- break;
174
- case "deactivateconnector":
175
- action = ResourceAction.DEACTIVATION;
176
- resourceId = (_a = input.connectorId) !== null && _a !== void 0 ? _a : "";
177
- break;
178
- case "configuretenantflow":
179
- action = ResourceAction.CONFIGURE;
180
- resourceId = (_b = input.connectorId) !== null && _b !== void 0 ? _b : "";
181
- break;
182
- case "deletetenantconfiguration":
183
- action = ResourceAction.UNCONFIGURE;
184
- resourceId = (_c = input.connectorId) !== null && _c !== void 0 ? _c : "";
185
- break;
186
- case "createtenantconfiguration":
187
- action = ResourceAction.ENABLE_CONFIGURATION;
188
- resourceId = (_d = input.connectorId) !== null && _d !== void 0 ? _d : "";
189
- break;
190
- case "updatetenantconfiguration":
191
- action = ResourceAction.UPDATE_CONFIGURATION;
192
- resourceId = (_e = input.connectorId) !== null && _e !== void 0 ? _e : "";
193
- break;
194
- case "disabletenantconfig":
195
- action = ResourceAction.DISABLE_CONFIGURATION;
196
- resourceId = (_f = input.connectorId) !== null && _f !== void 0 ? _f : "";
197
- break;
198
- case "deletetenantconfig":
199
- action = ResourceAction.DELETE_CONFIGURATION;
200
- resourceId = (_g = input.connectorId) !== null && _g !== void 0 ? _g : "";
201
- break;
202
- default:
203
- resourceId = (_j = (_h = input.clientId) !== null && _h !== void 0 ? _h : input.projectId) !== null && _j !== void 0 ? _j : "";
204
- }
205
- return { action, resourceId };
206
- }
207
- catch (error) {
208
- console.error("Error parsing custom auth context:", error);
209
- return {};
210
- }
211
- };
212
- const addCustomAuthContextHeader = (headers, context) => {
213
- try {
214
- const contextString = JSON.stringify(context);
215
- const encodedContext = btoa(contextString);
216
- headers[CUSTOM_AUTH_CONTEXT_HEADER_KEY] = encodedContext;
217
- }
218
- catch (error) {
219
- console.warn("Error adding custom auth context header:", error);
220
- }
221
- return headers;
222
- };
223
- const getOauthPopUpDimensions = () => {
224
- const screenWidth = window.innerWidth;
225
- const screenHeight = window.innerHeight;
226
- const width = Math.min(screenWidth - 100, 900);
227
- const height = Math.min(screenHeight - 100, 900);
228
- const top = Math.max((screenHeight - height) / 2, 100);
229
- const left = Math.max((screenWidth - width) / 2, 50);
230
- return { width, height, top, left };
231
- };
232
- function encodeState(state) {
233
- const { domain, uuid } = state;
234
- return btoa(`${domain}#${uuid}`);
235
- }
236
- const templateObjectValues = (obj, values) => {
237
- try {
238
- let objString = JSON.stringify(obj);
239
- Object.keys(values).forEach((key) => {
240
- objString = objString.replace(new RegExp(`{{${key}}}`, "g"), values[key]);
241
- });
242
- return JSON.parse(objString);
243
- }
244
- catch (error) {
245
- console.warn("Error templating object values", error);
246
- return undefined;
247
- }
248
- };
249
- const generateAuthUrl = ({ oauthDetails, formData = {}, }) => {
250
- var _a, _b;
251
- try {
252
- const templatedDetails = (_a = templateObjectValues(oauthDetails, formData)) !== null && _a !== void 0 ? _a : oauthDetails;
253
- const params = Object.assign({}, ((_b = templatedDetails === null || templatedDetails === void 0 ? void 0 : templatedDetails.params) !== null && _b !== void 0 ? _b : {}));
254
- if (templatedDetails.clientId)
255
- params.client_id = templatedDetails.clientId;
256
- params.redirect_uri = PROD_OAUTH_REDIRECT_URL;
257
- params.state = encodeState({ domain: "widget", uuid: "none" });
258
- const paramsString = Object.entries(params)
259
- .map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
260
- .join("&");
261
- return templatedDetails.baseUrl ? `${templatedDetails.baseUrl}?${paramsString}` : "";
262
- }
263
- catch (error) {
264
- console.error("Error generating auth URL:", error);
265
- return "";
266
- }
267
- };
268
- const getParams = (paramsString = window.location.search) => {
269
- try {
270
- const searchParams = new URLSearchParams(paramsString);
271
- const params = {};
272
- for (const [key, value] of searchParams.entries()) {
273
- params[key] = value;
274
- }
275
- return params;
276
- }
277
- catch (_a) {
278
- return {};
279
- }
280
- };
281
- const getFieldsFromContract = (contract) => {
282
- return Object.keys(contract)
283
- .map((key) => {
284
- var _a, _b, _c, _d, _e, _f, _g, _h;
285
- const field = contract[key];
286
- if (typeof field !== "object")
287
- return null;
288
- return {
289
- name: key,
290
- label: (_a = field.description) !== null && _a !== void 0 ? _a : "",
291
- initialValue: (_d = (_c = (_b = field.default) !== null && _b !== void 0 ? _b : field.defaultValue) !== null && _c !== void 0 ? _c : field.initialValue) !== null && _d !== void 0 ? _d : field.v,
292
- required: (_e = field.required) !== null && _e !== void 0 ? _e : false,
293
- type: (_f = field.type) !== null && _f !== void 0 ? _f : "text",
294
- hidden: (_g = field.hidden) !== null && _g !== void 0 ? _g : false,
295
- disabled: (_h = field.disabled) !== null && _h !== void 0 ? _h : false,
296
- };
297
- })
298
- .filter(Boolean);
299
- };
300
- const inputContractToFormData = (inputContract) => {
301
- var _a, _b;
302
- try {
303
- const fields = getFieldsFromContract(inputContract !== null && inputContract !== void 0 ? inputContract : {});
304
- if (!fields.length)
305
- return null;
306
- return {
307
- fields,
308
- description: (_a = inputContract.description) !== null && _a !== void 0 ? _a : "",
309
- submitButtonLabel: (_b = inputContract.submitLabel) !== null && _b !== void 0 ? _b : "Connect",
310
- };
311
- }
312
- catch (error) {
313
- console.warn("Error converting input contract to form data:", error);
314
- return null;
315
- }
316
- };
317
- const convertUiCodeFormDataToFormData = (formData) => {
318
- try {
319
- const { target, targetType } = formData;
320
- if (targetType === "object" && typeof target === "object" && target !== null) {
321
- const data = {};
322
- Object.keys(target).forEach((key) => {
323
- data[key] = convertUiCodeFormDataToFormData(target[key]);
324
- });
325
- return data;
326
- }
327
- else if (targetType === "array" && Array.isArray(target)) {
328
- return target.map((item) => convertUiCodeFormDataToFormData(item));
329
- }
330
- else {
331
- return target;
332
- }
333
- }
334
- catch (_a) {
335
- return formData;
336
- }
337
- };
338
- const safeParse = (jsonString) => {
339
- try {
340
- if (typeof jsonString === "object")
341
- return jsonString;
342
- return JSON.parse(jsonString);
343
- }
344
- catch (_a) {
345
- return {};
346
- }
347
- };
348
- const safeStringify = (json) => {
349
- try {
350
- return typeof json === "string" ? json : JSON.stringify(json);
351
- }
352
- catch (_a) {
353
- return "";
354
- }
355
- };
356
- function formatApolloErrors(error) {
357
- var _a;
358
- if (!error)
359
- return "";
360
- const code = (_a = error === null || error === void 0 ? void 0 : error.cause) === null || _a === void 0 ? void 0 : _a.code;
361
- try {
362
- switch (code) {
363
- case "RESOURCE_NOT_FOUND":
364
- case "resource_not_found":
365
- return "The requested resource could not be found";
366
- case "RESOURCE_ALREADY_EXISTS":
367
- case "resource_already_exists":
368
- return "The resource you are trying to create already exists";
369
- case "UNAUTHORIZED":
370
- case "unauthorized":
371
- case "UNAUTHORIZED_ERROR":
372
- return "You are not authorized to perform this operation";
373
- case "UNAUTHENTICATED":
374
- case "unauthenticated":
375
- case "UNAUTHENTICATED_ERROR":
376
- return "You are not authenticated to perform this operation";
377
- case "INTERNAL_SERVER_ERROR":
378
- case "internal_server_error":
379
- return "An unexpected error occurred on the server. Please try again later";
380
- default:
381
- return (error === null || error === void 0 ? void 0 : error.message) || "An unknown error occurred. Please try again.";
382
- }
383
- }
384
- catch (err) {
385
- return "An error occurred while processing the error. Please try again.";
386
- }
387
- }
388
- const getFieldType = (field) => {
389
- if (field.targetType === "array" && field.configs.selection.enable)
390
- return ConnectorFieldType.MULTI_SELECT;
391
- if (field.targetType === "object" && field.configs.selection.enable)
392
- return ConnectorFieldType.SELECT;
393
- if (field.targetType === "string")
394
- return ConnectorFieldType.TEXT;
395
- if (field.targetType === "number")
396
- return ConnectorFieldType.NUMBER;
397
- if (field.targetType === "boolean")
398
- return ConnectorFieldType.CHECKBOX;
399
- if (field.targetType === "date")
400
- return ConnectorFieldType.DATE;
401
- if (field.targetType === "datetime")
402
- return ConnectorFieldType.DATETIME;
403
- if (field.targetType === "time")
404
- return ConnectorFieldType.TIME;
405
- if (field.targetType === "datetime-local")
406
- return ConnectorFieldType.DATETIME_LOCAL;
407
- return ConnectorFieldType.TEXT;
408
- };
409
- const uiCodeToFormFields = (uiCodeString, options) => {
410
- try {
411
- const parsed = safeParse(uiCodeString);
412
- const { targetType, target } = parsed;
413
- const values = convertUiCodeFormDataToFormData(parsed);
414
- if (targetType !== 'object' || typeof target !== 'object' || target === null) {
415
- return [];
416
- }
417
- return Object.entries(target).map(([key, rawField]) => {
418
- var _a;
419
- const { configs = {}, default: defaultValue, } = rawField;
420
- const { label = key, description = '', required = false, placeholder = '', hideOption = {}, selection, } = configs;
421
- const field = {
422
- key,
423
- name: key,
424
- label: label !== null && label !== void 0 ? label : key,
425
- description,
426
- initialValue: (_a = values[key]) !== null && _a !== void 0 ? _a : defaultValue,
427
- type: getFieldType(rawField),
428
- required: Boolean(required),
429
- hidden: Boolean((hideOption === null || hideOption === void 0 ? void 0 : hideOption.enable) || key === "connectorId" || key === "id"),
430
- disabled: Boolean((hideOption === null || hideOption === void 0 ? void 0 : hideOption.enable) || key === "connectorId" || key === "id"),
431
- placeholder,
432
- };
433
- if (selection === null || selection === void 0 ? void 0 : selection.enable) {
434
- if (selection.type === 'CUSTOM' && selection.customSelector === 'GOOGLE_FILES_PICKER') {
435
- return Object.assign(Object.assign({}, field), { type: field.type === ConnectorFieldType.MULTI_SELECT ? ConnectorFieldType.GOOGLE_FILES_PICKER_MULTI_SELECT : ConnectorFieldType.GOOGLE_FILES_PICKER_SELECT, optionsSource: {
436
- type: 'GOOGLE_FILES_PICKER',
437
- openGoogleFilesPicker: options.openGoogleFilesPicker,
438
- } });
439
- }
440
- else if (selection.flowId) {
441
- const pagination = Object.assign(Object.assign({ sourceId: selection.flowId, sourceProject: selection.isSameProject ? 'self' : 'community', limit: selection.limit, type: selection.type }, (selection.type === 'OFFSET' && selection.offset != null ? { offset: selection.offset } : {})), (selection.type === 'CURSOR' && selection.cursor != null ? { cursor: selection.cursor } : {}));
442
- return Object.assign(Object.assign({}, field), { optionsSource: {
443
- type: 'DYNAMIC',
444
- pagination,
445
- getOptions: options.getOptions,
446
- loadMore: options.loadMore,
447
- refresh: options.refresh,
448
- searchOptions: options.searchOptions,
449
- } });
450
- }
451
- else if (Array.isArray(selection.list)) {
452
- return Object.assign(Object.assign({}, field), { optionsSource: {
453
- type: 'STATIC',
454
- staticOptions: selection.list.map((item) => ({
455
- label: item.title,
456
- value: item.value,
457
- })),
458
- } });
459
- }
460
- }
461
- return field;
462
- });
463
- }
464
- catch (error) {
465
- console.warn('Error parsing UI code to form fields:', error);
466
- return [];
467
- }
468
- };
469
- function populateFormDataInUiCode(uiCodeString, formData) {
470
- const uiCode = safeParse(uiCodeString) || {};
471
- const { target, targetType } = uiCode;
472
- if (!target || !targetType)
473
- return uiCode;
474
- if (targetType === "object") {
475
- const updatedTarget = Object.keys(target).reduce((acc, key) => {
476
- var _a;
477
- const value = formData[key];
478
- if (value !== undefined) {
479
- acc[key] = Object.assign(Object.assign({}, target[key]), { target: (_a = convertFormDataToUiCodeFormData(value)) === null || _a === void 0 ? void 0 : _a.target });
480
- }
481
- else {
482
- acc[key] = target[key];
483
- }
484
- return acc;
485
- }, {});
486
- return Object.assign(Object.assign({}, uiCode), { target: updatedTarget });
487
- }
488
- else if (targetType === "array" && Array.isArray(target)) {
489
- const updatedTarget = target.map((item, index) => {
490
- const updatedItem = Object.assign({}, item);
491
- // Assuming item has a unique key (e.g., id or name) to match formData fields
492
- Object.keys(item).forEach((key) => {
493
- var _a, _b;
494
- const formValue = (_a = formData[`${index}.${key}`]) !== null && _a !== void 0 ? _a : formData[key];
495
- if (formValue !== undefined) {
496
- updatedItem[key] = Object.assign(Object.assign({}, item[key]), { target: (_b = convertFormDataToUiCodeFormData(formValue)) === null || _b === void 0 ? void 0 : _b.target });
497
- }
498
- });
499
- return updatedItem;
500
- });
501
- return Object.assign(Object.assign({}, uiCode), { target: updatedTarget });
502
- }
503
- return uiCode;
504
- }
505
- const convertFormDataToUiCodeFormData = (formData) => {
506
- if (Array.isArray(formData)) {
507
- return {
508
- actionType: "map",
509
- targetType: "array",
510
- target: formData.map((item) => convertFormDataToUiCodeFormData(item)),
511
- };
512
- }
513
- else if (formData !== null && typeof formData === "object") {
514
- const target = {};
515
- for (const key in formData) {
516
- target[key] = convertFormDataToUiCodeFormData(formData[key]);
517
- }
518
- return {
519
- actionType: "map",
520
- targetType: "object",
521
- target,
522
- };
523
- }
524
- else if (typeof formData === "string") {
525
- return {
526
- actionType: "map",
527
- targetType: "string",
528
- target: formData,
529
- };
530
- }
531
- else if (typeof formData === "number") {
532
- return {
533
- actionType: "map",
534
- targetType: "number",
535
- target: formData,
536
- };
537
- }
538
- else if (typeof formData === "boolean") {
539
- return {
540
- actionType: "map",
541
- targetType: "boolean",
542
- target: formData,
543
- };
544
- }
545
- else {
546
- return {
547
- actionType: "map",
548
- targetType: "string",
549
- target: formData,
550
- };
551
- }
552
- };
553
- /**
554
- * Recursively removes __typename fields from an object or array.
555
- */
556
- function stripTypename(obj) {
557
- if (Array.isArray(obj)) {
558
- return obj.map(stripTypename);
559
- }
560
- else if (obj && typeof obj === 'object') {
561
- const newObj = {};
562
- for (const key in obj) {
563
- if (key === '__typename')
564
- continue;
565
- newObj[key] = stripTypename(obj[key]);
566
- }
567
- return newObj;
568
- }
569
- return obj;
570
- }
571
-
572
- // GraphQL endpoint (customize as needed)
573
- const GRAPHQL_ENDPOINT = "/graphql";
574
- // Utility to perform GraphQL queries/mutations using fetch
575
- async function fetchGraphQL({ query, variables, operationName }) {
576
- const config = getConfig();
577
- const response = await fetch(config.baseUrl + GRAPHQL_ENDPOINT, {
578
- method: "POST",
579
- headers: {
580
- "Content-Type": "application/json",
581
- authorization: `Bearer ${config.authToken}`,
582
- realm: REALM,
583
- [CUSTOM_AUTH_HEADER_KEY]: String(config.customAuth),
584
- [PROJECT_ID_HEADER_KEY]: config.spaceId,
585
- [TENANT_ID_HEADER_KEY]: config.tenantId,
586
- [REQUEST_TRACE_ID_HEADER_KEY]: `react-ai-core-${v4()}`,
587
- [CUSTOM_AUTH_CONTEXT_HEADER_KEY]: getCustomAuthContextValue(operationName, variables),
588
- },
589
- body: JSON.stringify({ query, variables }),
590
- });
591
- if (!response.ok) {
592
- switch (response.status) {
593
- case 401:
594
- throw new Error("Unauthorized: Please check your auth token");
595
- case 403:
596
- throw new Error("Forbidden: Please check your access");
597
- case 404:
598
- throw new Error("Not Found: Please check your request");
599
- default:
600
- throw new Error("Failed to fetch: Please check your request");
601
- }
602
- }
603
- const result = await response.json();
604
- if (result.errors) {
605
- throw new Error(result.errors.map((e) => e.message).join("; "));
606
- }
607
- return {
608
- data: result.data,
609
- errors: result.errors
610
- };
611
- }
612
- // GraphQL Queries & Mutations (as plain strings)
613
- const GET_WIDGET_CONNECTORS = `
614
- query Connectors($input: GetConnectorsListInput!) {
615
- connectors(input: $input) {
616
- name
617
- id
618
- imageUri
619
- description
620
- content
621
- actions {
622
- name
623
- handler
624
- actionType
625
- activatedStateLabel
626
- content
627
- shows
628
- handlerPayload
629
- multiConnectorWidgetConnectors {
630
- name
631
- id
632
- imageUri
633
- description
634
- content
635
- connectionId
636
- actions {
637
- name
638
- handler
639
- actionType
640
- activatedStateLabel
641
- content
642
- shows
643
- handlerPayload
644
- }
645
- events {
646
- name
647
- eventId
648
- content
649
- payload
650
- }
651
- connectedConnectors {
652
- id
653
- imageUrl
654
- clientId
655
- name
656
- enableActivate
657
- activateStatus
658
- authMethods {
659
- title
660
- inputContract
661
- type
662
- details
663
- isDefault
664
- }
665
- }
666
- status
667
- }
668
- }
669
- events {
670
- name
671
- eventId
672
- content
673
- payload
674
- }
675
- connectedConnectors {
676
- id
677
- imageUrl
678
- clientId
679
- name
680
- enableActivate
681
- activateStatus
682
- authMethods {
683
- title
684
- inputContract
685
- type
686
- details
687
- isDefault
688
- }
689
- }
690
- status
691
- }
692
- }
693
- `;
694
- const SAVE_ACTIVATE_CONNECTOR_STATUS = `
695
- mutation SaveActivateConnectorStatus(
696
- $input: SaveWidgetConnectorStatusInput!
697
- ) {
698
- saveWidgetConnectorStatus(input: $input)
699
- }
700
- `;
701
- const DEACTIVATE_CONNECTOR = `
702
- mutation DeactivateConnector($input: DeactivateConnectorInput!) {
703
- deactivateConnector(input: $input)
704
- }
705
- `;
706
- const GET_FIELD_DATA_QUERY = `
707
- query executeGetFieldDataFlow($input: ApiPrimaryResolverInvocationInput!) {
708
- executeGetFieldDataFlow(input: $input) {
709
- data
710
- }
711
- }
712
- `;
713
- const GET_TENANT_CONFIGURATIONS = `
714
- query GetConfigurationSubscription($input: ConfigurationSubscriptionInput!) {
715
- getConfigurationSubscription(input: $input) {
716
- connector {
717
- id
718
- name
719
- description
720
- imageUri
721
- status
722
- active
723
- actions {
724
- name
725
- handler
726
- actionType
727
- }
728
- connectedConnectors {
729
- id
730
- name
731
- clientId
732
- imageUrl
733
- enableActivate
734
- activateStatus
735
- authMethods {
736
- title
737
- inputContract
738
- type
739
- details
740
- isDefault
741
- }
742
- }
743
- }
744
- status
745
- metaData
746
- }
747
- }
748
- `;
749
- const GET_TENANT_CONFIGURATIONS_BY_ID = `
750
- query GetConfigurationSubscription($input: GetTenantConfigurationsInput) {
751
- tenantConfigurationsById(input: $input) {
752
- uiCode
753
- flowId
754
- stepId
755
- status
756
- configurations
757
- configuredStepSetting {
758
- keyIsEditable
759
- addButton {
760
- label
761
- isDisabled
762
- fieldsLimit
763
- }
764
- description
765
- label
766
- validation {
767
- fieldValidation
768
- submitValidation
769
- modelId
770
- jsonSchema
771
- submitValidationFunction
772
- }
773
- }
774
- }
775
- }
776
- `;
777
- const CREATE_TENANT_CONFIGURATION = `
778
- mutation CreateTenantConfiguration($input: TenantConfigurationsInput!) {
779
- createTenantConfiguration(input: $input) {
780
- id
781
- }
782
- }
783
- `;
784
- const UPDATE_TENANT_CONFIGURATION = `
785
- mutation UpdateTenantConfiguration($input: TenantConfigurationsInput!) {
786
- updateTenantConfiguration(input: $input) {
787
- id
788
- }
789
- }
790
- `;
791
- const DELETE_TENANT_CONFIG = `
792
- mutation DeleteTenantConfig($input: GetTenantConfigurationsInput!) {
793
- deleteTenantConfig(input: $input) {
794
- id
795
- }
796
- }
797
- `;
798
- const DISABLE_TENANT_CONFIG = `
799
- mutation DisableTenantConfig($input: GetTenantConfigurationsInput!) {
800
- disableTenantConfig(input: $input) {
801
- id
802
- }
803
- }
804
- `;
805
- const GENERATE_ACCESS_TOKEN = `
806
- query GenerateAccessToken($input: ConnectorConnectionInput!) {
807
- connectorConnection(input: $input)
808
- }
809
- `;
810
- // Refactored functions using fetchGraphQL
811
- async function getConnectors$1(variables) {
812
- return fetchGraphQL({ query: GET_WIDGET_CONNECTORS, variables, operationName: "connectors" });
813
- }
814
- async function saveActivateConnectorStatus(variables) {
815
- return fetchGraphQL({ query: SAVE_ACTIVATE_CONNECTOR_STATUS, variables, operationName: "saveactivatconnectorstatus" });
816
- }
817
- async function deactivateConnector$1(variables) {
818
- return fetchGraphQL({ query: DEACTIVATE_CONNECTOR, variables, operationName: "deactivateConnector" });
819
- }
820
- async function getFieldData(variables) {
821
- return fetchGraphQL({ query: GET_FIELD_DATA_QUERY, variables, operationName: "executeGetFieldDataFlow" });
822
- }
823
- async function getConfigurationSubscriptions(variables) {
824
- return fetchGraphQL({ query: GET_TENANT_CONFIGURATIONS, variables, operationName: "getconfigurationsubscription" });
825
- }
826
- async function getConfigurationSubscriptionById(variables) {
827
- return fetchGraphQL({ query: GET_TENANT_CONFIGURATIONS_BY_ID, variables, operationName: "getconfigurationsubscriptionbyid" });
828
- }
829
- async function createTenantConfiguration(variables) {
830
- return fetchGraphQL({ query: CREATE_TENANT_CONFIGURATION, variables, operationName: "createtenantconfiguration" });
831
- }
832
- async function updateTenantConfiguration(variables) {
833
- return fetchGraphQL({ query: UPDATE_TENANT_CONFIGURATION, variables, operationName: "updatetenantconfiguration" });
834
- }
835
- async function deleteTenantConfig(variables) {
836
- return fetchGraphQL({ query: DELETE_TENANT_CONFIG, variables, operationName: "deletetenantconfig" });
837
- }
838
- async function disableTenantConfig(variables) {
839
- return fetchGraphQL({ query: DISABLE_TENANT_CONFIG, variables, operationName: "disabletenantconfig" });
840
- }
841
- async function generateAccessToken(variables) {
842
- return fetchGraphQL({ query: GENERATE_ACCESS_TOKEN, variables, operationName: "generateaccesstoken" });
843
- }
844
-
845
- /**
846
- * Returns the backend URL for flow execution, appending /v1 if needed.
847
- */
848
- const getBackendUrl = () => {
849
- var _a;
850
- const config = getConfig();
851
- return ((_a = config.baseUrl) === null || _a === void 0 ? void 0 : _a.endsWith("/api")) ? config.baseUrl + "/v1" : `${config.baseUrl}/api/v1`;
852
- };
853
- /**
854
- * Executes a backend flow with the given path, input, and headers.
855
- * @returns {Promise<any>} The response data from the backend.
856
- */
857
- const executeFLow = async ({ path, input = {}, headers = {} }) => {
858
- try {
859
- const config = getConfig();
860
- const backendUrl = getBackendUrl();
861
- const response = await fetch(`${backendUrl}/${path}`, {
862
- method: "POST",
863
- headers: Object.assign({ "Content-Type": "application/json", [PROJECT_ID_HEADER_KEY]: config.spaceId, [TENANT_ID_HEADER_KEY]: config.tenantId, authorization: `${config.authToken}`, stage: config.flowsEnvironment }, headers),
864
- body: JSON.stringify({
865
- "input": input
866
- })
867
- });
868
- if (!response.ok) {
869
- throw new Error(`Failed to execute flow: ${response.statusText}`);
870
- }
871
- const data = await response.json();
872
- return data;
873
- }
874
- catch (error) {
875
- console.error("Error in executeFLow:", error);
876
- throw error;
877
- }
878
- };
879
-
880
- /**
881
- * Builds the request input for connector activation.
882
- */
883
- const buildRequestInput = (dependencyConnector, authMethod, formData) => {
884
- var _a;
885
- const config = getConfig();
886
- return {
887
- fastn_connection: {
888
- projectId: config === null || config === void 0 ? void 0 : config.spaceId,
889
- domain: (_a = config.baseUrl) === null || _a === void 0 ? void 0 : _a.replace("https://", "").replace("/api", "").replace("api", ""),
890
- redirectUri: PROD_OAUTH_REDIRECT_URL
891
- },
892
- oauth: {
893
- connector: {
894
- id: dependencyConnector === null || dependencyConnector === void 0 ? void 0 : dependencyConnector.id,
895
- clientId: dependencyConnector === null || dependencyConnector === void 0 ? void 0 : dependencyConnector.clientId,
896
- name: dependencyConnector === null || dependencyConnector === void 0 ? void 0 : dependencyConnector.name,
897
- isOauth: (authMethod === null || authMethod === void 0 ? void 0 : authMethod.type) === "OAUTH",
898
- oauth: authMethod === null || authMethod === void 0 ? void 0 : authMethod.details,
899
- input: formData,
900
- },
901
- response: {}
902
- }
903
- };
904
- };
905
- /**
906
- * Calls the backend to activate a connector.
907
- */
908
- const callActivateConnector = async (input, headers) => {
909
- const config = getConfig();
910
- const url = config.baseUrl + ACTIVATE_CONNECTOR_URL;
911
- const response = await fetch(url, {
912
- method: "POST",
913
- headers: Object.assign(Object.assign({ "Content-Type": "application/json" }, headers), { "x-fastn-api-key": ACTIVATE_CONNECTOR_ACCESS_KEY, "x-fastn-space-id": ACTIVATE_CONNECTOR_PROJECT_ID, "x-fastn-space-client-id": config.spaceId, 'stage': "LIVE" }),
914
- body: JSON.stringify({
915
- input
916
- })
917
- });
918
- if (!response.ok) {
919
- throw new Error(`Failed to activate connector: ${response.statusText}`);
920
- }
921
- const responseData = await response.json();
922
- return responseData.data;
923
- };
924
- /**
925
- * Handles the OAuth flow for connector activation.
926
- */
927
- const handleOauthFlow = async (authMethod, formData, input) => {
928
- const config = getConfig();
929
- const authUrl = generateAuthUrl({ oauthDetails: authMethod.details, formData });
930
- const { width, height, top, left } = getOauthPopUpDimensions();
931
- const oAuthPopUpWindow = window.open(authUrl, "OAuthPopup", `width=${width},height=${height},top=${top},left=${left}`);
932
- return new Promise((resolve, reject) => {
933
- let params = null;
934
- const messageListener = async (event) => {
935
- var _a;
936
- if (event.origin === PROD_OAUTH_REDIRECT_URL && ((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === "oauth_complete" && !params) {
937
- params = getParams(event.data.params);
938
- window.removeEventListener("message", messageListener);
939
- clearInterval(closePopupInterval);
940
- try {
941
- input.oauth.response = params;
942
- const data = await callActivateConnector(input, {
943
- [TENANT_ID_HEADER_KEY]: config === null || config === void 0 ? void 0 : config.tenantId,
944
- [CUSTOM_AUTH_HEADER_KEY]: String(config === null || config === void 0 ? void 0 : config.customAuth),
945
- authorization: config === null || config === void 0 ? void 0 : config.authToken
946
- });
947
- resolve({ data, status: "SUCCESS" });
948
- }
949
- catch (error) {
950
- console.error("Error in handleOauthFlow", error);
951
- reject(error);
952
- }
953
- finally {
954
- }
955
- }
956
- };
957
- const closePopupInterval = setInterval(() => {
958
- if (oAuthPopUpWindow.closed) {
959
- clearInterval(closePopupInterval);
960
- if (!params) {
961
- window.removeEventListener("message", messageListener);
962
- resolve({
963
- data: { message: "Popup closed without completing OAuth" },
964
- status: "CANCELLED"
965
- });
966
- }
967
- }
968
- }, 1000);
969
- window.addEventListener("message", messageListener);
970
- });
971
- };
972
- /**
973
- * Framework-agnostic activateConnector utility.
974
- * @param args - Activation arguments (connectorId, action, dependencyConnector, authMethod, input, saveStatusFn, executeActionHandlerFn, config)
975
- * @returns {Promise<{ status: string; data: any }>}
976
- */
977
- const activateConnector = async ({ connectorId, action, dependencyConnector, authMethod, input = {}, }) => {
978
- try {
979
- const config = getConfig();
980
- // Activate the connector
981
- let response = await activateConnectorCore({
982
- dependencyConnector,
983
- authMethod,
984
- formData: input,
985
- });
986
- if ((response === null || response === void 0 ? void 0 : response.status) === "CANCELLED") {
987
- return { data: null, status: "CANCELLED" };
988
- }
989
- // Execute the action handler
990
- response = await executeActionHandler(action === null || action === void 0 ? void 0 : action.handler, addCustomAuthContextHeader({}, { resourceId: connectorId, action: ResourceAction.ACTIVATION }));
991
- // Save connector status
992
- await saveActivateConnectorStatus({
993
- input: {
994
- projectId: config.spaceId,
995
- tenantId: config.tenantId,
996
- connectorId,
997
- isDependencyConnector: false,
998
- }
999
- });
1000
- return {
1001
- status: "SUCCESS",
1002
- data: response,
1003
- };
1004
- }
1005
- catch (error) {
1006
- console.error("Error in activateConnector:", error);
1007
- throw error;
1008
- }
1009
- };
1010
- /**
1011
- * Framework-agnostic deactivateConnector utility.
1012
- * @param args - Deactivation arguments (connectorId, action, deactivateConnectorFn, executeActionHandlerFn, config)
1013
- * @returns {Promise<{ status: string; data: any }>}
1014
- */
1015
- const deactivateConnector = async ({ connectorId, action, }) => {
1016
- try {
1017
- const config = getConfig();
1018
- // Execute the action handler
1019
- let response = {};
1020
- response = await executeActionHandler(action === null || action === void 0 ? void 0 : action.handler, addCustomAuthContextHeader({}, { resourceId: connectorId, action: ResourceAction.DEACTIVATION }));
1021
- // Deactivate the connector
1022
- await deactivateConnector$1({
1023
- input: {
1024
- projectId: config.spaceId,
1025
- tenantId: config.tenantId,
1026
- connectorId,
1027
- }
1028
- });
1029
- return {
1030
- status: "SUCCESS",
1031
- data: response,
1032
- };
1033
- }
1034
- catch (error) {
1035
- console.error("Error in deactivateConnector:", error);
1036
- throw error;
1037
- }
1038
- };
1039
- /**
1040
- * Framework-agnostic executeActionHandler utility.
1041
- * @param handler - The handler path or function
1042
- * @param headers - Optional headers
1043
- * @returns {Promise<any>}
1044
- */
1045
- const executeActionHandler = async (handler, headers = {}) => {
1046
- try {
1047
- if (!handler) {
1048
- return {
1049
- status: "SUCCESS",
1050
- data: {},
1051
- };
1052
- }
1053
- const response = await executeFLow({ path: handler, headers });
1054
- return response;
1055
- }
1056
- catch (error) {
1057
- console.warn("Error executing action handler:", error);
1058
- throw error;
1059
- }
1060
- };
1061
- // Core activation logic for internal use
1062
- const activateConnectorCore = async ({ dependencyConnector, authMethod, formData }) => {
1063
- try {
1064
- const input = buildRequestInput(dependencyConnector, authMethod, formData);
1065
- const isOauth = (authMethod === null || authMethod === void 0 ? void 0 : authMethod.type) === "OAUTH";
1066
- if (isOauth) {
1067
- return await handleOauthFlow(authMethod, formData, input);
1068
- }
1069
- const config = getConfig();
1070
- const data = await callActivateConnector(input, {
1071
- [TENANT_ID_HEADER_KEY]: config === null || config === void 0 ? void 0 : config.tenantId,
1072
- [CUSTOM_AUTH_HEADER_KEY]: String(config === null || config === void 0 ? void 0 : config.customAuth),
1073
- authorization: config === null || config === void 0 ? void 0 : config.authToken
1074
- });
1075
- return { data, status: "SUCCESS" };
1076
- }
1077
- catch (error) {
1078
- console.error("Error in activateConnectorCore", error);
1079
- throw error;
1080
- }
1081
- };
1082
-
1083
- // eventBus.ts
1084
- // Internal listener registry
1085
- const listeners = {
1086
- 'REFETCH_CONNECTORS': new Set(),
1087
- 'REFETCH_CONFIGURATIONS': new Set(),
1088
- 'REFRESH_CONFIGURATION_FORM': new Set(),
1089
- 'INVALIDATE_CONFIGURATION_FORM': new Set(),
1090
- 'INVALIDATE_CONFIGURATIONS': new Set(),
1091
- 'INVALIDATE_CONNECTORS': new Set(),
1092
- };
1093
- // Send a cross-context-safe event
1094
- const sendEvent = (event) => {
1095
- window.postMessage({ __eventBus: true, event }, '*');
1096
- };
1097
- // Register a callback for a specific event
1098
- const onEvent = (event, callback) => {
1099
- var _a;
1100
- (_a = listeners[event]) === null || _a === void 0 ? void 0 : _a.add(callback);
1101
- };
1102
- // Unregister a callback
1103
- const offEvent = (event, callback) => {
1104
- var _a;
1105
- (_a = listeners[event]) === null || _a === void 0 ? void 0 : _a.delete(callback);
1106
- };
1107
- // Internal postMessage listener
1108
- const handleMessage = (e) => {
1109
- const data = e.data;
1110
- if (!data || !data.__eventBus || !data.event)
1111
- return;
1112
- const callbacks = listeners[data.event];
1113
- callbacks === null || callbacks === void 0 ? void 0 : callbacks.forEach((cb) => cb());
1114
- };
1115
- // Register listener once
1116
- window.addEventListener('message', handleMessage);
1117
-
1118
- /**
1119
- * Fetches connectors and maps their actions for use in the application.
1120
- * Updates the global state store.
1121
- * @returns {Promise<Connector[]>}
1122
- */
1123
- async function getConnectors({ disabled = false, status = "ALL", refetch } = {}) {
1124
- try {
1125
- const config = getConfig();
1126
- const { data } = await getConnectors$1({
1127
- input: {
1128
- projectId: config.spaceId,
1129
- tenantId: config.tenantId,
1130
- onlyActive: !disabled,
1131
- environment: config.environment,
1132
- },
1133
- });
1134
- const connectors = data === null || data === void 0 ? void 0 : data.connectors;
1135
- const mappedConnectors = connectors.map((connector) => {
1136
- const actions = (connector.actions || [])
1137
- .filter((action) => {
1138
- // Only allow ACTIVATION, DEACTIVATION, or NONE
1139
- if (action.actionType !== "ACTIVATION" && action.actionType !== "DEACTIVATION" && action.actionType !== "NONE") {
1140
- return false;
1141
- }
1142
- if (!action.shows || action.shows === "ALWAYS") {
1143
- return true;
1144
- }
1145
- if (action.shows === "WHEN_ACTIVE" && connector.status === "ACTIVE") {
1146
- return true;
1147
- }
1148
- if (action.shows === "WHEN_INACTIVE" && connector.status === "INACTIVE") {
1149
- return true;
1150
- }
1151
- return false;
1152
- })
1153
- .map((action) => {
1154
- var _a, _b, _c, _d;
1155
- const handler = async (formData = {}) => {
1156
- var _a, _b, _c, _d;
1157
- try {
1158
- let response = null;
1159
- if ((action === null || action === void 0 ? void 0 : action.actionType) === "ACTIVATION") {
1160
- response = await activateConnector({
1161
- connectorId: connector.id,
1162
- action,
1163
- dependencyConnector: (_a = connector === null || connector === void 0 ? void 0 : connector.connectedConnectors) === null || _a === void 0 ? void 0 : _a[0],
1164
- authMethod: (_d = (_c = (_b = connector === null || connector === void 0 ? void 0 : connector.connectedConnectors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.authMethods) === null || _d === void 0 ? void 0 : _d[0],
1165
- input: formData,
1166
- });
1167
- }
1168
- else if ((action === null || action === void 0 ? void 0 : action.actionType) === "DEACTIVATION") {
1169
- response = await deactivateConnector({
1170
- connectorId: connector.id,
1171
- action,
1172
- });
1173
- await (refetch === null || refetch === void 0 ? void 0 : refetch());
1174
- }
1175
- else {
1176
- response = await executeActionHandler(action === null || action === void 0 ? void 0 : action.handler);
1177
- }
1178
- sendEvent("REFETCH_CONFIGURATIONS");
1179
- sendEvent("REFETCH_CONNECTORS");
1180
- return response;
1181
- }
1182
- catch (e) {
1183
- return {
1184
- data: {
1185
- error: e instanceof Error ? e.message : "Unknown error",
1186
- },
1187
- status: "ERROR",
1188
- };
1189
- }
1190
- };
1191
- const form = inputContractToFormData((_d = (_c = (_b = (_a = connector === null || connector === void 0 ? void 0 : connector.connectedConnectors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.authMethods) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.inputContract);
1192
- // Construct the action object with all properties at creation
1193
- return Object.assign({ name: action.name, actionType: action.actionType, form }, (form
1194
- ? { onSubmit: async (formData) => await handler(formData) }
1195
- : { onClick: async () => await handler() }));
1196
- });
1197
- return {
1198
- id: connector.id,
1199
- name: connector.name,
1200
- description: connector.description,
1201
- imageUri: connector === null || connector === void 0 ? void 0 : connector.imageUri,
1202
- status: connector.status,
1203
- actions,
1204
- };
1205
- }).filter((connector) => {
1206
- if (status === "ALL")
1207
- return true;
1208
- if (status === "ACTIVE" && connector.status === "ACTIVE")
1209
- return true;
1210
- if (status === "INACTIVE" && connector.status === "INACTIVE")
1211
- return true;
1212
- return false;
1213
- });
1214
- return mappedConnectors;
1215
- }
1216
- catch (error) {
1217
- throw new Error(formatApolloErrors(error));
1218
- }
1219
- }
1220
-
1221
- const handleDisableConfiguration = async ({ id, connectorId, }) => {
1222
- try {
1223
- const config = getConfig();
1224
- await disableTenantConfig({
1225
- input: {
1226
- clientId: config.spaceId,
1227
- tenantId: config.tenantId,
1228
- id: id,
1229
- connectorId,
1230
- widgetConnectorId: connectorId,
1231
- },
1232
- });
1233
- sendEvent("REFETCH_CONFIGURATIONS");
1234
- }
1235
- catch (error) {
1236
- throw new Error(formatApolloErrors(error));
1237
- }
1238
- };
1239
- const handleDeleteConfiguration = async ({ id, connectorId, }) => {
1240
- try {
1241
- const config = getConfig();
1242
- await deleteTenantConfig({
1243
- input: {
1244
- clientId: config.spaceId,
1245
- tenantId: config.tenantId,
1246
- id: id,
1247
- connectorId,
1248
- widgetConnectorId: connectorId,
1249
- },
1250
- });
1251
- sendEvent("REFETCH_CONFIGURATIONS");
1252
- }
1253
- catch (error) {
1254
- throw new Error(formatApolloErrors(error));
1255
- }
1256
- };
1257
- async function getConfigurations({ configurationId, status = "ALL", }) {
1258
- try {
1259
- const config = getConfig();
1260
- const { data } = await getConfigurationSubscriptions({
1261
- input: {
1262
- clientId: config.spaceId,
1263
- tenantId: config.tenantId,
1264
- id: configurationId,
1265
- status,
1266
- }
1267
- });
1268
- const configurations = (data.getConfigurationSubscription || [])
1269
- .map((configSubscription) => {
1270
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1271
- const configureAction = (_b = (_a = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _a === void 0 ? void 0 : _a.actions) === null || _b === void 0 ? void 0 : _b.find((action) => action.actionType === "CONFIGURATION");
1272
- if (!configureAction || ((_c = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _c === void 0 ? void 0 : _c.active) === false)
1273
- return null;
1274
- const actions = [];
1275
- if ((configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.status) === "ENABLED") {
1276
- actions.push({
1277
- name: "Disable",
1278
- actionType: ConnectorActionType.DISABLE,
1279
- onClick: async () => {
1280
- await handleDisableConfiguration({ connectorId: configSubscription.connector.id, id: configurationId });
1281
- return { data: null, status: "SUCCESS" };
1282
- },
1283
- });
1284
- actions.push({
1285
- name: "Delete",
1286
- actionType: ConnectorActionType.DELETE,
1287
- onClick: async () => {
1288
- await handleDeleteConfiguration({ connectorId: configSubscription.connector.id, id: configurationId });
1289
- return { data: null, status: "SUCCESS" };
1290
- },
1291
- });
1292
- }
1293
- else {
1294
- const form = inputContractToFormData((_h = (_g = (_f = (_e = (_d = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _d === void 0 ? void 0 : _d.connectedConnectors) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.authMethods) === null || _g === void 0 ? void 0 : _g.find((authMethod) => authMethod.isDefault)) === null || _h === void 0 ? void 0 : _h.inputContract);
1295
- const handler = async (formData = {}) => {
1296
- var _a, _b, _c, _d, _e, _f, _g, _h;
1297
- if (((_a = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _a === void 0 ? void 0 : _a.status) === "ACTIVE")
1298
- return { status: "SUCCESS" };
1299
- const result = await activateConnector({
1300
- connectorId: configSubscription.connector.id,
1301
- action: (_c = (_b = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _b === void 0 ? void 0 : _b.actions) === null || _c === void 0 ? void 0 : _c.find((action) => action.actionType === ResourceAction.ACTIVATION),
1302
- dependencyConnector: (_e = (_d = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _d === void 0 ? void 0 : _d.connectedConnectors) === null || _e === void 0 ? void 0 : _e[0],
1303
- authMethod: (_h = (_g = (_f = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _f === void 0 ? void 0 : _f.connectedConnectors) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.authMethods[0],
1304
- input: formData,
1305
- });
1306
- sendEvent("REFETCH_CONFIGURATIONS");
1307
- sendEvent("REFETCH_CONNECTORS");
1308
- return result;
1309
- };
1310
- actions.push({
1311
- name: "Enable",
1312
- actionType: ConnectorActionType.ENABLE,
1313
- form,
1314
- onClick: handler,
1315
- onSubmit: handler,
1316
- });
1317
- }
1318
- return {
1319
- id: configSubscription.connector.id,
1320
- connectorId: (_j = configSubscription === null || configSubscription === void 0 ? void 0 : configSubscription.connector) === null || _j === void 0 ? void 0 : _j.id,
1321
- configurationId,
1322
- name: configSubscription.connector.name,
1323
- flowId: configureAction.handler,
1324
- description: configSubscription.connector.description,
1325
- imageUri: configSubscription.connector.imageUri,
1326
- status: configSubscription.status,
1327
- actions,
1328
- metadata: configSubscription.metaData,
1329
- };
1330
- })
1331
- .filter(Boolean);
1332
- return configurations;
1333
- }
1334
- catch (err) {
1335
- throw new Error(formatApolloErrors(err));
1336
- }
1337
- }
1338
-
1339
- function loadGapiClient() {
1340
- return new Promise((resolve, reject) => {
1341
- const script = document.createElement('script');
1342
- script.src = 'https://apis.google.com/js/api.js';
1343
- script.onload = () => resolve();
1344
- script.onerror = () => reject(new Error('Failed to load gapi'));
1345
- document.body.appendChild(script);
1346
- });
1347
- }
1348
- async function initializeGooglePicker() {
1349
- await loadGapiClient();
1350
- return new Promise((resolve) => {
1351
- // @ts-ignore
1352
- gapi.load('picker', () => {
1353
- resolve();
1354
- });
1355
- });
1356
- }
1357
- async function createGooglePicker(developerKey, accessToken) {
1358
- // Ensure Google Picker API is initialized
1359
- await initializeGooglePicker();
1360
- return new Promise((resolve, reject) => {
1361
- try {
1362
- // @ts-ignore: `google.picker` is loaded via Google APIs script
1363
- const picker = new google.picker.PickerBuilder()
1364
- // @ts-ignore
1365
- .addView(google.picker.ViewId.DOCS)
1366
- // @ts-ignore
1367
- .addView(new google.picker.DocsView(google.picker.ViewId.FOLDERS)
1368
- .setIncludeFolders(true)
1369
- .setSelectFolderEnabled(true))
1370
- // @ts-ignore
1371
- .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
1372
- .setOAuthToken(accessToken)
1373
- .setDeveloperKey(developerKey || GOOGLE_FILES_PICKER_API_KEY)
1374
- .setCallback((data) => {
1375
- if ((data === null || data === void 0 ? void 0 : data.action) === "picked") {
1376
- resolve(data === null || data === void 0 ? void 0 : data.docs);
1377
- }
1378
- })
1379
- .build();
1380
- picker.setVisible(true);
1381
- const iframe = document.querySelector("iframe.picker-dialog-frame");
1382
- const pickerDialogBg = document.querySelector(".picker-dialog-bg");
1383
- if (iframe) {
1384
- iframe.style.pointerEvents = "auto";
1385
- pickerDialogBg.style.pointerEvents = "auto";
1386
- // Step 3: Allow only iframe to be clickable
1387
- iframe.addEventListener("click", (event) => {
1388
- event.preventDefault();
1389
- event.stopPropagation();
1390
- });
1391
- pickerDialogBg.addEventListener("click", (event) => {
1392
- event.preventDefault();
1393
- event.stopPropagation();
1394
- });
1395
- }
1396
- }
1397
- catch (error) {
1398
- reject(new Error('Failed to create Google Picker'));
1399
- }
1400
- });
1401
- }
1402
-
1403
- function openGoogleFilesPicker(parentArgs) {
1404
- return async (args) => {
1405
- var _a, _b;
1406
- try {
1407
- const config = getConfig();
1408
- let accessToken = null;
1409
- let apiKey = null;
1410
- const cachedToken = localStorage.getItem(config.spaceId +
1411
- parentArgs.connectorId +
1412
- config.tenantId +
1413
- "access_token");
1414
- if (cachedToken) {
1415
- const token = safeParse(cachedToken);
1416
- if ((token === null || token === void 0 ? void 0 : token.expires_at) && token.expires_at > Date.now()) {
1417
- accessToken = token.access_token;
1418
- }
1419
- }
1420
- if (!accessToken) {
1421
- const { data } = await generateAccessToken({
1422
- input: {
1423
- orgId: config.spaceId,
1424
- tenantId: config.tenantId,
1425
- connectorId: parentArgs.connectorId,
1426
- refresh: true,
1427
- },
1428
- });
1429
- const token = data === null || data === void 0 ? void 0 : data.connectorConnection;
1430
- // cache token in local storage
1431
- localStorage.setItem(config.spaceId +
1432
- parentArgs.connectorId +
1433
- config.tenantId +
1434
- "access_token", safeStringify({
1435
- access_token: token.access_token,
1436
- api_key: (_a = token.metadata) === null || _a === void 0 ? void 0 : _a.google_picker_api_key,
1437
- expires_at: token.expires_at || Date.now() + token.expires_in * 1000,
1438
- }));
1439
- accessToken = token.access_token;
1440
- apiKey = (_b = token.metadata) === null || _b === void 0 ? void 0 : _b.google_picker_api_key;
1441
- }
1442
- const docs = await createGooglePicker(args.apiKey || apiKey, accessToken);
1443
- const files = (docs || []).map((doc) => ({
1444
- label: doc === null || doc === void 0 ? void 0 : doc.name,
1445
- value: doc === null || doc === void 0 ? void 0 : doc.id,
1446
- }));
1447
- await args.onComplete(files);
1448
- }
1449
- catch (err) {
1450
- const error = err instanceof Error ? err : new Error("Unknown error");
1451
- await args.onError(error);
1452
- }
1453
- };
1454
- }
1455
- /**
1456
- * Returns a submit handler for a configuration form.
1457
- * Handles both creation and update flows.
1458
- */
1459
- function getSubmitHandler({ configuration, configurationId, connectorId, connectorIdUiCode, configurationIdUiCode, }) {
1460
- return async ({ formData }) => {
1461
- var _a, _b, _c, _d, _e;
1462
- const config = getConfig();
1463
- const uiCodeObject = Object.assign(Object.assign({}, safeParse(configuration.uiCode)), { target: Object.assign(Object.assign({}, (_a = safeParse(configuration.uiCode)) === null || _a === void 0 ? void 0 : _a.target), { connectorId: Object.assign(Object.assign({}, (_c = (_b = safeParse(configuration.uiCode)) === null || _b === void 0 ? void 0 : _b.target) === null || _c === void 0 ? void 0 : _c.connectorId), { target: connectorIdUiCode }), id: Object.assign(Object.assign({}, (_e = (_d = safeParse(configuration.uiCode)) === null || _d === void 0 ? void 0 : _d.target) === null || _e === void 0 ? void 0 : _e.id), { target: configurationIdUiCode }) }) });
1464
- const formDataObject = Object.assign(Object.assign({}, formData), { connectorId: connectorId, id: configurationId });
1465
- const uiCode = populateFormDataInUiCode(safeStringify(uiCodeObject), formDataObject);
1466
- try {
1467
- if (configuration.status === "ENABLED") {
1468
- await updateTenantConfiguration({
1469
- input: stripTypename({
1470
- clientId: config.spaceId,
1471
- tenantId: config.tenantId,
1472
- flowId: configuration === null || configuration === void 0 ? void 0 : configuration.flowId,
1473
- stepId: configuration === null || configuration === void 0 ? void 0 : configuration.stepId,
1474
- uiCode: safeStringify(uiCode),
1475
- id: configurationId,
1476
- connectorId: connectorId,
1477
- configurations: formDataObject,
1478
- }),
1479
- });
1480
- }
1481
- else {
1482
- await createTenantConfiguration({
1483
- input: stripTypename({
1484
- clientId: config.spaceId,
1485
- tenantId: config.tenantId,
1486
- flowId: configuration === null || configuration === void 0 ? void 0 : configuration.flowId,
1487
- stepId: configuration === null || configuration === void 0 ? void 0 : configuration.stepId,
1488
- uiCode: safeStringify(uiCode),
1489
- id: configurationId,
1490
- connectorId: connectorId,
1491
- configurations: formDataObject,
1492
- }),
1493
- });
1494
- }
1495
- sendEvent("REFRESH_CONFIGURATION_FORM");
1496
- sendEvent("REFETCH_CONFIGURATIONS");
1497
- }
1498
- catch (error) {
1499
- throw new Error(formatApolloErrors(error));
1500
- }
1501
- };
1502
- }
1503
- /**
1504
- * Fetches options for select fields, supporting pagination and search.
1505
- * Extensible for custom loaders.
1506
- */
1507
- async function fetchOptions(context, pagination, resetCursor = false, query) {
1508
- var _a, _b, _c;
1509
- const config = getConfig();
1510
- try {
1511
- const { data } = await getFieldData({
1512
- input: {
1513
- id: pagination.sourceId,
1514
- clientId: config.spaceId,
1515
- // sameProjectFlow: pagination.sourceProject === "self",
1516
- input: {
1517
- data: {
1518
- input: {
1519
- data: context,
1520
- limit: pagination.limit || 10,
1521
- cursor: resetCursor ? null : pagination.cursor,
1522
- curser: resetCursor ? null : pagination.cursor,
1523
- offset: resetCursor ? 0 : pagination.offset,
1524
- query,
1525
- },
1526
- headers: { [TENANT_ID_HEADER_KEY]: config.tenantId },
1527
- },
1528
- },
1529
- },
1530
- });
1531
- const response = ((_a = data === null || data === void 0 ? void 0 : data.executeGetFieldDataFlow) === null || _a === void 0 ? void 0 : _a.data) || {};
1532
- const newOptions = response.options || [];
1533
- const limit = pagination.limit || 0;
1534
- const offset = resetCursor ? 0 : pagination.offset || 0;
1535
- const newOffset = newOptions.length > 0 ? offset + limit : offset;
1536
- const total = (_b = response.total) !== null && _b !== void 0 ? _b : pagination.total;
1537
- const cursor = response.cursor || response.curser;
1538
- const hasNextPage = Boolean(cursor || response.hasNextPage) ||
1539
- (typeof total === "number"
1540
- ? total > newOffset
1541
- : newOptions.length === limit && !pagination.cursor);
1542
- return {
1543
- options: newOptions,
1544
- pagination: Object.assign(Object.assign({}, pagination), { cursor, offset: newOffset, total,
1545
- hasNextPage, loaded: newOptions.length }),
1546
- searchable: (_c = response === null || response === void 0 ? void 0 : response.searchable) !== null && _c !== void 0 ? _c : false,
1547
- };
1548
- }
1549
- catch (error) {
1550
- throw new Error(formatApolloErrors(error));
1551
- }
1552
- }
1553
- /**
1554
- * Loads more options for a select field.
1555
- */
1556
- async function loadMoreOptions(pagination, context) {
1557
- return fetchOptions(context || {}, pagination, false);
1558
- }
1559
- /**
1560
- * Refreshes options for a select field.
1561
- */
1562
- async function refreshOptions(pagination, context) {
1563
- return fetchOptions(context || {}, pagination, true);
1564
- }
1565
- /**
1566
- * Gets options for a select field.
1567
- */
1568
- async function getOptions(pagination, context, query) {
1569
- return fetchOptions(context || {}, pagination, false, query);
1570
- }
1571
- /**
1572
- * Searches options for a select field.
1573
- */
1574
- async function searchOptions(query, pagination, context) {
1575
- return fetchOptions(context || {}, pagination, false, query);
1576
- }
1577
- /**
1578
- * Fetches and builds a configuration form for a connector.
1579
- * Integrates with state management for loading/error.
1580
- * @param input - ConfigurationFormInput
1581
- * @returns Promise<ConfigurationForm>
1582
- */
1583
- async function getConfigurationForm(input) {
1584
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1585
- try {
1586
- const config = getConfig();
1587
- const { data: configurationFormData } = await getConfigurationSubscriptionById({
1588
- input: {
1589
- clientId: config.spaceId,
1590
- tenantId: config.tenantId,
1591
- id: input.configurationId,
1592
- connectorId: input.connectorId,
1593
- widgetConnectorId: input.connectorId,
1594
- flowId: (_a = input === null || input === void 0 ? void 0 : input.configuration) === null || _a === void 0 ? void 0 : _a.flowId,
1595
- },
1596
- });
1597
- const uiCodeString = (_b = configurationFormData === null || configurationFormData === void 0 ? void 0 : configurationFormData.tenantConfigurationsById) === null || _b === void 0 ? void 0 : _b.uiCode;
1598
- const uiCode = safeParse(uiCodeString || "") || {};
1599
- // remove connectorId and id field from uiCode.target and save that in separate fields
1600
- const connectorIdUiCode = (_c = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _c === void 0 ? void 0 : _c.connectorId;
1601
- const configurationIdUiCode = (_d = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _d === void 0 ? void 0 : _d.id;
1602
- (_e = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _e === void 0 ? true : delete _e.connectorId;
1603
- (_f = uiCode === null || uiCode === void 0 ? void 0 : uiCode.target) === null || _f === void 0 ? true : delete _f.id;
1604
- const fields = uiCodeToFormFields(uiCode, {
1605
- getOptions,
1606
- loadMore: loadMoreOptions,
1607
- refresh: refreshOptions,
1608
- searchOptions,
1609
- openGoogleFilesPicker: openGoogleFilesPicker({
1610
- connectorId: input.connectorId,
1611
- }),
1612
- });
1613
- return {
1614
- name: ((_g = input === null || input === void 0 ? void 0 : input.configuration) === null || _g === void 0 ? void 0 : _g.name) || "",
1615
- description: ((_h = input === null || input === void 0 ? void 0 : input.configuration) === null || _h === void 0 ? void 0 : _h.description) || "",
1616
- imageUri: ((_j = input === null || input === void 0 ? void 0 : input.configuration) === null || _j === void 0 ? void 0 : _j.imageUri) || "",
1617
- fields: fields,
1618
- submitHandler: getSubmitHandler({
1619
- configuration: configurationFormData === null || configurationFormData === void 0 ? void 0 : configurationFormData.tenantConfigurationsById,
1620
- configurationId: input === null || input === void 0 ? void 0 : input.configurationId,
1621
- connectorId: input === null || input === void 0 ? void 0 : input.connectorId,
1622
- connectorIdUiCode: connectorIdUiCode,
1623
- configurationIdUiCode: configurationIdUiCode,
1624
- }),
1625
- };
1626
- }
1627
- catch (error) {
1628
- throw new Error(formatApolloErrors(error));
1629
- }
1630
- }
1631
-
1632
- const registerRefetchFunction = (input) => {
1633
- const { refetchFunction, refetchKey } = input;
1634
- };
1635
-
1636
- class Fastn {
1637
- constructor(config) {
1638
- setConfig(config);
1639
- }
1640
- getConnectors(input) {
1641
- return getConnectors(input);
1642
- }
1643
- getConfigurations(input) {
1644
- return getConfigurations(input);
1645
- }
1646
- getConfigurationForm(input) {
1647
- return getConfigurationForm(input);
1648
- }
1649
- registerRefetchFunction(input) {
1650
- return registerRefetchFunction(input);
1651
- }
1652
- onEvent(event, callback) {
1653
- return onEvent(event, callback);
1654
- }
1655
- offEvent(event, callback) {
1656
- return offEvent(event, callback);
1657
- }
1658
- }
1659
-
1660
7
  const FastnContext = createContext(null);
1661
8
  const FastnProvider = ({ children, config, queryClient, }) => {
1662
9
  const fastn = useMemo(() => {