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