-
Notifications
You must be signed in to change notification settings - Fork 630
Expand file tree
/
Copy pathgateways.js
More file actions
2041 lines (1834 loc) · 69 KB
/
gateways.js
File metadata and controls
2041 lines (1834 loc) · 69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { loadAuthHeaders, updateAuthHeadersJSON } from "./auth.js";
import { MASKED_AUTH_VALUE } from "./constants.js";
import { closeModal, openModal } from "./modals.js";
import { initPromptSelect } from "./prompts.js";
import { initResourceSelect } from "./resources.js";
import { validateInputName, validateJson, validateUrl } from "./security.js";
import {
ensureNoResultsElement,
serverSideEditPromptsSearch,
serverSideEditResourcesSearch,
serverSideEditToolSearch,
serverSidePromptSearch,
serverSideResourceSearch,
serverSideToolSearch,
} from "./search.js";
import { getEditSelections } from "./servers.js";
import { applyVisibilityRestrictions } from "./teams.js";
import { initToolSelect } from "./tools.js";
import {
buildTableUrl,
decodeHtml,
fetchWithTimeout,
getCurrentTeamId,
handleFetchError,
isInactiveChecked,
makeCopyIdButton,
safeGetElement,
showErrorMessage,
showSuccessMessage,
} from "./utils.js";
/**
* SECURE: View Gateway function
*/
export const viewGateway = async function (gatewayId) {
try {
console.log(`Viewing gateway ID: ${gatewayId}`);
const response = await fetchWithTimeout(
`${window.ROOT_PATH}/admin/gateways/${gatewayId}`
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const gateway = await response.json();
const gatewayDetailsDiv = safeGetElement("gateway-details");
if (gatewayDetailsDiv) {
const container = document.createElement("div");
container.className = "space-y-2 dark:bg-gray-900 dark:text-gray-100";
// ID field with copy-to-clipboard button
const idP = document.createElement("p");
const idStrong = document.createElement("strong");
idStrong.textContent = "Gateway ID: ";
idP.appendChild(idStrong);
const idSpan = document.createElement("span");
idSpan.className = "font-mono text-sm";
idSpan.textContent = gateway.id;
idP.appendChild(idSpan);
idP.appendChild(makeCopyIdButton(gateway.id));
container.appendChild(idP);
const fields = [
{ label: "Name", value: gateway.name },
{ label: "URL", value: gateway.url },
{
label: "Description",
value: decodeHtml(gateway.description) || "N/A",
},
{ label: "Visibility", value: gateway.visibility || "private" },
];
// Add tags field with special handling
const tagsP = document.createElement("p");
const tagsStrong = document.createElement("strong");
tagsStrong.textContent = "Tags: ";
tagsP.appendChild(tagsStrong);
if (gateway.tags && gateway.tags.length > 0) {
gateway.tags.forEach((tag, index) => {
const tagSpan = document.createElement("span");
tagSpan.className =
"inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full mr-1";
const raw =
typeof tag === "object" && tag !== null
? tag.id || tag.label || JSON.stringify(tag)
: tag;
tagSpan.textContent = raw;
tagsP.appendChild(tagSpan);
});
} else {
tagsP.appendChild(document.createTextNode("No tags"));
}
container.appendChild(tagsP);
fields.forEach((field) => {
const p = document.createElement("p");
const strong = document.createElement("strong");
strong.textContent = field.label + ": ";
p.appendChild(strong);
p.appendChild(document.createTextNode(field.value));
container.appendChild(p);
});
// Status
const statusP = document.createElement("p");
const statusStrong = document.createElement("strong");
statusStrong.textContent = "Status: ";
statusP.appendChild(statusStrong);
const statusSpan = document.createElement("span");
let statusText = "";
let statusClass = "";
let statusIcon = "";
if (!gateway.enabled) {
statusText = "Inactive";
statusClass = "bg-red-100 text-red-800";
statusIcon = `
<svg class="ml-1 h-4 w-4 text-red-600 self-center" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M6.293 6.293a1 1 0 011.414 0L10 8.586l2.293-2.293a1 1 0 111.414 1.414L11.414 10l2.293 2.293a1 1 0 11-1.414 1.414L10 11.414l-2.293 2.293a1 1 0 11-1.414-1.414L8.586 10 6.293 7.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>`;
} else if (gateway.enabled && gateway.reachable) {
statusText = "Active";
statusClass = "bg-green-100 text-green-800";
statusIcon = `
<svg class="ml-1 h-4 w-4 text-green-600 self-center" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-4.586l5.293-5.293-1.414-1.414L9 11.586 7.121 9.707 5.707 11.121 9 14.414z" clip-rule="evenodd"></path>
</svg>`;
} else if (gateway.enabled && !gateway.reachable) {
statusText = "Offline";
statusClass = "bg-yellow-100 text-yellow-800";
statusIcon = `
<svg class="ml-1 h-4 w-4 text-yellow-600 self-center" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-10h2v4h-2V8zm0 6h2v2h-2v-2z" clip-rule="evenodd"></path>
</svg>`;
}
statusSpan.className = `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}`;
statusSpan.innerHTML = `${statusText} ${statusIcon}`;
statusP.appendChild(statusSpan);
container.appendChild(statusP);
// Add metadata section
const metadataDiv = document.createElement("div");
metadataDiv.className = "mt-6 border-t pt-4";
const metadataTitle = document.createElement("strong");
metadataTitle.textContent = "Metadata:";
metadataDiv.appendChild(metadataTitle);
const metadataGrid = document.createElement("div");
metadataGrid.className = "grid grid-cols-2 gap-4 mt-2 text-sm";
const metadataFields = [
{
label: "Created By",
value: gateway.created_by || gateway.createdBy || "Legacy Entity",
},
{
label: "Created At",
value:
gateway.created_at || gateway.createdAt
? new Date(
gateway.created_at || gateway.createdAt
).toLocaleString()
: "Pre-metadata",
},
{
label: "Created From IP",
value: gateway.created_from_ip || gateway.createdFromIp || "Unknown",
},
{
label: "Created Via",
value: gateway.created_via || gateway.createdVia || "Unknown",
},
{
label: "Last Modified By",
value: gateway.modified_by || gateway.modifiedBy || "N/A",
},
{
label: "Last Modified At",
value:
gateway.updated_at || gateway.updatedAt
? new Date(
gateway.updated_at || gateway.updatedAt
).toLocaleString()
: "N/A",
},
{
label: "Modified From IP",
value: gateway.modified_from_ip || gateway.modifiedFromIp || "N/A",
},
{
label: "Modified Via",
value: gateway.modified_via || gateway.modifiedVia || "N/A",
},
{ label: "Version", value: gateway.version || "1" },
{
label: "Import Batch",
value: gateway.importBatchId || "N/A",
},
];
metadataFields.forEach((field) => {
const fieldDiv = document.createElement("div");
const labelSpan = document.createElement("span");
labelSpan.className = "font-medium text-gray-600 dark:text-gray-400";
labelSpan.textContent = field.label + ":";
const valueSpan = document.createElement("span");
valueSpan.className = "ml-2";
valueSpan.textContent = field.value;
fieldDiv.appendChild(labelSpan);
fieldDiv.appendChild(valueSpan);
metadataGrid.appendChild(fieldDiv);
});
metadataDiv.appendChild(metadataGrid);
container.appendChild(metadataDiv);
gatewayDetailsDiv.innerHTML = "";
gatewayDetailsDiv.appendChild(container);
}
openModal("gateway-modal");
console.log("✓ Gateway details loaded successfully");
} catch (error) {
console.error("Error fetching gateway details:", error);
const errorMessage = handleFetchError(error, "load gateway details");
showErrorMessage(errorMessage);
}
};
/**
* SECURE: Edit Gateway function
*/
export const editGateway = async function (gatewayId) {
try {
console.log(`Editing gateway ID: ${gatewayId}`);
const response = await fetchWithTimeout(
`${window.ROOT_PATH}/admin/gateways/${gatewayId}`
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const gateway = await response.json();
console.log("Gateway Details: " + JSON.stringify(gateway, null, 2));
const isInactiveCheckedBool = isInactiveChecked("gateways");
let hiddenField = safeGetElement("edit-gateway-show-inactive");
if (!hiddenField) {
hiddenField = document.createElement("input");
hiddenField.type = "hidden";
hiddenField.name = "is_inactive_checked";
hiddenField.id = "edit-gateway-show-inactive";
const editForm = safeGetElement("edit-gateway-form");
if (editForm) {
editForm.appendChild(hiddenField);
}
}
hiddenField.value = isInactiveCheckedBool;
// Set form action and populate fields with validation
const editForm = safeGetElement("edit-gateway-form");
if (editForm) {
editForm.action = `${window.ROOT_PATH}/admin/gateways/${gatewayId}/edit`;
}
const nameValidation = validateInputName(gateway.name, "gateway");
const urlValidation = validateUrl(gateway.url);
const nameField = safeGetElement("edit-gateway-name");
const urlField = safeGetElement("edit-gateway-url");
const descField = safeGetElement("edit-gateway-description");
const transportField = safeGetElement("edit-gateway-transport");
if (nameField && nameValidation.valid) {
nameField.value = nameValidation.value;
}
if (urlField && urlValidation.valid) {
urlField.value = urlValidation.value;
}
if (descField) {
descField.value = decodeHtml(gateway.description || "");
}
// Set tags field
const tagsField = safeGetElement("edit-gateway-tags");
if (tagsField) {
const rawTags = gateway.tags
? gateway.tags.map((tag) =>
typeof tag === "object" && tag !== null ? tag.label || tag.id : tag
)
: [];
tagsField.value = rawTags.join(", ");
}
const teamId = new URL(window.location.href).searchParams.get("team_id");
if (teamId) {
const hiddenInput = document.createElement("input");
hiddenInput.type = "hidden";
hiddenInput.name = "team_id";
hiddenInput.value = teamId;
editForm.appendChild(hiddenInput);
}
const visibility = gateway.visibility
? gateway.visibility.toLowerCase()
: null;
const publicRadio = safeGetElement("edit-gateway-visibility-public");
const teamRadio = safeGetElement("edit-gateway-visibility-team");
const privateRadio = safeGetElement("edit-gateway-visibility-private");
// Clear all first
if (publicRadio) {
publicRadio.checked = false;
}
if (teamRadio) {
teamRadio.checked = false;
}
if (privateRadio) {
privateRadio.checked = false;
}
if (visibility) {
// When public visibility is disabled and we're in a team-scoped view,
// coerce legacy-public records to team.
const effectiveVisibility =
window.ALLOW_PUBLIC_VISIBILITY === false &&
visibility === "public" &&
teamId
? "team"
: visibility;
if (effectiveVisibility === "public" && publicRadio) {
publicRadio.checked = true;
} else if (effectiveVisibility === "team" && teamRadio) {
teamRadio.checked = true;
} else if (effectiveVisibility === "private" && privateRadio) {
privateRadio.checked = true;
}
}
if (transportField) {
transportField.value = gateway.transport || "SSE"; // falls back to Admin.SSE(default)
}
const authTypeField = safeGetElement("auth-type-gw-edit");
if (authTypeField) {
authTypeField.value = gateway.authType || ""; // falls back to None
}
// Auth containers
const authBasicSection = safeGetElement("auth-basic-fields-gw-edit");
const authBearerSection = safeGetElement("auth-bearer-fields-gw-edit");
const authHeadersSection = safeGetElement("auth-headers-fields-gw-edit");
const authOAuthSection = safeGetElement("auth-oauth-fields-gw-edit");
const authQueryParamSection = safeGetElement(
"auth-query_param-fields-gw-edit"
);
// Individual fields
const authUsernameField = safeGetElement(
"auth-basic-fields-gw-edit"
)?.querySelector("input[name='auth_username']");
const authPasswordField = safeGetElement(
"auth-basic-fields-gw-edit"
)?.querySelector("input[name='auth_password']");
const authTokenField = safeGetElement(
"auth-bearer-fields-gw-edit"
)?.querySelector("input[name='auth_token']");
const authHeaderKeyField = safeGetElement(
"auth-headers-fields-gw-edit"
)?.querySelector("input[name='auth_header_key']");
const authHeaderValueField = safeGetElement(
"auth-headers-fields-gw-edit"
)?.querySelector("input[name='auth_header_value']");
// OAuth fields
const oauthGrantTypeField = safeGetElement("oauth-grant-type-gw-edit");
const oauthClientIdField = safeGetElement("oauth-client-id-gw-edit");
const oauthClientSecretField = safeGetElement(
"oauth-client-secret-gw-edit"
);
const oauthTokenUrlField = safeGetElement("oauth-token-url-gw-edit");
const oauthAuthUrlField = safeGetElement("oauth-authorization-url-gw-edit");
const oauthRedirectUriField = safeGetElement("oauth-redirect-uri-gw-edit");
const oauthIssuerField = safeGetElement("oauth-issuer-gw-edit");
const oauthScopesField = safeGetElement("oauth-scopes-gw-edit");
const oauthAuthCodeFields = safeGetElement(
"oauth-auth-code-fields-gw-edit"
);
// Hide all auth sections first
if (authBasicSection) {
authBasicSection.style.display = "none";
}
if (authBearerSection) {
authBearerSection.style.display = "none";
}
if (authHeadersSection) {
authHeadersSection.style.display = "none";
}
if (authOAuthSection) {
authOAuthSection.style.display = "none";
}
if (authQueryParamSection) {
authQueryParamSection.style.display = "none";
}
switch (gateway.authType) {
case "basic":
if (authBasicSection) {
authBasicSection.style.display = "block";
if (authUsernameField) {
authUsernameField.value = gateway.authUsername || "";
}
if (authPasswordField) {
if (gateway.authPasswordUnmasked) {
authPasswordField.dataset.isMasked = "true";
authPasswordField.dataset.realValue =
gateway.authPasswordUnmasked;
} else {
delete authPasswordField.dataset.isMasked;
delete authPasswordField.dataset.realValue;
}
authPasswordField.value = MASKED_AUTH_VALUE;
}
}
break;
case "bearer":
if (authBearerSection) {
authBearerSection.style.display = "block";
if (authTokenField) {
if (gateway.authTokenUnmasked) {
authTokenField.dataset.isMasked = "true";
authTokenField.dataset.realValue = gateway.authTokenUnmasked;
authTokenField.value = MASKED_AUTH_VALUE;
} else {
delete authTokenField.dataset.isMasked;
delete authTokenField.dataset.realValue;
authTokenField.value = gateway.authToken || "";
}
}
}
break;
case "authheaders":
if (authHeadersSection) {
authHeadersSection.style.display = "block";
if (
Array.isArray(gateway.authHeaders) &&
gateway.authHeaders.length > 0
) {
loadAuthHeaders(
"auth-headers-container-gw-edit",
gateway.authHeaders,
{ maskValues: true }
);
} else {
updateAuthHeadersJSON("auth-headers-container-gw-edit");
}
if (authHeaderKeyField) {
authHeaderKeyField.value = gateway.authHeaderKey || "";
}
if (authHeaderValueField) {
if (
Array.isArray(gateway.authHeaders) &&
gateway.authHeaders.length === 1
) {
authHeaderValueField.dataset.isMasked = "true";
authHeaderValueField.dataset.realValue =
gateway.authHeaders[0].value ?? "";
}
authHeaderValueField.value = MASKED_AUTH_VALUE;
}
}
break;
case "oauth":
if (authOAuthSection) {
authOAuthSection.style.display = "block";
}
// Populate OAuth fields if available
if (gateway.oauthConfig) {
const config = gateway.oauthConfig;
if (oauthIssuerField) {
oauthIssuerField.value = config.issuer || "";
}
if (oauthGrantTypeField) {
oauthGrantTypeField.value = config.grant_type || "";
// Show/hide authorization code fields based on grant type
if (oauthAuthCodeFields) {
oauthAuthCodeFields.style.display =
config.grant_type === "authorization_code" ? "block" : "none";
}
}
if (oauthClientIdField) {
oauthClientIdField.value = config.client_id || "";
}
if (oauthClientSecretField) {
oauthClientSecretField.value = ""; // Don't populate secret for security
}
if (oauthTokenUrlField) {
oauthTokenUrlField.value = config.token_url || "";
}
if (oauthAuthUrlField) {
oauthAuthUrlField.value = config.authorization_url || "";
}
if (oauthRedirectUriField) {
oauthRedirectUriField.value = config.redirect_uri || "";
}
if (oauthScopesField) {
oauthScopesField.value = Array.isArray(config.scopes)
? config.scopes.join(" ")
: "";
}
}
break;
case "query_param":
if (authQueryParamSection) {
authQueryParamSection.style.display = "block";
// Get the input fields within the section
const queryParamKeyField = authQueryParamSection.querySelector(
"input[name='auth_query_param_key']"
);
const queryParamValueField = authQueryParamSection.querySelector(
"input[name='auth_query_param_value']"
);
if (queryParamKeyField && gateway.authQueryParamKey) {
queryParamKeyField.value = gateway.authQueryParamKey;
}
if (queryParamValueField) {
// Always show masked value for security
queryParamValueField.value = MASKED_AUTH_VALUE;
if (gateway.authQueryParamValueUnmasked) {
queryParamValueField.dataset.isMasked = "true";
queryParamValueField.dataset.realValue =
gateway.authQueryParamValueUnmasked;
} else {
delete queryParamValueField.dataset.isMasked;
delete queryParamValueField.dataset.realValue;
}
}
}
break;
case "":
default:
// No auth – keep everything hidden
break;
}
// Handle passthrough headers
const passthroughHeadersField = safeGetElement(
"edit-gateway-passthrough-headers"
);
if (passthroughHeadersField) {
if (
gateway.passthroughHeaders &&
Array.isArray(gateway.passthroughHeaders)
) {
passthroughHeadersField.value = gateway.passthroughHeaders.join(", ");
} else {
passthroughHeadersField.value = "";
}
}
openModal("gateway-edit-modal");
applyVisibilityRestrictions(["edit-gateway-visibility"]); // Disable public radio if restricted, preserve checked state
console.log("✓ Gateway edit modal loaded successfully");
} catch (error) {
console.error("Error fetching gateway for editing:", error);
const errorMessage = handleFetchError(error, "load gateway for editing");
showErrorMessage(errorMessage);
}
};
// ===================================================================
// GATEWAY SELECT (Associated MCP Servers) - search/select/clear
// ===================================================================
export const initGatewaySelect = function (
selectId = "associatedGateways",
pillsId = "selectedGatewayPills",
warnId = "selectedGatewayWarning",
max = 12,
selectBtnId = "selectAllGatewayBtn",
clearBtnId = "clearAllGatewayBtn",
searchInputId = "searchGateways"
) {
const container = safeGetElement(selectId);
const pillsBox = safeGetElement(pillsId);
const warnBox = safeGetElement(warnId);
const clearBtn = clearBtnId ? safeGetElement(clearBtnId) : null;
const selectBtn = selectBtnId ? safeGetElement(selectBtnId) : null;
const searchInput = searchInputId ? safeGetElement(searchInputId) : null;
if (!container || !pillsBox || !warnBox) {
console.warn(
`Gateway select elements not found: ${selectId}, ${pillsId}, ${warnId}`
);
return;
}
const pillClasses =
"inline-block bg-indigo-100 text-indigo-800 text-xs px-2 py-1 rounded-full dark:bg-indigo-900 dark:text-indigo-200";
// Search functionality
const applySearch = function () {
if (!searchInput) {
return;
}
try {
const query = searchInput.value.toLowerCase().trim();
const items = container.querySelectorAll(".tool-item");
let visibleCount = 0;
items.forEach((item) => {
const text = item.textContent.toLowerCase();
if (!query || text.includes(query)) {
item.style.display = "";
visibleCount++;
} else {
item.style.display = "none";
}
});
// Update "no results" message – ensure element exists even if template is cached
// Use edit-modal message element when operating on the edit container
const noMsgId = selectId.includes("Edit")
? "noEditGatewayMessage"
: "noGatewayMessage";
const searchQuerySpanId = selectId.includes("Edit")
? "searchQueryEditServers"
: "searchQueryServers";
const { msg: noMsg, span: searchQuerySpan } = ensureNoResultsElement(
selectId,
noMsgId,
searchQuerySpanId,
"MCP server"
);
if (query && visibleCount === 0) {
container.style.display = "none";
if (noMsg) {
noMsg.style.display = "block";
if (searchQuerySpan) {
searchQuerySpan.textContent = query;
}
}
} else {
container.style.display = "";
if (noMsg) {
noMsg.style.display = "none";
}
}
} catch (error) {
console.error("Error applying gateway search:", error);
}
};
// Bind search input
if (searchInput && !searchInput.dataset.searchBound) {
searchInput.addEventListener("input", applySearch);
searchInput.dataset.searchBound = "true";
}
const update = function () {
try {
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
const checked = Array.from(checkboxes).filter((cb) => cb.checked);
// Check if "Select All" mode is active
const selectAllInput = container.querySelector(
'input[name="selectAllGateways"]'
);
const allIdsInput = container.querySelector(
'input[name="allGatewayIds"]'
);
let count = checked.length;
// If Select All mode is active, use the count from allGatewayIds
if (selectAllInput && selectAllInput.value === "true" && allIdsInput) {
try {
const allIds = JSON.parse(allIdsInput.value);
count = allIds.length;
} catch (e) {
console.error("Error parsing allGatewayIds:", e);
}
}
// Rebuild pills safely - show first 3, then summarize the rest
pillsBox.innerHTML = "";
const maxPillsToShow = 3;
checked.slice(0, maxPillsToShow).forEach((cb) => {
const span = document.createElement("span");
span.className = pillClasses;
span.textContent =
cb.nextElementSibling?.textContent?.trim() || "Unnamed";
pillsBox.appendChild(span);
});
// If more than maxPillsToShow, show a summary pill
if (count > maxPillsToShow) {
const span = document.createElement("span");
span.className = pillClasses + " cursor-pointer";
span.title = "Click to see all selected gateways";
const remaining = count - maxPillsToShow;
span.textContent = `+${remaining} more`;
pillsBox.appendChild(span);
}
// Warning when > max
if (count > max) {
warnBox.textContent = `Selected ${count} MCP servers. Selecting more than ${max} servers may impact performance.`;
} else {
warnBox.textContent = "";
}
// Update the Select All button text to show count
if (selectBtnId) {
const currentSelectBtn = document.getElementById(selectBtnId);
if (currentSelectBtn) {
if (count > 0) {
currentSelectBtn.textContent = `Select All (${count})`;
} else {
currentSelectBtn.textContent = "Select All";
}
}
}
} catch (error) {
console.error("Error updating gateway select:", error);
}
};
// Remove old event listeners by cloning and replacing (preserving ID)
if (clearBtn && !clearBtn.dataset.listenerAttached) {
clearBtn.dataset.listenerAttached = "true";
const newClearBtn = clearBtn.cloneNode(true);
newClearBtn.dataset.listenerAttached = "true";
clearBtn.parentNode.replaceChild(newClearBtn, clearBtn);
newClearBtn.addEventListener("click", () => {
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((cb) => (cb.checked = false));
// Clear the "select all" flag
const selectAllInput = container.querySelector(
'input[name="selectAllGateways"]'
);
if (selectAllInput) {
selectAllInput.remove();
}
const allIdsInput = container.querySelector(
'input[name="allGatewayIds"]'
);
if (allIdsInput) {
allIdsInput.remove();
}
update();
// Reload associated items after clearing selection
reloadAssociatedItems();
});
}
if (selectBtn && !selectBtn.dataset.listenerAttached) {
selectBtn.dataset.listenerAttached = "true";
const newSelectBtn = selectBtn.cloneNode(true);
newSelectBtn.dataset.listenerAttached = "true";
selectBtn.parentNode.replaceChild(newSelectBtn, selectBtn);
newSelectBtn.addEventListener("click", async () => {
// Disable button and show loading state
newSelectBtn.disabled = true;
newSelectBtn.textContent = "Selecting all gateways...";
try {
// Fetch all gateway IDs from the server.
// Respect View Public checkbox: keep team_id, add include_public when checked.
// Use the correct checkbox for the active modal context.
const selectedTeamId = getCurrentTeamId();
const vpCbId = selectId.includes("Edit")
? "edit-server-view-public"
: "add-server-view-public";
const vpCb = document.getElementById(vpCbId);
const params = new URLSearchParams();
if (selectedTeamId) {
params.set("team_id", selectedTeamId);
}
if (vpCb && vpCb.checked) {
params.set("include_public", "true");
}
const queryString = params.toString();
const response = await fetch(
`${window.ROOT_PATH}/admin/gateways/ids${queryString ? `?${queryString}` : ""}`
);
if (!response.ok) {
throw new Error("Failed to fetch gateway IDs");
}
const data = await response.json();
const allGatewayIds = data.gateway_ids || [];
// Apply search filter first to determine which items are visible
applySearch();
// Check only currently visible checkboxes
const loadedCheckboxes = container.querySelectorAll(
'input[type="checkbox"]'
);
loadedCheckboxes.forEach((cb) => {
const parent = cb.closest(".tool-item") || cb.parentElement;
const isVisible =
parent && getComputedStyle(parent).display !== "none";
if (isVisible) {
cb.checked = true;
}
});
// Add a hidden input to indicate "select all" mode
// Remove any existing one first
let selectAllInput = container.querySelector(
'input[name="selectAllGateways"]'
);
if (!selectAllInput) {
selectAllInput = document.createElement("input");
selectAllInput.type = "hidden";
selectAllInput.name = "selectAllGateways";
container.appendChild(selectAllInput);
}
selectAllInput.value = "true";
// Also store the IDs as a JSON array for the backend
// Ensure the special 'null' sentinel is included when selecting all
try {
const nullCheckbox = container.querySelector(
'input[data-gateway-null="true"]'
);
if (nullCheckbox) {
// Include the literal string "null" so server-side
// `any(gid.lower() == 'null' ...)` evaluates to true.
if (!allGatewayIds.includes("null")) {
allGatewayIds.push("null");
}
}
} catch (err) {
console.error("Error ensuring null sentinel in gateway IDs:", err);
}
let allIdsInput = container.querySelector(
'input[name="allGatewayIds"]'
);
if (!allIdsInput) {
allIdsInput = document.createElement("input");
allIdsInput.type = "hidden";
allIdsInput.name = "allGatewayIds";
container.appendChild(allIdsInput);
}
allIdsInput.value = JSON.stringify(allGatewayIds);
update();
// Reload associated items after selecting all
reloadAssociatedItems();
} catch (error) {
console.error("Error in Select All:", error);
alert("Failed to select all gateways. Please try again.");
newSelectBtn.disabled = false;
update(); // Reset button text via update()
} finally {
newSelectBtn.disabled = false;
}
});
}
update(); // Initial render
// Attach change listeners to checkboxes (using delegation for dynamic content)
if (!container.dataset.changeListenerAttached) {
container.dataset.changeListenerAttached = "true";
container.addEventListener("change", (e) => {
if (e.target.type === "checkbox") {
// Log gateway_id when checkbox is clicked
// Normalize the special null-gateway checkbox to the literal string "null"
let gatewayId = e.target.value;
if (e.target.dataset && e.target.dataset.gatewayNull === "true") {
gatewayId = "null";
}
const gatewayName =
e.target.nextElementSibling?.textContent?.trim() || "Unknown";
const isChecked = e.target.checked;
console.log(
`[MCP Server Selection] Gateway ID: ${gatewayId}, Name: ${gatewayName}, Checked: ${isChecked}`
);
// Check if we're in "Select All" mode
const selectAllInput = container.querySelector(
'input[name="selectAllGateways"]'
);
const allIdsInput = container.querySelector(
'input[name="allGatewayIds"]'
);
if (selectAllInput && selectAllInput.value === "true" && allIdsInput) {
// User is manually checking/unchecking after Select All
// Update the allGatewayIds array to reflect the change
try {
let allIds = JSON.parse(allIdsInput.value);
if (e.target.checked) {
// Add the ID if it's not already there
if (!allIds.includes(gatewayId)) {
allIds.push(gatewayId);
}
} else {
// Remove the ID from the array
allIds = allIds.filter((id) => id !== gatewayId);
}
// Update the hidden field
allIdsInput.value = JSON.stringify(allIds);
} catch (error) {
console.error("Error updating allGatewayIds:", error);
}
}
// No exclusivity: allow the special 'null' gateway (RestTool/Prompts/Resources) to be
// selected together with real gateways. Server-side filtering already
// supports mixed lists like `gateway_id=abc,null`.
update();
// Trigger reload of associated tools, resources, and prompts with selected gateway filter
reloadAssociatedItems();
}
});
}
// Initial render
applySearch();
update();
};
/**
* Get all selected gateway IDs from the gateway selection container
* @returns {string[]} Array of selected gateway IDs
*/
export const getSelectedGatewayIds = function () {
// Prefer the gateway selection belonging to the currently active form.
// If the edit-server modal is open, use the edit modal's gateway container
// (`associatedEditGateways`). Otherwise use the create form container
// (`associatedGateways`). This allows the same filtering logic to work
// for both Add and Edit flows.
let container = safeGetElement("associatedGateways");
const editContainer = safeGetElement("associatedEditGateways");
const editModal = safeGetElement("server-edit-modal");
const isEditModalOpen = editModal && !editModal.classList.contains("hidden");
if (isEditModalOpen && editContainer) {
container = editContainer;
} else if (
editContainer &&
editContainer.offsetParent !== null &&
!container
) {
// If edit container is visible (e.g. modal rendered) and associatedGateways
// not present, prefer edit container.
container = editContainer;
}
console.log(
"[Gateway Selection DEBUG] Container used:",
container ? container.id : null
);
if (!container) {
console.warn(
"[Gateway Selection DEBUG] No gateway container found (associatedGateways or associatedEditGateways)"
);
return [];
}