-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathportal.js
More file actions
9441 lines (8177 loc) · 359 KB
/
Copy pathportal.js
File metadata and controls
9441 lines (8177 loc) · 359 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
// Anypoint API Portal - Interactive Features
// ============================================================================
// Helper Functions for Rendering
// ============================================================================
function renderJsonPath(jsonPath) {
if (!jsonPath) return '';
// Syntax highlighting for JSONPath
var html = '<code class="jsonpath">';
// Color different parts of the JSONPath
var parts = jsonPath.split('.');
var colored = parts.map(function(part, idx) {
if (part.startsWith('$')) {
return '<span class="jsonpath-root">' + escapeHtml(part) + '</span>';
} else if (part.includes('[')) {
// Handle array notation
var match = part.match(/^([^\[]+)(\[.+\])$/);
if (match) {
return '<span class="jsonpath-field">' + escapeHtml(match[1]) + '</span>' +
'<span class="jsonpath-bracket">' + escapeHtml(match[2]) + '</span>';
}
return '<span class="jsonpath-field">' + escapeHtml(part) + '</span>';
} else if (part === '*') {
return '<span class="jsonpath-wildcard">' + escapeHtml(part) + '</span>';
} else {
return '<span class="jsonpath-field">' + escapeHtml(part) + '</span>';
}
});
html += colored.join('<span class="jsonpath-dot">.</span>');
html += '</code>';
return html;
}
/**
* Build a [method] [serverUrl + path] URL bar as an HTML string.
* Used in x-origin modals, workflow steps, and anywhere operation info is shown.
* @param {string} method - HTTP method (GET, POST, etc.)
* @param {string} serverUrl - Resolved server base URL
* @param {string} path - Operation path template
* @param {string} [link] - Optional href to link the whole bar to an operation detail page
*/
function buildUrlBarHtml(method, serverUrl, path, link) {
var methodClass = method.toLowerCase();
var html = '<div class="operation-url-bar-inline">';
if (link) html += '<a href="' + escapeHtml(link) + '" class="operation-url-bar-link">';
html += '<span class="method method-' + methodClass + '">' + escapeHtml(method) + '</span>';
html += '<code class="url-bar-text">';
html += '<span class="url-server-part">' + escapeHtml(serverUrl) + '</span>';
html += '<span class="url-path-part">' + escapeHtml(path) + '</span>';
html += '</code>';
if (link) html += '</a>';
html += '</div>';
return html;
}
// ============================================================================
// X-Origin Modal and Interactive Fetching
// ============================================================================
// Stack of x-origin modals for nested pickers
var xOriginModalStack = [];
function openXOriginModal(opId, paramName, location) {
var inputId = 'param-' + opId + '-' + paramName;
var input = document.getElementById(inputId);
if (!input) {
console.error('X-Origin modal: Could not find input element with ID:', inputId);
return;
}
var originsJson = input.getAttribute('data-x-origins');
if (!originsJson) {
console.error('X-Origin modal: No data-x-origins attribute found on input:', inputId);
return;
}
var origins = [];
try {
// Try Base64 decoding first (new format)
if (originsJson.indexOf('[') !== 0 && originsJson.indexOf('{') !== 0) {
originsJson = atob(originsJson);
}
origins = JSON.parse(originsJson);
} catch (e) {
console.error('Failed to parse x-origins:', e);
console.error('Origins JSON:', originsJson);
return;
}
// Hide current modal if one is open (nested modal)
var modal = document.getElementById('xorigin-modal');
if (modal && modal.style.display === 'flex') {
modal.style.display = 'none';
}
// Push new modal context to stack
xOriginModalStack.push({ opId: opId, paramName: paramName, location: location, origins: origins });
var modal = document.getElementById('xorigin-modal');
var title = document.getElementById('xorigin-modal-title');
var body = document.getElementById('xorigin-modal-body');
if (!modal || !title || !body) {
console.error('X-Origin modal: Modal elements not found', { modal: !!modal, title: !!title, body: !!body });
return;
}
title.textContent = 'Select a value for: ' + paramName;
// Get operation lookup for parameter details
var opLookup = window.__OP_LOOKUP__ || {};
// Load environment variables to pre-fill form
var envVars = loadEnvVars();
var envVarsMap = {};
envVars.forEach(function(v) {
envVarsMap[v.name] = v.value;
});
// Build source selector dropdown (no execute button here - it's in the panel)
var html = '<div class="xorigin-selector-container">';
html += '<select id="xorigin-source-selector" class="xorigin-source-select" onchange="switchXOriginSource()">';
origins.forEach(function(origin, idx) {
var apiSlug = (origin.api || '').replace('urn:api:', '');
var operationId = origin.operation || '';
var name = origin.name;
var technicalRef = apiSlug + '#' + operationId;
var optionLabel = name ? (name + ' - ' + technicalRef) : technicalRef;
html += '<option value="' + idx + '">' + escapeHtml(optionLabel) + '</option>';
});
html += '</select>';
html += '</div>';
// Build source containers (hidden by default, first one visible)
origins.forEach(function(origin, idx) {
var apiSlug = (origin.api || '').replace('urn:api:', '');
var operationId = origin.operation || '';
html += '<div class="xorigin-source" data-source-idx="' + idx + '" style="display:' + (idx === 0 ? 'block' : 'none') + '">';
// Get operation details for this source
var apiEntry = opLookup[apiSlug];
var opMeta = apiEntry ? apiEntry.ops[operationId] : null;
// Show operation URL bar and parameters
if (opMeta) {
var xoriginServerUrl = getServerForApi(apiSlug).replace(/\/$/, '');
// Panel header matching try-panel-header structure (title and Send in same row)
var linkPrefix = window.__API_LINK_PREFIX__ || '';
html += '<div class="try-panel-header">';
// Left side: operationId as link (with xpath info if available)
html += '<div class="xorigin-title-section">';
html += '<a href="' + escapeHtml(linkPrefix + apiSlug + '.html#op-' + operationId) + '" target="_blank" class="xorigin-operation-link">';
html += '<h4>' + escapeHtml(apiSlug) + '.' + escapeHtml(operationId) + '</h4>';
html += '</a>';
// Xpath expressions inline
if (origin.values || origin.labels) {
html += '<span class="xorigin-xpath-info">';
if (origin.values) {
html += '<span class="xorigin-path-inline">';
html += '<span class="xorigin-path-label">values:</span>';
html += '<code class="xorigin-path-value">' + escapeHtml(origin.values) + '</code>';
html += '</span>';
}
if (origin.labels) {
html += '<span class="xorigin-path-inline">';
html += '<span class="xorigin-path-label">labels:</span>';
html += '<code class="xorigin-path-value">' + escapeHtml(origin.labels) + '</code>';
html += '</span>';
}
html += '</span>';
}
html += '</div>';
// Right side: actions (spinner + send button + dropdown)
html += '<div class="try-header-actions">';
html += '<span class="try-spinner" id="spinner-xorigin-' + idx + '" style="display:none">Sending...</span>';
html += '<button class="btn-send" onclick="executeXOriginSource(' + idx + ', this)">';
html += '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
html += '<span>Send</span>';
html += '</button>';
html += '<button class="btn-copy-curl" onclick="copyCurlCommand(\'xorigin-' + idx + '\', this)">';
html += '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>';
html += '<span>Copy cURL</span>';
html += '</button>';
html += '</div>';
html += '</div>';
// Operation URL bar (below header)
html += '<div class="operation-url-bar-container">';
html += buildUrlBarHtml(opMeta.method, xoriginServerUrl, opMeta.path, null);
html += '</div>';
// Use shared panel renderer for two-column layout (no execute button - it's in header)
var xoriginOpId = 'xorigin-' + idx;
html += renderOperationPanel(xoriginOpId, opMeta, {
yamlInputs: envVarsMap,
enableVariableRefs: false,
slug: '',
contextType: 'xorigin',
showExecuteButton: false // Button is in header now
});
// Extracted values will be shown in the "Extracted Values" tab of the response section
}
html += '</div>';
});
body.innerHTML = html;
modal.style.display = 'flex';
// Initialize ACE editors for request bodies
initCodeMirrorEditors();
// Focus trap: focus the first focusable element and store previous focus
modal._previousFocus = document.activeElement;
var firstFocusable = modal.querySelector('button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
if (firstFocusable) firstFocusable.focus();
}
function closeXOriginModal() {
// Pop current modal from stack
xOriginModalStack.pop();
var modal = document.getElementById('xorigin-modal');
// If there's a parent modal in the stack, restore it
if (xOriginModalStack.length > 0) {
var parentModal = xOriginModalStack[xOriginModalStack.length - 1];
// Reopen the parent modal
reopenXOriginModal(parentModal);
} else {
// No parent modal, close completely
modal.style.display = 'none';
// Restore focus to the element that opened the modal
if (modal._previousFocus) modal._previousFocus.focus();
}
}
function reopenXOriginModal(modalContext) {
var modal = document.getElementById('xorigin-modal');
var title = document.getElementById('xorigin-modal-title');
var body = document.getElementById('xorigin-modal-body');
if (!modal || !title || !body) {
console.error('X-Origin modal: Modal elements not found');
return;
}
var opId = modalContext.opId;
var paramName = modalContext.paramName;
var origins = modalContext.origins;
title.textContent = 'Select a value for: ' + paramName;
// Get operation lookup for parameter details
var opLookup = window.__OP_LOOKUP__ || {};
// Load environment variables to pre-fill form
var envVars = loadEnvVars();
var envVarsMap = {};
envVars.forEach(function(v) {
envVarsMap[v.name] = v.value;
});
// Build source selector dropdown
var html = '<div class="xorigin-selector-container">';
html += '<select id="xorigin-source-selector" class="xorigin-source-select" onchange="switchXOriginSource()">';
origins.forEach(function(origin, idx) {
var apiSlug = (origin.api || '').replace('urn:api:', '');
var operationId = origin.operation || '';
var name = origin.name;
var technicalRef = apiSlug + '#' + operationId;
var optionLabel = name ? (name + ' - ' + technicalRef) : technicalRef;
html += '<option value="' + idx + '">' + escapeHtml(optionLabel) + '</option>';
});
html += '</select>';
html += '</div>';
// Build source containers
origins.forEach(function(origin, idx) {
var apiSlug = (origin.api || '').replace('urn:api:', '');
var operationId = origin.operation || '';
html += '<div class="xorigin-source" data-source-idx="' + idx + '" style="display:' + (idx === 0 ? 'block' : 'none') + '">';
var apiEntry = opLookup[apiSlug];
var opMeta = apiEntry ? apiEntry.ops[operationId] : null;
if (opMeta) {
var xoriginServerUrl = getServerForApi(apiSlug).replace(/\/$/, '');
var linkPrefix = window.__API_LINK_PREFIX__ || '';
html += '<div class="try-panel-header">';
html += '<div class="xorigin-title-section">';
html += '<a href="' + escapeHtml(linkPrefix + apiSlug + '.html#op-' + operationId) + '" target="_blank" class="xorigin-operation-link">';
html += '<h4>' + escapeHtml(apiSlug) + '.' + escapeHtml(operationId) + '</h4>';
html += '</a>';
if (origin.values || origin.labels) {
html += '<span class="xorigin-xpath-info">';
if (origin.values) {
html += '<span class="xorigin-path-inline">';
html += '<span class="xorigin-path-label">values:</span>';
html += '<code class="xorigin-path-value">' + escapeHtml(origin.values) + '</code>';
html += '</span>';
}
if (origin.labels) {
html += '<span class="xorigin-path-inline">';
html += '<span class="xorigin-path-label">labels:</span>';
html += '<code class="xorigin-path-value">' + escapeHtml(origin.labels) + '</code>';
html += '</span>';
}
html += '</span>';
}
html += '</div>';
html += '<div class="try-header-actions">';
html += '<span class="try-spinner" id="spinner-xorigin-' + idx + '" style="display:none">Sending...</span>';
html += '<button class="btn-send" onclick="executeXOriginSource(' + idx + ', this)">';
html += '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
html += '<span>Send</span>';
html += '</button>';
html += '<button class="btn-copy-curl" onclick="copyCurlCommand(\'xorigin-' + idx + '\', this)">';
html += '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>';
html += '<span>Copy cURL</span>';
html += '</button>';
html += '</div>';
html += '</div>';
html += '<div class="operation-url-bar-container">';
html += buildUrlBarHtml(opMeta.method, xoriginServerUrl, opMeta.path, null);
html += '</div>';
var xoriginOpId = 'xorigin-' + idx;
html += renderOperationPanel(xoriginOpId, opMeta, {
yamlInputs: envVarsMap,
enableVariableRefs: false,
slug: '',
contextType: 'xorigin',
showExecuteButton: false
});
}
html += '</div>';
});
body.innerHTML = html;
modal.style.display = 'flex';
// Initialize ACE editors
initCodeMirrorEditors();
}
function switchXOriginSource() {
var selector = document.getElementById('xorigin-source-selector');
if (!selector) return;
var selectedIdx = parseInt(selector.value, 10);
var allSources = document.querySelectorAll('.xorigin-source');
allSources.forEach(function(source, idx) {
source.style.display = (idx === selectedIdx) ? 'block' : 'none';
});
}
async function executeXOriginSource(sourceIdx, buttonEl) {
// If sourceIdx not provided, get it from the selector
if (sourceIdx === undefined) {
var selector = document.getElementById('xorigin-source-selector');
if (selector) {
sourceIdx = parseInt(selector.value, 10);
} else {
sourceIdx = 0;
}
}
var xoriginOpId = 'xorigin-' + sourceIdx;
var sourceDiv = document.querySelector('.xorigin-source[data-source-idx="' + sourceIdx + '"]');
var responseDiv = document.getElementById('response-' + xoriginOpId);
var statusBadge = document.getElementById('status-' + xoriginOpId);
var responseBodyDiv = document.getElementById('respbody-' + xoriginOpId);
var responseHeadersDiv = document.getElementById('respheaders-' + xoriginOpId);
var valuesOutputDiv = document.getElementById('xorigin-values-' + sourceIdx);
if (!responseDiv) {
console.error('Response div not found', { responseDiv: !!responseDiv, sourceIdx: sourceIdx });
return;
}
// Button feedback
var originalText = 'Send';
if (buttonEl) {
var textSpan = buttonEl.querySelector('span');
if (textSpan) {
originalText = textSpan.textContent;
textSpan.textContent = 'Sending...';
}
buttonEl.disabled = true;
}
// Helper to reset button state
function resetButton() {
if (buttonEl) {
var textSpan = buttonEl.querySelector('span');
if (textSpan) textSpan.textContent = originalText;
buttonEl.disabled = false;
}
}
// Get the origin configuration from current modal context
var currentModal = xOriginModalStack[xOriginModalStack.length - 1];
if (!currentModal) {
console.error('No current x-origin modal in stack');
resetButton();
return;
}
var origins = currentModal.origins;
var origin = origins[sourceIdx];
// Check authentication
var token = sessionStorage.getItem('anypoint_token');
if (!token) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Please authenticate first.</div>';
responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
if (isTokenExpired()) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Token expired. Please re-authenticate.</div>';
responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
var apiSlug = (origin.api || '').replace('urn:api:', '');
var operationId = origin.operation || '';
var valuesPath = origin.values || '';
var labelsPath = origin.labels || '';
// Get operation metadata
var opLookup = window.__OP_LOOKUP__ || {};
var apiEntry = opLookup[apiSlug];
if (!apiEntry) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">API "' + escapeHtml(apiSlug) + '" not found.</div>';
responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
var opMeta = apiEntry.ops[operationId];
if (!opMeta) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Operation "' + escapeHtml(operationId) + '" not found.</div>';
responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
var method = opMeta.method;
var pathTemplate = opMeta.path;
// Collect parameters from input fields in the modal
var paramInputs = sourceDiv.querySelectorAll('input[data-param], select[data-param]');
var paramsByLocation = { path: {}, query: {}, header: {} };
var missingParams = [];
paramInputs.forEach(function(input) {
var paramName = input.getAttribute('data-param');
var paramIn = input.getAttribute('data-in');
var value = input.value;
if (value) {
paramsByLocation[paramIn][paramName] = value;
} else if (input.hasAttribute('required')) {
missingParams.push(paramName);
}
});
if (missingParams.length > 0) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Missing required parameters: ' + escapeHtml(missingParams.join(', ')) + '</div>';
responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
// Build URL - substitute path parameters
var path = pathTemplate;
for (var paramName in paramsByLocation.path) {
var value = paramsByLocation.path[paramName];
path = path.replace('{' + paramName + '}', encodeURIComponent(value));
}
// Check for any remaining unsubstituted path parameters
var unresolvedParams = (path.match(/\{([^}]+)\}/g) || []);
if (unresolvedParams.length > 0) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Missing path parameters: ' + escapeHtml(unresolvedParams.join(', ')) + '</div>';
responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
// Build query string
var queryParts = [];
for (var paramName in paramsByLocation.query) {
queryParts.push(encodeURIComponent(paramName) + '=' + encodeURIComponent(paramsByLocation.query[paramName]));
}
if (queryParts.length > 0) {
path += '?' + queryParts.join('&');
}
// Get server URL for the target API
var serverUrl = getServerForApi(apiSlug).replace(/\/$/, '');
var fullUrl = serverUrl + path;
// Update UI state
if (responseDiv) responseDiv.classList.add('empty');
try {
// Build headers including auth headers and parameter headers
var headers = Object.assign(
{'Content-Type': 'application/json'},
getAuthHeaders(),
paramsByLocation.header
);
var resp = await fetch(PROXY_URL, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
method: method,
url: fullUrl,
headers: headers,
body: null
})
});
var data = await resp.json();
await handleProxyResponse(data);
resetButton();
if (responseDiv) responseDiv.classList.remove('empty');
// Update status badge
if (statusBadge) {
var statusClass = 'status-error';
if (data.status >= 200 && data.status < 300) {
statusClass = 'status-2xx';
} else if (data.status >= 300 && data.status < 400) {
statusClass = 'status-3xx';
} else if (data.status >= 400 && data.status < 500) {
statusClass = 'status-4xx';
} else if (data.status >= 500) {
statusClass = 'status-5xx';
}
statusBadge.className = 'response-status-badge ' + statusClass;
statusBadge.textContent = data.status;
}
if (data.error) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Error: ' + escapeHtml(data.error) + '</div>';
if (responseDiv) responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
if (data.status < 200 || data.status >= 300) {
if (responseBodyDiv) responseBodyDiv.innerHTML = '<div class="xorigin-error">Request returned status ' + data.status + '</div>';
if (responseDiv) responseDiv.classList.remove('empty');
switchResponseTab(xoriginOpId, 'body');
resetButton();
return;
}
// Display response using shared function
displayResponseInAceEditors(responseBodyDiv, responseHeadersDiv, data);
// Parse response body for value extraction
var body = null;
try {
body = JSON.parse(data.body || '{}');
} catch (e) {
console.warn('X-Origin: Response is not valid JSON, cannot extract values');
resetButton();
return;
}
// Extract values and labels using paths
var values = extractXOriginValues(body, valuesPath);
var labels = [];
if (labelsPath) {
labels = extractXOriginValues(body, labelsPath);
if (labels.length !== values.length) {
console.warn('Labels count mismatch: ' + labels.length + ' labels vs ' + values.length + ' values.');
labels = [];
}
}
// Show extracted values in the "Extracted Values" tab
var extractedTab = document.getElementById('respextracted-xorigin-' + sourceIdx);
if (extractedTab) {
if (values.length > 0) {
// Build array of items with name and id
var items = values.map(function(val, valIdx) {
var valueStr = typeof val === 'object' ? JSON.stringify(val) : String(val);
var labelStr = labels[valIdx] ? String(labels[valIdx]) : valueStr;
return {
name: labelStr,
id: valueStr,
index: valIdx
};
});
// Sort by name
items.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
var valuesHtml = '<div class="xorigin-values-section">';
valuesHtml += '<table class="xorigin-values-table">';
valuesHtml += '<thead><tr><th>Name</th><th>ID</th><th></th></tr></thead>';
valuesHtml += '<tbody>';
items.forEach(function(item) {
valuesHtml += '<tr>';
valuesHtml += '<td class="xorigin-name-cell">' + escapeHtml(item.name) + '</td>';
valuesHtml += '<td class="xorigin-id-cell"><code>' + escapeHtml(item.id) + '</code></td>';
valuesHtml += '<td class="xorigin-action-cell"><button class="btn-use-value" data-value="' + escapeHtml(item.id) + '" onclick="useXOriginValue(' + sourceIdx + ', ' + item.index + ', this.getAttribute(\'data-value\'))">Select</button></td>';
valuesHtml += '</tr>';
});
valuesHtml += '</tbody>';
valuesHtml += '</table>';
valuesHtml += '</div>';
extractedTab.innerHTML = valuesHtml;
} else {
extractedTab.innerHTML = '<div class="xorigin-error">No values found at path: ' + escapeHtml(valuesPath) + '</div>';
}
}
} catch (e) {
// Restore button
if (buttonEl) {
var textSpan = buttonEl.querySelector('span');
if (textSpan) textSpan.textContent = originalText;
buttonEl.disabled = false;
}
if (responseDiv) responseDiv.classList.remove('empty');
if (statusBadge) {
statusBadge.textContent = 'Error';
statusBadge.className = 'response-status-badge status-error';
}
if (responseBodyDiv) {
responseBodyDiv.innerHTML = '<div class="xorigin-error">Request failed: ' + escapeHtml(e.message) + '</div>';
}
}
}
function useXOriginValue(sourceIdx, valueIdx, valueStr) {
var displayVal = valueStr;
// Get current modal context
var currentModal = xOriginModalStack[xOriginModalStack.length - 1];
if (!currentModal) {
console.error('No current x-origin modal in stack');
return;
}
var paramName = currentModal.paramName;
// Set the value in the input — MCP inputs use a different ID pattern
var inputId = currentModal.isMcp
? 'mcp-param-' + currentModal.opId + '-' + paramName.replace(/\./g, '-')
: 'param-' + currentModal.opId + '-' + paramName;
var input = document.getElementById(inputId);
if (input) {
input.value = displayVal;
}
// Add or update environment variable
var vars = loadEnvVars();
var existingVar = vars.find(function(v) { return v.name === paramName; });
if (existingVar) {
// Update existing variable
existingVar.value = displayVal;
} else {
// Add new variable
vars.push({ name: paramName, value: displayVal });
}
// Save and re-render environment variables
sessionStorage.setItem(ENV_STORAGE_KEY, JSON.stringify(vars));
renderEnvVars();
// If this is the last modal in the stack (closing back to the original panel),
// update all fields in the original panel with environment variable values
var isClosingToOriginalPanel = xOriginModalStack.length === 1;
if (isClosingToOriginalPanel) {
// Get the root opId (the original Try it out panel)
var rootOpId = currentModal.opId;
updatePanelFieldsFromEnvVars(rootOpId);
}
// Close modal
closeXOriginModal();
// Show feedback
showAuthMessage('Value set for ' + paramName + ': ' + displayVal + ' (added to environment variables)', false);
}
function updatePanelFieldsFromEnvVars(opId) {
// Load all environment variables
var vars = loadEnvVars();
var envVarsMap = {};
vars.forEach(function(v) {
envVarsMap[v.name] = v.value;
});
// Find all parameter inputs in the panel (try regular API panel first, then playground)
var panel = document.getElementById('try-' + opId);
if (!panel) {
panel = document.getElementById('playground-panel-' + opId);
}
if (!panel) return;
var inputs = panel.querySelectorAll('[data-param]');
inputs.forEach(function(input) {
var paramName = input.getAttribute('data-param');
// Only update if field is empty or doesn't have a variable reference
var currentValue = input.value || '';
var hasVarRef = currentValue && detectVariableReferences(currentValue).length > 0;
if (!hasVarRef && envVarsMap[paramName] !== undefined && envVarsMap[paramName] !== '') {
input.value = envVarsMap[paramName];
}
});
}
// Update all playground panels with current environment variables
function updateAllPlaygroundPanelsFromEnvVars() {
var playgroundPanels = document.querySelectorAll('[id^="playground-panel-"]');
playgroundPanels.forEach(function(panel) {
var sid = panel.id.replace('playground-panel-', '');
updatePanelFieldsFromEnvVars(sid);
});
}
function switchXOriginTab(sourceIdx, tabName) {
var source = document.querySelector('.xorigin-source[data-source-idx="' + sourceIdx + '"]');
if (!source) return;
// Update tab buttons
var tabButtons = source.querySelectorAll('.xorigin-tab-btn');
tabButtons.forEach(function(btn) {
btn.classList.remove('active');
});
var activeButton = Array.from(tabButtons).find(function(btn) {
return btn.textContent.toLowerCase().startsWith(tabName.toLowerCase());
});
if (activeButton) activeButton.classList.add('active');
// Update tab panels
var panels = source.querySelectorAll('.xorigin-tab-panel');
panels.forEach(function(panel) {
panel.classList.remove('active');
});
var activePanel = document.getElementById('xorigin-tab-' + tabName + '-' + sourceIdx);
if (activePanel) activePanel.classList.add('active');
}
// ============================================================================
// X-Origin for MCP Tool Inputs
// ============================================================================
function openMcpXOriginModal(invocableId, dataPath) {
var inputId = 'mcp-param-' + invocableId + '-' + dataPath.replace(/\./g, '-');
var input = document.getElementById(inputId);
if (!input) return;
var originsJson = input.getAttribute('data-x-origins');
if (!originsJson) return;
var origins = [];
try {
if (originsJson.indexOf('[') !== 0 && originsJson.indexOf('{') !== 0) {
originsJson = atob(originsJson);
}
origins = JSON.parse(originsJson);
} catch (e) {
console.error('Failed to parse x-origins for MCP:', e);
return;
}
var modal = document.getElementById('xorigin-modal');
if (modal && modal.style.display === 'flex') {
modal.style.display = 'none';
}
xOriginModalStack.push({
opId: invocableId,
paramName: dataPath,
origins: origins,
isMcp: true
});
var modal = document.getElementById('xorigin-modal');
var title = document.getElementById('xorigin-modal-title');
var body = document.getElementById('xorigin-modal-body');
if (!modal || !title || !body) return;
title.textContent = 'Select a value for: ' + dataPath;
var opLookup = window.__OP_LOOKUP__ || {};
var mcpLookup = window.__MCP_LOOKUP__ || {};
var envVars = loadEnvVars();
var envVarsMap = {};
envVars.forEach(function(v) { envVarsMap[v.name] = v.value; });
var html = '';
if (origins.length > 1) {
html += '<div class="xorigin-selector-container">';
html += '<select id="xorigin-source-selector" class="xorigin-source-select" onchange="switchXOriginSource()">';
origins.forEach(function(origin, idx) {
var urn = origin.api || '';
var opName = origin.operation || '';
var slug = urn.replace(/^urn:(api|mcp):/, '');
var sourceType = urn.startsWith('urn:mcp:') ? 'mcp' : 'api';
var technicalRef = slug + '#' + opName;
var label = origin.name ? (origin.name + ' - ' + technicalRef) : technicalRef;
html += '<option value="' + idx + '">[' + sourceType + '] ' + escapeHtml(label) + '</option>';
});
html += '</select></div>';
}
origins.forEach(function(origin, idx) {
var urn = origin.api || '';
var opName = origin.operation || '';
var isMcpSource = urn.startsWith('urn:mcp:');
var slug = urn.replace(/^urn:(api|mcp):/, '');
html += '<div class="xorigin-source" data-source-idx="' + idx + '" style="display:' + (idx === 0 ? 'block' : 'none') + '">';
if (isMcpSource) {
html += _buildMcpSourcePanel(idx, slug, opName, origin, mcpLookup, envVarsMap);
} else {
html += _buildApiSourcePanel(idx, slug, opName, origin, opLookup, envVarsMap);
}
html += '</div>';
});
body.innerHTML = html;
modal.style.display = 'flex';
initCodeMirrorEditors();
modal._previousFocus = document.activeElement;
var firstFocusable = modal.querySelector('button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
if (firstFocusable) firstFocusable.focus();
}
function _buildApiSourcePanel(idx, apiSlug, operationId, origin, opLookup, envVarsMap) {
var apiEntry = opLookup[apiSlug];
var opMeta = apiEntry ? apiEntry.ops[operationId] : null;
if (!opMeta) return '<div class="xorigin-error">API "' + escapeHtml(apiSlug) + '#' + escapeHtml(operationId) + '" not found in lookup.</div>';
var serverUrl = getServerForApi(apiSlug).replace(/\/$/, '');
var linkPrefix = window.__API_LINK_PREFIX__ || '';
var html = '';
html += '<div class="try-panel-header">';
html += '<div class="xorigin-title-section">';
html += '<a href="' + escapeHtml(linkPrefix + apiSlug + '.html#op-' + operationId) + '" target="_blank" class="xorigin-operation-link">';
html += '<h4>' + escapeHtml(apiSlug) + '.' + escapeHtml(operationId) + '</h4>';
html += '</a>';
html += _buildXpathInfoHtml(origin);
html += '</div>';
html += '<div class="try-header-actions">';
html += '<span class="try-spinner" id="spinner-xorigin-' + idx + '" style="display:none">Sending...</span>';
html += '<button class="btn-send" onclick="executeXOriginSource(' + idx + ', this)">';
html += '<img src="../assets/icons/send-icon.svg" alt="" width="13" height="11"><span>Send</span></button>';
html += '<button class="btn-copy-curl" onclick="copyCurlCommand(\'xorigin-' + idx + '\', this)">';
html += '<img src="../assets/icons/copy-curl-icon.svg" alt="" width="13" height="13"><span>Copy cURL</span></button>';
html += '</div></div>';
html += '<div class="operation-url-bar-container">';
html += buildUrlBarHtml(opMeta.method, serverUrl, opMeta.path, null);
html += '</div>';
var xoriginOpId = 'xorigin-' + idx;
html += renderOperationPanel(xoriginOpId, opMeta, {
yamlInputs: envVarsMap,
enableVariableRefs: false,
slug: '',
contextType: 'xorigin',
showExecuteButton: false
});
return html;
}
function _buildMcpSourcePanel(idx, mcpSlug, toolName, origin, mcpLookup, envVarsMap) {
var mcpEntry = mcpLookup[mcpSlug];
if (!mcpEntry) return '<div class="xorigin-error">MCP "' + escapeHtml(mcpSlug) + '" not found in lookup.</div>';
var toolMeta = mcpEntry.tools[toolName];
if (!toolMeta) return '<div class="xorigin-error">Tool "' + escapeHtml(toolName) + '" not found on MCP "' + escapeHtml(mcpSlug) + '".</div>';
var linkPrefix = window.__MCP_LINK_PREFIX__ || '';
var xoriginOpId = 'xorigin-' + idx;
var html = '';
// Header: title + xpath info + action buttons (same as API panel)
html += '<div class="try-panel-header">';
html += '<div class="xorigin-title-section">';
html += '<a href="' + escapeHtml(linkPrefix + mcpSlug + '.html#tool-' + toolName) + '" target="_blank" class="xorigin-operation-link">';
html += '<h4>' + escapeHtml(mcpSlug) + '.' + escapeHtml(toolName) + '</h4>';
html += '</a>';
html += _buildXpathInfoHtml(origin);
html += '</div>';
html += '<div class="try-header-actions">';
html += '<span class="try-spinner" id="spinner-xorigin-' + idx + '" style="display:none">Sending...</span>';
html += '<button class="btn-send" onclick="executeMcpXOriginSource(' + idx + ', this)">';
html += '<img src="../assets/icons/send-icon.svg" alt="" width="13" height="11"><span>Send</span></button>';
html += '<button class="btn-copy-curl" onclick="copyXOriginMcpCurl(\'' + xoriginOpId + '\', ' + idx + ', this)">';
html += '<img src="../assets/icons/copy-curl-icon.svg" alt="" width="13" height="13"><span>Copy cURL</span></button>';
html += '</div></div>';
// URL bar
html += '<div class="operation-url-bar-container">';
html += '<div class="operation-url-bar-inline">';
html += '<span class="method method-mcp-tool">TOOL</span>';
html += '<code class="url-bar-text">' + escapeHtml(toolName) + '</code>';
html += '</div></div>';
var inputSchema = toolMeta.inputSchema || {};
var properties = inputSchema.properties || {};
var required = inputSchema.required || [];
// Two-column grid (same as renderOperationPanel)
html += '<div class="operation-panel-grid">';
// Left column: Form + action buttons
html += '<div class="operation-panel-form">';
var propNames = Object.keys(properties);
if (propNames.length > 0) {
propNames.forEach(function(name) {
var prop = properties[name];
var ptype = (prop && prop.type) || 'string';
var isRequired = required.indexOf(name) !== -1;
var defaultVal = prop.default !== undefined && prop.default !== null ? prop.default : '';
var placeholder = ptype;
var prefilledVal = envVarsMap[name] || defaultVal;
html += '<div class="try-param-row">';
html += '<label><span class="param-name-wrapper"><code>' + escapeHtml(name) + '</code>';
if (isRequired) html += ' <span class="param-required" title="Required">*</span>';
html += ': <code class="param-type-inline">' + escapeHtml(ptype) + '</code></span></label>';
if (ptype === 'object' || ptype === 'array') {
var exampleJson = '';
if (prop._example_json) exampleJson = prop._example_json;
html += '<div id="mcp-arg-' + xoriginOpId + '-' + name + '" class="try-request-editor-cm"';
html += ' data-param="' + escapeHtml(name) + '" data-in="mcp-arg" data-type="' + ptype + '"';
html += ' data-content-type="application/json"';
html += ' data-example-body="' + escapeHtml(exampleJson) + '"></div>';
} else if (ptype === 'boolean') {
html += '<select data-param="' + escapeHtml(name) + '" data-in="mcp-arg" data-type="boolean">';
html += '<option value=""></option><option value="true">true</option><option value="false">false</option>';
html += '</select>';
} else {
html += '<input type="' + (ptype === 'integer' || ptype === 'number' ? 'number' : 'text') + '"';
html += ' data-param="' + escapeHtml(name) + '" data-in="mcp-arg" data-type="' + escapeHtml(ptype) + '"';
html += ' placeholder="' + escapeHtml(String(placeholder)) + '"';
html += ' value="' + escapeHtml(String(prefilledVal)) + '"';
if (isRequired) html += ' required';
html += '>';
}
html += '</div>';