-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathactions.js
More file actions
3554 lines (3095 loc) · 121 KB
/
Copy pathactions.js
File metadata and controls
3554 lines (3095 loc) · 121 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 { collectionSchema, environmentSchema, itemSchema } from '@usebruno/schema';
import { parseQueryParams, extractPromptVariables, getDataTypeFromValue } from '@usebruno/common/utils';
import { REQUEST_TYPES, DEFAULT_COLLECTION_FORMAT } from 'utils/common/constants';
import cloneDeep from 'lodash/cloneDeep';
import filter from 'lodash/filter';
import find from 'lodash/find';
import get from 'lodash/get';
import set from 'lodash/set';
import trim from 'lodash/trim';
import path, { normalizePath, isPathExternalToBasePath } from 'utils/common/path';
import { insertTaskIntoQueue, toggleSidebarCollapse } from 'providers/ReduxStore/slices/app';
import toast from 'react-hot-toast';
import IpcErrorModal from 'components/Errors/IpcErrorModal/index';
import SaveFileErrorModal from 'components/Errors/SaveFileErrorModal/index';
import {
findCollectionByUid,
findEnvironmentInCollection,
findItemInCollection,
findParentItemInCollection,
isItemAFolder,
refreshUidsInItem,
isItemARequest,
getAllVariables,
transformRequestToSaveToFilesystem,
transformCollectionRootToSave,
flattenItems
} from 'utils/collections';
import { uuid, waitForNextTick } from 'utils/common';
import { cancelNetworkRequest, connectWS, sendGrpcRequest, sendNetworkRequest, sendWsRequest } from 'utils/network/index';
import { callIpc } from 'utils/common/ipc';
import brunoClipboard from 'utils/bruno-clipboard';
import {
collectionAddEnvFileEvent as _collectionAddEnvFileEvent,
createCollection as _createCollection,
removeCollection as _removeCollection,
selectEnvironment as _selectEnvironment,
sortCollections as _sortCollections,
updateCollectionMountStatus,
moveCollection,
workspaceEnvUpdateEvent,
requestCancelled,
resetRunResults,
responseReceived,
updateLastAction,
setCollectionSecurityConfig,
collectionAddOauth2CredentialsByUrl,
collectionClearOauth2CredentialsByUrlAndCredentialsId,
initRunRequestEvent,
updateRunnerConfiguration as _updateRunnerConfiguration,
updateActiveConnections,
saveRequest as _saveRequest,
saveEnvironment as _saveEnvironment,
updateEnvironmentColor as _updateEnvironmentColor,
saveCollectionDraft,
saveFolderDraft,
addVar,
updateVar,
addFolderVar,
updateFolderVar,
addCollectionVar,
updateCollectionVar,
scriptUpdateCollectionVars,
setScriptCollVarBaseline,
_clearScriptCollectionBaselines,
addTransientDirectory,
addSaveTransientRequestModal,
updatePathParam,
toggleCollection
} from './index';
import { each } from 'lodash';
import { closeAllCollectionTabs, closeTabs as _closeTabs, focusTab, restoreTabs, reopenLastClosedTab } from 'providers/ReduxStore/slices/tabs';
import { clearOpenApiSyncTabState } from 'providers/ReduxStore/slices/openapi-sync';
import { removeCollectionFromWorkspace } from 'providers/ReduxStore/slices/workspaces';
import { resolveRequestFilename } from 'utils/common/platform';
import { interpolateUrl, parsePathParams, splitOnFirst } from 'utils/url/index';
import { sendCollectionOauth2Request as _sendCollectionOauth2Request } from 'utils/network/index';
import {
getGlobalEnvironmentVariables,
findCollectionByPathname,
getReorderedItemsInTargetDirectory,
resetSequencesInFolder,
getReorderedItemsInSourceDirectory,
calculateDraggedItemNewPathname,
transformFolderRootToSave,
getTreePathFromCollectionToItem,
mergeHeaders
} from 'utils/collections/index';
import { sanitizeName } from 'utils/common/regex';
import { applyScriptEnvVars, getScriptModifiedKeys } from 'utils/environments';
import { safeParseJSON, safeStringifyJSON } from 'utils/common/index';
import { resolveInheritedAuth } from 'utils/auth';
import { addTab } from 'providers/ReduxStore/slices/tabs';
import { updateSettingsSelectedTab } from './index';
import { saveGlobalEnvironment, _clearScriptGlobalEnvBaseline } from 'providers/ReduxStore/slices/global-environments';
import { getTabToFocusForCurrentWorkspace } from 'providers/ReduxStore/slices/workspaces/getTabToFocusForCurrentWorkspace';
import { clearPersistedScope } from 'hooks/usePersistedState/PersistedScopeProvider';
import {
getCollectionEnvironmentPath,
findCollectionEnvironmentFromSnapshot,
hydrateCollectionTabs,
hydrateSnapshotLookups
} from 'utils/snapshot';
// generate a unique names
const generateUniqueName = (originalName, existingItems, isFolder) => {
// Extract base name by removing any existing " (number)" suffix
const baseName = originalName.replace(/\s*\(\d+\)$/, '');
const baseFilename = sanitizeName(baseName);
// Get normalized filenames for items of the same type
const existingFilenames = existingItems
.filter((item) => isFolder ? item.type === 'folder' : item.type !== 'folder')
.map((item) => {
let filename = trim(item.filename);
// For requests, remove file extension (.bru, .yml, .yaml)
return isFolder ? filename : filename.replace(/\.(bru|yml|yaml)$/, '');
});
// Check if base name conflicts with existing items
if (!existingFilenames.includes(baseFilename)) {
return { newName: baseName, newFilename: baseFilename };
}
// Find highest counter among conflicting names
const counters = existingFilenames
.filter((filename) => filename === baseFilename || filename.startsWith(`${baseFilename} (`))
.map((filename) => {
if (filename === baseFilename) return 0;
const match = filename.match(/\((\d+)\)$/);
return match ? parseInt(match[1], 10) : 0;
});
const nextCounter = Math.max(0, ...counters) + 1;
return {
newName: `${baseName} (${nextCounter})`,
newFilename: `${baseFilename} (${nextCounter})`
};
};
export const renameCollection = (newName, collectionUid) => (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
const { ipcRenderer } = window;
ipcRenderer.invoke('renderer:rename-collection', newName, collection.pathname).then(resolve).catch(reject);
});
};
export const saveRequest = (itemUid, collectionUid, silent = false) => (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
const tempDirectory = state.collections.tempDirectories?.[collectionUid];
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
const collectionCopy = cloneDeep(collection);
const item = findItemInCollection(collectionCopy, itemUid);
if (!item) {
return reject(new Error('Not able to locate item'));
}
const isTransient = tempDirectory && item.pathname.startsWith(tempDirectory);
if (isTransient) {
dispatch(addSaveTransientRequestModal({ item, collection }));
return reject();
}
const itemToSave = transformRequestToSaveToFilesystem(item);
const { ipcRenderer } = window;
itemSchema
.validate(itemToSave)
.then(() => ipcRenderer.invoke('renderer:save-request', item.pathname, itemToSave, collection.format))
.then(() => {
if (!silent) {
toast.success('Request saved successfully');
}
dispatch(
_saveRequest({
itemUid,
collectionUid
})
);
})
.then(resolve)
.catch((err) => {
toast.error(err.message || 'Failed to save request!');
reject(err);
});
});
};
export const saveFile = (content, itemUid, collectionUid, silent = false) => async (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
const tempDirectory = state.collections.tempDirectories?.[collectionUid];
if (!collection) {
throw new Error('Collection not found');
}
const collectionCopy = cloneDeep(collection);
const item = findItemInCollection(collectionCopy, itemUid);
// Item is not used to save the bru file
// This is to validate if the bru content is associated with a valid item
if (!item) {
throw new Error('Not able to locate item');
}
const isTransient = tempDirectory && item.pathname.startsWith(tempDirectory);
if (isTransient) {
if (!silent) {
dispatch(addSaveTransientRequestModal({ item, collection }));
}
throw new Error('Cannot save transient request');
}
const { ipcRenderer } = window;
try {
if (['http-request', 'graphql-request'].includes(item?.type)) {
let json = await ipcRenderer.invoke('renderer:convert-to-json', item, content, collection.format);
delete json.isTransient;
await itemSchema.validate(json);
}
} catch (err) {
if (!silent) {
toast.custom(<SaveFileErrorModal error={err.message} />);
}
throw err;
}
try {
await ipcRenderer.invoke('renderer:save-file', item.pathname, content);
if (!silent) {
toast.success('File saved successfully!');
}
} catch (err) {
if (!silent) {
toast.error('Failed to save file!');
}
throw err;
}
};
export const saveMultipleRequests = (items) => (dispatch, getState) => {
const state = getState();
const { collections } = state.collections;
return new Promise((resolve, reject) => {
const itemsToSave = [];
each(items, (item) => {
const collection = findCollectionByUid(collections, item.collectionUid);
if (collection) {
const itemToSave = transformRequestToSaveToFilesystem(item);
const itemIsValid = itemSchema.validateSync(itemToSave);
if (itemIsValid) {
itemsToSave.push({
item: itemToSave,
pathname: item.pathname,
format: collection.format
});
}
}
});
const { ipcRenderer } = window;
ipcRenderer
.invoke('renderer:save-multiple-requests', itemsToSave)
.then(resolve)
.catch((err) => {
toast.error('Failed to save requests!');
reject(err);
});
});
};
export const saveCollectionRoot = (collectionUid) => (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
const collectionCopy = cloneDeep(collection);
// Transform collection root (uses draft if exists)
const collectionRootToSave = transformCollectionRootToSave(collectionCopy);
const { ipcRenderer } = window;
ipcRenderer
.invoke('renderer:save-collection-root', collectionCopy.pathname, collectionRootToSave, collectionCopy.brunoConfig)
.then(() => {
toast.success('Collection Settings saved successfully');
dispatch(saveCollectionDraft({ collectionUid }));
})
.then(resolve)
.catch((err) => {
toast.error('Failed to save collection settings!');
reject(err);
});
});
};
export const saveFolderRoot = (collectionUid, folderUid, silent = false) => (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
const folder = findItemInCollection(collection, folderUid);
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
if (!folder) {
return reject(new Error('Folder not found'));
}
const { ipcRenderer } = window;
// Use draft if it exists, otherwise use root
const folderRootToSave = transformFolderRootToSave(folder);
const folderData = {
name: folder.name,
folderPathname: folder.pathname,
collectionPathname: collection.pathname,
root: folderRootToSave
};
ipcRenderer
.invoke('renderer:save-folder-root', folderData)
.then(() => {
if (!silent) {
toast.success('Folder Settings saved successfully');
}
// If there was a draft, save it to root and clear the draft
if (folder.draft) {
dispatch(saveFolderDraft({ collectionUid, folderUid }));
}
})
.then(resolve)
.catch((err) => {
toast.error('Failed to save folder settings!');
reject(err);
});
});
};
export const saveMultipleCollections = (collectionDrafts) => (dispatch, getState) => {
const state = getState();
const { collections } = state.collections;
return new Promise((resolve, reject) => {
const savePromises = [];
each(collectionDrafts, (collectionDraft) => {
const collection = findCollectionByUid(collections, collectionDraft.collectionUid);
if (collection) {
const collectionCopy = cloneDeep(collection);
const collectionRootToSave = transformCollectionRootToSave(collectionCopy);
const { ipcRenderer } = window;
let savePromises = [];
savePromises.push(ipcRenderer.invoke('renderer:save-collection-root', collectionCopy.pathname, collectionRootToSave, collectionCopy.brunoConfig));
if (collectionCopy.draft?.brunoConfig) {
savePromises.push(ipcRenderer.invoke('renderer:update-bruno-config', collectionCopy.draft.brunoConfig, collectionCopy.pathname, collectionCopy.root));
}
Promise.all(savePromises)
.then(() => {
dispatch(saveCollectionDraft({ collectionUid: collectionDraft.collectionUid }));
})
.catch((err) => {
toast.error('Failed to save collection settings!');
reject(err);
});
}
});
Promise.all(savePromises)
.then(resolve)
.catch((err) => {
toast.error('Failed to save collection settings!');
reject(err);
});
});
};
export const saveMultipleFolders = (folderDrafts) => (dispatch, getState) => {
const state = getState();
const { collections } = state.collections;
return new Promise((resolve, reject) => {
const savePromises = [];
each(folderDrafts, (folderDraft) => {
const collection = findCollectionByUid(collections, folderDraft.collectionUid);
const folder = collection ? findItemInCollection(collection, folderDraft.folderUid) : null;
if (collection && folder) {
const folderRootToSave = transformFolderRootToSave(folder);
const folderData = {
name: folder.name,
folderPathname: folder.pathname,
collectionPathname: collection.pathname,
root: folderRootToSave
};
const { ipcRenderer } = window;
const savePromise = ipcRenderer
.invoke('renderer:save-folder-root', folderData)
.then(() => {
if (folder.draft) {
dispatch(saveFolderDraft({ collectionUid: folderDraft.collectionUid, folderUid: folderDraft.folderUid }));
}
});
savePromises.push(savePromise);
}
});
Promise.all(savePromises)
.then(resolve)
.catch((err) => {
toast.error('Failed to save folder settings!');
reject(err);
});
});
};
export const sendCollectionOauth2Request = (collectionUid, itemUid) => (dispatch, getState) => {
const state = getState();
const { globalEnvironments, activeGlobalEnvironmentUid } = state.globalEnvironments;
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
let collectionCopy = cloneDeep(collection);
// add selected global env variables to the collection object
const globalEnvironmentVariables = getGlobalEnvironmentVariables({
globalEnvironments,
activeGlobalEnvironmentUid
});
collectionCopy.globalEnvironmentVariables = globalEnvironmentVariables;
const environment = findEnvironmentInCollection(collectionCopy, collection.activeEnvironmentUid);
_sendCollectionOauth2Request(collectionCopy, environment, collectionCopy.runtimeVariables)
.then((response) => {
if (response?.data?.error) {
toast.error(response?.data?.error);
} else {
toast.success('Request made successfully');
}
return response;
})
.then(resolve)
.catch((err) => {
toast.error(err.message);
});
});
};
export const wsConnectOnly = (item, collectionUid) => (dispatch, getState) => {
const state = getState();
const { globalEnvironments, activeGlobalEnvironmentUid } = state.globalEnvironments;
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise(async (resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
let collectionCopy = cloneDeep(collection);
const itemCopy = cloneDeep(item);
const requestUid = uuid();
itemCopy.requestUid = requestUid;
const globalEnvironmentVariables = getGlobalEnvironmentVariables({
globalEnvironments,
activeGlobalEnvironmentUid
});
collectionCopy.globalEnvironmentVariables = globalEnvironmentVariables;
const environment = findEnvironmentInCollection(collectionCopy, collectionCopy.activeEnvironmentUid);
// WS connect does not run user scripts — no baseline to clear.
connectWS(itemCopy, collectionCopy, environment, collectionCopy.runtimeVariables, { connectOnly: true })
.then(resolve)
.catch((err) => {
toast.error(err.message);
});
});
};
/**
* Extract prompt variables from a request, collection, and environment variables.
* Tries to respect the hierarchy of the variables and avoid unnecessary prompts as much as possible
*
* @param {*} item
* @param {*} collection
* @returns {Promise<Object>} A promise that resolves with the prompt variables or null if no prompt variables are found
*/
const extractPromptVariablesForRequest = async (item, collection) => {
return new Promise(async (resolve, reject) => {
// Ensure window contains promptForVariables function
if (typeof window === 'undefined' || typeof window.promptForVariables !== 'function') {
console.error('Failed to initialize prompt variables: window.promptForVariables is not available. '
+ 'This may indicate an initialization issue with the app environment.');
return resolve(null);
}
const prompts = [];
const request = item.draft?.request ?? item.request ?? {};
const allVariables = getAllVariables(collection, item);
const clientCertConfig = get(collection, 'brunoConfig.clientCertificates.certs', []);
const requestTreePath = getTreePathFromCollectionToItem(collection, item);
// Get active headers from collection, folders, and request by priority order
const headers = mergeHeaders(collection, request, requestTreePath);
// Get request auth or inherited auth
const resolvedAuthRequest = resolveInheritedAuth(item, collection);
for (let clientCert of clientCertConfig) {
const domain = interpolateUrl({ url: clientCert?.domain, variables: allVariables });
if (domain) {
const hostRegex = '^(https:\\/\\/|grpc:\\/\\/|grpcs:\\/\\/)?' + domain.replaceAll('.', '\\.').replaceAll('*', '.*');
const requestUrl = interpolateUrl({ url: request.url, variables: allVariables });
if (requestUrl.match(hostRegex)) {
prompts.push(...extractPromptVariables(clientCert));
}
}
}
// Attempt to extract unique prompt variables from anywhere in the request and environment variables.
prompts.push(...extractPromptVariables(allVariables));
prompts.push(...extractPromptVariables(request.body?.[request.body.mode]));
prompts.push(...extractPromptVariables(headers));
prompts.push(...extractPromptVariables(request.params));
prompts.push(...extractPromptVariables(resolvedAuthRequest.auth));
prompts.push(...extractPromptVariables(request.url));
// Remove duplicates
const uniquePrompts = Array.from(new Set(prompts));
// If no prompt variables are found, return null
if (!uniquePrompts?.length) {
return resolve(null);
}
try {
// Prompt user for values if any prompt variables are found
const userValues = await window.promptForVariables(uniquePrompts);
const promptVariables = {};
// Populate runtimeVariables with user input for prompt variables
for (const prompt of uniquePrompts) {
promptVariables[`?${prompt}`] = userValues[prompt] ?? '';
}
return resolve(promptVariables);
} catch (error) {
return reject(error);
}
});
};
export const sendRequest = (item, collectionUid) => (dispatch, getState) => {
const state = getState();
const { globalEnvironments, activeGlobalEnvironmentUid } = state.globalEnvironments;
const collection = findCollectionByUid(state.collections.collections, collectionUid);
const itemUid = item?.uid;
return new Promise(async (resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
if (item.response?.stream?.running && item.cancelTokenUid) {
await dispatch(cancelRequest(item.cancelTokenUid, item, collection));
}
let collectionCopy = cloneDeep(collection);
const itemCopy = cloneDeep(item);
// add selected global env variables to the collection object
const globalEnvironmentVariables = getGlobalEnvironmentVariables({
globalEnvironments,
activeGlobalEnvironmentUid
});
collectionCopy.globalEnvironmentVariables = globalEnvironmentVariables;
const requestUid = uuid();
itemCopy.requestUid = requestUid;
try {
const promptVariables = await extractPromptVariablesForRequest(itemCopy, collectionCopy);
collectionCopy.promptVariables = promptVariables ?? {};
} catch (error) {
if (error === 'cancelled') {
return resolve(); // Resolve without error if user cancels prompt
}
return reject(error);
}
dispatch(clearScriptVariableBaselines(collectionUid));
await dispatch(
initRunRequestEvent({
requestUid,
itemUid,
collectionUid
})
);
const environment = findEnvironmentInCollection(collectionCopy, collectionCopy.activeEnvironmentUid);
const isGrpcRequest = itemCopy.type === 'grpc-request';
const isWsRequest = itemCopy.type === 'ws-request';
if (isGrpcRequest) {
sendGrpcRequest(itemCopy, collectionCopy, environment, collectionCopy.runtimeVariables)
.then(resolve)
.catch((err) => {
toast.error(err.message);
});
} else if (isWsRequest) {
const wsMessages = itemCopy.draft?.request?.body?.ws || itemCopy.request?.body?.ws || [];
const wsSelectedMessageIndex = Math.max(0, wsMessages.findIndex((msg) => msg.selected));
sendWsRequest(itemCopy, collectionCopy, environment, collectionCopy.runtimeVariables, wsSelectedMessageIndex)
.then(resolve)
.catch((err) => {
toast.error(err.message);
});
} else {
sendNetworkRequest(itemCopy, collectionCopy, environment, collectionCopy.runtimeVariables)
.then((response) => {
const { requestSent, ...responseData } = response;
// Ensure any timestamps in the response are converted to numbers
const serializedResponse = {
...responseData,
timeline: responseData.timeline?.map((entry) => ({
...entry,
timestamp: entry.timestamp instanceof Date ? entry.timestamp.getTime() : entry.timestamp
}))
};
return dispatch(
responseReceived({
itemUid,
collectionUid,
response: serializedResponse,
requestSent
})
);
})
.then(resolve)
.catch((err) => {
const request = itemCopy.draft?.request || itemCopy.request;
const requestSent = request ? { url: request.url, method: request.method } : undefined;
if (err && err.message === 'Error invoking remote method \'send-http-request\': Error: Request cancelled') {
dispatch(
responseReceived({
itemUid,
collectionUid,
response: null,
requestSent
})
);
return;
}
const errorResponse = {
status: 'Error',
isError: true,
error: err.message ?? 'Something went wrong',
size: 0,
duration: 0
};
dispatch(
responseReceived({
itemUid,
collectionUid,
response: errorResponse,
requestSent
})
);
});
}
});
};
export const cancelRequest = (cancelTokenUid, item, collection) => (dispatch) => {
return cancelNetworkRequest(cancelTokenUid)
.then(() => {
dispatch(
requestCancelled({
itemUid: item.uid,
collectionUid: collection.uid
})
);
})
.catch((err) => console.log(err));
};
export const cancelRunnerExecution = (cancelTokenUid) => (dispatch) => {
cancelNetworkRequest(cancelTokenUid).catch((err) => console.log(err));
};
export const runCollectionFolder
= (collectionUid, folderUid, recursive, delay, tags, selectedRequestUids) => (dispatch, getState) => {
const state = getState();
const { globalEnvironments, activeGlobalEnvironmentUid } = state.globalEnvironments;
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
let collectionCopy = cloneDeep(collection);
// add selected global env variables to the collection object
const globalEnvironmentVariables = getGlobalEnvironmentVariables({
globalEnvironments,
activeGlobalEnvironmentUid
});
collectionCopy.globalEnvironmentVariables = globalEnvironmentVariables;
const folder = findItemInCollection(collectionCopy, folderUid);
if (folderUid && !folder) {
return reject(new Error('Folder not found'));
}
const environment = findEnvironmentInCollection(collectionCopy, collection.activeEnvironmentUid);
dispatch(
resetRunResults({
collectionUid: collection.uid
})
);
const { ipcRenderer } = window;
ipcRenderer
.invoke(
'renderer:run-collection-folder',
folder,
collectionCopy,
environment,
collectionCopy.runtimeVariables,
recursive,
delay,
tags,
selectedRequestUids
)
.then(resolve)
.catch((err) => {
toast.error(get(err, 'error.message') || 'Something went wrong!');
reject(err);
});
});
};
export const newFolder = (folderName, directoryName, collectionUid, itemUid) => (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
const parentItem = itemUid ? findItemInCollection(collection, itemUid) : collection;
const items = filter(parentItem.items, (i) => isItemAFolder(i) || isItemARequest(i));
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
if (!itemUid) {
const folderWithSameNameExists = find(
collection.items,
(i) => i.type === 'folder' && trim(i.filename) === trim(directoryName)
);
if (!folderWithSameNameExists) {
const fullName = path.join(collection.pathname, directoryName);
const { ipcRenderer } = window;
const folderData = {
meta: {
name: folderName,
seq: items?.length + 1
},
request: {
auth: {
mode: 'inherit'
}
}
};
ipcRenderer
.invoke('renderer:new-folder', { pathname: fullName, folderData, format: collection.format })
.then(resolve)
.catch((error) => {
toast.error('Failed to create a new folder!');
reject(error);
});
} else {
return reject(new Error('Duplicate folder names under same parent folder are not allowed'));
}
} else {
const currentItem = findItemInCollection(collection, itemUid);
if (currentItem) {
const folderWithSameNameExists = find(
currentItem.items,
(i) => i.type === 'folder' && trim(i.filename) === trim(directoryName)
);
if (!folderWithSameNameExists) {
const fullName = path.join(currentItem.pathname, directoryName);
const { ipcRenderer } = window;
const folderData = {
meta: {
name: folderName,
seq: items?.length + 1
},
request: {
auth: {
mode: 'inherit'
}
}
};
ipcRenderer
.invoke('renderer:new-folder', { pathname: fullName, folderData, format: collection.format })
.then(resolve)
.catch((error) => {
toast.error('Failed to create a new folder!');
reject(error);
});
} else {
return reject(new Error('Duplicate folder names under same parent folder are not allowed'));
}
} else {
return reject(new Error('unable to find parent folder'));
}
}
});
};
export const renameItem
= ({ newName, newFilename, itemUid, collectionUid }) =>
(dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise((resolve, reject) => {
if (!collection) {
return reject(new Error('Collection not found'));
}
const collectionCopy = cloneDeep(collection);
const item = findItemInCollection(collectionCopy, itemUid);
if (!item) {
return reject(new Error('Unable to locate item'));
}
const { ipcRenderer } = window;
const renameName = async () => {
return ipcRenderer.invoke('renderer:rename-item-name', { itemPath: item.pathname, newName, collectionPathname: collection.pathname }).catch((err) => {
toast.error('Failed to rename the item name');
console.error(err);
throw new Error('Failed to rename the item name');
});
};
const renameFile = async () => {
const dirname = path.dirname(item.pathname);
let newPath = '';
if (item.type === 'folder') {
newPath = path.join(dirname, trim(newFilename));
} else {
const filename = resolveRequestFilename(newFilename, collection.format);
newPath = path.join(dirname, filename);
}
return ipcRenderer
.invoke('renderer:rename-item-filename', { oldPath: item.pathname, newPath, newName, newFilename, collectionPathname: collection.pathname })
.catch((err) => {
console.error(err);
throw new Error('Duplicate request names are not allowed under the same folder');
});
};
let renameOperation = null;
if (newName) renameOperation = renameName;
if (newFilename) renameOperation = renameFile;
if (!renameOperation) {
resolve();
}
renameOperation()
.then(() => {
toast.success('Item renamed successfully');
resolve();
})
.catch((err) => reject(err));
});
};
export const cloneItem = (newName, newFilename, itemUid, collectionUid) => (dispatch, getState) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
return new Promise((resolve, reject) => {
if (!collection) {
throw new Error('Collection not found');
}
const collectionCopy = cloneDeep(collection);
const item = findItemInCollection(collectionCopy, itemUid);
if (!item) {
throw new Error('Unable to locate item');
}
if (isItemAFolder(item)) {
const parentFolder = findParentItemInCollection(collection, item.uid) || collection;
const folderWithSameNameExists = find(
parentFolder.items,
(i) => i.type === 'folder' && trim(i?.filename) === trim(newFilename)
);
if (folderWithSameNameExists) {
return reject(new Error('Duplicate folder names under same parent folder are not allowed'));
}
set(item, 'name', newName);
set(item, 'filename', newFilename);
set(item, 'root.meta.name', newName);
set(item, 'root.meta.seq', parentFolder?.items?.length + 1);
const collectionPath = path.join(parentFolder.pathname, newFilename);
const { ipcRenderer } = window;
ipcRenderer.invoke('renderer:clone-folder', item, collectionPath, collection.pathname).then(resolve).catch(reject);
return;
}
const parentItem = findParentItemInCollection(collectionCopy, itemUid);
const filename = resolveRequestFilename(newFilename, collection.format);
const itemToSave = refreshUidsInItem(transformRequestToSaveToFilesystem(item));
set(itemToSave, 'name', trim(newName));
set(itemToSave, 'filename', trim(filename));
if (!parentItem) {
const reqWithSameNameExists = find(
collection.items,
(i) => i.type !== 'folder' && trim(i.filename) === trim(filename)
);
if (!reqWithSameNameExists) {
const fullPathname = path.join(collection.pathname, filename);
const { ipcRenderer } = window;
const requestItems = filter(collection.items, (i) => i.type !== 'folder');
itemToSave.seq = requestItems ? requestItems.length + 1 : 1;
itemSchema
.validate(itemToSave)
.then(() => ipcRenderer.invoke('renderer:new-request', fullPathname, itemToSave))
.then(resolve)
.catch(reject);
dispatch(
insertTaskIntoQueue({
uid: uuid(),
type: 'OPEN_REQUEST',
collectionUid,
itemPathname: fullPathname
})
);
} else {
return reject(new Error('Duplicate request names are not allowed under the same folder'));
}