-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.html
More file actions
1097 lines (1025 loc) · 50.2 KB
/
Copy pathindex.html
File metadata and controls
1097 lines (1025 loc) · 50.2 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
<script type="text/html" data-template-name="function-gpt">
<style>
.func-tabs-row {
margin-bottom: 0;
}
#node-input-libs-container-row .red-ui-editableList-container {
padding: 0px;
}
#node-input-libs-container-row .red-ui-editableList-container li {
padding:0px;
}
#node-input-libs-container-row .red-ui-editableList-item-remove {
right: 5px;
}
#node-input-libs-container-row .red-ui-editableList-header {
display: flex;
background: var(--red-ui-tertiary-background);
padding-right: 75px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
#node-input-libs-container-row .red-ui-editableList-header > div {
flex-grow: 1;
}
.node-libs-entry {
display: flex;
}
.node-libs-entry .red-ui-typedInput-container {
border-radius: 0;
border: none;
}
.node-libs-entry .red-ui-typedInput-type-select {
border-radius: 0 !important;
height: 34px;
}
.node-libs-entry > span > input[type=text] {
border-radius: 0;
border-top-color: var(--red-ui-form-background);
border-bottom-color: var(--red-ui-form-background);
border-right-color: var(--red-ui-form-background);
}
.node-libs-entry > span {
flex-grow: 1;
width: 50%;
position: relative;
}
.node-libs-entry span .node-input-libs-var, .node-libs-entry span .red-ui-typedInput-container {
width: 100%;
}
.node-libs-entry > span > span > i {
display: none;
}
.node-libs-entry > span > span.input-error > i {
display: inline;
}
</style>
<input type="hidden" id="node-input-func">
<input type="hidden" id="node-input-noerr">
<input type="hidden" id="node-input-finalize">
<input type="hidden" id="node-input-initialize">
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name">Name</span></label>
<div style="display: inline-block; width: calc(100% - 105px)"><input type="text" id="node-input-name" placeholder="Name" data-i18n="[placeholder]common.label.name"></div>
</div>
<div class="form-row">
<label for="node-input-config"><i class="fa fa-tag"></i> <span>GPT Config</span></label>
<div style="display: inline-block; width: calc(100% - 200px)"><input type="text" id="node-input-config"></div>
</div>
<div class="form-row func-tabs-row">
<ul style="min-width: 600px; margin-bottom: 20px;" id="func-tabs"></ul>
</div>
<div id="func-tabs-content" style="min-height: calc(100% - 165px);">
<div id="func-tab-config" style="display:none">
<div class="form-row">
<label for="node-input-outputs"><i class="fa fa-random"></i> <span data-i18n="function-gpt.label.outputs">Outputs</span></label>
<input id="node-input-outputs" style="width: 60px;" value="1">
</div>
<div class="form-row node-input-libs-row hide" style="margin-bottom: 0px;">
<label><i class="fa fa-cubes"></i> <span data-i18n="function-gpt.label.modules">Modules</span></label>
</div>
<div class="form-row node-input-libs-row hide" id="node-input-libs-container-row">
<ol id="node-input-libs-container"></ol>
</div>
</div>
<div id="func-tab-init" style="display:none">
<div class="form-row node-text-editor-row" style="position:relative">
<div style="height: 250px; min-height:150px;" class="node-text-editor" id="node-input-init-editor" ></div>
<div style="position: absolute; right:0; bottom: calc(100% - 20px); z-Index: 10;"><button type="button" id="node-init-expand-js" class="red-ui-button red-ui-button-small"><i class="fa fa-expand"></i></button></div>
</div>
</div>
<div id="func-tab-body" style="display:none">
<div class="form-row node-text-editor-row" style="position:relative">
<div style="height: 220px; min-height:150px;" class="node-text-editor" id="node-input-func-editor" ></div>
<div style="position: absolute; right:0; bottom: calc(100% - 20px); z-Index: 10;"><button type="button" id="node-function-expand-js" class="red-ui-button red-ui-button-small"><i class="fa fa-expand"></i></button></div>
</div>
</div>
<div id="func-tab-finalize" style="display:none">
<div class="form-row node-text-editor-row" style="position:relative">
<div style="height: 250px; min-height:150px;" class="node-text-editor" id="node-input-finalize-editor" ></div>
<div style="position: absolute; right:0; bottom: calc(100% - 20px); z-Index: 10;"><button type="button" id="node-finalize-expand-js" class="red-ui-button red-ui-button-small"><i class="fa fa-expand"></i></button></div>
</div>
</div>
</div>
<div id="func-tab-chatgpt" style="display: flex; gap: 6px;">
<input id="chatgpt-input" type="search" style="width:100%;" disabled/>
<input id="chatgpt-ask" class="ui-button ui-widget ui-corner-all primary" type="button" value="Ask ChatGPT" disabled>
<i id="chatgpt-loading" class="fa fa-spinner fa-spin" style="font-size:20px; line-height: 34px; display:none"></i>
<button id="chatgpt-cancel" class="ui-button ui-widget ui-corner-all primary" style="font-size:20px; display: none;">
<i class="fa fa-times"></i>
</button>
</div>
</script>
<script type="text/javascript">
(function() {
var invalidModuleVNames = [
'console',
'util',
'Buffer',
'Date',
'RED',
'node',
'__node__',
'context',
'flow',
'global',
'env',
'setTimeout',
'clearTimeout',
'setInterval',
'clearInterval',
'promisify'
]
var knownFunctionNodes = {};
RED.events.on("nodes:add", function(n) {
if (n.type === "function-gpt") {
knownFunctionNodes[n.id] = n;
}
})
RED.events.on("nodes:remove", function(n) {
if (n.type === "function-gpt") {
delete knownFunctionNodes[n.id];
}
})
var missingModules = [];
var missingModuleReasons = {};
RED.events.on("runtime-state", function(event) {
if (event.error === "missing-modules") {
missingModules = event.modules.map(function(m) { missingModuleReasons[m.module] = m.error; return m.module });
for (var id in knownFunctionNodes) {
if (knownFunctionNodes.hasOwnProperty(id) && knownFunctionNodes[id].libs && knownFunctionNodes[id].libs.length > 0) {
RED.editor.validateNode(knownFunctionNodes[id])
}
}
} else if (!event.text) {
missingModuleReasons = {};
missingModules = [];
for (var id in knownFunctionNodes) {
if (knownFunctionNodes.hasOwnProperty(id) && knownFunctionNodes[id].libs && knownFunctionNodes[id].libs.length > 0) {
RED.editor.validateNode(knownFunctionNodes[id])
}
}
}
RED.view.redraw();
});
var installAllowList = ['*'];
var installDenyList = [];
var modulesEnabled = true;
if (RED.settings.get('externalModules.modules.allowInstall', true) === false) {
modulesEnabled = false;
}
var settingsAllowList = RED.settings.get("externalModules.modules.allowList")
var settingsDenyList = RED.settings.get("externalModules.modules.denyList")
if (settingsAllowList || settingsDenyList) {
installAllowList = settingsAllowList;
installDenyList = settingsDenyList
}
installAllowList = RED.utils.parseModuleList(installAllowList);
installDenyList = RED.utils.parseModuleList(installDenyList);
// object that maps from library name to its descriptor
var allLibs = [];
function moduleName(module) {
var match = /^([^@]+)@(.+)/.exec(module);
if (match) {
return [match[1], match[2]];
}
return [module, undefined];
}
function getAllUsedModules() {
var moduleSet = new Set();
for (var id in knownFunctionNodes) {
if (knownFunctionNodes.hasOwnProperty(id)) {
if (knownFunctionNodes[id].libs) {
for (var i=0, l=knownFunctionNodes[id].libs.length; i<l; i++) {
if (RED.utils.checkModuleAllowed(knownFunctionNodes[id].libs[i].module,null,installAllowList,installDenyList)) {
moduleSet.add(knownFunctionNodes[id].libs[i].module);
}
}
}
}
}
var modules = Array.from(moduleSet);
modules.sort();
return modules;
}
function prepareLibraryConfig(node) {
$(".node-input-libs-row").show();
var usedModules = getAllUsedModules();
var typedModules = usedModules.map(function(l) {
return {icon:"fa fa-cube", value:l,label:l,hasValue:false}
})
typedModules.push({
value:"_custom_", label:RED._("editor:subflow.licenseOther"), icon:"red/images/typedInput/az.svg"
})
var libList = $("#node-input-libs-container").css('min-height','100px').css('min-width','450px').editableList({
header: $('<div><div data-i18n="node-red:function-gpt.require.moduleName">Module Name</div><div data-i18n="node-red:function-gpt.require.importAs">Import As</div></div>'),
addItem: function(container,i,opt) {
var parent = container.parent();
var row0 = $("<div/>").addClass("node-libs-entry").appendTo(container);
var fmoduleSpan = $("<span>").appendTo(row0);
var fmodule = $("<input/>", {
class: "node-input-libs-val",
placeholder: RED._("node-red:function.require.module"),
type: "text"
}).css({
}).appendTo(fmoduleSpan).typedInput({
types: typedModules,
default: usedModules.indexOf(opt.module) > -1 ? opt.module : "_custom_"
});
if (usedModules.indexOf(opt.module) === -1) {
fmodule.typedInput('value', opt.module);
}
var moduleWarning = $('<span style="position: absolute;right:2px;top:7px; display:inline-block; width: 16px;"><i class="fa fa-warning"></i></span>').appendTo(fmoduleSpan);
RED.popover.tooltip(moduleWarning.find("i"),function() {
var val = fmodule.typedInput("type");
if (val === "_custom_") {
val = fmodule.val();
}
var errors = [];
if (!RED.utils.checkModuleAllowed(val,null,installAllowList,installDenyList)) {
return RED._("node-red:function.error.moduleNotAllowed",{module:val});
} else {
return RED._("node-red:function.error.moduleLoadError",{module:val,error:missingModuleReasons[val]});
}
})
var fvarSpan = $("<span>").appendTo(row0);
var fvar = $("<input/>", {
class: "node-input-libs-var red-ui-font-code",
placeholder: RED._("node-red:function.require.var"),
type: "text"
}).css({
}).appendTo(fvarSpan).val(opt.var);
var vnameWarning = $('<span style="position: absolute; right:2px;top:7px;display:inline-block; width: 16px;"><i class="fa fa-warning"></i></span>').appendTo(fvarSpan);
RED.popover.tooltip(vnameWarning.find("i"),function() {
var val = fvar.val();
if (invalidModuleVNames.indexOf(val) !== -1) {
return RED._("node-red:function.error.moduleNameReserved",{name:val})
} else {
return RED._("node-red:function.error.moduleNameError",{name:val})
}
})
fvar.on("change keyup paste", function (e) {
var v = $(this).val().trim();
if (v === "" || / /.test(v) || invalidModuleVNames.indexOf(v) !== -1) {
fvar.addClass("input-error");
vnameWarning.addClass("input-error");
} else {
fvar.removeClass("input-error");
vnameWarning.removeClass("input-error");
}
});
fmodule.on("change keyup paste", function (e) {
var val = $(this).typedInput("type");
if (val === "_custom_") {
val = $(this).val();
}
var varName = val.trim().replace(/^@/,"").replace(/@.*$/,"").replace(/[-_/\.].?/g, function(v) { return v[1]?v[1].toUpperCase():"" });
fvar.val(varName);
fvar.trigger("change");
if (RED.utils.checkModuleAllowed(val,null,installAllowList,installDenyList) && (missingModules.indexOf(val) === -1)) {
fmodule.removeClass("input-error");
moduleWarning.removeClass("input-error");
} else {
fmodule.addClass("input-error");
moduleWarning.addClass("input-error");
}
});
if (RED.utils.checkModuleAllowed(opt.module,null,installAllowList,installDenyList) && (missingModules.indexOf(opt.module) === -1)) {
fmodule.removeClass("input-error");
moduleWarning.removeClass("input-error");
} else {
fmodule.addClass("input-error");
moduleWarning.addClass("input-error");
}
if (opt.var) {
fvar.trigger("change");
}
},
removable: true
});
var libs = node.libs || [];
for (var i=0,l=libs.length;i<l; i++) {
libList.editableList('addItem',libs[i])
}
}
function getLibsList() {
var _libs = [];
if (RED.settings.functionExternalModules !== false) {
var libs = $("#node-input-libs-container").editableList("items");
libs.each(function(i) {
var item = $(this);
var v = item.find(".node-input-libs-var").val();
var n = item.find(".node-input-libs-val").typedInput("type");
if (n === "_custom_") {
n = item.find(".node-input-libs-val").val();
}
if ((!v || (v === "")) ||
(!n || (n === ""))) {
return;
}
_libs.push({
var: v,
module: n
});
});
}
return _libs;
}
RED.nodes.registerType('function-gpt',{
color:"#fdd0a2",
category: 'function',
defaults: {
name: {value:"_DEFAULT_"},
config: {value: "", type: "chatgpt-config"},
func: {value:"\nreturn msg;"},
outputs: {value:1},
noerr: {value:0,required:true,
validate: function(v, opt) {
if (!v) {
return true;
}
return RED._("node-red:function.error.invalid-js");
}},
initialize: {value:""},
finalize: {value:""},
libs: {value: [], validate: function(v, opt) {
if (!v) { return true; }
for (var i=0,l=v.length;i<l;i++) {
var m = v[i];
if (!RED.utils.checkModuleAllowed(m.module,null,installAllowList,installDenyList)) {
return RED._("node-red:function.error.moduleNotAllowed", { module: m.module });
// return `Module ${m.module} not allowed`
}
if (m.var === "" || / /.test(m.var)) {
return RED._("node-red:function.error.moduleNameError", { name: m.var });
// return `Invalid module variable name: ${m.var}`;
}
if (missingModules.indexOf(m.module) > -1) {
return RED._("node-red:function.error.missing-module", { module: m.module });
// return `Module ${m.module} missing`
}
if (invalidModuleVNames.indexOf(m.var) !== -1){
return RED._("node-red:function.error.moduleNameError", { name: m.var });
// return `Invalid module variable name: ${m.var}`
}
}
return true;
}}
},
inputs:1,
outputs:1,
icon: "chatgpt.svg",
label: function() {
return this.name || "function-gpt";
},
labelStyle: function() {
return this.name?"node_label_italic":"";
},
oneditprepare: function() {
var node = this;
//restore last prompt from local storage
function restorePrompt() {
const ed = getCurrentEditor()
if (ed && ed.__stateId) {
const key = ed.__stateId + "-gpt-prompt"
const prompt = localStorage.getItem(key) || ""
$("#chatgpt-input").val(prompt)
}
}
function storePrompt() {
const ed = getCurrentEditor()
if (ed && ed.__stateId) {
const key = ed.__stateId + "-gpt-prompt"
const prompt = $("#chatgpt-input").val() || ""
localStorage.setItem(key, prompt)
}
}
function getCurrentEditor() {
const editorTabId = $('.func-tabs-row .red-ui-tabs .red-ui-tab.active')[0].id
switch (editorTabId) {
case "red-ui-tab-func-tab-init":
return node.initEditor
case "red-ui-tab-func-tab-body":
return node.editor
case "red-ui-tab-func-tab-finalize":
return node.finalizeEditor
}
}
var tabs = RED.tabs.create({
id: "func-tabs",
onchange: function(tab) {
$("#func-tabs-content").children().hide();
$("#" + tab.id).show();
if (tab.id === "func-tab-config") {
$("#func-tab-chatgpt").hide()
} else {
$("#func-tab-chatgpt").show()
}
let editor = $("#" + tab.id).find('.monaco-editor').first();
if(editor.length) {
if(node.editor.nodered && node.editor.type == "monaco") {
node.editor.nodered.refreshModuleLibs(getLibsList());
}
RED.tray.resize();
//auto focus editor on tab switch
if (node.initEditor.getDomNode() == editor[0]) {
node.initEditor.focus();
} else if (node.editor.getDomNode() == editor[0]) {
node.editor.focus();
} else if (node.finalizeEditor.getDomNode() == editor[0]) {
node.finalizeEditor.focus();
}
restorePrompt()
}
}
});
tabs.addTab({
id: "func-tab-config",
iconClass: "fa fa-cog",
label: node._("node-red:function.label.setup")
});
tabs.addTab({
id: "func-tab-init",
label: node._("node-red:function.label.initialize")
});
tabs.addTab({
id: "func-tab-body",
label: node._("node-red:function.label.function")
});
tabs.addTab({
id: "func-tab-finalize",
label: node._("node-red:function.label.finalize")
});
tabs.activateTab("func-tab-body");
$( "#node-input-outputs" ).spinner({
min: 0,
max: 500,
change: function(event, ui) {
var value = parseInt(this.value);
value = isNaN(value) ? 1 : value;
value = Math.max(value, parseInt($(this).attr("aria-valuemin")));
value = Math.min(value, parseInt($(this).attr("aria-valuemax")));
if (value !== this.value) { $(this).spinner("value", value); }
}
});
var buildEditor = function(id, stateId, focus, value, defaultValue, extraLibs, offset) {
var editor = RED.editor.createEditor({
id: id,
mode: 'ace/mode/nrjavascript',
value: value || defaultValue || "",
stateId: stateId,
focus: true,
globals: {
msg:true,
context:true,
RED: true,
util: true,
flow: true,
global: true,
console: true,
Buffer: true,
setTimeout: true,
clearTimeout: true,
setInterval: true,
clearInterval: true
},
extraLibs: extraLibs
});
if (defaultValue && value === "") {
editor.moveCursorTo(defaultValue.split("\n").length +offset, 0);
}
editor.__stateId = stateId;
return editor;
}
this.initEditor = buildEditor('node-input-init-editor', this.id + "/" + "initEditor", false, $("#node-input-initialize").val(), RED._("node-red:function.text.initialize"), undefined, 0);
this.editor = buildEditor('node-input-func-editor', this.id + "/" + "editor", true, $("#node-input-func").val(), undefined, node.libs || [], undefined, -1);
this.finalizeEditor = buildEditor('node-input-finalize-editor', this.id + "/" + "finalizeEditor", false, $("#node-input-finalize").val(), RED._("node-red:function.text.finalize"), undefined, 0);
RED.library.create({
url:"functions", // where to get the data from
type:"function", // the type of object the library is for
editor:this.editor, // the field name the main text body goes to
mode:"ace/mode/nrjavascript",
fields:[
'name', 'outputs',
{
name: 'initialize',
get: function() {
return node.initEditor.getValue();
},
set: function(v) {
node.initEditor.setValue(v||"// Code added here will be run once\n// whenever the node is started.\n", -1);
}
},
{
name: 'finalize',
get: function() {
return node.finalizeEditor.getValue();
},
set: function(v) {
node.finalizeEditor.setValue(v||"// Code added here will be run when the\n// node is being stopped or re-deployed.\n", -1);
}
},
{
name: 'info',
get: function() {
return node.infoEditor.getValue();
},
set: function(v) {
node.infoEditor.setValue(v||"", -1);
}
}
],
ext:"js"
});
var expandButtonClickHandler = function(editor) {
return function (e) {
e.preventDefault();
var value = editor.getValue();
editor.saveView(`inside function-expandButtonClickHandler ${editor.__stateId}`);
var extraLibs = node.libs || [];
RED.editor.editJavaScript({
value: value,
width: "Infinity",
stateId: editor.__stateId,
mode: "ace/mode/nrjavascript",
focus: true,
cancel: function () {
setTimeout(function () {
editor.focus();
}, 250);
},
complete: function (v, cursor) {
editor.setValue(v, -1);
setTimeout(function () {
editor.restoreView();
editor.focus();
}, 250);
},
extraLibs: extraLibs
});
}
}
$("#node-init-expand-js").on("click", expandButtonClickHandler(this.initEditor));
$("#node-function-expand-js").on("click", expandButtonClickHandler(this.editor));
$("#node-finalize-expand-js").on("click", expandButtonClickHandler(this.finalizeEditor));
RED.popover.tooltip($("#node-init-expand-js"), RED._("node-red:common.label.expand"));
RED.popover.tooltip($("#node-function-expand-js"), RED._("node-red:common.label.expand"));
RED.popover.tooltip($("#node-finalize-expand-js"), RED._("node-red:common.label.expand"));
/* Ask ChatGPT Logic */
let currentXhr = null
function updateUIStateGPT(state, editor) {
editor = editor || getCurrentEditor()
if (state === "ready") {
$("#chatgpt-ask").prop("disabled", false)
}
if (state === "loading") {
$("#chatgpt-ask").hide()
$("#chatgpt-loading").show()
$("#chatgpt-cancel").show()
$("#chatgpt-input").prop("disabled", true)
if (editor) {
editor.setReadOnly(true)
}
} else {
$("#chatgpt-ask").show()
$("#chatgpt-loading").hide()
$("#chatgpt-cancel").hide()
$("#chatgpt-input").prop("disabled", false)
if (editor) {
editor.setReadOnly(false)
}
}
}
/**
* Asks the ChatGPT API for a response to a prompt.
*
* @param {Object} editor The editor instance to use.
* @param {string} prompt The prompt to send to the ChatGPT API.
* @param {Object} codeLensRange The range of the code lens that was clicked.
* @param {boolean} replaceAll If true, all code in the editor will be replaced. If false, the 1st selection in the editor will be replaced - OR - if there is no selection, the code will be placed below the code lens.
* @param {boolean} returnMsg If false, ChatGPT API will be be asked to exclude `return msg` from the response.
*/
function askGPT (editor, prompt, codeLensRange, replaceAll, returnMsg) {
returnMsg = (returnMsg === 'false' || returnMsg === false) ? false : true
if (editor && prompt) {
updateUIStateGPT("loading", editor)
const clientSideConfigNode = RED.nodes.node(node.config)
let config = null
if (clientSideConfigNode && clientSideConfigNode.dirty) {
config = {
credentials: clientSideConfigNode.credentials,
model: clientSideConfigNode.model,
}
}
currentXhr = $.ajax({
url: "function-gpt-ask/" + node.id,
type: "POST",
data: {
prompt,
config,
returnMsg
},
// eslint-disable-next-line no-unused-vars
success: function (response) {
editor.setReadOnly(false) // permit edits again
if (!currentXhr) {
// probably cancelled already, just return
return
}
RED.notify("Success.", { type: "success" });
let content = response.choices[0].message.content
// remove any non code
if (hasCodeFence(content)) {
content = extractCodeBlocks(content, ['javascript', 'js', '']) // empty string is for no language specified in the code fence
}
const requires = extractRequires(content)
if (requires) {
content = '\n// IMPORTANT: require is not supported\n// Delete all calls to require and use the\n// function node "setup" tab to import modules\n\n' + content
}
// remove "return msg" if in the last line
if (returnMsg === false) {
content = removeReturnMsg(content)
}
const header = `//$PROMPT: ${prompt}\n`
const selectionIsEmpty = (selection) => {
return selection.isEmpty ? selection.isEmpty() : selection.start.row === selection.end.row && selection.start.col === selection.end.col
}
if (replaceAll) {
// Select all text
const fullRange = editor.getModel().getFullModelRange();
// Apply the text over the range
const suggestion = {
text: header + '\n' + content + '\n',
range: fullRange
}
editor.executeEdits('suggestion', [suggestion]);
// // Indicates the above edit is a complete undo/redo change.
// editor.pushUndoStop();
} else if (codeLensRange) {
// since this is a code lens action, the header(prompt) is already present in the editor
// therefore we assume the user wants to replace the selection (user is working in the editor)
const selection = editor.selection.getRange() // selection contains ACE position and MONACO range
// see if the selection is empty
if (selectionIsEmpty(selection)) {
const acePos = { row: codeLensRange.endLineNumber, col: 0 } // next line after the code lens
if (acePos.row < 0 || isNaN(acePos.row)) { acePos.row = 1 } // assume line 2
if (acePos.col < 0 || isNaN(acePos.col)) { acePos.col = 0 }
// dont need to add the header(prompt) since this was a code lens action and the header is already there
editor.session.insert(acePos, content + '\n') // replace uses executeEdits under the hood so undo/redo is supported
return
} else {
if (selection.containsPosition(codeLensRange)) {
selection.collapseToEnd() // collapse to end of selection
}
// dont need to add the header(prompt) since this was a code lens action and the header is already there
editor.session.replace(selection, content + '\n') // replace uses executeEdits under the hood so undo/redo is supported
}
} else {
// as there is no instruction to replace the selection and it isnt a code lens action,
// we look at the current selection and if it is empty, we insert the header and content at the current cursor position
// otherwise we replace the selection with the header and content
const selection = editor.selection.getRange() // selection contains ACE position and MONACO range
// see if the selection is empty
if (selectionIsEmpty(selection)) {
// if so, insert the header and content at the current cursor position
const acePos = { row: selection.startLineNumber - 1, col: selection.startColumn - 1 }
if (acePos.row < 0 || isNaN(acePos.row)) { acePos.row = 0 }
if (acePos.col < 0 || isNaN(acePos.col)) { acePos.col = 0 }
editor.session.insert(acePos, header + '\n' + content + '\n') // insert uses executeEdits under the hood so undo/redo is supported
} else {
// get the value of the current selection & check to see if it contains the header already
const selectionText = editor.getSelectedText() || ''
const indexOfHeader = selectionText.indexOf(header)
// if found, set the insert range to the start of the next line after the header
// to avoid overwriting the header line
if (indexOfHeader > -1) {
selection.start.row = selection.start.row + (indexOfHeader + 1) // ACE position
selection.startLineNumber = selection.start.row + 1 // MONACO range
selection.startColumn = 1 // MONACO range
selection.start.col = 0 // ACE position
editor.session.replace(selection, content + '\n') // dont need to add the header(prompt) since it is already there
} else {
// otherwise, just replace the selection with the header and content
editor.session.replace(selection, header + '\n' + content + '\n')
}
}
}
},
// eslint-disable-next-line no-unused-vars
error: function (jqXHR, textStatus, errorThrown) {
if (!currentXhr) {
// probably cancelled already, just return
return
}
if (jqXHR.status == 404) {
RED.notify("Please deploy the nodes before using ChatGPT", "error");
} else if (jqXHR.status == 500) {
if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
RED.notify(jqXHR.responseJSON.message, {type: "error", timeout: 7500});
} else {
RED.notify("Please ensure you have configured ChatGPT for this function-gpt node, and re-deployed.", "error");
}
} else if (jqXHR.status == 0) {
RED.notify(node._("node-red:common.notification.error", { message: node._("node-red:common.notification.errors.no-response") }), "error");
} else {
RED.notify(node._("node-red:common.notification.error", { message: node._("node-red:common.notification.errors.unexpected", { status: jqXHR.status, message: textStatus }) }), "error");
}
},
complete: function () {
currentXhr = null
updateUIStateGPT("complete", editor)
}
});
}
}
$("#chatgpt-input").on("focusout", () => {
storePrompt()
})
$("#chatgpt-cancel").on("click", () => {
if (currentXhr) {
currentXhr.onreadystatechange = null
currentXhr.abort()
currentXhr = null
}
updateUIStateGPT("cancel")
})
function askChatGPT () {
const prompt = ($("#chatgpt-input").val() + "").trim()
const editor = getCurrentEditor()
askGPT(editor, prompt, null, true, true) // replaceAll = true, return the msg = true
}
// allow enter on the text input
$("#chatgpt-input").on("keydown", (evt) => {
const key = evt.key
if (key === 'Enter') {
askChatGPT()
}
})
// control the click functionality of the "Ask" button
$("#chatgpt-ask").on("click", () => {
if (currentXhr) {
// should never happen, but just in case
updateUIStateGPT("loading")
return
}
askChatGPT()
})
if (RED.settings.functionExternalModules !== false) {
prepareLibraryConfig(node);
}
/**
* Create the code lens provider and command for the javascript modal
*/
function setupCodeLens() {
node.codeLensCommand = monaco.editor.registerCommand( 'execute-prompt', (...args) => {
askGPT(getCurrentEditor(), args[1], args[2], args[3], args[4]) // args[1] = prompt, args[2] = codeLensRange, args[3] = replaceAll, args[4] = return the msg
}
)
node.codeLensProvider = monaco.languages.registerCodeLensProvider("javascript", {
provideCodeLenses: function (model, token) {
const lenses = []
// get the text in the editor and check each line for //$PROMPT: _prompt_
const lines = model.getLinesContent()
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
if (/\/\/\$PROMPT: .+/.test(line)) {
const range = {
startLineNumber: i + 1,
startColumn: 1,
endLineNumber: i + 1,
endColumn: line.length + 1,
}
const prompt = line.replace(/\/\/\$PROMPT: /, '')
const command = {
id: 'execute-prompt',
title: "Ask ChatGPT",
arguments: [prompt, range, false, false] // false = dont replace all, false = dont return the msg
}
lenses.push({
range,
command,
})
}
}
return {
lenses,
dispose: () => {},
}
},
resolveCodeLens: function (model, codeLens, token) {
return codeLens;
},
});
}
// allow time for monaco editors to load and for panel to be visible
setTimeout(() => {
setupCodeLens()
restorePrompt()
updateUIStateGPT("ready")
}, 500)
},
oneditsave: function() {
var node = this;
var noerr = 0;
$("#node-input-noerr").val(0);
var disposeEditor = function(editorName,targetName,defaultValue) {
var editor = node[editorName];
var annot = editor.getSession().getAnnotations();
for (var k=0; k < annot.length; k++) {
if (annot[k].type === "error") {
noerr += annot.length;
break;
}
}
var val = editor.getValue();
if (defaultValue) {
if (val.trim() == defaultValue.trim()) {
val = "";
}
}
editor.destroy();
delete node[editorName];
$("#"+targetName).val(val);
}
disposeEditor("editor","node-input-func");
disposeEditor("initEditor","node-input-initialize", "// Code added here will be run once\n// whenever the node is started.\n");
disposeEditor("finalizeEditor","node-input-finalize", "// Code added here will be run when the\n// node is being stopped or re-deployed.\n");
if (node.codeLensCommand) {
node.codeLensCommand.dispose();
delete node.codeLensCommand;
}
if (node.codeLensProvider) {
node.codeLensProvider.dispose();
delete node.codeLensProvider;
}
$("#node-input-noerr").val(noerr);
this.noerr = noerr;
node.libs = getLibsList();
},
oneditcancel: function() {
var node = this;
if (node.codeLensCommand) {
node.codeLensCommand.dispose();
delete node.codeLensCommand;
}
if (node.codeLensProvider) {
node.codeLensProvider.dispose();
delete node.codeLensProvider;
}
node.editor.destroy();
delete node.editor;
node.initEditor.destroy();
delete node.initEditor;
node.finalizeEditor.destroy();
delete node.finalizeEditor;
},
oneditresize: function(size) {
const rowheight = 180
var rows = $("#dialog-form>div:not(.node-text-editor-row)");
var height = $("#dialog-form").height();
for (var i=0; i<rows.length; i++) {
height -= $(rows[i]).outerHeight(true);
}
var editorRow = $("#dialog-form>div.node-text-editor-row");
height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom")));
$("#dialog-form .node-text-editor").css("height",height+"px");
var height = size.height;
$("#node-input-init-editor").css("height", (height - rowheight)+"px");
$("#node-input-func-editor").css("height", (height - rowheight)+"px");
$("#node-input-finalize-editor").css("height", (height - rowheight)+"px");
this.initEditor.resize();
this.editor.resize();
this.finalizeEditor.resize();
$("#node-input-libs-container").css("height", (height - 250)+"px");
},
onadd: function() {
if (this.name === '_DEFAULT_') {
this.name = ''
RED.actions.invoke("core:generate-node-names", this, {generateHistory: false})
}
}
});
// #region gpt response parsing
/**
* Determines if a Markdown string contains one or more code fences.
* @param {string} markdown The Markdown string to check.
* @returns {boolean} True if the Markdown string contains one or more code fences, otherwise false.
* @example ```javascript
* const markdown = '```javascript\nconst a = 1 \n ```'
* hasCodeFence(markdown)
* // => true
* ```
* @example
* hasCodeFence('Hello world!')
* // => false
*/
function hasCodeFence (markdown) {
const lines = markdown.split('\n')
return lines.filter(line => line.trim().startsWith('```')).length > 0
}
/**
* Determines if a require is contained in the code
* @param {string} code The code to check.
* @returns {string[]} a list of requires otherwise null
* @example ```javascript
* const code = '```javascript\nconst moment = require('moment') \n ```'
* extractRequires(code)
* // => ['moment']
* ```
* @example
* extractRequires('var x = 123!')
* // => false
*/
function extractRequires (code) {
const requires = []