- |
+ |
{
},
header,
'name'
- )
- }
+ )}
autocomplete={headerAutoCompleteList}
onRun={handleRun}
collection={collection}
@@ -153,8 +152,7 @@ const RequestHeaders = ({ item, collection, addHeaderText }) => {
},
header,
'value'
- )
- }
+ )}
onRun={handleRun}
autocomplete={MimeTypes}
collection={collection}
diff --git a/packages/bruno-app/src/components/RequestPane/Settings/Tags/index.js b/packages/bruno-app/src/components/RequestPane/Settings/Tags/index.js
index 006a9894f..cb833f266 100644
--- a/packages/bruno-app/src/components/RequestPane/Settings/Tags/index.js
+++ b/packages/bruno-app/src/components/RequestPane/Settings/Tags/index.js
@@ -14,7 +14,7 @@ const Tags = ({ item, collection }) => {
const tags = item.draft ? get(item, 'draft.tags', []) : get(item, 'tags', []);
// Filter out tags that are already associated with the current request
- const collectionTagsWithoutCurrentRequestTags = collectionTags?.filter(tag => !tags.includes(tag)) || [];
+ const collectionTagsWithoutCurrentRequestTags = collectionTags?.filter((tag) => !tags.includes(tag)) || [];
const handleAdd = useCallback((tag) => {
const trimmedTag = tag.trim();
@@ -41,7 +41,7 @@ const Tags = ({ item, collection }) => {
const handleRequestSave = () => {
dispatch(saveRequest(item.uid, collection.uid));
- }
+ };
useEffect(() => {
dispatch(updateCollectionTagsList({ collectionUid: collection.uid }));
@@ -49,9 +49,9 @@ const Tags = ({ item, collection }) => {
return (
- {
);
};
-export default Tags;
\ No newline at end of file
+export default Tags;
diff --git a/packages/bruno-app/src/components/RequestPane/Settings/ToggleSelector/index.js b/packages/bruno-app/src/components/RequestPane/Settings/ToggleSelector/index.js
index 05ad36f4f..686cc2f70 100644
--- a/packages/bruno-app/src/components/RequestPane/Settings/ToggleSelector/index.js
+++ b/packages/bruno-app/src/components/RequestPane/Settings/ToggleSelector/index.js
@@ -50,13 +50,13 @@ const ToggleSelector = ({
relative inline-flex ${currentSize.container} flex-shrink-0 items-center rounded-full transition-colors
focus:outline-none focus:ring-1 focus:ring-offset-1
${disabled
- ? 'opacity-50 cursor-not-allowed'
- : 'cursor-pointer'
- }
+ ? 'opacity-50 cursor-not-allowed'
+ : 'cursor-pointer'
+ }
${checked
- ? 'bg-blue-600 dark:bg-blue-500'
- : 'bg-gray-200 dark:bg-gray-700'
- }
+ ? 'bg-blue-600 dark:bg-blue-500'
+ : 'bg-gray-200 dark:bg-gray-700'
+ }
`}
role="switch"
aria-checked={checked}
@@ -73,4 +73,4 @@ const ToggleSelector = ({
);
};
-export default ToggleSelector;
\ No newline at end of file
+export default ToggleSelector;
diff --git a/packages/bruno-app/src/components/RequestPane/Settings/index.js b/packages/bruno-app/src/components/RequestPane/Settings/index.js
index 9a3340b6d..f3cc73f48 100644
--- a/packages/bruno-app/src/components/RequestPane/Settings/index.js
+++ b/packages/bruno-app/src/components/RequestPane/Settings/index.js
@@ -156,4 +156,4 @@ const Settings = ({ item, collection }) => {
);
};
-export default Settings;
\ No newline at end of file
+export default Settings;
diff --git a/packages/bruno-app/src/components/RequestPane/Vars/VarsTable/index.js b/packages/bruno-app/src/components/RequestPane/Vars/VarsTable/index.js
index 1189747b4..d19c7c859 100644
--- a/packages/bruno-app/src/components/RequestPane/Vars/VarsTable/index.js
+++ b/packages/bruno-app/src/components/RequestPane/Vars/VarsTable/index.js
@@ -92,24 +92,24 @@ const VarsTable = ({ item, collection, vars, varType }) => {
headers={[
{ name: 'Name', accessor: 'name', width: '40%' },
{ name: varType === 'request' ? (
-
- Value
-
+
+ Value
+
) : (
-
- Expr
-
-
+
+ Expr
+
+
), accessor: 'value', width: '46%' },
{ name: '', accessor: '', width: '14%' }
]}
>
- {vars && vars.length
+ {vars && vars.length
? vars.map((_var) => {
return (
- |
+ |
{
},
_var,
'value'
- )
- }
+ )}
onRun={handleRun}
collection={collection}
item={item}
diff --git a/packages/bruno-app/src/components/RequestTabPanel/FolderNotFound/index.js b/packages/bruno-app/src/components/RequestTabPanel/FolderNotFound/index.js
index eff188890..9c450ffd2 100644
--- a/packages/bruno-app/src/components/RequestTabPanel/FolderNotFound/index.js
+++ b/packages/bruno-app/src/components/RequestTabPanel/FolderNotFound/index.js
@@ -39,4 +39,4 @@ const FolderNotFound = ({ folderUid }) => {
);
};
-export default FolderNotFound;
\ No newline at end of file
+export default FolderNotFound;
diff --git a/packages/bruno-app/src/components/RequestTabPanel/RequestIsLoading/index.js b/packages/bruno-app/src/components/RequestTabPanel/RequestIsLoading/index.js
index 9d2ff1346..35ae9c253 100644
--- a/packages/bruno-app/src/components/RequestTabPanel/RequestIsLoading/index.js
+++ b/packages/bruno-app/src/components/RequestTabPanel/RequestIsLoading/index.js
@@ -2,46 +2,48 @@ import { IconLoader2, IconFile } from '@tabler/icons';
import StyledWrapper from './StyledWrapper';
const RequestIsLoading = ({ item }) => {
- return
-
-
-
-
-
- File Info
-
-
+ return (
+
+
+
+
+
+
+ File Info
+
+
-
- Name:
-
- {item?.name}
+
+ Name:
+
+ {item?.name}
+
-
-
-
- Path:
-
- {item?.pathname}
-
-
-
-
- Size:
-
- {item?.size?.toFixed?.(2)} MB
-
-
-
-
-
- Loading...
+
+ Path:
+
+ {item?.pathname}
+
+
+
+
+ Size:
+
+ {item?.size?.toFixed?.(2)} MB
+
+
+
+
+
+
+ Loading...
+
-
-
-}
+
+ );
+};
-export default RequestIsLoading;
\ No newline at end of file
+export default RequestIsLoading;
diff --git a/packages/bruno-app/src/components/RequestTabPanel/RequestNotLoaded/index.js b/packages/bruno-app/src/components/RequestTabPanel/RequestNotLoaded/index.js
index 08d011326..39b9a76b3 100644
--- a/packages/bruno-app/src/components/RequestTabPanel/RequestNotLoaded/index.js
+++ b/packages/bruno-app/src/components/RequestTabPanel/RequestNotLoaded/index.js
@@ -8,64 +8,66 @@ const RequestNotLoaded = ({ collection, item }) => {
const handleLoadLargeRequest = () => {
!item?.loading && dispatch(loadLargeRequest({ collectionUid: collection?.uid, pathname: item?.pathname }));
- }
+ };
- return
-
-
-
-
-
- File Info
-
-
+ return (
+
+
+
+
+
+
+ File Info
+
+
-
+
-
- Path:
- {item?.pathname}
-
+
+ Path:
+ {item?.pathname}
+
-
- Size:
- {item?.size?.toFixed?.(2)} MB
-
+
+ Size:
+ {item?.size?.toFixed?.(2)} MB
+
- {!item?.error && (
-
-
-
- The request wasn't loaded due to its large size. Please try again with the following options:
-
-
-
-
- )}
+ )}
- {item?.loading && (
- <>
-
-
-
- Loading...
-
- >
- )}
+ {item?.loading && (
+ <>
+
+
+
+ Loading...
+
+ >
+ )}
+
-
-
-}
+
+ );
+};
-export default RequestNotLoaded;
\ No newline at end of file
+export default RequestNotLoaded;
diff --git a/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/StyledWrapper.js b/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/StyledWrapper.js
index 39cd89e4c..ec278887d 100644
--- a/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/StyledWrapper.js
+++ b/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/StyledWrapper.js
@@ -2,4 +2,4 @@ import styled from 'styled-components';
const StyledWrapper = styled.div``;
-export default StyledWrapper;
\ No newline at end of file
+export default StyledWrapper;
diff --git a/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/index.js b/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/index.js
index 7c803cf4c..396b5cbd2 100644
--- a/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/index.js
+++ b/packages/bruno-app/src/components/RequestTabs/CollectionToolBar/index.js
@@ -53,7 +53,7 @@ const CollectionToolBar = ({ collection }) => {
-
+
diff --git a/packages/bruno-app/src/components/RequestTabs/RequestTab/CloseTabIcon.js b/packages/bruno-app/src/components/RequestTabs/RequestTab/CloseTabIcon.js
index de2aa845d..377a4fc39 100644
--- a/packages/bruno-app/src/components/RequestTabs/RequestTab/CloseTabIcon.js
+++ b/packages/bruno-app/src/components/RequestTabs/RequestTab/CloseTabIcon.js
@@ -3,7 +3,8 @@ const CloseTabIcon = () => (
+ >
+
);
diff --git a/packages/bruno-app/src/components/RequestTabs/RequestTab/SpecialTab.js b/packages/bruno-app/src/components/RequestTabs/RequestTab/SpecialTab.js
index 12e919802..df5bda2a0 100644
--- a/packages/bruno-app/src/components/RequestTabs/RequestTab/SpecialTab.js
+++ b/packages/bruno-app/src/components/RequestTabs/RequestTab/SpecialTab.js
@@ -28,7 +28,7 @@ const SpecialTab = ({ handleCloseClick, type, tabName, handleDoubleClick, hasDra
Security
>
- )
+ );
}
case 'folder-settings': {
return (
diff --git a/packages/bruno-app/src/components/RequestTabs/RequestTab/index.js b/packages/bruno-app/src/components/RequestTabs/RequestTab/index.js
index 10ca52199..f0820badc 100644
--- a/packages/bruno-app/src/components/RequestTabs/RequestTab/index.js
+++ b/packages/bruno-app/src/components/RequestTabs/RequestTab/index.js
@@ -108,7 +108,7 @@ const RequestTab = ({ tab, collection, tabIndex, collectionRequestTabs, folderUi
if (['collection-settings', 'collection-overview', 'folder-settings', 'variables', 'collection-runner', 'security-settings'].includes(tab.type)) {
return (
{showConfirmCollectionClose && tab.type === 'collection-settings' && (
@@ -192,7 +192,6 @@ const RequestTab = ({ tab, collection, tabIndex, collectionRequestTabs, folderUi
);
}
-
const getMethodText = useCallback((item) => {
if (!item) return;
@@ -269,7 +268,7 @@ const RequestTab = ({ tab, collection, tabIndex, collectionRequestTabs, folderUi
/>
)}
dispatch(makeTabPermanent({ uid: tab.uid }))}
onMouseUp={(e) => {
diff --git a/packages/bruno-app/src/components/RequestTabs/index.js b/packages/bruno-app/src/components/RequestTabs/index.js
index 724707b4f..c9fbb74aa 100644
--- a/packages/bruno-app/src/components/RequestTabs/index.js
+++ b/packages/bruno-app/src/components/RequestTabs/index.js
@@ -24,7 +24,7 @@ const RequestTabs = () => {
const getTabClassname = (tab, index) => {
return classnames('request-tab select-none', {
- active: tab.uid === activeTabUid,
+ 'active': tab.uid === activeTabUid,
'last-tab': tabs && tabs.length && index === tabs.length - 1
});
};
diff --git a/packages/bruno-app/src/components/ResponsePane/ClearTimeline/index.js b/packages/bruno-app/src/components/ResponsePane/ClearTimeline/index.js
index 18704cc41..200cb0488 100644
--- a/packages/bruno-app/src/components/ResponsePane/ClearTimeline/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/ClearTimeline/index.js
@@ -16,7 +16,7 @@ const ClearTimeline = ({ collection, item }) => {
return (
-
+
Clear Timeline
diff --git a/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/StyledWrapper.js b/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/StyledWrapper.js
index db90d65f0..7c8ffe964 100644
--- a/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/StyledWrapper.js
+++ b/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/StyledWrapper.js
@@ -19,4 +19,4 @@ const Wrapper = styled.div`
}
`;
-export default Wrapper;
\ No newline at end of file
+export default Wrapper;
diff --git a/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/get-grpc-status-code-phrase.js b/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/get-grpc-status-code-phrase.js
index a8c96e645..2f2d09b1b 100644
--- a/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/get-grpc-status-code-phrase.js
+++ b/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/get-grpc-status-code-phrase.js
@@ -19,4 +19,4 @@ const grpcStatusCodePhraseMap = {
16: 'Unauthenticated'
};
-export default grpcStatusCodePhraseMap;
\ No newline at end of file
+export default grpcStatusCodePhraseMap;
diff --git a/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/index.js b/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/index.js
index da2bcb001..b9a982d7c 100644
--- a/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/GrpcResponsePane/GrpcStatusCode/index.js
@@ -14,7 +14,7 @@ const GrpcStatusCode = ({ status, text }) => {
});
};
- const statusText = text || grpcStatusCodePhraseMap[status]
+ const statusText = text || grpcStatusCodePhraseMap[status];
return (
@@ -24,4 +24,4 @@ const GrpcStatusCode = ({ status, text }) => {
);
};
-export default GrpcStatusCode;
\ No newline at end of file
+export default GrpcStatusCode;
diff --git a/packages/bruno-app/src/components/ResponsePane/LargeResponseWarning/index.js b/packages/bruno-app/src/components/ResponsePane/LargeResponseWarning/index.js
index 1686b4a38..57972f63c 100644
--- a/packages/bruno-app/src/components/ResponsePane/LargeResponseWarning/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/LargeResponseWarning/index.js
@@ -52,7 +52,7 @@ const LargeResponseWarning = ({ item, responseSize, onRevealResponse }) => {
Handling responses over {formatSize(10 * 1024 * 1024)} could degrade performance.
-
+
Size of current response: {formatSize(responseSize)}
@@ -89,4 +89,4 @@ const LargeResponseWarning = ({ item, responseSize, onRevealResponse }) => {
);
};
-export default LargeResponseWarning;
\ No newline at end of file
+export default LargeResponseWarning;
diff --git a/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultFilter/index.js b/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultFilter/index.js
index db6ee72f6..5320b4195 100644
--- a/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultFilter/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultFilter/index.js
@@ -45,11 +45,9 @@ const QueryResultFilter = ({ filter, onChange, mode }) => {
return (
- {infotipText && !isExpanded && }
+ {infotipText && !isExpanded && }
{
if (!error) return 'Something went wrong';
- const remoteMethodError = "Error invoking remote method 'send-http-request':";
-
+ const remoteMethodError = 'Error invoking remote method \'send-http-request\':';
+
if (error?.includes(remoteMethodError)) {
const parts = error.split(remoteMethodError);
return parts[1]?.trim() || error;
@@ -37,7 +37,7 @@ const QueryResult = ({ item, collection, data, dataBuffer, disableRunEventListen
if (typeof response.size === 'number') {
return response.size;
}
-
+
if (!dataBuffer) return 0;
try {
diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/StyledWrapper.js b/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/StyledWrapper.js
index 8cb5d4b43..8e77b37d3 100644
--- a/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/StyledWrapper.js
+++ b/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/StyledWrapper.js
@@ -12,4 +12,4 @@ const Wrapper = styled.div`
}
`;
-export default Wrapper;
\ No newline at end of file
+export default Wrapper;
diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.js b/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.js
index 49299422b..709666765 100644
--- a/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.js
@@ -44,7 +44,7 @@ const IconDockToRight = () => {
stroke="currentColor"
d="m 19.111502,18.486486 c -0.115516,0.259266 -0.354643,0.491338 -0.639512,0.620643 -0.221702,0.100633 -0.393081,0.114019 -1.474447,0.115163 l -1.223586,0.0013 V 12 4.7764125 h 1.22675 c 1.194609,0 1.234605,0.0039 1.526503,0.14937 0.187285,0.09333 0.363095,0.2407725 0.46858,0.3929775 l 0.168829,0.243606 0.0129,6.373606 c 0.0105,5.212942 -0.0015,6.405822 -0.06597,6.550511 z"
/>
-
+
);
};
@@ -67,8 +67,8 @@ const ResponseLayoutToggle = () => {
return (
-
{orientation === 'horizontal' ? (
@@ -81,4 +81,4 @@ const ResponseLayoutToggle = () => {
);
};
-export default ResponseLayoutToggle;
\ No newline at end of file
+export default ResponseLayoutToggle;
diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.spec.js b/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.spec.js
index 0dd1c7b1a..3131c3247 100644
--- a/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.spec.js
+++ b/packages/bruno-app/src/components/ResponsePane/ResponseLayoutToggle/index.spec.js
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom';
import React from 'react';
-import { render, screen, fireEvent} from '@testing-library/react';
+import { render, screen, fireEvent } from '@testing-library/react';
import { Provider } from 'react-redux';
import { ThemeProvider } from 'providers/Theme';
import { configureStore, createSlice } from '@reduxjs/toolkit';
@@ -24,12 +24,12 @@ const mockLocalStorage = {
beforeAll(() => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
- value: jest.fn().mockImplementation(query => ({
+ value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
addEventListener: jest.fn(),
removeEventListener: jest.fn()
- })),
+ }))
});
Object.defineProperty(window, 'localStorage', {
value: mockLocalStorage
@@ -110,10 +110,10 @@ describe('ResponseLayoutToggle', () => {
it('should switch to vertical layout when clicked in horizontal mode', () => {
const { store } = renderWithProviders();
const button = screen.getByRole('button');
-
+
// Initial state check
expect(button).toHaveAttribute('title', 'Switch to vertical layout');
-
+
fireEvent.click(button);
// Check if action was called
@@ -146,10 +146,10 @@ describe('ResponseLayoutToggle', () => {
};
const { store } = renderWithProviders(, customState);
const button = screen.getByRole('button');
-
+
// Initial state check
expect(button).toHaveAttribute('title', 'Switch to horizontal layout');
-
+
fireEvent.click(button);
// Check if action was called
diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseSize/ResponseSize.spec.js b/packages/bruno-app/src/components/ResponsePane/ResponseSize/ResponseSize.spec.js
index 11aa35d13..22b0182ee 100644
--- a/packages/bruno-app/src/components/ResponsePane/ResponseSize/ResponseSize.spec.js
+++ b/packages/bruno-app/src/components/ResponsePane/ResponseSize/ResponseSize.spec.js
@@ -58,7 +58,7 @@ describe('ResponseSize', () => {
});
it('should not render when size is an object', () => {
- const { container } = renderWithTheme();
+ const { container } = renderWithTheme();
expect(container).toBeEmptyDOMElement();
});
});
@@ -116,4 +116,4 @@ describe('ResponseSize', () => {
expect(element).toHaveAttribute('title', `${size.toLocaleString()}B`);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js b/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js
index fcdeaaca3..7707669c4 100644
--- a/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js
@@ -2,7 +2,6 @@ import React from 'react';
import StyledWrapper from './StyledWrapper';
const ResponseSize = ({ size }) => {
-
if (!Number.isFinite(size)) {
return null;
}
diff --git a/packages/bruno-app/src/components/ResponsePane/RunnerTimeline/index.js b/packages/bruno-app/src/components/ResponsePane/RunnerTimeline/index.js
index 4fac7ed6d..8c3e839aa 100644
--- a/packages/bruno-app/src/components/ResponsePane/RunnerTimeline/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/RunnerTimeline/index.js
@@ -31,7 +31,7 @@ const RunnerTimeline = ({ request = {}, response = {}, item, collection }) => {
collection={collection}
hideTimestamp={true}
/>
-
+
{oauth2Events.map((event, index) => {
const { data, timestamp } = event;
const { debugInfo } = data;
@@ -45,7 +45,7 @@ const RunnerTimeline = ({ request = {}, response = {}, item, collection }) => {
{debugInfo && debugInfo.length > 0 ? (
debugInfo.map((data, idx) => (
-
+
{
const preRequestError = item?.preRequestScriptErrorMessage;
const postResponseError = item?.postResponseScriptErrorMessage;
const testScriptError = item?.testScriptErrorMessage;
-
+
if (!preRequestError && !postResponseError && !testScriptError) return null;
-
+
const errors = [];
-
+
if (preRequestError) {
errors.push({
title: 'Pre-Request Script Error',
message: preRequestError
});
}
-
+
if (postResponseError) {
errors.push({
- title: 'Post-Response Script Error',
+ title: 'Post-Response Script Error',
message: postResponseError
});
}
-
+
if (testScriptError) {
errors.push({
title: 'Test Script Error',
message: testScriptError
});
}
-
+
return (
@@ -49,7 +48,7 @@ const ScriptError = ({ item, onClose }) => {
))}
-
@@ -60,4 +59,4 @@ const ScriptError = ({ item, onClose }) => {
);
};
-export default ScriptError;
\ No newline at end of file
+export default ScriptError;
diff --git a/packages/bruno-app/src/components/ResponsePane/ScriptErrorIcon/index.js b/packages/bruno-app/src/components/ResponsePane/ScriptErrorIcon/index.js
index 208a49ffd..41420eeb0 100644
--- a/packages/bruno-app/src/components/ResponsePane/ScriptErrorIcon/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/ScriptErrorIcon/index.js
@@ -4,10 +4,10 @@ import ToolHint from 'components/ToolHint';
const ScriptErrorIcon = ({ itemUid, onClick }) => {
const toolhintId = `script-error-icon-${itemUid}`;
-
+
return (
<>
- {
);
};
-export default ScriptErrorIcon;
\ No newline at end of file
+export default ScriptErrorIcon;
diff --git a/packages/bruno-app/src/components/ResponsePane/SkippedRequest/StyledWrapper.js b/packages/bruno-app/src/components/ResponsePane/SkippedRequest/StyledWrapper.js
index a7049ad6b..922798c17 100644
--- a/packages/bruno-app/src/components/ResponsePane/SkippedRequest/StyledWrapper.js
+++ b/packages/bruno-app/src/components/ResponsePane/SkippedRequest/StyledWrapper.js
@@ -8,4 +8,4 @@ const StyledWrapper = styled.div`
}
`;
-export default StyledWrapper;
\ No newline at end of file
+export default StyledWrapper;
diff --git a/packages/bruno-app/src/components/ResponsePane/SkippedRequest/index.js b/packages/bruno-app/src/components/ResponsePane/SkippedRequest/index.js
index 684dc3c37..64d9d76fd 100644
--- a/packages/bruno-app/src/components/ResponsePane/SkippedRequest/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/SkippedRequest/index.js
@@ -15,4 +15,4 @@ const SkippedRequest = () => {
);
};
-export default SkippedRequest;
\ No newline at end of file
+export default SkippedRequest;
diff --git a/packages/bruno-app/src/components/ResponsePane/StatusCode/get-status-code-phrase.js b/packages/bruno-app/src/components/ResponsePane/StatusCode/get-status-code-phrase.js
index c90ff7cc7..e5c7659fb 100644
--- a/packages/bruno-app/src/components/ResponsePane/StatusCode/get-status-code-phrase.js
+++ b/packages/bruno-app/src/components/ResponsePane/StatusCode/get-status-code-phrase.js
@@ -41,7 +41,7 @@ const statusCodePhraseMap = {
415: 'Unsupported Media Type',
416: 'Range Not Satisfiable',
417: 'Expectation Failed',
- 418: "I'm a teapot",
+ 418: 'I\'m a teapot',
421: 'Misdirected Request',
422: 'Unprocessable Entity',
423: 'Locked',
diff --git a/packages/bruno-app/src/components/ResponsePane/TestResults/index.js b/packages/bruno-app/src/components/ResponsePane/TestResults/index.js
index 624de837d..08770e6f9 100644
--- a/packages/bruno-app/src/components/ResponsePane/TestResults/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/TestResults/index.js
@@ -32,8 +32,7 @@ const ResultItem = ({ result, type }) => (
{type === 'assertion'
? `${result.lhsExpr}: ${result.rhsExpr}`
- : result.description
- }
+ : result.description}
@@ -52,16 +51,15 @@ const TestSection = ({
if (results.length === 0) return null;
return (
-
+
- {isExpanded ?
- :
-
- }
+ {isExpanded
+ ?
+ : }
{title} ({results.length}), Passed: {passedResults.length}, Failed: {failedResults.length}
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/GrpcTimelineItem/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/GrpcTimelineItem/index.js
index 6dcdbcf99..a42930777 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/GrpcTimelineItem/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/GrpcTimelineItem/index.js
@@ -1,13 +1,13 @@
-import { useState } from "react";
-import { RelativeTime } from "../TimelineItem/Common/Time/index";
-import Status from "../TimelineItem/Common/Status/index";
-import {
- IconChevronDown,
- IconChevronRight,
- IconServer,
- IconDatabase,
- IconAlertCircle,
- IconCircleCheck,
+import { useState } from 'react';
+import { RelativeTime } from '../TimelineItem/Common/Time/index';
+import Status from '../TimelineItem/Common/Status/index';
+import {
+ IconChevronDown,
+ IconChevronRight,
+ IconServer,
+ IconDatabase,
+ IconAlertCircle,
+ IconCircleCheck,
IconCircleX,
IconX,
IconSend
@@ -27,55 +27,53 @@ const EventTypeIcons = {
// Event type display names
const EventTypeNames = {
- metadata: "Metadata",
- response: "Response Message",
- request: "Request",
- message: "Message",
- status: "Status",
- error: "Error",
- end: "Stream Ended",
- cancel: "Cancelled"
+ metadata: 'Metadata',
+ response: 'Response Message',
+ request: 'Request',
+ message: 'Message',
+ status: 'Status',
+ error: 'Error',
+ end: 'Stream Ended',
+ cancel: 'Cancelled'
};
// Colors for different event types
const EventTypeColors = {
- metadata: "border-blue-500/20",
- response: "border-green-500/20",
- request: "border-orange-500/20",
- message: "border-orange-500/20",
- status: "border-purple-500/20",
- error: "border-red-500/20",
- end: "border-gray-500/20",
- cancel: "border-amber-500/20"
+ metadata: 'border-blue-500/20',
+ response: 'border-green-500/20',
+ request: 'border-orange-500/20',
+ message: 'border-orange-500/20',
+ status: 'border-purple-500/20',
+ error: 'border-red-500/20',
+ end: 'border-gray-500/20',
+ cancel: 'border-amber-500/20'
};
const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData, item }) => {
const [isCollapsed, setIsCollapsed] = useState(true);
- const toggleCollapse = () => setIsCollapsed(prev => !prev);
-
+ const toggleCollapse = () => setIsCollapsed((prev) => !prev);
+
// Use requestSent if available, otherwise fall back to request
const effectiveRequest = item.requestSent || request || item.request || {};
-
+
// Extract relevant data from request and response
const { method, url = '' } = effectiveRequest;
const { statusCode, statusText, duration } = response || {};
-
+
// Get event-specific icon and color
const eventIcon = EventTypeIcons[eventType] || ;
- const eventColor = EventTypeColors[eventType] || "border-gray-500/50";
- const eventName = EventTypeNames[eventType] || "Event";
+ const eventColor = EventTypeColors[eventType] || 'border-gray-500/50';
+ const eventName = EventTypeNames[eventType] || 'Event';
-
// Render appropriate content based on event type
const renderEventContent = () => {
-
const isClientStreaming = effectiveRequest.methodType === 'client-streaming' || effectiveRequest.methodType === 'bidi-streaming';
- switch(eventType) {
+ switch (eventType) {
case 'request':
return (
-
+
{effectiveRequest.headers && Object.keys(effectiveRequest.headers).length > 0 && (
Metadata
@@ -89,7 +87,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
)}
-
+
{/* gRPC Messages section */}
{!isClientStreaming && effectiveRequest.body?.mode === 'grpc' && effectiveRequest.body?.grpc?.length > 0 && (
@@ -100,8 +98,8 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
{effectiveRequest.body.grpc.filter((_, index) => index === 0).map((message, idx) => (
- {typeof message.content === 'string'
- ? message.content
+ {typeof message.content === 'string'
+ ? message.content
: JSON.stringify(message.content, null, 2)}
@@ -117,10 +115,10 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
Message
- {typeof eventData === 'string'
- ? eventData
- : JSON.stringify(eventData, null, 2)}
-
+ {typeof eventData === 'string'
+ ? eventData
+ : JSON.stringify(eventData, null, 2)}
+
);
@@ -142,7 +140,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
)}
);
-
+
case 'response':
// For message responses, show the response data
return (
@@ -159,7 +157,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
)}
);
-
+
case 'status':
// For status events, show status and trailers
return (
@@ -167,11 +165,11 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
-
+
{response.statusDescription && (
{response.statusDescription}
)}
-
+
{response.trailers && response.trailers.length > 0 && (
<>
Trailers
@@ -187,18 +185,18 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
)}
);
-
+
case 'error':
// For error events, show error details
return (
Error
{response.error || 'Unknown error'}
-
+
-
+
{response.trailers && response.trailers.length > 0 && (
<>
Error Metadata
@@ -214,7 +212,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
)}
);
-
+
case 'end':
// For end events, show summary
return (
@@ -225,7 +223,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
);
-
+
case 'cancel':
// For cancel events, show cancellation info
return (
@@ -234,7 +232,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
{response.statusDescription || 'The gRPC stream was cancelled'}
);
-
+
default:
return null;
}
@@ -242,7 +240,7 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
return (
-
+
{isCollapsed ? : }
{eventIcon}
{eventName}
@@ -261,14 +259,14 @@ const GrpcTimelineItem = ({ timestamp, request, response, eventType, eventData,
-
+
{/* Always show the URL */}
{url}
-
+
{/* Expanded content - only show for non-status items */}
{!isCollapsed && renderEventContent()}
);
};
-export default GrpcTimelineItem;
\ No newline at end of file
+export default GrpcTimelineItem;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Body/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Body/index.js
index 683c82bba..111ec6bb7 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Body/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Body/index.js
@@ -1,36 +1,36 @@
-import QueryResult from "components/ResponsePane/QueryResult/index";
-import { useState } from "react";
+import QueryResult from 'components/ResponsePane/QueryResult/index';
+import { useState } from 'react';
const BodyBlock = ({ collection, data, dataBuffer, headers, error, item }) => {
const [isBodyCollapsed, toggleBody] = useState(true);
return (
- toggleBody(!isBodyCollapsed)}>
-
- {isBodyCollapsed ? 'โผ' : 'โถ'} Body
-
-
- {isBodyCollapsed && (
-
- {data || dataBuffer ? (
-
-
-
- ) : (
- No Body found
- )}
+ toggleBody(!isBodyCollapsed)}>
+
+ {isBodyCollapsed ? 'โผ' : 'โถ'} Body
+
- )}
-
- )
-}
+ {isBodyCollapsed && (
+
+ {data || dataBuffer ? (
+
+
+
+ ) : (
+ No Body found
+ )}
+
+ )}
+
+ );
+};
-export default BodyBlock;
\ No newline at end of file
+export default BodyBlock;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Headers/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Headers/index.js
index 425bbf0d0..4f28cf6e8 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Headers/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Headers/index.js
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useState } from 'react';
const HeadersBlock = ({ headers, type }) => {
const [areHeadersCollapsed, toggleHeaders] = useState(true);
@@ -8,21 +8,19 @@ const HeadersBlock = ({ headers, type }) => {
toggleHeaders(!areHeadersCollapsed)}>
{areHeadersCollapsed ? 'โผ' : 'โถ'} Headers
- {headers && Object.keys(headers).length > 0 &&
- ({Object.keys(headers).length})
- }
+ {headers && Object.keys(headers).length > 0
+ && ({Object.keys(headers).length}) }
{areHeadersCollapsed && (
- {headers && Object.keys(headers).length > 0
+ {headers && Object.keys(headers).length > 0
?
- : No Headers found
- }
+ : No Headers found }
)}
- )
+ );
};
const Headers = ({ headers, type }) => {
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Method/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Method/index.js
index 1e0b22d3a..3f3cf7d36 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Method/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Method/index.js
@@ -3,8 +3,8 @@ const Method = ({ method }) => {
{method?.toUpperCase()}
- )
-}
+ );
+};
const methodColors = {
GET: 'text-green-500',
@@ -13,7 +13,7 @@ const methodColors = {
DELETE: 'text-red-500',
PATCH: 'text-purple-500',
OPTIONS: 'text-gray-500',
- HEAD: 'text-gray-500',
+ HEAD: 'text-gray-500'
};
-export default Method;
\ No newline at end of file
+export default Method;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Status/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Status/index.js
index 8c0094120..0d96a8e4c 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Status/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Status/index.js
@@ -8,8 +8,8 @@ const Status = ({ statusCode, statusText }) => {
{statusCode}{' '}
{statusText || ''}
- )
-}
+ );
+};
const statusColor = (statusCode) => {
if (statusCode >= 200 && statusCode < 300) {
@@ -23,4 +23,4 @@ const statusColor = (statusCode) => {
}
};
-export default Status;
\ No newline at end of file
+export default Status;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Time/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Time/index.js
index d4fd0ec07..3f882ba39 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Time/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Common/Time/index.js
@@ -1,36 +1,36 @@
-import { useState, useEffect } from "react";
+import { useState, useEffect } from 'react';
const getRelativeTime = (date) => {
- const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
- const diff = (date - new Date()) / 1000;
+ const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
+ const diff = (date - new Date()) / 1000;
- const timeUnits = [
- { unit: 'year', seconds: 31536000 },
- { unit: 'month', seconds: 2592000 },
- { unit: 'week', seconds: 604800 },
- { unit: 'day', seconds: 86400 },
- { unit: 'hour', seconds: 3600 },
- { unit: 'minute', seconds: 60 },
- { unit: 'second', seconds: 1 }
- ];
+ const timeUnits = [
+ { unit: 'year', seconds: 31536000 },
+ { unit: 'month', seconds: 2592000 },
+ { unit: 'week', seconds: 604800 },
+ { unit: 'day', seconds: 86400 },
+ { unit: 'hour', seconds: 3600 },
+ { unit: 'minute', seconds: 60 },
+ { unit: 'second', seconds: 1 }
+ ];
- for (const { unit, seconds } of timeUnits) {
- if (Math.abs(diff) >= seconds || unit === 'second') {
- return rtf.format(Math.round(diff / seconds), unit);
- }
+ for (const { unit, seconds } of timeUnits) {
+ if (Math.abs(diff) >= seconds || unit === 'second') {
+ return rtf.format(Math.round(diff / seconds), unit);
}
+ }
};
export const RelativeTime = ({ timestamp }) => {
- const [relativeTime, setRelativeTime] = useState(getRelativeTime(new Date(timestamp)));
+ const [relativeTime, setRelativeTime] = useState(getRelativeTime(new Date(timestamp)));
- useEffect(() => {
- const interval = setInterval(() => {
- setRelativeTime(getRelativeTime(new Date(timestamp)));
- }, 1000);
+ useEffect(() => {
+ const interval = setInterval(() => {
+ setRelativeTime(getRelativeTime(new Date(timestamp)));
+ }, 1000);
- return () => clearInterval(interval);
- }, [timestamp]);
+ return () => clearInterval(interval);
+ }, [timestamp]);
- return {relativeTime};
+ return {relativeTime};
};
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Network/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Network/index.js
index 25d704e63..d9d0e71a4 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Network/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Network/index.js
@@ -8,15 +8,17 @@ const Network = ({ logs }) => {
}
const nextLog = logs[index + 1];
const isSameLogType = nextLog?.type === currentLog?.type;
- return <>
-
- {!isSameLogType && }
- >;
+ return (
+ <>
+
+ {!isSameLogType && }
+ >
+ );
})}
- )
-}
+ );
+};
const NetworkLogsEntry = ({ entry }) => {
const { type, message } = entry;
@@ -50,5 +52,4 @@ const NetworkLogsEntry = ({ entry }) => {
);
};
-
-export default Network;
\ No newline at end of file
+export default Network;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Request/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Request/index.js
index 053be2916..51ce28bf0 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Request/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Request/index.js
@@ -1,5 +1,5 @@
-import Headers from "../Common/Headers/index";
-import BodyBlock from "../Common/Body/index";
+import Headers from '../Common/Headers/index';
+import BodyBlock from '../Common/Body/index';
const safeStringifyJSONIfNotString = (obj) => {
if (obj === null || obj === undefined) return '';
@@ -15,9 +15,8 @@ const safeStringifyJSONIfNotString = (obj) => {
}
};
-
const Request = ({ collection, request, item }) => {
- let { url, headers, data, dataBuffer, error } = request || {};
+ let { url, headers, data, dataBuffer, error } = request || {};
if (!dataBuffer) {
dataBuffer = Buffer.from(safeStringifyJSONIfNotString(data))?.toString('base64');
}
@@ -30,12 +29,12 @@ const Request = ({ collection, request, item }) => {
{/* Headers */}
-
+
{/* Body */}
-
- )
-}
+
+ );
+};
-export default Request;
\ No newline at end of file
+export default Request;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Response/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Response/index.js
index 70acf0aa2..4c595f29c 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Response/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/Response/index.js
@@ -1,6 +1,6 @@
-import BodyBlock from "../Common/Body/index";
-import Headers from "../Common/Headers/index";
-import Status from "../Common/Status/index";
+import BodyBlock from '../Common/Body/index';
+import Headers from '../Common/Headers/index';
+import Status from '../Common/Status/index';
const safeStringifyJSONIfNotString = (obj) => {
if (obj === null || obj === undefined) return '';
@@ -24,20 +24,20 @@ const Response = ({ collection, response, item }) => {
return (
- {/* Status */}
-
-
+ {/* Status */}
+
+
{response.duration && {response.duration}ms}
{response.size && {response.size}B}
+
+
+ {/* Headers */}
+
+
+ {/* Body */}
+
+ );
+};
- {/* Headers */}
-
-
- {/* Body */}
-
-
- )
-}
-
-export default Response;
\ No newline at end of file
+export default Response;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/index.js
index 8d6081f47..b680c73ca 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/TimelineItem/index.js
@@ -1,21 +1,21 @@
-import { useState } from "react";
-import Network from "./Network/index";
-import Request from "./Request/index";
-import Response from "./Response/index";
-import Method from "./Common/Method/index";
-import Status from "./Common/Status/index";
-import { RelativeTime } from "./Common/Time/index";
+import { useState } from 'react';
+import Network from './Network/index';
+import Request from './Request/index';
+import Response from './Response/index';
+import Method from './Common/Method/index';
+import Status from './Common/Status/index';
+import { RelativeTime } from './Common/Time/index';
const TimelineItem = ({ timestamp, request, response, item, collection, isOauth2, hideTimestamp = false }) => {
const [isCollapsed, _toggleCollapse] = useState(false);
const [activeTab, setActiveTab] = useState('request');
- const toggleCollapse = () => _toggleCollapse(prev => !prev);
+ const toggleCollapse = () => _toggleCollapse((prev) => !prev);
const { method, status, statusCode, statusText, url = '' } = request || {};
const { status: responseStatus, statusCode: responseStatusCode, statusText: responseStatusText } = response || {};
const showNetworkLogs = response.timeline && response.timeline.length > 0;
return (
-
+
@@ -84,4 +84,4 @@ const TimelineItem = ({ timestamp, request, response, item, collection, isOauth2
);
};
-export default TimelineItem;
\ No newline at end of file
+export default TimelineItem;
diff --git a/packages/bruno-app/src/components/ResponsePane/Timeline/index.js b/packages/bruno-app/src/components/ResponsePane/Timeline/index.js
index 693f26438..3b5ea4531 100644
--- a/packages/bruno-app/src/components/ResponsePane/Timeline/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/Timeline/index.js
@@ -47,9 +47,9 @@ const Timeline = ({ collection, item }) => {
// Get the effective auth source if auth mode is inherit
const authSource = getEffectiveAuthSource(collection, item);
const isGrpcRequest = item.type === 'grpc-request' || item.type === 'ws-request';
-
+
// Filter timeline entries based on new rules
- const combinedTimeline = ([...(collection?.timeline || [])]).filter(obj => {
+ const combinedTimeline = ([...(collection?.timeline || [])]).filter((obj) => {
// Always show entries for this item
if (obj.itemUid === item.uid) return true;
@@ -60,28 +60,27 @@ const Timeline = ({ collection, item }) => {
}
return false;
- }).sort((a, b) => b.timestamp - a.timestamp)
+ }).sort((a, b) => b.timestamp - a.timestamp);
return (
{/* Timeline container with scrollbar */}
-
{combinedTimeline.map((event, index) => {
// Handle regular requests
if (event.type === 'request') {
-
const { data, timestamp, eventType } = event;
- const { request, response, eventData = {}, timestamp: eventTimestamp = timestamp } = data;
-
+ const { request, response, eventData = {}, timestamp: eventTimestamp = timestamp } = data;
+
if (isGrpcRequest) {
return (
{
);
}
-
+
// Regular HTTP request
return (
@@ -105,9 +104,7 @@ const Timeline = ({ collection, item }) => {
/>
);
- }
- // Handle OAuth2 events
- else if (event.type === 'oauth2') {
+ } else if (event.type === 'oauth2') { // Handle OAuth2 events
const { data, timestamp } = event;
const { debugInfo } = data;
return (
@@ -120,7 +117,7 @@ const Timeline = ({ collection, item }) => {
{debugInfo && debugInfo.length > 0 ? (
debugInfo.map((data, idx) => (
-
+
{
);
}
-
+
return null;
})}
@@ -146,4 +143,4 @@ const Timeline = ({ collection, item }) => {
);
};
-export default Timeline;
\ No newline at end of file
+export default Timeline;
diff --git a/packages/bruno-app/src/components/ResponsePane/index.js b/packages/bruno-app/src/components/ResponsePane/index.js
index 246cd8ff5..3ce781915 100644
--- a/packages/bruno-app/src/components/ResponsePane/index.js
+++ b/packages/bruno-app/src/components/ResponsePane/index.js
@@ -33,7 +33,7 @@ const ResponsePane = ({ item, collection }) => {
const isLoading = ['queued', 'sending'].includes(item.requestState);
const [showScriptErrorCard, setShowScriptErrorCard] = useState(false);
- const requestTimeline = ([...(collection.timeline || [])]).filter(obj => {
+ const requestTimeline = ([...(collection.timeline || [])]).filter((obj) => {
if (obj.itemUid === item.uid) return true;
});
@@ -93,15 +93,17 @@ const ResponsePane = ({ item, collection }) => {
return ;
}
case 'timeline': {
- return ;
+ return ;
}
case 'tests': {
- return ;
+ return (
+
+ );
}
default: {
@@ -183,7 +185,7 @@ const ResponsePane = ({ item, collection }) => {
/>
)}
- {focusedTab?.responsePaneTab === "timeline" ? (
+ {focusedTab?.responsePaneTab === 'timeline' ? (
) : (item?.response && !item?.response?.error) ? (
<>
@@ -201,7 +203,7 @@ const ResponsePane = ({ item, collection }) => {
) : null}
{
onClose={() => setShowScriptErrorCard(false)}
/>
)}
-
+
{!item?.response ? (
- focusedTab?.responsePaneTab === "timeline" && requestTimeline?.length ? (
+ focusedTab?.responsePaneTab === 'timeline' && requestTimeline?.length ? (
{
);
}
case 'tests': {
- return ;
+ return (
+
+ );
}
default: {
@@ -134,7 +136,7 @@ const ResponsePane = ({ rightPaneWidth, item, collection }) => {
onClose={() => setShowScriptErrorCard(false)}
/>
)}
-
+
{getTabPanel(selectedTab)}
diff --git a/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/StyledWrapper.jsx b/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/StyledWrapper.jsx
index d04cc68ba..a6d2315a4 100644
--- a/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/StyledWrapper.jsx
+++ b/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/StyledWrapper.jsx
@@ -1,7 +1,7 @@
import styled from 'styled-components';
const StyledWrapper = styled.div`
- background-color: ${props => props.theme.sidebar.bg};
+ background-color: ${(props) => props.theme.sidebar.bg};
height: 100%;
display: flex;
flex-direction: column;
@@ -13,7 +13,7 @@ const StyledWrapper = styled.div`
align-items: center;
justify-content: space-between;
padding: 1rem;
- border-bottom: 1px solid ${props => props.theme.sidebar.dragbar};
+ border-bottom: 1px solid ${(props) => props.theme.sidebar.dragbar};
margin-bottom: 0.5rem;
.counter {
@@ -33,7 +33,7 @@ const StyledWrapper = styled.div`
align-items: center;
gap: 0.25rem;
font-size: ${(props) => props.theme.font.size.base};
- color: ${props => props.theme.textLink};
+ color: ${(props) => props.theme.textLink};
background: none;
border: none;
padding: 0.25rem 0.5rem;
@@ -58,14 +58,14 @@ const StyledWrapper = styled.div`
}
&::-webkit-scrollbar-thumb {
- background-color: ${props => props.theme.console.scrollbarThumb};
+ background-color: ${(props) => props.theme.console.scrollbarThumb};
border-radius: 3px;
}
.loading-message,
.empty-message {
padding: 0.75rem;
- color: ${props => props.theme.colors.text.muted};
+ color: ${(props) => props.theme.colors.text.muted};
font-size: ${(props) => props.theme.font.size.base};
}
@@ -84,17 +84,17 @@ const StyledWrapper = styled.div`
position: relative;
height: 2.5rem;
border: 1px solid transparent;
- background-color: ${props => props.theme.sidebar.bg};
+ background-color: ${(props) => props.theme.sidebar.bg};
transition: transform 0.15s ease, background-color 0.15s ease, box-shadow 0.15s ease;
&.is-selected {
- background-color: ${props => props.theme.requestTabs.active.bg};
+ background-color: ${(props) => props.theme.requestTabs.active.bg};
}
&.is-dragging {
opacity: 0.5;
- background-color: ${props => props.theme.sidebar.bg};
- border: 1px dashed ${props => props.theme.sidebar.dragbar};
+ background-color: ${(props) => props.theme.sidebar.bg};
+ border: 1px dashed ${(props) => props.theme.sidebar.dragbar};
transform: scale(0.98);
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
z-index: 5;
@@ -107,7 +107,7 @@ const StyledWrapper = styled.div`
left: 0;
right: 0;
height: 2px;
- background: ${props => props.theme.dragAndDrop?.border || props.theme.textLink};
+ background: ${(props) => props.theme.dragAndDrop?.border || props.theme.textLink};
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease;
@@ -125,7 +125,7 @@ const StyledWrapper = styled.div`
&::before {
opacity: 1;
height: 2px;
- background: ${props => props.theme.dragAndDrop?.border || props.theme.textLink};
+ background: ${(props) => props.theme.dragAndDrop?.border || props.theme.textLink};
}
}
@@ -133,25 +133,25 @@ const StyledWrapper = styled.div`
&::after {
opacity: 1;
height: 2px;
- background: ${props => props.theme.dragAndDrop?.border || props.theme.textLink};
+ background: ${(props) => props.theme.dragAndDrop?.border || props.theme.textLink};
}
}
.drag-handle {
cursor: grab;
margin-right: 0.25rem;
- color: ${props => props.theme.sidebar.muted};
+ color: ${(props) => props.theme.sidebar.muted};
display: flex;
align-items: center;
transition: color 0.15s ease;
&:hover {
- color: ${props => props.theme.text};
+ color: ${(props) => props.theme.text};
}
&:active {
cursor: grabbing;
- color: ${props => props.theme.textLink};
+ color: ${(props) => props.theme.textLink};
}
}
@@ -162,7 +162,7 @@ const StyledWrapper = styled.div`
.checkbox {
width: 1rem;
height: 1rem;
- border: 1px solid ${props => props.theme.sidebar.dragbar};
+ border: 1px solid ${(props) => props.theme.sidebar.dragbar};
border-radius: 3px;
display: flex;
align-items: center;
@@ -170,7 +170,7 @@ const StyledWrapper = styled.div`
transition: all 0.1s ease;
&:hover {
- border-color: ${props => props.theme.textLink};
+ border-color: ${(props) => props.theme.textLink};
}
}
}
@@ -181,34 +181,34 @@ const StyledWrapper = styled.div`
font-weight: 500;
margin-right: 0.5rem;
min-width: 3rem;
- color: ${props => props.theme.sidebar.muted}; // Default color for unknown methods
+ color: ${(props) => props.theme.sidebar.muted}; // Default color for unknown methods
&.method-get {
- color: ${props => props.theme.request.methods.get};
+ color: ${(props) => props.theme.request.methods.get};
}
&.method-post {
- color: ${props => props.theme.request.methods.post};
+ color: ${(props) => props.theme.request.methods.post};
}
&.method-put {
- color: ${props => props.theme.request.methods.put};
+ color: ${(props) => props.theme.request.methods.put};
}
&.method-delete {
- color: ${props => props.theme.request.methods.delete};
+ color: ${(props) => props.theme.request.methods.delete};
}
&.method-patch {
- color: ${props => props.theme.request.methods.patch};
+ color: ${(props) => props.theme.request.methods.patch};
}
&.method-options {
- color: ${props => props.theme.request.methods.options};
+ color: ${(props) => props.theme.request.methods.options};
}
&.method-head {
- color: ${props => props.theme.request.methods.head};
+ color: ${(props) => props.theme.request.methods.head};
}
}
@@ -222,10 +222,10 @@ const StyledWrapper = styled.div`
.folder-path {
margin-left: 0.5rem;
font-size: ${(props) => props.theme.font.size.base};
- color: ${props => props.theme.sidebar.muted};
+ color: ${(props) => props.theme.sidebar.muted};
}
}
}
`;
-export default StyledWrapper;
\ No newline at end of file
+export default StyledWrapper;
diff --git a/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/index.jsx b/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/index.jsx
index aa3a3c9f0..bc4ed9fe6 100644
--- a/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/index.jsx
+++ b/packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/index.jsx
@@ -33,13 +33,13 @@ const RequestItem = ({ item, index, moveItem, isSelected, onSelect, onDrop }) =>
item: { uid: item.uid, name: item.name, request: item.request, index },
collect: (monitor) => ({ isDragging: monitor.isDragging() }),
options: {
- dropEffect: "move"
+ dropEffect: 'move'
},
end: (draggedItem, monitor) => {
if (monitor.didDrop()) {
onDrop();
}
- },
+ }
});
const [{ isOver, canDrop }, drop] = useDrop({
@@ -49,24 +49,24 @@ const RequestItem = ({ item, index, moveItem, isSelected, onSelect, onDrop }) =>
setDropType(null);
return;
}
-
+
const dropType = determineDropType(monitor);
setDropType(dropType);
},
drop: (draggedItem, monitor) => {
if (draggedItem.uid === item.uid) return;
-
+
const dropType = determineDropType(monitor);
let targetIndex = index;
-
+
if (dropType === 'below') {
targetIndex = index + 1;
}
-
+
if (draggedItem.index < targetIndex) {
targetIndex = targetIndex - 1;
}
-
+
moveItem(draggedItem.uid, targetIndex);
setDropType(null);
return { item: draggedItem };
@@ -74,7 +74,7 @@ const RequestItem = ({ item, index, moveItem, isSelected, onSelect, onDrop }) =>
collect: (monitor) => ({
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
- }),
+ })
});
useEffect(() => {
@@ -136,7 +136,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
const processItems = (items) => {
if (!items?.length) return;
- items.forEach(item => {
+ items.forEach((item) => {
if (isItemARequest(item) && !item.partial) {
const relativePath = path.relative(collection.pathname, path.dirname(item.pathname));
const folderPath = relativePath !== '.' ? relativePath : '';
@@ -167,9 +167,9 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
const savedConfiguration = get(collection, 'runnerConfiguration', null);
if (savedConfiguration?.requestItemsOrder?.length > 0) {
const orderedRequests = [];
- const requestMap = new Map(requests.map(req => [req.uid, req]));
+ const requestMap = new Map(requests.map((req) => [req.uid, req]));
- savedConfiguration.requestItemsOrder.forEach(uid => {
+ savedConfiguration.requestItemsOrder.forEach((uid) => {
const request = requestMap.get(uid);
if (request) {
orderedRequests.push(request);
@@ -177,7 +177,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
}
});
- requestMap.forEach(request => {
+ requestMap.forEach((request) => {
orderedRequests.push(request);
});
@@ -188,7 +188,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
setOriginalRequests(cloneDeep(requests));
} catch (error) {
- console.error("Error loading collection structure:", error);
+ console.error('Error loading collection structure:', error);
} finally {
setIsLoading(false);
}
@@ -196,7 +196,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
const moveItem = useCallback((draggedItemUid, hoverIndex) => {
setFlattenedRequests((prevRequests) => {
- const dragIndex = prevRequests.findIndex(item => item.uid === draggedItemUid);
+ const dragIndex = prevRequests.findIndex((item) => item.uid === draggedItemUid);
if (dragIndex === -1 || dragIndex === hoverIndex) {
return prevRequests;
@@ -213,12 +213,12 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
const handleDrop = useCallback(() => {
const selectedUids = new Set(selectedItems);
- setFlattenedRequests(currentRequests => {
+ setFlattenedRequests((currentRequests) => {
const newOrderedSelectedUids = currentRequests
- .filter(item => selectedUids.has(item.uid))
- .map(item => item.uid);
+ .filter((item) => selectedUids.has(item.uid))
+ .map((item) => item.uid);
- const allRequestUidsOrder = currentRequests.map(item => item.uid);
+ const allRequestUidsOrder = currentRequests.map((item) => item.uid);
setSelectedItems(newOrderedSelectedUids);
dispatch(updateRunnerConfiguration(collection.uid, newOrderedSelectedUids, allRequestUidsOrder));
@@ -230,32 +230,32 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
const handleRequestSelect = useCallback((item) => {
try {
if (selectedItems.includes(item.uid)) {
- const newSelectedUids = selectedItems.filter(uid => uid !== item.uid);
+ const newSelectedUids = selectedItems.filter((uid) => uid !== item.uid);
setSelectedItems(newSelectedUids);
-
- const allRequestUidsOrder = flattenedRequests.map(item => item.uid);
+
+ const allRequestUidsOrder = flattenedRequests.map((item) => item.uid);
dispatch(updateRunnerConfiguration(collection.uid, newSelectedUids, allRequestUidsOrder));
} else {
const newSelectedUids = [...selectedItems, item.uid];
const orderedSelectedUids = flattenedRequests
- .filter(req => newSelectedUids.includes(req.uid))
- .map(req => req.uid);
+ .filter((req) => newSelectedUids.includes(req.uid))
+ .map((req) => req.uid);
setSelectedItems(orderedSelectedUids);
- const allRequestUidsOrder = flattenedRequests.map(item => item.uid);
+ const allRequestUidsOrder = flattenedRequests.map((item) => item.uid);
dispatch(updateRunnerConfiguration(collection.uid, orderedSelectedUids, allRequestUidsOrder));
}
} catch (error) {
- console.error("Error selecting item:", error);
+ console.error('Error selecting item:', error);
}
}, [selectedItems, setSelectedItems, flattenedRequests, dispatch, collection.uid]);
const handleSelectAll = useCallback(() => {
try {
- const allRequestUidsOrder = flattenedRequests.map(item => item.uid);
-
+ const allRequestUidsOrder = flattenedRequests.map((item) => item.uid);
+
if (selectedItems.length === flattenedRequests.length) {
setSelectedItems([]);
dispatch(updateRunnerConfiguration(collection.uid, [], allRequestUidsOrder));
@@ -264,7 +264,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
dispatch(updateRunnerConfiguration(collection.uid, allRequestUidsOrder, allRequestUidsOrder));
}
} catch (error) {
- console.error("Error selecting/deselecting all items:", error);
+ console.error('Error selecting/deselecting all items:', error);
}
}, [flattenedRequests, selectedItems, setSelectedItems, dispatch, collection.uid]);
@@ -274,7 +274,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
setSelectedItems([]);
dispatch(updateRunnerConfiguration(collection.uid, [], []));
} catch (error) {
- console.error("Error resetting configuration:", error);
+ console.error('Error resetting configuration:', error);
}
}, [originalRequests, setSelectedItems, collection.uid, dispatch]);
@@ -286,7 +286,7 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
- {selectedItems.length === flattenedRequests.length ? "Deselect All" : "Select All"}
+ {selectedItems.length === flattenedRequests.length ? 'Deselect All' : 'Select All'}
@@ -324,4 +324,4 @@ const RunConfigurationPanel = ({ collection, selectedItems, setSelectedItems })
);
};
-export default RunConfigurationPanel;
\ No newline at end of file
+export default RunConfigurationPanel;
diff --git a/packages/bruno-app/src/components/RunnerResults/RunnerTags/index.jsx b/packages/bruno-app/src/components/RunnerResults/RunnerTags/index.jsx
index b61b5b9f6..959169d4f 100644
--- a/packages/bruno-app/src/components/RunnerResults/RunnerTags/index.jsx
+++ b/packages/bruno-app/src/components/RunnerResults/RunnerTags/index.jsx
@@ -8,7 +8,7 @@ const RunnerTags = ({ collectionUid, className = '' }) => {
const dispatch = useDispatch();
const collections = useSelector((state) => state.collections.collections);
const collection = cloneDeep(find(collections, (c) => c.uid === collectionUid));
-
+
// tags for the collection run
const tags = get(collection, 'runnerTags', { include: [], exclude: [] });
@@ -17,7 +17,7 @@ const RunnerTags = ({ collectionUid, className = '' }) => {
// all available tags in the collection that can be used for filtering
const availableTags = get(collection, 'allTags', []);
- const tagsHintList = availableTags.filter(t => !tags.exclude.includes(t) && !tags.include.includes(t));
+ const tagsHintList = availableTags.filter((t) => !tags.exclude.includes(t) && !tags.include.includes(t));
useEffect(() => {
dispatch(updateCollectionTagsList({ collectionUid }));
@@ -34,7 +34,7 @@ const RunnerTags = ({ collectionUid, className = '' }) => {
if (tags.exclude.includes(trimmedTag)) {
return 'tag is present in the exclude list!';
}
- }
+ };
const handleAddTag = ({ tag, to }) => {
const trimmedTag = tag.trim();
@@ -105,8 +105,8 @@ const RunnerTags = ({ collectionUid, className = '' }) => {
Included tags:
handleAddTag({ tag, to: 'include' })}
- handleRemoveTag={tag => handleRemoveTag({ tag, from: 'include' })}
+ handleAddTag={(tag) => handleAddTag({ tag, to: 'include' })}
+ handleRemoveTag={(tag) => handleRemoveTag({ tag, from: 'include' })}
tagsHintList={tagsHintList}
handleValidation={handleValidation}
/>
@@ -115,8 +115,8 @@ const RunnerTags = ({ collectionUid, className = '' }) => {
Excluded tags:
handleAddTag({ tag, to: 'exclude' })}
- handleRemoveTag={tag => handleRemoveTag({ tag, from: 'exclude' })}
+ handleAddTag={(tag) => handleAddTag({ tag, to: 'exclude' })}
+ handleRemoveTag={(tag) => handleRemoveTag({ tag, from: 'exclude' })}
tagsHintList={tagsHintList}
handleValidation={handleValidation}
/>
@@ -124,7 +124,7 @@ const RunnerTags = ({ collectionUid, className = '' }) => {
)}
- )
-}
+ );
+};
-export default RunnerTags;
\ No newline at end of file
+export default RunnerTags;
diff --git a/packages/bruno-app/src/components/RunnerResults/index.jsx b/packages/bruno-app/src/components/RunnerResults/index.jsx
index d1adc4df1..171c4bd98 100644
--- a/packages/bruno-app/src/components/RunnerResults/index.jsx
+++ b/packages/bruno-app/src/components/RunnerResults/index.jsx
@@ -24,19 +24,19 @@ const getTestStatus = (results) => {
};
const allTestsPassed = (item) => {
- return item.status !== 'error' &&
- item.testStatus === 'pass' &&
- item.assertionStatus === 'pass' &&
- item.preRequestTestStatus === 'pass' &&
- item.postResponseTestStatus === 'pass';
+ return item.status !== 'error'
+ && item.testStatus === 'pass'
+ && item.assertionStatus === 'pass'
+ && item.preRequestTestStatus === 'pass'
+ && item.postResponseTestStatus === 'pass';
};
const anyTestFailed = (item) => {
- return item.status === 'error' ||
- item.testStatus === 'fail' ||
- item.assertionStatus === 'fail' ||
- item.preRequestTestStatus === 'fail' ||
- item.postResponseTestStatus === 'fail';
+ return item.status === 'error'
+ || item.testStatus === 'fail'
+ || item.assertionStatus === 'fail'
+ || item.preRequestTestStatus === 'fail'
+ || item.postResponseTestStatus === 'fail';
};
// === Centralized filters definition ===
@@ -123,7 +123,7 @@ export default function RunnerResults({ collection }) {
filename: info.filename,
pathname: info.pathname,
displayName: getDisplayName(collection.pathname, info.pathname, info.name),
- tags: [...(info.request?.tags || [])].sort(),
+ tags: [...(info.request?.tags || [])].sort()
};
if (newItem.status !== 'error' && newItem.status !== 'skipped' && newItem.status !== 'running') {
newItem.testStatus = getTestStatus(newItem.testResults);
@@ -193,7 +193,7 @@ export default function RunnerResults({ collection }) {
}, [collection.runnerConfiguration, configureMode, delay]);
const ensureCollectionIsMounted = () => {
- if(collection.mountStatus === 'mounted'){
+ if (collection.mountStatus === 'mounted') {
return;
}
dispatch(mountCollection({
@@ -252,7 +252,7 @@ export default function RunnerResults({ collection }) {
};
useEffect(() => {
- if(tagsEnabled) {
+ if (tagsEnabled) {
setConfigureMode(false);
}
}, [tagsEnabled]);
@@ -283,7 +283,7 @@ export default function RunnerResults({ collection }) {
)}
- {isCollectionLoading ? Requests in this collection are still loading. : null}
+ {isCollectionLoading ? Requests in this collection are still loading. : null}
{/* Tags for the collection run */}
-
+
{/* Configure requests option */}
@@ -316,7 +316,7 @@ export default function RunnerResults({ collection }) {
-
+
{configureMode && selectedRequestItems.length > 0
? `Run ${selectedRequestItems.length} Selected Request${selectedRequestItems.length > 1 ? 's' : ''}`
- : "Run Collection"
- }
+ : 'Run Collection'}
@@ -405,7 +404,7 @@ export default function RunnerResults({ collection }) {
{tagsEnabled && areTagsAdded && (
Tags:
-
+
{tags.include.join(', ')}
@@ -415,10 +414,12 @@ export default function RunnerResults({ collection }) {
)}
- {runnerInfo?.statusText ?
-
- {runnerInfo?.statusText}
-
+ {runnerInfo?.statusText
+ ? (
+
+ {runnerInfo?.statusText}
+
+ )
: null}
{/* Items list */}
@@ -429,14 +430,14 @@ export default function RunnerResults({ collection }) {
- {allTestsPassed(item) ?
-
+ {allTestsPassed(item)
+ ?
: null}
- {item.status === 'skipped' ?
-
+ {item.status === 'skipped'
+ ?
: null}
- {anyTestFailed(item) ?
-
+ {anyTestFailed(item)
+ ?
: null}
{tagsEnabled && areTagsAdded && item?.tags?.length > 0 && (
- Tags: {item.tags.filter(t => tags.include.includes(t)).join(', ')}
+ Tags: {item.tags.filter((t) => tags.include.includes(t)).join(', ')}
)}
{item.status == 'error' ? {item.error} : null}
@@ -468,63 +469,63 @@ export default function RunnerResults({ collection }) {
{item.preRequestTestResults
? filterTestResults(item.preRequestTestResults).map((result) => (
- -
- {result.status === 'pass' ? (
-
-
- {result.description}
-
- ) : (
- <>
-
-
+
-
+ {result.status === 'pass' ? (
+
+
{result.description}
- {result.error}
- >
- )}
-
- ))
+ ) : (
+ <>
+
+
+ {result.description}
+
+ {result.error}
+ >
+ )}
+
+ ))
: null}
{item.postResponseTestResults
? filterTestResults(item.postResponseTestResults).map((result) => (
- -
- {result.status === 'pass' ? (
-
-
- {result.description}
-
- ) : (
- <>
-
-
+
-
+ {result.status === 'pass' ? (
+
+
{result.description}
- {result.error}
- >
- )}
-
- ))
+ ) : (
+ <>
+
+
+ {result.description}
+
+ {result.error}
+ >
+ )}
+
+ ))
: null}
{item.testResults
? filterTestResults(item.testResults).map((result) => (
- -
- {result.status === 'pass' ? (
-
-
- {result.description}
-
- ) : (
- <>
-
-
+
-
+ {result.status === 'pass' ? (
+
+
{result.description}
- {result.error}
- >
- )}
-
- ))
+ ) : (
+ <>
+
+
+ {result.description}
+
+ {result.error}
+ >
+ )}
+
+ ))
: null}
{filterTestResults(item.assertionResults).map((result) => (
-
diff --git a/packages/bruno-app/src/components/SecuritySettings/JsSandboxMode/index.js b/packages/bruno-app/src/components/SecuritySettings/JsSandboxMode/index.js
index c4ab2dbf2..9c7fb679c 100644
--- a/packages/bruno-app/src/components/SecuritySettings/JsSandboxMode/index.js
+++ b/packages/bruno-app/src/components/SecuritySettings/JsSandboxMode/index.js
@@ -20,7 +20,7 @@ const JsSandboxMode = ({ collection }) => {
};
return (
-
+
{jsSandboxMode === 'safe' && (
{
{
The collection might include JavaScript code in Variables, Scripts, Tests, and Assertions.
-
+
Please choose the security level for the JavaScript code execution.
@@ -78,7 +78,7 @@ const JsSandboxModeModal = ({ collection }) => {
/>
Developer Mode
- (use only if you trust the authors of the collection)
+ (use only if you trust the authors of the collection)
diff --git a/packages/bruno-app/src/components/SecuritySettings/index.js b/packages/bruno-app/src/components/SecuritySettings/index.js
index cf8d44df1..ed518ba77 100644
--- a/packages/bruno-app/src/components/SecuritySettings/index.js
+++ b/packages/bruno-app/src/components/SecuritySettings/index.js
@@ -28,8 +28,8 @@ const SecuritySettings = ({ collection }) => {
JavaScript Sandbox
-
- The collection might include JavaScript code in Variables, Scripts, Tests, and Assertions.
+
+ The collection might include JavaScript code in Variables, Scripts, Tests, and Assertions.
@@ -64,7 +64,7 @@ const SecuritySettings = ({ collection }) => {
/>
Developer Mode
- (use only if you trust the authors of the collection)
+ (use only if you trust the authors of the collection)
diff --git a/packages/bruno-app/src/components/SensitiveFieldWarning/StyledWrapper.js b/packages/bruno-app/src/components/SensitiveFieldWarning/StyledWrapper.js
index ab1ff4424..4c62b6001 100644
--- a/packages/bruno-app/src/components/SensitiveFieldWarning/StyledWrapper.js
+++ b/packages/bruno-app/src/components/SensitiveFieldWarning/StyledWrapper.js
@@ -7,4 +7,4 @@ const Wrapper = styled.div`
}
`;
-export default Wrapper;
\ No newline at end of file
+export default Wrapper;
diff --git a/packages/bruno-app/src/components/SensitiveFieldWarning/index.js b/packages/bruno-app/src/components/SensitiveFieldWarning/index.js
index 2b2cce326..4e242ea9d 100644
--- a/packages/bruno-app/src/components/SensitiveFieldWarning/index.js
+++ b/packages/bruno-app/src/components/SensitiveFieldWarning/index.js
@@ -13,13 +13,13 @@ const SensitiveFieldWarning = ({ fieldName, warningMessage }) => {
{warningMessage}
- }
+ )}
/>
diff --git a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CloneCollection/index.js b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CloneCollection/index.js
index 4cd9af13f..043217467 100644
--- a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CloneCollection/index.js
+++ b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CloneCollection/index.js
@@ -10,7 +10,7 @@ import { sanitizeName, validateName, validateNameError } from 'utils/common/rege
import Help from 'components/Help';
import PathDisplay from 'components/PathDisplay';
import { useState } from 'react';
-import { IconArrowBackUp, IconEdit } from "@tabler/icons";
+import { IconArrowBackUp, IconEdit } from '@tabler/icons';
import { findCollectionByUid } from 'utils/collections/index';
import get from 'lodash/get';
@@ -18,7 +18,7 @@ const CloneCollection = ({ onClose, collectionUid }) => {
const inputRef = useRef();
const dispatch = useDispatch();
const [isEditing, toggleEditing] = useState(false);
- const collection = useSelector(state => findCollectionByUid(state.collections.collections, collectionUid));
+ const collection = useSelector((state) => findCollectionByUid(state.collections.collections, collectionUid));
const preferences = useSelector((state) => state.app.preferences);
const defaultLocation = get(preferences, 'general.defaultCollectionLocation', '');
const { name } = collection;
@@ -38,7 +38,7 @@ const CloneCollection = ({ onClose, collectionUid }) => {
collectionFolderName: Yup.string()
.min(1, 'must be at least 1 character')
.max(255, 'must be 255 characters or less')
- .test('is-valid-collection-name', function(value) {
+ .test('is-valid-collection-name', function (value) {
const isValid = validateName(value);
return isValid ? true : this.createError({ message: validateNameError(value) });
})
@@ -86,7 +86,7 @@ const CloneCollection = ({ onClose, collectionUid }) => {
return (
- |
diff --git a/packages/bruno-app/src/components/TagList/StyledWrapper.js b/packages/bruno-app/src/components/TagList/StyledWrapper.js
index 8eab4d965..2aa48f248 100644
--- a/packages/bruno-app/src/components/TagList/StyledWrapper.js
+++ b/packages/bruno-app/src/components/TagList/StyledWrapper.js
@@ -134,4 +134,4 @@ const StyledWrapper = styled.div`
}
`;
-export default StyledWrapper;
\ No newline at end of file
+export default StyledWrapper;
diff --git a/packages/bruno-app/src/components/TagList/index.js b/packages/bruno-app/src/components/TagList/index.js
index 1b800a6a0..94403225d 100644
--- a/packages/bruno-app/src/components/TagList/index.js
+++ b/packages/bruno-app/src/components/TagList/index.js
@@ -51,7 +51,7 @@ const TagList = ({ tagsHintList = [], handleAddTag, tags, handleRemoveTag, onSav
onSave={onSave}
data-testid="tag-input"
/>
- {error && {error}}
+ {error && {error}}
{tags && tags.length
? tags.map((_tag) => (
diff --git a/packages/bruno-app/src/components/ToggleSwitch/StyledWrapper.js b/packages/bruno-app/src/components/ToggleSwitch/StyledWrapper.js
index cf6bb9e92..1fbb0aeb5 100644
--- a/packages/bruno-app/src/components/ToggleSwitch/StyledWrapper.js
+++ b/packages/bruno-app/src/components/ToggleSwitch/StyledWrapper.js
@@ -2,11 +2,11 @@ import styled from 'styled-components';
const switchSizes = {
'2xs': { width: 32, height: 16, buttonSize: 14 },
- xs: { width: 40, height: 20, buttonSize: 18 },
- s: { width: 44, height: 22, buttonSize: 20 },
- m: { width: 50, height: 24, buttonSize: 22 }, // default size
- l: { width: 56, height: 28, buttonSize: 26 },
- xl: { width: 64, height: 32, buttonSize: 30 },
+ 'xs': { width: 40, height: 20, buttonSize: 18 },
+ 's': { width: 44, height: 22, buttonSize: 20 },
+ 'm': { width: 50, height: 24, buttonSize: 22 }, // default size
+ 'l': { width: 56, height: 28, buttonSize: 26 },
+ 'xl': { width: 64, height: 32, buttonSize: 30 },
'2xl': { width: 72, height: 36, buttonSize: 34 }
};
diff --git a/packages/bruno-app/src/hooks/useFocusTrap/index.js b/packages/bruno-app/src/hooks/useFocusTrap/index.js
index 760603d21..f4fd0577f 100644
--- a/packages/bruno-app/src/hooks/useFocusTrap/index.js
+++ b/packages/bruno-app/src/hooks/useFocusTrap/index.js
@@ -1,20 +1,19 @@
import { useEffect, useRef } from 'react';
const useFocusTrap = (modalRef) => {
-
// refer to this implementation for modal focus: https://stackoverflow.com/a/38865836
const focusableSelector = 'a[href], area[href], input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex]:not([tabindex="-1"]), *[contenteditable]';
-
+
useEffect(() => {
const modalElement = modalRef.current;
if (!modalElement) return;
const focusableElements = Array.from(document.querySelectorAll(focusableSelector));
const modalFocusableElements = Array.from(modalElement.querySelectorAll(focusableSelector));
- const elementsToHide = focusableElements.filter(el => !modalFocusableElements.includes(el));
+ const elementsToHide = focusableElements.filter((el) => !modalFocusableElements.includes(el));
// Hide elements outside the modal
- elementsToHide.forEach(el => {
+ elementsToHide.forEach((el) => {
const originalTabIndex = el.getAttribute('tabindex');
el.setAttribute('data-tabindex', originalTabIndex || 'inline');
el.setAttribute('tabindex', -1);
@@ -42,7 +41,7 @@ const useFocusTrap = (modalRef) => {
modalElement.removeEventListener('keydown', handleKeyDown);
// Restore original tabindex values
- elementsToHide.forEach(el => {
+ elementsToHide.forEach((el) => {
const originalTabIndex = el.getAttribute('data-tabindex');
el.setAttribute('tabindex', originalTabIndex === 'inline' ? '' : originalTabIndex);
});
diff --git a/packages/bruno-app/src/hooks/usePrevious/index.js b/packages/bruno-app/src/hooks/usePrevious/index.js
index 41a072238..c71547858 100644
--- a/packages/bruno-app/src/hooks/usePrevious/index.js
+++ b/packages/bruno-app/src/hooks/usePrevious/index.js
@@ -4,10 +4,10 @@ function usePrevious(value) {
const ref = useRef();
useEffect(() => {
- ref.current = value; //assign the value of ref to the argument
- }, [value]); //this code will run when the value of 'value' changes
+ ref.current = value; // assign the value of ref to the argument
+ }, [value]); // this code will run when the value of 'value' changes
- return ref.current; //in the end, return the current ref value.
+ return ref.current; // in the end, return the current ref value.
}
export default usePrevious;
diff --git a/packages/bruno-app/src/i18n/index.js b/packages/bruno-app/src/i18n/index.js
index 26e89695f..0696d740c 100644
--- a/packages/bruno-app/src/i18n/index.js
+++ b/packages/bruno-app/src/i18n/index.js
@@ -4,8 +4,8 @@ import translationEn from './translation/en.json';
const resources = {
en: {
- translation: translationEn,
- },
+ translation: translationEn
+ }
};
i18n
diff --git a/packages/bruno-app/src/pages/Bruno/index.js b/packages/bruno-app/src/pages/Bruno/index.js
index 0a4002640..8e5f8b944 100644
--- a/packages/bruno-app/src/pages/Bruno/index.js
+++ b/packages/bruno-app/src/pages/Bruno/index.js
@@ -106,26 +106,26 @@ export default function Main() {
data-app-state="loading"
style={{
height: isConsoleOpen ? `calc(100vh - 22px - ${isConsoleOpen ? '300px' : '0px'})` : 'calc(100vh - 22px)'
- }}
- >
-
-
-
- {showHomePage ? (
-
- ) : (
- <>
-
-
- >
- )}
-
-
-
-
-
-
+ }}
+ >
+
+
+
+ {showHomePage ? (
+
+ ) : (
+ <>
+
+
+ >
+ )}
+
+
+
+
+
+
//
);
}
diff --git a/packages/bruno-app/src/pages/ErrorBoundary/index.js b/packages/bruno-app/src/pages/ErrorBoundary/index.js
index 9a9ccb151..944cb5d9d 100644
--- a/packages/bruno-app/src/pages/ErrorBoundary/index.js
+++ b/packages/bruno-app/src/pages/ErrorBoundary/index.js
@@ -8,12 +8,14 @@ class ErrorBoundary extends React.Component {
this.state = { hasError: false };
}
+
componentDidMount() {
// Add a global error event listener to capture client-side errors
window.onerror = (message, source, lineno, colno, error) => {
this.setState({ hasError: true, error });
};
}
+
componentDidCatch(error, errorInfo) {
console.log({ error, errorInfo });
this.setState({ hasError: true, error, errorInfo });
diff --git a/packages/bruno-app/src/providers/App/index.js b/packages/bruno-app/src/providers/App/index.js
index 8c7d2a4e4..2fa3edd85 100644
--- a/packages/bruno-app/src/providers/App/index.js
+++ b/packages/bruno-app/src/providers/App/index.js
@@ -21,7 +21,7 @@ export const AppProvider = (props) => {
useEffect(() => {
const platform = get(navigator, 'platform', '');
- if(platform && platform.toLowerCase().indexOf('mac') > -1) {
+ if (platform && platform.toLowerCase().indexOf('mac') > -1) {
document.body.classList.add('os-mac');
}
}, []);
diff --git a/packages/bruno-app/src/providers/Hotkeys/index.js b/packages/bruno-app/src/providers/Hotkeys/index.js
index 48f1b6e90..841dc200a 100644
--- a/packages/bruno-app/src/providers/Hotkeys/index.js
+++ b/packages/bruno-app/src/providers/Hotkeys/index.js
@@ -82,19 +82,18 @@ export const HotkeysProvider = (props) => {
if (collection) {
const item = findItemInCollection(collection, activeTab.uid);
if (item) {
-
- if(item.type === 'grpc-request') {
+ if (item.type === 'grpc-request') {
const request = item.draft ? item.draft.request : item.request;
- if(!request.url) {
+ if (!request.url) {
toast.error('Please enter a valid gRPC server URL');
return;
}
- if(!request.method) {
+ if (!request.method) {
toast.error('Please select a gRPC method');
return;
}
}
-
+
dispatch(sendRequest(item, collection.uid)).catch((err) =>
toast.custom((t) => toast.dismiss(t.id)} />, {
duration: 5000
diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/middleware.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/middleware.js
index a21b21768..a0f8b185c 100644
--- a/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/middleware.js
+++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/middleware.js
@@ -1,4 +1,4 @@
-import { handleMakeTabParmanent } from "./utils";
+import { handleMakeTabParmanent } from './utils';
const actionsToIntercept = [
// Request-level actions
diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/utils.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/utils.js
index ede864893..fffedc088 100644
--- a/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/utils.js
+++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/draft/utils.js
@@ -1,5 +1,5 @@
-import { makeTabPermanent } from "providers/ReduxStore/slices/tabs";
-import { findCollectionByUid, findItemInCollection } from "utils/collections/index";
+import { makeTabPermanent } from 'providers/ReduxStore/slices/tabs';
+import { findCollectionByUid, findItemInCollection } from 'utils/collections/index';
import find from 'lodash/find';
function handleMakeTabParmanent(state, action, dispatch) {
@@ -24,9 +24,7 @@ function handleMakeTabParmanent(state, action, dispatch) {
if (item) {
dispatch(makeTabPermanent({ uid: itemUid }));
}
- }
- // Handle folder-level changes (folder settings tab)
- else if (folderUid) {
+ } else if (folderUid) { // Handle folder-level changes (folder settings tab)
const folder = findItemInCollection(collection, folderUid);
if (folder) {
dispatch(makeTabPermanent({ uid: folderUid }));
@@ -39,4 +37,4 @@ function handleMakeTabParmanent(state, action, dispatch) {
export {
handleMakeTabParmanent
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js b/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
index 6346bf9dc..2228c5ec0 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js
@@ -589,7 +589,7 @@ export const sendRequest = (item, collectionUid) => (dispatch, getState) => {
})
.then(resolve)
.catch((err) => {
- if (err && err.message === "Error invoking remote method 'send-http-request': Error: Request cancelled") {
+ if (err && err.message === 'Error invoking remote method \'send-http-request\': Error: Request cancelled') {
dispatch(
responseReceived({
itemUid,
@@ -637,8 +637,8 @@ export const cancelRunnerExecution = (cancelTokenUid) => (dispatch) => {
cancelNetworkRequest(cancelTokenUid).catch((err) => console.log(err));
};
-export const runCollectionFolder =
- (collectionUid, folderUid, recursive, delay, tags, selectedRequestUids) => (dispatch, getState) => {
+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);
@@ -793,68 +793,68 @@ export const newFolder = (folderName, directoryName, collectionUid, itemUid) =>
});
};
-export const renameItem =
- ({ newName, newFilename, itemUid, collectionUid }) =>
- (dispatch, getState) => {
- const state = getState();
- const collection = findCollectionByUid(state.collections.collections, collectionUid);
+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 new Promise((resolve, reject) => {
+ if (!collection) {
+ return reject(new Error('Collection not found'));
}
- return ipcRenderer
- .invoke('renderer:rename-item-filename', { oldPath: item.pathname, newPath, newName, newFilename, collectionPathname: collection.pathname })
- .catch((err) => {
- toast.error('Failed to rename the file');
+ 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 file');
+ throw new Error('Failed to rename the item name');
});
- };
+ };
- let renameOperation = null;
- if (newName) renameOperation = renameName;
- if (newFilename) renameOperation = renameFile;
+ 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);
+ }
- if (!renameOperation) {
- resolve();
- }
+ return ipcRenderer
+ .invoke('renderer:rename-item-filename', { oldPath: item.pathname, newPath, newName, newFilename, collectionPathname: collection.pathname })
+ .catch((err) => {
+ toast.error('Failed to rename the file');
+ console.error(err);
+ throw new Error('Failed to rename the file');
+ });
+ };
- renameOperation()
- .then(() => {
- toast.success('Item renamed successfully');
+ let renameOperation = null;
+ if (newName) renameOperation = renameName;
+ if (newFilename) renameOperation = renameFile;
+
+ if (!renameOperation) {
resolve();
- })
- .catch((err) => reject(err));
- });
- };
+ }
+
+ renameOperation()
+ .then(() => {
+ toast.success('Item renamed successfully');
+ resolve();
+ })
+ .catch((err) => reject(err));
+ });
+ };
export const cloneItem = (newName, newFilename, itemUid, collectionUid) => (dispatch, getState) => {
const state = getState();
@@ -1088,140 +1088,140 @@ export const sortCollections = (payload) => (dispatch) => {
dispatch(_sortCollections(payload));
};
-export const moveItem =
- ({ targetDirname, sourcePathname }) =>
- (dispatch, getState) => {
- return new Promise((resolve, reject) => {
- const { ipcRenderer } = window;
+export const moveItem
+ = ({ targetDirname, sourcePathname }) =>
+ (dispatch, getState) => {
+ return new Promise((resolve, reject) => {
+ const { ipcRenderer } = window;
- ipcRenderer.invoke('renderer:move-item', { targetDirname, sourcePathname }).then(resolve).catch(reject);
- });
- };
+ ipcRenderer.invoke('renderer:move-item', { targetDirname, sourcePathname }).then(resolve).catch(reject);
+ });
+ };
-export const handleCollectionItemDrop =
- ({ targetItem, draggedItem, dropType, collectionUid }) =>
- (dispatch, getState) => {
- const state = getState();
- const collection = findCollectionByUid(state.collections.collections, collectionUid);
- // if its withincollection set the source to current collection,
- // if its cross collection set the source to the source collection
- const sourceCollectionUid = draggedItem.sourceCollectionUid
- const isCrossCollectionMove = sourceCollectionUid && collectionUid !== sourceCollectionUid;
- const sourceCollection = isCrossCollectionMove ? findCollectionByUid(state.collections.collections, sourceCollectionUid) : collection;
- const { uid: draggedItemUid, pathname: draggedItemPathname } = draggedItem;
- const { uid: targetItemUid, pathname: targetItemPathname } = targetItem;
- const targetItemDirectory = findParentItemInCollection(collection, targetItemUid) || collection;
- const targetItemDirectoryItems = cloneDeep(targetItemDirectory.items);
- const draggedItemDirectory = findParentItemInCollection(sourceCollection, draggedItemUid) || sourceCollection;
- const draggedItemDirectoryItems = cloneDeep(draggedItemDirectory.items);
+export const handleCollectionItemDrop
+ = ({ targetItem, draggedItem, dropType, collectionUid }) =>
+ (dispatch, getState) => {
+ const state = getState();
+ const collection = findCollectionByUid(state.collections.collections, collectionUid);
+ // if its withincollection set the source to current collection,
+ // if its cross collection set the source to the source collection
+ const sourceCollectionUid = draggedItem.sourceCollectionUid;
+ const isCrossCollectionMove = sourceCollectionUid && collectionUid !== sourceCollectionUid;
+ const sourceCollection = isCrossCollectionMove ? findCollectionByUid(state.collections.collections, sourceCollectionUid) : collection;
+ const { uid: draggedItemUid, pathname: draggedItemPathname } = draggedItem;
+ const { uid: targetItemUid, pathname: targetItemPathname } = targetItem;
+ const targetItemDirectory = findParentItemInCollection(collection, targetItemUid) || collection;
+ const targetItemDirectoryItems = cloneDeep(targetItemDirectory.items);
+ const draggedItemDirectory = findParentItemInCollection(sourceCollection, draggedItemUid) || sourceCollection;
+ const draggedItemDirectoryItems = cloneDeep(draggedItemDirectory.items);
- const handleMoveToNewLocation = async ({
- draggedItem,
- draggedItemDirectoryItems,
- targetItem,
- targetItemDirectoryItems,
- newPathname,
- dropType
- }) => {
- const { uid: targetItemUid } = targetItem;
- const { pathname: draggedItemPathname, uid: draggedItemUid } = draggedItem;
+ const handleMoveToNewLocation = async ({
+ draggedItem,
+ draggedItemDirectoryItems,
+ targetItem,
+ targetItemDirectoryItems,
+ newPathname,
+ dropType
+ }) => {
+ const { uid: targetItemUid } = targetItem;
+ const { pathname: draggedItemPathname, uid: draggedItemUid } = draggedItem;
- const newDirname = path.dirname(newPathname);
- await dispatch(
- moveItem({
- targetDirname: newDirname,
- sourcePathname: draggedItemPathname
- })
- );
-
- // Update sequences in the source directory
- if (draggedItemDirectoryItems?.length) {
- // reorder items in the source directory
- const draggedItemDirectoryItemsWithoutDraggedItem = draggedItemDirectoryItems.filter(
- (i) => i.uid !== draggedItemUid
+ const newDirname = path.dirname(newPathname);
+ await dispatch(
+ moveItem({
+ targetDirname: newDirname,
+ sourcePathname: draggedItemPathname
+ })
);
- const reorderedSourceItems = getReorderedItemsInSourceDirectory({
- items: draggedItemDirectoryItemsWithoutDraggedItem
- });
- if (reorderedSourceItems?.length) {
+
+ // Update sequences in the source directory
+ if (draggedItemDirectoryItems?.length) {
+ // reorder items in the source directory
+ const draggedItemDirectoryItemsWithoutDraggedItem = draggedItemDirectoryItems.filter(
+ (i) => i.uid !== draggedItemUid
+ );
+ const reorderedSourceItems = getReorderedItemsInSourceDirectory({
+ items: draggedItemDirectoryItemsWithoutDraggedItem
+ });
+ if (reorderedSourceItems?.length) {
await dispatch(updateItemsSequences({ itemsToResequence: reorderedSourceItems, collectionUid: sourceCollectionUid || collectionUid }));
+ }
}
- }
- // Update sequences in the target directory (if dropping adjacent)
- if (dropType === 'adjacent') {
- const targetItemSequence = targetItemDirectoryItems.findIndex((i) => i.uid === targetItemUid)?.seq;
+ // Update sequences in the target directory (if dropping adjacent)
+ if (dropType === 'adjacent') {
+ const targetItemSequence = targetItemDirectoryItems.findIndex((i) => i.uid === targetItemUid)?.seq;
- const draggedItemWithNewPathAndSequence = {
- ...draggedItem,
- pathname: newPathname,
- seq: targetItemSequence
- };
+ const draggedItemWithNewPathAndSequence = {
+ ...draggedItem,
+ pathname: newPathname,
+ seq: targetItemSequence
+ };
- // draggedItem is added to the targetItem's directory
- const reorderedTargetItems = getReorderedItemsInTargetDirectory({
- items: [...targetItemDirectoryItems, draggedItemWithNewPathAndSequence],
+ // draggedItem is added to the targetItem's directory
+ const reorderedTargetItems = getReorderedItemsInTargetDirectory({
+ items: [...targetItemDirectoryItems, draggedItemWithNewPathAndSequence],
+ targetItemUid,
+ draggedItemUid
+ });
+
+ if (reorderedTargetItems?.length) {
+ await dispatch(updateItemsSequences({ itemsToResequence: reorderedTargetItems, collectionUid }));
+ }
+ }
+ };
+
+ const handleReorderInSameLocation = async ({ draggedItem, targetItem, targetItemDirectoryItems }) => {
+ const { uid: targetItemUid } = targetItem;
+ const { uid: draggedItemUid } = draggedItem;
+
+ // reorder items in the targetItem's directory
+ const reorderedItems = getReorderedItemsInTargetDirectory({
+ items: targetItemDirectoryItems,
targetItemUid,
draggedItemUid
});
- if (reorderedTargetItems?.length) {
- await dispatch(updateItemsSequences({ itemsToResequence: reorderedTargetItems, collectionUid }));
- }
- }
- };
-
- const handleReorderInSameLocation = async ({ draggedItem, targetItem, targetItemDirectoryItems }) => {
- const { uid: targetItemUid } = targetItem;
- const { uid: draggedItemUid } = draggedItem;
-
- // reorder items in the targetItem's directory
- const reorderedItems = getReorderedItemsInTargetDirectory({
- items: targetItemDirectoryItems,
- targetItemUid,
- draggedItemUid
- });
-
- if (reorderedItems?.length) {
+ if (reorderedItems?.length) {
await dispatch(updateItemsSequences({ itemsToResequence: reorderedItems, collectionUid }));
- }
+ }
+ };
+
+ return new Promise(async (resolve, reject) => {
+ try {
+ const newPathname = calculateDraggedItemNewPathname({
+ draggedItem,
+ targetItem,
+ dropType,
+ collectionPathname: collection.pathname
+ });
+ if (!newPathname) return;
+ if (targetItemPathname?.startsWith(draggedItemPathname)) return;
+ if (newPathname !== draggedItemPathname) {
+ await handleMoveToNewLocation({
+ targetItem,
+ targetItemDirectoryItems,
+ draggedItem,
+ draggedItemDirectoryItems,
+ newPathname,
+ dropType
+ });
+ } else {
+ await handleReorderInSameLocation({ draggedItem, targetItemDirectoryItems, targetItem });
+ }
+ resolve();
+ } catch (error) {
+ console.error(error);
+ toast.error(error?.message);
+ reject(error);
+ }
+ });
};
- return new Promise(async (resolve, reject) => {
- try {
- const newPathname = calculateDraggedItemNewPathname({
- draggedItem,
- targetItem,
- dropType,
- collectionPathname: collection.pathname
- });
- if (!newPathname) return;
- if (targetItemPathname?.startsWith(draggedItemPathname)) return;
- if (newPathname !== draggedItemPathname) {
- await handleMoveToNewLocation({
- targetItem,
- targetItemDirectoryItems,
- draggedItem,
- draggedItemDirectoryItems,
- newPathname,
- dropType
- });
- } else {
- await handleReorderInSameLocation({ draggedItem, targetItemDirectoryItems, targetItem });
- }
- resolve();
- } catch (error) {
- console.error(error);
- toast.error(error?.message);
- reject(error);
- }
- });
- };
-
-export const updateItemsSequences =
- ({ itemsToResequence, collectionUid }) =>
- (dispatch, getState) => {
- return new Promise((resolve, reject) => {
+export const updateItemsSequences
+ = ({ itemsToResequence, collectionUid }) =>
+ (dispatch, getState) => {
+ return new Promise((resolve, reject) => {
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
@@ -1229,11 +1229,11 @@ export const updateItemsSequences =
return reject(new Error('Collection not found'));
}
- const { ipcRenderer } = window;
+ const { ipcRenderer } = window;
ipcRenderer.invoke('renderer:resequence-items', itemsToResequence, collection.pathname).then(resolve).catch(reject);
- });
- };
+ });
+ };
export const newHttpRequest = (params) => (dispatch, getState) => {
const {
@@ -2038,52 +2038,52 @@ export const mergeAndPersistEnvironment
const state = getState();
const collection = findCollectionByUid(state.collections.collections, collectionUid);
- if (!collection) {
- return reject(new Error('Collection not found'));
- }
-
- const environmentUid = collection.activeEnvironmentUid;
- if (!environmentUid) {
- return reject(new Error('No active environment found'));
- }
-
- const collectionCopy = cloneDeep(collection);
- const environment = findEnvironmentInCollection(collectionCopy, environmentUid);
- if (!environment) {
- return reject(new Error('Environment not found'));
- }
-
- // Only proceed if there are persistent variables to save
- if (!persistentEnvVariables || Object.keys(persistentEnvVariables).length === 0) {
- return resolve();
- }
-
- let existingVars = environment.variables || [];
-
- let normalizedNewVars = Object.entries(persistentEnvVariables).map(([name, value]) => ({
- uid: uuid(),
- name,
- value,
- type: 'text',
- enabled: true,
- secret: false
- }));
-
- const merged = existingVars.map((v) => {
- const found = normalizedNewVars.find((nv) => nv.name === v.name);
- if (found) {
- return { ...v, value: found.value };
+ if (!collection) {
+ return reject(new Error('Collection not found'));
}
- return v;
- });
- normalizedNewVars.forEach((nv) => {
- if (!merged.some((v) => v.name === nv.name)) {
- merged.push(nv);
+
+ const environmentUid = collection.activeEnvironmentUid;
+ if (!environmentUid) {
+ return reject(new Error('No active environment found'));
}
- });
+
+ const collectionCopy = cloneDeep(collection);
+ const environment = findEnvironmentInCollection(collectionCopy, environmentUid);
+ if (!environment) {
+ return reject(new Error('Environment not found'));
+ }
+
+ // Only proceed if there are persistent variables to save
+ if (!persistentEnvVariables || Object.keys(persistentEnvVariables).length === 0) {
+ return resolve();
+ }
+
+ let existingVars = environment.variables || [];
+
+ let normalizedNewVars = Object.entries(persistentEnvVariables).map(([name, value]) => ({
+ uid: uuid(),
+ name,
+ value,
+ type: 'text',
+ enabled: true,
+ secret: false
+ }));
+
+ const merged = existingVars.map((v) => {
+ const found = normalizedNewVars.find((nv) => nv.name === v.name);
+ if (found) {
+ return { ...v, value: found.value };
+ }
+ return v;
+ });
+ normalizedNewVars.forEach((nv) => {
+ if (!merged.some((v) => v.name === nv.name)) {
+ merged.push(nv);
+ }
+ });
// Save all non-ephemeral vars and all variables that were previously persisted
- const persistedNames = new Set(Object.keys(persistentEnvVariables));
+ const persistedNames = new Set(Object.keys(persistentEnvVariables));
// Add all existing non-ephemeral variables to persistedNames so they are preserved
existingVars.forEach((v) => {
@@ -2092,17 +2092,17 @@ export const mergeAndPersistEnvironment
}
});
- const environmentToSave = cloneDeep(environment);
- environmentToSave.variables = buildPersistedEnvVariables(merged, { mode: 'merge', persistedNames });
+ const environmentToSave = cloneDeep(environment);
+ environmentToSave.variables = buildPersistedEnvVariables(merged, { mode: 'merge', persistedNames });
- const { ipcRenderer } = window;
- environmentSchema
- .validate(environmentToSave)
- .then(() => ipcRenderer.invoke('renderer:save-environment', collection.pathname, environmentToSave))
- .then(resolve)
- .catch(reject);
- });
- };
+ const { ipcRenderer } = window;
+ environmentSchema
+ .validate(environmentToSave)
+ .then(() => ipcRenderer.invoke('renderer:save-environment', collection.pathname, environmentToSave))
+ .then(resolve)
+ .catch(reject);
+ });
+ };
export const selectEnvironment = (environmentUid, collectionUid) => (dispatch, getState) => {
return new Promise((resolve, reject) => {
@@ -2325,20 +2325,20 @@ export const importCollection = (collection, collectionLocation) => (dispatch, g
});
};
-export const moveCollectionAndPersist =
- ({ draggedItem, targetItem }) =>
- (dispatch, getState) => {
- dispatch(moveCollection({ draggedItem, targetItem }));
+export const moveCollectionAndPersist
+ = ({ draggedItem, targetItem }) =>
+ (dispatch, getState) => {
+ dispatch(moveCollection({ draggedItem, targetItem }));
- return new Promise((resolve, reject) => {
- const { ipcRenderer } = window;
- const state = getState();
+ return new Promise((resolve, reject) => {
+ const { ipcRenderer } = window;
+ const state = getState();
- const collectionPaths = state.collections.collections.map((collection) => collection.pathname);
+ const collectionPaths = state.collections.collections.map((collection) => collection.pathname);
- ipcRenderer.invoke('renderer:update-collection-paths', collectionPaths).then(resolve).catch(reject);
- });
- };
+ ipcRenderer.invoke('renderer:update-collection-paths', collectionPaths).then(resolve).catch(reject);
+ });
+ };
export const saveCollectionSecurityConfig = (collectionUid, securityConfig) => (dispatch, getState) => {
return new Promise((resolve, reject) => {
@@ -2457,48 +2457,48 @@ export const clearOauth2Cache = (payload) => async (dispatch, getState) => {
};
// todo: could be removed
-export const loadRequestViaWorker =
- ({ collectionUid, pathname }) =>
- (dispatch, getState) => {
- return new Promise(async (resolve, reject) => {
- const { ipcRenderer } = window;
- ipcRenderer.invoke('renderer:load-request-via-worker', { collectionUid, pathname }).then(resolve).catch(reject);
- });
- };
+export const loadRequestViaWorker
+ = ({ collectionUid, pathname }) =>
+ (dispatch, getState) => {
+ return new Promise(async (resolve, reject) => {
+ const { ipcRenderer } = window;
+ ipcRenderer.invoke('renderer:load-request-via-worker', { collectionUid, pathname }).then(resolve).catch(reject);
+ });
+ };
// todo: could be removed
-export const loadRequest =
- ({ collectionUid, pathname }) =>
- (dispatch, getState) => {
- return new Promise(async (resolve, reject) => {
- const { ipcRenderer } = window;
- ipcRenderer.invoke('renderer:load-request', { collectionUid, pathname }).then(resolve).catch(reject);
- });
- };
+export const loadRequest
+ = ({ collectionUid, pathname }) =>
+ (dispatch, getState) => {
+ return new Promise(async (resolve, reject) => {
+ const { ipcRenderer } = window;
+ ipcRenderer.invoke('renderer:load-request', { collectionUid, pathname }).then(resolve).catch(reject);
+ });
+ };
-export const loadLargeRequest =
- ({ collectionUid, pathname }) =>
- (dispatch, getState) => {
- return new Promise(async (resolve, reject) => {
- const { ipcRenderer } = window;
- ipcRenderer.invoke('renderer:load-large-request', { collectionUid, pathname }).then(resolve).catch(reject);
- });
- };
+export const loadLargeRequest
+ = ({ collectionUid, pathname }) =>
+ (dispatch, getState) => {
+ return new Promise(async (resolve, reject) => {
+ const { ipcRenderer } = window;
+ ipcRenderer.invoke('renderer:load-large-request', { collectionUid, pathname }).then(resolve).catch(reject);
+ });
+ };
-export const mountCollection =
- ({ collectionUid, collectionPathname, brunoConfig }) =>
- (dispatch, getState) => {
- dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounting' }));
- return new Promise(async (resolve, reject) => {
- callIpc('renderer:mount-collection', { collectionUid, collectionPathname, brunoConfig })
- .then(() => dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounted' })))
- .then(resolve)
- .catch(() => {
- dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'unmounted' }));
- reject();
- });
- });
- };
+export const mountCollection
+ = ({ collectionUid, collectionPathname, brunoConfig }) =>
+ (dispatch, getState) => {
+ dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounting' }));
+ return new Promise(async (resolve, reject) => {
+ callIpc('renderer:mount-collection', { collectionUid, collectionPathname, brunoConfig })
+ .then(() => dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounted' })))
+ .then(resolve)
+ .catch(() => {
+ dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'unmounted' }));
+ reject();
+ });
+ });
+ };
export const showInFolder = (collectionPath) => () => {
return new Promise((resolve, reject) => {
@@ -2507,8 +2507,8 @@ export const showInFolder = (collectionPath) => () => {
});
};
-export const updateRunnerConfiguration =
- (collectionUid, selectedRequestItems, requestItemsOrder, delay) => (dispatch) => {
+export const updateRunnerConfiguration
+ = (collectionUid, selectedRequestItems, requestItemsOrder, delay) => (dispatch) => {
dispatch(
_updateRunnerConfiguration({
collectionUid,
@@ -2523,32 +2523,32 @@ export const updateActiveConnectionsInStore = (activeConnectionIds) => (dispatch
dispatch(updateActiveConnections(activeConnectionIds));
};
-export const openCollectionSettings =
- (collectionUid, tabName = 'overview') =>
- (dispatch, getState) => {
- const state = getState();
- const collection = findCollectionByUid(state.collections.collections, collectionUid);
+export const openCollectionSettings
+ = (collectionUid, tabName = 'overview') =>
+ (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'));
- }
+ return new Promise((resolve, reject) => {
+ if (!collection) {
+ return reject(new Error('Collection not found'));
+ }
- dispatch(
- updateSettingsSelectedTab({
- collectionUid: collection.uid,
- tab: tabName
- })
- );
+ dispatch(
+ updateSettingsSelectedTab({
+ collectionUid: collection.uid,
+ tab: tabName
+ })
+ );
- dispatch(
- addTab({
- uid: collection.uid,
- collectionUid: collection.uid,
- type: 'collection-settings'
- })
- );
+ dispatch(
+ addTab({
+ uid: collection.uid,
+ collectionUid: collection.uid,
+ type: 'collection-settings'
+ })
+ );
- resolve();
- });
- };
+ resolve();
+ });
+ };
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js
index d362e0961..233c8b7de 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js
@@ -84,8 +84,8 @@ const initiatedGrpcResponse = {
isError: false,
duration: 0,
responses: [],
- timestamp: Date.now(),
-}
+ timestamp: Date.now()
+};
const initiatedWsResponse = {
status: 'PENDING',
@@ -190,7 +190,7 @@ export const collectionsSlice = createSlice({
},
sortCollections: (state, action) => {
state.collectionSortOrder = action.payload.order;
- const collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
switch (action.payload.order) {
case 'default':
state.collections = state.collections.sort((a, b) => a.importedAt - b.importedAt);
@@ -406,7 +406,7 @@ export const collectionsSlice = createSlice({
},
responseReceived: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
-
+
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
if (item) {
@@ -418,15 +418,15 @@ export const collectionsSlice = createSlice({
if (!collection.timeline) {
collection.timeline = [];
}
-
+
// Ensure timestamp is a number (milliseconds since epoch)
- const timestamp = item?.requestSent?.timestamp instanceof Date
- ? item.requestSent.timestamp.getTime()
+ const timestamp = item?.requestSent?.timestamp instanceof Date
+ ? item.requestSent.timestamp.getTime()
: item?.requestSent?.timestamp || Date.now();
// Append the new timeline entry with numeric timestamp
collection.timeline.push({
- type: "request",
+ type: 'request',
collectionUid: collection.uid,
folderUid: null,
itemUid: item.uid,
@@ -434,7 +434,7 @@ export const collectionsSlice = createSlice({
data: {
request: item.requestSent || item.request,
response: action.payload.response,
- timestamp: timestamp,
+ timestamp: timestamp
}
});
}
@@ -444,7 +444,7 @@ export const collectionsSlice = createSlice({
const { itemUid, collectionUid, eventType, eventData } = action.payload;
const collection = findCollectionByUid(state.collections, collectionUid);
if (!collection) return;
-
+
const item = findItemInCollection(collection, itemUid);
if (!item) return;
const request = item.draft ? item.draft.request : item.request;
@@ -464,7 +464,7 @@ export const collectionsSlice = createSlice({
}
collection.timeline.push({
- type: "request",
+ type: 'request',
eventType: eventType, // Add the specific gRPC event type
collectionUid: collection.uid,
folderUid: null,
@@ -473,36 +473,34 @@ export const collectionsSlice = createSlice({
data: {
request: eventData || item.requestSent || item.request,
timestamp: Date.now(),
- eventData: eventData,
+ eventData: eventData
}
});
-
},
grpcResponseReceived: (state, action) => {
const { itemUid, collectionUid, eventType, eventData } = action.payload;
const collection = findCollectionByUid(state.collections, collectionUid);
-
+
if (!collection) return;
const item = findItemInCollection(collection, itemUid);
if (!item) return;
-
+
// Get current response state or create initial state
- const currentResponse = item.response || initiatedGrpcResponse
+ const currentResponse = item.response || initiatedGrpcResponse;
const timestamp = item?.requestSent?.timestamp;
let updatedResponse = { ...currentResponse, duration: Date.now() - (timestamp || Date.now()) };
-
// Process based on event type
switch (eventType) {
case 'response':
const { error, res } = eventData;
-
+
// Handle error if present
if (error) {
const errorCode = error.code || 2; // Default to UNKNOWN if no code
-
+
updatedResponse.error = error.details || 'gRPC error occurred';
updatedResponse.statusCode = errorCode;
updatedResponse.statusText = grpcStatusCodes[errorCode] || 'UNKNOWN';
@@ -511,72 +509,72 @@ export const collectionsSlice = createSlice({
}
// Add response to list
- updatedResponse.responses = res
- ? [...(currentResponse?.responses || []), res]
+ updatedResponse.responses = res
+ ? [...(currentResponse?.responses || []), res]
: [...(currentResponse?.responses || [])];
break;
-
+
case 'metadata':
updatedResponse.headers = eventData.metadata;
updatedResponse.metadata = eventData.metadata;
break;
-
+
case 'status':
// Extract status info
const statusCode = eventData.status?.code;
const statusDetails = eventData.status?.details;
const statusMetadata = eventData.status?.metadata;
-
+
// Set status based on actual code and details
updatedResponse.statusCode = statusCode;
updatedResponse.statusText = grpcStatusCodes[statusCode] || 'UNKNOWN';
updatedResponse.statusDescription = statusDetails;
updatedResponse.statusDetails = eventData.status;
-
+
// Store trailers (status metadata)
if (statusMetadata) {
updatedResponse.trailers = statusMetadata;
}
-
+
// Handle error status (non-zero code)
if (statusCode !== 0) {
updatedResponse.isError = true;
updatedResponse.error = statusDetails || `gRPC error with code ${statusCode} (${updatedResponse.statusText})`;
}
-
+
break;
-
+
case 'error':
// Extract error details
const errorCode = eventData.error?.code || 2; // Default to UNKNOWN if no code
const errorDetails = eventData.error?.details || eventData.error?.message;
const errorMetadata = eventData.error?.metadata;
-
+
updatedResponse.isError = true;
updatedResponse.error = errorDetails || 'Unknown gRPC error';
updatedResponse.statusCode = errorCode;
updatedResponse.statusText = grpcStatusCodes[errorCode] || 'UNKNOWN';
updatedResponse.statusDescription = errorDetails;
-
+
// Store error metadata as trailers if present
if (errorMetadata) {
updatedResponse.trailers = errorMetadata;
}
-
+
break;
-
+
case 'end':
- state.activeConnections = state.activeConnections.filter(id => id !== itemUid);
+ state.activeConnections = state.activeConnections.filter((id) => id !== itemUid);
break;
-
+
case 'cancel':
updatedResponse.statusCode = 1; // CANCELLED
updatedResponse.statusText = 'CANCELLED';
updatedResponse.statusDescription = 'Stream cancelled by client or server';
- state.activeConnections = state.activeConnections.filter(id => id !== itemUid);
+ state.activeConnections = state.activeConnections.filter((id) => id !== itemUid);
break;
}
-
+
item.requestState = 'received';
item.response = updatedResponse;
@@ -587,7 +585,7 @@ export const collectionsSlice = createSlice({
// Append the new timeline entry with specific gRPC event type
collection.timeline.push({
- type: "request",
+ type: 'request',
eventType: eventType, // Add the specific gRPC event type
collectionUid: collection.uid,
folderUid: null,
@@ -597,7 +595,7 @@ export const collectionsSlice = createSlice({
request: item.requestSent || item.request,
response: updatedResponse,
eventData: eventData, // Store the original event data
- timestamp: Date.now(),
+ timestamp: Date.now()
}
});
},
@@ -629,7 +627,7 @@ export const collectionsSlice = createSlice({
if (collection) {
if (itemUid) {
- collection.timeline = collection?.timeline?.filter(t => t?.itemUid !== itemUid);
+ collection.timeline = collection?.timeline?.filter((t) => t?.itemUid !== itemUid);
}
}
},
@@ -885,7 +883,7 @@ export const collectionsSlice = createSlice({
case 'ntlm':
item.draft.request.auth.mode = 'ntlm';
item.draft.request.auth.ntlm = action.payload.content;
- break;
+ break;
case 'oauth2':
item.draft.request.auth.mode = 'oauth2';
item.draft.request.auth.oauth2 = action.payload.content;
@@ -940,7 +938,7 @@ export const collectionsSlice = createSlice({
if (!item.draft) {
item.draft = cloneDeep(item);
}
- const existingOtherParams = item.draft.request.params?.filter(p => p.type !== 'query') || [];
+ const existingOtherParams = item.draft.request.params?.filter((p) => p.type !== 'query') || [];
const newQueryParams = map(params, ({ name = '', value = '', enabled = true }) => ({
uid: uuid(),
name,
@@ -984,13 +982,13 @@ export const collectionsSlice = createSlice({
const queryParams = params.filter((param) => param.type === 'query');
const pathParams = params.filter((param) => param.type === 'path');
-
+
// Reorder only query params based on updateReorderedItem
const reorderedQueryParams = updateReorderedItem.map((uid) => {
return queryParams.find((param) => param.uid === uid);
});
item.draft.request.params = [...reorderedQueryParams, ...pathParams];
-
+
// Update request URL
const parts = splitOnFirst(item.draft.request.url, '?');
const query = stringifyQueryParams(filter(item.draft.request.params, (p) => p.enabled && p.type === 'query'));
@@ -1187,7 +1185,7 @@ export const collectionsSlice = createSlice({
if (!item.draft) {
item.draft = cloneDeep(item);
}
- item.draft.request.headers = map(action.payload.headers, ({name = '', value = '', enabled = true}) => ({
+ item.draft.request.headers = map(action.payload.headers, ({ name = '', value = '', enabled = true }) => ({
uid: uuid(),
name: name,
value: value,
@@ -1229,8 +1227,8 @@ export const collectionsSlice = createSlice({
if (!folder || !isItemAFolder(folder)) {
return;
}
-
- folder.root.request.headers = map(headers, ({name = '', value = '', enabled = true}) => ({
+
+ folder.root.request.headers = map(headers, ({ name = '', value = '', enabled = true }) => ({
uid: uuid(),
name: name,
value: value,
@@ -1404,16 +1402,16 @@ export const collectionsSlice = createSlice({
},
addFile: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
-
+
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
-
+
if (item && isItemARequest(item)) {
if (!item.draft) {
item.draft = cloneDeep(item);
}
item.draft.request.body.file = item.draft.request.body.file || [];
-
+
item.draft.request.body.file.push({
uid: uuid(),
filePath: '',
@@ -1425,23 +1423,23 @@ export const collectionsSlice = createSlice({
},
updateFile: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
-
+
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
-
+
if (item && isItemARequest(item)) {
if (!item.draft) {
item.draft = cloneDeep(item);
}
-
+
const param = find(item.draft.request.body.file, (p) => p.uid === action.payload.param.uid);
-
+
if (param) {
const contentType = mime.contentType(path.extname(action.payload.param.filePath));
param.filePath = action.payload.param.filePath;
param.contentType = action.payload.param.contentType || contentType || '';
param.selected = action.payload.param.selected;
-
+
item.draft.request.body.file = item.draft.request.body.file.map((p) => {
p.selected = p.uid === param.uid;
return p;
@@ -1452,20 +1450,20 @@ export const collectionsSlice = createSlice({
},
deleteFile: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
-
+
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
-
+
if (item && isItemARequest(item)) {
if (!item.draft) {
item.draft = cloneDeep(item);
}
-
+
item.draft.request.body.file = filter(
item.draft.request.body.file,
(p) => p.uid !== action.payload.paramUid
);
-
+
if (item.draft.request.body.file.length > 0) {
item.draft.request.body.file[0].selected = true;
}
@@ -1511,7 +1509,7 @@ export const collectionsSlice = createSlice({
if (!item.draft) {
item.draft = cloneDeep(item);
}
-
+
switch (item.draft.request.body.mode) {
case 'json': {
item.draft.request.body.json = action.payload.content;
@@ -1648,7 +1646,7 @@ export const collectionsSlice = createSlice({
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
if (collection) {
- const item = findItemInCollection(collection, action.payload.itemUid);
+ const item = findItemInCollection(collection, action.payload.itemUid);
if (item && isItemARequest(item)) {
if (!item.draft) {
@@ -1845,17 +1843,17 @@ export const collectionsSlice = createSlice({
// Extract payload data
const { updateReorderedItem } = action.payload;
- if(type == "request"){
+ if (type == 'request') {
const params = item.draft.request.vars.req;
item.draft.request.vars.req = updateReorderedItem.map((uid) => {
- return params.find((param) => param.uid === uid);
- });
+ return params.find((param) => param.uid === uid);
+ });
} else if (type === 'response') {
const params = item.draft.request.vars.res;
item.draft.request.vars.res = updateReorderedItem.map((uid) => {
- return params.find((param) => param.uid === uid);
+ return params.find((param) => param.uid === uid);
});
}
}
@@ -1900,7 +1898,7 @@ export const collectionsSlice = createSlice({
break;
case 'ntlm':
set(collection, 'draft.root.request.auth.ntlm', action.payload.content);
- break;
+ break;
case 'oauth2':
set(collection, 'draft.root.request.auth.oauth2', action.payload.content);
break;
@@ -2389,7 +2387,7 @@ export const collectionsSlice = createSlice({
name: directoryName,
collapsed: true,
type: 'folder',
- items: [],
+ items: []
};
currentSubItems.push(childItem);
}
@@ -2617,7 +2615,7 @@ export const collectionsSlice = createSlice({
const { requestUid, itemUid, collectionUid } = action.payload;
const collection = findCollectionByUid(state.collections, collectionUid);
if (!collection) return;
-
+
const item = findItemInCollection(collection, itemUid);
if (!item) return;
@@ -2646,11 +2644,11 @@ export const collectionsSlice = createSlice({
item.preRequestScriptErrorMessage = action.payload.errorMessage;
}
- if(type === 'post-response-script-execution') {
+ if (type === 'post-response-script-execution') {
item.postResponseScriptErrorMessage = action.payload.errorMessage;
}
- if(type === 'test-script-execution') {
+ if (type === 'test-script-execution') {
item.testScriptErrorMessage = action.payload.errorMessage;
}
@@ -2665,7 +2663,7 @@ export const collectionsSlice = createSlice({
if (type === 'request-sent') {
const { cancelTokenUid, requestSent } = action.payload;
item.requestSent = requestSent;
-
+
// sometimes the response is received before the request-sent event arrives
if (item.requestState === 'queued') {
item.requestState = 'sending';
@@ -2682,12 +2680,12 @@ export const collectionsSlice = createSlice({
const { results } = action.payload;
item.testResults = results;
}
-
+
if (type === 'test-results-pre-request') {
const { results } = action.payload;
item.preRequestTestResults = results;
}
-
+
if (type === 'test-results-post-response') {
const { results } = action.payload;
item.postResponseTestResults = results;
@@ -2801,7 +2799,7 @@ export const collectionsSlice = createSlice({
if (collection) {
collection.runnerResult = null;
- collection.runnerTags = { include: [], exclude: [] }
+ collection.runnerTags = { include: [], exclude: [] };
collection.runnerTagsEnabled = false;
collection.runnerConfiguration = null;
}
@@ -2874,14 +2872,14 @@ export const collectionsSlice = createSlice({
);
// Add the new credential with folderUid and itemUid
- filteredOauth2Credentials.push({
- collectionUid,
- folderUid,
- itemUid,
- url,
+ filteredOauth2Credentials.push({
+ collectionUid,
+ folderUid,
+ itemUid,
+ url,
credentials,
credentialsId,
- debugInfo
+ debugInfo
});
collection.oauth2Credentials = filteredOauth2Credentials;
@@ -2890,9 +2888,9 @@ export const collectionsSlice = createSlice({
collection.timeline = [];
}
- if(debugInfo) {
+ if (debugInfo) {
collection.timeline.push({
- type: "oauth2",
+ type: 'oauth2',
collectionUid,
folderUid,
itemUid,
@@ -2904,7 +2902,7 @@ export const collectionsSlice = createSlice({
url,
credentials,
credentialsId,
- debugInfo: debugInfo.data,
+ debugInfo: debugInfo.data
}
});
}
@@ -2940,7 +2938,7 @@ export const collectionsSlice = createSlice({
updateFolderAuthMode: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
const folder = collection ? findItemInCollection(collection, action.payload.folderUid) : null;
-
+
if (folder) {
if (!folder.draft) {
folder.draft = cloneDeep(folder.root);
@@ -3009,7 +3007,7 @@ export const collectionsSlice = createSlice({
updateCollectionTagsList: (state, action) => {
const { collectionUid } = action.payload;
const collection = findCollectionByUid(state.collections, collectionUid);
-
+
if (collection) {
collection.allTags = getUniqueTagsFromItems(collection.items);
}
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/global-environments.js b/packages/bruno-app/src/providers/ReduxStore/slices/global-environments.js
index 8e8effd1e..3df3db9e8 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/global-environments.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/global-environments.js
@@ -29,7 +29,7 @@ export const globalEnvironmentsSlice = createSlice({
_saveGlobalEnvironment: (state, action) => {
const { environmentUid: globalEnvironmentUid, variables } = action.payload;
if (globalEnvironmentUid) {
- const environment = state.globalEnvironments.find(env => env?.uid == globalEnvironmentUid);
+ const environment = state.globalEnvironments.find((env) => env?.uid == globalEnvironmentUid);
if (environment) {
environment.variables = variables;
}
@@ -38,7 +38,7 @@ export const globalEnvironmentsSlice = createSlice({
_renameGlobalEnvironment: (state, action) => {
const { environmentUid: globalEnvironmentUid, name } = action.payload;
if (globalEnvironmentUid) {
- const environment = state.globalEnvironments.find(env => env?.uid == globalEnvironmentUid);
+ const environment = state.globalEnvironments.find((env) => env?.uid == globalEnvironmentUid);
if (environment) {
environment.name = name;
}
@@ -57,7 +57,7 @@ export const globalEnvironmentsSlice = createSlice({
_selectGlobalEnvironment: (state, action) => {
const { environmentUid: globalEnvironmentUid } = action.payload;
if (globalEnvironmentUid) {
- const environment = state.globalEnvironments.find(env => env?.uid == globalEnvironmentUid);
+ const environment = state.globalEnvironments.find((env) => env?.uid == globalEnvironmentUid);
if (environment) {
state.activeGlobalEnvironmentUid = globalEnvironmentUid;
}
@@ -68,7 +68,7 @@ export const globalEnvironmentsSlice = createSlice({
_deleteGlobalEnvironment: (state, action) => {
const { environmentUid: uid } = action.payload;
if (uid) {
- state.globalEnvironments = state.globalEnvironments.filter(env => env?.uid !== uid);
+ state.globalEnvironments = state.globalEnvironments.filter((env) => env?.uid !== uid);
if (uid === state.activeGlobalEnvironmentUid) {
state.activeGlobalEnvironmentUid = null;
}
@@ -109,7 +109,7 @@ export const copyGlobalEnvironment = ({ name, environmentUid: baseEnvUid }) => (
return new Promise((resolve, reject) => {
const state = getState();
const globalEnvironments = state.globalEnvironments.globalEnvironments;
- const baseEnv = globalEnvironments?.find(env => env?.uid == baseEnvUid)
+ const baseEnv = globalEnvironments?.find((env) => env?.uid == baseEnvUid);
const uid = uuid();
let environment = { uid, name, variables: baseEnv.variables };
const { ipcRenderer } = window;
@@ -130,7 +130,7 @@ export const renameGlobalEnvironment = ({ name: newName, environmentUid }) => (d
const { ipcRenderer } = window;
const state = getState();
const globalEnvironments = state.globalEnvironments.globalEnvironments;
- const environment = globalEnvironments?.find(env => env?.uid == environmentUid)
+ const environment = globalEnvironments?.find((env) => env?.uid == environmentUid);
if (!environment) {
return reject(new Error('Environment not found'));
}
@@ -147,7 +147,7 @@ export const saveGlobalEnvironment = ({ variables, environmentUid }) => (dispatc
return new Promise((resolve, reject) => {
const state = getState();
const globalEnvironments = state.globalEnvironments.globalEnvironments;
- const environment = globalEnvironments?.find(env => env?.uid == environmentUid);
+ const environment = globalEnvironments?.find((env) => env?.uid == environmentUid);
if (!environment) {
return reject(new Error('Environment not found'));
@@ -200,7 +200,7 @@ export const globalEnvironmentsUpdateEvent = ({ globalEnvironmentVariables }) =>
const state = getState();
const globalEnvironments = state?.globalEnvironments?.globalEnvironments || [];
const environmentUid = state?.globalEnvironments?.activeGlobalEnvironmentUid;
- const environment = globalEnvironments?.find(env => env?.uid == environmentUid);
+ const environment = globalEnvironments?.find((env) => env?.uid == environmentUid);
if (!environment || !environmentUid) {
return resolve();
@@ -210,7 +210,7 @@ export const globalEnvironmentsUpdateEvent = ({ globalEnvironmentVariables }) =>
// "globalEnvironmentVariables" will include only the enabled variables and newly added variables created using the script.
// Update the value of each variable if it's present in "globalEnvironmentVariables", otherwise keep the existing value.
- variables = variables?.map?.(variable => ({
+ variables = variables?.map?.((variable) => ({
...variable,
value: has(globalEnvironmentVariables, variable?.name)
? globalEnvironmentVariables[variable?.name]
@@ -219,7 +219,7 @@ export const globalEnvironmentsUpdateEvent = ({ globalEnvironmentVariables }) =>
// add new env values
Object.entries(globalEnvironmentVariables)?.forEach?.(([key, value]) => {
- let isAnExistingVariable = variables?.find(v => v?.name == key)
+ let isAnExistingVariable = variables?.find((v) => v?.name == key);
if (!isAnExistingVariable) {
variables.push({
uid: uuid(),
@@ -246,7 +246,6 @@ export const globalEnvironmentsUpdateEvent = ({ globalEnvironmentVariables }) =>
reject(error);
});
});
-}
+};
-
-export default globalEnvironmentsSlice.reducer;
\ No newline at end of file
+export default globalEnvironmentsSlice.reducer;
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/logs.js b/packages/bruno-app/src/providers/ReduxStore/slices/logs.js
index a96f1ec90..71e5b844a 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/logs.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/logs.js
@@ -40,9 +40,9 @@ export const logsSlice = createSlice({
args: args || [],
timestamp: timestamp || new Date().toISOString()
};
-
+
state.logs.push(newLog);
-
+
if (state.logs.length > state.maxLogs) {
state.logs = state.logs.slice(-state.maxLogs);
}
@@ -59,9 +59,9 @@ export const logsSlice = createSlice({
args: args || [],
timestamp: timestamp || new Date().toISOString()
};
-
+
state.debugErrors.push(newError);
-
+
if (state.debugErrors.length > state.maxDebugErrors) {
state.debugErrors = state.debugErrors.slice(-state.maxDebugErrors);
}
@@ -93,7 +93,7 @@ export const logsSlice = createSlice({
},
toggleAllFilters: (state, action) => {
const enabled = action.payload;
- Object.keys(state.filters).forEach(key => {
+ Object.keys(state.filters).forEach((key) => {
state.filters[key] = enabled;
});
},
@@ -103,7 +103,7 @@ export const logsSlice = createSlice({
},
toggleAllNetworkFilters: (state, action) => {
const enabled = action.payload;
- Object.keys(state.networkFilters).forEach(key => {
+ Object.keys(state.networkFilters).forEach((key) => {
state.networkFilters[key] = enabled;
});
},
@@ -122,15 +122,15 @@ export const logsSlice = createSlice({
}
});
-export const {
- addLog,
+export const {
+ addLog,
addDebugError,
- clearLogs,
+ clearLogs,
clearDebugErrors,
- openConsole,
- closeConsole,
+ openConsole,
+ closeConsole,
setActiveTab,
- updateFilter,
+ updateFilter,
toggleAllFilters,
updateNetworkFilter,
toggleAllNetworkFilters,
@@ -140,4 +140,4 @@ export const {
clearSelectedError
} = logsSlice.actions;
-export default logsSlice.reducer;
\ No newline at end of file
+export default logsSlice.reducer;
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/notifications.js b/packages/bruno-app/src/providers/ReduxStore/slices/notifications.js
index 062f367ca..c03db6d6a 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/notifications.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/notifications.js
@@ -33,7 +33,7 @@ export const filterNotificationsByVersion = (notifications, currentVersion) => {
if (!currentVersion) return notifications;
- return notifications.filter(notification => {
+ return notifications.filter((notification) => {
const { minVersion, maxVersion } = notification;
if (!minVersion && !maxVersion) return true;
if (!minVersion) return semver.lte(currentVersion, maxVersion);
@@ -103,10 +103,10 @@ export const notificationSlice = createSlice({
}
});
-export const { setNotifications, setFetchingStatus, markNotificationAsRead, markAllNotificationsAsRead } =
- notificationSlice.actions;
+export const { setNotifications, setFetchingStatus, markNotificationAsRead, markAllNotificationsAsRead }
+ = notificationSlice.actions;
-export const fetchNotifications = ({currentVersion}) => (dispatch, getState) => {
+export const fetchNotifications = ({ currentVersion }) => (dispatch, getState) => {
return new Promise((resolve) => {
const { ipcRenderer } = window;
dispatch(setFetchingStatus(true));
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/notifications.spec.js b/packages/bruno-app/src/providers/ReduxStore/slices/notifications.spec.js
index 80e84d9bd..887193743 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/notifications.spec.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/notifications.spec.js
@@ -53,9 +53,9 @@ describe('filterNotificationsByVersion - basic', () => {
describe('filterNotificationsByVersion - semver', () => {
it('should filter out notifications outside version range', () => {
const notifications = [
- { minVersion: '1.0.0', maxVersion: '1.1.0' }, // should be included
- { minVersion: '2.0.0', maxVersion: '2.1.0' }, // should be filtered out
- { minVersion: '0.5.0', maxVersion: '0.9.0' } // should be filtered out
+ { minVersion: '1.0.0', maxVersion: '1.1.0' }, // should be included
+ { minVersion: '2.0.0', maxVersion: '2.1.0' }, // should be filtered out
+ { minVersion: '0.5.0', maxVersion: '0.9.0' } // should be filtered out
];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
@@ -66,10 +66,10 @@ describe('filterNotificationsByVersion - semver', () => {
it('should handle mixed valid and invalid version ranges', () => {
const notifications = [
- { minVersion: '1.0.0', maxVersion: '2.0.0' }, // should be included
- { minVersion: '3.0.0', maxVersion: '4.0.0' }, // should be filtered out
- { minVersion: '1.5.0', maxVersion: '1.8.0' }, // should be included
- { minVersion: '0.1.0', maxVersion: '0.5.0' } // should be filtered out
+ { minVersion: '1.0.0', maxVersion: '2.0.0' }, // should be included
+ { minVersion: '3.0.0', maxVersion: '4.0.0' }, // should be filtered out
+ { minVersion: '1.5.0', maxVersion: '1.8.0' }, // should be included
+ { minVersion: '0.1.0', maxVersion: '0.5.0' } // should be filtered out
];
const currentVersion = '1.6.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
@@ -81,9 +81,9 @@ describe('filterNotificationsByVersion - semver', () => {
it('should handle edge cases of version ranges', () => {
const notifications = [
- { minVersion: '1.0.0', maxVersion: '1.0.0' }, // should be included
- { minVersion: '1.0.1', maxVersion: '2.0.0' }, // should be filtered out
- { minVersion: '0.9.9', maxVersion: '1.0.0' } // should be included
+ { minVersion: '1.0.0', maxVersion: '1.0.0' }, // should be included
+ { minVersion: '1.0.1', maxVersion: '2.0.0' }, // should be filtered out
+ { minVersion: '0.9.9', maxVersion: '1.0.0' } // should be included
];
const currentVersion = '1.0.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
@@ -130,4 +130,4 @@ describe('filterNotificationsByVersion - undefined version bounds', () => {
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([]);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/tabs.js b/packages/bruno-app/src/providers/ReduxStore/slices/tabs.js
index f872cd23b..a6ffc9e0f 100644
--- a/packages/bruno-app/src/providers/ReduxStore/slices/tabs.js
+++ b/packages/bruno-app/src/providers/ReduxStore/slices/tabs.js
@@ -22,11 +22,11 @@ export const tabsSlice = createSlice({
const { uid, collectionUid, type, requestPaneTab, preview, exampleUid, itemUid } = action.payload;
const nonReplaceableTabTypes = [
- "variables",
- "collection-runner",
- "security-settings",
+ 'variables',
+ 'collection-runner',
+ 'security-settings'
];
-
+
const existingTab = find(state.tabs, (tab) => tab.uid === uid);
if (existingTab) {
state.activeTabUid = existingTab.uid;
@@ -60,7 +60,7 @@ export const tabsSlice = createSlice({
type: type || 'request',
preview: preview !== undefined
? preview
- : !nonReplaceableTabTypes.includes(type),
+ : !nonReplaceableTabTypes.includes(type),
...(uid ? { folderUid: uid } : {}),
...(exampleUid ? { exampleUid } : {}),
...(itemUid ? { itemUid } : {})
@@ -69,7 +69,7 @@ export const tabsSlice = createSlice({
state.activeTabUid = uid;
return;
}
-
+
state.tabs.push({
uid,
collectionUid,
@@ -80,7 +80,7 @@ export const tabsSlice = createSlice({
type: type || 'request',
...(uid ? { folderUid: uid } : {}),
preview: preview !== undefined
- ? preview
+ ? preview
: !nonReplaceableTabTypes.includes(type),
...(exampleUid ? { exampleUid } : {}),
...(itemUid ? { itemUid } : {})
diff --git a/packages/bruno-app/src/selectors/tab.js b/packages/bruno-app/src/selectors/tab.js
index 76aa67365..a38382c16 100644
--- a/packages/bruno-app/src/selectors/tab.js
+++ b/packages/bruno-app/src/selectors/tab.js
@@ -1,9 +1,9 @@
import { createSelector } from '@reduxjs/toolkit';
export const isTabForItemActive = ({ itemUid }) => createSelector([
- (state) => state.tabs?.activeTabUid
+ (state) => state.tabs?.activeTabUid
], (activeTabUid) => activeTabUid === itemUid);
export const isTabForItemPresent = ({ itemUid }) => createSelector([
- (state) => state.tabs.tabs,
-], (tabs) => tabs.some((tab) => tab.uid === itemUid));
\ No newline at end of file
+ (state) => state.tabs.tabs
+], (tabs) => tabs.some((tab) => tab.uid === itemUid));
diff --git a/packages/bruno-app/src/utils/codegenerator/auth.js b/packages/bruno-app/src/utils/codegenerator/auth.js
index 7098cf8ac..ad28970eb 100644
--- a/packages/bruno-app/src/utils/codegenerator/auth.js
+++ b/packages/bruno-app/src/utils/codegenerator/auth.js
@@ -1,7 +1,6 @@
import get from 'lodash/get';
export const getAuthHeaders = (collectionRootAuth, requestAuth) => {
-
// Discovered edge case where code generation fails when you create a collection which has not been saved yet:
// Collection auth therefore null, and request inherits from collection, therefore it is also null
// TypeError: Cannot read properties of undefined (reading 'mode')
diff --git a/packages/bruno-app/src/utils/codegenerator/har.js b/packages/bruno-app/src/utils/codegenerator/har.js
index b8a4bd19b..11d5b66d2 100644
--- a/packages/bruno-app/src/utils/codegenerator/har.js
+++ b/packages/bruno-app/src/utils/codegenerator/har.js
@@ -107,13 +107,13 @@ const createPostData = (body) => {
text: filePath,
params: filePath
? [
- {
- name: selectedFile?.name || 'file',
- value: filePath,
- fileName: filePath,
- contentType: selectedFile?.contentType || 'application/octet-stream'
- }
- ]
+ {
+ name: selectedFile?.name || 'file',
+ value: filePath,
+ fileName: filePath,
+ contentType: selectedFile?.contentType || 'application/octet-stream'
+ }
+ ]
: []
};
}
@@ -130,7 +130,7 @@ const createPostData = (body) => {
}
};
-export const buildHarRequest = ({ request, headers }) => {
+export const buildHarRequest = ({ request, headers }) => {
// NOTE:
// This is just a safety check.
// The interpolateUrlPathParams method validates the url, but it does not throw
diff --git a/packages/bruno-app/src/utils/codegenerator/targets.js b/packages/bruno-app/src/utils/codegenerator/targets.js
index 95b222dbc..9a536677e 100644
--- a/packages/bruno-app/src/utils/codegenerator/targets.js
+++ b/packages/bruno-app/src/utils/codegenerator/targets.js
@@ -5,22 +5,22 @@ export const getLanguages = () => {
for (const target of Object.values(targets)) {
const { key, title } = target.info;
const clients = Object.keys(target.clientsById);
- const languages =
- (clients.length === 1)
+ const languages
+ = (clients.length === 1)
? [{
- name: title,
- target: key,
- client: clients[0]
- }]
- : clients.map(client => ({
- name: `${title}-${client}`,
- target: key,
- client
- }));
+ name: title,
+ target: key,
+ client: clients[0]
+ }]
+ : clients.map((client) => ({
+ name: `${title}-${client}`,
+ target: key,
+ client
+ }));
allLanguages.push(...languages);
-
+
// Move "Shell-curl" to the top of the array
- const shellCurlIndex = allLanguages.findIndex(lang => lang.name === "Shell-curl");
+ const shellCurlIndex = allLanguages.findIndex((lang) => lang.name === 'Shell-curl');
if (shellCurlIndex !== -1) {
const [shellCurl] = allLanguages.splice(shellCurlIndex, 1);
allLanguages.unshift(shellCurl);
@@ -28,4 +28,4 @@ export const getLanguages = () => {
}
return allLanguages;
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-app/src/utils/codemirror/autocomplete.js b/packages/bruno-app/src/utils/codemirror/autocomplete.js
index def351389..38e4e1fdc 100644
--- a/packages/bruno-app/src/utils/codemirror/autocomplete.js
+++ b/packages/bruno-app/src/utils/codemirror/autocomplete.js
@@ -29,12 +29,12 @@ const STATIC_API_HINTS = {
'req.getName()',
'req.getTags()',
'req.disableParsingResponseJson()',
- 'req.onFail(function(err) {})',
+ 'req.onFail(function(err) {})'
],
res: [
'res',
'res.status',
- 'res.statusText',
+ 'res.statusText',
'res.headers',
'res.body',
'res.responseTime',
@@ -100,7 +100,7 @@ const STATIC_API_HINTS = {
};
// Mock data functions - prefixed with $
-const MOCK_DATA_HINTS = Object.keys(mockDataFunctions).map(key => `$${key}`);
+const MOCK_DATA_HINTS = Object.keys(mockDataFunctions).map((key) => `$${key}`);
// Constants for word pattern matching
const WORD_PATTERN = /[\w.$-/]/;
@@ -115,11 +115,11 @@ const NON_CHARACTER_KEYS = /^(?!Shift|Tab|Enter|Escape|ArrowUp|ArrowDown|ArrowLe
const generateProgressiveHints = (fullHint) => {
const parts = fullHint.split('.');
const progressiveHints = [];
-
+
for (let i = 1; i <= parts.length; i++) {
progressiveHints.push(parts.slice(0, i).join('.'));
}
-
+
return progressiveHints;
};
@@ -139,21 +139,21 @@ const shouldSkipVariableKey = (key) => {
*/
const transformVariablesToHints = (allVariables = {}) => {
const hints = [];
-
+
// Process all variables without type-specific handling
- Object.keys(allVariables).forEach(key => {
+ Object.keys(allVariables).forEach((key) => {
if (!shouldSkipVariableKey(key)) {
hints.push(key);
}
});
-
+
// Handle process environment variables
if (allVariables.process && allVariables.process.env) {
- Object.keys(allVariables.process.env).forEach(key => {
+ Object.keys(allVariables.process.env).forEach((key) => {
hints.push(`process.env.${key}`);
});
}
-
+
return hints;
};
@@ -164,11 +164,11 @@ const transformVariablesToHints = (allVariables = {}) => {
*/
const addApiHintsToSet = (apiHints, showHintsFor) => {
const apiTypes = ['req', 'res', 'bru'];
-
- apiTypes.forEach(apiType => {
+
+ apiTypes.forEach((apiType) => {
if (showHintsFor.includes(apiType)) {
- STATIC_API_HINTS[apiType].forEach(hint => {
- generateProgressiveHints(hint).forEach(h => apiHints.add(h));
+ STATIC_API_HINTS[apiType].forEach((hint) => {
+ generateProgressiveHints(hint).forEach((h) => apiHints.add(h));
});
}
});
@@ -181,14 +181,14 @@ const addApiHintsToSet = (apiHints, showHintsFor) => {
*/
const addVariableHintsToSet = (variableHints, allVariables) => {
// Add mock data hints
- MOCK_DATA_HINTS.forEach(hint => {
- generateProgressiveHints(hint).forEach(h => variableHints.add(h));
+ MOCK_DATA_HINTS.forEach((hint) => {
+ generateProgressiveHints(hint).forEach((h) => variableHints.add(h));
});
-
+
// Add variable hints with progressive hints
const variableHintsList = transformVariablesToHints(allVariables);
- variableHintsList.forEach(hint => {
- generateProgressiveHints(hint).forEach(h => variableHints.add(h));
+ variableHintsList.forEach((hint) => {
+ generateProgressiveHints(hint).forEach((h) => variableHints.add(h));
});
};
@@ -199,8 +199,8 @@ const addVariableHintsToSet = (variableHints, allVariables) => {
*/
const addCustomHintsToSet = (anywordHints, customHints) => {
if (customHints && Array.isArray(customHints)) {
- customHints.forEach(hint => {
- generateProgressiveHints(hint).forEach(h => anywordHints.add(h));
+ customHints.forEach((hint) => {
+ generateProgressiveHints(hint).forEach((h) => anywordHints.add(h));
});
}
};
@@ -218,14 +218,14 @@ const buildCategorizedHintsList = (allVariables = {}, anywordAutocompleteHints =
variables: new Set(),
anyword: new Set()
};
-
+
const showHintsFor = options.showHintsFor || [];
-
+
// Add different types of hints
addApiHintsToSet(categorizedHints.api, showHintsFor);
addVariableHintsToSet(categorizedHints.variables, allVariables);
addCustomHintsToSet(categorizedHints.anyword, anywordAutocompleteHints);
-
+
return {
api: Array.from(categorizedHints.api).sort(),
variables: Array.from(categorizedHints.variables).sort(),
@@ -242,7 +242,7 @@ const buildCategorizedHintsList = (allVariables = {}, anywordAutocompleteHints =
*/
const calculateVariableReplacementPositions = (cursor, startPos, wordMatch) => {
let replaceFrom, replaceTo;
-
+
if (wordMatch.endsWith('.')) {
replaceFrom = cursor;
replaceTo = cursor;
@@ -256,7 +256,7 @@ const calculateVariableReplacementPositions = (cursor, startPos, wordMatch) => {
replaceTo = cursor;
}
}
-
+
return { replaceFrom, replaceTo };
};
@@ -270,7 +270,7 @@ const calculateVariableReplacementPositions = (cursor, startPos, wordMatch) => {
*/
const calculateWordReplacementPositions = (cursor, start, end, word) => {
let replaceFrom, replaceTo;
-
+
if (word.endsWith('.')) {
replaceFrom = { line: cursor.line, ch: end };
replaceTo = cursor;
@@ -284,7 +284,7 @@ const calculateWordReplacementPositions = (cursor, start, end, word) => {
replaceTo = { line: cursor.line, ch: end };
}
}
-
+
return { replaceFrom, replaceTo };
};
@@ -309,18 +309,18 @@ const determineWordContext = (word) => {
const extractWordFromLine = (currentLine, cursorPosition) => {
let start = cursorPosition;
let end = start;
-
+
while (end < currentLine.length && WORD_PATTERN.test(currentLine.charAt(end))) {
++end;
}
while (start && WORD_PATTERN.test(currentLine.charAt(start - 1))) {
--start;
}
-
+
if (start === end) {
return null;
}
-
+
return {
word: currentLine.slice(start, end),
start,
@@ -337,14 +337,14 @@ const getCurrentWordWithContext = (cm) => {
const cursor = cm.getCursor();
const currentLine = cm.getLine(cursor.line);
const currentString = cm.getRange({ line: cursor.line, ch: 0 }, cursor);
-
+
// Check for variable pattern {{word
const variableMatch = currentString.match(VARIABLE_PATTERN);
if (variableMatch) {
const wordMatch = variableMatch[1];
const startPos = { line: cursor.line, ch: currentString.lastIndexOf('{{') + 2 };
const { replaceFrom, replaceTo } = calculateVariableReplacementPositions(cursor, startPos, wordMatch);
-
+
return {
word: wordMatch,
from: replaceFrom,
@@ -353,13 +353,13 @@ const getCurrentWordWithContext = (cm) => {
requiresBraces: true
};
}
-
+
// Check for regular word
const wordInfo = extractWordFromLine(currentLine, cursor.ch);
if (!wordInfo) {
return null;
}
-
+
const { word, start, end } = wordInfo;
const { replaceFrom, replaceTo } = calculateWordReplacementPositions(cursor, start, end, word);
const context = determineWordContext(word);
@@ -381,20 +381,20 @@ const getCurrentWordWithContext = (cm) => {
*/
const extractNextSegmentSuggestions = (filteredHints, currentInput) => {
const suggestions = new Set();
-
- filteredHints.forEach(hint => {
+
+ filteredHints.forEach((hint) => {
if (!hint.toLowerCase().startsWith(currentInput.toLowerCase())) {
return;
}
-
+
// Handle exact match case
if (hint.toLowerCase() === currentInput.toLowerCase()) {
suggestions.add(hint.substring(hint.lastIndexOf('.') + 1));
return;
}
-
+
const inputLength = currentInput.length;
-
+
if (currentInput.endsWith('.')) {
// Show next segment after the dot
const afterDot = hint.substring(inputLength);
@@ -406,13 +406,13 @@ const extractNextSegmentSuggestions = (filteredHints, currentInput) => {
const lastDotInInput = currentInput.lastIndexOf('.');
const currentSegmentStart = lastDotInInput + 1;
const nextDotAfterInput = hint.indexOf('.', currentSegmentStart);
- const segment = nextDotAfterInput === -1
+ const segment = nextDotAfterInput === -1
? hint.substring(currentSegmentStart)
: hint.substring(currentSegmentStart, nextDotAfterInput);
suggestions.add(segment);
}
});
-
+
return Array.from(suggestions).sort();
};
@@ -426,7 +426,7 @@ const getHintParts = (filteredHints, currentInput) => {
if (!filteredHints || filteredHints.length === 0) {
return [];
}
-
+
return extractNextSegmentSuggestions(filteredHints, currentInput);
};
@@ -439,18 +439,18 @@ const getHintParts = (filteredHints, currentInput) => {
*/
const getAllowedHintsByContext = (categorizedHints, context, showHintsFor) => {
let allowedHints = [];
-
+
if (context === 'variables' && showHintsFor.includes('variables')) {
allowedHints = [...categorizedHints.variables];
} else if (context === 'api') {
- const hasApiHints = showHintsFor.some(hint => ['req', 'res', 'bru'].includes(hint));
+ const hasApiHints = showHintsFor.some((hint) => ['req', 'res', 'bru'].includes(hint));
if (hasApiHints) {
allowedHints = [...categorizedHints.api];
}
} else if (context === 'anyword') {
allowedHints = [...categorizedHints.anyword];
}
-
+
return allowedHints;
};
@@ -466,15 +466,15 @@ const filterHintsByContext = (categorizedHints, currentWord, context, showHintsF
if (!currentWord) {
return [];
}
-
+
const allowedHints = getAllowedHintsByContext(categorizedHints, context, showHintsFor);
-
- const filtered = allowedHints.filter(hint => {
+
+ const filtered = allowedHints.filter((hint) => {
return hint.toLowerCase().startsWith(currentWord.toLowerCase());
});
-
+
const hintParts = getHintParts(filtered, currentWord);
-
+
return hintParts.slice(0, 50);
};
@@ -486,11 +486,11 @@ const filterHintsByContext = (categorizedHints, currentWord, context, showHintsF
* @returns {Object} Hint object with list and positions
*/
const createVariableHintList = (filteredHints, from, to) => {
- const hintList = filteredHints.map(hint => ({
+ const hintList = filteredHints.map((hint) => ({
text: hint,
displayText: hint
}));
-
+
return {
list: hintList,
from,
@@ -525,23 +525,23 @@ export const getAutoCompleteHints = (cm, allVariables = {}, anywordAutocompleteH
if (!allVariables) {
return null;
}
-
+
const wordInfo = getCurrentWordWithContext(cm);
if (!wordInfo) {
return null;
}
-
+
const { word, from, to, context, requiresBraces } = wordInfo;
- const showHintsFor = options.showHintsFor || [];
-
+ const showHintsFor = options.showHintsFor || [];
+
// Check if this context requires braces but we're not in a brace context
if (context === 'variables' && !requiresBraces) {
return null;
}
-
+
const categorizedHints = buildCategorizedHintsList(allVariables, anywordAutocompleteHints, options);
const filteredHints = filterHintsByContext(categorizedHints, word, context, showHintsFor);
-
+
if (filteredHints.length === 0) {
return null;
}
@@ -549,7 +549,7 @@ export const getAutoCompleteHints = (cm, allVariables = {}, anywordAutocompleteH
if (context === 'variables') {
return createVariableHintList(filteredHints, from, to);
}
-
+
return createStandardHintList(filteredHints, from, to);
};
@@ -562,34 +562,34 @@ const handleClickForAutocomplete = (cm, options) => {
const allVariables = options.getAllVariables?.() || {};
const anywordAutocompleteHints = options.getAnywordAutocompleteHints?.() || [];
const showHintsFor = options.showHintsFor || [];
-
+
// Build all available hints
const categorizedHints = buildCategorizedHintsList(allVariables, anywordAutocompleteHints, options);
-
+
// Combine all hints based on showHintsFor configuration
let allHints = [];
-
+
// Add API hints if enabled
- const hasApiHints = showHintsFor.some(hint => ['req', 'res', 'bru'].includes(hint));
+ const hasApiHints = showHintsFor.some((hint) => ['req', 'res', 'bru'].includes(hint));
if (hasApiHints) {
allHints = [...allHints, ...categorizedHints.api];
}
-
+
// Add variable hints if enabled
if (showHintsFor.includes('variables')) {
allHints = [...allHints, ...categorizedHints.variables];
}
-
+
// Add anyword hints (always included)
allHints = [...allHints, ...categorizedHints.anyword];
-
+
// Remove duplicates and sort
allHints = [...new Set(allHints)].sort();
-
+
if (allHints.length === 0) {
return;
}
-
+
const cursor = cm.getCursor();
if (cursor.ch > 0) return;
@@ -618,18 +618,18 @@ const handleKeyupForAutocomplete = (cm, event, options) => {
if (!NON_CHARACTER_KEYS.test(event?.key)) {
return;
}
-
+
const allVariables = options.getAllVariables?.() || {};
const anywordAutocompleteHints = options.getAnywordAutocompleteHints?.() || [];
const hints = getAutoCompleteHints(cm, allVariables, anywordAutocompleteHints, options);
-
+
if (!hints) {
if (cm.state.completionActive) {
cm.state.completionActive.close();
}
return;
}
-
+
cm.showHint({
hint: () => hints,
completeSingle: false
@@ -646,11 +646,11 @@ export const setupAutoComplete = (editor, options = {}) => {
if (!editor) {
return;
}
-
+
const keyupHandler = (cm, event) => {
handleKeyupForAutocomplete(cm, event, options);
};
-
+
editor.on('keyup', keyupHandler);
const clickHandler = (cm) => {
@@ -659,12 +659,12 @@ export const setupAutoComplete = (editor, options = {}) => {
handleClickForAutocomplete(cm, options);
}
};
-
+
// Add click handler if showHintsOnClick is enabled
if (options.showHintsOnClick) {
editor.on('mousedown', clickHandler);
}
-
+
return () => {
editor.off('keyup', keyupHandler);
if (options.showHintsOnClick) {
@@ -678,4 +678,4 @@ if (!CodeMirror.commands.autocomplete) {
CodeMirror.commands.autocomplete = (cm, hint, options) => {
cm.showHint({ hint, ...options });
};
-}
\ No newline at end of file
+}
diff --git a/packages/bruno-app/src/utils/codemirror/autocomplete.spec.js b/packages/bruno-app/src/utils/codemirror/autocomplete.spec.js
index 5a8d984c1..124fc0cb0 100644
--- a/packages/bruno-app/src/utils/codemirror/autocomplete.spec.js
+++ b/packages/bruno-app/src/utils/codemirror/autocomplete.spec.js
@@ -16,9 +16,9 @@ jest.mock('codemirror', () => {
});
// Import the functions to test
-import {
- getAutoCompleteHints,
- setupAutoComplete
+import {
+ getAutoCompleteHints,
+ setupAutoComplete
} from './autocomplete';
describe('Bruno Autocomplete', () => {
@@ -40,7 +40,7 @@ describe('Bruno Autocomplete', () => {
mockedCodemirror.getRange.mockReturnValue('{{envVar');
const allVariables = {
envVar1: 'value1',
- envVar2: 'value2',
+ envVar2: 'value2'
};
const result = getAutoCompleteHints(mockedCodemirror, allVariables, [], {
@@ -59,7 +59,7 @@ describe('Bruno Autocomplete', () => {
it('should include mock data functions with $ prefix', () => {
mockedCodemirror.getCursor.mockReturnValue({ line: 0, ch: 9 });
mockedCodemirror.getRange.mockReturnValue('{{$randomI');
-
+
const result = getAutoCompleteHints(mockedCodemirror, {}, [], {
showHintsFor: ['variables']
});
@@ -334,11 +334,11 @@ describe('Bruno Autocomplete', () => {
});
expect(result).toBeTruthy();
- const displayTexts = result.list.map(item =>
+ const displayTexts = result.list.map((item) =>
typeof item === 'object' ? item.displayText : item
);
-
- const userVars = displayTexts.filter(text => !text.startsWith('$'));
+
+ const userVars = displayTexts.filter((text) => !text.startsWith('$'));
expect(userVars).toEqual(['apple', 'banana', 'zebra']);
});
});
@@ -440,9 +440,9 @@ describe('Bruno Autocomplete', () => {
describe('Event handling', () => {
it('should trigger hints on character key press', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsFor: ['req']
+ showHintsFor: ['req']
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
const keyupHandler = mockedCodemirror.on.mock.calls[0][1];
@@ -465,7 +465,7 @@ describe('Bruno Autocomplete', () => {
const nonCharacterKeys = ['Shift', 'Tab', 'Enter', 'Escape', 'ArrowUp', 'ArrowDown', 'Meta'];
- nonCharacterKeys.forEach(key => {
+ nonCharacterKeys.forEach((key) => {
const mockEvent = { key };
keyupHandler(mockedCodemirror, mockEvent);
});
@@ -492,9 +492,9 @@ describe('Bruno Autocomplete', () => {
});
it('should pass options to getAutoCompleteHints', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsFor: ['req']
+ showHintsFor: ['req']
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
const keyupHandler = mockedCodemirror.on.mock.calls[0][1];
@@ -515,9 +515,9 @@ describe('Bruno Autocomplete', () => {
describe('Click event handling (showHintsOnClick)', () => {
it('should setup mousedown event listener when showHintsOnClick is enabled', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsOnClick: true
+ showHintsOnClick: true
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
@@ -527,9 +527,9 @@ describe('Bruno Autocomplete', () => {
});
it('should not setup mousedown event listener when showHintsOnClick is disabled', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsOnClick: false
+ showHintsOnClick: false
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
@@ -538,7 +538,7 @@ describe('Bruno Autocomplete', () => {
});
it('should not setup mousedown event listener when showHintsOnClick is undefined', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
@@ -549,9 +549,9 @@ describe('Bruno Autocomplete', () => {
it('should show hints on click when showHintsOnClick is enabled', () => {
jest.useFakeTimers();
-
+
const mockGetAnywordAutocompleteHints = jest.fn(() => ['Content-Type', 'Accept']);
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
getAnywordAutocompleteHints: mockGetAnywordAutocompleteHints,
showHintsOnClick: true,
@@ -560,8 +560,8 @@ describe('Bruno Autocomplete', () => {
cleanupFn = setupAutoComplete(mockedCodemirror, options);
// Find the click handler (mousedown event)
- const clickHandler = mockedCodemirror.on.mock.calls.find(call => call[0] === 'mousedown')[1];
-
+ const clickHandler = mockedCodemirror.on.mock.calls.find((call) => call[0] === 'mousedown')[1];
+
mockedCodemirror.getCursor.mockReturnValue({ line: 0, ch: 0 });
clickHandler(mockedCodemirror);
@@ -572,26 +572,26 @@ describe('Bruno Autocomplete', () => {
expect(mockGetAllVariables).toHaveBeenCalled();
expect(mockGetAnywordAutocompleteHints).toHaveBeenCalled();
expect(mockedCodemirror.showHint).toHaveBeenCalled();
-
+
jest.useRealTimers();
});
it('should not show hints on click when showHintsOnClick is disabled', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsOnClick: false
+ showHintsOnClick: false
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
// There should be no mousedown handler
- const mousedownCalls = mockedCodemirror.on.mock.calls.filter(call => call[0] === 'mousedown');
+ const mousedownCalls = mockedCodemirror.on.mock.calls.filter((call) => call[0] === 'mousedown');
expect(mousedownCalls).toHaveLength(0);
});
it('should cleanup mousedown event listener when showHintsOnClick was enabled', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsOnClick: true
+ showHintsOnClick: true
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
@@ -603,9 +603,9 @@ describe('Bruno Autocomplete', () => {
});
it('should only cleanup keyup event listener when showHintsOnClick was disabled', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables,
- showHintsOnClick: false
+ showHintsOnClick: false
};
cleanupFn = setupAutoComplete(mockedCodemirror, options);
@@ -617,9 +617,9 @@ describe('Bruno Autocomplete', () => {
it('should show all available hints on click based on showHintsFor configuration', () => {
jest.useFakeTimers();
-
+
const mockGetAnywordAutocompleteHints = jest.fn(() => ['Content-Type', 'Accept']);
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables.mockReturnValue({
envVar1: 'value1',
envVar2: 'value2'
@@ -631,8 +631,8 @@ describe('Bruno Autocomplete', () => {
cleanupFn = setupAutoComplete(mockedCodemirror, options);
// Find the click handler (mousedown event)
- const clickHandler = mockedCodemirror.on.mock.calls.find(call => call[0] === 'mousedown')[1];
-
+ const clickHandler = mockedCodemirror.on.mock.calls.find((call) => call[0] === 'mousedown')[1];
+
const mockCursor = { line: 0, ch: 0 };
mockedCodemirror.getCursor.mockReturnValue(mockCursor);
@@ -649,19 +649,19 @@ describe('Bruno Autocomplete', () => {
// Verify the hint function returns the expected structure
const hintCall = mockedCodemirror.showHint.mock.calls[0][0];
const hintResult = hintCall.hint();
-
+
expect(hintResult).toEqual({
list: expect.any(Array),
from: mockCursor,
to: mockCursor
});
expect(hintResult.list.length).toBeGreaterThan(0);
-
+
jest.useRealTimers();
});
it('should not show hints on click when no hints are available', () => {
- const options = {
+ const options = {
getAllVariables: mockGetAllVariables.mockReturnValue({}),
getAnywordAutocompleteHints: jest.fn(() => []),
showHintsOnClick: true,
@@ -670,8 +670,8 @@ describe('Bruno Autocomplete', () => {
cleanupFn = setupAutoComplete(mockedCodemirror, options);
// Find the click handler (mousedown event)
- const clickHandler = mockedCodemirror.on.mock.calls.find(call => call[0] === 'mousedown')[1];
-
+ const clickHandler = mockedCodemirror.on.mock.calls.find((call) => call[0] === 'mousedown')[1];
+
mockedCodemirror.getCursor.mockReturnValue({ line: 0, ch: 0 });
clickHandler(mockedCodemirror);
@@ -704,4 +704,4 @@ describe('Bruno Autocomplete', () => {
expect(mockedCodemirror.commands.autocomplete).toBe(existingCommand);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-app/src/utils/codemirror/brunoVarInfo.js b/packages/bruno-app/src/utils/codemirror/brunoVarInfo.js
index 332ba182b..0559500de 100644
--- a/packages/bruno-app/src/utils/codemirror/brunoVarInfo.js
+++ b/packages/bruno-app/src/utils/codemirror/brunoVarInfo.js
@@ -628,7 +628,6 @@ if (!SERVER_RENDERED) {
let token = cm.getTokenAt(pos, true);
if (token) {
-
const line = cm.getLine(pos.line);
// Find the opening {{ before the cursor
@@ -694,10 +693,10 @@ if (!SERVER_RENDERED) {
const popupBox = popup.getBoundingClientRect();
const popupStyle = popup.currentStyle || window.getComputedStyle(popup);
- const popupWidth =
- popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight);
- const popupHeight =
- popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom);
+ const popupWidth
+ = popupBox.right - popupBox.left + parseFloat(popupStyle.marginLeft) + parseFloat(popupStyle.marginRight);
+ const popupHeight
+ = popupBox.bottom - popupBox.top + parseFloat(popupStyle.marginTop) + parseFloat(popupStyle.marginBottom);
const GAP_REM = 0.5;
const EDGE_MARGIN_REM = 0.9375;
diff --git a/packages/bruno-app/src/utils/codemirror/javascript-lint.js b/packages/bruno-app/src/utils/codemirror/javascript-lint.js
index 0038406aa..385479e99 100644
--- a/packages/bruno-app/src/utils/codemirror/javascript-lint.js
+++ b/packages/bruno-app/src/utils/codemirror/javascript-lint.js
@@ -21,7 +21,7 @@ if (!SERVER_RENDERED) {
}
return [];
}
-
+
// Set default options for Bruno
const defaultOptions = {
esversion: 11,
@@ -33,19 +33,19 @@ if (!SERVER_RENDERED) {
module: true,
node: true,
predef: {
- 'bru': false,
- 'req': false,
- 'res': false,
- 'test': false,
- 'expect': false,
- 'require': false,
- 'module': false
+ bru: false,
+ req: false,
+ res: false,
+ test: false,
+ expect: false,
+ require: false,
+ module: false
}
};
-
+
// Merge provided options with defaults
options = Object.assign({}, defaultOptions, options);
-
+
if (!options.indent)
// JSHint error.character actually is a column index, this fixes underlining on lines using tabs for indentation
options.indent = 1; // JSHint default value is 4
@@ -68,9 +68,9 @@ if (!SERVER_RENDERED) {
errors = filter(errors, (error) => {
if (error.code === 'E058' || error.code === 'W024') {
if (
- error.evidence &&
- error.evidence.includes('await') &&
- error.scope === '(main)'
+ error.evidence
+ && error.evidence.includes('await')
+ && error.scope === '(main)'
) {
return false;
}
@@ -80,7 +80,7 @@ if (!SERVER_RENDERED) {
/*
* Filter out errors due to atob/btoa redefinition
- *
+ *
* - W079: Redefinition of '{a}'
* This JSHint warning triggers when a variable name conflicts with a built-in global.
* We filter this for atob/btoa to allow explicit requires in Node.js environments
diff --git a/packages/bruno-app/src/utils/codemirror/mock-data-hints.js b/packages/bruno-app/src/utils/codemirror/mock-data-hints.js
index fb03e9f11..8339e606b 100644
--- a/packages/bruno-app/src/utils/codemirror/mock-data-hints.js
+++ b/packages/bruno-app/src/utils/codemirror/mock-data-hints.js
@@ -1,6 +1,6 @@
import { mockDataFunctions } from '@usebruno/common';
-const MOCK_FUNCTION_SUGGESTIONS = Object.keys(mockDataFunctions).map(key => `$${key}`);
+const MOCK_FUNCTION_SUGGESTIONS = Object.keys(mockDataFunctions).map((key) => `$${key}`);
export const getMockDataHints = (cm) => {
const cursor = cm.getCursor();
@@ -12,7 +12,7 @@ export const getMockDataHints = (cm) => {
const wordMatch = match[1];
if (!wordMatch) return null;
- const suggestions = MOCK_FUNCTION_SUGGESTIONS.filter(name => name.startsWith(`$${wordMatch}`));
+ const suggestions = MOCK_FUNCTION_SUGGESTIONS.filter((name) => name.startsWith(`$${wordMatch}`));
if (!suggestions.length) return null;
const startPos = { line: cursor.line, ch: currentString.lastIndexOf('{{$') + 2 }; // +2 accounts for `{{`
@@ -20,6 +20,6 @@ export const getMockDataHints = (cm) => {
return {
list: suggestions,
from: startPos,
- to: cm.getCursor(),
+ to: cm.getCursor()
};
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-app/src/utils/collections/index.js b/packages/bruno-app/src/utils/collections/index.js
index 34509ef99..04331b527 100644
--- a/packages/bruno-app/src/utils/collections/index.js
+++ b/packages/bruno-app/src/utils/collections/index.js
@@ -1,4 +1,4 @@
-import {cloneDeep, isEqual, sortBy, filter, map, isString, findIndex, find, each, get } from 'lodash';
+import { cloneDeep, isEqual, sortBy, filter, map, isString, findIndex, find, each, get } from 'lodash';
import { uuid } from 'utils/common';
import { buildPersistedEnvVariables } from 'utils/environments';
import { sortByNameThenSequence } from 'utils/common/index';
@@ -146,7 +146,7 @@ export const areItemsLoading = (folder) => {
if (!folder || folder.isLoading) {
return true;
}
-
+
let flattenedItems = flattenItems(folder.items);
return flattenedItems?.reduce((isLoading, i) => {
if (i?.loading) {
@@ -154,13 +154,13 @@ export const areItemsLoading = (folder) => {
}
return isLoading;
}, false);
-}
+};
export const getItemsLoadStats = (folder) => {
let loadingCount = 0;
let flattenedItems = flattenItems(folder.items);
- flattenedItems?.forEach(i => {
- if(i?.loading) {
+ flattenedItems?.forEach((i) => {
+ if (i?.loading) {
loadingCount += 1;
}
});
@@ -168,7 +168,7 @@ export const getItemsLoadStats = (folder) => {
loading: loadingCount,
total: flattenedItems?.length
};
-}
+};
export const transformCollectionToSaveToExportAsFile = (collection, options = {}) => {
const copyHeaders = (headers) => {
@@ -228,9 +228,9 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
filePath: param.filePath,
contentType: param.contentType,
selected: param.selected
- }
+ };
});
- }
+ };
const copyExamples = (examples = []) => {
return map(examples, (example) => {
@@ -286,7 +286,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
return;
}
- const isGrpcRequest = si.type === 'grpc-request'
+ const isGrpcRequest = si.type === 'grpc-request';
const di = {
uid: si.uid,
@@ -330,7 +330,6 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
di.request.protoPath = si.request.protoPath;
delete di.request.params;
}
-
// Handle auth object dynamically
di.request.auth = {
@@ -371,7 +370,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
password: get(si.request, 'auth.ntlm.password', ''),
domain: get(si.request, 'auth.ntlm.domain', '')
};
- break;
+ break;
case 'oauth2':
let grantType = get(si.request, 'auth.oauth2.grantType', '');
switch (grantType) {
@@ -392,7 +391,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
tokenQueryKey: get(si.request, 'auth.oauth2.tokenQueryKey', ''),
autoFetchToken: get(si.request, 'auth.oauth2.autoFetchToken', true),
autoRefreshToken: get(si.request, 'auth.oauth2.autoRefreshToken', true),
- additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {}),
+ additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {})
};
break;
case 'authorization_code':
@@ -413,7 +412,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
tokenQueryKey: get(si.request, 'auth.oauth2.tokenQueryKey', ''),
autoFetchToken: get(si.request, 'auth.oauth2.autoFetchToken', true),
autoRefreshToken: get(si.request, 'auth.oauth2.autoRefreshToken', true),
- additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {}),
+ additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {})
};
break;
case 'implicit':
@@ -429,7 +428,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
tokenHeaderPrefix: get(si.request, 'auth.oauth2.tokenHeaderPrefix', 'Bearer'),
tokenQueryKey: get(si.request, 'auth.oauth2.tokenQueryKey', ''),
autoFetchToken: get(si.request, 'auth.oauth2.autoFetchToken', true),
- additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {}),
+ additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {})
};
break;
case 'client_credentials':
@@ -447,7 +446,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
tokenQueryKey: get(si.request, 'auth.oauth2.tokenQueryKey', ''),
autoFetchToken: get(si.request, 'auth.oauth2.autoFetchToken', true),
autoRefreshToken: get(si.request, 'auth.oauth2.autoRefreshToken', true),
- additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {}),
+ additionalParameters: get(si.request, 'auth.oauth2.additionalParameters', {})
};
break;
}
@@ -474,10 +473,10 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
}
if (di.request.body.mode === 'grpc') {
- di.request.body.grpc = di.request.body.grpc.map(({name, content}, index) => ({
+ di.request.body.grpc = di.request.body.grpc.map(({ name, content }, index) => ({
name: name ? name : `message ${index + 1}`,
content: replaceTabsWithSpaces(content)
- }))
+ }));
}
if (di.request.body.mode === 'ws') {
@@ -684,7 +683,7 @@ export const transformRequestToSaveToFilesystem = (item) => {
if (_item.type === 'grpc-request') {
itemToSave.request.methodType = _item.request.methodType;
itemToSave.request.protoPath = _item.request.protoPath;
- delete itemToSave.request.params
+ delete itemToSave.request.params;
}
if (_item.type === 'ws-request') {
@@ -727,7 +726,7 @@ export const transformRequestToSaveToFilesystem = (item) => {
if (itemToSave.request.body.mode === 'grpc') {
itemToSave.request.body = {
...itemToSave.request.body,
- grpc: itemToSave.request.body.grpc.map(({name, content}, index) => ({
+ grpc: itemToSave.request.body.grpc.map(({ name, content }, index) => ({
name: name ? name : `message ${index + 1}`,
content: replaceTabsWithSpaces(content)
}))
@@ -895,7 +894,7 @@ export const humanizeRequestAuthMode = (mode) => {
case 'ntlm': {
label = 'NTLM';
break;
- }
+ }
case 'oauth2': {
label = 'OAuth 2.0';
break;
@@ -1070,7 +1069,7 @@ export const getDefaultRequestPaneTab = (item) => {
export const getGlobalEnvironmentVariables = ({ globalEnvironments, activeGlobalEnvironmentUid }) => {
let variables = {};
- const environment = globalEnvironments?.find(env => env?.uid === activeGlobalEnvironmentUid);
+ const environment = globalEnvironments?.find((env) => env?.uid === activeGlobalEnvironmentUid);
if (environment) {
each(environment.variables, (variable) => {
if (variable.name && variable.enabled) {
@@ -1082,7 +1081,7 @@ export const getGlobalEnvironmentVariables = ({ globalEnvironments, activeGlobal
};
export const getGlobalEnvironmentVariablesMasked = ({ globalEnvironments, activeGlobalEnvironmentUid }) => {
- const environment = globalEnvironments?.find(env => env?.uid === activeGlobalEnvironmentUid);
+ const environment = globalEnvironments?.find((env) => env?.uid === activeGlobalEnvironmentUid);
if (environment && Array.isArray(environment.variables)) {
return environment.variables
@@ -1093,7 +1092,6 @@ export const getGlobalEnvironmentVariablesMasked = ({ globalEnvironments, active
return [];
};
-
export const getEnvironmentVariables = (collection) => {
let variables = {};
if (collection) {
@@ -1154,7 +1152,7 @@ export const getTotalRequestCountInCollection = (collection) => {
};
export const getAllVariables = (collection, item) => {
- if(!collection) return {};
+ if (!collection) return {};
const envVariables = getEnvironmentVariables(collection);
const requestTreePath = getTreePathFromCollectionToItem(collection, item);
let { collectionVariables, folderVariables, requestVariables } = mergeVars(collection, requestTreePath);
@@ -1176,7 +1174,7 @@ export const getAllVariables = (collection, item) => {
...requestVariables,
...runtimeVariables,
...promptVariables
- }
+ };
const maskedEnvVariables = getEnvironmentVariablesMasked(collection) || [];
const maskedGlobalEnvVariables = collection?.globalEnvSecrets || [];
@@ -1186,7 +1184,7 @@ export const getAllVariables = (collection, item) => {
const uniqueMaskedVariables = [...new Set([...filteredMaskedEnvVariables, ...filteredMaskedGlobalEnvVariables])];
- const oauth2CredentialVariables = getFormattedCollectionOauth2Credentials({ oauth2Credentials: collection?.oauth2Credentials })
+ const oauth2CredentialVariables = getFormattedCollectionOauth2Credentials({ oauth2Credentials: collection?.oauth2Credentials });
return {
...globalEnvironmentVariables,
@@ -1342,7 +1340,6 @@ export const getFormattedCollectionOauth2Credentials = ({ oauth2Credentials = []
return credentialsVariables;
};
-
// item sequence utils - START
export const resetSequencesInFolder = (folderItems) => {
@@ -1374,7 +1371,7 @@ export const getReorderedItemsInTargetDirectory = ({ items, targetItemUid, dragg
const draggedItem = findItem(itemsWithFixedSequences, draggedItemUid);
const targetSequence = targetItem?.seq;
const draggedSequence = draggedItem?.seq;
- itemsWithFixedSequences?.forEach(item => {
+ itemsWithFixedSequences?.forEach((item) => {
const isDraggedItem = item?.uid === draggedItemUid;
const isBetween = isItemBetweenSequences(item?.seq, draggedSequence, targetSequence);
if (isBetween) {
@@ -1386,15 +1383,15 @@ export const getReorderedItemsInTargetDirectory = ({ items, targetItemUid, dragg
}
});
// only return items that have been reordered
- return itemsWithFixedSequences.filter(item =>
- items?.find(originalItem => originalItem?.uid === item?.uid)?.seq !== item?.seq
+ return itemsWithFixedSequences.filter((item) =>
+ items?.find((originalItem) => originalItem?.uid === item?.uid)?.seq !== item?.seq
);
};
export const getReorderedItemsInSourceDirectory = ({ items }) => {
const itemsWithFixedSequences = resetSequencesInFolder(cloneDeep(items));
- return itemsWithFixedSequences.filter(item =>
- items?.find(originalItem => originalItem?.uid === item?.uid)?.seq !== item?.seq
+ return itemsWithFixedSequences.filter((item) =>
+ items?.find((originalItem) => originalItem?.uid === item?.uid)?.seq !== item?.seq
);
};
@@ -1406,9 +1403,9 @@ export const calculateDraggedItemNewPathname = ({ draggedItem, targetItem, dropT
const isTargetItemAFolder = isItemAFolder(targetItem);
if (dropType === 'inside' && (isTargetItemAFolder || isTargetTheCollection)) {
- return path.join(targetItemPathname, draggedItemFilename)
+ return path.join(targetItemPathname, draggedItemFilename);
} else if (dropType === 'adjacent') {
- return path.join(targetItemDirname, draggedItemFilename)
+ return path.join(targetItemDirname, draggedItemFilename);
}
return null;
};
@@ -1418,10 +1415,10 @@ export const calculateDraggedItemNewPathname = ({ draggedItem, targetItem, dropT
export const getUniqueTagsFromItems = (items = []) => {
const allTags = new Set();
const getTags = (items) => {
- items.forEach(item => {
+ items.forEach((item) => {
if (isItemARequest(item)) {
const tags = item.draft ? get(item, 'draft.tags', []) : get(item, 'tags', []);
- tags.forEach(tag => allTags.add(tag));
+ tags.forEach((tag) => allTags.add(tag));
}
if (item.items) {
getTags(item.items);
@@ -1432,10 +1429,9 @@ export const getUniqueTagsFromItems = (items = []) => {
return Array.from(allTags).sort();
};
-
export const getRequestItemsForCollectionRun = ({ recursive, items = [], tags }) => {
let requestItems = [];
-
+
if (recursive) {
requestItems = flattenItems(items);
} else {
@@ -1447,7 +1443,7 @@ export const getRequestItemsForCollectionRun = ({ recursive, items = [], tags })
}
const requestTypes = ['http-request', 'graphql-request'];
- requestItems = requestItems.filter(request => requestTypes.includes(request.type));
+ requestItems = requestItems.filter((request) => requestTypes.includes(request.type));
if (tags && tags.include && tags.exclude) {
const includeTags = tags.include ? tags.include : [];
diff --git a/packages/bruno-app/src/utils/common/codemirror.js b/packages/bruno-app/src/utils/common/codemirror.js
index 168daf25d..56729ee39 100644
--- a/packages/bruno-app/src/utils/common/codemirror.js
+++ b/packages/bruno-app/src/utils/common/codemirror.js
@@ -13,7 +13,7 @@ const pathFoundInVariables = (path, obj) => {
* Defines a custom CodeMirror mode for Bruno variables highlighting.
* This function creates a specialized mode that can highlight both Bruno template
* variables (in the format {{variable}}) and URL path parameters (in the format /:param).
- *
+ *
* @param {Object} _variables - The variables object containing data to validate against
* @param {string} mode - The base CodeMirror mode to extend (e.g., 'javascript', 'application/json')
* @param {boolean} highlightPathParams - Whether to highlight URL path parameters
diff --git a/packages/bruno-app/src/utils/common/folders-requests-sorting.spec.js b/packages/bruno-app/src/utils/common/folders-requests-sorting.spec.js
index fbcf71379..262b69c63 100644
--- a/packages/bruno-app/src/utils/common/folders-requests-sorting.spec.js
+++ b/packages/bruno-app/src/utils/common/folders-requests-sorting.spec.js
@@ -95,7 +95,7 @@ describe('sortByNameThenSequence', () => {
expect(result).toEqual([
{ name: 'folder_1', seq: 1 },
{ name: 'folder_3', seq: 1 },
- { name: 'folder_2', seq: 2 },
+ { name: 'folder_2', seq: 2 }
]);
});
@@ -371,4 +371,4 @@ describe('sortByNameThenSequence', () => {
]);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-app/src/utils/common/index.js b/packages/bruno-app/src/utils/common/index.js
index e94fd8be6..419d4a402 100644
--- a/packages/bruno-app/src/utils/common/index.js
+++ b/packages/bruno-app/src/utils/common/index.js
@@ -79,7 +79,6 @@ export const normalizeFileName = (name) => {
};
export const getContentType = (headers) => {
-
// Return empty string for invalid headers
if (!headers || typeof headers !== 'object' || Object.keys(headers).length === 0) {
return '';
@@ -111,8 +110,7 @@ export const getContentType = (headers) => {
}
return contentType;
-}
-
+};
export const startsWith = (str, search) => {
if (!str || !str.length || typeof str !== 'string') {
@@ -182,17 +180,17 @@ export const generateUidBasedOnHash = (str) => {
return `${hash}`.padEnd(21, '0');
};
-export const stringifyIfNot = v => typeof v === 'string' ? v : String(v);
+export const stringifyIfNot = (v) => typeof v === 'string' ? v : String(v);
export const getEncoding = (headers) => {
// Parse the charset from content type: https://stackoverflow.com/a/33192813
const charsetMatch = /charset=([^()<>@,;:"/[\]?.=\s]*)/i.exec(headers?.['content-type'] || '');
return charsetMatch?.[1];
-}
+};
export const multiLineMsg = (...messages) => {
- return messages.filter(m => m !== undefined && m !== null && m !== '').join('\n');
-}
+ return messages.filter((m) => m !== undefined && m !== null && m !== '').join('\n');
+};
export const formatSize = (bytes) => {
// Handle invalid inputs
@@ -211,19 +209,19 @@ export const formatSize = (bytes) => {
}
return (bytes / (1024 * 1024 * 1024)).toFixed(1) + 'GB';
-}
+};
-export const sortByNameThenSequence = items => {
- const isSeqValid = seq => Number.isFinite(seq) && Number.isInteger(seq) && seq > 0;
+export const sortByNameThenSequence = (items) => {
+ const isSeqValid = (seq) => Number.isFinite(seq) && Number.isInteger(seq) && seq > 0;
// Sort folders alphabetically by name
const alphabeticallySorted = [...items].sort((a, b) => a.name && b.name && a.name.localeCompare(b.name));
// Extract folders without 'seq'
- const withoutSeq = alphabeticallySorted.filter(f => !isSeqValid(f['seq']));
+ const withoutSeq = alphabeticallySorted.filter((f) => !isSeqValid(f['seq']));
// Extract folders with 'seq' and sort them by 'seq'
- const withSeq = alphabeticallySorted.filter(f => isSeqValid(f['seq'])).sort((a, b) => a.seq - b.seq);
+ const withSeq = alphabeticallySorted.filter((f) => isSeqValid(f['seq'])).sort((a, b) => a.seq - b.seq);
const sortedItems = withoutSeq;
@@ -242,7 +240,7 @@ export const sortByNameThenSequence = items => {
const newGroup = Array.isArray(existingItem)
? [...existingItem, item]
: [existingItem, item];
-
+
withoutSeq.splice(position, 1, newGroup);
} else {
// Insert item at the specified position
diff --git a/packages/bruno-app/src/utils/common/ipc.js b/packages/bruno-app/src/utils/common/ipc.js
index 3559737f2..b1d1871c3 100644
--- a/packages/bruno-app/src/utils/common/ipc.js
+++ b/packages/bruno-app/src/utils/common/ipc.js
@@ -11,4 +11,4 @@ export const callIpc = (channel, ...args) => {
}
return ipcRenderer.invoke(channel, ...args);
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-app/src/utils/common/path.js b/packages/bruno-app/src/utils/common/path.js
index 9ce10c33b..7f18551db 100644
--- a/packages/bruno-app/src/utils/common/path.js
+++ b/packages/bruno-app/src/utils/common/path.js
@@ -2,9 +2,9 @@ import platform from 'platform';
import path from 'path';
const isWindowsOS = () => {
- const os = platform.os;
- const osFamily = os.family.toLowerCase();
- return osFamily.includes('windows');
+ const os = platform.os;
+ const osFamily = os.family.toLowerCase();
+ return osFamily.includes('windows');
};
/**
diff --git a/packages/bruno-app/src/utils/common/platform.js b/packages/bruno-app/src/utils/common/platform.js
index d1c62e694..3ba2c549f 100644
--- a/packages/bruno-app/src/utils/common/platform.js
+++ b/packages/bruno-app/src/utils/common/platform.js
@@ -15,7 +15,6 @@ export const resolveRequestFilename = (name, extension = 'bru') => {
};
export const getSubdirectoriesFromRoot = (rootPath, pathname) => {
-
const relativePath = path.relative(rootPath, pathname);
return relativePath ? relativePath.split(path.sep) : [];
};
diff --git a/packages/bruno-app/src/utils/common/regex.js b/packages/bruno-app/src/utils/common/regex.js
index a8e4c6eee..8e7c796b5 100644
--- a/packages/bruno-app/src/utils/common/regex.js
+++ b/packages/bruno-app/src/utils/common/regex.js
@@ -1,56 +1,56 @@
const invalidCharacters = /[<>:"/\\|?*\x00-\x1F]/g; // replace invalid characters with hyphens
const reservedDeviceNames = /^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$/i;
const firstCharacter = /^[^\s\-<>:"/\\|?*\x00-\x1F]/; // no space, hyphen and `invalidCharacters`
-const middleCharacters = /^[^<>:"/\\|?*\x00-\x1F]*$/; // no `invalidCharacters`
+const middleCharacters = /^[^<>:"/\\|?*\x00-\x1F]*$/; // no `invalidCharacters`
const lastCharacter = /[^.\s<>:"/\\|?*\x00-\x1F]$/; // no dot, space and `invalidCharacters`
export const variableNameRegex = /^[\w-.]*$/;
export const sanitizeName = (name) => {
- name = name
- .replace(invalidCharacters, '-') // replace invalid characters with hyphens
- .replace(/^[\s\-]+/, '') // remove leading spaces and hyphens
- .replace(/[.\s]+$/, ''); // remove trailing dots and spaces
- return name;
+ name = name
+ .replace(invalidCharacters, '-') // replace invalid characters with hyphens
+ .replace(/^[\s\-]+/, '') // remove leading spaces and hyphens
+ .replace(/[.\s]+$/, ''); // remove trailing dots and spaces
+ return name;
};
export const validateName = (name) => {
- if (!name) return false;
- if (name.length > 255) return false; // max name length
+ if (!name) return false;
+ if (name.length > 255) return false; // max name length
- if (reservedDeviceNames.test(name)) return false; // windows reserved names
+ if (reservedDeviceNames.test(name)) return false; // windows reserved names
- return (
- firstCharacter.test(name) &&
- middleCharacters.test(name) &&
- lastCharacter.test(name)
- );
+ return (
+ firstCharacter.test(name)
+ && middleCharacters.test(name)
+ && lastCharacter.test(name)
+ );
};
export const validateNameError = (name) => {
- if (!name) return "Name cannot be empty.";
+ if (!name) return 'Name cannot be empty.';
- if (name.length > 255) {
- return "Name cannot exceed 255 characters.";
+ if (name.length > 255) {
+ return 'Name cannot exceed 255 characters.';
+ }
+
+ if (reservedDeviceNames.test(name)) {
+ return 'Name cannot be a reserved device name.';
+ }
+
+ if (!firstCharacter.test(name[0])) {
+ return 'Invalid first character.';
+ }
+
+ for (let i = 1; i < name.length - 1; i++) {
+ if (!middleCharacters.test(name[i])) {
+ return `Invalid character '${name[i]}' at position ${i + 1}.`;
}
+ }
- if (reservedDeviceNames.test(name)) {
- return "Name cannot be a reserved device name.";
- }
+ if (!lastCharacter.test(name[name.length - 1])) {
+ return 'Invalid last character.';
+ }
- if (!firstCharacter.test(name[0])) {
- return "Invalid first character.";
- }
-
- for (let i = 1; i < name.length - 1; i++) {
- if (!middleCharacters.test(name[i])) {
- return `Invalid character '${name[i]}' at position ${i + 1}.`;
- }
- }
-
- if (!lastCharacter.test(name[name.length - 1])) {
- return "Invalid last character.";
- }
-
- return '';
-};
\ No newline at end of file
+ return '';
+};
diff --git a/packages/bruno-app/src/utils/common/regex.spec.js b/packages/bruno-app/src/utils/common/regex.spec.js
index 3994a2b2d..a4ce6eecf 100644
--- a/packages/bruno-app/src/utils/common/regex.spec.js
+++ b/packages/bruno-app/src/utils/common/regex.spec.js
@@ -110,7 +110,6 @@ describe('regex validators', () => {
expect(sanitizeName('เธชเธงเธฑเธชเธเธตเธเธฒเธงเนเธฅเธ!?@#$%^&*()')).toBe('เธชเธงเธฑเธชเธเธตเธเธฒเธงเนเธฅเธ!-@#$%^&-()');
expect(sanitizeName('ฮณฮตฮนฮฌ ฯฮฟฯ
ฮบฯฯฮผฮฟฯ!?@#$%^&*()')).toBe('ฮณฮตฮนฮฌ ฯฮฟฯ
ฮบฯฯฮผฮฟฯ!-@#$%^&-()');
});
-
});
});
@@ -124,7 +123,7 @@ describe('sanitizeName and validateName', () => {
'file/with?invalid*chars'
];
- validNames.forEach(name => {
+ validNames.forEach((name) => {
const sanitized = sanitizeName(name);
expect(validateName(sanitized)).toBe(true);
});
@@ -132,8 +131,8 @@ describe('sanitizeName and validateName', () => {
it('should sanitize and then validate names with reserved device names', () => {
const reservedNames = ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'LPT2'];
-
- reservedNames.forEach(name => {
+
+ reservedNames.forEach((name) => {
const sanitized = sanitizeName(name);
expect(validateName(sanitized)).toBe(false);
});
@@ -143,10 +142,10 @@ describe('sanitizeName and validateName', () => {
const invalidNames = [
' <>:"/\\|?* ',
' ... ',
- ' ',
+ ' '
];
- invalidNames.forEach(name => {
+ invalidNames.forEach((name) => {
const sanitized = sanitizeName(name);
expect(validateName(sanitized)).toBe(false);
});
@@ -158,7 +157,7 @@ describe('sanitizeName and validateName', () => {
' COM1 '
];
- mixedNames.forEach(name => {
+ mixedNames.forEach((name) => {
const sanitized = sanitizeName(name);
expect(validateName(sanitized)).toBe(false);
});
diff --git a/packages/bruno-app/src/utils/common/setupPolyfills.js b/packages/bruno-app/src/utils/common/setupPolyfills.js
index 8d42d17b9..1bb2504c9 100644
--- a/packages/bruno-app/src/utils/common/setupPolyfills.js
+++ b/packages/bruno-app/src/utils/common/setupPolyfills.js
@@ -1,24 +1,24 @@
export const setupPolyfills = () => {
// polyfill required to make react-pdf
- if (typeof Promise.withResolvers === "undefined") {
+ if (typeof Promise.withResolvers === 'undefined') {
if (typeof window !== 'undefined') {
window.Promise.withResolvers = function () {
- let resolve, reject
+ let resolve, reject;
const promise = new Promise((res, rej) => {
- resolve = res
- reject = rej
- })
- return { promise, resolve, reject }
- }
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+ };
} else {
global.Promise.withResolvers = function () {
- let resolve, reject
+ let resolve, reject;
const promise = new Promise((res, rej) => {
- resolve = res
- reject = rej
- })
- return { promise, resolve, reject }
- }
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+ };
}
}
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-app/src/utils/curl/curl-to-json.js b/packages/bruno-app/src/utils/curl/curl-to-json.js
index 24269f9a9..262f73ea7 100644
--- a/packages/bruno-app/src/utils/curl/curl-to-json.js
+++ b/packages/bruno-app/src/utils/curl/curl-to-json.js
@@ -19,7 +19,7 @@ function getContentType(headers = {}) {
}
function repr(value, isKey) {
- return isKey ? "'" + jsesc(value, { quotes: 'single' }) + "'" : value;
+ return isKey ? '\'' + jsesc(value, { quotes: 'single' }) + '\'' : value;
}
/**
@@ -92,7 +92,7 @@ function getFilesString(request) {
{
filePath: repr(filePath),
contentType: request.headers['Content-Type'],
- selected: true,
+ selected: true
}
];
diff --git a/packages/bruno-app/src/utils/curl/curl-to-json.spec.js b/packages/bruno-app/src/utils/curl/curl-to-json.spec.js
index c4133a3e0..e85b12a9b 100644
--- a/packages/bruno-app/src/utils/curl/curl-to-json.spec.js
+++ b/packages/bruno-app/src/utils/curl/curl-to-json.spec.js
@@ -27,7 +27,7 @@ describe('curlToJson', () => {
raw_url: 'https://www.usebruno.com',
method: 'get',
headers: {
- Accept: 'application/json, text/plain, */*',
+ 'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8'
}
});
@@ -50,11 +50,11 @@ describe('curlToJson', () => {
raw_url: 'https://www.usebruno.com',
method: 'post',
headers: {
- Accept: 'application/json, text/plain, */*',
+ 'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
'Content-Type': 'application/json;charset=utf-8',
- Origin: 'https://www.usebruno.com',
- Referer: 'https://www.usebruno.com/'
+ 'Origin': 'https://www.usebruno.com',
+ 'Referer': 'https://www.usebruno.com/'
},
data: '{"email":"test@usebruno.com","password":"test"}'
});
@@ -71,7 +71,7 @@ describe('curlToJson', () => {
raw_url: 'https://www.usebruno.com',
method: 'get',
headers: {
- cookie: "val_1=''; val_2=\\^373:0\\^373:0; val_3=hello"
+ cookie: 'val_1=\'\'; val_2=\\^373:0\\^373:0; val_3=hello'
}
});
});
@@ -104,11 +104,11 @@ describe('curlToJson', () => {
raw_url: 'https://www.usebruno.com',
method: 'post',
headers: {
- Accept: 'application/json, text/plain, */*',
+ 'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8',
'Content-Type': 'application/json;charset=utf-8',
- Origin: 'https://www.usebruno.com',
- Referer: 'https://www.usebruno.com/'
+ 'Origin': 'https://www.usebruno.com',
+ 'Referer': 'https://www.usebruno.com/'
},
isDataBinary: true,
data: [
diff --git a/packages/bruno-app/src/utils/curl/index.js b/packages/bruno-app/src/utils/curl/index.js
index 866df7b32..f288fccc8 100644
--- a/packages/bruno-app/src/utils/curl/index.js
+++ b/packages/bruno-app/src/utils/curl/index.js
@@ -40,9 +40,9 @@ export const getRequestFromCurlCommand = (curlCommand, requestType = 'http-reque
}
const parsedHeaders = request?.headers;
- const headers =
- parsedHeaders &&
- Object.keys(parsedHeaders).map((key) => ({ name: key, value: parsedHeaders[key], enabled: true }));
+ const headers
+ = parsedHeaders
+ && Object.keys(parsedHeaders).map((key) => ({ name: key, value: parsedHeaders[key], enabled: true }));
const contentType = headers?.find((h) => h.name.toLowerCase() === 'content-type')?.value;
const parsedBody = request.data;
diff --git a/packages/bruno-app/src/utils/curl/parse-curl.js b/packages/bruno-app/src/utils/curl/parse-curl.js
index cf499d187..e7493b5f2 100644
--- a/packages/bruno-app/src/utils/curl/parse-curl.js
+++ b/packages/bruno-app/src/utils/curl/parse-curl.js
@@ -441,7 +441,6 @@ const postBuildProcessRequest = (request) => {
// remove data and isQuery from request as they are no longer needed
delete request.data;
delete request.isQuery;
-
} else if (request.data) {
// if data is present, set method to POST unless the method is explicitly set
if (!request.method || request.method === 'HEAD') {
@@ -483,7 +482,7 @@ const cleanCurlCommand = (curlCommand) => {
// Handle escape sequences
curlCommand = curlCommand.replace(/\$('.*')/g, (match, group) => group);
// Convert escaped single quotes to shell quote pattern
- curlCommand = curlCommand.replace(/\\'(?!')/g, "'\\''");
+ curlCommand = curlCommand.replace(/\\'(?!')/g, '\'\\\'\'');
// Fix concatenated HTTP methods
curlCommand = fixConcatenatedMethods(curlCommand);
diff --git a/packages/bruno-app/src/utils/curl/parse-curl.spec.js b/packages/bruno-app/src/utils/curl/parse-curl.spec.js
index e0da77d37..8701d980c 100644
--- a/packages/bruno-app/src/utils/curl/parse-curl.spec.js
+++ b/packages/bruno-app/src/utils/curl/parse-curl.spec.js
@@ -318,9 +318,9 @@ describe('parseCurlCommand', () => {
expect(result).toEqual({
method: 'get',
headers: {
- 'Cookie': 'session=abc123'
+ Cookie: 'session=abc123'
},
- cookieString: "session=abc123",
+ cookieString: 'session=abc123',
cookies: {
session: 'abc123'
},
@@ -337,9 +337,9 @@ describe('parseCurlCommand', () => {
expect(result).toEqual({
method: 'get',
headers: {
- 'Cookie': 'session=abc123; user=john'
+ Cookie: 'session=abc123; user=john'
},
- cookieString: "session=abc123; user=john",
+ cookieString: 'session=abc123; user=john',
cookies: {
session: 'abc123',
user: 'john'
@@ -357,9 +357,9 @@ describe('parseCurlCommand', () => {
expect(result).toEqual({
method: 'get',
headers: {
- 'Cookie': 'session=abc123; user=john'
+ Cookie: 'session=abc123; user=john'
},
- cookieString: "session=abc123; user=john",
+ cookieString: 'session=abc123; user=john',
cookies: {
session: 'abc123',
user: 'john'
@@ -378,15 +378,15 @@ describe('parseCurlCommand', () => {
expect(result).toEqual({
method: 'get',
headers: {
- 'Cookie': 'session=abc123; user=john; path=/; domain=example.com; expires=Thu, 01 Jan 1970 00:00:00 GMT; secure; HttpOnly'
+ Cookie: 'session=abc123; user=john; path=/; domain=example.com; expires=Thu, 01 Jan 1970 00:00:00 GMT; secure; HttpOnly'
},
- cookieString: "session=abc123; user=john; path=/; domain=example.com; expires=Thu, 01 Jan 1970 00:00:00 GMT; secure; HttpOnly",
+ cookieString: 'session=abc123; user=john; path=/; domain=example.com; expires=Thu, 01 Jan 1970 00:00:00 GMT; secure; HttpOnly',
cookies: {
session: 'abc123',
user: 'john',
path: '/',
domain: 'example.com',
- expires: 'Thu, 01 Jan 1970 00:00:00 GMT',
+ expires: 'Thu, 01 Jan 1970 00:00:00 GMT'
},
url: 'https://api.example.com',
urlWithoutQuery: 'https://api.example.com'
diff --git a/packages/bruno-app/src/utils/exporters/postman-collection.js b/packages/bruno-app/src/utils/exporters/postman-collection.js
index 65fc7e1ca..06e8c3f0a 100644
--- a/packages/bruno-app/src/utils/exporters/postman-collection.js
+++ b/packages/bruno-app/src/utils/exporters/postman-collection.js
@@ -2,7 +2,6 @@ import * as FileSaver from 'file-saver';
import { brunoToPostman } from '@usebruno/converters';
export const exportCollection = (collection) => {
-
const collectionToExport = brunoToPostman(collection);
const fileName = `${collection.name}.json`;
diff --git a/packages/bruno-app/src/utils/importers/bruno-collection.js b/packages/bruno-app/src/utils/importers/bruno-collection.js
index d940c0397..6757d0e8a 100644
--- a/packages/bruno-app/src/utils/importers/bruno-collection.js
+++ b/packages/bruno-app/src/utils/importers/bruno-collection.js
@@ -1,7 +1,6 @@
import { BrunoError } from 'utils/common/error';
import { validateSchema, transformItemsInCollection, updateUidsInCollection, hydrateSeqInCollection } from './common';
-
export const processBrunoCollection = async (jsonData) => {
try {
let collection = hydrateSeqInCollection(jsonData);
diff --git a/packages/bruno-app/src/utils/importers/insomnia-collection.js b/packages/bruno-app/src/utils/importers/insomnia-collection.js
index 5e41b5832..ca2af6a6c 100644
--- a/packages/bruno-app/src/utils/importers/insomnia-collection.js
+++ b/packages/bruno-app/src/utils/importers/insomnia-collection.js
@@ -1,7 +1,6 @@
import { BrunoError } from 'utils/common/error';
import { insomniaToBruno } from '@usebruno/converters';
-
export const convertInsomniaToBruno = (data) => {
try {
return insomniaToBruno(data);
diff --git a/packages/bruno-app/src/utils/importers/postman-collection.js b/packages/bruno-app/src/utils/importers/postman-collection.js
index 28bfddf05..f4c369570 100644
--- a/packages/bruno-app/src/utils/importers/postman-collection.js
+++ b/packages/bruno-app/src/utils/importers/postman-collection.js
@@ -14,8 +14,8 @@ const readFile = (files) => {
const postmanToBruno = (collection) => {
return new Promise((resolve, reject) => {
window.ipcRenderer.invoke('renderer:convert-postman-to-bruno', collection)
- .then(result => resolve(result))
- .catch(err => {
+ .then((result) => resolve(result))
+ .catch((err) => {
console.error('Error converting Postman to Bruno via Electron:', err);
reject(new BrunoError('Conversion failed'));
});
diff --git a/packages/bruno-app/src/utils/network/grpc-event-listeners.js b/packages/bruno-app/src/utils/network/grpc-event-listeners.js
index 4362b9e98..95a09a70c 100644
--- a/packages/bruno-app/src/utils/network/grpc-event-listeners.js
+++ b/packages/bruno-app/src/utils/network/grpc-event-listeners.js
@@ -15,9 +15,8 @@ const useGrpcEventListeners = () => {
// Handle gRPC requestSent event
const removeGrpcRequestSentListener = ipcRenderer.on('grpc:request', (requestId, collectionUid, eventData) => {
-
dispatch(runGrpcRequestEvent({
- eventType: "request",
+ eventType: 'request',
itemUid: requestId,
collectionUid: collectionUid,
requestUid: requestId,
@@ -26,9 +25,8 @@ const useGrpcEventListeners = () => {
});
const removeGrpcMessageSentListener = ipcRenderer.on('grpc:message', (requestId, collectionUid, eventData) => {
-
dispatch(runGrpcRequestEvent({
- eventType: "message",
+ eventType: 'message',
itemUid: requestId,
collectionUid: collectionUid,
requestUid: requestId,
@@ -38,7 +36,6 @@ const useGrpcEventListeners = () => {
// Handle gRPC response event (for unary calls and streaming)
const removeGrpcResponseListener = ipcRenderer.on(`grpc:response`, (requestId, collectionUid, data) => {
-
dispatch(grpcResponseReceived({
itemUid: requestId,
collectionUid: collectionUid,
@@ -49,7 +46,6 @@ const useGrpcEventListeners = () => {
// Handle gRPC metadata
const removeGrpcMetadataListener = ipcRenderer.on(`grpc:metadata`, (requestId, collectionUid, data) => {
-
dispatch(grpcResponseReceived({
itemUid: requestId,
collectionUid: collectionUid,
@@ -57,10 +53,9 @@ const useGrpcEventListeners = () => {
eventData: data
}));
});
-
+
// Handle gRPC status updates
- const removeGrpcStatusListener = ipcRenderer.on(`grpc:status`, (requestId, collectionUid, data) => {
-
+ const removeGrpcStatusListener = ipcRenderer.on(`grpc:status`, (requestId, collectionUid, data) => {
dispatch(grpcResponseReceived({
itemUid: requestId,
collectionUid: collectionUid,
@@ -68,10 +63,9 @@ const useGrpcEventListeners = () => {
eventData: data
}));
});
-
+
// Handle gRPC errors
const removeGrpcErrorListener = ipcRenderer.on(`grpc:error`, (requestId, collectionUid, data) => {
-
dispatch(grpcResponseReceived({
itemUid: requestId,
collectionUid: collectionUid,
@@ -79,10 +73,9 @@ const useGrpcEventListeners = () => {
eventData: data
}));
});
-
+
// Handle gRPC end event
const removeGrpcEndListener = ipcRenderer.on(`grpc:server-end-stream`, (requestId, collectionUid, data) => {
-
dispatch(grpcResponseReceived({
itemUid: requestId,
collectionUid: collectionUid,
@@ -90,10 +83,9 @@ const useGrpcEventListeners = () => {
eventData: data
}));
});
-
+
// Handle gRPC cancel event
const removeGrpcCancelListener = ipcRenderer.on(`grpc:server-cancel-stream`, (requestId, collectionUid, data) => {
-
dispatch(grpcResponseReceived({
itemUid: requestId,
collectionUid: collectionUid,
@@ -103,7 +95,6 @@ const useGrpcEventListeners = () => {
});
const removeGrpcConnectionsChangedListener = ipcRenderer.on(`grpc:connections-changed`, (data) => {
-
dispatch(updateActiveConnectionsInStore(data));
});
@@ -118,8 +109,7 @@ const useGrpcEventListeners = () => {
removeGrpcCancelListener();
removeGrpcConnectionsChangedListener();
};
-
}, [isElectron]);
};
-export default useGrpcEventListeners;
\ No newline at end of file
+export default useGrpcEventListeners;
diff --git a/packages/bruno-app/src/utils/network/index.js b/packages/bruno-app/src/utils/network/index.js
index 721b3bd7b..0cf24d4ae 100644
--- a/packages/bruno-app/src/utils/network/index.js
+++ b/packages/bruno-app/src/utils/network/index.js
@@ -8,7 +8,7 @@ export const sendNetworkRequest = async (item, collection, environment, runtimeV
.then((response) => {
// if there is an error, we return the response object as is
if (response?.error) {
- resolve(response)
+ resolve(response);
}
resolve({
@@ -33,19 +33,17 @@ export const sendNetworkRequest = async (item, collection, environment, runtimeV
export const sendGrpcRequest = async (item, collection, environment, runtimeVariables) => {
return new Promise((resolve, reject) => {
startGrpcRequest(item, collection, environment, runtimeVariables)
- .then((initialState) => {
- // Return an initial state object to update the UI
- // The real response data will be handled by event listeners
- resolve({
- ...initialState,
- timeline: []
- });
- })
- .catch((err) => reject(err));
+ .then((initialState) => {
+ // Return an initial state object to update the UI
+ // The real response data will be handled by event listeners
+ resolve({
+ ...initialState,
+ timeline: []
+ });
+ })
+ .catch((err) => reject(err));
});
-}
-
-
+};
const sendHttpRequest = async (item, collection, environment, runtimeVariables) => {
return new Promise((resolve, reject) => {
@@ -85,19 +83,19 @@ export const startGrpcRequest = async (item, collection, environment, runtimeVar
return new Promise((resolve, reject) => {
const { ipcRenderer } = window;
const request = item.draft ? item.draft : item;
-
+
ipcRenderer.invoke('grpc:start-connection', {
- request,
- collection,
- environment,
+ request,
+ collection,
+ environment,
runtimeVariables
})
- .then(() => {
- resolve();
- })
- .catch(err => {
- reject(err);
- });
+ .then(() => {
+ resolve();
+ })
+ .catch((err) => {
+ reject(err);
+ });
});
};
@@ -190,7 +188,7 @@ export const isGrpcConnectionActive = async (connectionId) => {
return new Promise((resolve, reject) => {
const { ipcRenderer } = window;
ipcRenderer.invoke('grpc:is-connection-active', connectionId)
- .then(response => {
+ .then((response) => {
if (response.success) {
resolve(response.isActive);
} else {
@@ -199,7 +197,7 @@ export const isGrpcConnectionActive = async (connectionId) => {
resolve(false);
}
})
- .catch(err => {
+ .catch((err) => {
console.error('Failed to check connection status:', err);
// On error, assume the connection is not active
resolve(false);
@@ -217,14 +215,14 @@ export const isGrpcConnectionActive = async (connectionId) => {
export const generateGrpcSampleMessage = async (methodPath, existingMessage = null, options = {}) => {
return new Promise((resolve, reject) => {
const { ipcRenderer } = window;
-
- ipcRenderer.invoke('grpc:generate-sample-message', {
- methodPath,
- existingMessage,
- options
+
+ ipcRenderer.invoke('grpc:generate-sample-message', {
+ methodPath,
+ existingMessage,
+ options
})
- .then(resolve)
- .catch(reject);
+ .then(resolve)
+ .catch(reject);
});
};
diff --git a/packages/bruno-app/src/utils/tabs/index.js b/packages/bruno-app/src/utils/tabs/index.js
index 392b0835b..e66b9f148 100644
--- a/packages/bruno-app/src/utils/tabs/index.js
+++ b/packages/bruno-app/src/utils/tabs/index.js
@@ -17,4 +17,4 @@ export const scrollToTheActiveTab = () => {
if (activeTab) {
activeTab.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-app/src/utils/tests/collections/grpc-export-import.spec.js b/packages/bruno-app/src/utils/tests/collections/grpc-export-import.spec.js
index 9596e50d4..3fb13ddde 100644
--- a/packages/bruno-app/src/utils/tests/collections/grpc-export-import.spec.js
+++ b/packages/bruno-app/src/utils/tests/collections/grpc-export-import.spec.js
@@ -47,7 +47,7 @@ describe('gRPC Export/Import', () => {
name: 'Streaming Request',
request: {
url: 'grpc://localhost:50051',
- method: '/randomService/randomMethod',
+ method: '/randomService/randomMethod',
methodType: 'bidi-streaming',
protoPath: 'proto/streaming.proto',
headers: [],
diff --git a/packages/bruno-app/src/utils/tests/collections/items-sequencing.spec.js b/packages/bruno-app/src/utils/tests/collections/items-sequencing.spec.js
index adfb5dab9..5c103eaab 100644
--- a/packages/bruno-app/src/utils/tests/collections/items-sequencing.spec.js
+++ b/packages/bruno-app/src/utils/tests/collections/items-sequencing.spec.js
@@ -6,33 +6,32 @@ describe('resetSequencesInFolder', () => {
items: [
{ uid: '1', seq: 1 },
{ uid: '2', seq: 3 },
- { uid: '3', seq: 6 },
- ],
+ { uid: '3', seq: 6 }
+ ]
};
const fixedFolder = resetSequencesInFolder(folder.items);
expect(fixedFolder).toEqual([
{ uid: '1', seq: 1 },
{ uid: '2', seq: 2 },
- { uid: '3', seq: 3 },
+ { uid: '3', seq: 3 }
]);
});
-
it('should fix the sequences in the folder 2', () => {
const folder = {
items: [
{ uid: '1', seq: 3 },
{ uid: '2', seq: 1 },
- { uid: '3', seq: 2 },
- ],
+ { uid: '3', seq: 2 }
+ ]
};
const fixedFolder = resetSequencesInFolder(folder.items);
expect(fixedFolder).toEqual([
{ uid: '2', seq: 1 },
{ uid: '3', seq: 2 },
- { uid: '1', seq: 3 },
+ { uid: '1', seq: 3 }
]);
});
@@ -42,7 +41,7 @@ describe('resetSequencesInFolder', () => {
{ uid: '1', seq: 1 },
{ uid: '2', type: 'folder' },
{ uid: '3', type: 'folder' },
- { uid: '4', seq: 7 },
+ { uid: '4', seq: 7 }
]
};
@@ -51,7 +50,7 @@ describe('resetSequencesInFolder', () => {
{ uid: '1', seq: 1 },
{ uid: '2', seq: 2, type: 'folder' },
{ uid: '3', seq: 3, type: 'folder' },
- { uid: '4', seq: 4 },
+ { uid: '4', seq: 4 }
]);
});
@@ -61,8 +60,8 @@ describe('resetSequencesInFolder', () => {
{ uid: '1', seq: 2 },
{ uid: '2', seq: 2 },
{ uid: '3', seq: 3 },
- { uid: '4', seq: 1 },
- ],
+ { uid: '4', seq: 1 }
+ ]
};
const fixedFolder = resetSequencesInFolder(folder.items);
@@ -70,7 +69,7 @@ describe('resetSequencesInFolder', () => {
{ uid: '4', seq: 1 },
{ uid: '1', seq: 2 },
{ uid: '2', seq: 3 },
- { uid: '3', seq: 4 },
+ { uid: '3', seq: 4 }
]);
});
});
diff --git a/packages/bruno-app/src/utils/url/index.spec.js b/packages/bruno-app/src/utils/url/index.spec.js
index f3ff35074..db6af815a 100644
--- a/packages/bruno-app/src/utils/url/index.spec.js
+++ b/packages/bruno-app/src/utils/url/index.spec.js
@@ -293,7 +293,7 @@ describe('Url Utils - interpolateUrl, interpolateUrlPathParams', () => {
const url = '{{host}}/api/:id/path?foo={{foo}}&bar={{bar}}&baz={{process.env.baz}}';
const expectedUrl = 'https://example.com/api/:id/path?foo=foo_value&bar=bar_value&baz=baz_value';
- const result = interpolateUrl({ url, variables: { host: 'https://example.com', foo: 'foo_value', bar: 'bar_value', 'process.env.baz': 'baz_value' } });
+ const result = interpolateUrl({ url, variables: { 'host': 'https://example.com', 'foo': 'foo_value', 'bar': 'bar_value', 'process.env.baz': 'baz_value' } });
expect(result).toEqual(expectedUrl);
});
@@ -313,7 +313,7 @@ describe('Url Utils - interpolateUrl, interpolateUrlPathParams', () => {
const params = [{ name: 'id', type: 'path', enabled: true, value: '123' }];
const expectedUrl = 'https://example.com/api/123/path?foo=foo_value&bar=bar_value&baz=baz_value';
- const intermediateResult = interpolateUrl({ url, variables: { host: 'https://example.com', foo: 'foo_value', bar: 'bar_value', 'process.env.baz': 'baz_value' } });
+ const intermediateResult = interpolateUrl({ url, variables: { 'host': 'https://example.com', 'foo': 'foo_value', 'bar': 'bar_value', 'process.env.baz': 'baz_value' } });
const result = interpolateUrlPathParams(intermediateResult, params);
expect(result).toEqual(expectedUrl);
diff --git a/packages/bruno-cli/src/commands/import.js b/packages/bruno-cli/src/commands/import.js
index 78701ea36..2ee8d838b 100644
--- a/packages/bruno-cli/src/commands/import.js
+++ b/packages/bruno-cli/src/commands/import.js
@@ -75,7 +75,7 @@ const isUrl = (str) => {
const readOpenApiFile = async (source, options = {}) => {
try {
let content;
-
+
if (isUrl(source)) {
// Handle URL input
console.log(chalk.yellow(`Fetching specification from URL: ${source}`));
@@ -83,22 +83,22 @@ const readOpenApiFile = async (source, options = {}) => {
const axiosOptions = {
timeout: 30000, // 30 second timeout
maxContentLength: 10 * 1024 * 1024,
- validateStatus: status => status >= 200 && status < 300
+ validateStatus: (status) => status >= 200 && status < 300
};
-
+
// Skip SSL certificate validation if insecure flag is set
if (options.insecure) {
console.log(chalk.yellow('Warning: SSL certificate verification is disabled. Use with caution.'));
axiosOptions.httpsAgent = new (require('https')).Agent({ rejectUnauthorized: false });
}
-
+
const response = await axios.get(source, axiosOptions);
content = response.data;
} catch (error) {
if (error.code === 'ECONNABORTED') {
throw new Error('Request timed out. The server took too long to respond.');
- } else if (error.code === 'CERT_HAS_EXPIRED' || error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT' ||
- error.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
+ } else if (error.code === 'CERT_HAS_EXPIRED' || error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT'
+ || error.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
throw new Error(`SSL Certificate error: ${error.code}. Try using --insecure if you trust this source.`);
} else if (error.response) {
throw new Error(`Failed to fetch from URL: ${error.response.status} ${error.response.statusText}`);
@@ -108,7 +108,7 @@ const readOpenApiFile = async (source, options = {}) => {
throw new Error(`Error fetching URL: ${error.message}`);
}
}
-
+
// If response is already an object, return it directly
if (typeof content === 'object' && content !== null) {
return content;
@@ -120,7 +120,7 @@ const readOpenApiFile = async (source, options = {}) => {
}
content = fs.readFileSync(source, 'utf8');
}
-
+
// If content is a string, try to parse as JSON or YAML
if (typeof content === 'string') {
try {
@@ -133,7 +133,7 @@ const readOpenApiFile = async (source, options = {}) => {
}
}
}
-
+
return content;
} catch (error) {
// Let the specific error handling from above propagate
@@ -247,7 +247,7 @@ const handler = async (argv) => {
// Convert WSDL to Bruno format
brunoCollection = await wsdlToBruno(wsdlContent);
}
-
+
// Override collection name if provided
if (collectionName) {
brunoCollection.name = collectionName;
@@ -260,17 +260,17 @@ const handler = async (argv) => {
console.log(chalk.green(`Bruno collection saved as JSON to ${outputPath}`));
} else if (output) {
const resolvedOutput = path.resolve(output);
-
+
// Check if output is an existing directory
const isOutputDirectory = await exists(resolvedOutput) && isDirectory(resolvedOutput);
-
+
// Determine the final output directory
let outputDir;
if (isOutputDirectory) {
// If output is an existing directory, use collection name to create a subdirectory
const dirName = sanitizeName(brunoCollection.name);
outputDir = path.join(resolvedOutput, dirName);
-
+
// Check if this subfolder already exists
if (await exists(outputDir)) {
const dirContents = fs.readdirSync(outputDir);
@@ -285,14 +285,14 @@ const handler = async (argv) => {
} else {
// If output doesn't exist or is not a directory, use it directly
outputDir = resolvedOutput;
-
+
// Check if parent directory exists
const parentDir = path.dirname(outputDir);
if (!await exists(parentDir)) {
console.error(chalk.red(`Parent directory does not exist: ${parentDir}`));
process.exit(1);
}
-
+
fs.mkdirSync(outputDir, { recursive: true });
}
@@ -313,4 +313,4 @@ module.exports = {
isUrl,
readOpenApiFile,
readWSDLFile
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-cli/src/commands/run.js b/packages/bruno-cli/src/commands/run.js
index 3448cebab..ce0b6d3dc 100644
--- a/packages/bruno-cli/src/commands/run.js
+++ b/packages/bruno-cli/src/commands/run.js
@@ -7,7 +7,7 @@ const { exists, isFile, isDirectory } = require('../utils/filesystem');
const { runSingleRequest } = require('../runner/run-single-request');
const { getEnvVars } = require('../utils/bru');
const { parseEnvironmentJson } = require('../utils/environment');
-const { isRequestTagsIncluded } = require("@usebruno/common")
+const { isRequestTagsIncluded } = require('@usebruno/common');
const makeJUnitOutput = require('../reporters/junit');
const makeHtmlOutput = require('../reporters/html');
const { rpad } = require('../utils/common');
@@ -98,7 +98,7 @@ const printRunSummary = (results) => {
totalPostResponseTests,
passedPostResponseTests,
failedPostResponseTests
- }
+ };
};
const getJsSandboxRuntime = (sandbox) => {
@@ -199,8 +199,8 @@ const builder = async (yargs) => {
default: false
})
.option('delay', {
- type:"number",
- description: "Delay between each requests (in miliseconds)"
+ type: 'number',
+ description: 'Delay between each requests (in miliseconds)'
})
.option('tags', {
type: 'string',
@@ -393,8 +393,8 @@ const handler = async function (argv) {
const match = value.match(/^([^=]+)=(.*)$/);
if (!match) {
console.error(
- chalk.red(`Overridable environment variable not correct: use name=value - presented: `) +
- chalk.dim(`${value}`)
+ chalk.red(`Overridable environment variable not correct: use name=value - presented: `)
+ + chalk.dim(`${value}`)
);
process.exit(constants.EXIT_STATUS.ERROR_INCORRECT_ENV_OVERRIDE);
}
@@ -483,7 +483,7 @@ const handler = async function (argv) {
recursive = true;
}
- const resolvedPaths = paths.map(p => path.resolve(process.cwd(), p));
+ const resolvedPaths = paths.map((p) => path.resolve(process.cwd(), p));
for (const resolvedPath of resolvedPaths) {
const pathExists = await exists(resolvedPath);
@@ -499,13 +499,13 @@ const handler = async function (argv) {
requestItems = requestItems.filter((item) => {
const requestHasTests = hasExecutableTestInScript(item.request?.tests);
const requestHasActiveAsserts = item.request?.assertions.some((x) => x.enabled) || false;
-
+
const preRequestScript = item.request?.script?.req;
const requestHasPreRequestTests = hasExecutableTestInScript(preRequestScript);
-
+
const postResponseScript = item.request?.script?.res;
const requestHasPostResponseTests = hasExecutableTestInScript(postResponseScript);
-
+
return requestHasTests || requestHasActiveAsserts || requestHasPreRequestTests || requestHasPostResponseTests;
});
}
@@ -540,7 +540,7 @@ const handler = async function (argv) {
}
reject(`bru.runRequest: invalid request path - ${itemPathname}`);
});
- }
+ };
let currentRequestIndex = 0;
let nJumps = 0; // count the number of jumps to avoid infinite loops
@@ -564,12 +564,12 @@ const handler = async function (argv) {
const isLastRun = currentRequestIndex === requestItems.length - 1;
const isValidDelay = !Number.isNaN(delay) && delay > 0;
- if(isValidDelay && !isLastRun){
- console.log(chalk.yellow(`Waiting for ${delay}ms or ${(delay/1000).toFixed(3)}s before next request.`));
+ if (isValidDelay && !isLastRun) {
+ console.log(chalk.yellow(`Waiting for ${delay}ms or ${(delay / 1000).toFixed(3)}s before next request.`));
await new Promise((resolve) => setTimeout(resolve, delay));
}
- if(Number.isNaN(delay) && !isLastRun){
+ if (Number.isNaN(delay) && !isLastRun) {
console.log(chalk.red(`Ignoring delay because it's not a valid number.`));
}
@@ -610,7 +610,6 @@ const handler = async function (argv) {
});
}
-
// bail if option is set and there is a failure
if (bail) {
const requestFailure = result?.error && !result?.skipped;
@@ -643,7 +642,7 @@ const handler = async function (argv) {
if (nextRequestIdx >= 0) {
currentRequestIndex = nextRequestIdx;
} else {
- console.error("Could not find request with name '" + nextRequestName + "'");
+ console.error('Could not find request with name \'' + nextRequestName + '\'');
currentRequestIndex++;
}
} else {
@@ -667,13 +666,12 @@ const handler = async function (argv) {
};
const reporters = {
- 'json': (path) => fs.writeFileSync(path, JSON.stringify(outputJson, null, 2)),
- 'junit': (path) => makeJUnitOutput(results, path),
+ json: (path) => fs.writeFileSync(path, JSON.stringify(outputJson, null, 2)),
+ junit: (path) => makeJUnitOutput(results, path),
html: (path) => makeHtmlOutput(outputJson, path, runCompletionTime, environmentName)
- }
+ };
- for (const formatter of Object.keys(formats))
- {
+ for (const formatter of Object.keys(formats)) {
const reportPath = formats[formatter];
const reporter = reporters[formatter];
diff --git a/packages/bruno-cli/src/index.js b/packages/bruno-cli/src/index.js
index 038667072..f92f9ce0a 100644
--- a/packages/bruno-cli/src/index.js
+++ b/packages/bruno-cli/src/index.js
@@ -20,7 +20,7 @@ const run = async () => {
.commandDir('commands')
.epilogue(CLI_EPILOGUE)
.usage('Usage: $0 [options]')
- .demandCommand(1, "Woof!! Let's play with some APIs!!")
+ .demandCommand(1, 'Woof!! Let\'s play with some APIs!!')
.help('h')
.alias('h', 'help');
};
diff --git a/packages/bruno-cli/src/reporters/html.js b/packages/bruno-cli/src/reporters/html.js
index 93a201907..b6647ac8c 100644
--- a/packages/bruno-cli/src/reporters/html.js
+++ b/packages/bruno-cli/src/reporters/html.js
@@ -17,7 +17,7 @@ const makeHtmlOutput = async (results, outputPath, runCompletionTime, environmen
runnerResults = results;
}
- const htmlString = generateHtmlReport({
+ const htmlString = generateHtmlReport({
runnerResults: runnerResults,
version: `usebruno v${CLI_VERSION}`,
environment: environment,
diff --git a/packages/bruno-cli/src/reporters/junit.js b/packages/bruno-cli/src/reporters/junit.js
index 133bfbddf..aa2b0eb2e 100644
--- a/packages/bruno-cli/src/reporters/junit.js
+++ b/packages/bruno-cli/src/reporters/junit.js
@@ -23,49 +23,48 @@ const makeJUnitOutput = async (results, outputPath) => {
'@timestamp': new Date().toISOString().split('Z')[0],
'@hostname': os.hostname(),
'@time': result.runtime.toFixed(3),
- testcase: []
+ 'testcase': []
};
- result.assertionResults &&
- result.assertionResults.forEach((assertion) => {
- const testcase = {
- '@name': `${assertion.lhsExpr} ${assertion.rhsExpr}`,
- '@status': assertion.status,
- '@classname': result.request.url,
- '@time': (result.runtime / totalTests).toFixed(3)
- };
+ result.assertionResults
+ && result.assertionResults.forEach((assertion) => {
+ const testcase = {
+ '@name': `${assertion.lhsExpr} ${assertion.rhsExpr}`,
+ '@status': assertion.status,
+ '@classname': result.request.url,
+ '@time': (result.runtime / totalTests).toFixed(3)
+ };
- if (assertion.status === 'fail') {
- suite['@failures']++;
+ if (assertion.status === 'fail') {
+ suite['@failures']++;
- testcase.failure = [{ '@type': 'failure', '@message': assertion.error }];
- }
+ testcase.failure = [{ '@type': 'failure', '@message': assertion.error }];
+ }
- suite.testcase.push(testcase);
- });
+ suite.testcase.push(testcase);
+ });
- result.testResults &&
- result.testResults.forEach((test) => {
- const testcase = {
- '@name': test.description,
- '@status': test.status,
- '@classname': result.request.url,
- '@time': (result.runtime / totalTests).toFixed(3)
- };
+ result.testResults
+ && result.testResults.forEach((test) => {
+ const testcase = {
+ '@name': test.description,
+ '@status': test.status,
+ '@classname': result.request.url,
+ '@time': (result.runtime / totalTests).toFixed(3)
+ };
- if (test.status === 'fail') {
- suite['@failures']++;
+ if (test.status === 'fail') {
+ suite['@failures']++;
- testcase.failure = [{ '@type': 'failure', '@message': test.error }];
- }
+ testcase.failure = [{ '@type': 'failure', '@message': test.error }];
+ }
- suite.testcase.push(testcase);
- });
+ suite.testcase.push(testcase);
+ });
if (result?.skipped) {
suite['@skipped'] = 1;
- }
- else if (result.error) {
+ } else if (result.error) {
suite['@errors'] = 1;
suite['@tests'] = 1;
suite.testcase = [
@@ -74,7 +73,7 @@ const makeJUnitOutput = async (results, outputPath) => {
'@status': 'fail',
'@classname': result.request.url,
'@time': result.runtime.toFixed(3),
- error: [{ '@type': 'error', '@message': result.error }]
+ 'error': [{ '@type': 'error', '@message': result.error }]
}
];
}
diff --git a/packages/bruno-cli/src/runner/interpolate-vars.js b/packages/bruno-cli/src/runner/interpolate-vars.js
index 3ed8ba735..b2f614e7e 100644
--- a/packages/bruno-cli/src/runner/interpolate-vars.js
+++ b/packages/bruno-cli/src/runner/interpolate-vars.js
@@ -89,10 +89,10 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
} else if (contentType === 'multipart/form-data') {
if (Array.isArray(request?.data) && !(request.data instanceof FormData)) {
try {
- request.data = request?.data?.map(d => ({
+ request.data = request?.data?.map((d) => ({
...d,
value: _interpolate(d?.value)
- }));
+ }));
} catch (err) {}
}
} else {
@@ -263,10 +263,10 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
if (request.ntlmConfig) {
request.ntlmConfig.username = _interpolate(request.ntlmConfig.username) || '';
request.ntlmConfig.password = _interpolate(request.ntlmConfig.password) || '';
- request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || '';
+ request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || '';
}
- if(request?.auth) delete request.auth;
+ if (request?.auth) delete request.auth;
if (request) return request;
};
diff --git a/packages/bruno-cli/src/runner/prepare-request.js b/packages/bruno-cli/src/runner/prepare-request.js
index 607676d36..aeadc2109 100644
--- a/packages/bruno-cli/src/runner/prepare-request.js
+++ b/packages/bruno-cli/src/runner/prepare-request.js
@@ -66,7 +66,7 @@ const prepareRequest = async (item = {}, collection = {}) => {
if (collectionAuth.apikey?.placement === 'header') {
axiosRequest.headers[collectionAuth.apikey?.key] = collectionAuth.apikey?.value;
}
-
+
if (collectionAuth.apikey?.placement === 'queryparams') {
if (axiosRequest.url && collectionAuth.apikey?.key) {
try {
@@ -89,7 +89,7 @@ const prepareRequest = async (item = {}, collection = {}) => {
if (collectionAuth.mode === 'oauth2') {
const grantType = get(collectionAuth, 'oauth2.grantType');
-
+
if (grantType === 'client_credentials') {
axiosRequest.oauth2 = {
grantType,
@@ -226,7 +226,7 @@ const prepareRequest = async (item = {}, collection = {}) => {
if (request.auth.mode === 'oauth2') {
const grantType = get(request, 'auth.oauth2.grantType');
-
+
if (grantType === 'client_credentials') {
axiosRequest.oauth2 = {
grantType: grantType,
@@ -265,12 +265,12 @@ const prepareRequest = async (item = {}, collection = {}) => {
};
}
}
-
+
if (request.auth.mode === 'apikey') {
if (request.auth.apikey?.placement === 'header') {
axiosRequest.headers[request.auth.apikey?.key] = request.auth.apikey?.value;
}
-
+
if (request.auth.apikey?.placement === 'queryparams') {
if (axiosRequest.url && request.auth.apikey?.key) {
try {
diff --git a/packages/bruno-cli/src/runner/run-single-request.js b/packages/bruno-cli/src/runner/run-single-request.js
index d21f8a31d..72511b3a2 100644
--- a/packages/bruno-cli/src/runner/run-single-request.js
+++ b/packages/bruno-cli/src/runner/run-single-request.js
@@ -167,7 +167,7 @@ const runSingleRequest = async function (
// run pre request script
const requestScriptFile = get(request, 'script.req');
- const collectionName = collection?.brunoConfig?.name
+ const collectionName = collection?.brunoConfig?.name;
if (requestScriptFile?.length) {
const scriptRuntime = new ScriptRuntime({ runtime: scriptingConfig?.runtime });
const result = await scriptRuntime.runRequestScript(
@@ -236,7 +236,7 @@ const runSingleRequest = async function (
const insecure = get(options, 'insecure', false);
const noproxy = get(options, 'noproxy', false);
const httpsAgentRequestFields = {};
-
+
if (insecure) {
httpsAgentRequestFields['rejectUnauthorized'] = false;
} else {
@@ -291,7 +291,7 @@ const runSingleRequest = async function (
const collectionProxyConfig = get(brunoConfig, 'proxy', {});
const collectionProxyEnabled = get(collectionProxyConfig, 'enabled', false);
-
+
if (noproxy) {
// If noproxy flag is set, don't use any proxy
proxyMode = 'off';
@@ -383,40 +383,40 @@ const runSingleRequest = async function (
});
}
- //set cookies if enabled
+ // set cookies if enabled
if (!options.disableCookies) {
const cookieString = getCookieStringForUrl(request.url);
if (cookieString && typeof cookieString === 'string' && cookieString.length) {
const existingCookieHeaderName = Object.keys(request.headers).find(
- name => name.toLowerCase() === 'cookie'
+ (name) => name.toLowerCase() === 'cookie'
);
const existingCookieString = existingCookieHeaderName ? request.headers[existingCookieHeaderName] : '';
-
+
// Helper function to parse cookies into an object
const parseCookies = (str) => str.split(';').reduce((cookies, cookie) => {
- const [name, ...rest] = cookie.split('=');
- if (name && name.trim()) {
- cookies[name.trim()] = rest.join('=').trim();
- }
- return cookies;
+ const [name, ...rest] = cookie.split('=');
+ if (name && name.trim()) {
+ cookies[name.trim()] = rest.join('=').trim();
+ }
+ return cookies;
}, {});
-
+
const mergedCookies = {
- ...parseCookies(existingCookieString),
- ...parseCookies(cookieString),
+ ...parseCookies(existingCookieString),
+ ...parseCookies(cookieString)
};
-
+
const combinedCookieString = Object.entries(mergedCookies)
- .map(([name, value]) => `${name}=${value}`)
- .join('; ');
-
+ .map(([name, value]) => `${name}=${value}`)
+ .join('; ');
+
request.headers[existingCookieHeaderName || 'Cookie'] = combinedCookieString;
}
}
// stringify the request url encoded params
const contentTypeHeader = Object.keys(request.headers).find(
- name => name.toLowerCase() === 'content-type'
+ (name) => name.toLowerCase() === 'content-type'
);
if (contentTypeHeader && request.headers[contentTypeHeader] === 'application/x-www-form-urlencoded') {
@@ -462,7 +462,7 @@ const runSingleRequest = async function (
const token = await getOAuth2Token(request.oauth2);
if (token) {
const { tokenPlacement = 'header', tokenHeaderPrefix = '', tokenQueryKey = 'access_token' } = request.oauth2;
-
+
if (tokenPlacement === 'header' && token) {
request.headers['Authorization'] = `${tokenHeaderPrefix} ${token}`.trim();
} else if (tokenPlacement === 'url') {
@@ -478,14 +478,13 @@ const runSingleRequest = async function (
} catch (error) {
console.error('OAuth2 token fetch error:', error.message);
}
-
+
// Remove oauth2 config from request to prevent it from being sent
delete request.oauth2;
}
let response, responseTime;
try {
-
// Set timeout from request settings, default to 0 (no timeout)
const requestTimeout = request.settings?.timeout || 0;
if (requestTimeout > 0) {
@@ -502,7 +501,6 @@ const runSingleRequest = async function (
delete request.ntlmConfig;
}
-
if (request.awsv4config) {
// todo: make this happen in prepare-request.js
// interpolate the aws v4 config
@@ -537,7 +535,7 @@ const runSingleRequest = async function (
responseTime = response.headers.get('request-duration');
response.headers.delete('request-duration');
- //save cookies if enabled
+ // save cookies if enabled
if (!options.disableCookies) {
saveCookies(request.url, response.headers);
}
@@ -571,7 +569,7 @@ const runSingleRequest = async function (
url: null,
responseTime: 0
},
- error: err?.message || err?.errors?.map(e => e?.message)?.at(0) || err?.code || 'Request Failed!',
+ error: err?.message || err?.errors?.map((e) => e?.message)?.at(0) || err?.code || 'Request Failed!',
status: 'error',
assertionResults: [],
testResults: [],
@@ -586,8 +584,8 @@ const runSingleRequest = async function (
response.responseTime = responseTime;
console.log(
- chalk.green(stripExtension(relativeItemPathname)) +
- chalk.dim(` (${response.status} ${response.statusText}) - ${responseTime} ms`)
+ chalk.green(stripExtension(relativeItemPathname))
+ + chalk.dim(` (${response.status} ${response.statusText}) - ${responseTime} ms`)
);
// Log pre-request test results
@@ -675,7 +673,6 @@ const runSingleRequest = async function (
}
}
-
logResults(assertionResults, 'Assertions');
return {
diff --git a/packages/bruno-cli/src/utils/axios-instance.js b/packages/bruno-cli/src/utils/axios-instance.js
index 4bba1af73..d6162089e 100644
--- a/packages/bruno-cli/src/utils/axios-instance.js
+++ b/packages/bruno-cli/src/utils/axios-instance.js
@@ -33,17 +33,16 @@ const createRedirectConfig = (error, redirectUrl) => {
if (METHOD_CHANGING_REDIRECTS.includes(statusCode) && originalMethod !== 'head') {
requestConfig.method = 'get';
requestConfig.data = undefined;
-
+
// Clean up headers that are no longer relevant
delete requestConfig.headers['content-length'];
delete requestConfig.headers['Content-Length'];
- delete requestConfig.headers['content-type'];
+ delete requestConfig.headers['content-type'];
delete requestConfig.headers['Content-Type'];
} else {
// For 307, 308 and other status codes: preserve method and body
- if (requestConfig.data && typeof requestConfig.data === 'object' &&
- requestConfig.data.constructor && requestConfig.data.constructor.name === 'FormData') {
-
+ if (requestConfig.data && typeof requestConfig.data === 'object'
+ && requestConfig.data.constructor && requestConfig.data.constructor.name === 'FormData') {
const formData = requestConfig.data;
if (formData._released || (formData._streams && formData._streams.length === 0)) {
if (error.config._originalMultipartData && error.config.collectionPath) {
@@ -51,7 +50,7 @@ const createRedirectConfig = (error, redirectUrl) => {
requestConfig.data = recreatedForm;
const formHeaders = recreatedForm.getHeaders();
Object.assign(requestConfig.headers, formHeaders);
-
+
// preserve the original data for potential future redirects
requestConfig._originalMultipartData = error.config._originalMultipartData;
requestConfig.collectionPath = error.config.collectionPath;
@@ -80,7 +79,7 @@ function makeAxiosInstance({ requestMaxRedirects = 5, disableCookies } = {}) {
proxy: false,
maxRedirects: 0,
headers: {
- "User-Agent": `bruno-runtime/${CLI_VERSION}`
+ 'User-Agent': `bruno-runtime/${CLI_VERSION}`
}
});
@@ -133,7 +132,7 @@ function makeAxiosInstance({ requestMaxRedirects = 5, disableCookies } = {}) {
redirectUrl = URL.resolve(error.config.url, locationHeader);
}
- if (!disableCookies){
+ if (!disableCookies) {
saveCookies(error.config.url, error.response.headers);
}
diff --git a/packages/bruno-cli/src/utils/bru.js b/packages/bruno-cli/src/utils/bru.js
index 58d4a520a..c132891e1 100644
--- a/packages/bruno-cli/src/utils/bru.js
+++ b/packages/bruno-cli/src/utils/bru.js
@@ -1,5 +1,5 @@
const _ = require('lodash');
-const {
+const {
parseRequest: _parseRequest,
parseCollection: _parseCollection
} = require('@usebruno/filestore');
@@ -24,7 +24,7 @@ const collectionBruToJson = (bru) => {
const sequence = _.get(json, 'meta.seq');
if (json?.meta) {
transformedJson.meta = {
- name: json.meta.name,
+ name: json.meta.name
};
if (sequence) {
@@ -94,11 +94,11 @@ const bruToJson = (bru) => {
if (requestType === 'grpc-request') {
const selectedMethod = _.get(json, 'grpc.method');
- if(selectedMethod) transformedJson.request.method = selectedMethod;
+ if (selectedMethod) transformedJson.request.method = selectedMethod;
const selectedMethodType = _.get(json, 'grpc.methodType');
- if(selectedMethodType) transformedJson.request.methodType = selectedMethodType;
+ if (selectedMethodType) transformedJson.request.methodType = selectedMethodType;
const protoPath = _.get(json, 'grpc.protoPath');
- if(protoPath) transformedJson.request.protoPath = protoPath;
+ if (protoPath) transformedJson.request.protoPath = protoPath;
transformedJson.request.auth.mode = _.get(json, 'grpc.auth', 'none');
transformedJson.request.body = _.get(json, 'body', {
mode: 'grpc',
diff --git a/packages/bruno-cli/src/utils/collection.js b/packages/bruno-cli/src/utils/collection.js
index 72b6e5676..8358bc47d 100644
--- a/packages/bruno-cli/src/utils/collection.js
+++ b/packages/bruno-cli/src/utils/collection.js
@@ -9,7 +9,7 @@ const chalk = require('chalk');
const createCollectionJsonFromPathname = (collectionPath) => {
const environmentsPath = path.join(collectionPath, `environments`);
-
+
// get the collection bruno json config [/bruno.json]
const brunoConfig = getCollectionBrunoJsonConfig(collectionPath);
@@ -29,17 +29,16 @@ const createCollectionJsonFromPathname = (collectionPath) => {
if (stats.isDirectory()) {
if (filePath === environmentsPath) continue;
if (filePath.startsWith('.git') || filePath.startsWith('node_modules')) continue;
-
+
// get the folder root
- let folderItem = { name: file, pathname: filePath, type: 'folder', items: traverse(filePath) }
+ let folderItem = { name: file, pathname: filePath, type: 'folder', items: traverse(filePath) };
const folderBruJson = getFolderRoot(filePath);
if (folderBruJson) {
folderItem.root = folderBruJson;
folderItem.seq = folderBruJson.meta.seq;
}
currentDirItems.push(folderItem);
- }
- else {
+ } else {
if (['collection.bru', 'folder.bru'].includes(file)) continue;
if (path.extname(filePath) !== '.bru') continue;
@@ -78,7 +77,7 @@ const createCollectionJsonFromPathname = (collectionPath) => {
root: collectionRoot,
pathname: collectionPath,
items: collectionItems
- }
+ };
return collection;
};
@@ -96,7 +95,7 @@ const getCollectionBrunoJsonConfig = (dir) => {
const brunoConfigFile = fs.readFileSync(brunoJsonPath, 'utf8');
const brunoConfig = JSON.parse(brunoConfigFile);
return brunoConfig;
-}
+};
const getCollectionRoot = (dir) => {
const collectionRootPath = path.join(dir, 'collection.bru');
@@ -191,7 +190,7 @@ const mergeVars = (collection, request, requestTreePath) => {
request.folderVariables = folderVariables;
request.requestVariables = requestVariables;
- if(request?.vars) {
+ if (request?.vars) {
request.vars.req = Array.from(reqVars, ([name, value]) => ({
name,
value,
@@ -359,7 +358,7 @@ const mergeAuth = (collection, request, requestTreePath) => {
if (request.auth && request.auth.mode === 'inherit') {
request.auth = effectiveAuth;
}
-}
+};
const getAllRequestsInFolder = (folderItems = [], recursive = true) => {
let requests = [];
@@ -380,12 +379,11 @@ const getAllRequestsInFolder = (folderItems = [], recursive = true) => {
const getAllRequestsAtFolderRoot = (folderItems = []) => {
return getAllRequestsInFolder(folderItems, false);
-}
+};
-const getCallStack = (resolvedPaths = [], collection, {recursive}) => {
+const getCallStack = (resolvedPaths = [], collection, { recursive }) => {
let requestItems = [];
-
if (!resolvedPaths || !resolvedPaths.length) {
return requestItems;
}
@@ -430,7 +428,7 @@ const safeWriteFileSync = (filePath, content) => {
/**
* Creates a Bruno collection directory structure from a Bruno collection object
- *
+ *
* @param {Object} collection - The Bruno collection object
* @param {string} dirPath - The output directory path
*/
@@ -442,9 +440,9 @@ const createCollectionFromBrunoObject = async (collection, dirPath) => {
type: 'collection',
ignore: ['node_modules', '.git']
};
-
+
fs.writeFileSync(
- path.join(dirPath, 'bruno.json'),
+ path.join(dirPath, 'bruno.json'),
JSON.stringify(brunoConfig, null, 2)
);
@@ -474,7 +472,7 @@ const createCollectionFromBrunoObject = async (collection, dirPath) => {
/**
* Recursively processes collection items to create files and folders
- *
+ *
* @param {Array} items - Collection items
* @param {string} currentPath - Current directory path
*/
@@ -537,17 +535,17 @@ const processCollectionItems = async (items = [], currentPath) => {
}
};
-const sortByNameThenSequence = items => {
- const isSeqValid = seq => Number.isFinite(seq) && Number.isInteger(seq) && seq > 0;
+const sortByNameThenSequence = (items) => {
+ const isSeqValid = (seq) => Number.isFinite(seq) && Number.isInteger(seq) && seq > 0;
// Sort folders alphabetically by name
const alphabeticallySorted = [...items].sort((a, b) => a.name && b.name && a.name.localeCompare(b.name));
// Extract folders without 'seq'
- const withoutSeq = alphabeticallySorted.filter(f => !isSeqValid(f['seq']));
+ const withoutSeq = alphabeticallySorted.filter((f) => !isSeqValid(f['seq']));
// Extract folders with 'seq' and sort them by 'seq'
- const withSeq = alphabeticallySorted.filter(f => isSeqValid(f['seq'])).sort((a, b) => a.seq - b.seq);
+ const withSeq = alphabeticallySorted.filter((f) => isSeqValid(f['seq'])).sort((a, b) => a.seq - b.seq);
const sortedItems = withoutSeq;
@@ -566,7 +564,7 @@ const sortByNameThenSequence = items => {
const newGroup = Array.isArray(existingItem)
? [...existingItem, item]
: [existingItem, item];
-
+
withoutSeq.splice(position, 1, newGroup);
} else {
// Insert item at the specified position
@@ -578,7 +576,6 @@ const sortByNameThenSequence = items => {
return sortedItems.flat();
};
-
module.exports = {
createCollectionJsonFromPathname,
mergeHeaders,
@@ -591,4 +588,4 @@ module.exports = {
getAllRequestsInFolder,
getAllRequestsAtFolderRoot,
getCallStack
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-cli/src/utils/filesystem.js b/packages/bruno-cli/src/utils/filesystem.js
index e06d962c8..8c589f06a 100644
--- a/packages/bruno-cli/src/utils/filesystem.js
+++ b/packages/bruno-cli/src/utils/filesystem.js
@@ -120,41 +120,41 @@ const getSubDirectories = (dir) => {
/**
* Sanitizes a filename to make it safe for filesystem operations
- *
+ *
* @param {string} name - The name to sanitize
* @returns {string} - The sanitized name
*/
const sanitizeName = (name) => {
if (!name) return '';
-
+
const invalidCharacters = /[<>:"/\\|?*\x00-\x1F]/g;
return name
- .replace(invalidCharacters, '-') // replace invalid characters with hyphens
- .replace(/^[.\s-]+/, '') // remove leading dots, hyphens and spaces
- .replace(/[.\s]+$/, ''); // remove trailing dots and spaces (keep trailing hyphens)
+ .replace(invalidCharacters, '-') // replace invalid characters with hyphens
+ .replace(/^[.\s-]+/, '') // remove leading dots, hyphens and spaces
+ .replace(/[.\s]+$/, ''); // remove trailing dots and spaces (keep trailing hyphens)
};
/**
* Validates if a name is valid for the filesystem
- *
+ *
* @param {string} name - The name to validate
* @returns {boolean} - True if the name is valid, false otherwise
*/
const validateName = (name) => {
if (!name) return false;
-
+
const reservedDeviceNames = /^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$/i;
const firstCharacter = /^[^.\s\-\<>:"/\\|?*\x00-\x1F]/; // no dot, space, or hyphen at start
- const middleCharacters = /^[^<>:"/\\|?*\x00-\x1F]*$/; // no invalid characters
- const lastCharacter = /[^.\s]$/; // no dot or space at end, hyphen allowed
-
- if (name.length > 255) return false; // max name length
+ const middleCharacters = /^[^<>:"/\\|?*\x00-\x1F]*$/; // no invalid characters
+ const lastCharacter = /[^.\s]$/; // no dot or space at end, hyphen allowed
+
+ if (name.length > 255) return false; // max name length
if (reservedDeviceNames.test(name)) return false; // windows reserved names
return (
- firstCharacter.test(name) &&
- middleCharacters.test(name) &&
- lastCharacter.test(name)
+ firstCharacter.test(name)
+ && middleCharacters.test(name)
+ && lastCharacter.test(name)
);
};
diff --git a/packages/bruno-cli/src/utils/form-data.js b/packages/bruno-cli/src/utils/form-data.js
index eab5d5824..9bff10442 100644
--- a/packages/bruno-cli/src/utils/form-data.js
+++ b/packages/bruno-cli/src/utils/form-data.js
@@ -39,4 +39,4 @@ const createFormData = (data, collectionPath) => {
module.exports = {
createFormData
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-cli/src/utils/proxy-util.js b/packages/bruno-cli/src/utils/proxy-util.js
index 2a93d517e..3d3be5045 100644
--- a/packages/bruno-cli/src/utils/proxy-util.js
+++ b/packages/bruno-cli/src/utils/proxy-util.js
@@ -79,15 +79,14 @@ class PatchedHttpsProxyAgent extends HttpsProxyAgent {
}
}
-
const getSystemProxyEnvVariables = () => {
const { http_proxy, HTTP_PROXY, https_proxy, HTTPS_PROXY, no_proxy, NO_PROXY } = process.env;
return {
http_proxy: http_proxy || HTTP_PROXY,
https_proxy: https_proxy || HTTPS_PROXY,
no_proxy: no_proxy || NO_PROXY
- };
-}
+ };
+};
module.exports = {
shouldUseProxy,
diff --git a/packages/bruno-cli/src/utils/request.js b/packages/bruno-cli/src/utils/request.js
index 6a75a3cc7..44f3fd6a0 100644
--- a/packages/bruno-cli/src/utils/request.js
+++ b/packages/bruno-cli/src/utils/request.js
@@ -1,28 +1,27 @@
-
// Check for meaningful test() calls (not commented out or in strings)
const hasExecutableTestInScript = (script) => {
if (!script) return false;
-
+
// Remove single-line comments (// ...) and multi-line comments (/* ... */)
let cleanScript = script
- .replace(/\/\/.*$/gm, '') // Remove line comments
+ .replace(/\/\/.*$/gm, '') // Remove line comments
.replace(/\/\*[\s\S]*?\*\//g, ''); // Remove block comments
-
+
// Remove string literals to avoid matching test() inside strings
cleanScript = cleanScript
- .replace(/"(?:[^"\\]|\\.)*"/g, '""') // Remove double-quoted strings
- .replace(/'(?:[^'\\]|\\.)*'/g, "''") // Remove single-quoted strings
+ .replace(/"(?:[^"\\]|\\.)*"/g, '""') // Remove double-quoted strings
+ .replace(/'(?:[^'\\]|\\.)*'/g, '\'\'') // Remove single-quoted strings
.replace(/`(?:[^`\\]|\\.)*`/g, '``'); // Remove template literals
-
+
// Look for standalone test() calls (not object method calls like obj.test())
// Find all test( occurrences and check they're not preceded by dots
let hasValidTest = false;
let searchFrom = 0;
-
+
while (true) {
const index = cleanScript.indexOf('test', searchFrom);
if (index === -1) break;
-
+
// Check if this looks like test( with optional whitespace
const afterTest = cleanScript.substring(index + 4);
if (/^\s*\(/.test(afterTest)) {
@@ -32,13 +31,13 @@ const hasExecutableTestInScript = (script) => {
break;
}
}
-
+
searchFrom = index + 1;
}
-
+
return hasValidTest;
};
module.exports = {
hasExecutableTestInScript
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-cli/tests/runner/collection-json-from-pathname.spec.js b/packages/bruno-cli/tests/runner/collection-json-from-pathname.spec.js
index 8cab346cd..b26a08443 100644
--- a/packages/bruno-cli/tests/runner/collection-json-from-pathname.spec.js
+++ b/packages/bruno-cli/tests/runner/collection-json-from-pathname.spec.js
@@ -1,19 +1,19 @@
-const path = require("node:path");
+const path = require('node:path');
const { describe, it, expect } = require('@jest/globals');
const constants = require('../../src/constants');
const { createCollectionJsonFromPathname } = require('../../src/utils/collection');
describe('create collection json from pathname', () => {
- it("should throw an error when the pathname is not a valid bruno collection root", () => {
+ it('should throw an error when the pathname is not a valid bruno collection root', () => {
const invalidCollectionPathname = path.join(__dirname, './fixtures/collection-invalid');
jest.spyOn(console, 'error').mockImplementation(() => { });
let mockProcessExit = jest.spyOn(process, 'exit').mockImplementation((code) => { throw new Error(code); });
try { createCollectionJsonFromPathname(invalidCollectionPathname); } catch { }
expect(mockProcessExit).toHaveBeenCalledWith(constants.EXIT_STATUS.ERROR_NOT_IN_COLLECTION);
jest.restoreAllMocks();
- })
+ });
- it("creates a bruno collection json from the collection bru files", () => {
+ it('creates a bruno collection json from the collection bru files', () => {
const collectionPathname = path.join(__dirname, './fixtures/collection-json-from-pathname/collection');
const outputCollectionJson = createCollectionJsonFromPathname(collectionPathname);
@@ -21,10 +21,10 @@ describe('create collection json from pathname', () => {
expect(c).toBeDefined();
/* collection bruno.json */
- expect(c).toHaveProperty('brunoConfig.version', "1");
+ expect(c).toHaveProperty('brunoConfig.version', '1');
expect(c).toHaveProperty('brunoConfig.name', 'collection');
expect(c).toHaveProperty('brunoConfig.type', 'collection');
- expect(c).toHaveProperty('brunoConfig.ignore', ["node_modules", ".git"]);
+ expect(c).toHaveProperty('brunoConfig.ignore', ['node_modules', '.git']);
expect(c).toHaveProperty('brunoConfig.proxy.enabled', false);
expect(c).toHaveProperty('brunoConfig.proxy.protocol', 'http');
expect(c).toHaveProperty('brunoConfig.proxy.hostname', '');
@@ -169,4 +169,4 @@ describe('create collection json from pathname', () => {
// tests
expect(c).toHaveProperty('items[4].request.tests', 'test(\"request level script\", function() {\n expect(\"test\").to.equal(\"test\");\n});');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-cli/tests/runner/prepare-request.spec.js b/packages/bruno-cli/tests/runner/prepare-request.spec.js
index 14e5b5af4..61dd143fd 100644
--- a/packages/bruno-cli/tests/runner/prepare-request.spec.js
+++ b/packages/bruno-cli/tests/runner/prepare-request.spec.js
@@ -62,11 +62,11 @@ describe('prepare-request: prepareRequest', () => {
describe('API Key Authentication', () => {
it('If collection auth is apikey in header', async () => {
collection.root.request.auth = {
- mode: "apikey",
+ mode: 'apikey',
apikey: {
- key: "x-api-key",
- value: "{{apiKey}}",
- placement: "header"
+ key: 'x-api-key',
+ value: '{{apiKey}}',
+ placement: 'header'
}
};
@@ -76,11 +76,11 @@ describe('prepare-request: prepareRequest', () => {
it('If collection auth is apikey in header and request has existing headers', async () => {
collection.root.request.auth = {
- mode: "apikey",
+ mode: 'apikey',
apikey: {
- key: "x-api-key",
- value: "{{apiKey}}",
- placement: "header"
+ key: 'x-api-key',
+ value: '{{apiKey}}',
+ placement: 'header'
}
};
@@ -92,11 +92,11 @@ describe('prepare-request: prepareRequest', () => {
it('If collection auth is apikey in query parameters', async () => {
collection.root.request.auth = {
- mode: "apikey",
+ mode: 'apikey',
apikey: {
- key: "x-api-key",
- value: "{{apiKey}}",
- placement: "queryparams"
+ key: 'x-api-key',
+ value: '{{apiKey}}',
+ placement: 'queryparams'
}
};
@@ -172,7 +172,7 @@ describe('prepare-request: prepareRequest', () => {
};
const result = await prepareRequest(item, collection);
-
+
expect(result.oauth2).toBeDefined();
expect(result.oauth2.grantType).toBe('client_credentials');
expect(result.oauth2.accessTokenUrl).toBe('https://auth.example.com/token');
@@ -204,7 +204,7 @@ describe('prepare-request: prepareRequest', () => {
};
const result = await prepareRequest(item, collection);
-
+
expect(result.oauth2).toBeDefined();
expect(result.oauth2.grantType).toBe('password');
expect(result.oauth2.accessTokenUrl).toBe('https://auth.example.com/token');
@@ -298,7 +298,7 @@ describe('prepare-request: prepareRequest', () => {
};
const result = await prepareRequest(item, collection);
-
+
const expected = {
username: 'testUser',
password: 'testPass123'
@@ -345,11 +345,11 @@ describe('prepare-request: prepareRequest', () => {
describe('API Key Authentication', () => {
it('If request auth is apikey in header', async () => {
item.request.auth = {
- mode: "apikey",
+ mode: 'apikey',
apikey: {
- key: "x-api-key",
- value: "{{apiKey}}",
- placement: "header"
+ key: 'x-api-key',
+ value: '{{apiKey}}',
+ placement: 'header'
}
};
@@ -359,11 +359,11 @@ describe('prepare-request: prepareRequest', () => {
it('If request auth is apikey in header and request has existing headers', async () => {
item.request.auth = {
- mode: "apikey",
+ mode: 'apikey',
apikey: {
- key: "x-api-key",
- value: "{{apiKey}}",
- placement: "header"
+ key: 'x-api-key',
+ value: '{{apiKey}}',
+ placement: 'header'
}
};
@@ -375,11 +375,11 @@ describe('prepare-request: prepareRequest', () => {
it('If request auth is apikey in query parameters', async () => {
item.request.auth = {
- mode: "apikey",
+ mode: 'apikey',
apikey: {
- key: "x-api-key",
- value: "{{apiKey}}",
- placement: "queryparams"
+ key: 'x-api-key',
+ value: '{{apiKey}}',
+ placement: 'queryparams'
}
};
diff --git a/packages/bruno-cli/tests/runner/report-metadata.spec.js b/packages/bruno-cli/tests/runner/report-metadata.spec.js
index 9732e4aeb..2db861b35 100644
--- a/packages/bruno-cli/tests/runner/report-metadata.spec.js
+++ b/packages/bruno-cli/tests/runner/report-metadata.spec.js
@@ -49,4 +49,4 @@ describe('HTML Report Generation', () => {
expect(htmlString).toContain('{{ totalDataReceived }}');
expect(htmlString).toContain('{{ averageResponseTime }}');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-cli/tests/utils/common.spec.js b/packages/bruno-cli/tests/utils/common.spec.js
index bd4c1e7e0..16707f906 100644
--- a/packages/bruno-cli/tests/utils/common.spec.js
+++ b/packages/bruno-cli/tests/utils/common.spec.js
@@ -306,4 +306,4 @@ describe('hasExecutableTestInScript', () => {
expect(hasExecutableTestInScript(script)).toBe(true);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-common/src/interpolate/index.spec.ts b/packages/bruno-common/src/interpolate/index.spec.ts
index b47be2fdd..98d4e3223 100644
--- a/packages/bruno-common/src/interpolate/index.spec.ts
+++ b/packages/bruno-common/src/interpolate/index.spec.ts
@@ -7,9 +7,9 @@ const calculateAgeFromBirthDate = (birthDate = BRUNO_BIRTH_DATE) => {
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
- const hasBirthdayPassedThisYear =
- today.getMonth() > birthDate.getMonth() ||
- (today.getMonth() === birthDate.getMonth() && today.getDate() >= birthDate.getDate());
+ const hasBirthdayPassedThisYear
+ = today.getMonth() > birthDate.getMonth()
+ || (today.getMonth() === birthDate.getMonth() && today.getDate() >= birthDate.getDate());
if (!hasBirthdayPassedThisYear) {
age--;
@@ -25,7 +25,7 @@ describe('interpolate', () => {
const inputString = 'Hello, my name is {{user.name}} and I am {{user.age}} years old';
const inputObject = {
'user.name': 'Bruno',
- user: {
+ 'user': {
age: BRUNO_AGE
}
};
@@ -51,8 +51,8 @@ describe('interpolate', () => {
it('should handle all valid keys', () => {
const inputObject = {
user: {
- full_name: 'Bruno',
- age: BRUNO_AGE,
+ 'full_name': 'Bruno',
+ 'age': BRUNO_AGE,
'fav-food': ['egg', 'meat'],
'want.attention': true
}
@@ -77,7 +77,7 @@ describe('interpolate', () => {
const inputString = 'Hello, my name is {{ user.name }} and I am {{user.age}} years old';
const inputObject = {
'user.name': 'Bruno',
- user: {
+ 'user': {
age: BRUNO_AGE
}
};
@@ -92,7 +92,7 @@ describe('interpolate', () => {
const inputObject = {
data: {
'user.name': 'Bruno',
- user: {
+ 'user': {
name: 'Not _Bruno_',
age: BRUNO_AGE
}
@@ -198,7 +198,7 @@ describe('interpolate - recursive', () => {
const inputObject = {
'user.message': 'Hello, my name is {{user.name}} and I am {{user.age}} years old',
'user.name': 'Bruno',
- user: {
+ 'user': {
age: BRUNO_AGE
}
};
@@ -214,7 +214,7 @@ describe('interpolate - recursive', () => {
'user.message': 'Hello, my name is {{user.name}} and I am {{user.age}} years old',
'user.name': 'Bruno {{user.lastName}}',
'user.lastName': 'Dog',
- user: {
+ 'user': {
age: BRUNO_AGE
}
};
@@ -231,7 +231,7 @@ describe('interpolate - recursive', () => {
'user.full_name': '{{user.name}}',
'user.name': 'Bruno {{user.lastName}}',
'user.lastName': 'Dog',
- user: {
+ 'user': {
age: BRUNO_AGE
}
};
@@ -245,7 +245,7 @@ describe('interpolate - recursive', () => {
const inputString = '{{user.message}}';
const inputObject = {
'user.message': 'Hello, my name is {{user.name}} and I am {{user.age}} years old',
- user: {
+ 'user': {
age: BRUNO_AGE
}
};
@@ -265,8 +265,8 @@ describe('interpolate - recursive', () => {
const inputObject = {
user: {
message,
- full_name: 'Bruno',
- age: BRUNO_AGE,
+ 'full_name': 'Bruno',
+ 'age': BRUNO_AGE,
'fav-food': ['egg', 'meat'],
'want.attention': true
}
@@ -381,7 +381,7 @@ describe('interpolate - object handling', () => {
it('should stringify simple objects', () => {
const inputString = 'User: {{user}}';
const inputObject = {
- 'user': { name: 'Bruno', age: BRUNO_AGE }
+ user: { name: 'Bruno', age: BRUNO_AGE }
};
const result = interpolate(inputString, inputObject);
@@ -403,9 +403,9 @@ describe('interpolate - object handling', () => {
it('should stringify nested objects', () => {
const inputString = 'User: {{user}}';
const inputObject = {
- 'user': {
+ user: {
name: 'Bruno',
- age: BRUNO_AGE,
+ age: BRUNO_AGE,
preferences: {
food: ['egg', 'meat'],
toys: { favorite: 'ball' }
@@ -432,7 +432,7 @@ describe('interpolate - object handling', () => {
it('should handle null values correctly', () => {
const inputString = 'User: {{user}}';
const inputObject = {
- 'user': null
+ user: null
};
const result = interpolate(inputString, inputObject);
@@ -443,8 +443,8 @@ describe('interpolate - object handling', () => {
it('should handle objects with nested interpolation', () => {
const inputString = 'User: {{user}}';
const inputObject = {
- 'user': {
- name: 'Bruno',
+ 'user': {
+ name: 'Bruno',
message: '{{user.greeting}}'
},
'user.greeting': 'Hello there!'
@@ -458,7 +458,7 @@ describe('interpolate - object handling', () => {
it('should handle objects within arrays', () => {
const inputString = 'Items: {{items}}';
const inputObject = {
- 'items': [
+ items: [
{ id: 1, name: 'Toy' },
{ id: 2, name: 'Bone' },
{ id: 3, name: 'Ball', colors: ['red', 'blue'] }
@@ -503,7 +503,7 @@ describe('interpolate - mock variable interpolation', () => {
it('should escape special characters in mock variable values and produce valid JSON when escapeJSONStrings is true', () => {
const inputString = '{"escapedValue": "{{$randomLoremParagraphs}}"}';
-
+
expect(() => {
const result = interpolate(inputString, {}, { escapeJSONStrings: true });
JSON.parse(result); // This should not throw an error
@@ -512,7 +512,7 @@ describe('interpolate - mock variable interpolation', () => {
it('should not produce valid JSON when escapeJSONStrings is false', () => {
const inputString = '{"escapedValue": "{{$randomLoremParagraphs}}"}';
-
+
expect(() => {
const result = interpolate(inputString, {}, { escapeJSONStrings: false });
JSON.parse(result); // This should throw an error
@@ -521,13 +521,13 @@ describe('interpolate - mock variable interpolation', () => {
it('should throw an error when producing invalid JSON regardless of escapeJSONStrings option', () => {
const inputString = '{"escapedValue": "{{$randomLoremParagraphs}}"}';
-
+
// Test without providing the options argument
expect(() => {
const result = interpolate(inputString, {});
JSON.parse(result); // This should throw an error
}).toThrow();
-
+
// Test with escapeJSONStrings explicitly set to false
expect(() => {
const result = interpolate(inputString, {}, { escapeJSONStrings: false });
@@ -540,7 +540,7 @@ describe('interpolate - Date() handling', () => {
it('should interpolate Date() using JSON.stringify', () => {
const inputString = 'Date is {{date}}';
const inputObject = {
- date: new Date("2025-04-17T15:33:41.117Z")
+ date: new Date('2025-04-17T15:33:41.117Z')
};
const jsonStringifiedDate = JSON.stringify(inputObject.date);
@@ -548,27 +548,27 @@ describe('interpolate - Date() handling', () => {
expect(result).toBe('Date is "2025-04-17T15:33:41.117Z"');
expect(result).toBe(`Date is ${jsonStringifiedDate}`);
- })
+ });
it('should interpolate Date() when its nested in an object', () => {
const inputString = 'Date is {{date}}';
const inputObject = {
date: {
- now: new Date("2025-04-17T15:33:41.117Z")
+ now: new Date('2025-04-17T15:33:41.117Z')
}
};
const result = interpolate(inputString, inputObject);
expect(result).toBe('Date is {"now":"2025-04-17T15:33:41.117Z"}');
- })
+ });
});
describe('interpolate - moment() handling', () => {
it('should interpolate moment() using JSON.stringify', () => {
const inputString = 'Date is {{date}}';
const inputObject = {
- date: moment("2025-04-17T15:33:41.117Z")
+ date: moment('2025-04-17T15:33:41.117Z')
};
const jsonStringifiedDate = JSON.stringify(inputObject.date);
@@ -576,18 +576,18 @@ describe('interpolate - moment() handling', () => {
expect(result).toBe('Date is "2025-04-17T15:33:41.117Z"');
expect(result).toBe(`Date is ${jsonStringifiedDate}`);
- })
+ });
it('should interpolate moment() when its nested in an object', () => {
const inputString = 'Date is {{date}}';
const inputObject = {
date: {
- now: moment("2025-04-17T15:33:41.117Z")
+ now: moment('2025-04-17T15:33:41.117Z')
}
};
const result = interpolate(inputString, inputObject);
expect(result).toBe('Date is {"now":"2025-04-17T15:33:41.117Z"}');
- })
-})
\ No newline at end of file
+ });
+});
diff --git a/packages/bruno-common/src/interpolate/index.ts b/packages/bruno-common/src/interpolate/index.ts
index daa10ab98..4cd8a2b16 100644
--- a/packages/bruno-common/src/interpolate/index.ts
+++ b/packages/bruno-common/src/interpolate/index.ts
@@ -12,7 +12,7 @@
*/
import { mockDataFunctions } from '../utils/faker-functions';
-import { get } from "lodash-es";
+import { get } from 'lodash-es';
const interpolate = (
str: string,
@@ -96,4 +96,4 @@ const replace = (
return resultStr;
};
-export default interpolate;
\ No newline at end of file
+export default interpolate;
diff --git a/packages/bruno-common/src/runner/index.ts b/packages/bruno-common/src/runner/index.ts
index 3e3c842b0..e5040fded 100644
--- a/packages/bruno-common/src/runner/index.ts
+++ b/packages/bruno-common/src/runner/index.ts
@@ -1,4 +1,4 @@
-import { generateHtmlReport } from "./reports/html/generate-report";
-import { getRunnerSummary } from "./runner-summary";
+import { generateHtmlReport } from './reports/html/generate-report';
+import { getRunnerSummary } from './runner-summary';
-export { generateHtmlReport, getRunnerSummary };
\ No newline at end of file
+export { generateHtmlReport, getRunnerSummary };
diff --git a/packages/bruno-common/src/runner/reports/html/generate-report.ts b/packages/bruno-common/src/runner/reports/html/generate-report.ts
index e08ddce29..7d140af51 100644
--- a/packages/bruno-common/src/runner/reports/html/generate-report.ts
+++ b/packages/bruno-common/src/runner/reports/html/generate-report.ts
@@ -1,6 +1,6 @@
-import { T_RunnerResults } from "../../types";
-import { isHtmlContentType, getContentType, redactImageData, encodeBase64 } from "../../utils";
-import htmlTemplateString from "./template";
+import { T_RunnerResults } from '../../types';
+import { isHtmlContentType, getContentType, redactImageData, encodeBase64 } from '../../utils';
+import htmlTemplateString from './template';
const generateHtmlReport = ({
runnerResults,
@@ -32,10 +32,10 @@ const generateHtmlReport = ({
data: response?.data ? redactImageData(response?.data, responseContentType) : response?.data,
isHtml: isHtmlContentType(responseContentType)
}
- }
+ };
}),
summary
- }
+ };
});
const htmlString = htmlTemplateString(encodeBase64(JSON.stringify({
results: resultsWithSummaryAndCleanData,
@@ -46,4 +46,4 @@ const generateHtmlReport = ({
return htmlString;
};
-export { generateHtmlReport }
\ No newline at end of file
+export { generateHtmlReport };
diff --git a/packages/bruno-common/src/runner/reports/html/template.ts b/packages/bruno-common/src/runner/reports/html/template.ts
index 44589b81d..ca49cb337 100644
--- a/packages/bruno-common/src/runner/reports/html/template.ts
+++ b/packages/bruno-common/src/runner/reports/html/template.ts
@@ -1,4 +1,4 @@
-export const htmlTemplateString = (resutsJsonString: string) =>`
+export const htmlTemplateString = (resutsJsonString: string) => `
diff --git a/packages/bruno-common/src/runner/runner-summary.ts b/packages/bruno-common/src/runner/runner-summary.ts
index 4fb276a29..3e99e676f 100644
--- a/packages/bruno-common/src/runner/runner-summary.ts
+++ b/packages/bruno-common/src/runner/runner-summary.ts
@@ -1,4 +1,4 @@
-import { T_RunnerRequestExecutionResult, T_RunSummary } from "./types";
+import { T_RunnerRequestExecutionResult, T_RunSummary } from './types';
// todo: this is generic, not specific to html, can be moved out of the report/html sub-package
export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_RunSummary => {
@@ -35,7 +35,7 @@ export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_R
let anyFailed = false;
for (const testResult of testResults || []) {
- if (testResult.status === "pass") {
+ if (testResult.status === 'pass') {
passedTests += 1;
} else {
anyFailed = true;
@@ -43,7 +43,7 @@ export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_R
}
}
for (const assertionResult of assertionResults || []) {
- if (assertionResult.status === "pass") {
+ if (assertionResult.status === 'pass') {
passedAssertions += 1;
} else {
anyFailed = true;
@@ -51,7 +51,7 @@ export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_R
}
}
for (const preRequestTestResult of preRequestTestResults || []) {
- if (preRequestTestResult.status === "pass") {
+ if (preRequestTestResult.status === 'pass') {
passedPreRequestTests += 1;
} else {
anyFailed = true;
@@ -59,7 +59,7 @@ export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_R
}
}
for (const postResponseTestResult of postResponseTestResults || []) {
- if (postResponseTestResult.status === "pass") {
+ if (postResponseTestResult.status === 'pass') {
passedPostResponseTests += 1;
} else {
anyFailed = true;
@@ -67,7 +67,7 @@ export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_R
}
}
- if (!anyFailed && status !== "error") {
+ if (!anyFailed && status !== 'error') {
passedRequests += 1;
} else if (anyFailed) {
failedRequests += 1;
@@ -93,6 +93,6 @@ export const getRunnerSummary = (results: T_RunnerRequestExecutionResult[]): T_R
failedPreRequestTests,
totalPostResponseTests,
passedPostResponseTests,
- failedPostResponseTests,
+ failedPostResponseTests
};
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-common/src/runner/types/index.ts b/packages/bruno-common/src/runner/types/index.ts
index 3565930f2..1b696ba12 100644
--- a/packages/bruno-common/src/runner/types/index.ts
+++ b/packages/bruno-common/src/runner/types/index.ts
@@ -5,7 +5,7 @@ type T_AssertionPassResult = {
rhsOperand: string;
operator: string;
status: string;
-}
+};
type T_AssertionFailResult = {
lhsExpr: string;
@@ -14,7 +14,7 @@ type T_AssertionFailResult = {
operator: string;
status: string;
error: string;
-}
+};
type T_AssertionResult = T_AssertionPassResult | T_AssertionFailResult;
@@ -40,7 +40,7 @@ type T_EmptyRequest = {
headers?: null | undefined;
data?: null | undefined;
isHtml?: boolean | undefined;
-}
+};
// request types
type T_Request = {
@@ -58,7 +58,7 @@ type T_EmptyResponse = {
data?: null | undefined;
responseTime?: number | undefined;
isHtml?: boolean | undefined;
-}
+};
type T_SkippedResponse = {
status?: string | null | undefined;
@@ -67,7 +67,7 @@ type T_SkippedResponse = {
data?: null | undefined;
responseTime?: number | undefined;
isHtml?: boolean | undefined;
-}
+};
// response types
type T_Response = {
@@ -92,14 +92,14 @@ export type T_RunnerRequestExecutionResult = {
preRequestTestResults?: T_TestResult[];
postResponseTestResults?: T_TestResult[];
runDuration: number;
-}
+};
export type T_RunnerResults = {
iterationIndex: number;
iterationData?: any; // todo - csv/json row data
results: T_RunnerRequestExecutionResult[];
summary: T_RunSummary;
-}
+};
// run summary type
export type T_RunSummary = {
@@ -120,4 +120,4 @@ export type T_RunSummary = {
totalPostResponseTests: number;
passedPostResponseTests: number;
failedPostResponseTests: number;
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-common/src/runner/utils/index.ts b/packages/bruno-common/src/runner/utils/index.ts
index 76f1f774c..00fb2cbc5 100644
--- a/packages/bruno-common/src/runner/utils/index.ts
+++ b/packages/bruno-common/src/runner/utils/index.ts
@@ -2,13 +2,13 @@ export const encodeBase64 = (str: string) => {
const bytes = new TextEncoder().encode(str);
const binary = bytes.reduce((acc, byte) => acc + String.fromCharCode(byte), '');
return btoa(binary);
-}
+};
export const decodeBase64 = (base64: string) => {
const binary = atob(base64);
- const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
-}
+};
export const getContentType = (headers: Record): string => {
if (!headers || typeof headers !== 'object') {
@@ -20,12 +20,12 @@ export const getContentType = (headers: Record {
- return contentType?.includes("html");
+ return contentType?.includes('html');
};
export const redactImageData = (data: string | object | number | boolean, contentType: string) => {
- if (contentType?.includes("image")) {
- return "Response content redacted (image data)";
+ if (contentType?.includes('image')) {
+ return 'Response content redacted (image data)';
}
return data;
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-common/src/utils/faker-functions.spec.ts b/packages/bruno-common/src/utils/faker-functions.spec.ts
index eb2e70793..18f4f3f27 100644
--- a/packages/bruno-common/src/utils/faker-functions.spec.ts
+++ b/packages/bruno-common/src/utils/faker-functions.spec.ts
@@ -1,6 +1,6 @@
-import { mockDataFunctions } from "./faker-functions";
+import { mockDataFunctions } from './faker-functions';
-describe("mockDataFunctions Regex Validation", () => {
+describe('mockDataFunctions Regex Validation', () => {
beforeAll(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2024-01-01T00:00:00.000Z'));
@@ -10,15 +10,15 @@ describe("mockDataFunctions Regex Validation", () => {
jest.useRealTimers();
});
- test("timestamp and isoTimestamp should return mocked time values", () => {
- const expectedTimestamp = '1704067200';
+ test('timestamp and isoTimestamp should return mocked time values', () => {
+ const expectedTimestamp = '1704067200';
const expectedIsoTimestamp = '2024-01-01T00:00:00.000Z';
expect(mockDataFunctions.timestamp()).toBe(expectedTimestamp);
expect(mockDataFunctions.isoTimestamp()).toBe(expectedIsoTimestamp);
});
- test("all values should match their expected patterns", () => {
+ test('all values should match their expected patterns', () => {
const patterns: Record = {
guid: /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/,
randomUUID: /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/,
@@ -137,7 +137,7 @@ describe("mockDataFunctions Regex Validation", () => {
randomLoremParagraphs: /^[\s\S]+$/,
randomLoremText: /^[\s\S]+$/,
randomLoremSlug: /^[\s\S]+$/,
- randomLoremLines: /^[\s\S]+$/,
+ randomLoremLines: /^[\s\S]+$/
};
const errors: string[] = [];
@@ -151,7 +151,7 @@ describe("mockDataFunctions Regex Validation", () => {
});
if (errors.length > 0) {
- throw new Error(errors.join("\n"));
+ throw new Error(errors.join('\n'));
}
});
});
diff --git a/packages/bruno-common/src/utils/index.ts b/packages/bruno-common/src/utils/index.ts
index 2c125dea3..62a418fe0 100644
--- a/packages/bruno-common/src/utils/index.ts
+++ b/packages/bruno-common/src/utils/index.ts
@@ -1,7 +1,7 @@
export {
encodeUrl,
parseQueryParams,
- buildQueryString,
+ buildQueryString
} from './url';
export {
diff --git a/packages/bruno-common/src/utils/url/index.spec.ts b/packages/bruno-common/src/utils/url/index.spec.ts
index e9815e306..19f934ab1 100644
--- a/packages/bruno-common/src/utils/url/index.spec.ts
+++ b/packages/bruno-common/src/utils/url/index.spec.ts
@@ -218,4 +218,4 @@ describe('buildQueryString', () => {
const result = buildQueryString(params, { encode: false });
expect(result).toBe('filter=status|active&sort=name|asc');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-common/src/utils/url/index.ts b/packages/bruno-common/src/utils/url/index.ts
index 7b3debebb..18a34de3f 100644
--- a/packages/bruno-common/src/utils/url/index.ts
+++ b/packages/bruno-common/src/utils/url/index.ts
@@ -32,7 +32,7 @@ function parseQueryParams(query: string, { decode = false }: ExtractQueryParamsO
const [queryString, ...hashParts] = query.split('#');
const pairs = queryString.split('&');
- const params = pairs.map(pair => {
+ const params = pairs.map((pair) => {
const [name, ...valueParts] = pair.split('=');
if (!name) {
@@ -83,4 +83,4 @@ export {
type QueryParam,
type BuildQueryStringOptions,
type ExtractQueryParamsOptions
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-converters/babel.config.js b/packages/bruno-converters/babel.config.js
index c74fb53e2..619f8c1b1 100644
--- a/packages/bruno-converters/babel.config.js
+++ b/packages/bruno-converters/babel.config.js
@@ -1,3 +1,3 @@
module.exports = {
- presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
+ presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
};
diff --git a/packages/bruno-converters/jest.config.js b/packages/bruno-converters/jest.config.js
index fa59852bc..26db256f0 100644
--- a/packages/bruno-converters/jest.config.js
+++ b/packages/bruno-converters/jest.config.js
@@ -1,6 +1,6 @@
module.exports = {
transform: {
- '^.+\\.js$': 'babel-jest',
+ '^.+\\.js$': 'babel-jest'
},
setupFiles: ['/jest.setup.js'],
transformIgnorePatterns: [
diff --git a/packages/bruno-converters/jest.setup.js b/packages/bruno-converters/jest.setup.js
index a2246e495..f2500acc9 100644
--- a/packages/bruno-converters/jest.setup.js
+++ b/packages/bruno-converters/jest.setup.js
@@ -6,6 +6,6 @@ jest.mock('./src/common', () => {
return {
__esModule: true, // Use this property to indicate it's an ES module
...originalModule,
- uuid: jest.fn(() => 'mockeduuidvalue123456'), // Mock uuid to return a fixed value
+ uuid: jest.fn(() => 'mockeduuidvalue123456') // Mock uuid to return a fixed value
};
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/src/common/index.js b/packages/bruno-converters/src/common/index.js
index 8672ed548..223e90337 100644
--- a/packages/bruno-converters/src/common/index.js
+++ b/packages/bruno-converters/src/common/index.js
@@ -47,7 +47,7 @@ export const validateSchema = (collection = {}) => {
collectionSchema.validateSync(collection);
return collection;
} catch (err) {
- console.log("Error validating schema", err);
+ console.log('Error validating schema', err);
throw new Error('The Collection has an invalid schema');
}
};
@@ -95,7 +95,6 @@ export const updateUidsInCollection = (_collection) => {
export const transformItemsInCollection = (collection) => {
const transformItems = (items = []) => {
each(items, (item) => {
-
if (['http', 'graphql'].includes(item.type)) {
item.type = `${item.type}-request`;
@@ -209,4 +208,4 @@ export const deleteSecretsInEnvs = (envs) => {
}
});
});
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-converters/src/constants/regex.js b/packages/bruno-converters/src/constants/regex.js
index 989dbc1c3..1771f90d3 100644
--- a/packages/bruno-converters/src/constants/regex.js
+++ b/packages/bruno-converters/src/constants/regex.js
@@ -1 +1 @@
-export const invalidVariableCharacterRegex = /[^\w-.]/g;
\ No newline at end of file
+export const invalidVariableCharacterRegex = /[^\w-.]/g;
diff --git a/packages/bruno-converters/src/index.js b/packages/bruno-converters/src/index.js
index 1bcd54cea..ba2215ea5 100644
--- a/packages/bruno-converters/src/index.js
+++ b/packages/bruno-converters/src/index.js
@@ -4,4 +4,4 @@ export { default as brunoToPostman } from './postman/bruno-to-postman.js';
export { default as openApiToBruno } from './openapi/openapi-to-bruno.js';
export { default as insomniaToBruno } from './insomnia/insomnia-to-bruno.js';
export { default as wsdlToBruno } from './wsdl/wsdl-to-bruno.js';
-export { default as postmanTranslation } from './postman/postman-translations.js';
\ No newline at end of file
+export { default as postmanTranslation } from './postman/postman-translations.js';
diff --git a/packages/bruno-converters/src/insomnia/insomnia-to-bruno.js b/packages/bruno-converters/src/insomnia/insomnia-to-bruno.js
index cbf2e2930..5863d8d45 100644
--- a/packages/bruno-converters/src/insomnia/insomnia-to-bruno.js
+++ b/packages/bruno-converters/src/insomnia/insomnia-to-bruno.js
@@ -159,8 +159,8 @@ const transformInsomniaRequestItem = (request, index, allRequests) => {
}
const settings = {
- encodeUrl: request.settings?.encodeUrl !== false && request.settingEncodeUrl !== false, // handles v4 and v5 import
- }
+ encodeUrl: request.settings?.encodeUrl !== false && request.settingEncodeUrl !== false // handles v4 and v5 import
+ };
brunoRequestItem.settings = settings;
@@ -259,13 +259,13 @@ const parseInsomniaCollection = (data) => {
brunoCollection.name = insomniaCollection.name;
- const requestsAndFolders =
- insomniaResources.filter((resource) => resource._type === 'request' || resource._type === 'request_group') ||
- [];
+ const requestsAndFolders
+ = insomniaResources.filter((resource) => resource._type === 'request' || resource._type === 'request_group')
+ || [];
function createFolderStructure(resources, parentId = null) {
- const requestGroups =
- resources.filter((resource) => resource._type === 'request_group' && resource.parentId === parentId) || [];
+ const requestGroups
+ = resources.filter((resource) => resource._type === 'request_group' && resource.parentId === parentId) || [];
const requests = resources.filter((resource) => resource._type === 'request' && resource.parentId === parentId);
const folders = requestGroups.map((folder, index, allFolder) => {
@@ -274,12 +274,12 @@ const parseInsomniaCollection = (data) => {
(resource) => resource._type === 'request' && resource.parentId === folder._id
);
- return {
+ return {
uid: uuid(),
name,
type: 'folder',
items: createFolderStructure(resources, folder._id).concat(
- requests.filter(r => r.parentId === folder._id).map(transformInsomniaRequestItem)
+ requests.filter((r) => r.parentId === folder._id).map(transformInsomniaRequestItem)
)
};
});
@@ -300,7 +300,7 @@ const parseInsomniaCollection = (data) => {
export const insomniaToBruno = (insomniaCollection) => {
try {
- if(typeof insomniaCollection !== 'object') {
+ if (typeof insomniaCollection !== 'object') {
insomniaCollection = jsyaml.load(insomniaCollection);
}
let collection;
@@ -309,7 +309,7 @@ export const insomniaToBruno = (insomniaCollection) => {
} else {
collection = parseInsomniaCollection(insomniaCollection);
}
-
+
const transformedCollection = transformItemsInCollection(collection);
const hydratedCollection = hydrateSeqInCollection(transformedCollection);
const validatedCollection = validateSchema(hydratedCollection);
diff --git a/packages/bruno-converters/src/openapi/openapi-to-bruno.js b/packages/bruno-converters/src/openapi/openapi-to-bruno.js
index 8569d5c8a..68f05759d 100644
--- a/packages/bruno-converters/src/openapi/openapi-to-bruno.js
+++ b/packages/bruno-converters/src/openapi/openapi-to-bruno.js
@@ -752,7 +752,7 @@ const resolveRefs = (spec, components = spec?.components, cache = new Map()) =>
}
if (Array.isArray(spec)) {
- return spec.map(item => resolveRefs(item, components, cache));
+ return spec.map((item) => resolveRefs(item, components, cache));
}
if ('$ref' in spec) {
@@ -966,71 +966,71 @@ export const parseOpenApiCollection = (data, options = {}) => {
items: [],
environments: []
};
- try {
- const collectionData = resolveRefs(data);
- if (!collectionData) {
- throw new Error('Invalid OpenAPI collection. Failed to resolve refs.');
- return;
- }
+ try {
+ const collectionData = resolveRefs(data);
+ if (!collectionData) {
+ throw new Error('Invalid OpenAPI collection. Failed to resolve refs.');
+ return;
+ }
- // Currently parsing of openapi spec is "do your best", that is
- // allows "invalid" openapi spec
+ // Currently parsing of openapi spec is "do your best", that is
+ // allows "invalid" openapi spec
- // Assumes v3 if not defined. v2 is not supported yet
- if (collectionData.openapi && !collectionData.openapi.startsWith('3')) {
- throw new Error('Only OpenAPI v3 is supported currently.');
- return;
- }
+ // Assumes v3 if not defined. v2 is not supported yet
+ if (collectionData.openapi && !collectionData.openapi.startsWith('3')) {
+ throw new Error('Only OpenAPI v3 is supported currently.');
+ return;
+ }
- brunoCollection.name = collectionData.info?.title?.trim() || 'Untitled Collection';
+ brunoCollection.name = collectionData.info?.title?.trim() || 'Untitled Collection';
- let servers = collectionData.servers || [];
+ let servers = collectionData.servers || [];
- // Create environments based on the servers
- servers.forEach((server, index) => {
- let baseUrl = getDefaultUrl(server);
- let environmentName = server.description ? server.description : `Environment ${index + 1}`;
+ // Create environments based on the servers
+ servers.forEach((server, index) => {
+ let baseUrl = getDefaultUrl(server);
+ let environmentName = server.description ? server.description : `Environment ${index + 1}`;
- brunoCollection.environments.push({
- uid: uuid(),
- name: environmentName,
- variables: [
- {
- uid: uuid(),
- name: 'baseUrl',
- value: baseUrl,
- type: 'text',
- enabled: true,
- secret: false
- },
- ]
- });
+ brunoCollection.environments.push({
+ uid: uuid(),
+ name: environmentName,
+ variables: [
+ {
+ uid: uuid(),
+ name: 'baseUrl',
+ value: baseUrl,
+ type: 'text',
+ enabled: true,
+ secret: false
+ }
+ ]
});
+ });
- let securityConfig = getSecurity(collectionData);
+ let securityConfig = getSecurity(collectionData);
- let allRequests = Object.entries(collectionData.paths)
- .map(([path, methods]) => {
- return Object.entries(methods)
- .filter(([method, op]) => {
- return ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'].includes(
- method.toLowerCase()
- );
- })
- .map(([method, operationObject]) => {
- return {
- method: method,
- path: path.replace(/{([^}]+)}/g, ':$1'), // Replace placeholders enclosed in curly braces with colons
+ let allRequests = Object.entries(collectionData.paths)
+ .map(([path, methods]) => {
+ return Object.entries(methods)
+ .filter(([method, op]) => {
+ return ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'].includes(
+ method.toLowerCase()
+ );
+ })
+ .map(([method, operationObject]) => {
+ return {
+ method: method,
+ path: path.replace(/{([^}]+)}/g, ':$1'), // Replace placeholders enclosed in curly braces with colons
originalPath: path, // Keep original path for grouping
- operationObject: operationObject,
- global: {
+ operationObject: operationObject,
+ global: {
server: '{{baseUrl}}',
- security: securityConfig
- }
- };
- });
- })
- .reduce((acc, val) => acc.concat(val), []); // flatten
+ security: securityConfig
+ }
+ };
+ });
+ })
+ .reduce((acc, val) => acc.concat(val), []); // flatten
// Support both tag-based and path-based grouping
const groupingType = options.groupBy || 'tags';
@@ -1069,114 +1069,114 @@ export const parseOpenApiCollection = (data, options = {}) => {
brunoCollection.items = brunoCollectionItems;
}
- // Determine collection-level authentication based on global security requirements
- const buildCollectionAuth = (scheme) => {
- const authTemplate = {
- mode: 'none',
- basic: null,
- bearer: null,
- digest: null,
- apikey: null,
- oauth2: null,
- };
+ // Determine collection-level authentication based on global security requirements
+ const buildCollectionAuth = (scheme) => {
+ const authTemplate = {
+ mode: 'none',
+ basic: null,
+ bearer: null,
+ digest: null,
+ apikey: null,
+ oauth2: null
+ };
- if (!scheme) return authTemplate;
+ if (!scheme) return authTemplate;
- if (scheme.type === 'http' && scheme.scheme === 'basic') {
- return {
- ...authTemplate,
- mode: 'basic',
- basic: {
- username: '{{username}}',
- password: '{{password}}'
- }
- };
- } else if (scheme.type === 'http' && scheme.scheme === 'bearer') {
- return {
- ...authTemplate,
- mode: 'bearer',
- bearer: {
- token: '{{token}}'
- }
- };
- } else if (scheme.type === 'http' && scheme.scheme === 'digest') {
- return {
- ...authTemplate,
- mode: 'digest',
- digest: {
- username: '{{username}}',
- password: '{{password}}'
- }
- };
- } else if (scheme.type === 'apiKey') {
- return {
- ...authTemplate,
- mode: 'apikey',
- apikey: {
- key: scheme.name,
- value: '{{apiKey}}',
- placement: scheme.in === 'query' ? 'queryparams' : 'header'
- }
- };
- } else if (scheme.type === 'oauth2') {
- let flows = scheme.flows || {};
- let grantType = 'client_credentials';
- if (flows.authorizationCode) {
- grantType = 'authorization_code';
- } else if (flows.implicit) {
- grantType = 'implicit';
- } else if (flows.password) {
- grantType = 'password';
+ if (scheme.type === 'http' && scheme.scheme === 'basic') {
+ return {
+ ...authTemplate,
+ mode: 'basic',
+ basic: {
+ username: '{{username}}',
+ password: '{{password}}'
}
- const flowConfig = grantType === 'authorization_code' ? flows.authorizationCode || {} : grantType === 'implicit' ? flows.implicit || {} : grantType === 'password' ? flows.password || {} : flows.clientCredentials || {};
-
- return {
- ...authTemplate,
- mode: 'oauth2',
- oauth2: {
- grantType,
- authorizationUrl: flowConfig.authorizationUrl || '{{oauth_authorize_url}}',
- accessTokenUrl: flowConfig.tokenUrl || '{{oauth_token_url}}',
- refreshTokenUrl: flowConfig.refreshUrl || '{{oauth_refresh_url}}',
- callbackUrl: '{{oauth_callback_url}}',
- clientId: '{{oauth_client_id}}',
- clientSecret: '{{oauth_client_secret}}',
- scope: Array.isArray(flowConfig.scopes) ? flowConfig.scopes.join(' ') : Object.keys(flowConfig.scopes || {}).join(' '),
- state: '{{oauth_state}}',
- credentialsPlacement: 'header',
- tokenPlacement: 'header',
- tokenHeaderPrefix: 'Bearer',
- autoFetchToken: false,
- autoRefreshToken: true
- }
- };
+ };
+ } else if (scheme.type === 'http' && scheme.scheme === 'bearer') {
+ return {
+ ...authTemplate,
+ mode: 'bearer',
+ bearer: {
+ token: '{{token}}'
+ }
+ };
+ } else if (scheme.type === 'http' && scheme.scheme === 'digest') {
+ return {
+ ...authTemplate,
+ mode: 'digest',
+ digest: {
+ username: '{{username}}',
+ password: '{{password}}'
+ }
+ };
+ } else if (scheme.type === 'apiKey') {
+ return {
+ ...authTemplate,
+ mode: 'apikey',
+ apikey: {
+ key: scheme.name,
+ value: '{{apiKey}}',
+ placement: scheme.in === 'query' ? 'queryparams' : 'header'
+ }
+ };
+ } else if (scheme.type === 'oauth2') {
+ let flows = scheme.flows || {};
+ let grantType = 'client_credentials';
+ if (flows.authorizationCode) {
+ grantType = 'authorization_code';
+ } else if (flows.implicit) {
+ grantType = 'implicit';
+ } else if (flows.password) {
+ grantType = 'password';
}
- return authTemplate;
- };
+ const flowConfig = grantType === 'authorization_code' ? flows.authorizationCode || {} : grantType === 'implicit' ? flows.implicit || {} : grantType === 'password' ? flows.password || {} : flows.clientCredentials || {};
- let collectionAuth = buildCollectionAuth(securityConfig.supported[0]);
-
- brunoCollection.root = {
- request: {
- auth: collectionAuth,
- },
- meta: {
- name: brunoCollection.name
- }
- };
-
- return brunoCollection;
- } catch (err) {
- if (!(err instanceof Error)) {
- throw new Error('Unknown error');
+ return {
+ ...authTemplate,
+ mode: 'oauth2',
+ oauth2: {
+ grantType,
+ authorizationUrl: flowConfig.authorizationUrl || '{{oauth_authorize_url}}',
+ accessTokenUrl: flowConfig.tokenUrl || '{{oauth_token_url}}',
+ refreshTokenUrl: flowConfig.refreshUrl || '{{oauth_refresh_url}}',
+ callbackUrl: '{{oauth_callback_url}}',
+ clientId: '{{oauth_client_id}}',
+ clientSecret: '{{oauth_client_secret}}',
+ scope: Array.isArray(flowConfig.scopes) ? flowConfig.scopes.join(' ') : Object.keys(flowConfig.scopes || {}).join(' '),
+ state: '{{oauth_state}}',
+ credentialsPlacement: 'header',
+ tokenPlacement: 'header',
+ tokenHeaderPrefix: 'Bearer',
+ autoFetchToken: false,
+ autoRefreshToken: true
+ }
+ };
}
- throw err;
+ return authTemplate;
+ };
+
+ let collectionAuth = buildCollectionAuth(securityConfig.supported[0]);
+
+ brunoCollection.root = {
+ request: {
+ auth: collectionAuth
+ },
+ meta: {
+ name: brunoCollection.name
+ }
+ };
+
+ return brunoCollection;
+ } catch (err) {
+ if (!(err instanceof Error)) {
+ throw new Error('Unknown error');
}
+ throw err;
+ }
};
export const openApiToBruno = (openApiSpecification, options = {}) => {
try {
- if(typeof openApiSpecification !== 'object') {
+ if (typeof openApiSpecification !== 'object') {
openApiSpecification = jsyaml.load(openApiSpecification);
}
@@ -1184,7 +1184,7 @@ export const openApiToBruno = (openApiSpecification, options = {}) => {
const transformedCollection = transformItemsInCollection(collection);
const hydratedCollection = hydrateSeqInCollection(transformedCollection);
const validatedCollection = validateSchema(hydratedCollection);
- return validatedCollection
+ return validatedCollection;
} catch (err) {
console.error('Error converting OpenAPI to Bruno:', err);
if (!(err instanceof Error)) {
diff --git a/packages/bruno-converters/src/postman/bruno-to-postman.js b/packages/bruno-converters/src/postman/bruno-to-postman.js
index 43725a190..8b81ca271 100644
--- a/packages/bruno-converters/src/postman/bruno-to-postman.js
+++ b/packages/bruno-converters/src/postman/bruno-to-postman.js
@@ -10,8 +10,8 @@ import { deleteSecretsInEnvs, deleteUidsInEnvs, deleteUidsInItems, isItemAReques
*/
export const transformUrl = (url, params) => {
if (typeof url !== 'string' || !url.trim()) {
- url = "";
- console.error("Invalid URL input:", url);
+ url = '';
+ console.error('Invalid URL input:', url);
}
const urlRegexPatterns = {
diff --git a/packages/bruno-converters/src/postman/postman-env-to-bruno-env.js b/packages/bruno-converters/src/postman/postman-env-to-bruno-env.js
index 1b0a4bf36..a57108349 100644
--- a/packages/bruno-converters/src/postman/postman-env-to-bruno-env.js
+++ b/packages/bruno-converters/src/postman/postman-env-to-bruno-env.js
@@ -1,5 +1,5 @@
import each from 'lodash/each';
-import { invalidVariableCharacterRegex } from '../constants';
+import { invalidVariableCharacterRegex } from '../constants';
import { uuid } from '../common';
const isSecret = (type) => {
@@ -9,7 +9,7 @@ const isSecret = (type) => {
const importPostmanEnvironmentVariables = (brunoEnvironment, values = []) => {
brunoEnvironment.variables = brunoEnvironment.variables || [];
- each(values.filter(i => !(i.key == null && i.value == null)), (i) => {
+ each(values.filter((i) => !(i.key == null && i.value == null)), (i) => {
const brunoEnvironmentVariable = {
uid: uuid(),
name: (i.key ?? '').replace(invalidVariableCharacterRegex, '_'),
diff --git a/packages/bruno-converters/src/postman/postman-to-bruno.js b/packages/bruno-converters/src/postman/postman-to-bruno.js
index a2023c30f..b3d6238c6 100644
--- a/packages/bruno-converters/src/postman/postman-to-bruno.js
+++ b/packages/bruno-converters/src/postman/postman-to-bruno.js
@@ -86,8 +86,8 @@ const constructUrlFromParts = (url) => {
const hostStr = Array.isArray(host) ? host.filter(Boolean).join('.') : host || '';
const pathStr = Array.isArray(path) ? path.filter(Boolean).join('/') : path || '';
const portStr = port ? `:${port}` : '';
- const queryStr =
- query && Array.isArray(query) && query.length > 0
+ const queryStr
+ = query && Array.isArray(query) && query.length > 0
? `?${query
.filter((q) => q && q.key)
.map((q) => `${q.key}=${q.value || ''}`)
@@ -131,7 +131,7 @@ const importScriptsFromEvents = (events, requestObject) => {
}
if (event.script.exec && event.script.exec.length > 0) {
- requestObject.script.req = postmanTranslation(event.script.exec)
+ requestObject.script.req = postmanTranslation(event.script.exec);
} else {
requestObject.script.req = '';
console.warn('Unexpected event.script.exec type', typeof event.script.exec);
@@ -144,7 +144,7 @@ const importScriptsFromEvents = (events, requestObject) => {
}
if (event.script.exec && event.script.exec.length > 0) {
- requestObject.script.res = postmanTranslation(event.script.exec)
+ requestObject.script.res = postmanTranslation(event.script.exec);
} else {
requestObject.script.res = '';
console.warn('Unexpected event.script.exec type', typeof event.script.exec);
@@ -155,7 +155,7 @@ const importScriptsFromEvents = (events, requestObject) => {
};
const importCollectionLevelVariables = (variables, requestObject) => {
- const vars = variables.filter(v => !(v.key == null && v.value == null)).map((v) => ({
+ const vars = variables.filter((v) => !(v.key == null && v.value == null)).map((v) => ({
uid: uuid(),
name: (v.key ?? '').replace(invalidVariableCharacterRegex, '_'),
value: v.value ?? '',
@@ -216,7 +216,7 @@ export const processAuth = (auth, requestObject, isCollection = false) => {
requestObject.auth.apikey = {
key: authValues.key || '',
value: authValues.value?.toString() || '', // Convert the value to a string as Postman's schema does not rigidly define the type of it,
- placement: 'header' //By default we are placing the apikey values in headers!
+ placement: 'header' // By default we are placing the apikey values in headers!
};
break;
case AUTH_TYPES.DIGEST:
@@ -266,14 +266,14 @@ export const processAuth = (auth, requestObject, isCollection = false) => {
...baseOAuth2Config,
authorizationUrl: findValueUsingKey('authUrl'),
callbackUrl: findValueUsingKey('redirect_uri'),
- pkce: true, // Explicitly set pkce to true for this grant type
+ pkce: true // Explicitly set pkce to true for this grant type
};
break;
case 'password_credentials':
requestObject.auth.oauth2 = {
...baseOAuth2Config,
username: findValueUsingKey('username'),
- password: findValueUsingKey('password'),
+ password: findValueUsingKey('password')
};
break;
case 'client_credentials':
@@ -358,9 +358,8 @@ const importPostmanV2CollectionItem = (brunoParent, item, { useWorkers = false }
}
folderMap[folderName] = brunoFolderItem;
-
} else if (i.request) {
- const method = i?.request?.method?.toUpperCase();
+ const method = i?.request?.method?.toUpperCase();
if (!method || typeof method !== 'string' || !method.trim()) {
console.warn('Missing or invalid request.method', method);
return;
@@ -410,7 +409,7 @@ const importPostmanV2CollectionItem = (brunoParent, item, { useWorkers = false }
const settings = {
encodeUrl: i.protocolProfileBehavior?.disableUrlEncoding !== true
- }
+ };
// Handle followRedirects setting
if (i.protocolProfileBehavior?.followRedirects !== undefined) {
@@ -439,7 +438,7 @@ const importPostmanV2CollectionItem = (brunoParent, item, { useWorkers = false }
brunoRequestItem.request.script = {};
}
if (event.script.exec && event.script.exec.length > 0) {
- brunoRequestItem.request.script.req = postmanTranslation(event.script.exec)
+ brunoRequestItem.request.script.req = postmanTranslation(event.script.exec);
} else {
brunoRequestItem.request.script.req = '';
console.warn('Unexpected event.script.exec type', typeof event.script.exec);
@@ -450,13 +449,12 @@ const importPostmanV2CollectionItem = (brunoParent, item, { useWorkers = false }
brunoRequestItem.request.script = {};
}
if (event.script.exec && event.script.exec.length > 0) {
- brunoRequestItem.request.script.res = postmanTranslation(event.script.exec)
+ brunoRequestItem.request.script.res = postmanTranslation(event.script.exec);
} else {
brunoRequestItem.request.script.res = '';
console.warn('Unexpected event.script.exec type', typeof event.script.exec);
}
}
-
});
}
}
@@ -734,7 +732,6 @@ const importPostmanV2CollectionItem = (brunoParent, item, { useWorkers = false }
});
};
-
const searchLanguageByHeader = (headers) => {
let contentType;
each(headers, (header) => {
@@ -824,7 +821,7 @@ const importPostmanV2Collection = async (collection, { useWorkers = false }) =>
// Apply translated scripts to all items in the collection
const applyScriptsToItems = (items) => {
- items.forEach(item => {
+ items.forEach((item) => {
if (item.type === 'folder') {
// Apply scripts to the folder
if (translatedScripts.has(item.uid)) {
@@ -866,7 +863,6 @@ const importPostmanV2Collection = async (collection, { useWorkers = false }) =>
};
applyScriptsToItems(brunoCollection.items);
-
} catch (error) {
console.error('Error in script translation worker:', error);
} finally {
@@ -877,7 +873,6 @@ const importPostmanV2Collection = async (collection, { useWorkers = false }) =>
return brunoCollection;
};
-
const parsePostmanCollection = async (collection, { useWorkers = false }) => {
try {
let schema = get(collection, 'info.schema');
@@ -906,7 +901,6 @@ const parsePostmanCollection = async (collection, { useWorkers = false }) => {
const postmanToBruno = async (postmanCollection, { useWorkers = false } = {}) => {
try {
-
const parsedPostmanCollection = await parsePostmanCollection(postmanCollection, { useWorkers });
const transformedCollection = transformItemsInCollection(parsedPostmanCollection);
const hydratedCollection = hydrateSeqInCollection(transformedCollection);
@@ -918,4 +912,4 @@ const postmanToBruno = async (postmanCollection, { useWorkers = false } = {}) =>
}
};
-export default postmanToBruno;
\ No newline at end of file
+export default postmanToBruno;
diff --git a/packages/bruno-converters/src/postman/postman-translations.js b/packages/bruno-converters/src/postman/postman-translations.js
index eb7fc1bbe..1c58b433b 100644
--- a/packages/bruno-converters/src/postman/postman-translations.js
+++ b/packages/bruno-converters/src/postman/postman-translations.js
@@ -34,7 +34,7 @@ const replacements = {
'pm\\.environment\\.name': 'bru.getEnvName()',
'pm\\.response\\.status': 'res.statusText',
'pm\\.response\\.headers': 'res.getHeaders()',
- "tests\\['([^']+)'\\]\\s*=\\s*([^;]+);": 'test("$1", function() { expect(Boolean($2)).to.be.true; });',
+ 'tests\\[\'([^\']+)\'\\]\\s*=\\s*([^;]+);': 'test("$1", function() { expect(Boolean($2)).to.be.true; });',
// Supported Postman request translations:
// - pm.request.url / request.url -> req.getUrl()
@@ -66,7 +66,7 @@ const replacements = {
'pm\\.cookies\\.jar\\(\\)\\.set\\(': 'bru.cookies.jar().setCookie(',
'pm\\.cookies\\.jar\\(\\)\\.unset\\(': 'bru.cookies.jar().deleteCookie(',
'pm\\.cookies\\.jar\\(\\)\\.clear\\(': 'bru.cookies.jar().deleteCookies(',
- 'pm\\.cookies\\.jar\\(\\)\\.getAll\\(': 'bru.cookies.jar().getCookies(',
+ 'pm\\.cookies\\.jar\\(\\)\\.getAll\\(': 'bru.cookies.jar().getCookies('
};
const extendedReplacements = Object.keys(replacements).reduce((acc, key) => {
@@ -85,15 +85,13 @@ const processRegexReplacement = (code) => {
for (const { regex, replacement } of compiledReplacements) {
if (regex.test(code)) {
code = code.replace(regex, replacement);
-
}
}
if ((code.includes('pm.') || code.includes('postman.'))) {
code = code.replace(/^(.*(pm\.|postman\.).*)$/gm, '// $1');
}
return code;
-}
-
+};
const postmanTranslation = (script, options = {}) => {
let modifiedScript = Array.isArray(script) ? script.join('\n') : script;
@@ -116,4 +114,4 @@ const postmanTranslation = (script, options = {}) => {
}
};
-export default postmanTranslation;
\ No newline at end of file
+export default postmanTranslation;
diff --git a/packages/bruno-converters/src/utils/jscode-shift-translator.js b/packages/bruno-converters/src/utils/jscode-shift-translator.js
index 8af8e07b1..67e92900c 100644
--- a/packages/bruno-converters/src/utils/jscode-shift-translator.js
+++ b/packages/bruno-converters/src/utils/jscode-shift-translator.js
@@ -4,7 +4,7 @@ const cloneDeep = require('lodash/cloneDeep');
/**
* Efficiently builds a string representation of a member expression without using toSource()
- *
+ *
* @param {Object} node - The member expression node from the AST
* @return {string} - String representation of the member expression (e.g., "pm.environment.get")
*/
@@ -13,16 +13,16 @@ function getMemberExpressionString(node) {
if (node.type === 'Identifier') {
return node.name;
}
-
+
if (node.type === 'CallExpression') {
const calleeStr = getMemberExpressionString(node.callee);
return `${calleeStr}()`;
}
-
+
// Handle member expressions
if (node.type === 'MemberExpression') {
const objectStr = getMemberExpressionString(node.object);
-
+
// For computed properties like obj[prop], we need special handling
if (node.computed) {
// For literals like obj["prop"], we can include them in the string
@@ -32,13 +32,13 @@ function getMemberExpressionString(node) {
// For other computed properties, we can't reliably represent them as a simple string
return `${objectStr}.[computed]`;
}
-
+
// For regular property access like obj.prop
if (node.property.type === 'Identifier') {
return `${objectStr}.${node.property.name}`;
}
}
-
+
return '[unsupported]';
}
@@ -47,13 +47,13 @@ const simpleTranslations = {
// Global Variables
'pm.globals.get': 'bru.getGlobalEnvVar',
'pm.globals.set': 'bru.setGlobalEnvVar',
-
+
// Environment variables
'pm.environment.get': 'bru.getEnvVar',
'pm.environment.set': 'bru.setEnvVar',
'pm.environment.name': 'bru.getEnvName()',
'pm.environment.unset': 'bru.deleteEnvVar',
-
+
// Variables
'pm.variables.get': 'bru.getVar',
'pm.variables.set': 'bru.setVar',
@@ -64,10 +64,10 @@ const simpleTranslations = {
'pm.collectionVariables.set': 'bru.setVar',
'pm.collectionVariables.has': 'bru.hasVar',
'pm.collectionVariables.unset': 'bru.deleteVar',
-
+
// Request flow control
'pm.setNextRequest': 'bru.setNextRequest',
-
+
// Testing
'pm.test': 'test',
'pm.expect': 'expect',
@@ -88,7 +88,7 @@ const simpleTranslations = {
'request.headers': 'req.getHeaders()',
'request.body': 'req.getBody()',
'request.name': 'req.getName()',
-
+
// Response properties
'pm.response.json': 'res.getBody',
'pm.response.code': 'res.getStatus()',
@@ -102,20 +102,20 @@ const simpleTranslations = {
'pm.response.size().header': 'res.getSize().header',
'pm.response.size().total': 'res.getSize().total',
'pm.cookies.jar': 'bru.cookies.jar',
-
+
'pm.cookies.jar().get': 'bru.cookies.jar().getCookie',
- 'pm.cookies.jar().getAll': 'bru.cookies.jar().getCookies',
+ 'pm.cookies.jar().getAll': 'bru.cookies.jar().getCookies',
'pm.cookies.jar().set': 'bru.cookies.jar().setCookie',
'pm.cookies.jar().unset': 'bru.cookies.jar().deleteCookie',
- 'pm.cookies.jar().clear': 'bru.cookies.jar().deleteCookies',
-
+ 'pm.cookies.jar().clear': 'bru.cookies.jar().deleteCookies',
+
// Execution control
'pm.execution.skipRequest': 'bru.runner.skipRequest',
-
+
// Legacy Postman API (deprecated) (we can use pm instead of postman, as we are converting all postman references to pm in the code as the part of pre-processing)
'pm.setEnvironmentVariable': 'bru.setEnvVar',
'pm.getEnvironmentVariable': 'bru.getEnvVar',
- 'pm.clearEnvironmentVariable': 'bru.deleteEnvVar',
+ 'pm.clearEnvironmentVariable': 'bru.deleteEnvVar'
};
/* Complex transformations that need custom handling
@@ -131,15 +131,15 @@ const complexTransformations = [
pattern: 'pm.sendRequest',
transform: sendRequestTransformer
},
-
+
// pm.environment.has requires special handling
- {
+ {
pattern: 'pm.environment.has',
transform: (path, j) => {
const callExpr = path.parent.value;
-
+
const args = callExpr.arguments;
-
+
// Create: bru.getEnvVar(arg) !== undefined && bru.getEnvVar(arg) !== null
return j.logicalExpression(
'&&',
@@ -174,9 +174,9 @@ const complexTransformations = [
pattern: 'pm.response.to.have.status',
transform: (path, j) => {
const callExpr = path.parent.value;
-
+
const args = callExpr.arguments;
-
+
// Create: expect(res.getStatus()).to.equal(arg)
return j.callExpression(
j.memberExpression(
@@ -201,9 +201,8 @@ const complexTransformations = [
pattern: 'pm.response.to.have.header',
transform: (path, j) => {
const callExpr = path.parent.value;
-
+
const args = callExpr.arguments;
-
if (args.length > 0) {
// Apply toLowerCase() to the first argument
@@ -232,15 +231,14 @@ const complexTransformations = [
),
args
);
-
}
},
- // handle pm.response.to.have.body to expect(res.getBody()).to.equal(arg)
+ // handle pm.response.to.have.body to expect(res.getBody()).to.equal(arg)
{
pattern: 'pm.response.to.have.body',
transform: (path, j) => {
const callExpr = path.parent.value;
-
+
const args = callExpr.arguments;
return j.callExpression(
@@ -250,7 +248,6 @@ const complexTransformations = [
),
args
);
-
}
},
@@ -259,9 +256,9 @@ const complexTransformations = [
pattern: 'pm.execution.setNextRequest',
transform: (path, j) => {
const callExpr = path.parent.value;
-
+
const args = callExpr.arguments;
-
+
// If argument is null or 'null', transform to bru.runner.stopExecution()
if (
args[0].type === 'Literal' && (args[0].value === null || args[0].value === 'null')
@@ -271,23 +268,23 @@ const complexTransformations = [
[]
);
}
-
+
// Otherwise, keep as bru.runner.setNextRequest with the same argument
return j.callExpression(
j.identifier('bru.runner.setNextRequest'),
args
);
}
- },
+ }
];
// Create a map for complex transformations to enable O(1) lookups
const complexTransformationsMap = {};
-complexTransformations.forEach(transform => {
+complexTransformations.forEach((transform) => {
complexTransformationsMap[transform.pattern] = transform;
});
-const varInitsToReplace = new Set(['pm', 'postman', 'pm.request','pm.response', 'pm.test', 'pm.expect', 'pm.environment', 'pm.variables', 'pm.collectionVariables', 'pm.execution', 'pm.globals']);
+const varInitsToReplace = new Set(['pm', 'postman', 'pm.request', 'pm.response', 'pm.test', 'pm.expect', 'pm.environment', 'pm.variables', 'pm.collectionVariables', 'pm.execution', 'pm.globals']);
/**
* Process all transformations (both simple and complex) in the AST in a single pass
@@ -295,12 +292,12 @@ const varInitsToReplace = new Set(['pm', 'postman', 'pm.request','pm.response',
* @param {Set} transformedNodes - Set of already transformed nodes
*/
function processTransformations(ast, transformedNodes) {
- ast.find(j.MemberExpression).forEach(path => {
+ ast.find(j.MemberExpression).forEach((path) => {
if (transformedNodes.has(path.node)) return;
-
+
// Get string representation using our utility function
const memberExprStr = getMemberExpressionString(path.value);
-
+
// First check for simple transformations (O(1))
if (simpleTranslations.hasOwnProperty(memberExprStr)) {
const replacement = simpleTranslations[memberExprStr];
@@ -308,15 +305,15 @@ function processTransformations(ast, transformedNodes) {
transformedNodes.add(path.node);
return; // Skip complex transformation check if simple transformation applied
}
-
+
// Then check for complex transformations (O(1))
- if (complexTransformationsMap.hasOwnProperty(memberExprStr) &&
- path.parent.value.type === 'CallExpression') {
+ if (complexTransformationsMap.hasOwnProperty(memberExprStr)
+ && path.parent.value.type === 'CallExpression') {
const transform = complexTransformationsMap[memberExprStr];
const replacement = transform.transform(path, j);
if (Array.isArray(replacement)) {
replacement.forEach((nodePath, index) => {
- if(index === 0) {
+ if (index === 0) {
j(path.parent).replaceWith(nodePath);
} else {
j(path.parent.parent).insertAfter(nodePath);
@@ -342,9 +339,9 @@ function translateCode(code) {
// Replace 'postman' with 'pm' using regex before creating the AST
// This is more efficient than an AST traversal
code = code.replace(/\bpostman\b/g, 'pm');
-
+
const ast = j(code);
-
+
// Keep track of transformed nodes to avoid double-processing
const transformedNodes = new Set();
@@ -356,13 +353,13 @@ function translateCode(code) {
// Process all transformations in a single pass
processTransformations(ast, transformedNodes);
-
+
// Handle legacy Postman global APIs
handleLegacyGlobalAPIs(ast, transformedNodes, code);
-
+
// Handle special Postman syntax patterns
handleTestsBracketNotation(ast);
-
+
return ast.toSource();
}
@@ -375,23 +372,22 @@ function preprocessAliases(ast) {
const symbolTable = new Map();
const MAX_ITERATIONS = 5;
let iterations = 0;
-
+
// Keep preprocessing until no more changes can be made
let changesMade;
do {
changesMade = false;
-
+
// First pass: Identify all variables
findVariableDefinitions(ast, symbolTable);
-
+
// Second pass: Replace all variable references with their resolved values
changesMade = resolveVariableReferences(ast, symbolTable) || false;
-
+
// Third pass: Clean up variable declarations that are no longer needed
changesMade = removeResolvedDeclarations(ast, symbolTable) || false;
iterations++;
-
} while (changesMade && iterations < MAX_ITERATIONS);
}
@@ -402,23 +398,22 @@ function preprocessAliases(ast) {
*/
function findVariableDefinitions(ast, symbolTable) {
// Use a single traversal to handle both direct assignments and object destructuring
- ast.find(j.VariableDeclarator).forEach(path => {
+ ast.find(j.VariableDeclarator).forEach((path) => {
// Only process nodes that have an initializer
if (!path.value.init) return;
// Handle direct assignments: const response = pm.response
if (path.value.id.type === 'Identifier') {
const varName = path.value.id.name;
-
+
// If it's a direct identifier, just map it
if (path.value.init.type === 'Identifier') {
- symbolTable.set(varName, {
+ symbolTable.set(varName, {
type: 'identifier',
value: path.value.init.name
});
- }
- // If it's a member expression, store both parts
- else if (path.value.init.type === 'MemberExpression') {
+ } else if (path.value.init.type === 'MemberExpression') {
+ // If it's a member expression, store both parts
const sourceCode = getMemberExpressionString(path.value.init);
symbolTable.set(varName, {
type: 'memberExpression',
@@ -426,12 +421,11 @@ function findVariableDefinitions(ast, symbolTable) {
node: path.value.init
});
}
- }
- // Handle object destructuring: const { response } = pm
- else if (path.value.id.type === 'ObjectPattern' && path.value.init.type === 'Identifier') {
+ } else if (path.value.id.type === 'ObjectPattern' && path.value.init.type === 'Identifier') {
+ // Handle object destructuring: const { response } = pm
const source = path.value.init.name;
-
- path.value.id.properties.forEach(prop => {
+
+ path.value.id.properties.forEach((prop) => {
if (prop.key.name && prop.value.type === 'Identifier') {
const destVarName = prop.value.name;
symbolTable.set(destVarName, {
@@ -456,28 +450,28 @@ function findVariableDefinitions(ast, symbolTable) {
*/
function resolveVariableReferences(ast, symbolTable) {
let changesMade = false;
-
+
/**
* Example of what this function does:
- *
+ *
* Input Postman code:
* const response = pm.response;
* const jsonData = response.json(); // response is a reference to pm.response
- *
+ *
* After resolution:
* const response = pm.response;
* const jsonData = pm.response.json(); // response reference is replaced with pm.response
- *
+ *
* Then in the next preprocessing phase, unnecessary variables like 'response' will be removed.
*/
-
+
// Replace all identifier references with their resolved values
- ast.find(j.Identifier).forEach(path => {
+ ast.find(j.Identifier).forEach((path) => {
const varName = path.value.name;
-
+
/**
* Skip specific types of identifiers that shouldn't be replaced:
- *
+ *
* Case 1: Variable definitions (left side of declarations)
* -----------------------------------------------------
* In code like:
@@ -485,7 +479,7 @@ function resolveVariableReferences(ast, symbolTable) {
* ^
* We shouldn't replace 'response' on the left side with pm.response,
* which would result in: const pm.response = pm.response; (invalid syntax)
- *
+ *
* Case 2: Property names in member expressions
* -----------------------------------------------------
* In code like:
@@ -493,11 +487,11 @@ function resolveVariableReferences(ast, symbolTable) {
* ^
* We shouldn't replace the 'status' property name with anything,
* only the 'response' object reference should be replaced.
- *
+ *
* We only want to replace identifiers that are being used as references,
* not the ones being defined or used as property names.
*/
-
+
// Skip if this is a variable definition or property name
if (path.parent.value.type === 'VariableDeclarator' && path.parent.value.id === path.value) {
return;
@@ -505,12 +499,12 @@ function resolveVariableReferences(ast, symbolTable) {
if (path.parent.value.type === 'MemberExpression' && path.parent.value.property === path.value && !path.parent.value.computed) {
return;
}
-
+
// Only replace if this is a known variable
if (!symbolTable.has(varName)) return;
const symbolInfo = symbolTable.get(varName);
- if(!varInitsToReplace.has(symbolInfo.value)) {
+ if (!varInitsToReplace.has(symbolInfo.value)) {
return;
}
const newNode = cloneDeep(symbolInfo.node);
@@ -520,10 +514,9 @@ function resolveVariableReferences(ast, symbolTable) {
value: symbolInfo.value,
node: newNode
});
- changesMade = true;
-
+ changesMade = true;
});
-
+
return changesMade;
}
@@ -533,54 +526,54 @@ function resolveVariableReferences(ast, symbolTable) {
* @param {Map} symbolTable - Map of variable references
* @returns {boolean} Whether any changes were made
*/
-function removeResolvedDeclarations(ast, symbolTable) {
+function removeResolvedDeclarations(ast, symbolTable) {
let changesMade = false;
-
+
/**
* Example of what this function does:
- *
+ *
* Original Postman code:
* const response = pm.response;
* const jsonData = response.json();
* console.log(jsonData.name);
- *
+ *
* After variable resolution:
* const response = pm.response; // This declaration is now redundant
* const jsonData = pm.response.json(); // This value has been resolved
* console.log(jsonData.name); // This still references jsonData
- *
+ *
* Final code after this cleanup step:
* const jsonData = pm.response.json(); // response variable declaration is removed
* console.log(jsonData.name); // jsonData is kept since it's still referenced
- *
+ *
* We only remove declarations that:
* 1. Have been fully resolved (references to pm.* objects)
* 2. No longer provide any value (since all references were replaced with resolved values)
*/
-
+
// Use a single traversal to handle both regular variable declarations and destructuring
- ast.find(j.VariableDeclarator).forEach(path => {
+ ast.find(j.VariableDeclarator).forEach((path) => {
// Case 1: Handle regular variable declarations
if (path.value.id.type === 'Identifier') {
const varName = path.value.id.name;
const replacement = symbolTable.get(varName);
- if(!replacement || !varInitsToReplace.has(replacement.value)) return;
-
+ if (!replacement || !varInitsToReplace.has(replacement.value)) return;
+
/**
* This code differentiates between two types of variable declarations:
- *
+ *
* Example 1: Single variable declaration
* -----------------------------------
* Input: const response = pm.response;
* Action: The entire statement can be removed
* Output: [statement removed]
- *
+ *
* Example 2: Multiple variables in one declaration
* -----------------------------------
* Input: const response = pm.response, unrelated = 5;
* Action: Only remove the 'response' declarator, keep the others
* Output: const unrelated = 5;
- *
+ *
* We need this distinction to ensure we don't accidentally remove
* unrelated variables that happen to be declared in the same statement.
*/
@@ -591,47 +584,45 @@ function removeResolvedDeclarations(ast, symbolTable) {
// Otherwise just remove this declarator
j(path).remove();
}
-
+
changesMade = true;
- }
- // Case 2: Handle destructuring of pm
- else if (path.value.id.type === 'ObjectPattern' &&
- path.value.init &&
- path.value.init.type === 'Identifier' &&
- path.value.init.name === 'pm') {
-
+ } else if (path.value.id.type === 'ObjectPattern'
+ // Case 2: Handle destructuring of pm
+ && path.value.init
+ && path.value.init.type === 'Identifier'
+ && path.value.init.name === 'pm') {
/**
* Example of destructuring removal:
- *
+ *
* Original Postman code:
* const { response, environment } = pm;
* console.log(response.json().name);
* console.log(environment.get("variable"));
- *
+ *
* After variable resolution steps:
* const { response, environment } = pm; // This destructuring is now redundant
* console.log(pm.response.json().name); // 'response' references already replaced with pm.response
* console.log(pm.environment.get("variable")); // 'environment' references replaced
- *
+ *
* Final code after this cleanup step:
* console.log(pm.response.json().name); // Destructuring declaration is completely removed
* console.log(pm.environment.get("variable"));
- *
+ *
* This step specifically targets the Postman pattern of destructuring the pm object,
* which is common in Postman scripts but needs to be removed in the Bruno conversion.
*/
-
+
const declarationPath = j(path).closest(j.VariableDeclaration);
if (declarationPath.get().value.declarations.length === 1) {
declarationPath.remove();
} else {
j(path).remove();
}
-
+
changesMade = true;
}
});
-
+
return changesMade;
}
@@ -642,25 +633,25 @@ function removeResolvedDeclarations(ast, symbolTable) {
function processCookieJarVariables(ast) {
// Map of Postman cookie jar method names to Bruno equivalents
const cookieMethodMapping = {
- 'get': 'getCookie',
- 'getAll': 'getCookies',
- 'set': 'setCookie',
- 'unset': 'deleteCookie',
- 'clear': 'deleteCookies'
+ get: 'getCookie',
+ getAll: 'getCookies',
+ set: 'setCookie',
+ unset: 'deleteCookie',
+ clear: 'deleteCookies'
};
// Track variables that are assigned to cookie jar instances
const cookieJarVariables = new Set();
// First pass: Find all variables assigned to cookie jar instances
- ast.find(j.VariableDeclarator).forEach(path => {
+ ast.find(j.VariableDeclarator).forEach((path) => {
if (path.value.init && path.value.init.type === 'CallExpression') {
const initCall = path.value.init;
-
+
// Check if this is a cookie jar assignment
if (initCall.callee.type === 'MemberExpression') {
const calleeStr = getMemberExpressionString(initCall.callee);
-
+
if (calleeStr === 'pm.cookies.jar' || calleeStr === 'bru.cookies.jar') {
if (path.value.id.type === 'Identifier') {
cookieJarVariables.add(path.value.id.name);
@@ -671,14 +662,13 @@ function processCookieJarVariables(ast) {
});
// Second pass: Rename method calls on cookie jar variables
- ast.find(j.CallExpression).forEach(path => {
- if (path.value.callee.type === 'MemberExpression' &&
- path.value.callee.object.type === 'Identifier' &&
- path.value.callee.property.type === 'Identifier') {
-
+ ast.find(j.CallExpression).forEach((path) => {
+ if (path.value.callee.type === 'MemberExpression'
+ && path.value.callee.object.type === 'Identifier'
+ && path.value.callee.property.type === 'Identifier') {
const varName = path.value.callee.object.name;
const methodName = path.value.callee.property.name;
-
+
// If this is a method call on a cookie jar variable
if (cookieJarVariables.has(varName) && cookieMethodMapping[methodName]) {
const newMethodName = cookieMethodMapping[methodName];
@@ -704,23 +694,22 @@ function handleTestsBracketNotation(ast) {
property: {} // Accept any property type
}
}
- }).forEach(path => {
+ }).forEach((path) => {
// Get the assignment expression
const assignment = path.value.expression;
const left = assignment.left;
-
+
// Verify it's a valid tests[] expression
- if (left.object.type === 'Identifier' &&
- left.object.name === 'tests' &&
- left.computed === true) {
-
+ if (left.object.type === 'Identifier'
+ && left.object.name === 'tests'
+ && left.computed === true) {
const property = left.property;
const rightSide = assignment.right;
-
+
// Handle string literals
if (property.type === 'Literal' && typeof property.value === 'string') {
const testName = property.value;
-
+
// Replace with test() function call
j(path).replaceWith(
j.expressionStatement(
@@ -752,15 +741,14 @@ function handleTestsBracketNotation(ast) {
)
)
);
- }
- // Handle template literals
- else if (property.type === 'TemplateLiteral') {
+ } else if (property.type === 'TemplateLiteral') {
+ // Handle template literals
// Create a template literal with the same quasi and expressions
const templateLiteral = j.templateLiteral(
property.quasis,
property.expressions
);
-
+
// Replace with test() function call using template literal
j(path).replaceWith(
j.expressionStatement(
@@ -801,7 +789,7 @@ function handleTestsBracketNotation(ast) {
* Handle legacy Postman global API transformations
* This function processes legacy Postman globals like responseBody, responseHeaders, responseTime
* while preserving user-defined variables with the same names
- *
+ *
* @param {Object} ast - jscodeshift AST
* @param {Set} transformedNodes - Set of already transformed nodes
* @param {string} code - The original Postman script code
@@ -816,9 +804,9 @@ function handleLegacyGlobalAPIs(ast, transformedNodes, code) {
// Check for variable declarations with legacy global names - track which ones have conflicts
const conflictingNames = new Set();
-
+
// Check variable declarations
- ast.find(j.VariableDeclarator).forEach(path => {
+ ast.find(j.VariableDeclarator).forEach((path) => {
if (path.value.id.type === 'Identifier') {
const varName = path.value.id.name;
if (legacyGlobalRegex.test(varName)) {
@@ -830,13 +818,13 @@ function handleLegacyGlobalAPIs(ast, transformedNodes, code) {
// Handle JSON.parse(responseBody) โ res.getBody()
// Only transform if responseBody doesn't have a user variable conflict
if (!conflictingNames.has('responseBody')) {
- ast.find(j.CallExpression).forEach(path => {
+ ast.find(j.CallExpression).forEach((path) => {
if (transformedNodes.has(path.node)) return;
-
+
const callExpr = path.value;
if (callExpr.callee.type === 'MemberExpression' && callExpr.callee.object.name === 'JSON' && callExpr.callee.property.name === 'parse') {
const args = callExpr.arguments;
-
+
// Check if the argument is 'responseBody'
if (args.length > 0 && args[0].type === 'Identifier' && args[0].name === 'responseBody') {
// Replace JSON.parse(responseBody) with res.getBody()
@@ -859,33 +847,33 @@ function handleLegacyGlobalAPIs(ast, transformedNodes, code) {
if (conflictingNames.has(name)) {
return;
}
-
- ast.find(j.Identifier, { name }).forEach(path => {
+
+ ast.find(j.Identifier, { name }).forEach((path) => {
if (transformedNodes.has(path.node)) return;
-
+
// Only transform identifiers that are being used as values, not as variable names
const parent = path.parent.value;
-
+
// Skip if this is part of a variable declaration (const responseBody = ...)
if (parent.type === 'VariableDeclarator' && parent.id === path.node) {
return; // Keep unchanged
}
-
+
// Skip if this is part of an assignment (responseBody = ...)
if (parent.type === 'AssignmentExpression' && parent.left === path.node) {
return; // Keep unchanged
}
-
+
// Skip if this is part of a function parameter
if (parent.type === 'FunctionDeclaration' || parent.type === 'FunctionExpression') {
return; // Keep unchanged
}
-
+
// Skip if this is part of an object property
if (parent.type === 'Property' && (parent.key === path.node || parent.value === path.node)) {
return; // Keep unchanged
}
-
+
// Transform all other references (including function call arguments)
// This will transform console.log(responseBody) โ console.log(res.getBody())
j(path).replaceWith(j.identifier(replacement));
@@ -895,4 +883,4 @@ function handleLegacyGlobalAPIs(ast, transformedNodes, code) {
}
export { getMemberExpressionString };
-export default translateCode;
\ No newline at end of file
+export default translateCode;
diff --git a/packages/bruno-converters/src/utils/send-request-transformer.js b/packages/bruno-converters/src/utils/send-request-transformer.js
index 4f16c4311..1e22b4694 100644
--- a/packages/bruno-converters/src/utils/send-request-transformer.js
+++ b/packages/bruno-converters/src/utils/send-request-transformer.js
@@ -6,12 +6,12 @@
*/
const convertArrayToObject = (j, arrayValue) => {
const obj = j.objectExpression([]);
-
+
if (arrayValue.type === 'ArrayExpression') {
- arrayValue.elements.forEach(elem => {
+ arrayValue.elements.forEach((elem) => {
if (elem.type === 'ObjectExpression') {
- const keyProp = elem.properties.find(p => (p.key.name === 'key' || p.key.value === 'key'));
- const valueProp = elem.properties.find(p => (p.key.name === 'value' || p.key.value === 'value'));
+ const keyProp = elem.properties.find((p) => (p.key.name === 'key' || p.key.value === 'key'));
+ const valueProp = elem.properties.find((p) => (p.key.name === 'value' || p.key.value === 'value'));
if (keyProp && valueProp) {
obj.properties.push(
@@ -25,7 +25,7 @@ const convertArrayToObject = (j, arrayValue) => {
}
});
}
-
+
return obj;
};
@@ -37,7 +37,7 @@ const convertArrayToObject = (j, arrayValue) => {
* @param {string} headerValue - Header value
*/
const addOrUpdateHeader = (j, requestOptions, headerName, headerValue) => {
- let headersProp = requestOptions.properties.find(p => (p.key.name === 'headers' || p.key.value === 'headers'));
+ let headersProp = requestOptions.properties.find((p) => (p.key.name === 'headers' || p.key.value === 'headers'));
if (!headersProp) {
headersProp = j.property('init', j.identifier('headers'), j.objectExpression([]));
@@ -47,9 +47,9 @@ const addOrUpdateHeader = (j, requestOptions, headerName, headerValue) => {
}
// filter out existing header with same name (case-insensitive)
- headersProp.value.properties = headersProp.value.properties.filter(p =>
- p.key.type !== 'Literal' ||
- p.key.value.toLowerCase() !== headerName.toLowerCase()
+ headersProp.value.properties = headersProp.value.properties.filter((p) =>
+ p.key.type !== 'Literal'
+ || p.key.value.toLowerCase() !== headerName.toLowerCase()
);
headersProp.value.properties.push(
@@ -69,7 +69,7 @@ const addOrUpdateHeader = (j, requestOptions, headerName, headerValue) => {
const transformHeaders = (j, requestOptions) => {
if (requestOptions.type !== 'ObjectExpression') return;
- requestOptions.properties.forEach(prop => {
+ requestOptions.properties.forEach((prop) => {
// find and rename 'header' property to 'headers'
if (prop.key.name === 'header' || prop.key.value === 'header') {
prop.key.name = 'headers';
@@ -91,19 +91,19 @@ const transformHeaders = (j, requestOptions) => {
*/
const transformBody = (j, requestOptions) => {
if (requestOptions.type !== 'ObjectExpression') return null;
-
- requestOptions.properties.forEach(prop => {
+
+ requestOptions.properties.forEach((prop) => {
if (prop.key.name === 'body' || prop.key.value === 'body') {
if (prop.value.type === 'ObjectExpression') {
const bodyProps = prop.value.properties;
- const modeProp = bodyProps.find(p => (p.key.name === 'mode' || p.key.value === 'mode'));
+ const modeProp = bodyProps.find((p) => (p.key.name === 'mode' || p.key.value === 'mode'));
if (modeProp && modeProp.value.type === 'Literal') {
const bodyMode = modeProp.value.value;
// Handle raw mode (text, json, xml, etc.)
if (bodyMode === 'raw') {
- const rawProp = bodyProps.find(p => (p.key.name === 'raw' || p.key.value === 'raw'));
+ const rawProp = bodyProps.find((p) => (p.key.name === 'raw' || p.key.value === 'raw'));
if (rawProp) {
// Replace body with data
@@ -111,37 +111,35 @@ const transformBody = (j, requestOptions) => {
prop.key.value = 'data';
prop.value = rawProp.value;
}
- }
- // Handle urlencoded mode
- else if (bodyMode === 'urlencoded') {
- const urlencodedProp = bodyProps.find(p => (p.key.name === 'urlencoded' || p.key.value === 'urlencoded') && p.value.type === 'ArrayExpression');
+ } else if (bodyMode === 'urlencoded') {
+ // Handle urlencoded mode
+ const urlencodedProp = bodyProps.find((p) => (p.key.name === 'urlencoded' || p.key.value === 'urlencoded') && p.value.type === 'ArrayExpression');
if (urlencodedProp) {
// Replace the body property with a 'data' property
prop.key.name = 'data';
prop.key.value = 'data';
-
+
// Transform the urlencoded array to an object
prop.value = convertArrayToObject(j, urlencodedProp.value);
// Add Content-Type header for urlencoded
addOrUpdateHeader(j, requestOptions, 'Content-Type', 'application/x-www-form-urlencoded');
}
- }
- // Handle formdata mode
- else if (bodyMode === 'formdata') {
- const formdataProp = bodyProps.find(p => (p.key.name === 'formdata' || p.key.value === 'formdata') && p.value.type === 'ArrayExpression');
+ } else if (bodyMode === 'formdata') {
+ // Handle formdata mode
+ const formdataProp = bodyProps.find((p) => (p.key.name === 'formdata' || p.key.value === 'formdata') && p.value.type === 'ArrayExpression');
if (formdataProp) {
- // Replace the body property with a 'data' property
- prop.key.name = 'data';
- prop.key.value = 'data';
-
- // Transform the urlencoded array to an object
- prop.value = convertArrayToObject(j, formdataProp.value);
-
- // Add Content-Type header for urlencoded
- addOrUpdateHeader(j, requestOptions, 'Content-Type', 'multipart/form-data');
+ // Replace the body property with a 'data' property
+ prop.key.name = 'data';
+ prop.key.value = 'data';
+
+ // Transform the urlencoded array to an object
+ prop.value = convertArrayToObject(j, formdataProp.value);
+
+ // Add Content-Type header for urlencoded
+ addOrUpdateHeader(j, requestOptions, 'Content-Type', 'multipart/form-data');
}
}
}
@@ -158,7 +156,7 @@ const transformBody = (j, requestOptions) => {
*/
const transformCallback = (j, callback) => {
if (!callback || (callback.type !== 'FunctionExpression' && callback.type !== 'ArrowFunctionExpression')) return null;
-
+
const params = callback.params;
const callbackBody = callback.body;
@@ -175,10 +173,10 @@ const transformCallback = (j, callback) => {
// Define translations for callback response properties
const responsePropertyMap = {
- 'json': 'data',
- 'text': 'data',
- 'code': 'status',
- 'status': 'statusText',
+ json: 'data',
+ text: 'data',
+ code: 'status',
+ status: 'statusText'
};
// Process the callback body to transform response property references
@@ -187,7 +185,7 @@ const transformCallback = (j, callback) => {
type: 'Identifier',
name: responseVarName
}
- }).forEach(memberPath => {
+ }).forEach((memberPath) => {
const property = memberPath.node.property;
// Handle property access
@@ -239,26 +237,25 @@ const findAndTransformVariableDeclaration = (j, root, variableName, visited = ne
return null;
}
visited.add(variableName);
-
+
let transformedConfig = null;
-
+
// Find the variable declaration
root.find(j.VariableDeclarator, {
id: { name: variableName }
- }).forEach(declaratorPath => {
+ }).forEach((declaratorPath) => {
const init = declaratorPath.value.init;
-
+
if (init && init.type === 'ObjectExpression') {
// Found the actual object expression - clone and transform it
const configClone = j(init).at(0).get().value;
-
+
// Transform headers and body
transformHeaders(j, configClone);
transformBody(j, configClone);
-
+
transformedConfig = configClone;
- }
- else if (init && init.type === 'Identifier') {
+ } else if (init && init.type === 'Identifier') {
// This variable references another variable - follow the chain
const referencedVariableName = init.name;
transformedConfig = findAndTransformVariableDeclaration(j, root, referencedVariableName, visited);
@@ -288,14 +285,13 @@ const sendRequestTransformer = (path, j) => {
transformHeaders(j, requestOptions);
// Transform body
transformBody(j, requestOptions);
- }
- // Handle case where requestOptions is a variable reference
- else if (requestOptions.type === 'Identifier') {
+ } else if (requestOptions.type === 'Identifier') {
+ // Handle case where requestOptions is a variable reference
const variableName = requestOptions.name;
-
+
// Find the root of the current file/program
const root = j(path).closest(j.Program);
-
+
// Find and transform the variable declaration
findAndTransformVariableDeclaration(j, root, variableName);
}
@@ -303,12 +299,12 @@ const sendRequestTransformer = (path, j) => {
// Create the callback block and promise chain if there's a callback
if (callback) {
const transformedCallback = transformCallback(j, callback);
-
+
// Add async keyword to the callback function
if (transformedCallback && (transformedCallback.type === 'FunctionExpression' || transformedCallback.type === 'ArrowFunctionExpression')) {
transformedCallback.async = true;
}
-
+
// Create expression: await bru.sendRequest(requestConfig, callback);
const sendRequestCall = j.callExpression(
j.identifier('bru.sendRequest'),
@@ -323,8 +319,8 @@ const sendRequestTransformer = (path, j) => {
j.identifier('bru.sendRequest'),
[requestOptions]
);
-
+
return wasAwaited ? sendRequestCall : j.awaitExpression(sendRequestCall);
};
-export default sendRequestTransformer;
\ No newline at end of file
+export default sendRequestTransformer;
diff --git a/packages/bruno-converters/src/workers/postman-translator-worker.js b/packages/bruno-converters/src/workers/postman-translator-worker.js
index 1c9ebea79..c4e0b31b5 100644
--- a/packages/bruno-converters/src/workers/postman-translator-worker.js
+++ b/packages/bruno-converters/src/workers/postman-translator-worker.js
@@ -3,7 +3,7 @@ const path = require('node:path');
const os = require('node:os');
function getMaxWorkers() {
- return Math.max(os.availableParallelism(), 1)
+ return Math.max(os.availableParallelism(), 1);
}
class WorkerPool {
@@ -28,7 +28,7 @@ class WorkerPool {
runTask(data) {
return new Promise((resolve, reject) => {
const task = { data, resolve, reject };
-
+
if (this.idle.length > 0) {
this._runTaskOnWorker(this.idle.shift(), task);
} else {
@@ -40,42 +40,42 @@ class WorkerPool {
// Run a task on a specific worker
_runTaskOnWorker(workerId, task) {
const worker = this.workers[workerId];
-
+
const messageHandler = (result) => {
// Cleanup listeners
worker.removeListener('message', messageHandler);
worker.removeListener('error', errorHandler);
-
+
// Mark worker as idle
this.idle.push(workerId);
-
+
// Process queue if tasks are waiting
if (this.queue.length > 0) {
this._runTaskOnWorker(workerId, this.queue.shift());
}
-
+
// Resolve the task
task.resolve(result);
};
-
+
const errorHandler = (err) => {
worker.removeListener('message', messageHandler);
worker.removeListener('error', errorHandler);
-
+
this.idle.push(workerId);
-
+
if (this.queue.length > 0) {
this._runTaskOnWorker(workerId, this.queue.shift());
}
-
+
task.reject(err);
};
-
+
worker.on('message', messageHandler);
worker.on('error', errorHandler);
worker.postMessage(task.data);
}
-
+
// Terminate all workers
terminate() {
for (const worker of this.workers) {
@@ -95,8 +95,8 @@ function countScriptLines(script) {
// Calculate complexity of a script entry
function calculateScriptComplexity([uid, entry]) {
let totalLines = 0;
- const { events } = entry
-
+ const { events } = entry;
+
if (events && Array.isArray(events)) {
events.forEach(({ script }) => {
if (script && script.exec) {
@@ -104,7 +104,7 @@ function calculateScriptComplexity([uid, entry]) {
}
});
}
-
+
return { uid, entry, complexity: totalLines || 1 }; // Minimum complexity of 1
}
@@ -112,86 +112,84 @@ function calculateScriptComplexity([uid, entry]) {
function createBalancedBatches(scriptEntries, workerCount) {
// Calculate complexity for each script
const scriptsWithComplexity = scriptEntries.map(calculateScriptComplexity);
-
+
// Sort scripts by complexity (descending)
scriptsWithComplexity.sort((a, b) => b.complexity - a.complexity);
-
+
// Initialize batches
- const batches = Array.from({ length: workerCount }, () => ({
- entries: [],
- totalComplexity: 0
+ const batches = Array.from({ length: workerCount }, () => ({
+ entries: [],
+ totalComplexity: 0
}));
-
+
// Algorithm: Greedy load balancing
// 1. Process scripts in descending order of complexity
// 2. Always assign each script to the batch with lowest current load
// 3. This minimizes the maximum workload across all workers
for (const { uid, entry, complexity } of scriptsWithComplexity) {
-
const batchWithLowestComplexity = batches.reduce(
(target, current) => current.totalComplexity < target.totalComplexity ? current : target
);
-
+
// Add the script to this batch
- batchWithLowestComplexity.entries.push({uid, entry});
+ batchWithLowestComplexity.entries.push({ uid, entry });
batchWithLowestComplexity.totalComplexity += complexity;
}
-
- return batches.map(batch =>
+
+ return batches.map((batch) =>
batch.entries.map(({ uid, entry }) => [uid, entry])
- ).filter(batch => batch.length > 0);
+ ).filter((batch) => batch.length > 0);
}
const scriptTranslationWorker = async (scriptMap) => {
// Convert the Map to an array of entries
const scriptEntries = Array.from(scriptMap.entries());
const maxWorkers = getMaxWorkers();
-
+
// For very small collections, don't parallelize
if (scriptEntries.length <= 50) {
- const workerPool = new WorkerPool(path.join(__dirname,'./src/workers/scripts/translate-postman-scripts.js'), 1);
+ const workerPool = new WorkerPool(path.join(__dirname, './src/workers/scripts/translate-postman-scripts.js'), 1);
workerPool.initialize();
-
+
try {
const translatedScripts = new Map();
const result = await workerPool.runTask({ scripts: scriptEntries });
-
+
if (result.error) {
console.error('Error in script translation worker:', result.error);
throw new Error(result.error);
}
-
+
result.forEach(([uid, { request }]) => {
translatedScripts.set(uid, { request });
});
-
+
return translatedScripts;
} finally {
workerPool.terminate();
}
}
-
const workerCount = Math.min(maxWorkers, 4);
-
+
// Create balanced batches based on script complexity
const batches = createBalancedBatches(scriptEntries, workerCount);
-
- const translatedScripts = new Map();
+
+ const translatedScripts = new Map();
// Create worker pool with optimal size
- const workerPool = new WorkerPool(path.join(__dirname,'./src/workers/scripts/translate-postman-scripts.js'), workerCount);
+ const workerPool = new WorkerPool(path.join(__dirname, './src/workers/scripts/translate-postman-scripts.js'), workerCount);
workerPool.initialize();
// Process all batches in parallel using worker pool
- const batchPromises = batches.map(batch => {
+ const batchPromises = batches.map((batch) => {
return workerPool.runTask({ scripts: batch })
- .then(modScripts => {
+ .then((modScripts) => {
modScripts.forEach(([name, { request }]) => {
translatedScripts.set(name, { request });
});
})
- .catch(err => {
+ .catch((err) => {
console.error('Error in script translation worker:', err);
throw new Error(err);
});
@@ -208,4 +206,4 @@ const scriptTranslationWorker = async (scriptMap) => {
return translatedScripts;
};
-export default scriptTranslationWorker
\ No newline at end of file
+export default scriptTranslationWorker;
diff --git a/packages/bruno-converters/src/workers/scripts/translate-postman-scripts.js b/packages/bruno-converters/src/workers/scripts/translate-postman-scripts.js
index 816a08f03..9d532b832 100644
--- a/packages/bruno-converters/src/workers/scripts/translate-postman-scripts.js
+++ b/packages/bruno-converters/src/workers/scripts/translate-postman-scripts.js
@@ -7,21 +7,21 @@ parentPort.on('message', (workerData) => {
const modScripts = scripts.map(([uid, { events }]) => {
const requestObject = {
script: {}
- }
-
+ };
+
if (events && Array.isArray(events)) {
events.forEach((event) => {
- if(event?.script && event.script.exec) {
- if(event.listen === 'prerequest') {
- if(event.script.exec && event.script.exec.length > 0) {
+ if (event?.script && event.script.exec) {
+ if (event.listen === 'prerequest') {
+ if (event.script.exec && event.script.exec.length > 0) {
requestObject.script.req = postmanTranslation(event.script.exec);
} else {
requestObject.script.req = '';
}
}
- if(event.listen === 'test') {
- if(event.script.exec && event.script.exec.length > 0) {
+ if (event.listen === 'test') {
+ if (event.script.exec && event.script.exec.length > 0) {
requestObject.script.res = postmanTranslation(event.script.exec);
} else {
requestObject.script.res = '';
@@ -33,11 +33,10 @@ parentPort.on('message', (workerData) => {
return [uid, { request: requestObject }];
});
-
+
parentPort.postMessage(modScripts);
- }
- catch(error) {
+ } catch (error) {
console.error(error);
parentPort.postMessage({ error: error?.message });
}
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/insomnia/insomnia-collection-v5.spec.js b/packages/bruno-converters/tests/insomnia/insomnia-collection-v5.spec.js
index e7be6dea8..3d73e8398 100644
--- a/packages/bruno-converters/tests/insomnia/insomnia-collection-v5.spec.js
+++ b/packages/bruno-converters/tests/insomnia/insomnia-collection-v5.spec.js
@@ -5,7 +5,7 @@ describe('insomnia-collection', () => {
it('should correctly import a valid Insomnia v5 collection file', async () => {
const brunoCollection = insomniaToBruno(insomniaCollection);
- expect(brunoCollection).toMatchObject(expectedOutput)
+ expect(brunoCollection).toMatchObject(expectedOutput);
});
});
@@ -81,7 +81,7 @@ environments:
data:
var1: value1
var2: value2
-`
+`;
const expectedOutput = {
environments: [
@@ -105,81 +105,81 @@ const expectedOutput = {
]
}
],
- "items": [
+ items: [
{
- "items": [
+ items: [
{
- "name": "Request1",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "none",
+ name: 'Request1',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'none'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "url": "https://testbench-sanity.usebruno.com/ping"
+ headers: [],
+ method: 'GET',
+ params: [],
+ url: 'https://testbench-sanity.usebruno.com/ping'
},
- "seq": 1,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- "settings": {
- "encodeUrl": true,
- },
- },
+ seq: 1,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456',
+ settings: {
+ encodeUrl: true
+ }
+ }
],
- "name": "Folder1",
- "type": "folder",
- "uid": "mockeduuidvalue123456",
+ name: 'Folder1',
+ type: 'folder',
+ uid: 'mockeduuidvalue123456'
},
{
- "items": [
+ items: [
{
- "name": "Request2",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "none",
+ name: 'Request2',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'none'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "url": "https://testbench-sanity.usebruno.com/ping"
+ headers: [],
+ method: 'GET',
+ params: [],
+ url: 'https://testbench-sanity.usebruno.com/ping'
},
- "seq": 1,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- "settings": {
- "encodeUrl": false,
- },
- },
+ seq: 1,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456',
+ settings: {
+ encodeUrl: false
+ }
+ }
],
- "name": "Folder2",
- "type": "folder",
- "uid": "mockeduuidvalue123456",
- },
+ name: 'Folder2',
+ type: 'folder',
+ uid: 'mockeduuidvalue123456'
+ }
],
- "name": "Hello World Workspace Insomnia",
- "uid": "mockeduuidvalue123456",
- "version": "1",
-};
\ No newline at end of file
+ name: 'Hello World Workspace Insomnia',
+ uid: 'mockeduuidvalue123456',
+ version: '1'
+};
diff --git a/packages/bruno-converters/tests/insomnia/insomnia-collection.spec.js b/packages/bruno-converters/tests/insomnia/insomnia-collection.spec.js
index 15553aa2e..588083bc8 100644
--- a/packages/bruno-converters/tests/insomnia/insomnia-collection.spec.js
+++ b/packages/bruno-converters/tests/insomnia/insomnia-collection.spec.js
@@ -4,61 +4,61 @@ import insomniaToBruno from '../../src/insomnia/insomnia-to-bruno';
describe('insomnia-collection', () => {
it('should correctly import a valid Insomnia collection file', async () => {
const brunoCollection = insomniaToBruno(insomniaCollection);
-
- expect(brunoCollection).toMatchObject(expectedOutput)
+
+ expect(brunoCollection).toMatchObject(expectedOutput);
});
});
const insomniaCollection = {
- "_type": "export",
- "__export_format": 4,
- "__export_date": "2024-05-20T10:02:44.123Z",
- "__export_source": "insomnia.desktop.app:v2021.5.2",
- "resources": [
+ _type: 'export',
+ __export_format: 4,
+ __export_date: '2024-05-20T10:02:44.123Z',
+ __export_source: 'insomnia.desktop.app:v2021.5.2',
+ resources: [
{
- "_id": "req_1",
- "_type": "request",
- "parentId": "fld_1",
- "name": "Request1",
- "method": "GET",
- "url": "https://testbench-sanity.usebruno.com/ping",
- "settingEncodeUrl": false,
- "parameters": []
+ _id: 'req_1',
+ _type: 'request',
+ parentId: 'fld_1',
+ name: 'Request1',
+ method: 'GET',
+ url: 'https://testbench-sanity.usebruno.com/ping',
+ settingEncodeUrl: false,
+ parameters: []
},
{
- "_id": "req_2",
- "_type": "request",
- "parentId": "fld_2",
- "name": "Request2",
- "method": "GET",
- "url": "https://testbench-sanity.usebruno.com/ping",
- "settingEncodeUrl": true,
- "parameters": []
+ _id: 'req_2',
+ _type: 'request',
+ parentId: 'fld_2',
+ name: 'Request2',
+ method: 'GET',
+ url: 'https://testbench-sanity.usebruno.com/ping',
+ settingEncodeUrl: true,
+ parameters: []
},
{
- "_id": "fld_1",
- "_type": "request_group",
- "parentId": "wrk_1",
- "name": "Folder1"
+ _id: 'fld_1',
+ _type: 'request_group',
+ parentId: 'wrk_1',
+ name: 'Folder1'
},
{
- "_id": "fld_2",
- "_type": "request_group",
- "parentId": "wrk_1",
- "name": "Folder2"
+ _id: 'fld_2',
+ _type: 'request_group',
+ parentId: 'wrk_1',
+ name: 'Folder2'
},
{
- "_id": "wrk_1",
- "_type": "workspace",
- "name": "Hello World Workspace Insomnia"
+ _id: 'wrk_1',
+ _type: 'workspace',
+ name: 'Hello World Workspace Insomnia'
},
{
- "_id": "env_1",
- "_type": "environment",
- "parentId": "wrk_1",
- "data": {
- "var1": "value1",
- "var2": "value2"
+ _id: 'env_1',
+ _type: 'environment',
+ parentId: 'wrk_1',
+ data: {
+ var1: 'value1',
+ var2: 'value2'
}
}
]
@@ -86,139 +86,139 @@ const expectedOutput = {
]
}
],
- "items": [
+ items: [
{
- "items": [
+ items: [
{
- "name": "Request1",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "none",
+ name: 'Request1',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'none'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "url": "https://testbench-sanity.usebruno.com/ping"
- },
- "seq": 1,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- "settings": {
- "encodeUrl": false,
+ headers: [],
+ method: 'GET',
+ params: [],
+ url: 'https://testbench-sanity.usebruno.com/ping'
},
+ seq: 1,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456',
+ settings: {
+ encodeUrl: false
+ }
},
{
- "name": "Request1",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "none",
+ name: 'Request1',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'none'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "url": "https://testbench-sanity.usebruno.com/ping"
+ headers: [],
+ method: 'GET',
+ params: [],
+ url: 'https://testbench-sanity.usebruno.com/ping'
},
- "seq": 2,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- "settings": {
- "encodeUrl": false,
- },
- },
+ seq: 2,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456',
+ settings: {
+ encodeUrl: false
+ }
+ }
],
- "name": "Folder1",
- "type": "folder",
- "uid": "mockeduuidvalue123456",
+ name: 'Folder1',
+ type: 'folder',
+ uid: 'mockeduuidvalue123456'
},
{
- "items": [
+ items: [
{
- "name": "Request2",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "none",
+ name: 'Request2',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'none'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "url": "https://testbench-sanity.usebruno.com/ping"
- },
- "seq": 1,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- "settings": {
- "encodeUrl": true,
+ headers: [],
+ method: 'GET',
+ params: [],
+ url: 'https://testbench-sanity.usebruno.com/ping'
},
+ seq: 1,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456',
+ settings: {
+ encodeUrl: true
+ }
},
{
- "name": "Request2",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "none",
+ name: 'Request2',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'none'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "url": "https://testbench-sanity.usebruno.com/ping"
+ headers: [],
+ method: 'GET',
+ params: [],
+ url: 'https://testbench-sanity.usebruno.com/ping'
},
- "seq": 2,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- "settings": {
- "encodeUrl": true,
- },
- },
+ seq: 2,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456',
+ settings: {
+ encodeUrl: true
+ }
+ }
],
- "name": "Folder2",
- "type": "folder",
- "uid": "mockeduuidvalue123456",
- },
+ name: 'Folder2',
+ type: 'folder',
+ uid: 'mockeduuidvalue123456'
+ }
],
- "name": "Hello World Workspace Insomnia",
- "uid": "mockeduuidvalue123456",
- "version": "1",
-};
\ No newline at end of file
+ name: 'Hello World Workspace Insomnia',
+ uid: 'mockeduuidvalue123456',
+ version: '1'
+};
diff --git a/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-auth.spec.js b/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-auth.spec.js
index f999cdfae..1ca62b70a 100644
--- a/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-auth.spec.js
+++ b/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-auth.spec.js
@@ -59,7 +59,7 @@ servers:
const req = collection.items[0];
expect(req.request.auth.mode).toBe('apikey');
expect(req.request.auth.apikey.placement).toBe('queryparams');
- const hasQueryParam = req.request.params.some(p => p.name === 'api_key' && p.type === 'query');
+ const hasQueryParam = req.request.params.some((p) => p.name === 'api_key' && p.type === 'query');
expect(hasQueryParam).toBe(true);
});
@@ -88,7 +88,7 @@ servers:
const { items: [req] } = openApiToBruno(spec);
expect(req.request.auth.mode).toBe('apikey');
expect(req.request.auth.apikey.placement).toBe('header');
- const apiKeyHeader = req.request.headers.find(h => h.name === 'DEMO_API_KEY');
+ const apiKeyHeader = req.request.headers.find((h) => h.name === 'DEMO_API_KEY');
expect(apiKeyHeader).toBeDefined();
expect(apiKeyHeader.value).toBe('{{apiKey}}');
});
diff --git a/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-circular-references.spec.js b/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-circular-references.spec.js
index debaedc72..feee497b4 100644
--- a/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-circular-references.spec.js
+++ b/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-circular-references.spec.js
@@ -16,233 +16,233 @@ describe('openapi-circular-references', () => {
});
const circularRefsData = {
- "components": {
- "schemas": {
- "schema_1": {
- "additionalProperties": false,
- "description": "schema_1",
- "properties": {
- "conditions": {
- "$ref": "#/components/schemas/schema_1"
+ components: {
+ schemas: {
+ schema_1: {
+ additionalProperties: false,
+ description: 'schema_1',
+ properties: {
+ conditions: {
+ $ref: '#/components/schemas/schema_1'
}
},
- "type": "object"
+ type: 'object'
},
- "schema_2": {
- "additionalProperties": false,
- "description": "schema_2",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_1",
- "items": { "$ref": "#/components/schemas/schema_1" },
- "type": "array"
+ schema_2: {
+ additionalProperties: false,
+ description: 'schema_2',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_1',
+ items: { $ref: '#/components/schemas/schema_1' },
+ type: 'array'
},
- "operation": {
- "description": "operation",
- "enum": ["ANY", "ALL"],
- "type": "string"
+ operation: {
+ description: 'operation',
+ enum: ['ANY', 'ALL'],
+ type: 'string'
}
},
- "type": "object"
+ type: 'object'
}
}
},
- "info": {
- "description": "circular reference openapi sample json spec",
- "title": "circular reference openapi sample json spec",
- "version": "0.1"
+ info: {
+ description: 'circular reference openapi sample json spec',
+ title: 'circular reference openapi sample json spec',
+ version: '0.1'
},
- "openapi": "3.0.1",
- "paths": {
- "/": {
- "post": {
- "deprecated": false,
- "description": "echo ping api",
- "operationId": "echo ping",
- "parameters": [],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/schema_1"
+ openapi: '3.0.1',
+ paths: {
+ '/': {
+ post: {
+ deprecated: false,
+ description: 'echo ping api',
+ operationId: 'echo ping',
+ parameters: [],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ $ref: '#/components/schemas/schema_1'
}
}
},
- "description": "echo ping api",
- "required": true
+ description: 'echo ping api',
+ required: true
},
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "example": "ping"
+ responses: {
+ 200: {
+ content: {
+ 'application/json': {
+ example: 'ping'
}
},
- "description": "Returned if the request is successful."
+ description: 'Returned if the request is successful.'
}
}
}
}
},
- "servers": [{ "url": "https://echo.usebruno.com" }]
+ servers: [{ url: 'https://echo.usebruno.com' }]
};
// More complex circular reference test with a longer chain
const complexCircularRefsData = {
- "components": {
- "schemas": {
- "schema_1": {
- "additionalProperties": false,
- "description": "schema_1",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_1",
- "items": { "$ref": "#/components/schemas/schema_2" },
- "type": "array"
+ components: {
+ schemas: {
+ schema_1: {
+ additionalProperties: false,
+ description: 'schema_1',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_1',
+ items: { $ref: '#/components/schemas/schema_2' },
+ type: 'array'
}
},
- "type": "object"
+ type: 'object'
},
- "schema_2": {
- "additionalProperties": false,
- "description": "schema_2",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_2",
- "items": { "$ref": "#/components/schemas/schema_3" },
- "type": "array"
+ schema_2: {
+ additionalProperties: false,
+ description: 'schema_2',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_2',
+ items: { $ref: '#/components/schemas/schema_3' },
+ type: 'array'
}
},
- "type": "object"
+ type: 'object'
},
- "schema_3": {
- "additionalProperties": false,
- "description": "schema_3",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_3",
- "items": { "$ref": "#/components/schemas/schema_4" },
- "type": "array"
+ schema_3: {
+ additionalProperties: false,
+ description: 'schema_3',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_3',
+ items: { $ref: '#/components/schemas/schema_4' },
+ type: 'array'
}
},
- "type": "object"
+ type: 'object'
},
- "schema_4": {
- "additionalProperties": false,
- "description": "schema_4",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_4",
- "items": { "$ref": "#/components/schemas/schema_5" },
- "type": "array"
+ schema_4: {
+ additionalProperties: false,
+ description: 'schema_4',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_4',
+ items: { $ref: '#/components/schemas/schema_5' },
+ type: 'array'
}
},
- "type": "object"
+ type: 'object'
},
- "schema_5": {
- "additionalProperties": false,
- "description": "schema_4",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_5",
- "items": { "$ref": "#/components/schemas/schema_1" },
- "type": "array"
+ schema_5: {
+ additionalProperties: false,
+ description: 'schema_4',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_5',
+ items: { $ref: '#/components/schemas/schema_1' },
+ type: 'array'
}
},
- "type": "object"
+ type: 'object'
},
- "schema_6": {
- "additionalProperties": false,
- "description": "schema_3",
- "properties": {
- "conditionGroup": {
- "description": "nested schema_3",
- "items": { "$ref": "#/components/schemas/schema_1" },
- "type": "array"
+ schema_6: {
+ additionalProperties: false,
+ description: 'schema_3',
+ properties: {
+ conditionGroup: {
+ description: 'nested schema_3',
+ items: { $ref: '#/components/schemas/schema_1' },
+ type: 'array'
},
- "operation": {
- "description": "operation",
- "enum": ["ANY", "ALL"],
- "type": "string"
+ operation: {
+ description: 'operation',
+ enum: ['ANY', 'ALL'],
+ type: 'string'
}
},
- "type": "object"
+ type: 'object'
}
}
},
- "info": {
- "description": "circular reference openapi sample json spec",
- "title": "circular reference openapi sample json spec",
- "version": "0.1"
+ info: {
+ description: 'circular reference openapi sample json spec',
+ title: 'circular reference openapi sample json spec',
+ version: '0.1'
},
- "openapi": "3.0.1",
- "paths": {
- "/": {
- "post": {
- "deprecated": false,
- "description": "echo ping api",
- "operationId": "echo ping",
- "parameters": [],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/schema_1"
+ openapi: '3.0.1',
+ paths: {
+ '/': {
+ post: {
+ deprecated: false,
+ description: 'echo ping api',
+ operationId: 'echo ping',
+ parameters: [],
+ requestBody: {
+ content: {
+ 'application/json': {
+ schema: {
+ $ref: '#/components/schemas/schema_1'
}
}
},
- "description": "echo ping api",
- "required": true
+ description: 'echo ping api',
+ required: true
},
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "example": "ping"
+ responses: {
+ 200: {
+ content: {
+ 'application/json': {
+ example: 'ping'
}
},
- "description": "Returned if the request is successful."
+ description: 'Returned if the request is successful.'
}
}
}
}
},
- "servers": [{ "url": "https://echo.usebruno.com" }]
+ servers: [{ url: 'https://echo.usebruno.com' }]
};
const circularRefsOutput = {
- "environments": [
+ environments: [
{
- "name": "Environment 1",
- "variables": [
+ name: 'Environment 1',
+ variables: [
{
- "enabled": true,
- "name": "baseUrl",
- "secret": false,
- "type": "text",
- "value": "https://echo.usebruno.com",
- },
- ],
- },
- ],
- "items": [
- {
- "name": "echo ping",
- "type": "http-request",
- "request": {
- "url": "{{baseUrl}}/",
- "method": "POST",
- "auth": {
- "mode": "inherit",
- },
- "headers": [],
- "params": [],
- "body": {
- "mode": "json",
+ enabled: true,
+ name: 'baseUrl',
+ secret: false,
+ type: 'text',
+ value: 'https://echo.usebruno.com'
}
- },
- },
+ ]
+ }
],
- "name": "circular reference openapi sample json spec",
- "version": "1",
-};
\ No newline at end of file
+ items: [
+ {
+ name: 'echo ping',
+ type: 'http-request',
+ request: {
+ url: '{{baseUrl}}/',
+ method: 'POST',
+ auth: {
+ mode: 'inherit'
+ },
+ headers: [],
+ params: [],
+ body: {
+ mode: 'json'
+ }
+ }
+ }
+ ],
+ name: 'circular reference openapi sample json spec',
+ version: '1'
+};
diff --git a/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-to-bruno.spec.js b/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-to-bruno.spec.js
index 9a88018bc..d2e087961 100644
--- a/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-to-bruno.spec.js
+++ b/packages/bruno-converters/tests/openapi/openapi-to-bruno/openapi-to-bruno.spec.js
@@ -10,7 +10,7 @@ describe('openapi-collection', () => {
it('should set auth mode to inherit when no security is defined in the collection', () => {
const brunoCollection = openApiToBruno(openApiCollectionString);
-
+
// The openApiCollectionString has no security defined, so auth mode should be 'inherit'
expect(brunoCollection.items[0].items[0].request.auth.mode).toBe('inherit');
});
@@ -299,61 +299,61 @@ servers:
`;
const expectedOutput = {
- "environments": [
+ environments: [
{
- "name": "Environment 1",
- "uid": "mockeduuidvalue123456",
- "variables": [
+ name: 'Environment 1',
+ uid: 'mockeduuidvalue123456',
+ variables: [
{
- "enabled": true,
- "name": "baseUrl",
- "secret": false,
- "type": "text",
- "uid": "mockeduuidvalue123456",
+ enabled: true,
+ name: 'baseUrl',
+ secret: false,
+ type: 'text',
+ uid: 'mockeduuidvalue123456',
value: 'https://echo.usebruno.com'
- },
- ],
- },
+ }
+ ]
+ }
],
- "items": [
+ items: [
{
- "items": [
+ items: [
{
- "name": "Request1 and Request2",
- "request": {
- "auth": {
- "basic": null,
- "bearer": null,
- "digest": null,
- "mode": "inherit",
+ name: 'Request1 and Request2',
+ request: {
+ auth: {
+ basic: null,
+ bearer: null,
+ digest: null,
+ mode: 'inherit'
},
- "body": {
- "formUrlEncoded": [],
- "json": null,
- "mode": "none",
- "multipartForm": [],
- "text": null,
- "xml": null,
+ body: {
+ formUrlEncoded: [],
+ json: null,
+ mode: 'none',
+ multipartForm: [],
+ text: null,
+ xml: null
},
- "headers": [],
- "method": "GET",
- "params": [],
- "script": {
- "res": null,
+ headers: [],
+ method: 'GET',
+ params: [],
+ script: {
+ res: null
},
- "url": "{{baseUrl}}/get",
+ url: '{{baseUrl}}/get'
},
- "seq": 1,
- "type": "http-request",
- "uid": "mockeduuidvalue123456",
- },
+ seq: 1,
+ type: 'http-request',
+ uid: 'mockeduuidvalue123456'
+ }
],
- "name": "Folder1",
- "type": "folder",
- "uid": "mockeduuidvalue123456",
- },
+ name: 'Folder1',
+ type: 'folder',
+ uid: 'mockeduuidvalue123456'
+ }
],
- "name": "Hello World OpenAPI",
- "uid": "mockeduuidvalue123456",
- "version": "1",
-};
\ No newline at end of file
+ name: 'Hello World OpenAPI',
+ uid: 'mockeduuidvalue123456',
+ version: '1'
+};
diff --git a/packages/bruno-converters/tests/postman/bruno-to-postman.spec.js b/packages/bruno-converters/tests/postman/bruno-to-postman.spec.js
index 417c527b2..3997e37fb 100644
--- a/packages/bruno-converters/tests/postman/bruno-to-postman.spec.js
+++ b/packages/bruno-converters/tests/postman/bruno-to-postman.spec.js
@@ -1,10 +1,10 @@
-import { sanitizeUrl, transformUrl, brunoToPostman } from "../../src/postman/bruno-to-postman";
+import { sanitizeUrl, transformUrl, brunoToPostman } from '../../src/postman/bruno-to-postman';
describe('transformUrl', () => {
it('should handle basic URL with path variables', () => {
const url = 'https://example.com/{{username}}/api/resource/:id';
const params = [
- { name: 'id', value: '123', type: 'path' },
+ { name: 'id', value: '123', type: 'path' }
];
const result = transformUrl(url, params);
@@ -16,7 +16,7 @@ describe('transformUrl', () => {
path: ['{{username}}', 'api', 'resource', ':id'],
query: [],
variable: [
- { key: 'id', value: '123' },
+ { key: 'id', value: '123' }
]
});
});
diff --git a/packages/bruno-converters/tests/postman/postman-env-to-bruno-env.spec.js b/packages/bruno-converters/tests/postman/postman-env-to-bruno-env.spec.js
index d1831b480..91421e478 100644
--- a/packages/bruno-converters/tests/postman/postman-env-to-bruno-env.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-env-to-bruno-env.spec.js
@@ -4,20 +4,20 @@ import postmanToBrunoEnvironment from '../../src/postman/postman-env-to-bruno-en
describe('postmanToBrunoEnvironment Function', () => {
it('should correctly import a valid Postman environment file', async () => {
const postmanEnvironment = {
- "id": "some-id",
- "name": "My Environment",
- "values": [
+ id: 'some-id',
+ name: 'My Environment',
+ values: [
{
- "key": "var1",
- "value": "value1",
- "enabled": true,
- "type": "text"
+ key: 'var1',
+ value: 'value1',
+ enabled: true,
+ type: 'text'
},
{
- "key": "var2",
- "value": "value2",
- "enabled": false,
- "type": "secret"
+ key: 'var2',
+ value: 'value2',
+ enabled: false,
+ type: 'secret'
}
]
};
@@ -33,7 +33,7 @@ describe('postmanToBrunoEnvironment Function', () => {
enabled: true,
secret: false,
type: 'text',
- uid: "mockeduuidvalue123456",
+ uid: 'mockeduuidvalue123456'
},
{
name: 'var2',
@@ -41,9 +41,9 @@ describe('postmanToBrunoEnvironment Function', () => {
enabled: false,
secret: true,
type: 'text',
- uid: "mockeduuidvalue123456",
- },
- ],
+ uid: 'mockeduuidvalue123456'
+ }
+ ]
};
expect(brunoEnvironment).toEqual(expectedEnvironment);
@@ -51,28 +51,28 @@ describe('postmanToBrunoEnvironment Function', () => {
it('should handle falsy values in environment variables', async () => {
const postmanEnvironment = {
- "id": "some-id",
- "name": "My Environment",
- "values": [
+ id: 'some-id',
+ name: 'My Environment',
+ values: [
{
- "enabled": true,
- "type": "text"
+ enabled: true,
+ type: 'text'
},
{
- "value": "",
- "enabled": true,
- "type": "text"
+ value: '',
+ enabled: true,
+ type: 'text'
},
{
- "key": "",
- "enabled": true,
- "type": "text"
+ key: '',
+ enabled: true,
+ type: 'text'
},
{
- "key": "",
- "value": "",
- "enabled": true,
- "type": "text"
+ key: '',
+ value: '',
+ enabled: true,
+ type: 'text'
}
]
};
@@ -88,7 +88,7 @@ describe('postmanToBrunoEnvironment Function', () => {
enabled: true,
secret: false,
type: 'text',
- uid: "mockeduuidvalue123456",
+ uid: 'mockeduuidvalue123456'
},
{
name: '',
@@ -96,7 +96,7 @@ describe('postmanToBrunoEnvironment Function', () => {
enabled: true,
secret: false,
type: 'text',
- uid: "mockeduuidvalue123456",
+ uid: 'mockeduuidvalue123456'
},
{
name: '',
@@ -104,9 +104,9 @@ describe('postmanToBrunoEnvironment Function', () => {
enabled: true,
secret: false,
type: 'text',
- uid: "mockeduuidvalue123456"
+ uid: 'mockeduuidvalue123456'
}
- ],
+ ]
};
expect(brunoEnvironment).toEqual(expectedEnvironment);
@@ -114,17 +114,17 @@ describe('postmanToBrunoEnvironment Function', () => {
it.skip('should throw Error when JSON parsing fails', async () => {
const invalidBrunoEnvironment = {
- "id": "some-id",
- "name": "My Environment",
- "values": [
+ id: 'some-id',
+ name: 'My Environment',
+ values: [
{
- "key": "var1",
- "value": "value1",
- "enabled": true,
- "type": "text"
+ key: 'var1',
+ value: 'value1',
+ enabled: true,
+ type: 'text'
}
]
- }
+ };
await expect(postmanToBrunoEnvironment(invalidBrunoEnvironment)).rejects.toThrow(Error);
await expect(postmanToBrunoEnvironment(invalidBrunoEnvironment)).rejects.toThrow(
@@ -132,19 +132,19 @@ describe('postmanToBrunoEnvironment Function', () => {
);
});
- it("should handle empty variables", async () => {
+ it('should handle empty variables', async () => {
const collectionWithEmptyVars = {
- "name": "My Environment",
- "values": []
+ name: 'My Environment',
+ values: []
};
const brunoCollection = await postmanToBrunoEnvironment(collectionWithEmptyVars);
expect(brunoCollection.variables).toEqual([]);
});
- it("should handle undefined variables", async () => {
+ it('should handle undefined variables', async () => {
const collectionWithUndefinedVars = {
- "name": "My Environment",
+ name: 'My Environment'
};
const brunoCollection = await postmanToBrunoEnvironment(collectionWithUndefinedVars);
diff --git a/packages/bruno-converters/tests/postman/postman-to-bruno/postman-to-bruno.spec.js b/packages/bruno-converters/tests/postman/postman-to-bruno/postman-to-bruno.spec.js
index 926ac706f..180174868 100644
--- a/packages/bruno-converters/tests/postman/postman-to-bruno/postman-to-bruno.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-to-bruno/postman-to-bruno.spec.js
@@ -29,49 +29,49 @@ describe('postman-collection', () => {
it('should handle falsy values in collection variables', async () => {
const collectionWithFalsyVars = {
- "info": {
- "_postman_id": "7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9",
- "name": "collection with falsy vars",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with falsy vars',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- "variable": [
+ variable: [
{
- "type": "string"
+ type: 'string'
},
{
- "key": "",
- "type": "string"
+ key: '',
+ type: 'string'
},
{
- "value": "",
- "type": "string"
+ value: '',
+ type: 'string'
},
{
- "key": "",
- "value": "",
- "type": "string"
+ key: '',
+ value: '',
+ type: 'string'
}
],
- "item": []
+ item: []
};
const brunoCollection = await postmanToBruno(collectionWithFalsyVars);
-
+
expect(brunoCollection.root.request.vars.req).toEqual([
{
- uid: "mockeduuidvalue123456",
+ uid: 'mockeduuidvalue123456',
name: '',
value: '',
enabled: true
},
{
- uid: "mockeduuidvalue123456",
+ uid: 'mockeduuidvalue123456',
name: '',
value: '',
enabled: true
},
{
- uid: "mockeduuidvalue123456",
+ uid: 'mockeduuidvalue123456',
name: '',
value: '',
enabled: true
@@ -79,15 +79,15 @@ describe('postman-collection', () => {
]);
});
- it("should handle empty variables", async () => {
+ it('should handle empty variables', async () => {
const collectionWithEmptyVars = {
- "info": {
- "_postman_id": "7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9",
- "name": "collection with falsy vars",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with falsy vars',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- "variable": [],
- "item": []
+ variable: [],
+ item: []
};
const brunoCollection = await postmanToBruno(collectionWithEmptyVars);
@@ -178,28 +178,28 @@ describe('postman-collection', () => {
it('should handle collection with auth object having undefined type', async () => {
const collectionWithUndefinedAuthType = {
- 'info': {
- '_postman_id': '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
- 'name': 'collection with undefined auth type',
- 'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with undefined auth type',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- 'auth': {
- 'basic': [
+ auth: {
+ basic: [
{ key: 'username', value: 'testuser', type: 'string' },
{ key: 'password', value: 'testpass', type: 'string' }
]
},
- 'item': [
+ item: [
{
- 'name': 'request',
- 'request': {
- 'method': 'GET',
- 'header': [],
- 'url': {
- 'raw': 'https://api.example.com/test',
- 'protocol': 'https',
- 'host': ['api', 'example', 'com'],
- 'path': ['test']
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://api.example.com/test',
+ protocol: 'https',
+ host: ['api', 'example', 'com'],
+ path: ['test']
}
}
}
@@ -207,7 +207,7 @@ describe('postman-collection', () => {
};
const brunoCollection = await postmanToBruno(collectionWithUndefinedAuthType);
-
+
// Collection level auth should default to 'none'
expect(brunoCollection.root.request.auth).toEqual({
mode: 'none',
@@ -233,28 +233,28 @@ describe('postman-collection', () => {
it('should handle collection with auth object having null type', async () => {
const collectionWithNullAuthType = {
- 'info': {
- '_postman_id': '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
- 'name': 'collection with null auth type',
- 'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with null auth type',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- 'auth': {
- 'type': null,
- 'bearer': {
- 'token': 'test-token'
+ auth: {
+ type: null,
+ bearer: {
+ token: 'test-token'
}
},
- 'item': [
+ item: [
{
- 'name': 'request',
- 'request': {
- 'method': 'GET',
- 'header': [],
- 'url': {
- 'raw': 'https://api.example.com/test',
- 'protocol': 'https',
- 'host': ['api', 'example', 'com'],
- 'path': ['test']
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://api.example.com/test',
+ protocol: 'https',
+ host: ['api', 'example', 'com'],
+ path: ['test']
}
}
}
@@ -262,7 +262,7 @@ describe('postman-collection', () => {
};
const brunoCollection = await postmanToBruno(collectionWithNullAuthType);
-
+
// Collection level auth should default to 'none'
expect(brunoCollection.root.request.auth).toEqual({
mode: 'none',
@@ -277,29 +277,29 @@ describe('postman-collection', () => {
it('should handle collection with auth object having unexpected type value', async () => {
const collectionWithUnexpectedAuthType = {
- 'info': {
- '_postman_id': '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
- 'name': 'collection with unexpected auth type',
- 'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with unexpected auth type',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- 'auth': {
- 'type': 'unexpected_auth_type',
- 'basic': [
+ auth: {
+ type: 'unexpected_auth_type',
+ basic: [
{ key: 'username', value: 'testuser', type: 'string' },
{ key: 'password', value: 'testpass', type: 'string' }
]
},
- 'item': [
+ item: [
{
- 'name': 'request',
- 'request': {
- 'method': 'GET',
- 'header': [],
- 'url': {
- 'raw': 'https://api.example.com/test',
- 'protocol': 'https',
- 'host': ['api', 'example', 'com'],
- 'path': ['test']
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://api.example.com/test',
+ protocol: 'https',
+ host: ['api', 'example', 'com'],
+ path: ['test']
}
}
}
@@ -307,7 +307,7 @@ describe('postman-collection', () => {
};
const brunoCollection = await postmanToBruno(collectionWithUnexpectedAuthType);
-
+
// Collection level auth should default to 'none'
expect(brunoCollection.root.request.auth).toEqual({
mode: 'none',
@@ -333,25 +333,25 @@ describe('postman-collection', () => {
it('should handle request with auth object having undefined type', async () => {
const collectionWithRequestUndefinedAuthType = {
- 'info': {
- '_postman_id': '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
- 'name': 'collection with request undefined auth type',
- 'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with request undefined auth type',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- 'item': [
+ item: [
{
- 'name': 'request',
- 'request': {
- 'method': 'GET',
- 'header': [],
- 'url': {
- 'raw': 'https://api.example.com/test',
- 'protocol': 'https',
- 'host': ['api', 'example', 'com'],
- 'path': ['test']
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://api.example.com/test',
+ protocol: 'https',
+ host: ['api', 'example', 'com'],
+ path: ['test']
},
- 'auth': {
- 'basic': [
+ auth: {
+ basic: [
{ key: 'username', value: 'testuser', type: 'string' },
{ key: 'password', value: 'testpass', type: 'string' }
]
@@ -373,7 +373,7 @@ describe('postman-collection', () => {
oauth2: null,
digest: null
});
-
+
// Request auth should default to 'none'
expect(brunoCollection.items[0].request.auth).toEqual({
mode: 'none',
@@ -388,31 +388,31 @@ describe('postman-collection', () => {
it('should handle folder with auth object having unexpected type', async () => {
const collectionWithFolderUnexpectedAuthType = {
- 'info': {
- '_postman_id': '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
- 'name': 'collection with folder unexpected auth type',
- 'schema': 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'collection with folder unexpected auth type',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
},
- 'item': [
+ item: [
{
- 'name': 'folder',
- 'auth': {
- 'type': 'unexpected_folder_auth_type',
- 'bearer': {
- 'token': 'folder-token'
+ name: 'folder',
+ auth: {
+ type: 'unexpected_folder_auth_type',
+ bearer: {
+ token: 'folder-token'
}
},
- 'item': [
+ item: [
{
- 'name': 'request',
- 'request': {
- 'method': 'GET',
- 'header': [],
- 'url': {
- 'raw': 'https://api.example.com/test',
- 'protocol': 'https',
- 'host': ['api', 'example', 'com'],
- 'path': ['test']
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://api.example.com/test',
+ protocol: 'https',
+ host: ['api', 'example', 'com'],
+ path: ['test']
}
}
}
@@ -422,7 +422,7 @@ describe('postman-collection', () => {
};
const brunoCollection = await postmanToBruno(collectionWithFolderUnexpectedAuthType);
-
+
// Folder auth should default to 'none'
expect(brunoCollection.items[0].root.request.auth).toEqual({
mode: 'none',
@@ -453,52 +453,52 @@ describe('postman-collection', () => {
// โโโ request (GET)
const postmanCollection = {
- "info": {
- "_postman_id": "7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9",
- "name": "simple collection",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
- "_exporter_id": "21992467",
- "_collection_link": "https://random-user-007.postman.co/workspace/testing~7523f559-3d5f-4c30-8315-3cb3c3ff98b7/collection/21992467-7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9?action=share&source=collection_link&creator=007"
- },
- "item": [
- {
- "name": "folder",
- "item": [
- {
- "name": "request",
- "request": {
- "method": "GET",
- "header": [],
- "url": {
- "raw": "https://usebruno.com",
- "protocol": "https",
- "host": [
- "usebruno",
- "com"
- ]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "request",
- "request": {
- "method": "GET",
- "header": [],
- "url": {
- "raw": "https://usebruno.com",
- "protocol": "https",
- "host": [
- "usebruno",
- "com"
- ]
- }
- },
- "response": []
- }
- ]
+ info: {
+ _postman_id: '7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9',
+ name: 'simple collection',
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
+ _exporter_id: '21992467',
+ _collection_link: 'https://random-user-007.postman.co/workspace/testing~7523f559-3d5f-4c30-8315-3cb3c3ff98b7/collection/21992467-7f91bbd8-cb97-41ac-8d0b-e1fcd8bb4ce9?action=share&source=collection_link&creator=007'
+ },
+ item: [
+ {
+ name: 'folder',
+ item: [
+ {
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://usebruno.com',
+ protocol: 'https',
+ host: [
+ 'usebruno',
+ 'com'
+ ]
+ }
+ },
+ response: []
+ }
+ ]
+ },
+ {
+ name: 'request',
+ request: {
+ method: 'GET',
+ header: [],
+ url: {
+ raw: 'https://usebruno.com',
+ protocol: 'https',
+ host: [
+ 'usebruno',
+ 'com'
+ ]
+ }
+ },
+ response: []
+ }
+ ]
};
// Simple Collection (bruno)
@@ -507,120 +507,120 @@ const postmanCollection = {
// โโโ request (GET)
const expectedOutput = {
- "name": "simple collection",
- "uid": "mockeduuidvalue123456",
- "version": "1",
- "items": [
- {
- "uid": "mockeduuidvalue123456",
- "name": "folder",
- "type": "folder",
- "seq": 1,
- "items": [
+ name: 'simple collection',
+ uid: 'mockeduuidvalue123456',
+ version: '1',
+ items: [
+ {
+ uid: 'mockeduuidvalue123456',
+ name: 'folder',
+ type: 'folder',
+ seq: 1,
+ items: [
{
- "uid": "mockeduuidvalue123456",
- "name": "request",
- "type": "http-request",
- "seq": 1,
- "request": {
- "url": "https://usebruno.com",
- "method": "GET",
- "auth": {
- "mode": "inherit",
- "basic": null,
- "bearer": null,
- "awsv4": null,
- "apikey": null,
- "oauth2": null,
- "digest": null
+ uid: 'mockeduuidvalue123456',
+ name: 'request',
+ type: 'http-request',
+ seq: 1,
+ request: {
+ url: 'https://usebruno.com',
+ method: 'GET',
+ auth: {
+ mode: 'inherit',
+ basic: null,
+ bearer: null,
+ awsv4: null,
+ apikey: null,
+ oauth2: null,
+ digest: null
},
- "headers": [],
- "params": [],
- "body": {
- "mode": "none",
- "json": null,
- "text": null,
- "xml": null,
- "formUrlEncoded": [],
- "multipartForm": []
+ headers: [],
+ params: [],
+ body: {
+ mode: 'none',
+ json: null,
+ text: null,
+ xml: null,
+ formUrlEncoded: [],
+ multipartForm: []
},
- "docs": ""
+ docs: ''
}
}
],
- "root": {
- "docs": "",
- "meta": {
- "name": "folder"
+ root: {
+ docs: '',
+ meta: {
+ name: 'folder'
},
- "request": {
- "auth": {
- "mode": "inherit",
- "basic": null,
- "bearer": null,
- "awsv4": null,
- "apikey": null,
- "oauth2": null,
- "digest": null
- },
- "headers": [],
- "script": {},
- "tests": "",
- "vars": {}
+ request: {
+ auth: {
+ mode: 'inherit',
+ basic: null,
+ bearer: null,
+ awsv4: null,
+ apikey: null,
+ oauth2: null,
+ digest: null
+ },
+ headers: [],
+ script: {},
+ tests: '',
+ vars: {}
}
}
- },
- {
- "uid": "mockeduuidvalue123456",
- "name": "request",
- "type": "http-request",
- "seq": 2,
- "request": {
- "url": "https://usebruno.com",
- "method": "GET",
- "auth": {
- "mode": "inherit",
- "basic": null,
- "bearer": null,
- "awsv4": null,
- "apikey": null,
- "oauth2": null,
- "digest": null
+ },
+ {
+ uid: 'mockeduuidvalue123456',
+ name: 'request',
+ type: 'http-request',
+ seq: 2,
+ request: {
+ url: 'https://usebruno.com',
+ method: 'GET',
+ auth: {
+ mode: 'inherit',
+ basic: null,
+ bearer: null,
+ awsv4: null,
+ apikey: null,
+ oauth2: null,
+ digest: null
},
- "headers": [],
- "params": [],
- "body": {
- "mode": "none",
- "json": null,
- "text": null,
- "xml": null,
- "formUrlEncoded": [],
- "multipartForm": []
+ headers: [],
+ params: [],
+ body: {
+ mode: 'none',
+ json: null,
+ text: null,
+ xml: null,
+ formUrlEncoded: [],
+ multipartForm: []
},
- "docs": ""
+ docs: ''
+ }
+ }
+ ],
+ environments: [],
+ root: {
+ docs: '',
+ meta: {
+ name: 'simple collection'
+ },
+ request: {
+ auth: {
+ mode: 'none',
+ basic: null,
+ bearer: null,
+ awsv4: null,
+ apikey: null,
+ oauth2: null,
+ digest: null
},
- }
- ],
- "environments": [],
- "root": {
- "docs": "",
- "meta": {
- "name": "simple collection"
- },
- "request": {
- "auth": {
- "mode": "none",
- "basic": null,
- "bearer": null,
- "awsv4": null,
- "apikey": null,
- "oauth2": null,
- "digest": null
- },
- "headers": [],
- "script": {},
- "tests": "",
- "vars": {}
- }
- }
- };
\ No newline at end of file
+ headers: [],
+ script: {},
+ tests: '',
+ vars: {}
+ }
+ }
+};
diff --git a/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-request.spec.js b/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-request.spec.js
index dd3e11331..333cedcbc 100644
--- a/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-request.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-request.spec.js
@@ -1,4 +1,4 @@
-const { default: postmanTranslation } = require("../../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../../src/postman/postman-translations');
describe('postmanTranslations - request commands', () => {
test('should handle request commands', () => {
@@ -42,4 +42,4 @@ describe('postmanTranslations - request commands', () => {
`;
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-response.spec.js b/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-response.spec.js
index 590825f13..ccfd2ee13 100644
--- a/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-response.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-to-bruno/postman-translations/postman-response.spec.js
@@ -1,4 +1,4 @@
-const { default: postmanTranslation } = require("../../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../../src/postman/postman-translations');
describe('postmanTranslations - response commands', () => {
test('should handle response commands', () => {
diff --git a/packages/bruno-converters/tests/postman/postman-to-bruno/process-auth.spec.js b/packages/bruno-converters/tests/postman/postman-to-bruno/process-auth.spec.js
index a6d90ed1b..ba05a4c18 100644
--- a/packages/bruno-converters/tests/postman/postman-to-bruno/process-auth.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-to-bruno/process-auth.spec.js
@@ -1,5 +1,4 @@
-const { processAuth } = require("../../../src/postman/postman-to-bruno");
-
+const { processAuth } = require('../../../src/postman/postman-to-bruno');
describe('processAuth', () => {
let requestObject;
@@ -466,7 +465,7 @@ describe('processAuth', () => {
it('should handle auth object with null type', () => {
const auth = {
- type: null,
+ type: null
};
processAuth(auth, requestObject);
expect(requestObject.auth.mode).toBe('none');
@@ -498,7 +497,7 @@ describe('processAuth', () => {
it('should handle auth object with boolean type value', () => {
const auth = {
- type: "unknown_auth_type",
+ type: 'unknown_auth_type',
unknown_auth_type: {
accessKey: 'test-access-key',
secretKey: 'test-secret-key'
diff --git a/packages/bruno-converters/tests/postman/postman-to-bruno/request-auth.spec.js b/packages/bruno-converters/tests/postman/postman-to-bruno/request-auth.spec.js
index 09cc712c9..ee37ba871 100644
--- a/packages/bruno-converters/tests/postman/postman-to-bruno/request-auth.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-to-bruno/request-auth.spec.js
@@ -2,8 +2,6 @@ import { describe, it, expect } from '@jest/globals';
import postmanToBruno from '../../../src/postman/postman-to-bruno';
describe('Request Authentication', () => {
-
-
it('should handle basic auth at request level', async () => {
const postmanCollection = {
info: {
@@ -391,5 +389,4 @@ describe('Request Authentication', () => {
basic: null, bearer: null, awsv4: null, apikey: null, oauth2: null, digest: null
});
});
-
});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/postman-comments.spec.js b/packages/bruno-converters/tests/postman/postman-translations/postman-comments.spec.js
index ba3f29d37..7cb5df0e5 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/postman-comments.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/postman-comments.spec.js
@@ -1,4 +1,4 @@
-const { default: postmanTranslation } = require("../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../src/postman/postman-translations');
describe('postmanTranslations - comment handling', () => {
test('should not translate non-pm commands', () => {
@@ -16,15 +16,15 @@ describe('postmanTranslations - comment handling', () => {
});
test('should comment non-translated pm commands', () => {
- const inputScript = "pm.test('random test', () => pm.globals.clear());";
- const expectedOutput = "// test('random test', () => pm.globals.clear());";
+ const inputScript = 'pm.test(\'random test\', () => pm.globals.clear());';
+ const expectedOutput = '// test(\'random test\', () => pm.globals.clear());';
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
test('should handle multiple pm commands on the same line', () => {
- const inputScript = "pm.environment.get('key'); pm.environment.set('key', 'value');";
- const expectedOutput = "bru.getEnvVar('key'); bru.setEnvVar('key', 'value');";
- expect(postmanTranslation(inputScript)).toBe(expectedOutput);
+ const inputScript = 'pm.environment.get(\'key\'); pm.environment.set(\'key\', \'value\');';
+ const expectedOutput = 'bru.getEnvVar(\'key\'); bru.setEnvVar(\'key\', \'value\');';
+ expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
test('should handle comments and other JavaScript code', () => {
@@ -50,4 +50,4 @@ describe('postmanTranslations - comment handling', () => {
`;
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js b/packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js
index e4fe0ee32..9b32883a8 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/postman-cookie-conversions.spec.js
@@ -1,15 +1,15 @@
-const { default: postmanTranslation } = require("../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../src/postman/postman-translations');
describe('postmanTranslations - cookie API conversions', () => {
test('should convert pm.cookies.jar().get to bru.cookies.jar().getCookie', () => {
const inputScript = `pm.cookies.jar().get('https://example.com', 'sessionId', (err, cookie) => {
console.log(cookie);
});`;
-
+
const expectedOutput = `bru.cookies.jar().getCookie('https://example.com', 'sessionId', (err, cookie) => {
console.log(cookie);
});`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -17,11 +17,11 @@ describe('postmanTranslations - cookie API conversions', () => {
const inputScript = `pm.cookies.jar().getAll('https://example.com', (err, cookies) => {
console.log(cookies);
});`;
-
+
const expectedOutput = `bru.cookies.jar().getCookies('https://example.com', (err, cookies) => {
console.log(cookies);
});`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -29,11 +29,11 @@ describe('postmanTranslations - cookie API conversions', () => {
const inputScript = `pm.cookies.jar().set('https://example.com', 'sessionId', 'abc123', (err) => {
if (err) console.error(err);
});`;
-
+
const expectedOutput = `bru.cookies.jar().setCookie('https://example.com', 'sessionId', 'abc123', (err) => {
if (err) console.error(err);
});`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -41,11 +41,11 @@ describe('postmanTranslations - cookie API conversions', () => {
const inputScript = `pm.cookies.jar().unset('https://example.com', 'sessionId', (err) => {
if (err) console.error(err);
});`;
-
+
const expectedOutput = `bru.cookies.jar().deleteCookie('https://example.com', 'sessionId', (err) => {
if (err) console.error(err);
});`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -53,11 +53,11 @@ describe('postmanTranslations - cookie API conversions', () => {
const inputScript = `pm.cookies.jar().clear('https://example.com', (err) => {
if (err) console.error(err);
});`;
-
+
const expectedOutput = `bru.cookies.jar().deleteCookies('https://example.com', (err) => {
if (err) console.error(err);
});`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -71,7 +71,7 @@ describe('postmanTranslations - cookie API conversions', () => {
pm.cookies.jar().unset('https://api.example.com', 'temp');
pm.cookies.jar().clear('https://api.example.com');
`;
-
+
const expectedOutput = `
bru.cookies.jar().setCookie('https://api.example.com', 'auth', 'token123');
const cookie = bru.cookies.jar().getCookie('https://api.example.com', 'auth');
@@ -81,7 +81,7 @@ describe('postmanTranslations - cookie API conversions', () => {
bru.cookies.jar().deleteCookie('https://api.example.com', 'temp');
bru.cookies.jar().deleteCookies('https://api.example.com');
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -91,13 +91,13 @@ describe('postmanTranslations - cookie API conversions', () => {
jar.set('https://example.com', 'user', 'john');
const userCookie = jar.get('https://example.com', 'user');
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.setCookie('https://example.com', 'user', 'john');
const userCookie = jar.getCookie('https://example.com', 'user');
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -112,7 +112,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.getCookie('https://api.example.com', 'authToken', (error, cookie) => {
@@ -123,7 +123,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -138,7 +138,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.getCookies('https://api.example.com', (error, cookies) => {
@@ -149,7 +149,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -166,7 +166,7 @@ describe('postmanTranslations - cookie API conversions', () => {
if (error) console.error(error);
});
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.setCookie('https://api.example.com', {
@@ -179,7 +179,7 @@ describe('postmanTranslations - cookie API conversions', () => {
if (error) console.error(error);
});
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -194,7 +194,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.deleteCookie('https://api.example.com', 'tempCookie', (error) => {
@@ -205,7 +205,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -220,7 +220,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.deleteCookies('https://api.example.com', (error) => {
@@ -231,7 +231,7 @@ describe('postmanTranslations - cookie API conversions', () => {
}
});
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -261,7 +261,7 @@ describe('postmanTranslations - cookie API conversions', () => {
cookieJar.unset('https://example.com', 'temp');
cookieJar.clear('https://example.com');
`;
-
+
const expectedOutput = `
const cookieJar = bru.cookies.jar();
@@ -287,7 +287,7 @@ describe('postmanTranslations - cookie API conversions', () => {
cookieJar.deleteCookie('https://example.com', 'temp');
cookieJar.deleteCookies('https://example.com');
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
@@ -302,7 +302,7 @@ describe('postmanTranslations - cookie API conversions', () => {
console.log(cookies);
});
`;
-
+
const expectedOutput = `
const jar = bru.cookies.jar();
jar.getCookie('https://api.com', 'session');
@@ -313,7 +313,7 @@ describe('postmanTranslations - cookie API conversions', () => {
console.log(cookies);
});
`;
-
+
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/postman-edge-cases.spec.js b/packages/bruno-converters/tests/postman/postman-translations/postman-edge-cases.spec.js
index d304026ea..a70226102 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/postman-edge-cases.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/postman-edge-cases.spec.js
@@ -1,4 +1,4 @@
-const { default: postmanTranslation } = require("../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../src/postman/postman-translations');
describe('postmanTranslations - edge cases', () => {
test('should handle nested commands and edge cases', () => {
@@ -44,4 +44,4 @@ describe('postmanTranslations - edge cases', () => {
`;
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/postman-test-commands.spec.js b/packages/bruno-converters/tests/postman/postman-translations/postman-test-commands.spec.js
index 7c75b518e..5091b32f5 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/postman-test-commands.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/postman-test-commands.spec.js
@@ -1,4 +1,4 @@
-const { default: postmanTranslation } = require("../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../src/postman/postman-translations');
describe('postmanTranslations - test commands', () => {
test('should handle test commands', () => {
@@ -20,4 +20,4 @@ describe('postmanTranslations - test commands', () => {
`;
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/postman-variables.spec.js b/packages/bruno-converters/tests/postman/postman-translations/postman-variables.spec.js
index 70801f295..3ce310908 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/postman-variables.spec.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/postman-variables.spec.js
@@ -1,4 +1,4 @@
-const { default: postmanTranslation } = require("../../../src/postman/postman-translations");
+const { default: postmanTranslation } = require('../../../src/postman/postman-translations');
describe('postmanTranslations - variables commands', () => {
test('should translate variable commands correctly', () => {
@@ -22,4 +22,4 @@ describe('postmanTranslations - variables commands', () => {
`;
expect(postmanTranslation(inputScript)).toBe(expectedOutput);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/combined.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/combined.test.js
index 4916a10c0..86eb58eed 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/combined.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/combined.test.js
@@ -1,85 +1,85 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Combined API Features Translation', () => {
- // Basic translation test
- it('should translate code', () => {
- const code = 'console.log("Hello, world!");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(code);
- });
+ // Basic translation test
+ it('should translate code', () => {
+ const code = 'console.log("Hello, world!");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(code);
+ });
- // Preserving comments
- it('should preserve comments', () => {
- const code = '// This is a comment';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('// This is a comment');
- });
+ // Preserving comments
+ it('should preserve comments', () => {
+ const code = '// This is a comment';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('// This is a comment');
+ });
- it('should preserve comments inside functions', () => {
- const code = `
+ it('should preserve comments inside functions', () => {
+ const code = `
function getUserDetails() {
// Get user details from API
const response = pm.response.json();
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
function getUserDetails() {
// Get user details from API
const response = res.getBody();
}
`);
- });
+ });
- it('should preserve comments inside if statements', () => {
- const code = `
+ it('should preserve comments inside if statements', () => {
+ const code = `
if (pm.response.code === 200) {
// Success
console.log("Success");
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
if (res.getStatus() === 200) {
// Success
console.log("Success");
}
`);
- });
+ });
- it('should preserve multiline comments', () => {
- const code = `
+ it('should preserve multiline comments', () => {
+ const code = `
/*
This is a multiline comment
*/
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
/*
This is a multiline comment
*/
`);
- });
+ });
- it('should preserve comments inside for loops', () => {
- const code = `
+ it('should preserve comments inside for loops', () => {
+ const code = `
for (let i = 0; i < 10; i++) {
// Loop iteration
console.log(pm.response.json()[i]);
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
for (let i = 0; i < 10; i++) {
// Loop iteration
console.log(res.getBody()[i]);
}
`);
- });
+ });
- // Multiple transformations in the same code block
- it('should handle multiple translations in the same code block', () => {
- const code = `
+ // Multiple transformations in the same code block
+ it('should handle multiple translations in the same code block', () => {
+ const code = `
const token = pm.environment.get("authToken");
pm.test("Auth flow works", function() {
const response = pm.response.json();
@@ -88,120 +88,118 @@ describe('Combined API Features Translation', () => {
pm.collectionVariables.set("sessionId", response.session.id);
});
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).not.toContain('pm.test("Auth flow works", function() {');
- expect(translatedCode).not.toContain('pm.expect(response.authenticated).to.be.true;');
- expect(translatedCode).not.toContain('pm.environment.set("userId", response.user.id);');
- expect(translatedCode).not.toContain('pm.collectionVariables.set("sessionId", response.session.id);');
- expect(translatedCode).toContain('const token = bru.getEnvVar("authToken");');
- expect(translatedCode).toContain('test("Auth flow works", function() {');
- expect(translatedCode).toContain('const response = res.getBody();');
- expect(translatedCode).toContain('expect(response.authenticated).to.be.true;');
- expect(translatedCode).toContain('bru.setEnvVar("userId", response.user.id);');
- expect(translatedCode).toContain('bru.setVar("sessionId", response.session.id);');
- });
+ expect(translatedCode).not.toContain('pm.test("Auth flow works", function() {');
+ expect(translatedCode).not.toContain('pm.expect(response.authenticated).to.be.true;');
+ expect(translatedCode).not.toContain('pm.environment.set("userId", response.user.id);');
+ expect(translatedCode).not.toContain('pm.collectionVariables.set("sessionId", response.session.id);');
+ expect(translatedCode).toContain('const token = bru.getEnvVar("authToken");');
+ expect(translatedCode).toContain('test("Auth flow works", function() {');
+ expect(translatedCode).toContain('const response = res.getBody();');
+ expect(translatedCode).toContain('expect(response.authenticated).to.be.true;');
+ expect(translatedCode).toContain('bru.setEnvVar("userId", response.user.id);');
+ expect(translatedCode).toContain('bru.setVar("sessionId", response.session.id);');
+ });
- // Nested expressions
- it('should handle nested Postman API calls', () => {
- const code = 'pm.environment.set("computed", pm.variables.get("base") + "-suffix");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setEnvVar("computed", bru.getVar("base") + "-suffix");');
- });
+ // Nested expressions
+ it('should handle nested Postman API calls', () => {
+ const code = 'pm.environment.set("computed", pm.variables.get("base") + "-suffix");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setEnvVar("computed", bru.getVar("base") + "-suffix");');
+ });
- it('should handle more complex nested expressions', () => {
- const code = 'pm.collectionVariables.set("fullPath", pm.environment.get("baseUrl") + pm.variables.get("endpoint"));';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setVar("fullPath", bru.getEnvVar("baseUrl") + bru.getVar("endpoint"));');
- });
+ it('should handle more complex nested expressions', () => {
+ const code = 'pm.collectionVariables.set("fullPath", pm.environment.get("baseUrl") + pm.variables.get("endpoint"));';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setVar("fullPath", bru.getEnvVar("baseUrl") + bru.getVar("endpoint"));');
+ });
- // Unrelated code
- it('should leave unrelated code untouched', () => {
- const code = `
+ // Unrelated code
+ it('should leave unrelated code untouched', () => {
+ const code = `
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(code);
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(code);
+ });
- it('should handle Postman API calls within JavaScript methods', () => {
- const code = `
+ it('should handle Postman API calls within JavaScript methods', () => {
+ const code = `
const helpers = {
getAuthHeader: function() {
return "Bearer " + pm.environment.get("token");
}
};
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('return "Bearer " + bru.getEnvVar("token");');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('return "Bearer " + bru.getEnvVar("token");');
+ });
-
- it('should handle aliases with object destructuring', () => {
- const code = `
+ it('should handle aliases with object destructuring', () => {
+ const code = `
const { environment, variables } = pm;
environment.set("token", "abc123");
variables.get("userId");
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ expect(translatedCode).toBe(`
bru.setEnvVar("token", "abc123");
bru.getVar("userId");
`);
- });
+ });
- // Code context tests
- it('should translate pm commands inside functions', () => {
- const code = `
+ // Code context tests
+ it('should translate pm commands inside functions', () => {
+ const code = `
function getAuthHeader() {
return "Bearer " + pm.environment.get("token");
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
function getAuthHeader() {
return "Bearer " + bru.getEnvVar("token");
}
`);
- });
+ });
- it('should translate pm commands inside if statements', () => {
- const code = `
+ it('should translate pm commands inside if statements', () => {
+ const code = `
if (pm.response.code === 200) {
console.log("Success");
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
if (res.getStatus() === 200) {
console.log("Success");
}
`);
- });
+ });
-
- it('should translate pm commands inside if statements', () => {
- const code = `
+ it('should translate pm commands inside if statements', () => {
+ const code = `
const json = pm.response.json();
if (json.code === 200) {
console.log("Success");
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const json = res.getBody();
if (json.code === 200) {
console.log("Success");
}
`);
- });
+ });
- it('should translate pm commands inside else statements', () => {
- const code = `
+ it('should translate pm commands inside else statements', () => {
+ const code = `
if (pm.response.code === 200) {
console.log("Success");
pm.response.to.have.status(200);
@@ -210,8 +208,8 @@ describe('Combined API Features Translation', () => {
expect(res.getStatus()).to.equal(400);
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
if (res.getStatus() === 200) {
console.log("Success");
expect(res.getStatus()).to.equal(200);
@@ -220,40 +218,40 @@ describe('Combined API Features Translation', () => {
expect(res.getStatus()).to.equal(400);
}
`);
- });
+ });
- it('should translate pm commands inside for loops', () => {
- const code = `
+ it('should translate pm commands inside for loops', () => {
+ const code = `
for (let i = 0; i < pm.response.json().length; i++) {
console.log(pm.response.json()[i]);
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
for (let i = 0; i < res.getBody().length; i++) {
console.log(res.getBody()[i]);
}
`);
- });
+ });
- it('should translate pm commands inside while loops', () => {
- const code = `
+ it('should translate pm commands inside while loops', () => {
+ const code = `
while (pm.response.code === 200) {
console.log("Success");
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
while (res.getStatus() === 200) {
console.log("Success");
}
`);
- });
+ });
- it('should translate pm commands inside switch statements', () => {
- const code = `
+ it('should translate pm commands inside switch statements', () => {
+ const code = `
switch (pm.response.code) {
case 200:
console.log("Success");
@@ -261,18 +259,18 @@ describe('Combined API Features Translation', () => {
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
switch (res.getStatus()) {
case 200:
console.log("Success");
break;
}
`);
- });
+ });
- it('should translate pm commands inside try catch statements', () => {
- const code = `
+ it('should translate pm commands inside try catch statements', () => {
+ const code = `
try {
pm.response.to.have.status(200);
} catch (error) {
@@ -281,8 +279,8 @@ describe('Combined API Features Translation', () => {
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
try {
expect(res.getStatus()).to.equal(200);
} catch (error) {
@@ -290,10 +288,10 @@ describe('Combined API Features Translation', () => {
expect(res.getStatus()).to.equal(400);
}
`);
- });
+ });
- it('should translate aliases within if statements block', () => {
- const code = `
+ it('should translate aliases within if statements block', () => {
+ const code = `
const env = pm.environment;
const vars = pm.variables;
const collVars = pm.collectionVariables;
@@ -314,8 +312,8 @@ describe('Combined API Features Translation', () => {
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
function processResponse() {
if(res.getStatus() === 200) {
console.log("Success");
@@ -328,10 +326,10 @@ describe('Combined API Features Translation', () => {
}
}
`);
- });
+ });
- it('should handle pm aliases inside functions', () => {
- const code = `
+ it('should handle pm aliases inside functions', () => {
+ const code = `
const tempRes = pm.response;
const tempTest = pm.test;
const tempExpect = pm.expect;
@@ -347,9 +345,9 @@ describe('Combined API Features Translation', () => {
}
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ expect(translatedCode).toBe(`
function processResponse() {
test("Status code is 200", function() { expect(res.getStatus()).to.equal(200); });
bru.setEnvVar("userId", res.getBody().userId);
@@ -357,86 +355,86 @@ describe('Combined API Features Translation', () => {
bru.setVar("sessionId", res.getBody().sessionId);
}
`);
- });
+ });
- it('should nested pm commands', () => {
- const code = `
+ it('should nested pm commands', () => {
+ const code = `
pm.collectionVariables.get(pm.environment.get('key'))
pm.test("Status code is 200", function() {
pm.response.to.have.status(200);
});
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
bru.getVar(bru.getEnvVar('key'))
test("Status code is 200", function() {
expect(res.getStatus()).to.equal(200);
});
`);
- });
+ });
- it('should handle pm objects in template literals', () => {
- const code = `
+ it('should handle pm objects in template literals', () => {
+ const code = `
const baseUrl = pm.environment.get("baseUrl");
const endpoint = pm.variables.get("endpoint");
const url = \`\${baseUrl}/api/\${endpoint}\`;
console.log(\`Response status: \${pm.response.code}\`);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const baseUrl = bru.getEnvVar("baseUrl");');
- expect(translatedCode).toContain('const endpoint = bru.getVar("endpoint");');
- expect(translatedCode).toContain('const url = `${baseUrl}/api/${endpoint}`;');
- expect(translatedCode).toContain('console.log(`Response status: ${res.getStatus()}`);');
- });
+ const translatedCode = translateCode(code);
- it('should handle pm objects in arrow functions', () => {
- const code = `
+ expect(translatedCode).toContain('const baseUrl = bru.getEnvVar("baseUrl");');
+ expect(translatedCode).toContain('const endpoint = bru.getVar("endpoint");');
+ expect(translatedCode).toContain('const url = `${baseUrl}/api/${endpoint}`;');
+ expect(translatedCode).toContain('console.log(`Response status: ${res.getStatus()}`);');
+ });
+
+ it('should handle pm objects in arrow functions', () => {
+ const code = `
const getAuthHeader = () => "Bearer " + pm.environment.get("token");
const processItems = items => items.forEach(item => {
pm.variables.set(item.key, item.value);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const getAuthHeader = () => "Bearer " + bru.getEnvVar("token");');
- expect(translatedCode).toContain('const processItems = items => items.forEach(item => {');
- expect(translatedCode).toContain('bru.setVar(item.key, item.value);');
- });
+ const translatedCode = translateCode(code);
- it('test', () => {
- const code = `
+ expect(translatedCode).toContain('const getAuthHeader = () => "Bearer " + bru.getEnvVar("token");');
+ expect(translatedCode).toContain('const processItems = items => items.forEach(item => {');
+ expect(translatedCode).toContain('bru.setVar(item.key, item.value);');
+ });
+
+ it('test', () => {
+ const code = `
const globals = pm.globals;
const key = globals.get("key");
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const key = bru.getGlobalEnvVar("key");
`);
- })
+ });
- it('should handle pm.response.to.have.body integrated with other assertions', () => {
- const code = `
+ it('should handle pm.response.to.have.body integrated with other assertions', () => {
+ const code = `
pm.test("Response validation", function() {
pm.response.to.have.status(200);
pm.response.to.have.body({"success": true});
pm.response.to.have.header("Content-Type", "application/json");
});
`;
- const translatedCode = translateCode(code);
-
- const expectedOutput = `
+ const translatedCode = translateCode(code);
+
+ const expectedOutput = `
test("Response validation", function() {
expect(res.getStatus()).to.equal(200);
expect(res.getBody()).to.equal({"success": true});
expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");
});
`;
- expect(translatedCode).toBe(expectedOutput);
- });
+ expect(translatedCode).toBe(expectedOutput);
+ });
- it('should handle pm.response.to.have.body with dynamic content', () => {
- const code = `
+ it('should handle pm.response.to.have.body with dynamic content', () => {
+ const code = `
const expectedResponse = {
id: pm.environment.get("userId"),
token: pm.variables.get("authToken"),
@@ -447,9 +445,9 @@ describe('Combined API Features Translation', () => {
pm.response.to.have.body(expectedResponse);
});
`;
- const translatedCode = translateCode(code);
-
- const expectedOutput = `
+ const translatedCode = translateCode(code);
+
+ const expectedOutput = `
const expectedResponse = {
id: bru.getEnvVar("userId"),
token: bru.getVar("authToken"),
@@ -459,12 +457,12 @@ describe('Combined API Features Translation', () => {
test("Dynamic response validation", function() {
expect(res.getBody()).to.equal(expectedResponse);
});
- `
- expect(translatedCode).toBe(expectedOutput);
- });
+ `;
+ expect(translatedCode).toBe(expectedOutput);
+ });
- it('should handle pm.response.to.have.body in control structures', () => {
- const code = `
+ it('should handle pm.response.to.have.body in control structures', () => {
+ const code = `
const jsonData = pm.response.json();
if (jsonData.status === "success") {
@@ -476,9 +474,9 @@ describe('Combined API Features Translation', () => {
pm.expect(jsonData.error).to.exist;
}
`;
- const translatedCode = translateCode(code);
-
- const expectedOutput = `
+ const translatedCode = translateCode(code);
+
+ const expectedOutput = `
const jsonData = res.getBody();
if (jsonData.status === "success") {
@@ -490,6 +488,6 @@ describe('Combined API Features Translation', () => {
expect(jsonData.error).to.exist;
}
`;
- expect(translatedCode).toBe(expectedOutput);
- });
-});
\ No newline at end of file
+ expect(translatedCode).toBe(expectedOutput);
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/environment.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/environment.test.js
index c3461f6de..47c46ce19 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/environment.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/environment.test.js
@@ -1,71 +1,71 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Environment Variable Translation', () => {
- it('should translate pm.environment.get', () => {
- const code = 'pm.environment.get("test");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.getEnvVar("test");');
- });
+ it('should translate pm.environment.get', () => {
+ const code = 'pm.environment.get("test");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.getEnvVar("test");');
+ });
- it('should translate pm.environment.set', () => {
- const code = 'pm.environment.set("test", "value");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setEnvVar("test", "value");');
- });
+ it('should translate pm.environment.set', () => {
+ const code = 'pm.environment.set("test", "value");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setEnvVar("test", "value");');
+ });
- it('should translate pm.environment.has', () => {
- const code = 'pm.environment.has("test")';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.getEnvVar("test") !== undefined && bru.getEnvVar("test") !== null');
- });
+ it('should translate pm.environment.has', () => {
+ const code = 'pm.environment.has("test")';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.getEnvVar("test") !== undefined && bru.getEnvVar("test") !== null');
+ });
- it('should translate pm.environment.unset', () => {
- const code = 'pm.environment.unset("test");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.deleteEnvVar("test");');
- });
+ it('should translate pm.environment.unset', () => {
+ const code = 'pm.environment.unset("test");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.deleteEnvVar("test");');
+ });
- it('should translate pm.environment.name', () => {
- const code = 'pm.environment.name;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.getEnvName();');
- });
+ it('should translate pm.environment.name', () => {
+ const code = 'pm.environment.name;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.getEnvName();');
+ });
- it('should handle nested Postman API calls with environment', () => {
- const code = 'pm.environment.set("computed", pm.variables.get("base") + "-suffix");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setEnvVar("computed", bru.getVar("base") + "-suffix");');
- });
+ it('should handle nested Postman API calls with environment', () => {
+ const code = 'pm.environment.set("computed", pm.variables.get("base") + "-suffix");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setEnvVar("computed", bru.getVar("base") + "-suffix");');
+ });
- it('should handle JSON operations with environment variables', () => {
- const code = 'pm.environment.set("user", JSON.stringify({ id: 123, name: "John" }));';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setEnvVar("user", JSON.stringify({ id: 123, name: "John" }));');
- });
+ it('should handle JSON operations with environment variables', () => {
+ const code = 'pm.environment.set("user", JSON.stringify({ id: 123, name: "John" }));';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setEnvVar("user", JSON.stringify({ id: 123, name: "John" }));');
+ });
- it('should handle JSON.parse with environment variables', () => {
- const code = 'const userData = JSON.parse(pm.environment.get("user"));';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const userData = JSON.parse(bru.getEnvVar("user"));');
- });
+ it('should handle JSON.parse with environment variables', () => {
+ const code = 'const userData = JSON.parse(pm.environment.get("user"));';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const userData = JSON.parse(bru.getEnvVar("user"));');
+ });
- it('should translate pm.environment.name with different access patterns', () => {
- const code = `
+ it('should translate pm.environment.name with different access patterns', () => {
+ const code = `
const envName1 = pm.environment.name;
const env = pm.environment;
const envName2 = env.name;
console.log(pm.environment.name);
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const envName1 = bru.getEnvName();
const envName2 = bru.getEnvName();
console.log(bru.getEnvName());
`);
- });
+ });
- it('should handle environment aliases', () => {
- const code = `
+ it('should handle environment aliases', () => {
+ const code = `
const env = pm.environment;
const name = env.name;
const has = env.has("test");
@@ -73,37 +73,37 @@ describe('Environment Variable Translation', () => {
const get = env.get("test");
const unset = env.unset("test");
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const name = bru.getEnvName();
const has = bru.getEnvVar("test") !== undefined && bru.getEnvVar("test") !== null;
const set = bru.setEnvVar("test", "value");
const get = bru.getEnvVar("test");
const unset = bru.deleteEnvVar("test");
`);
- });
+ });
- // Legacy API (postman.) tests related to environment
- it('should translate postman.setEnvironmentVariable', () => {
- const code = 'postman.setEnvironmentVariable("apiKey", "abc123");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setEnvVar("apiKey", "abc123");');
- });
+ // Legacy API (postman.) tests related to environment
+ it('should translate postman.setEnvironmentVariable', () => {
+ const code = 'postman.setEnvironmentVariable("apiKey", "abc123");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setEnvVar("apiKey", "abc123");');
+ });
- it('should translate postman.getEnvironmentVariable', () => {
- const code = 'const baseUrl = postman.getEnvironmentVariable("baseUrl");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const baseUrl = bru.getEnvVar("baseUrl");');
- });
+ it('should translate postman.getEnvironmentVariable', () => {
+ const code = 'const baseUrl = postman.getEnvironmentVariable("baseUrl");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const baseUrl = bru.getEnvVar("baseUrl");');
+ });
- it('should translate postman.clearEnvironmentVariable', () => {
- const code = 'postman.clearEnvironmentVariable("tempToken");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.deleteEnvVar("tempToken");');
- });
+ it('should translate postman.clearEnvironmentVariable', () => {
+ const code = 'postman.clearEnvironmentVariable("tempToken");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.deleteEnvVar("tempToken");');
+ });
- it('should handle all environment variable methods together', () => {
- const code = `
+ it('should handle all environment variable methods together', () => {
+ const code = `
// All environment variable methods
const envName = pm.environment.name;
const hasToken = pm.environment.has("token");
@@ -112,29 +112,29 @@ describe('Environment Variable Translation', () => {
console.log(\`Environment: \${envName}, Has token: \${hasToken}, Token: \${token}\`);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const envName = bru.getEnvName();');
- expect(translatedCode).toContain('const hasToken = bru.getEnvVar("token") !== undefined && bru.getEnvVar("token") !== null;');
- expect(translatedCode).toContain('const token = bru.getEnvVar("token");');
- expect(translatedCode).toContain('bru.setEnvVar("timestamp", new Date().toISOString());');
- });
+ const translatedCode = translateCode(code);
- // Additional robust tests for environment variables
- it('should handle environment variables with computed property names', () => {
- const code = `
+ expect(translatedCode).toContain('const envName = bru.getEnvName();');
+ expect(translatedCode).toContain('const hasToken = bru.getEnvVar("token") !== undefined && bru.getEnvVar("token") !== null;');
+ expect(translatedCode).toContain('const token = bru.getEnvVar("token");');
+ expect(translatedCode).toContain('bru.setEnvVar("timestamp", new Date().toISOString());');
+ });
+
+ // Additional robust tests for environment variables
+ it('should handle environment variables with computed property names', () => {
+ const code = `
const prefix = "api";
const suffix = "Key";
pm.environment.set(prefix + "_" + suffix, "abc123");
const computedValue = pm.environment.get(prefix + "_" + suffix);
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('bru.setEnvVar(prefix + "_" + suffix, "abc123");');
- expect(translatedCode).toContain('const computedValue = bru.getEnvVar(prefix + "_" + suffix);');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('bru.setEnvVar(prefix + "_" + suffix, "abc123");');
+ expect(translatedCode).toContain('const computedValue = bru.getEnvVar(prefix + "_" + suffix);');
+ });
- it('should handle environment variables in complex object structures', () => {
- const code = `
+ it('should handle environment variables in complex object structures', () => {
+ const code = `
const config = {
baseUrl: pm.environment.get("apiUrl"),
headers: {
@@ -145,16 +145,16 @@ describe('Environment Variable Translation', () => {
validate: pm.environment.has("validateResponses")
};
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('baseUrl: bru.getEnvVar("apiUrl"),');
- expect(translatedCode).toContain('"Authorization": "Bearer " + bru.getEnvVar("token"),');
- expect(translatedCode).toContain('"X-Api-Key": bru.getEnvVar("apiKey") || "default-key"');
- expect(translatedCode).toContain('timeout: parseInt(bru.getEnvVar("timeout") || "5000"),');
- expect(translatedCode).toContain('validate: bru.getEnvVar("validateResponses") !== undefined && bru.getEnvVar("validateResponses") !== null');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('baseUrl: bru.getEnvVar("apiUrl"),');
+ expect(translatedCode).toContain('"Authorization": "Bearer " + bru.getEnvVar("token"),');
+ expect(translatedCode).toContain('"X-Api-Key": bru.getEnvVar("apiKey") || "default-key"');
+ expect(translatedCode).toContain('timeout: parseInt(bru.getEnvVar("timeout") || "5000"),');
+ expect(translatedCode).toContain('validate: bru.getEnvVar("validateResponses") !== undefined && bru.getEnvVar("validateResponses") !== null');
+ });
- it('should handle environment variables in conditionals correctly', () => {
- const code = `
+ it('should handle environment variables in conditionals correctly', () => {
+ const code = `
if (pm.environment.has("apiKey")) {
if (pm.environment.get("apiKey").length > 0) {
console.log("Valid API key exists");
@@ -165,29 +165,29 @@ describe('Environment Variable Translation', () => {
console.log("No API key defined");
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('if (bru.getEnvVar("apiKey") !== undefined && bru.getEnvVar("apiKey") !== null) {');
- expect(translatedCode).toContain('if (bru.getEnvVar("apiKey").length > 0) {');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('if (bru.getEnvVar("apiKey") !== undefined && bru.getEnvVar("apiKey") !== null) {');
+ expect(translatedCode).toContain('if (bru.getEnvVar("apiKey").length > 0) {');
+ });
- it('should handle multiple levels of environment variable aliasing', () => {
- const code = `
+ it('should handle multiple levels of environment variable aliasing', () => {
+ const code = `
const env = pm.environment;
env.set("key", "value");
const value = env.get("key");
const exists = env.has("key");
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
bru.setEnvVar("key", "value");
const value = bru.getEnvVar("key");
const exists = bru.getEnvVar("key") !== undefined && bru.getEnvVar("key") !== null;
`);
- });
+ });
- it('should handle environment variables with dynamic values', () => {
- const code = `
+ it('should handle environment variables with dynamic values', () => {
+ const code = `
// Generate a timestamp for this request
const timestamp = new Date().toISOString();
pm.environment.set("requestTimestamp", timestamp);
@@ -201,14 +201,14 @@ describe('Environment Variable Translation', () => {
expiryTime.setMinutes(expiryTime.getMinutes() + 30);
pm.environment.set("tokenExpiry", expiryTime.getTime());
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('bru.setEnvVar("requestTimestamp", timestamp);');
- expect(translatedCode).toContain('bru.setEnvVar("requestId", uniqueId);');
- expect(translatedCode).toContain('bru.setEnvVar("tokenExpiry", expiryTime.getTime());');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('bru.setEnvVar("requestTimestamp", timestamp);');
+ expect(translatedCode).toContain('bru.setEnvVar("requestId", uniqueId);');
+ expect(translatedCode).toContain('bru.setEnvVar("tokenExpiry", expiryTime.getTime());');
+ });
- it('should handle environment variables in try-catch blocks', () => {
- const code = `
+ it('should handle environment variables in try-catch blocks', () => {
+ const code = `
try {
const configStr = pm.environment.get("config");
const config = JSON.parse(configStr);
@@ -218,13 +218,13 @@ describe('Environment Variable Translation', () => {
pm.environment.set("configError", error.message);
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('const configStr = bru.getEnvVar("config");');
- expect(translatedCode).toContain('bru.setEnvVar("configError", error.message);');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('const configStr = bru.getEnvVar("config");');
+ expect(translatedCode).toContain('bru.setEnvVar("configError", error.message);');
+ });
- it('should handle legacy environment and pm.setEnvironmentVariable together', () => {
- const code = `
+ it('should handle legacy environment and pm.setEnvironmentVariable together', () => {
+ const code = `
// Legacy style
postman.setEnvironmentVariable("legacyKey", "legacyValue");
@@ -234,9 +234,9 @@ describe('Environment Variable Translation', () => {
// Another legacy form
pm.setEnvironmentVariable("thirdKey", "thirdValue");
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('bru.setEnvVar("legacyKey", "legacyValue");');
- expect(translatedCode).toContain('const value = bru.getEnvVar("anotherKey");');
- expect(translatedCode).toContain('bru.setEnvVar("thirdKey", "thirdValue");');
- });
-});
\ No newline at end of file
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('bru.setEnvVar("legacyKey", "legacyValue");');
+ expect(translatedCode).toContain('const value = bru.getEnvVar("anotherKey");');
+ expect(translatedCode).toContain('bru.setEnvVar("thirdKey", "thirdValue");');
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/exec-flow.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/exec-flow.test.js
index 053e99685..838b6a838 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/exec-flow.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/exec-flow.test.js
@@ -1,33 +1,33 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Execution Flow Translation', () => {
- // Request flow control
- it('should translate pm.setNextRequest', () => {
- const code = 'pm.setNextRequest("Get User Details");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setNextRequest("Get User Details");');
- });
+ // Request flow control
+ it('should translate pm.setNextRequest', () => {
+ const code = 'pm.setNextRequest("Get User Details");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.setNextRequest("Get User Details");');
+ });
- it('should translate pm.execution.skipRequest', () => {
- const code = 'if (condition) pm.execution.skipRequest();';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('if (condition) bru.runner.skipRequest();');
- });
+ it('should translate pm.execution.skipRequest', () => {
+ const code = 'if (condition) pm.execution.skipRequest();';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('if (condition) bru.runner.skipRequest();');
+ });
- it('should translate pm.execution.setNextRequest(null)', () => {
- const code = 'pm.execution.setNextRequest(null);';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.runner.stopExecution();');
- });
+ it('should translate pm.execution.setNextRequest(null)', () => {
+ const code = 'pm.execution.setNextRequest(null);';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.runner.stopExecution();');
+ });
- it('should translate pm.execution.setNextRequest("null")', () => {
- const code = 'pm.execution.setNextRequest("null");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.runner.stopExecution();');
- });
+ it('should translate pm.execution.setNextRequest("null")', () => {
+ const code = 'pm.execution.setNextRequest("null");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('bru.runner.stopExecution();');
+ });
- it('should handle pm.execution.setNextRequest with non-null parameters', () => {
- const code = `
+ it('should handle pm.execution.setNextRequest with non-null parameters', () => {
+ const code = `
// Continue normal flow
pm.execution.setNextRequest("Get user details");
@@ -35,14 +35,14 @@ describe('Execution Flow Translation', () => {
const nextReq = "Update profile";
pm.execution.setNextRequest(nextReq);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('bru.runner.setNextRequest("Get user details");');
- expect(translatedCode).toContain('bru.runner.setNextRequest(nextReq);');
- });
+ const translatedCode = translateCode(code);
- it('should handle all execution control methods together', () => {
- const code = `
+ expect(translatedCode).toContain('bru.runner.setNextRequest("Get user details");');
+ expect(translatedCode).toContain('bru.runner.setNextRequest(nextReq);');
+ });
+
+ it('should handle all execution control methods together', () => {
+ const code = `
// All execution control methods
if (pm.response.code === 401) {
pm.execution.skipRequest();
@@ -52,13 +52,13 @@ describe('Execution Flow Translation', () => {
pm.setNextRequest("Get User Details");
}
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('if (res.getStatus() === 401) {');
- expect(translatedCode).toContain('bru.runner.skipRequest();');
- expect(translatedCode).toContain('} else if (res.getStatus() === 500) {');
- expect(translatedCode).toContain('bru.runner.stopExecution();');
- expect(translatedCode).toContain('} else {');
- expect(translatedCode).toContain('bru.setNextRequest("Get User Details");');
- });
-});
\ No newline at end of file
+ const translatedCode = translateCode(code);
+
+ expect(translatedCode).toContain('if (res.getStatus() === 401) {');
+ expect(translatedCode).toContain('bru.runner.skipRequest();');
+ expect(translatedCode).toContain('} else if (res.getStatus() === 500) {');
+ expect(translatedCode).toContain('bru.runner.stopExecution();');
+ expect(translatedCode).toContain('} else {');
+ expect(translatedCode).toContain('bru.setNextRequest("Get User Details");');
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-global-apis.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-global-apis.test.js
index 489bf734a..549611acd 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-global-apis.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-global-apis.test.js
@@ -6,12 +6,12 @@ describe('Legacy Postman API Translation', () => {
const input = `
const data = JSON.parse(responseBody);
`;
-
+
const result = translateCode(input);
const expected = `
const data = res.getBody();
`;
-
+
expect(result).toEqual(expected);
});
@@ -20,9 +20,9 @@ describe('Legacy Postman API Translation', () => {
console.log(responseHeaders);
const headers = responseHeaders;
`;
-
+
const result = translateCode(input);
-
+
expect(result).toContain('res.getHeaders()');
expect(result).not.toContain('responseHeaders');
});
@@ -32,9 +32,9 @@ describe('Legacy Postman API Translation', () => {
console.log(responseTime);
const time = responseTime;
`;
-
+
const result = translateCode(input);
-
+
expect(result).toContain('res.getResponseTime()');
expect(result).not.toContain('responseTime');
});
@@ -44,9 +44,9 @@ describe('Legacy Postman API Translation', () => {
const data = JSON.parse(responseBody);
console.log(data);
`;
-
+
const result = translateCode(input);
-
+
expect(result).toContain('res.getBody()');
expect(result).not.toContain('JSON.parse(responseBody)');
expect(result).not.toContain('responseBody');
@@ -61,7 +61,7 @@ describe('Legacy Postman API Translation', () => {
const expected = `
console.log(res.getBody());
`;
-
+
expect(result).toContain(expected);
});
@@ -73,9 +73,9 @@ describe('Legacy Postman API Translation', () => {
console.log(data, headers, time);
`;
-
+
const result = translateCode(input);
-
+
expect(result).toContain('res.getBody()');
expect(result).toContain('res.getHeaders()');
expect(result).toContain('res.getResponseTime()');
@@ -91,13 +91,13 @@ describe('Legacy Postman API Translation', () => {
const responseBody = pm.response.json();
console.log(responseBody);
`;
-
+
const result = translateCode(input);
const expected = `
const responseBody = res.getBody();
console.log(responseBody);
`;
-
+
// pm.response.json() should be transformed to res.getBody() (Postman API transformation)
expect(result).toEqual(expected);
});
@@ -107,13 +107,13 @@ describe('Legacy Postman API Translation', () => {
const responseHeaders = pm.response.headers;
console.log(responseHeaders);
`;
-
+
const result = translateCode(input);
const expected = `
const responseHeaders = res.getHeaders();
console.log(responseHeaders);
`;
-
+
expect(result).toEqual(expected);
});
@@ -122,13 +122,13 @@ describe('Legacy Postman API Translation', () => {
const responseTime = pm.response.responseTime;
console.log(responseTime);
`;
-
+
const result = translateCode(input);
const expected = `
const responseTime = res.getResponseTime();
console.log(responseTime);
`;
-
+
expect(result).toEqual(expected);
});
@@ -138,14 +138,14 @@ describe('Legacy Postman API Translation', () => {
const data = JSON.parse(responseBody);
console.log(data);
`;
-
+
const result = translateCode(input);
const expected = `
const responseBody = res.getBody();
const data = JSON.parse(responseBody);
console.log(data);
`;
-
+
expect(result).toEqual(expected);
});
});
@@ -158,7 +158,7 @@ describe('Legacy Postman API Translation', () => {
console.log(responseHeaders);
console.log(responseTime);
`;
-
+
const result = translateCode(input);
const expected = `
const responseBody = res.getBody();
@@ -166,9 +166,8 @@ describe('Legacy Postman API Translation', () => {
console.log(res.getHeaders());
console.log(res.getResponseTime());
`;
-
- expect(result).toEqual(expected);
+ expect(result).toEqual(expected);
});
test('should translate JSON.parse(responseBody) only when no conflict exists', () => {
@@ -177,14 +176,14 @@ describe('Legacy Postman API Translation', () => {
const data = JSON.parse(responseBody);
console.log(responseHeaders);
`;
-
+
const result = translateCode(input);
const expected = `
const responseHeaders = res.getHeaders();
const data = res.getBody();
console.log(responseHeaders);
`;
-
+
expect(result).toEqual(expected);
});
});
@@ -197,7 +196,7 @@ describe('Legacy Postman API Translation', () => {
console.log(responseHeaders);
}
`;
-
+
const result = translateCode(input);
const expected = `
function test(responseBody) {
@@ -205,7 +204,7 @@ describe('Legacy Postman API Translation', () => {
console.log(res.getHeaders());
}
`;
-
+
expect(result).toEqual(expected);
});
@@ -217,9 +216,9 @@ describe('Legacy Postman API Translation', () => {
};
console.log(responseTime);
`;
-
+
const result = translateCode(input);
-
+
const expected = `
const config = {
responseBody: 'custom',
@@ -227,7 +226,7 @@ describe('Legacy Postman API Translation', () => {
};
console.log(res.getResponseTime());
`;
-
+
expect(result).toEqual(expected);
});
@@ -237,15 +236,15 @@ describe('Legacy Postman API Translation', () => {
responseHeaders = 'new headers';
console.log(responseTime);
`;
-
+
const result = translateCode(input);
-
+
const expected = `
responseBody = 'new value';
responseHeaders = 'new headers';
console.log(res.getResponseTime());
`;
-
+
expect(result).toEqual(expected);
});
@@ -261,9 +260,9 @@ describe('Legacy Postman API Translation', () => {
console.log(responseHeaders);
}
`;
-
+
const result = translateCode(input);
-
+
const expected = `
const responseBody = res.getBody();
const data = JSON.parse(responseBody);
@@ -275,7 +274,7 @@ describe('Legacy Postman API Translation', () => {
console.log(res.getHeaders());
}
`;
-
+
expect(result).toEqual(expected);
});
});
@@ -286,13 +285,13 @@ describe('Legacy Postman API Translation', () => {
const data = { name: 'test' };
console.log(data.name);
`;
-
+
const result = translateCode(input);
const expected = `
const data = { name: 'test' };
console.log(data.name);
`;
-
+
expect(result).toEqual(expected);
});
});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-tests-syntax.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-tests-syntax.test.js
index 34c6f32a6..f10203bbe 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-tests-syntax.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/legacy-tests-syntax.test.js
@@ -1,156 +1,156 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Legacy Tests[] Syntax Translation', () => {
- it('should handle tests[] commands', () => {
- const code = `
+ it('should handle tests[] commands', () => {
+ const code = `
tests["Status code is 200"] = pm.response.code === 200;`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Status code is 200", function() {
expect(Boolean(res.getStatus() === 200)).to.be.true;
});`);
- });
+ });
- it('should handle tests[] with complex expressions', () => {
- const code = `
+ it('should handle tests[] with complex expressions', () => {
+ const code = `
tests["Response has valid data"] = pm.response.json().data && pm.response.json().data.length > 0;`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Response has valid data", function() {
expect(Boolean(res.getBody().data && res.getBody().data.length > 0)).to.be.true;
});`);
- });
+ });
- it('should handle tests[] with string equality', () => {
- const code = `
+ it('should handle tests[] with string equality', () => {
+ const code = `
tests["Content-Type is application/json"] = pm.response.headers.get("Content-Type") === "application/json";`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Content-Type is application/json", function() {
expect(Boolean(res.getHeader("Content-Type") === "application/json")).to.be.true;
});`);
- });
+ });
- it('should handle tests[] with function calls', () => {
- const code = `
+ it('should handle tests[] with function calls', () => {
+ const code = `
tests["Response time is acceptable"] = pm.response.responseTime < 500;`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Response time is acceptable", function() {
expect(Boolean(res.getResponseTime() < 500)).to.be.true;
});`);
- });
+ });
- it('should handle tests[] with variable references', () => {
- const code = `
+ it('should handle tests[] with variable references', () => {
+ const code = `
const expectedStatus = 201;
tests["Status code is correct"] = pm.response.code === expectedStatus;`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const expectedStatus = 201;
test("Status code is correct", function() {
expect(Boolean(res.getStatus() === expectedStatus)).to.be.true;
});`);
- });
+ });
- it('should handle multiple tests[] statements', () => {
- const code = `
+ it('should handle multiple tests[] statements', () => {
+ const code = `
tests["Status code is 200"] = pm.response.code === 200;
tests["Response has data"] = pm.response.json().hasOwnProperty("data");`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Status code is 200", function() {
expect(Boolean(res.getStatus() === 200)).to.be.true;
});
test("Response has data", function() {
expect(Boolean(res.getBody().hasOwnProperty("data"))).to.be.true;
});`);
- });
+ });
- it('should handle tests[] with special characters in name', () => {
- const code = `
+ it('should handle tests[] with special characters in name', () => {
+ const code = `
tests["Special characters: !@#$%^&*()"] = true;`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Special characters: !@#$%^&*()", function() {
expect(Boolean(true)).to.be.true;
});`);
- });
+ });
- it('should handle tests[] with pm.environment variables', () => {
- const code = `
+ it('should handle tests[] with pm.environment variables', () => {
+ const code = `
tests["Response matches environment variable"] = pm.response.json().id === pm.environment.get("expectedId");`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Response matches environment variable", function() {
expect(Boolean(res.getBody().id === bru.getEnvVar("expectedId"))).to.be.true;
});`);
- });
+ });
- it('should handle nested pm objects in tests[] assignments', () => {
- const code = `
+ it('should handle nested pm objects in tests[] assignments', () => {
+ const code = `
tests["Authentication header is present"] = pm.request.headers.has("Authorization");
tests["Data count is correct"] = pm.response.json().items.length === pm.variables.get("expectedCount");
`;
- const translatedCode = translateCode(code);
-
- // The exact translation might vary depending on implementation details,
- // but we can check for key transformations
- expect(translatedCode).toContain('test("Authentication header is present"');
- expect(translatedCode).toContain('test("Data count is correct"');
- expect(translatedCode).toContain('res.getBody().items.length === bru.getVar("expectedCount")');
- });
+ const translatedCode = translateCode(code);
- // Additional robust tests for legacy tests[] syntax
- it('should handle tests[] with complex boolean expressions', () => {
- const code = `
+ // The exact translation might vary depending on implementation details,
+ // but we can check for key transformations
+ expect(translatedCode).toContain('test("Authentication header is present"');
+ expect(translatedCode).toContain('test("Data count is correct"');
+ expect(translatedCode).toContain('res.getBody().items.length === bru.getVar("expectedCount")');
+ });
+
+ // Additional robust tests for legacy tests[] syntax
+ it('should handle tests[] with complex boolean expressions', () => {
+ const code = `
tests["Complex validation"] = (pm.response.code >= 200 && pm.response.code < 300) ||
(pm.response.json().success === true && pm.response.json().data !== null);`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Complex validation", function() {');
- expect(translatedCode).toContain('expect(Boolean((res.getStatus() >= 200 && res.getStatus() < 300) ||');
- expect(translatedCode).toContain('(res.getBody().success === true && res.getBody().data !== null))).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle tests[] with array methods', () => {
- const code = `
+ expect(translatedCode).toContain('test("Complex validation", function() {');
+ expect(translatedCode).toContain('expect(Boolean((res.getStatus() >= 200 && res.getStatus() < 300) ||');
+ expect(translatedCode).toContain('(res.getBody().success === true && res.getBody().data !== null))).to.be.true;');
+ });
+
+ it('should handle tests[] with array methods', () => {
+ const code = `
tests["All items have an ID"] = pm.response.json().items.every(item => item.hasOwnProperty('id'));
tests["Has premium item"] = pm.response.json().items.some(item => item.type === 'premium');`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("All items have an ID", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getBody().items.every(item => item.hasOwnProperty(\'id\')))).to.be.true;');
- expect(translatedCode).toContain('test("Has premium item", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getBody().items.some(item => item.type === \'premium\'))).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle tests[] with template literals in the name', () => {
- const code = `
+ expect(translatedCode).toContain('test("All items have an ID", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getBody().items.every(item => item.hasOwnProperty(\'id\')))).to.be.true;');
+ expect(translatedCode).toContain('test("Has premium item", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getBody().items.some(item => item.type === \'premium\'))).to.be.true;');
+ });
+
+ it('should handle tests[] with template literals in the name', () => {
+ const code = `
const endpoint = "users";
tests[\`Endpoint \${endpoint} returns valid response\`] = pm.response.code === 200;`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const endpoint = "users";');
- expect(translatedCode).toContain('test(`Endpoint ${endpoint} returns valid response`, function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getStatus() === 200)).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle tests[] with deep property access', () => {
- const code = `
+ expect(translatedCode).toContain('const endpoint = "users";');
+ expect(translatedCode).toContain('test(`Endpoint ${endpoint} returns valid response`, function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getStatus() === 200)).to.be.true;');
+ });
+
+ it('should handle tests[] with deep property access', () => {
+ const code = `
tests["User has admin role"] = pm.response.json().user &&
pm.response.json().user.roles &&
pm.response.json().user.roles.includes('admin');`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("User has admin role", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getBody().user &&');
- expect(translatedCode).toContain('res.getBody().user.roles &&');
- expect(translatedCode).toContain('res.getBody().user.roles.includes(\'admin\'))).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle tests[] with JSON schema validation patterns', () => {
- const code = `
+ expect(translatedCode).toContain('test("User has admin role", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getBody().user &&');
+ expect(translatedCode).toContain('res.getBody().user.roles &&');
+ expect(translatedCode).toContain('res.getBody().user.roles.includes(\'admin\'))).to.be.true;');
+ });
+
+ it('should handle tests[] with JSON schema validation patterns', () => {
+ const code = `
const schema = {
type: "object",
required: ["id", "name"],
@@ -166,20 +166,20 @@ describe('Legacy Tests[] Syntax Translation', () => {
tests["Has required fields"] = data.hasOwnProperty('id') && data.hasOwnProperty('name');
tests["ID is string"] = typeof data.id === 'string';
tests["Name is string"] = typeof data.name === 'string';`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const schema = {');
- expect(translatedCode).toContain('type: "object",');
- expect(translatedCode).toContain('required: ["id", "name"],');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('test("Has required fields", function() {');
- expect(translatedCode).toContain('expect(Boolean(data.hasOwnProperty(\'id\') && data.hasOwnProperty(\'name\'))).to.be.true;');
- expect(translatedCode).toContain('test("ID is string", function() {');
- expect(translatedCode).toContain('expect(Boolean(typeof data.id === \'string\')).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle tests[] within conditional blocks', () => {
- const code = `
+ expect(translatedCode).toContain('const schema = {');
+ expect(translatedCode).toContain('type: "object",');
+ expect(translatedCode).toContain('required: ["id", "name"],');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('test("Has required fields", function() {');
+ expect(translatedCode).toContain('expect(Boolean(data.hasOwnProperty(\'id\') && data.hasOwnProperty(\'name\'))).to.be.true;');
+ expect(translatedCode).toContain('test("ID is string", function() {');
+ expect(translatedCode).toContain('expect(Boolean(typeof data.id === \'string\')).to.be.true;');
+ });
+
+ it('should handle tests[] within conditional blocks', () => {
+ const code = `
const data = pm.response.json();
if (pm.response.code === 200) {
@@ -191,22 +191,22 @@ describe('Legacy Tests[] Syntax Translation', () => {
} else {
tests["Error response has message"] = data.hasOwnProperty('message');
}`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('if (res.getStatus() === 200) {');
- expect(translatedCode).toContain('test("Success response has data", function() {');
- expect(translatedCode).toContain('expect(Boolean(data.hasOwnProperty(\'items\'))).to.be.true;');
- expect(translatedCode).toContain('if (data.items.length > 0) {');
- expect(translatedCode).toContain('test("First item has ID", function() {');
- expect(translatedCode).toContain('expect(Boolean(data.items[0].hasOwnProperty(\'id\'))).to.be.true;');
- expect(translatedCode).toContain('} else {');
- expect(translatedCode).toContain('test("Error response has message", function() {');
- expect(translatedCode).toContain('expect(Boolean(data.hasOwnProperty(\'message\'))).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle tests[] with combination of legacy and modern styles', () => {
- const code = `
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('if (res.getStatus() === 200) {');
+ expect(translatedCode).toContain('test("Success response has data", function() {');
+ expect(translatedCode).toContain('expect(Boolean(data.hasOwnProperty(\'items\'))).to.be.true;');
+ expect(translatedCode).toContain('if (data.items.length > 0) {');
+ expect(translatedCode).toContain('test("First item has ID", function() {');
+ expect(translatedCode).toContain('expect(Boolean(data.items[0].hasOwnProperty(\'id\'))).to.be.true;');
+ expect(translatedCode).toContain('} else {');
+ expect(translatedCode).toContain('test("Error response has message", function() {');
+ expect(translatedCode).toContain('expect(Boolean(data.hasOwnProperty(\'message\'))).to.be.true;');
+ });
+
+ it('should handle tests[] with combination of legacy and modern styles', () => {
+ const code = `
// Legacy style
tests["Status code is 200"] = pm.response.code === 200;
@@ -219,20 +219,20 @@ describe('Legacy Tests[] Syntax Translation', () => {
// Mix by using tests[] inside pm.test
tests["All items have price"] = json.items.every(item => item.hasOwnProperty('price'));
});`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Status code is 200", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getStatus() === 200)).to.be.true;');
- expect(translatedCode).toContain('test("Response has valid data", function() {');
- expect(translatedCode).toContain('const json = res.getBody();');
- expect(translatedCode).toContain('expect(json).to.be.an(\'object\');');
- expect(translatedCode).toContain('expect(json.items).to.be.an(\'array\');');
- expect(translatedCode).toContain('test("All items have price", function() {');
- expect(translatedCode).toContain('expect(Boolean(json.items.every(item => item.hasOwnProperty(\'price\')))).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle complex real-world tests[] example', () => {
- const code = `
+ expect(translatedCode).toContain('test("Status code is 200", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getStatus() === 200)).to.be.true;');
+ expect(translatedCode).toContain('test("Response has valid data", function() {');
+ expect(translatedCode).toContain('const json = res.getBody();');
+ expect(translatedCode).toContain('expect(json).to.be.an(\'object\');');
+ expect(translatedCode).toContain('expect(json.items).to.be.an(\'array\');');
+ expect(translatedCode).toContain('test("All items have price", function() {');
+ expect(translatedCode).toContain('expect(Boolean(json.items.every(item => item.hasOwnProperty(\'price\')))).to.be.true;');
+ });
+
+ it('should handle complex real-world tests[] example', () => {
+ const code = `
// Parse response
const response = pm.response.json();
@@ -264,20 +264,20 @@ describe('Legacy Tests[] Syntax Translation', () => {
pm.environment.set("targetItemId", targetItem.id);
tests["Found target item"] = true;
}`;
- const translatedCode = translateCode(code);
-
- // Check key transformations
- expect(translatedCode).toContain('const response = res.getBody();');
- expect(translatedCode).toContain('test("Status code is 200", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getStatus() === 200)).to.be.true;');
- expect(translatedCode).toContain('test("Has content-type header", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getHeaders().has("Content-Type"))).to.be.true;');
- expect(translatedCode).toContain('test("Content-Type is JSON", function() {');
- expect(translatedCode).toContain('expect(Boolean(res.getHeader("Content-Type").includes("application/json"))).to.be.true;');
- expect(translatedCode).toContain('const expectedItems = parseInt(bru.getEnvVar("expectedItemCount"));');
- expect(translatedCode).toContain('test("Has correct number of items", function() {');
- expect(translatedCode).toContain('expect(Boolean(response.items.length === expectedItems)).to.be.true;');
- expect(translatedCode).toContain('const targetItem = response.items.find(item => item.name === bru.getVar("targetItemName"));');
- expect(translatedCode).toContain('bru.setEnvVar("targetItemId", targetItem.id);');
- });
-});
\ No newline at end of file
+ const translatedCode = translateCode(code);
+
+ // Check key transformations
+ expect(translatedCode).toContain('const response = res.getBody();');
+ expect(translatedCode).toContain('test("Status code is 200", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getStatus() === 200)).to.be.true;');
+ expect(translatedCode).toContain('test("Has content-type header", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getHeaders().has("Content-Type"))).to.be.true;');
+ expect(translatedCode).toContain('test("Content-Type is JSON", function() {');
+ expect(translatedCode).toContain('expect(Boolean(res.getHeader("Content-Type").includes("application/json"))).to.be.true;');
+ expect(translatedCode).toContain('const expectedItems = parseInt(bru.getEnvVar("expectedItemCount"));');
+ expect(translatedCode).toContain('test("Has correct number of items", function() {');
+ expect(translatedCode).toContain('expect(Boolean(response.items.length === expectedItems)).to.be.true;');
+ expect(translatedCode).toContain('const targetItem = response.items.find(item => item.name === bru.getVar("targetItemName"));');
+ expect(translatedCode).toContain('bru.setEnvVar("targetItemId", targetItem.id);');
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/multiline-syntax.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/multiline-syntax.test.js
index a9be82130..cb7a61685 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/multiline-syntax.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/multiline-syntax.test.js
@@ -90,7 +90,7 @@ describe('Multiline Syntax Handling', () => {
const translatedCode = translateCode(code);
expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("content-type".toLowerCase())');
});
-
+
it('should handle response properties with multiline syntax', () => {
const code = `
const responseBody = pm
@@ -189,7 +189,7 @@ describe('Multiline Syntax Handling', () => {
expect(translatedCode).toContain('.property(\'success\')');
expect(translatedCode).toContain('.equal(true)');
});
-
+
it('should handle a comprehensive script with various multiline formats', () => {
const code = `
// This comprehensive script tests different multiline styles and whitespace variations
@@ -253,31 +253,31 @@ describe('Multiline Syntax Handling', () => {
}
}
`;
-
+
const translatedCode = translateCode(code);
-
+
expect(translatedCode).toContain('const baseUrl = bru.getEnvVar("baseUrl")');
expect(translatedCode).toContain('const apiKey = bru.getEnvVar("apiKey")');
expect(translatedCode).toContain('const userId = bru.getEnvVar("userId")');
-
+
// Check variables translations
expect(translatedCode).toContain('bru.setVar("testId", "test-" + Date.now())');
expect(translatedCode).toContain('bru.setVar("timestamp", new Date().toISOString())');
-
+
// Check collection variables
expect(translatedCode).toContain('bru.setVar("lastRun", new Date())');
-
+
// Check complex conditionals
expect(translatedCode).toContain('if (bru.getEnvVar("apiKey") !== undefined && bru.getEnvVar("apiKey") !== null &&');
expect(translatedCode).toContain('bru.hasVar("testId"))');
-
+
// Check response testing
expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200)');
expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("content-type".toLowerCase())');
-
+
// Check flow control
expect(translatedCode).toContain('if (res.getStatus() === 401)');
expect(translatedCode).toContain('bru.runner.stopExecution()');
expect(translatedCode).toContain('bru.runner.setNextRequest("Next API Call")');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/postman-references.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/postman-references.test.js
index 20e7890a7..99adb5447 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/postman-references.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/postman-references.test.js
@@ -38,7 +38,7 @@ describe('Postman to PM References Conversion', () => {
pm.expect(pm.response.code).to.equal(200);
});
`;
-
+
const translatedCode = translateCode(code);
expect(translatedCode).toContain('const apiKey = bru.getEnvVar("apiKey");');
expect(translatedCode).toContain('const baseUrl = bru.getEnvVar("baseUrl");');
@@ -51,7 +51,7 @@ describe('Postman to PM References Conversion', () => {
const { environment } = postman;
environment.set("key", "value");
`;
-
+
const translatedCode = translateCode(code);
expect(translatedCode).toContain('bru.setEnvVar("key", "value");');
});
@@ -67,7 +67,7 @@ describe('Postman to PM References Conversion', () => {
postman.setNextRequest("Development Flow");
}
`;
-
+
const translatedCode = translateCode(code);
expect(translatedCode).toContain('if (bru.getEnvVar("isProduction") === "true") {');
expect(translatedCode).toContain('const apiUrl = bru.getEnvVar("prodUrl");');
@@ -86,7 +86,7 @@ describe('Postman to PM References Conversion', () => {
// Set environment variables with response data
postman.setEnvironmentVariable("lastResponseCode", responseCode);
`;
-
+
const translatedCode = translateCode(code);
expect(translatedCode).toContain('const responseCode = res.getStatus();');
expect(translatedCode).toContain('const responseBody = res.getBody();');
@@ -99,7 +99,7 @@ describe('Postman to PM References Conversion', () => {
console.log("This is a pm script");
const message = "We're using pm to test our API";
`;
-
+
const translatedCode = translateCode(code);
expect(translatedCode).toContain('console.log("This is a pm script");');
expect(translatedCode).toContain('const message = "We\'re using pm to test our API";');
@@ -121,7 +121,7 @@ describe('Postman to PM References Conversion', () => {
postman.expect(code).to.equal(200);
});
`;
-
+
const translatedCode = translateCode(code);
// Should handle the aliases properly
expect(translatedCode).toContain('const apiKey = bru.getEnvVar("apiKey");');
@@ -129,4 +129,4 @@ describe('Postman to PM References Conversion', () => {
expect(translatedCode).toContain('test("Response is valid", function() {');
expect(translatedCode).toContain('expect(code).to.equal(200);');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/request.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/request.test.js
index a0469e2b9..989fd3817 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/request.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/request.test.js
@@ -1,54 +1,54 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Request Translation', () => {
- it('should translate pm.request.url', () => {
- const code = 'const requestUrl = pm.request.url;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const requestUrl = req.getUrl();');
- });
+ it('should translate pm.request.url', () => {
+ const code = 'const requestUrl = pm.request.url;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const requestUrl = req.getUrl();');
+ });
- it('should translate pm.request.method', () => {
- const code = 'const method = pm.request.method;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const method = req.getMethod();');
- });
+ it('should translate pm.request.method', () => {
+ const code = 'const method = pm.request.method;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const method = req.getMethod();');
+ });
- it('should translate pm.request.headers', () => {
- const code = 'const headers = pm.request.headers;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const headers = req.getHeaders();');
- });
+ it('should translate pm.request.headers', () => {
+ const code = 'const headers = pm.request.headers;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const headers = req.getHeaders();');
+ });
- it('should translate pm.request.body', () => {
- const code = 'const body = pm.request.body;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const body = req.getBody();');
- });
+ it('should translate pm.request.body', () => {
+ const code = 'const body = pm.request.body;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const body = req.getBody();');
+ });
- it('should translate pm.response.statusText', () => {
- const code = 'const statusText = pm.response.statusText;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const statusText = res.statusText;');
- });
+ it('should translate pm.response.statusText', () => {
+ const code = 'const statusText = pm.response.statusText;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const statusText = res.statusText;');
+ });
- it('should translate multiple request methods in one block', () => {
- const code = `
+ it('should translate multiple request methods in one block', () => {
+ const code = `
const url = pm.request.url;
const method = pm.request.method;
const headers = pm.request.headers;
const body = pm.request.body;
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const url = req.getUrl();
const method = req.getMethod();
const headers = req.getHeaders();
const body = req.getBody();
`);
- });
+ });
- it('should handle request and response properties together', () => {
- const code = `
+ it('should handle request and response properties together', () => {
+ const code = `
// Get request data
const url = pm.request.url;
const method = pm.request.method;
@@ -63,18 +63,18 @@ describe('Request Translation', () => {
pm.expect(url).to.include("/api/items");
});
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('const url = req.getUrl();');
- expect(translatedCode).toContain('const method = req.getMethod();');
- expect(translatedCode).toContain('const statusCode = res.getStatus();');
- expect(translatedCode).toContain('const statusText = res.statusText;');
- expect(translatedCode).toContain('test("Request was made correctly", function() {');
- expect(translatedCode).toContain('expect(method).to.equal("POST");');
- expect(translatedCode).toContain('expect(url).to.include("/api/items");');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('const url = req.getUrl();');
+ expect(translatedCode).toContain('const method = req.getMethod();');
+ expect(translatedCode).toContain('const statusCode = res.getStatus();');
+ expect(translatedCode).toContain('const statusText = res.statusText;');
+ expect(translatedCode).toContain('test("Request was made correctly", function() {');
+ expect(translatedCode).toContain('expect(method).to.equal("POST");');
+ expect(translatedCode).toContain('expect(url).to.include("/api/items");');
+ });
- it('should handle request properties in conditional blocks', () => {
- const code = `
+ it('should handle request properties in conditional blocks', () => {
+ const code = `
if (pm.request.method === "POST") {
console.log("This is a POST request to " + pm.request.url);
pm.test("Request has correct content-type", function() {
@@ -82,16 +82,16 @@ describe('Request Translation', () => {
});
}
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('if (req.getMethod() === "POST") {');
- expect(translatedCode).toContain('console.log("This is a POST request to " + req.getUrl());');
- expect(translatedCode).toContain('test("Request has correct content-type", function() {');
- // Note: The expectation for headers.has might be transformed differently
- // depending on how complex transformations are handled
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('if (req.getMethod() === "POST") {');
+ expect(translatedCode).toContain('console.log("This is a POST request to " + req.getUrl());');
+ expect(translatedCode).toContain('test("Request has correct content-type", function() {');
+ // Note: The expectation for headers.has might be transformed differently
+ // depending on how complex transformations are handled
+ });
- it('should handle request data extraction and variable setting', () => {
- const code = `
+ it('should handle request data extraction and variable setting', () => {
+ const code = `
// Extract request data
const requestData = pm.request.body;
const contentType = pm.request.headers.get("Content-Type");
@@ -100,11 +100,11 @@ describe('Request Translation', () => {
pm.variables.set("lastRequestBody", JSON.stringify(requestData));
pm.environment.set("lastContentType", contentType);
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('const requestData = req.getBody();');
- expect(translatedCode).toContain('bru.setVar("lastRequestBody", JSON.stringify(requestData));');
- expect(translatedCode).toContain('bru.setEnvVar("lastContentType", contentType);');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('const requestData = req.getBody();');
+ expect(translatedCode).toContain('bru.setVar("lastRequestBody", JSON.stringify(requestData));');
+ expect(translatedCode).toContain('bru.setEnvVar("lastContentType", contentType);');
+ });
it('should translate legacy request.* properties', () => {
const code = `
@@ -121,4 +121,4 @@ describe('Request Translation', () => {
const name = req.getName();
`);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/response.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/response.test.js
index 5df2fe5bb..d154ba9ef 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/response.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/response.test.js
@@ -1,111 +1,111 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Response Translation', () => {
- // Basic response property tests
- it('should translate pm.response.json', () => {
- const code = 'const jsonData = pm.response.json();';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const jsonData = res.getBody();');
- });
+ // Basic response property tests
+ it('should translate pm.response.json', () => {
+ const code = 'const jsonData = pm.response.json();';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const jsonData = res.getBody();');
+ });
- it('should translate pm.response.code', () => {
- const code = 'if (pm.response.code === 200) { console.log("Success"); }';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('if (res.getStatus() === 200) { console.log("Success"); }');
- });
+ it('should translate pm.response.code', () => {
+ const code = 'if (pm.response.code === 200) { console.log("Success"); }';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('if (res.getStatus() === 200) { console.log("Success"); }');
+ });
- it('should translate pm.response.text', () => {
- const code = 'const responseText = pm.response.text();';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const responseText = JSON.stringify(res.getBody());');
- });
+ it('should translate pm.response.text', () => {
+ const code = 'const responseText = pm.response.text();';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const responseText = JSON.stringify(res.getBody());');
+ });
- it('should translate pm.response.responseTime', () => {
- const code = 'console.log("Response time:", pm.response.responseTime);';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('console.log("Response time:", res.getResponseTime());');
- });
+ it('should translate pm.response.responseTime', () => {
+ const code = 'console.log("Response time:", pm.response.responseTime);';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('console.log("Response time:", res.getResponseTime());');
+ });
- it('should translate pm.response.statusText', () => {
- const code = 'console.log("Status text:", pm.response.statusText);';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('console.log("Status text:", res.statusText);');
- });
+ it('should translate pm.response.statusText', () => {
+ const code = 'console.log("Status text:", pm.response.statusText);';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('console.log("Status text:", res.statusText);');
+ });
- it('should translate pm.response.headers', () => {
- const code = 'console.log("Headers:", pm.response.headers);';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('console.log("Headers:", res.getHeaders());');
- });
+ it('should translate pm.response.headers', () => {
+ const code = 'console.log("Headers:", pm.response.headers);';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('console.log("Headers:", res.getHeaders());');
+ });
- // Complex response transformations
- it('should transform pm.response.to.have.status', () => {
- const code = 'pm.response.to.have.status(201);';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('expect(res.getStatus()).to.equal(201);');
- });
+ // Complex response transformations
+ it('should transform pm.response.to.have.status', () => {
+ const code = 'pm.response.to.have.status(201);';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('expect(res.getStatus()).to.equal(201);');
+ });
- it('should transform pm.response.to.have.header with single argument', () => {
- const code = 'pm.response.to.have.header("Content-Type");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase());');
- });
-
- it('should transform multiple pm.response.to.have.header statements', () => {
- const code = `
+ it('should transform pm.response.to.have.header with single argument', () => {
+ const code = 'pm.response.to.have.header("Content-Type");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase());');
+ });
+
+ it('should transform multiple pm.response.to.have.header statements', () => {
+ const code = `
pm.response.to.have.header("Content-Type", "application/json");
pm.response.to.have.header("Cache-Control", "no-cache");
`;
- const translatedCode = translateCode(code);
-
- // Check for the existence of all four assertions (two pairs)
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Cache-Control".toLowerCase(), "no-cache");');
- });
-
- it('should transform pm.response.to.have.header inside control structures', () => {
- const code = `
+ const translatedCode = translateCode(code);
+
+ // Check for the existence of all four assertions (two pairs)
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Cache-Control".toLowerCase(), "no-cache");');
+ });
+
+ it('should transform pm.response.to.have.header inside control structures', () => {
+ const code = `
if (pm.response.code === 200) {
pm.response.to.have.header("Content-Type", "application/json");
}
`;
- const translatedCode = translateCode(code);
-
- // The assertions should be inside the if block
- expect(translatedCode).toContain('if (res.getStatus() === 200) {');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
- });
-
- it('should transform pm.response.to.have.header with variable parameters', () => {
- const code = `
+ const translatedCode = translateCode(code);
+
+ // The assertions should be inside the if block
+ expect(translatedCode).toContain('if (res.getStatus() === 200) {');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
+ });
+
+ it('should transform pm.response.to.have.header with variable parameters', () => {
+ const code = `
const headerName = "Content-Type";
const expectedValue = "application/json";
pm.response.to.have.header(headerName, expectedValue);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const headerName = "Content-Type";');
- expect(translatedCode).toContain('const expectedValue = "application/json";');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(headerName.toLowerCase(), expectedValue);');
- });
+ const translatedCode = translateCode(code);
- // Response aliases tests
- it('should handle response aliases', () => {
- const code = `
+ expect(translatedCode).toContain('const headerName = "Content-Type";');
+ expect(translatedCode).toContain('const expectedValue = "application/json";');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(headerName.toLowerCase(), expectedValue);');
+ });
+
+ // Response aliases tests
+ it('should handle response aliases', () => {
+ const code = `
const response = pm.response;
const status = response.status;
const body = response.json();
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const status = res.statusText;
const body = res.getBody();
`);
- });
+ });
- // Response to.have.status with different formats
- it('should handle pm.response.to.have.status with different status codes', () => {
- const code = `
+ // Response to.have.status with different formats
+ it('should handle pm.response.to.have.status with different status codes', () => {
+ const code = `
// Test different status codes
pm.response.to.have.status(200); // OK
pm.response.to.have.status(201); // Created
@@ -117,97 +117,96 @@ describe('Response Translation', () => {
const expectedStatus = 200;
pm.response.to.have.status(expectedStatus);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(201);');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(400);');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(404);');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(500);');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(expectedStatus);');
- });
+ const translatedCode = translateCode(code);
- // Alias for pm.response.to.have.status
- it('should handle pm.response.to.have.status alias', () => {
- const code = `
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(201);');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(400);');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(404);');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(500);');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(expectedStatus);');
+ });
+
+ // Alias for pm.response.to.have.status
+ it('should handle pm.response.to.have.status alias', () => {
+ const code = `
const resp = pm.response;
resp.to.have.status(200);
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
expect(res.getStatus()).to.equal(200);
`);
- });
+ });
- it('should handle pm.response.to.have.header alias', () => {
- const code = `
+ it('should handle pm.response.to.have.header alias', () => {
+ const code = `
const resp = pm.response;
resp.to.have.header("Content-Type");
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase());
`);
- });
-
- it('should handle pm.response.to.have.header alias with value check', () => {
- const code = `
+ });
+
+ it('should handle pm.response.to.have.header alias with value check', () => {
+ const code = `
const resp = pm.response;
resp.to.have.header("Content-Type", "application/json");
`;
- const translatedCode = translateCode(code);
-
- // Check for both assertions when using an alias
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
- });
+ const translatedCode = translateCode(code);
-
- it('should translate response.status', () => {
- const code = `
+ // Check for both assertions when using an alias
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
+ });
+
+ it('should translate response.status', () => {
+ const code = `
const resp = pm.response;
const statusCode = resp.status;
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const statusCode = res.statusText;
`);
- });
-
- it('should translate response.body', () => {
- const code = `
+ });
+
+ it('should translate response.body', () => {
+ const code = `
const resp = pm.response;
const responseBody = resp.json();
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const responseBody = res.getBody();
`);
- });
+ });
- it('should translate response.headers', () => {
- const code = `
+ it('should translate response.headers', () => {
+ const code = `
const resp = pm.response;
const headers = resp.headers;
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const headers = res.getHeaders();
`);
- });
+ });
- it('should translate pm.response.statusText', () => {
- const code = `
+ it('should translate pm.response.statusText', () => {
+ const code = `
const resp = pm.response;
const statusText = resp.statusText;
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const statusText = res.statusText;
`);
- });
-
- it('should translate multiple response methods in one block', () => {
- const code = `
+ });
+
+ it('should translate multiple response methods in one block', () => {
+ const code = `
const resp = pm.response;
const statusCode = resp.code;
const statusText = resp.statusText;
@@ -216,8 +215,8 @@ describe('Response Translation', () => {
const time = resp.responseTime;
resp.to.have.status(200);
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
const statusCode = res.getStatus();
const statusText = res.statusText;
const jsonData = res.getBody();
@@ -225,25 +224,25 @@ describe('Response Translation', () => {
const time = res.getResponseTime();
expect(res.getStatus()).to.equal(200);
`);
- });
+ });
- it('should handle accessing nested properties on response objects', () => {
- const code = `
+ it('should handle accessing nested properties on response objects', () => {
+ const code = `
const resp = pm.response;
const data = resp.json();
if (data && data.user && data.user.id) {
pm.environment.set("userId", data.user.id);
}
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).not.toContain('const resp = pm.response;');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('bru.setEnvVar("userId", data.user.id);');
- });
+ const translatedCode = translateCode(code);
- it('should handle all response property methods together', () => {
- const code = `
+ expect(translatedCode).not.toContain('const resp = pm.response;');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('bru.setEnvVar("userId", data.user.id);');
+ });
+
+ it('should handle all response property methods together', () => {
+ const code = `
// All response property methods
const statusCode = pm.response.code;
const responseBody = pm.response.json();
@@ -258,47 +257,47 @@ describe('Response Translation', () => {
pm.expect(statusText).to.equal('OK');
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const statusCode = res.getStatus();');
- expect(translatedCode).toContain('const responseBody = res.getBody();');
- expect(translatedCode).toContain('const responseText = JSON.stringify(res.getBody());');
- expect(translatedCode).toContain('const responseTime = res.getResponseTime();');
- expect(translatedCode).toContain('const statusText = res.statusText;');
- expect(translatedCode).toContain('test("Response is valid", function() {');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
- expect(translatedCode).toContain('expect(responseBody).to.be.an(\'object\');');
- expect(translatedCode).toContain('expect(responseTime).to.be.below(1000);');
- expect(translatedCode).toContain('expect(statusText).to.equal(\'OK\');');
- });
+ const translatedCode = translateCode(code);
- it('should handle pm objects with array access on response', () => {
- const code = `
+ expect(translatedCode).toContain('const statusCode = res.getStatus();');
+ expect(translatedCode).toContain('const responseBody = res.getBody();');
+ expect(translatedCode).toContain('const responseText = JSON.stringify(res.getBody());');
+ expect(translatedCode).toContain('const responseTime = res.getResponseTime();');
+ expect(translatedCode).toContain('const statusText = res.statusText;');
+ expect(translatedCode).toContain('test("Response is valid", function() {');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
+ expect(translatedCode).toContain('expect(responseBody).to.be.an(\'object\');');
+ expect(translatedCode).toContain('expect(responseTime).to.be.below(1000);');
+ expect(translatedCode).toContain('expect(statusText).to.equal(\'OK\');');
+ });
+
+ it('should handle pm objects with array access on response', () => {
+ const code = `
const items = pm.response.json().items;
for (let i = 0; i < items.length; i++) {
pm.collectionVariables.set("item_" + i, items[i].id);
}
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const items = res.getBody().items;');
- expect(translatedCode).toContain('bru.setVar("item_" + i, items[i].id);');
- });
+ const translatedCode = translateCode(code);
- it('should handle response JSON with optional chaining and nullish coalescing', () => {
- const code = `
+ expect(translatedCode).toContain('const items = res.getBody().items;');
+ expect(translatedCode).toContain('bru.setVar("item_" + i, items[i].id);');
+ });
+
+ it('should handle response JSON with optional chaining and nullish coalescing', () => {
+ const code = `
const userId = pm.response.json()?.user?.id ?? "anonymous";
const items = pm.response.json()?.data?.items || [];
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const userId = res.getBody()?.user?.id ?? "anonymous";');
- expect(translatedCode).toContain('const items = res.getBody()?.data?.items || [];');
- });
+ const translatedCode = translateCode(code);
- it('should handle response headers with different access patterns', () => {
- // will need to handle get, set methods, bruno does not support this yet
- const code = `
+ expect(translatedCode).toContain('const userId = res.getBody()?.user?.id ?? "anonymous";');
+ expect(translatedCode).toContain('const items = res.getBody()?.data?.items || [];');
+ });
+
+ it('should handle response headers with different access patterns', () => {
+ // will need to handle get, set methods, bruno does not support this yet
+ const code = `
const contentType = pm.response.headers.get('Content-Type');
const contentLength = pm.response.headers.get('Content-Length');
console.log("contentType", contentType);
@@ -310,34 +309,34 @@ describe('Response Translation', () => {
pm.expect(contentType).to.include('application/json');
});
`;
- const translatedCode = translateCode(code);
-
- // Check how header access is translated
- expect(translatedCode).toContain('const contentType = res.getHeader(\'Content-Type\');');
- expect(translatedCode).toContain('const contentLength = res.getHeader(\'Content-Length\');');
- expect(translatedCode).toContain('console.log("contentType", contentType);');
- expect(translatedCode).toContain('console.log("contentLength", contentLength);');
- expect(translatedCode).not.toContain('pm.test')
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(\'Content-Type\'.toLowerCase())');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(\'Content-Length\'.toLowerCase())');
- expect(translatedCode).toContain('expect(contentType).to.include(\'application/json\')');
- });
+ const translatedCode = translateCode(code);
- it('should transform response data with array destructuring', () => {
- const code = `
+ // Check how header access is translated
+ expect(translatedCode).toContain('const contentType = res.getHeader(\'Content-Type\');');
+ expect(translatedCode).toContain('const contentLength = res.getHeader(\'Content-Length\');');
+ expect(translatedCode).toContain('console.log("contentType", contentType);');
+ expect(translatedCode).toContain('console.log("contentLength", contentLength);');
+ expect(translatedCode).not.toContain('pm.test');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(\'Content-Type\'.toLowerCase())');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(\'Content-Length\'.toLowerCase())');
+ expect(translatedCode).toContain('expect(contentType).to.include(\'application/json\')');
+ });
+
+ it('should transform response data with array destructuring', () => {
+ const code = `
const { id, name, items } = pm.response.json();
const [first, second] = items;
pm.environment.set("userId", id);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const { id, name, items } = res.getBody();');
- expect(translatedCode).toContain('const [first, second] = items;');
- expect(translatedCode).toContain('bru.setEnvVar("userId", id);');
- });
+ const translatedCode = translateCode(code);
- it('should handle response in complex conditionals', () => {
- const code = `
+ expect(translatedCode).toContain('const { id, name, items } = res.getBody();');
+ expect(translatedCode).toContain('const [first, second] = items;');
+ expect(translatedCode).toContain('bru.setEnvVar("userId", id);');
+ });
+
+ it('should handle response in complex conditionals', () => {
+ const code = `
if (pm.response.code >= 200 && pm.response.code < 300) {
if (pm.response.headers.get('Content-Type').includes('application/json')) {
const data = pm.response.json();
@@ -354,18 +353,18 @@ describe('Response Translation', () => {
console.error("Request failed with status:", pm.response.code);
}
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('if (res.getStatus() >= 200 && res.getStatus() < 300) {');
- expect(translatedCode).toContain('if (res.getHeader(\'Content-Type\').includes(\'application/json\')) {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('bru.setEnvVar("authToken", data.token);');
- expect(translatedCode).toContain('} else if (res.getStatus() === 404) {');
- expect(translatedCode).toContain('console.error("Request failed with status:", res.getStatus());');
- });
+ const translatedCode = translateCode(code);
- it('should handle response processing with try-catch', () => {
- const code = `
+ expect(translatedCode).toContain('if (res.getStatus() >= 200 && res.getStatus() < 300) {');
+ expect(translatedCode).toContain('if (res.getHeader(\'Content-Type\').includes(\'application/json\')) {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('bru.setEnvVar("authToken", data.token);');
+ expect(translatedCode).toContain('} else if (res.getStatus() === 404) {');
+ expect(translatedCode).toContain('console.error("Request failed with status:", res.getStatus());');
+ });
+
+ it('should handle response processing with try-catch', () => {
+ const code = `
try {
const data = pm.response.json();
pm.environment.set("userData", JSON.stringify(data.user));
@@ -375,16 +374,16 @@ describe('Response Translation', () => {
pm.environment.set("rawResponse", text);
}
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('bru.setEnvVar("userData", JSON.stringify(data.user));');
- expect(translatedCode).toContain('const text = JSON.stringify(res.getBody());');
- expect(translatedCode).toContain('bru.setEnvVar("rawResponse", text);');
- });
+ const translatedCode = translateCode(code);
- it('should handle JSON path style access to response data', () => {
- const code = `
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('bru.setEnvVar("userData", JSON.stringify(data.user));');
+ expect(translatedCode).toContain('const text = JSON.stringify(res.getBody());');
+ expect(translatedCode).toContain('bru.setEnvVar("rawResponse", text);');
+ });
+
+ it('should handle JSON path style access to response data', () => {
+ const code = `
const data = pm.response.json();
const userId = data.user.id;
const userEmail = data.user.contact.email;
@@ -392,31 +391,31 @@ describe('Response Translation', () => {
pm.environment.set("userId", userId);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('const userId = data.user.id;');
- expect(translatedCode).toContain('const userEmail = data.user.contact.email;');
- expect(translatedCode).toContain('const firstItem = data.items[0];');
- expect(translatedCode).toContain('bru.setEnvVar("userId", userId);');
- });
+ const translatedCode = translateCode(code);
- it('should handle template literals with response data', () => {
- const code = `
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('const userId = data.user.id;');
+ expect(translatedCode).toContain('const userEmail = data.user.contact.email;');
+ expect(translatedCode).toContain('const firstItem = data.items[0];');
+ expect(translatedCode).toContain('bru.setEnvVar("userId", userId);');
+ });
+
+ it('should handle template literals with response data', () => {
+ const code = `
const data = pm.response.json();
const welcomeMessage = \`Hello, \${data.user.name}! Your ID is \${data.user.id}.\`;
pm.environment.set("welcomeMessage", welcomeMessage);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('const welcomeMessage = `Hello, ${data.user.name}! Your ID is ${data.user.id}.`;');
- expect(translatedCode).toContain('bru.setEnvVar("welcomeMessage", welcomeMessage);');
- });
+ const translatedCode = translateCode(code);
- it('should handle response processing in arrow functions', () => {
- const code = `
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('const welcomeMessage = `Hello, ${data.user.name}! Your ID is ${data.user.id}.`;');
+ expect(translatedCode).toContain('bru.setEnvVar("welcomeMessage", welcomeMessage);');
+ });
+
+ it('should handle response processing in arrow functions', () => {
+ const code = `
const processItems = () => {
const items = pm.response.json().items;
return items.map(item => item.id);
@@ -425,16 +424,16 @@ describe('Response Translation', () => {
const itemIds = processItems();
pm.environment.set("itemIds", JSON.stringify(itemIds));
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const items = res.getBody().items;');
- expect(translatedCode).toContain('return items.map(item => item.id);');
- expect(translatedCode).toContain('const itemIds = processItems();');
- expect(translatedCode).toContain('bru.setEnvVar("itemIds", JSON.stringify(itemIds));');
- });
+ const translatedCode = translateCode(code);
- it('should handle complex inline operations with response data', () => {
- const code = `
+ expect(translatedCode).toContain('const items = res.getBody().items;');
+ expect(translatedCode).toContain('return items.map(item => item.id);');
+ expect(translatedCode).toContain('const itemIds = processItems();');
+ expect(translatedCode).toContain('bru.setEnvVar("itemIds", JSON.stringify(itemIds));');
+ });
+
+ it('should handle complex inline operations with response data', () => {
+ const code = `
const items = pm.response.json().items;
const totalValue = items.reduce((sum, item) => sum + item.price, 0);
const highValueItems = items.filter(item => item.price > 100);
@@ -443,18 +442,18 @@ describe('Response Translation', () => {
pm.environment.set("totalValue", totalValue);
pm.environment.set("highValueItemCount", highValueItems.length);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const items = res.getBody().items;');
- expect(translatedCode).toContain('const totalValue = items.reduce((sum, item) => sum + item.price, 0);');
- expect(translatedCode).toContain('const highValueItems = items.filter(item => item.price > 100);');
- expect(translatedCode).toContain('const itemNames = items.map(item => item.name);');
- expect(translatedCode).toContain('bru.setEnvVar("totalValue", totalValue);');
- expect(translatedCode).toContain('bru.setEnvVar("highValueItemCount", highValueItems.length);');
- });
+ const translatedCode = translateCode(code);
- it('should handle complex test structure with pm.response.to.have.header', () => {
- const code = `
+ expect(translatedCode).toContain('const items = res.getBody().items;');
+ expect(translatedCode).toContain('const totalValue = items.reduce((sum, item) => sum + item.price, 0);');
+ expect(translatedCode).toContain('const highValueItems = items.filter(item => item.price > 100);');
+ expect(translatedCode).toContain('const itemNames = items.map(item => item.name);');
+ expect(translatedCode).toContain('bru.setEnvVar("totalValue", totalValue);');
+ expect(translatedCode).toContain('bru.setEnvVar("highValueItemCount", highValueItems.length);');
+ });
+
+ it('should handle complex test structure with pm.response.to.have.header', () => {
+ const code = `
pm.test("Response headers validation", function() {
pm.response.to.have.header("Content-Type", "application/json");
pm.response.to.have.header("Cache-Control");
@@ -463,22 +462,22 @@ describe('Response Translation', () => {
pm.expect(responseTime).to.be.below(1000);
});
`;
- const translatedCode = translateCode(code);
-
- // Check for test function conversion
- expect(translatedCode).toContain('test("Response headers validation", function() {');
-
- // Check for header assertions inside the test callback
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Cache-Control".toLowerCase())');
-
- // Check that other test assertions are preserved
- expect(translatedCode).toContain('const responseTime = res.getResponseTime();');
- expect(translatedCode).toContain('expect(responseTime).to.be.below(1000);');
- });
-
- it('should handle dynamic header names in pm.response.to.have.header', () => {
- const code = `
+ const translatedCode = translateCode(code);
+
+ // Check for test function conversion
+ expect(translatedCode).toContain('test("Response headers validation", function() {');
+
+ // Check for header assertions inside the test callback
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Content-Type".toLowerCase(), "application/json");');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property("Cache-Control".toLowerCase())');
+
+ // Check that other test assertions are preserved
+ expect(translatedCode).toContain('const responseTime = res.getResponseTime();');
+ expect(translatedCode).toContain('expect(responseTime).to.be.below(1000);');
+ });
+
+ it('should handle dynamic header names in pm.response.to.have.header', () => {
+ const code = `
function checkHeaderPresent(headerName) {
pm.response.to.have.header(headerName);
}
@@ -490,98 +489,98 @@ describe('Response Translation', () => {
checkHeaderPresent("Authorization");
validateHeader("Content-Type", "application/json");
`;
- const translatedCode = translateCode(code);
-
- // Check function transformations
- expect(translatedCode).toContain('function checkHeaderPresent(headerName) {');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(headerName.toLowerCase())');
-
- expect(translatedCode).toContain('function validateHeader(headerName, expectedValue) {');
- expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(headerName.toLowerCase(), expectedValue);');
-
- // Check function calls
- expect(translatedCode).toContain('checkHeaderPresent("Authorization");');
- expect(translatedCode).toContain('validateHeader("Content-Type", "application/json");');
- });
+ const translatedCode = translateCode(code);
- it('should transform pm.response.to.have.body with string literal', () => {
- const code = 'pm.response.to.have.body("Expected response body");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('expect(res.getBody()).to.equal("Expected response body");');
- });
+ // Check function transformations
+ expect(translatedCode).toContain('function checkHeaderPresent(headerName) {');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(headerName.toLowerCase())');
- it('should transform pm.response.to.have.body with variable parameter', () => {
- const code = `
+ expect(translatedCode).toContain('function validateHeader(headerName, expectedValue) {');
+ expect(translatedCode).toContain('expect(res.getHeaders()).to.have.property(headerName.toLowerCase(), expectedValue);');
+
+ // Check function calls
+ expect(translatedCode).toContain('checkHeaderPresent("Authorization");');
+ expect(translatedCode).toContain('validateHeader("Content-Type", "application/json");');
+ });
+
+ it('should transform pm.response.to.have.body with string literal', () => {
+ const code = 'pm.response.to.have.body("Expected response body");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('expect(res.getBody()).to.equal("Expected response body");');
+ });
+
+ it('should transform pm.response.to.have.body with variable parameter', () => {
+ const code = `
const expectedBody = {"status": "success", "data": [1, 2, 3]};
pm.response.to.have.body(expectedBody);
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toContain('const expectedBody = {"status": "success", "data": [1, 2, 3]};');
- expect(translatedCode).toContain('expect(res.getBody()).to.equal(expectedBody);');
- });
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toContain('const expectedBody = {"status": "success", "data": [1, 2, 3]};');
+ expect(translatedCode).toContain('expect(res.getBody()).to.equal(expectedBody);');
+ });
- it('should transform pm.response.to.have.body with JSON object', () => {
- const code = `pm.response.to.have.body({"status": "success", "message": "Operation completed"});`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('expect(res.getBody()).to.equal({"status": "success", "message": "Operation completed"});');
- });
+ it('should transform pm.response.to.have.body with JSON object', () => {
+ const code = `pm.response.to.have.body({"status": "success", "message": "Operation completed"});`;
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('expect(res.getBody()).to.equal({"status": "success", "message": "Operation completed"});');
+ });
- it('should transform pm.response.to.have.body inside test function', () => {
- const code = `
+ it('should transform pm.response.to.have.body inside test function', () => {
+ const code = `
pm.test("Response body validation", function() {
const expectedResponse = {"result": true};
pm.response.to.have.body(expectedResponse);
});
`;
- const translatedCode = translateCode(code);
- const expectedOutput = `
+ const translatedCode = translateCode(code);
+ const expectedOutput = `
test("Response body validation", function() {
const expectedResponse = {"result": true};
expect(res.getBody()).to.equal(expectedResponse);
});
- `
- expect(translatedCode).toBe(expectedOutput);
- });
+ `;
+ expect(translatedCode).toBe(expectedOutput);
+ });
- it('should transform pm.response.to.have.body with response alias', () => {
- const code = `
+ it('should transform pm.response.to.have.body with response alias', () => {
+ const code = `
const resp = pm.response;
resp.to.have.body({"status": "ok"});
`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
expect(res.getBody()).to.equal({"status": "ok"});
`);
- });
+ });
- // --- getSize translations ---------------------------
- it('should translate pm.response.size()', () => {
- const code = 'const size = pm.response.size();';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const size = res.getSize();');
- });
+ // --- getSize translations ---------------------------
+ it('should translate pm.response.size()', () => {
+ const code = 'const size = pm.response.size();';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const size = res.getSize();');
+ });
- it('should translate pm.response.size().body', () => {
- const code = 'const bodySize = pm.response.size().body;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const bodySize = res.getSize().body;');
- });
+ it('should translate pm.response.size().body', () => {
+ const code = 'const bodySize = pm.response.size().body;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const bodySize = res.getSize().body;');
+ });
- it('should translate pm.response.size().header', () => {
- const code = 'const headerSize = pm.response.size().header;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const headerSize = res.getSize().header;');
- });
+ it('should translate pm.response.size().header', () => {
+ const code = 'const headerSize = pm.response.size().header;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const headerSize = res.getSize().header;');
+ });
- it('should translate pm.response.size().total', () => {
- const code = 'const totalSize = pm.response.size().total;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const totalSize = res.getSize().total;');
- });
+ it('should translate pm.response.size().total', () => {
+ const code = 'const totalSize = pm.response.size().total;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const totalSize = res.getSize().total;');
+ });
- it('should translate pm.response.responseSize alias', () => {
- const code = 'const responseSize = pm.response.responseSize;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const responseSize = res.getSize().body;');
- });
-});
\ No newline at end of file
+ it('should translate pm.response.responseSize alias', () => {
+ const code = 'const responseSize = pm.response.responseSize;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('const responseSize = res.getSize().body;');
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/scoped-variables.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/scoped-variables.test.js
index 9ed5ed700..d6c8966b2 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/scoped-variables.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/scoped-variables.test.js
@@ -1,7 +1,7 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Scoped Variables', () => {
- it.skip('should handle scoped variables correctly', () => {
+ it.skip('should handle scoped variables correctly', () => {
const code = `
const response = pm.response;
const status = response.status;
@@ -11,7 +11,7 @@ describe('Scoped Variables', () => {
const status = response.status;
console.log(status);
}
- `
+ `;
const result = translateCode(code);
console.log(result);
expect(result).toBe(`
@@ -22,8 +22,8 @@ describe('Scoped Variables', () => {
const status = response.status;
console.log(status);
}
- `)
- })
+ `);
+ });
it.skip('should handle scoped variables correctly', () => {
const code = `
@@ -35,7 +35,7 @@ describe('Scoped Variables', () => {
const status = response.status;
console.log(status);
}
- `
+ `;
const result = translateCode(code);
console.log(result);
expect(result).toBe(`
@@ -46,6 +46,6 @@ describe('Scoped Variables', () => {
const status = res.statusText;
console.log(status);
}
- `)
- })
-})
\ No newline at end of file
+ `);
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/testing-framework.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/testing-framework.test.js
index fc3988f1f..ab6c690b6 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/testing-framework.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/testing-framework.test.js
@@ -1,59 +1,59 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Testing Framework Translation', () => {
- // Basic testing framework translations
- it('should translate pm.test', () => {
- const code = 'pm.test("Status code is 200", function() { pm.response.to.have.status(200); });';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('test("Status code is 200", function() { expect(res.getStatus()).to.equal(200); });');
- });
+ // Basic testing framework translations
+ it('should translate pm.test', () => {
+ const code = 'pm.test("Status code is 200", function() { pm.response.to.have.status(200); });';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('test("Status code is 200", function() { expect(res.getStatus()).to.equal(200); });');
+ });
- it('should translate pm.expect', () => {
- const code = 'pm.expect(jsonData.success).to.be.true;';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('expect(jsonData.success).to.be.true;');
- });
+ it('should translate pm.expect', () => {
+ const code = 'pm.expect(jsonData.success).to.be.true;';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('expect(jsonData.success).to.be.true;');
+ });
- it('should translate pm.expect.fail', () => {
- const code = 'if (!isValid) pm.expect.fail("Data is invalid");';
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe('if (!isValid) expect.fail("Data is invalid");');
- });
+ it('should translate pm.expect.fail', () => {
+ const code = 'if (!isValid) pm.expect.fail("Data is invalid");';
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe('if (!isValid) expect.fail("Data is invalid");');
+ });
- // Tests with response assertions
- it('should translate pm.response.to.have.status in tests', () => {
- const code = `
+ // Tests with response assertions
+ it('should translate pm.response.to.have.status in tests', () => {
+ const code = `
pm.test("Check environment and call successful", function () {
pm.expect(pm.environment.name).to.equal("ENVIRONMENT_NAME");
pm.response.to.have.status(200);
});`;
- const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ const translatedCode = translateCode(code);
+ expect(translatedCode).toBe(`
test("Check environment and call successful", function () {
expect(bru.getEnvName()).to.equal("ENVIRONMENT_NAME");
expect(res.getStatus()).to.equal(200);
});`);
- });
+ });
- // Test aliases
- it('should handle test aliases', () => {
- const code = `
+ // Test aliases
+ it('should handle test aliases', () => {
+ const code = `
const { test, expect } = pm;
test("Status code is 200", function () {
expect(pm.response.code).to.equal(200);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).not.toContain('const { test, expect } = pm');
- expect(translatedCode).toContain('test("Status code is 200", function () {');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
- });
+ const translatedCode = translateCode(code);
- // Tests inside different code structures
- it('should translate pm commands inside tests with nested functions', () => {
- const code = `
+ expect(translatedCode).not.toContain('const { test, expect } = pm');
+ expect(translatedCode).toContain('test("Status code is 200", function () {');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
+ });
+
+ // Tests inside different code structures
+ it('should translate pm commands inside tests with nested functions', () => {
+ const code = `
pm.test("Auth flow works", function() {
const response = pm.response.json();
pm.expect(response.authenticated).to.be.true;
@@ -61,29 +61,29 @@ describe('Testing Framework Translation', () => {
pm.collectionVariables.set("sessionId", response.session.id);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Auth flow works", function() {');
- expect(translatedCode).toContain('const response = res.getBody();');
- expect(translatedCode).toContain('expect(response.authenticated).to.be.true;');
- expect(translatedCode).toContain('bru.setEnvVar("userId", response.user.id);');
- expect(translatedCode).toContain('bru.setVar("sessionId", response.session.id);');
- });
+ const translatedCode = translateCode(code);
- it('should translate pm.test with arrow functions', () => {
- const code = `
+ expect(translatedCode).toContain('test("Auth flow works", function() {');
+ expect(translatedCode).toContain('const response = res.getBody();');
+ expect(translatedCode).toContain('expect(response.authenticated).to.be.true;');
+ expect(translatedCode).toContain('bru.setEnvVar("userId", response.user.id);');
+ expect(translatedCode).toContain('bru.setVar("sessionId", response.session.id);');
+ });
+
+ it('should translate pm.test with arrow functions', () => {
+ const code = `
pm.test("Status code is 200", () => {
pm.expect(pm.response.code).to.eql(200);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Status code is 200", () => {');
- expect(translatedCode).toContain('expect(res.getStatus()).to.eql(200);');
- });
+ const translatedCode = translateCode(code);
- it('should handle multiple test assertions in one function', () => {
- const code = `
+ expect(translatedCode).toContain('test("Status code is 200", () => {');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.eql(200);');
+ });
+
+ it('should handle multiple test assertions in one function', () => {
+ const code = `
pm.test("The response has all properties", () => {
const responseJson = pm.response.json();
pm.expect(responseJson.type).to.eql('vip');
@@ -91,18 +91,18 @@ describe('Testing Framework Translation', () => {
pm.expect(responseJson.id).to.have.lengthOf(1);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("The response has all properties", () => {');
- expect(translatedCode).toContain('const responseJson = res.getBody();');
- expect(translatedCode).toContain('expect(responseJson.type).to.eql(\'vip\');');
- expect(translatedCode).toContain('expect(responseJson.name).to.be.a(\'string\');');
- expect(translatedCode).toContain('expect(responseJson.id).to.have.lengthOf(1);');
- });
+ const translatedCode = translateCode(code);
- // Test with aliased variables
- it('should translate aliases within test functions', () => {
- const code = `
+ expect(translatedCode).toContain('test("The response has all properties", () => {');
+ expect(translatedCode).toContain('const responseJson = res.getBody();');
+ expect(translatedCode).toContain('expect(responseJson.type).to.eql(\'vip\');');
+ expect(translatedCode).toContain('expect(responseJson.name).to.be.a(\'string\');');
+ expect(translatedCode).toContain('expect(responseJson.id).to.have.lengthOf(1);');
+ });
+
+ // Test with aliased variables
+ it('should translate aliases within test functions', () => {
+ const code = `
const tempRes = pm.response;
const tempTest = pm.test;
const tempExpect = pm.expect;
@@ -111,18 +111,18 @@ describe('Testing Framework Translation', () => {
tempExpect(tempRes.code).to.equal(200);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).not.toContain('const tempRes = pm.response;');
- expect(translatedCode).not.toContain('const tempTest = pm.test;');
- expect(translatedCode).not.toContain('const tempExpect = pm.expect;');
- expect(translatedCode).toContain('test("Status code is 200", function() {');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
- });
+ const translatedCode = translateCode(code);
- // Additional robust tests for testing framework
- it('should handle nested test functions', () => {
- const code = `
+ expect(translatedCode).not.toContain('const tempRes = pm.response;');
+ expect(translatedCode).not.toContain('const tempTest = pm.test;');
+ expect(translatedCode).not.toContain('const tempExpect = pm.expect;');
+ expect(translatedCode).toContain('test("Status code is 200", function() {');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
+ });
+
+ // Additional robust tests for testing framework
+ it('should handle nested test functions', () => {
+ const code = `
pm.test("Main test group", function() {
const responseJson = pm.response.json();
@@ -137,18 +137,18 @@ describe('Testing Framework Translation', () => {
});
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Main test group", function() {');
- expect(translatedCode).toContain('const responseJson = res.getBody();');
- expect(translatedCode).toContain('test("User data validation", function() {');
- expect(translatedCode).toContain('expect(responseJson.user).to.be.an(\'object\');');
- expect(translatedCode).toContain('test("Settings validation", function() {');
- expect(translatedCode).toContain('expect(responseJson.settings.notifications).to.be.a(\'boolean\');');
- });
+ const translatedCode = translateCode(code);
- it('should handle test with dynamic test names', () => {
- const code = `
+ expect(translatedCode).toContain('test("Main test group", function() {');
+ expect(translatedCode).toContain('const responseJson = res.getBody();');
+ expect(translatedCode).toContain('test("User data validation", function() {');
+ expect(translatedCode).toContain('expect(responseJson.user).to.be.an(\'object\');');
+ expect(translatedCode).toContain('test("Settings validation", function() {');
+ expect(translatedCode).toContain('expect(responseJson.settings.notifications).to.be.a(\'boolean\');');
+ });
+
+ it('should handle test with dynamic test names', () => {
+ const code = `
const endpoint = pm.variables.get("currentEndpoint");
pm.test(\`\${endpoint} returns correct data\`, function() {
@@ -156,16 +156,16 @@ describe('Testing Framework Translation', () => {
pm.expect(responseJson).to.be.an('object');
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const endpoint = bru.getVar("currentEndpoint");');
- expect(translatedCode).toContain('test(`${endpoint} returns correct data`, function() {');
- expect(translatedCode).toContain('const responseJson = res.getBody();');
- expect(translatedCode).toContain('expect(responseJson).to.be.an(\'object\');');
- });
+ const translatedCode = translateCode(code);
- it('should handle test with conditional execution', () => {
- const code = `
+ expect(translatedCode).toContain('const endpoint = bru.getVar("currentEndpoint");');
+ expect(translatedCode).toContain('test(`${endpoint} returns correct data`, function() {');
+ expect(translatedCode).toContain('const responseJson = res.getBody();');
+ expect(translatedCode).toContain('expect(responseJson).to.be.an(\'object\');');
+ });
+
+ it('should handle test with conditional execution', () => {
+ const code = `
const responseJson = pm.response.json();
if (responseJson.type === 'user') {
@@ -180,19 +180,19 @@ describe('Testing Framework Translation', () => {
});
}
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const responseJson = res.getBody();');
- expect(translatedCode).toContain('if (responseJson.type === \'user\') {');
- expect(translatedCode).toContain('test("User validation", function() {');
- expect(translatedCode).toContain('expect(responseJson.name).to.be.a(\'string\');');
- expect(translatedCode).toContain('} else if (responseJson.type === \'admin\') {');
- expect(translatedCode).toContain('test("Admin validation", function() {');
- expect(translatedCode).toContain('expect(responseJson.accessLevel).to.be.above(5);');
- });
+ const translatedCode = translateCode(code);
- it('should handle assertions with logical operators', () => {
- const code = `
+ expect(translatedCode).toContain('const responseJson = res.getBody();');
+ expect(translatedCode).toContain('if (responseJson.type === \'user\') {');
+ expect(translatedCode).toContain('test("User validation", function() {');
+ expect(translatedCode).toContain('expect(responseJson.name).to.be.a(\'string\');');
+ expect(translatedCode).toContain('} else if (responseJson.type === \'admin\') {');
+ expect(translatedCode).toContain('test("Admin validation", function() {');
+ expect(translatedCode).toContain('expect(responseJson.accessLevel).to.be.above(5);');
+ });
+
+ it('should handle assertions with logical operators', () => {
+ const code = `
pm.test("Response has valid structure", function() {
const data = pm.response.json();
@@ -201,17 +201,17 @@ describe('Testing Framework Translation', () => {
pm.expect(!data.deleted).to.be.true;
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Response has valid structure", function() {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('expect(data.id && data.name).to.be.ok;');
- expect(translatedCode).toContain('expect(data.active || data.pending).to.be.true;');
- expect(translatedCode).toContain('expect(!data.deleted).to.be.true;');
- });
+ const translatedCode = translateCode(code);
- it('should handle array and object assertions', () => {
- const code = `
+ expect(translatedCode).toContain('test("Response has valid structure", function() {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('expect(data.id && data.name).to.be.ok;');
+ expect(translatedCode).toContain('expect(data.active || data.pending).to.be.true;');
+ expect(translatedCode).toContain('expect(!data.deleted).to.be.true;');
+ });
+
+ it('should handle array and object assertions', () => {
+ const code = `
pm.test("Array and object validations", function() {
const data = pm.response.json();
@@ -226,20 +226,20 @@ describe('Testing Framework Translation', () => {
pm.expect(data.user).to.include({active: true});
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Array and object validations", function() {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('expect(data.items).to.be.an(\'array\');');
- expect(translatedCode).toContain('expect(data.items).to.have.lengthOf.at.least(1);');
- expect(translatedCode).toContain('expect(data.items[0]).to.have.property(\'id\');');
- expect(translatedCode).toContain('expect(data.user).to.be.an(\'object\');');
- expect(translatedCode).toContain('expect(data.user).to.have.all.keys(\'id\', \'name\', \'email\');');
- expect(translatedCode).toContain('expect(data.user).to.include({active: true});');
- });
+ const translatedCode = translateCode(code);
- it('should handle chai assertions with deep equality', () => {
- const code = `
+ expect(translatedCode).toContain('test("Array and object validations", function() {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('expect(data.items).to.be.an(\'array\');');
+ expect(translatedCode).toContain('expect(data.items).to.have.lengthOf.at.least(1);');
+ expect(translatedCode).toContain('expect(data.items[0]).to.have.property(\'id\');');
+ expect(translatedCode).toContain('expect(data.user).to.be.an(\'object\');');
+ expect(translatedCode).toContain('expect(data.user).to.have.all.keys(\'id\', \'name\', \'email\');');
+ expect(translatedCode).toContain('expect(data.user).to.include({active: true});');
+ });
+
+ it('should handle chai assertions with deep equality', () => {
+ const code = `
pm.test("Deep equality checks", function() {
const data = pm.response.json();
@@ -253,20 +253,20 @@ describe('Testing Framework Translation', () => {
pm.expect(data.meta).to.deep.include({format: 'json'});
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Deep equality checks", function() {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('expect(data.config).to.deep.equal({');
- expect(translatedCode).toContain('version: "1.0",');
- expect(translatedCode).toContain('active: true,');
- expect(translatedCode).toContain('features: ["search", "export"]');
- expect(translatedCode).toContain('expect(data.tags).to.have.members([\'api\', \'test\']);');
- expect(translatedCode).toContain('expect(data.meta).to.deep.include({format: \'json\'});');
- });
+ const translatedCode = translateCode(code);
- it('should handle chai assertions with string comparisons', () => {
- const code = `
+ expect(translatedCode).toContain('test("Deep equality checks", function() {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('expect(data.config).to.deep.equal({');
+ expect(translatedCode).toContain('version: "1.0",');
+ expect(translatedCode).toContain('active: true,');
+ expect(translatedCode).toContain('features: ["search", "export"]');
+ expect(translatedCode).toContain('expect(data.tags).to.have.members([\'api\', \'test\']);');
+ expect(translatedCode).toContain('expect(data.meta).to.deep.include({format: \'json\'});');
+ });
+
+ it('should handle chai assertions with string comparisons', () => {
+ const code = `
pm.test("String validations", function() {
const data = pm.response.json();
@@ -277,19 +277,19 @@ describe('Testing Framework Translation', () => {
pm.expect(data.code).to.have.lengthOf(8);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("String validations", function() {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('expect(data.id).to.be.a(\'string\');');
- expect(translatedCode).toContain('expect(data.name).to.match(/^[A-Za-z\\s]+$/);');
- expect(translatedCode).toContain('expect(data.description).to.include(\'API\');');
- expect(translatedCode).toContain('expect(data.url).to.have.string(\'api/v1\');');
- expect(translatedCode).toContain('expect(data.code).to.have.lengthOf(8);');
- });
+ const translatedCode = translateCode(code);
- it('should handle assertions with numeric comparisons', () => {
- const code = `
+ expect(translatedCode).toContain('test("String validations", function() {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('expect(data.id).to.be.a(\'string\');');
+ expect(translatedCode).toContain('expect(data.name).to.match(/^[A-Za-z\\s]+$/);');
+ expect(translatedCode).toContain('expect(data.description).to.include(\'API\');');
+ expect(translatedCode).toContain('expect(data.url).to.have.string(\'api/v1\');');
+ expect(translatedCode).toContain('expect(data.code).to.have.lengthOf(8);');
+ });
+
+ it('should handle assertions with numeric comparisons', () => {
+ const code = `
pm.test("Numeric validations", function() {
const data = pm.response.json();
@@ -300,19 +300,19 @@ describe('Testing Framework Translation', () => {
pm.expect(data.quantity * data.price).to.equal(data.total);
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Numeric validations", function() {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('expect(data.count).to.be.a(\'number\');');
- expect(translatedCode).toContain('expect(data.count).to.be.above(0);');
- expect(translatedCode).toContain('expect(data.price).to.be.within(10, 100);');
- expect(translatedCode).toContain('expect(data.discount).to.be.at.most(25);');
- expect(translatedCode).toContain('expect(data.quantity * data.price).to.equal(data.total);');
- });
+ const translatedCode = translateCode(code);
- it('should handle pm.expect.fail with conditions', () => {
- const code = `
+ expect(translatedCode).toContain('test("Numeric validations", function() {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('expect(data.count).to.be.a(\'number\');');
+ expect(translatedCode).toContain('expect(data.count).to.be.above(0);');
+ expect(translatedCode).toContain('expect(data.price).to.be.within(10, 100);');
+ expect(translatedCode).toContain('expect(data.discount).to.be.at.most(25);');
+ expect(translatedCode).toContain('expect(data.quantity * data.price).to.equal(data.total);');
+ });
+
+ it('should handle pm.expect.fail with conditions', () => {
+ const code = `
pm.test("Validate critical fields", function() {
const data = pm.response.json();
@@ -328,19 +328,19 @@ describe('Testing Framework Translation', () => {
pm.expect(data.name).to.be.a('string');
});
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('test("Validate critical fields", function() {');
- expect(translatedCode).toContain('const data = res.getBody();');
- expect(translatedCode).toContain('if (!data.id) {');
- expect(translatedCode).toContain('expect.fail("Missing ID field");');
- expect(translatedCode).toContain('if (data.status !== \'active\' && data.status !== \'pending\') {');
- expect(translatedCode).toContain('expect.fail("Invalid status: " + data.status);');
- expect(translatedCode).toContain('expect(data.name).to.be.a(\'string\');');
- });
+ const translatedCode = translateCode(code);
- it('should handle complex test compositions', () => {
- const code = `
+ expect(translatedCode).toContain('test("Validate critical fields", function() {');
+ expect(translatedCode).toContain('const data = res.getBody();');
+ expect(translatedCode).toContain('if (!data.id) {');
+ expect(translatedCode).toContain('expect.fail("Missing ID field");');
+ expect(translatedCode).toContain('if (data.status !== \'active\' && data.status !== \'pending\') {');
+ expect(translatedCode).toContain('expect.fail("Invalid status: " + data.status);');
+ expect(translatedCode).toContain('expect(data.name).to.be.a(\'string\');');
+ });
+
+ it('should handle complex test compositions', () => {
+ const code = `
// Helper function
function validateUserObject(user) {
pm.expect(user).to.be.an('object');
@@ -384,16 +384,16 @@ describe('Testing Framework Translation', () => {
}
});
`;
- const translatedCode = translateCode(code);
-
- // Test key transformations
- expect(translatedCode).toContain('function validateUserObject(user) {');
- expect(translatedCode).toContain('expect(user).to.be.an(\'object\');');
- expect(translatedCode).toContain('test("Response validation", function() {');
- expect(translatedCode).toContain('const response = res.getBody();');
- expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
- expect(translatedCode).toContain('test("Related users validation", function() {');
- expect(translatedCode).toContain('test(`User at index ${index}`, function() {');
- expect(translatedCode).toContain('bru.setEnvVar("validUsers", JSON.stringify(validUsers));');
- });
-});
\ No newline at end of file
+ const translatedCode = translateCode(code);
+
+ // Test key transformations
+ expect(translatedCode).toContain('function validateUserObject(user) {');
+ expect(translatedCode).toContain('expect(user).to.be.an(\'object\');');
+ expect(translatedCode).toContain('test("Response validation", function() {');
+ expect(translatedCode).toContain('const response = res.getBody();');
+ expect(translatedCode).toContain('expect(res.getStatus()).to.equal(200);');
+ expect(translatedCode).toContain('test("Related users validation", function() {');
+ expect(translatedCode).toContain('test(`User at index ${index}`, function() {');
+ expect(translatedCode).toContain('bru.setEnvVar("validUsers", JSON.stringify(validUsers));');
+ });
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/transformers/send-request.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/transformers/send-request.test.js
index 68ac426d4..dadb15830 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/transformers/send-request.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/transformers/send-request.test.js
@@ -803,4 +803,4 @@ describe('Send Request Translation', () => {
`);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variable-chaining.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variable-chaining.test.js
index 3c700000e..86b987b6d 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variable-chaining.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variable-chaining.test.js
@@ -7,9 +7,9 @@ describe('Variable Chaining Resolution', () => {
const alias = original;
const data = alias.json();
`;
-
+
const translatedCode = translateCode(code);
-
+
// Check that alias.json() was properly resolved to res.getBody()
expect(translatedCode).toContain('const data = res.getBody();');
// The original variable declarations should be removed
@@ -30,26 +30,26 @@ describe('Variable Chaining Resolution', () => {
// This should not be replaced
const unrelatedVar = "some value";
`;
-
+
const translatedCode = translateCode(code);
-
+
// Check correct replacements
expect(translatedCode).not.toContain('const respVar');
expect(translatedCode).not.toContain('const envVar');
expect(translatedCode).toContain('const statusCode = res.getStatus();');
expect(translatedCode).toContain('const envValue = bru.getEnvVar("key");');
-
+
// Check that unrelated variables are preserved
expect(translatedCode).toContain('const unrelatedVar = "some value";');
});
-
+
/**
* This test verifies that when multiple variables are declared in a single statement,
* only the ones referencing Postman objects are removed and the others are preserved.
- *
+ *
* For example, in a statement like:
* const response = pm.response, counter = 5, helper = "test";
- *
+ *
* Only 'response' should be removed, resulting in:
* const counter = 5, helper = "test";
*/
@@ -67,25 +67,25 @@ describe('Variable Chaining Resolution', () => {
let env = pm.environment, timeout = 1000, isValid = true;
const baseUrl = env.get("baseUrl");
`;
-
+
const translatedCode = translateCode(code);
-
+
// Postman references should be replaced
expect(translatedCode).not.toContain('response = pm.response');
expect(translatedCode).not.toContain('env = pm.environment');
-
+
// Regular variables should be preserved
expect(translatedCode).toContain('const counter = 5');
expect(translatedCode).toContain('helper = "test"');
expect(translatedCode).toContain('timeout = 1000');
expect(translatedCode).toContain('isValid = true');
-
+
// References to Postman objects should be properly translated
expect(translatedCode).toContain('const statusCode = res.getStatus();');
expect(translatedCode).toContain('const baseUrl = bru.getEnvVar("baseUrl");');
-
+
// Console logs with regular variables should be preserved
expect(translatedCode).toContain('console.log("Counter value:", counter);');
expect(translatedCode).toContain('console.log("Helper string:", helper);');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variables.test.js b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variables.test.js
index fe0f80593..43824a0f8 100644
--- a/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variables.test.js
+++ b/packages/bruno-converters/tests/postman/postman-translations/transpiler-tests/variables.test.js
@@ -1,171 +1,171 @@
import translateCode from '../../../../src/utils/jscode-shift-translator';
describe('Variables Translation', () => {
- // Regular variables tests
- it('should translate pm.variables.get', () => {
- const code = 'pm.variables.get("test");';
- const translatedCode = translateCode(code);
+ // Regular variables tests
+ it('should translate pm.variables.get', () => {
+ const code = 'pm.variables.get("test");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.getVar("test");');
- });
+ expect(translatedCode).toBe('bru.getVar("test");');
+ });
- it('should translate pm.variables.set', () => {
- const code = 'pm.variables.set("test", "value");';
- const translatedCode = translateCode(code);
+ it('should translate pm.variables.set', () => {
+ const code = 'pm.variables.set("test", "value");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setVar("test", "value");');
- });
+ expect(translatedCode).toBe('bru.setVar("test", "value");');
+ });
- it('should translate pm.variables.has', () => {
- const code = 'pm.variables.has("userId");';
- const translatedCode = translateCode(code);
+ it('should translate pm.variables.has', () => {
+ const code = 'pm.variables.has("userId");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.hasVar("userId");');
- });
+ expect(translatedCode).toBe('bru.hasVar("userId");');
+ });
- it('should translate pm.variables.replaceIn', () => {
- const code = 'pm.variables.replaceIn("Hello {{name}}");';
- const translatedCode = translateCode(code);
+ it('should translate pm.variables.replaceIn', () => {
+ const code = 'pm.variables.replaceIn("Hello {{name}}");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.interpolate("Hello {{name}}");');
- });
+ expect(translatedCode).toBe('bru.interpolate("Hello {{name}}");');
+ });
- it('should translate pm.variables.replaceIn with variables and expressions', () => {
- const code = 'const greeting = pm.variables.replaceIn("Hello {{name}}, your user id is {{userId}}");';
- const translatedCode = translateCode(code);
+ it('should translate pm.variables.replaceIn with variables and expressions', () => {
+ const code = 'const greeting = pm.variables.replaceIn("Hello {{name}}, your user id is {{userId}}");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const greeting = bru.interpolate("Hello {{name}}, your user id is {{userId}}");');
- });
+ expect(translatedCode).toBe('const greeting = bru.interpolate("Hello {{name}}, your user id is {{userId}}");');
+ });
- it('should translate pm.variables.replaceIn within complex expressions', () => {
- const code = 'const url = baseUrl + pm.variables.replaceIn("/users/{{userId}}/profile");';
- const translatedCode = translateCode(code);
+ it('should translate pm.variables.replaceIn within complex expressions', () => {
+ const code = 'const url = baseUrl + pm.variables.replaceIn("/users/{{userId}}/profile");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const url = baseUrl + bru.interpolate("/users/{{userId}}/profile");');
- });
+ expect(translatedCode).toBe('const url = baseUrl + bru.interpolate("/users/{{userId}}/profile");');
+ });
- it('should translate pm.variables.replaceIn with multiple nested variable references', () => {
- const code = 'const template = pm.variables.replaceIn("{{prefix}}-{{env}}-{{suffix}}");';
- const translatedCode = translateCode(code);
+ it('should translate pm.variables.replaceIn with multiple nested variable references', () => {
+ const code = 'const template = pm.variables.replaceIn("{{prefix}}-{{env}}-{{suffix}}");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const template = bru.interpolate("{{prefix}}-{{env}}-{{suffix}}");');
- });
+ expect(translatedCode).toBe('const template = bru.interpolate("{{prefix}}-{{env}}-{{suffix}}");');
+ });
- it('should translate aliased variables.replaceIn', () => {
- const code = `
+ it('should translate aliased variables.replaceIn', () => {
+ const code = `
const variables = pm.variables;
const message = variables.replaceIn("Welcome, {{username}}!");
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ expect(translatedCode).toBe(`
const message = bru.interpolate("Welcome, {{username}}!");
`);
- });
+ });
- // Collection variables tests
- it('should translate pm.collectionVariables.get', () => {
- const code = 'pm.collectionVariables.get("apiUrl");';
- const translatedCode = translateCode(code);
+ // Collection variables tests
+ it('should translate pm.collectionVariables.get', () => {
+ const code = 'pm.collectionVariables.get("apiUrl");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.getVar("apiUrl");');
- });
+ expect(translatedCode).toBe('bru.getVar("apiUrl");');
+ });
- it('should translate pm.collectionVariables.set', () => {
- const code = 'pm.collectionVariables.set("token", jsonData.token);';
- const translatedCode = translateCode(code);
+ it('should translate pm.collectionVariables.set', () => {
+ const code = 'pm.collectionVariables.set("token", jsonData.token);';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setVar("token", jsonData.token);');
- });
+ expect(translatedCode).toBe('bru.setVar("token", jsonData.token);');
+ });
- it('should translate pm.collectionVariables.has', () => {
- const code = 'pm.collectionVariables.has("authToken");';
- const translatedCode = translateCode(code);
+ it('should translate pm.collectionVariables.has', () => {
+ const code = 'pm.collectionVariables.has("authToken");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.hasVar("authToken");');
- });
+ expect(translatedCode).toBe('bru.hasVar("authToken");');
+ });
- it('should translate pm.collectionVariables.unset', () => {
- const code = 'pm.collectionVariables.unset("tempVar");';
- const translatedCode = translateCode(code);
+ it('should translate pm.collectionVariables.unset', () => {
+ const code = 'pm.collectionVariables.unset("tempVar");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.deleteVar("tempVar");');
- });
+ expect(translatedCode).toBe('bru.deleteVar("tempVar");');
+ });
- it('should handle pm.globals.get', () => {
- const code = 'pm.globals.get("test");';
- const translatedCode = translateCode(code);
+ it('should handle pm.globals.get', () => {
+ const code = 'pm.globals.get("test");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.getGlobalEnvVar("test");');
- });
+ expect(translatedCode).toBe('bru.getGlobalEnvVar("test");');
+ });
- it('should handle pm.globals.set', () => {
- const code = 'pm.globals.set("test", "value");';
- const translatedCode = translateCode(code);
+ it('should handle pm.globals.set', () => {
+ const code = 'pm.globals.set("test", "value");';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('bru.setGlobalEnvVar("test", "value");');
- });
+ expect(translatedCode).toBe('bru.setGlobalEnvVar("test", "value");');
+ });
- // Alias tests for variables
- it('should handle variables aliases', () => {
- const code = `
+ // Alias tests for variables
+ it('should handle variables aliases', () => {
+ const code = `
const vars = pm.variables;
const has = vars.has("test");
const set = vars.set("test", "value");
const get = vars.get("test");
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ expect(translatedCode).toBe(`
const has = bru.hasVar("test");
const set = bru.setVar("test", "value");
const get = bru.getVar("test");
`);
- });
+ });
- // Alias tests for collection variables
- it('should handle collection variables aliases', () => {
- const code = `
+ // Alias tests for collection variables
+ it('should handle collection variables aliases', () => {
+ const code = `
const collVars = pm.collectionVariables;
const has = collVars.has("test");
const set = collVars.set("test", "value");
const get = collVars.get("test");
const unset = collVars.unset("test");
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ expect(translatedCode).toBe(`
const has = bru.hasVar("test");
const set = bru.setVar("test", "value");
const get = bru.getVar("test");
const unset = bru.deleteVar("test");
`);
- });
+ });
- it('should handle pm.globals aliases', () => {
- const code = `
+ it('should handle pm.globals aliases', () => {
+ const code = `
const globals = pm.globals;
const get = globals.get("test");
const set = globals.set("test", "value");
`;
- const translatedCode = translateCode(code);
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe(`
+ expect(translatedCode).toBe(`
const get = bru.getGlobalEnvVar("test");
const set = bru.setGlobalEnvVar("test", "value");
`);
- })
+ });
- // Combined tests
- it('should handle conditional expressions with variable calls', () => {
- const code = 'const userStatus = pm.variables.has("userId") ? "logged-in" : "guest";';
- const translatedCode = translateCode(code);
+ // Combined tests
+ it('should handle conditional expressions with variable calls', () => {
+ const code = 'const userStatus = pm.variables.has("userId") ? "logged-in" : "guest";';
+ const translatedCode = translateCode(code);
- expect(translatedCode).toBe('const userStatus = bru.hasVar("userId") ? "logged-in" : "guest";');
- });
+ expect(translatedCode).toBe('const userStatus = bru.hasVar("userId") ? "logged-in" : "guest";');
+ });
- it('should handle all variable methods together', () => {
- const code = `
+ it('should handle all variable methods together', () => {
+ const code = `
// All variable methods
const hasUserId = pm.variables.has("userId");
const userId = pm.variables.get("userId");
@@ -173,15 +173,15 @@ describe('Variables Translation', () => {
console.log(\`Has userId: \${hasUserId}, User ID: \${userId}\`);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const hasUserId = bru.hasVar("userId");');
- expect(translatedCode).toContain('const userId = bru.getVar("userId");');
- expect(translatedCode).toContain('bru.setVar("requestTime", new Date().toISOString());');
- });
+ const translatedCode = translateCode(code);
- it('should handle all collection variable methods together', () => {
- const code = `
+ expect(translatedCode).toContain('const hasUserId = bru.hasVar("userId");');
+ expect(translatedCode).toContain('const userId = bru.getVar("userId");');
+ expect(translatedCode).toContain('bru.setVar("requestTime", new Date().toISOString());');
+ });
+
+ it('should handle all collection variable methods together', () => {
+ const code = `
// All collection variable methods
const hasApiUrl = pm.collectionVariables.has("apiUrl");
const apiUrl = pm.collectionVariables.get("apiUrl");
@@ -190,18 +190,18 @@ describe('Variables Translation', () => {
console.log(\`Has API URL: \${hasApiUrl}, API URL: \${apiUrl}\`);
`;
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toContain('const hasApiUrl = bru.hasVar("apiUrl");');
- expect(translatedCode).toContain('const apiUrl = bru.getVar("apiUrl");');
- expect(translatedCode).toContain('bru.setVar("requestTime", new Date().toISOString());');
- expect(translatedCode).toContain('bru.deleteVar("tempVar");');
- });
+ const translatedCode = translateCode(code);
- it('should handle more complex nested expressions with variables', () => {
- const code = 'pm.collectionVariables.set("fullPath", pm.environment.get("baseUrl") + pm.variables.get("endpoint"));';
- const translatedCode = translateCode(code);
-
- expect(translatedCode).toBe('bru.setVar("fullPath", bru.getEnvVar("baseUrl") + bru.getVar("endpoint"));');
- });
-});
\ No newline at end of file
+ expect(translatedCode).toContain('const hasApiUrl = bru.hasVar("apiUrl");');
+ expect(translatedCode).toContain('const apiUrl = bru.getVar("apiUrl");');
+ expect(translatedCode).toContain('bru.setVar("requestTime", new Date().toISOString());');
+ expect(translatedCode).toContain('bru.deleteVar("tempVar");');
+ });
+
+ it('should handle more complex nested expressions with variables', () => {
+ const code = 'pm.collectionVariables.set("fullPath", pm.environment.get("baseUrl") + pm.variables.get("endpoint"));';
+ const translatedCode = translateCode(code);
+
+ expect(translatedCode).toBe('bru.setVar("fullPath", bru.getEnvVar("baseUrl") + bru.getVar("endpoint"));');
+ });
+});
diff --git a/packages/bruno-converters/tests/utils/getMemberExpressionString.test.js b/packages/bruno-converters/tests/utils/getMemberExpressionString.test.js
index f5dd69f09..fe1f9b5fc 100644
--- a/packages/bruno-converters/tests/utils/getMemberExpressionString.test.js
+++ b/packages/bruno-converters/tests/utils/getMemberExpressionString.test.js
@@ -12,7 +12,7 @@ describe('getMemberExpressionString', () => {
),
j.identifier('get')
);
-
+
const result = getMemberExpressionString(memberExpr);
expect(result).toBe('pm.environment.get');
});
@@ -28,7 +28,7 @@ describe('getMemberExpressionString', () => {
j.literal('get'),
true // computed
);
-
+
const result = getMemberExpressionString(memberExpr);
expect(result).toBe('pm.environment.get');
});
@@ -40,7 +40,7 @@ describe('getMemberExpressionString', () => {
j.identifier('varName'),
true // computed
);
-
+
const result = getMemberExpressionString(memberExpr);
expect(result).toBe('obj.[computed]');
});
@@ -50,4 +50,4 @@ describe('getMemberExpressionString', () => {
const result = getMemberExpressionString(identifier);
expect(result).toBe('pm');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-electron/notarize.js b/packages/bruno-electron/notarize.js
index d76c3624e..101154ae5 100644
--- a/packages/bruno-electron/notarize.js
+++ b/packages/bruno-electron/notarize.js
@@ -20,11 +20,11 @@ const notarize = async function (params) {
try {
await electron_notarize.notarize({
- appBundleId: appId,
- appPath: appPath,
- appleId: process.env.APPLE_ID,
- appleIdPassword: process.env.APPLE_ID_PASSWORD,
- ascProvider: 'W7LPPWA48L'
+ appBundleId: appId,
+ appPath: appPath,
+ appleId: process.env.APPLE_ID,
+ appleIdPassword: process.env.APPLE_ID_PASSWORD,
+ ascProvider: 'W7LPPWA48L'
});
} catch (error) {
console.error(error);
@@ -33,4 +33,4 @@ const notarize = async function (params) {
console.log(`Done notarizing ${appId}`);
};
-module.exports = notarize;
\ No newline at end of file
+module.exports = notarize;
diff --git a/packages/bruno-electron/src/app/about-bruno.js b/packages/bruno-electron/src/app/about-bruno.js
index 484a062be..63f3df566 100644
--- a/packages/bruno-electron/src/app/about-bruno.js
+++ b/packages/bruno-electron/src/app/about-bruno.js
@@ -1,4 +1,4 @@
-module.exports = function aboutBruno({version}) {
+module.exports = function aboutBruno({ version }) {
return `
@@ -173,4 +173,4 @@ module.exports = function aboutBruno({version}) {
`;
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-electron/src/app/collection-watcher.js b/packages/bruno-electron/src/app/collection-watcher.js
index aa3f5a188..c8a88dd77 100644
--- a/packages/bruno-electron/src/app/collection-watcher.js
+++ b/packages/bruno-electron/src/app/collection-watcher.js
@@ -347,7 +347,6 @@ const add = async (win, pathname, collectionUid, collectionPath, useWorkerThread
file.size = sizeInMB(fileStats?.size);
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
-
} catch (error) {
console.error(error);
} finally {
@@ -390,7 +389,7 @@ const add = async (win, pathname, collectionUid, collectionPath, useWorkerThread
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
}
- } catch(error) {
+ } catch (error) {
file.data = {
name: path.basename(pathname),
type: 'http-request'
@@ -656,10 +655,10 @@ const unlinkDir = async (win, pathname, collectionUid, collectionPath) => {
const onWatcherSetupComplete = (win, watchPath, collectionUid, watcher) => {
// Mark discovery as complete
watcher.completeCollectionDiscovery(win, collectionUid);
-
+
const UiStateSnapshotStore = new UiStateSnapshot();
const collectionsSnapshotState = UiStateSnapshotStore.getCollections();
- const collectionSnapshotState = collectionsSnapshotState?.find(c => c?.pathname == watchPath);
+ const collectionSnapshotState = collectionsSnapshotState?.find((c) => c?.pathname == watchPath);
win.webContents.send('main:hydrate-app-with-ui-state-snapshot', collectionSnapshotState);
};
@@ -674,8 +673,8 @@ class CollectionWatcher {
if (!this.loadingStates[collectionUid]) {
this.loadingStates[collectionUid] = {
isDiscovering: false, // Initial discovery phase
- isProcessing: false, // Processing discovered files
- pendingFiles: new Set(), // Files that need processing
+ isProcessing: false, // Processing discovered files
+ pendingFiles: new Set() // Files that need processing
};
}
}
@@ -683,10 +682,10 @@ class CollectionWatcher {
startCollectionDiscovery(win, collectionUid) {
this.initializeLoadingState(collectionUid);
const state = this.loadingStates[collectionUid];
-
+
state.isDiscovering = true;
state.pendingFiles.clear();
-
+
win.webContents.send('main:collection-loading-state-updated', {
collectionUid,
isLoading: true
@@ -701,10 +700,10 @@ class CollectionWatcher {
markFileAsProcessed(win, collectionUid, filepath) {
if (!this.loadingStates[collectionUid]) return;
-
+
const state = this.loadingStates[collectionUid];
state.pendingFiles.delete(filepath);
-
+
// If discovery is complete and no pending files, mark as not loading
if (!state.isDiscovering && state.pendingFiles.size === 0 && state.isProcessing) {
state.isProcessing = false;
@@ -717,10 +716,10 @@ class CollectionWatcher {
completeCollectionDiscovery(win, collectionUid) {
if (!this.loadingStates[collectionUid]) return;
-
+
const state = this.loadingStates[collectionUid];
state.isDiscovering = false;
-
+
// If there are pending files, start processing phase
if (state.pendingFiles.size > 0) {
state.isProcessing = true;
@@ -743,7 +742,7 @@ class CollectionWatcher {
}
this.initializeLoadingState(collectionUid);
-
+
this.startCollectionDiscovery(win, collectionUid);
const ignores = brunoConfig?.ignore || [];
@@ -812,7 +811,7 @@ class CollectionWatcher {
this.watchers[watchPath].close();
this.watchers[watchPath] = null;
}
-
+
if (collectionUid) {
this.cleanupLoadingState(collectionUid);
}
@@ -821,7 +820,7 @@ class CollectionWatcher {
getWatcherByItemPath(itemPath) {
const paths = Object.keys(this.watchers);
- const watcherPath = paths?.find(collectionPath => {
+ const watcherPath = paths?.find((collectionPath) => {
const absCollectionPath = path.resolve(collectionPath);
const absItemPath = path.resolve(itemPath);
@@ -837,7 +836,7 @@ class CollectionWatcher {
watcher.unwatch(itemPath);
}
}
-
+
addItemPathInWatcher(itemPath) {
const watcher = this.getWatcherByItemPath(itemPath);
if (watcher && !watcher?.has?.(itemPath)) {
diff --git a/packages/bruno-electron/src/app/menu-template.js b/packages/bruno-electron/src/app/menu-template.js
index d1eabffd7..d5d05c737 100644
--- a/packages/bruno-electron/src/app/menu-template.js
+++ b/packages/bruno-electron/src/app/menu-template.js
@@ -83,11 +83,11 @@ const template = [
width: 350,
height: 250,
webPreferences: {
- nodeIntegration: true,
- },
+ nodeIntegration: true
+ }
});
aboutWindow.removeMenu();
- aboutWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(aboutBruno({version}))}`);
+ aboutWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(aboutBruno({ version }))}`);
}
},
{ label: 'Documentation', click: () => ipcMain.emit('main:open-docs') }
diff --git a/packages/bruno-electron/src/index.js b/packages/bruno-electron/src/index.js
index b28ad6e57..fe7ebebe2 100644
--- a/packages/bruno-electron/src/index.js
+++ b/packages/bruno-electron/src/index.js
@@ -4,7 +4,7 @@ const isDev = require('electron-is-dev');
const os = require('os');
if (isDev) {
- if(!fs.existsSync(path.join(__dirname, '../../bruno-js/src/sandbox/bundle-browser-rollup.js'))) {
+ if (!fs.existsSync(path.join(__dirname, '../../bruno-js/src/sandbox/bundle-browser-rollup.js'))) {
console.log('JS Sandbox libraries have not been bundled yet');
console.log('Please run the below command \nnpm run sandbox:bundle-libraries --workspace=packages/bruno-js');
throw new Error('JS Sandbox libraries have not been bundled yet');
@@ -16,8 +16,8 @@ const { BrowserWindow, app, session, Menu, globalShortcut, ipcMain } = require('
const { setContentSecurityPolicy } = require('electron-util');
if (isDev && process.env.ELECTRON_USER_DATA_PATH) {
- console.debug("`ELECTRON_USER_DATA_PATH` found, modifying `userData` path: \n"
- + `\t${app.getPath("userData")} -> ${process.env.ELECTRON_USER_DATA_PATH}`);
+ console.debug('`ELECTRON_USER_DATA_PATH` found, modifying `userData` path: \n'
+ + `\t${app.getPath('userData')} -> ${process.env.ELECTRON_USER_DATA_PATH}`);
app.setPath('userData', process.env.ELECTRON_USER_DATA_PATH);
}
@@ -56,18 +56,18 @@ const terminalManager = new TerminalManager();
// Reference: https://content-security-policy.com/
const contentSecurityPolicy = [
- "default-src 'self'",
- "connect-src 'self' https://*.posthog.com",
- "font-src 'self' https: data:;",
- "frame-src data:",
+ 'default-src \'self\'',
+ 'connect-src \'self\' https://*.posthog.com',
+ 'font-src \'self\' https: data:;',
+ 'frame-src data:',
'script-src \'self\' \'unsafe-inline\' data:',
// this has been commented out to make oauth2 work
// "form-action 'none'",
// we make an exception and allow http for images so that
// they can be used as link in the embedded markdown editors
- "img-src 'self' blob: data: http: https:",
- "media-src 'self' blob: data: https:",
- "style-src 'self' 'unsafe-inline' https:"
+ 'img-src \'self\' blob: data: http: https:',
+ 'media-src \'self\' blob: data: https:',
+ 'style-src \'self\' \'unsafe-inline\' https:'
];
setContentSecurityPolicy(contentSecurityPolicy.join(';') + ';');
@@ -78,18 +78,17 @@ let mainWindow;
// Prepare the renderer once the app is ready
app.on('ready', async () => {
-
if (isDev) {
const { installExtension, REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer');
try {
const extensions = await installExtension([REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS], {
- loadExtensionOptions: {allowFileAccess: true},
- })
- console.log(`Added Extensions: ${extensions.map(ext => ext.name).join(", ")}`)
- await require("node:timers/promises").setTimeout(1000);
+ loadExtensionOptions: { allowFileAccess: true }
+ });
+ console.log(`Added Extensions: ${extensions.map((ext) => ext.name).join(', ')}`);
+ await require('node:timers/promises').setTimeout(1000);
session.defaultSession.getAllExtensions().map((ext) => {
console.log(`Loading Extension: ${ext.name}`);
- session.defaultSession.loadExtension(ext.path)
+ session.defaultSession.loadExtension(ext.path);
});
} catch (err) {
console.error('An error occurred while loading extensions: ', err);
@@ -140,13 +139,13 @@ app.on('ready', async () => {
console.error('Original message:', reason);
if (isDev) {
console.error(
- 'Could not connect to Next.Js dev server, is it running?' +
- ' Start the dev server using "npm run dev:web" and restart electron'
+ 'Could not connect to Next.Js dev server, is it running?'
+ + ' Start the dev server using "npm run dev:web" and restart electron'
);
} else {
console.error(
- 'If you are using an official production build: the above error is most likely a bug! ' +
- ' Please report this under: https://github.com/usebruno/bruno/issues'
+ 'If you are using an official production build: the above error is most likely a bug! '
+ + ' Please report this under: https://github.com/usebruno/bruno/issues'
);
}
});
@@ -186,20 +185,19 @@ app.on('ready', async () => {
}
return { action: 'deny' };
});
-
mainWindow.webContents.on('did-finish-load', async () => {
let ogSend = mainWindow.webContents.send;
- mainWindow.webContents.send = function(channel, ...args) {
- return ogSend.apply(this, [channel, ...args?.map(_ => {
+ mainWindow.webContents.send = function (channel, ...args) {
+ return ogSend.apply(this, [channel, ...args?.map((_) => {
// todo: replace this with @msgpack/msgpack encode/decode
return safeParseJSON(safeStringifyJSON(_));
})]);
- }
-
+ };
+
// Handle onboarding
await onboardUser(mainWindow, lastOpenedCollections);
-
+
// Send cookies list after renderer is ready
try {
cookiesStore.initializeCookies();
@@ -249,16 +247,15 @@ app.on('open-file', (event, path) => {
openCollection(mainWindow, collectionWatcher, path);
});
-
// Register the global shortcuts
app.on('browser-window-focus', () => {
// Quick fix for Electron issue #29996: https://github.com/electron/electron/issues/29996
globalShortcut.register('Ctrl+=', () => {
mainWindow.webContents.setZoomLevel(mainWindow.webContents.getZoomLevel() + 1);
});
-})
+});
// Disable global shortcuts when not focused
app.on('browser-window-blur', () => {
- globalShortcut.unregisterAll()
-})
\ No newline at end of file
+ globalShortcut.unregisterAll();
+});
diff --git a/packages/bruno-electron/src/ipc/collection.js b/packages/bruno-electron/src/ipc/collection.js
index 5c703a61c..cf64e682e 100644
--- a/packages/bruno-electron/src/ipc/collection.js
+++ b/packages/bruno-electron/src/ipc/collection.js
@@ -4,7 +4,7 @@ const fsExtra = require('fs-extra');
const os = require('os');
const path = require('path');
const { ipcMain, shell, dialog, app } = require('electron');
-const {
+const {
parseRequest,
stringifyRequest,
parseRequestViaWorker,
@@ -20,6 +20,7 @@ const { postmanToBruno } = brunoConverters;
const { cookiesStore } = require('../store/cookies');
const { parseLargeRequestWithRedaction } = require('../utils/parse');
const { wsClient } = require('../ipc/network/ws-event-handlers');
+const { hasSubDirectories } = require('../utils/filesystem');
const {
writeFile,
@@ -105,7 +106,7 @@ const validatePathIsInsideCollection = (filePath, lastOpenedCollections) => {
if (!collectionPath) {
throw new Error(`Path: ${filePath} should be inside a collection`);
}
-}
+};
const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollections) => {
// create collection
@@ -190,21 +191,23 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
await createDirectory(dirPath);
const uid = generateUidBasedOnHash(dirPath);
const format = getCollectionFormat(previousPath);
+ let brunoConfig;
if (format === 'yml') {
const content = fs.readFileSync('opencollection.yml', 'utf8');
const {
- brunoConfig,
+ brunoConfig: parsedBrunoConfig,
collectionRoot
} = parseCollection(content);
+ brunoConfig = parsedBrunoConfig;
brunoConfig.name = collectionName;
const newContent = stringifyCollection(collectionRoot, brunoConfig, { format });
await writeFile(path.join(dirPath, 'opencollection.yml'), newContent);
} else if (format === 'bru') {
const content = fs.readFileSync('bruno.json', 'utf8');
- const brunoConfig = JSON.parse(content);
+ brunoConfig = JSON.parse(content);
brunoConfig.name = collectionName;
const newContent = await stringifyJson(brunoConfig);
await writeFile(path.join(dirPath, 'bruno.json'), newContent);
@@ -614,7 +617,6 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
// rename item
ipcMain.handle('renderer:rename-item-name', async (event, { itemPath, newName, collectionPathname }) => {
try {
-
if (!fs.existsSync(itemPath)) {
throw new Error(`path: ${itemPath} does not exist`);
}
@@ -634,7 +636,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
}
};
}
-
+
const folderFileContent = await stringifyFolder(folderFileJsonContent, { format });
await writeFile(folderFilePath, folderFileContent);
@@ -689,7 +691,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
const folderFileContent = await stringifyFolder(folderFileJsonContent, { format });
await writeFile(folderFilePath, folderFileContent);
-
+
const requestFilesAtSource = await searchForRequestFiles(oldPath, collectionPathname);
for (let requestFile of requestFilesAtSource) {
@@ -746,7 +748,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
await fsExtra.copy(tempDir, oldPath);
await fsExtra.remove(tempDir);
} catch (err) {
- console.error("Failed to restore data to the old path:", err);
+ console.error('Failed to restore data to the old path:', err);
}
}
}
@@ -826,7 +828,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
ipcMain.handle('renderer:update-collection-paths', async (_, collectionPaths) => {
lastOpenedCollections.update(collectionPaths);
- })
+ });
ipcMain.handle('renderer:import-collection', async (event, collection, collectionLocation, format = 'bru') => {
try {
@@ -1058,7 +1060,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
if (fs.existsSync(targetDirname)) {
const sourceDirname = path.dirname(sourcePathname);
const pathnamesBefore = await getPaths(sourcePathname);
- const pathnamesAfter = pathnamesBefore?.map(p => p?.replace(sourceDirname, targetDirname));
+ const pathnamesAfter = pathnamesBefore?.map((p) => p?.replace(sourceDirname, targetDirname));
await copyPath(sourcePathname, targetDirname);
await removePath(sourcePathname);
// move the request uids of the previous file/folders to the new file/folder items
@@ -1185,7 +1187,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
}
});
- ipcMain.handle('renderer:get-parsed-cookie', async (event, cookieStr) => {
+ ipcMain.handle('renderer:get-parsed-cookie', async (event, cookieStr) => {
try {
return parseCookieString(cookieStr);
} catch (error) {
@@ -1393,7 +1395,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
return Promise.reject(error);
}
});
-
+
// todo: could be removed
ipcMain.handle('renderer:load-request', async (event, { collectionUid, pathname }) => {
let fileStats;
@@ -1501,10 +1503,10 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
maxFileSize
} = await getCollectionStats(collectionPathname);
- const shouldLoadCollectionAsync =
- (size > MAX_COLLECTION_SIZE_IN_MB) ||
- (filesCount > MAX_COLLECTION_FILES_COUNT) ||
- (maxFileSize > MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB);
+ const shouldLoadCollectionAsync
+ = (size > MAX_COLLECTION_SIZE_IN_MB)
+ || (filesCount > MAX_COLLECTION_FILES_COUNT)
+ || (maxFileSize > MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB);
watcher.addWatcher(mainWindow, collectionPathname, collectionUid, brunoConfig, false, shouldLoadCollectionAsync);
});
diff --git a/packages/bruno-electron/src/ipc/filesystem.js b/packages/bruno-electron/src/ipc/filesystem.js
index ecdae948f..b28b56d73 100644
--- a/packages/bruno-electron/src/ipc/filesystem.js
+++ b/packages/bruno-electron/src/ipc/filesystem.js
@@ -10,7 +10,6 @@ const {
} = require('../utils/filesystem');
const registerFilesystemIpc = (mainWindow) => {
-
ipcMain.handle('renderer:browse-directory', async (event, pathname, request) => {
try {
return await browseDirectory(mainWindow);
diff --git a/packages/bruno-electron/src/ipc/global-environments.js b/packages/bruno-electron/src/ipc/global-environments.js
index 40e6ccb7e..30c988895 100644
--- a/packages/bruno-electron/src/ipc/global-environments.js
+++ b/packages/bruno-electron/src/ipc/global-environments.js
@@ -4,7 +4,6 @@ const { globalEnvironmentsStore } = require('../store/global-environments');
const { generateUniqueName, sanitizeName } = require('../utils/filesystem');
const registerGlobalEnvironmentsIpc = (mainWindow) => {
-
// GLOBAL ENVIRONMENTS
ipcMain.handle('renderer:create-global-environment', async (event, { uid, name, variables }) => {
@@ -28,7 +27,7 @@ const registerGlobalEnvironmentsIpc = (mainWindow) => {
ipcMain.handle('renderer:save-global-environment', async (event, { environmentUid, variables }) => {
try {
- globalEnvironmentsStore.saveGlobalEnvironment({ environmentUid, variables })
+ globalEnvironmentsStore.saveGlobalEnvironment({ environmentUid, variables });
} catch (error) {
return Promise.reject(error);
}
@@ -59,4 +58,4 @@ const registerGlobalEnvironmentsIpc = (mainWindow) => {
});
};
-module.exports = registerGlobalEnvironmentsIpc;
\ No newline at end of file
+module.exports = registerGlobalEnvironmentsIpc;
diff --git a/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js b/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js
index 26e6960d7..c5580edaf 100644
--- a/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js
+++ b/packages/bruno-electron/src/ipc/network/authorize-user-in-window.js
@@ -66,7 +66,7 @@ const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalH
},
fromCache: false,
completed: true,
- requests: [], // No sub-requests in this context
+ requests: [] // No sub-requests in this context
};
// Add to mainRequests
@@ -80,14 +80,14 @@ const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalH
webSession.webRequest.onBeforeSendHeaders((details, callback) => {
const { id: requestId, requestHeaders, method, url } = details;
-
+
if (details.resourceType === 'mainFrame' && Object.keys(additionalHeaders).length > 0) {
// Add our custom headers
for (const [name, value] of Object.entries(additionalHeaders)) {
requestHeaders[name] = value;
}
}
-
+
if (currentMainRequest?.requestId === requestId) {
currentMainRequest.request = {
url,
@@ -185,7 +185,7 @@ const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalH
const urlWithHash = new URL(finalUrl);
const hash = urlWithHash.hash.substring(1); // Remove the leading #
const hashParams = new URLSearchParams(hash);
-
+
// Extract tokens from hash fragment
const implicitTokens = {
access_token: hashParams.get('access_token'),
@@ -194,7 +194,7 @@ const authorizeUserInWindow = ({ authorizeUrl, callbackUrl, session, additionalH
state: hashParams.get('state'),
scope: hashParams.get('scope')
};
-
+
return resolve({ implicitTokens, debugInfo });
} else {
// Default case - authorization code flow
diff --git a/packages/bruno-electron/src/ipc/network/axios-instance.js b/packages/bruno-electron/src/ipc/network/axios-instance.js
index 651e891da..7c59622e1 100644
--- a/packages/bruno-electron/src/ipc/network/axios-instance.js
+++ b/packages/bruno-electron/src/ipc/network/axios-instance.js
@@ -2,7 +2,7 @@ const URL = require('url');
const Socket = require('net').Socket;
const axios = require('axios');
const connectionCache = new Map(); // Cache to store checkConnection() results
-const electronApp = require("electron");
+const electronApp = require('electron');
const { setupProxyAgents } = require('../../utils/proxy-util');
const { addCookieToJar, getCookieStringForUrl } = require('../../utils/cookies');
const { preferencesUtil } = require('../../store/preferences');
@@ -12,7 +12,7 @@ const { createFormData } = require('../../utils/form-data');
const LOCAL_IPV6 = '::1';
const LOCAL_IPV4 = '127.0.0.1';
const LOCALHOST = 'localhost';
-const version = electronApp?.app?.getVersion() ?? "";
+const version = electronApp?.app?.getVersion() ?? '';
const redirectResponseCodes = [301, 302, 303, 307, 308];
const saveCookies = (url, headers) => {
@@ -29,7 +29,7 @@ const saveCookies = (url, headers) => {
}
}
}
-}
+};
const getTld = (hostname) => {
if (!hostname) {
@@ -71,11 +71,11 @@ const checkConnection = (host, port) =>
* @see https://github.com/axios/axios/issues/695
* @returns {axios.AxiosInstance}
*/
-function makeAxiosInstance({
- proxyMode = 'off',
- proxyConfig = {},
- requestMaxRedirects = 5,
- httpsAgentRequestFields = {},
+function makeAxiosInstance({
+ proxyMode = 'off',
+ proxyConfig = {},
+ requestMaxRedirects = 5,
+ httpsAgentRequestFields = {},
interpolationOptions = {}
} = {}) {
/** @type {axios.AxiosInstance} */
@@ -95,7 +95,7 @@ function makeAxiosInstance({
proxy: false,
maxRedirects: 0,
headers: {
- "User-Agent": `bruno-runtime/${version}`
+ 'User-Agent': `bruno-runtime/${version}`
}
});
@@ -112,19 +112,19 @@ function makeAxiosInstance({
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Preparing request to ${config.url}`,
+ message: `Preparing request to ${config.url}`
});
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Current time is ${new Date().toISOString()}`,
+ message: `Current time is ${new Date().toISOString()}`
});
-
+
// Add request method and headers
timeline.push({
timestamp: new Date(),
type: 'request',
- message: `${config.method.toUpperCase()} ${config.url}`,
+ message: `${config.method.toUpperCase()} ${config.url}`
});
Object.entries(config.headers).forEach(([key, value]) => {
@@ -139,17 +139,17 @@ function makeAxiosInstance({
timeline.push({
timestamp: new Date(),
type: 'requestHeader',
- message: `${key}: ${value}`,
+ message: `${key}: ${value}`
});
});
-
+
// Add request data if available
if (config.data) {
let requestData = typeof config.data === 'string' ? config.data : JSON.stringify(config.data, null, 2);
timeline.push({
timestamp: new Date(),
type: 'requestData',
- message: requestData,
+ message: requestData
});
}
@@ -171,7 +171,7 @@ function makeAxiosInstance({
const agentOptions = {
...httpsAgentRequestFields,
- keepAlive: true,
+ keepAlive: true
};
try {
@@ -182,24 +182,23 @@ function makeAxiosInstance({
proxyConfig: proxyConfig,
httpsAgentRequestFields: agentOptions,
interpolationOptions: interpolationOptions, // Provide your interpolation options
- timeline,
+ timeline
});
- }
- catch(err) {
+ } catch (err) {
if (err.timeline) {
timeline = err.timeline;
}
timeline.push({
timestamp: new Date(),
type: 'error',
- message: `Error setting up proxy agents: ${err?.message}`,
+ message: `Error setting up proxy agents: ${err?.message}`
});
}
config.metadata.timeline = timeline;
return config;
});
- let redirectCount = 0
+ let redirectCount = 0;
instance.interceptors.response.use(
(response) => {
@@ -210,7 +209,7 @@ function makeAxiosInstance({
redirectCount = 0;
const config = response.config;
- timeline = config?.metadata?.timeline || []
+ timeline = config?.metadata?.timeline || [];
const duration = end - config?.metadata.startTime;
const httpVersion = response?.request?.res?.httpVersion || response?.httpVersion;
@@ -218,27 +217,27 @@ function makeAxiosInstance({
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Using HTTP/2, server supports multiplexing`,
+ message: `Using HTTP/2, server supports multiplexing`
});
}
timeline.push({
timestamp: new Date(),
type: 'response',
- message: `HTTP/${httpVersion || '1.1'} ${response.status} ${response.statusText}`,
+ message: `HTTP/${httpVersion || '1.1'} ${response.status} ${response.statusText}`
});
Object.entries(response.headers).forEach(([key, value]) => {
timeline.push({
timestamp: new Date(),
type: 'responseHeader',
- message: `${key}: ${value}`,
+ message: `${key}: ${value}`
});
});
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Request completed in ${duration} ms`,
+ message: `Request completed in ${duration} ms`
});
response.timeline = timeline;
return response;
@@ -260,19 +259,19 @@ function makeAxiosInstance({
timeline.push({
timestamp: new Date(),
type: 'response',
- message: `HTTP/${error.response.httpVersion || '1.1'} ${error.response.status} ${error.response.statusText}`,
+ message: `HTTP/${error.response.httpVersion || '1.1'} ${error.response.status} ${error.response.statusText}`
});
Object.entries(error.response.headers).forEach(([key, value]) => {
timeline.push({
timestamp: new Date(),
type: 'responseHeader',
- message: `${key}: ${value}`,
+ message: `${key}: ${value}`
});
});
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Request completed in ${duration} ms`,
+ message: `Request completed in ${duration} ms`
});
// Attach the timeline to the response
@@ -298,11 +297,11 @@ function makeAxiosInstance({
if (locationHeader && !locationHeader.match(/^https?:\/\//i)) {
// It's a relative URL, resolve it against the original URL
redirectUrl = URL.resolve(error.config.url, locationHeader);
-
+
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Resolving relative redirect URL: ${locationHeader} โ ${redirectUrl}`,
+ message: `Resolving relative redirect URL: ${locationHeader} โ ${redirectUrl}`
});
}
@@ -315,8 +314,8 @@ function makeAxiosInstance({
...error.config,
url: redirectUrl,
headers: {
- ...error.config.headers,
- },
+ ...error.config.headers
+ }
};
// Apply proper HTTP redirect behavior based on status code
@@ -325,39 +324,38 @@ function makeAxiosInstance({
// For 301, 302, 303: change method to GET unless it was HEAD
if ([301, 302, 303].includes(statusCode) && originalMethod !== 'head') {
- requestConfig.method = 'get';
- requestConfig.data = undefined;
- delete requestConfig.headers['content-length'];
- delete requestConfig.headers['Content-Length'];
-
- delete requestConfig.headers['content-type'];
- delete requestConfig.headers['Content-Type'];
-
- timeline.push({
- timestamp: new Date(),
- type: 'info',
- message: `Changed method from ${originalMethod.toUpperCase()} to GET for ${statusCode} redirect and removed request body`,
- });
+ requestConfig.method = 'get';
+ requestConfig.data = undefined;
+ delete requestConfig.headers['content-length'];
+ delete requestConfig.headers['Content-Length'];
+
+ delete requestConfig.headers['content-type'];
+ delete requestConfig.headers['Content-Type'];
+
+ timeline.push({
+ timestamp: new Date(),
+ type: 'info',
+ message: `Changed method from ${originalMethod.toUpperCase()} to GET for ${statusCode} redirect and removed request body`
+ });
} else {
// For 307, 308 and other status codes: preserve method and body
- if (requestConfig.data && typeof requestConfig.data === 'object' &&
- requestConfig.data.constructor && requestConfig.data.constructor.name === 'FormData') {
-
+ if (requestConfig.data && typeof requestConfig.data === 'object'
+ && requestConfig.data.constructor && requestConfig.data.constructor.name === 'FormData') {
const formData = requestConfig.data;
if (formData._released || (formData._streams && formData._streams.length === 0)) {
if (error.config._originalMultipartData && error.config.collectionPath) {
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Recreating consumed FormData for ${statusCode} redirect`,
+ message: `Recreating consumed FormData for ${statusCode} redirect`
});
const recreatedForm = createFormData(error.config._originalMultipartData, error.config.collectionPath);
requestConfig.data = recreatedForm;
-
+
const formHeaders = recreatedForm.getHeaders();
Object.assign(requestConfig.headers, formHeaders);
-
+
// preserve the original data for potential future redirects
requestConfig._originalMultipartData = error.config._originalMultipartData;
requestConfig.collectionPath = error.config.collectionPath;
@@ -365,7 +363,7 @@ function makeAxiosInstance({
timeline.push({
timestamp: new Date(),
type: 'info',
- message: `FormData consumed but no original data available for ${statusCode} redirect`,
+ message: `FormData consumed but no original data available for ${statusCode} redirect`
});
}
} else {
@@ -382,7 +380,7 @@ function makeAxiosInstance({
}
}
- try {
+ try {
setupProxyAgents({
requestConfig,
proxyMode,
@@ -391,34 +389,32 @@ function makeAxiosInstance({
interpolationOptions,
timeline
});
- }
- catch(err) {
+ } catch (err) {
if (err.timeline) {
timeline = err.timeline;
}
timeline.push({
timestamp: new Date(),
type: 'error',
- message: `Error setting up proxy agents: ${err?.message}`,
+ message: `Error setting up proxy agents: ${err?.message}`
});
}
requestConfig.metadata.timeline = timeline;
// Make the redirected request
return instance(requestConfig);
- }
- else {
+ } else {
const errorResponseData = error.response.data;
timeline.push({
timestamp: new Date(),
type: 'response',
- message: `HTTP/${error.response.httpVersion || '1.1'} ${error.response.status} ${error.response.statusText}`,
+ message: `HTTP/${error.response.httpVersion || '1.1'} ${error.response.status} ${error.response.statusText}`
});
Object.entries(error?.response?.headers || {}).forEach(([key, value]) => {
timeline.push({
timestamp: new Date(),
type: 'responseHeader',
- message: `${key}: ${value}`,
+ message: `${key}: ${value}`
});
});
timeline?.push({
@@ -439,13 +435,12 @@ function makeAxiosInstance({
error.response.timeline = timeline;
return Promise.reject(error);
}
- }
- else if (error?.code) {
+ } else if (error?.code) {
Object.entries(error?.response?.headers || {}).forEach(([key, value]) => {
timeline.push({
timestamp: new Date(),
type: 'responseHeader',
- message: `${key}: ${value}`,
+ message: `${key}: ${value}`
});
});
timeline?.push({
diff --git a/packages/bruno-electron/src/ipc/network/cert-utils.js b/packages/bruno-electron/src/ipc/network/cert-utils.js
index 61f72a7f3..61038334c 100644
--- a/packages/bruno-electron/src/ipc/network/cert-utils.js
+++ b/packages/bruno-electron/src/ipc/network/cert-utils.js
@@ -30,8 +30,8 @@ const getCertsAndProxyConfig = async ({
let caCertFilePath = preferencesUtil.shouldUseCustomCaCertificate() && preferencesUtil.getCustomCaCertificateFilePath();
let caCertificatesData = getCACertificates({
- caCertFilePath,
- shouldKeepDefaultCerts: preferencesUtil.shouldKeepDefaultCaCertificates()
+ caCertFilePath,
+ shouldKeepDefaultCerts: preferencesUtil.shouldKeepDefaultCaCertificates()
});
let caCertificates = caCertificatesData.caCertificates;
@@ -92,14 +92,14 @@ const getCertsAndProxyConfig = async ({
/**
* Proxy configuration
- *
+ *
* Preferences proxyMode has three possible values: on, off, system
* Collection proxyMode has three possible values: true, false, global
- *
+ *
* When collection proxyMode is true, it overrides the app-level proxy settings
* When collection proxyMode is false, it ignores the app-level proxy settings
* When collection proxyMode is global, it uses the app-level proxy settings
- *
+ *
* Below logic calculates the proxyMode and proxyConfig to be used for the request
*/
let proxyMode = 'off';
@@ -114,8 +114,8 @@ const getCertsAndProxyConfig = async ({
proxyConfig = preferencesUtil.getGlobalProxyConfig();
proxyMode = get(proxyConfig, 'mode', 'off');
}
-
- return { proxyMode, proxyConfig, httpsAgentRequestFields, interpolationOptions };
-}
-module.exports = { getCertsAndProxyConfig };
\ No newline at end of file
+ return { proxyMode, proxyConfig, httpsAgentRequestFields, interpolationOptions };
+};
+
+module.exports = { getCertsAndProxyConfig };
diff --git a/packages/bruno-electron/src/ipc/network/grpc-event-handlers.js b/packages/bruno-electron/src/ipc/network/grpc-event-handlers.js
index 26ee77c47..5fc21ed0c 100644
--- a/packages/bruno-electron/src/ipc/network/grpc-event-handlers.js
+++ b/packages/bruno-electron/src/ipc/network/grpc-event-handlers.js
@@ -1,6 +1,6 @@
// To implement grpc event handlers
const { ipcMain, app } = require('electron');
-const { GrpcClient } = require("@usebruno/requests")
+const { GrpcClient } = require('@usebruno/requests');
const { safeParseJSON, safeStringifyJSON } = require('../../utils/common');
const { cloneDeep, get } = require('lodash');
const { preferencesUtil } = require('../../store/preferences');
@@ -16,7 +16,7 @@ let grpcClient;
* Register IPC handlers for gRPC
*/
const registerGrpcEventHandlers = (window) => {
- const sendEvent = (eventName, ...args) => {
+ const sendEvent = (eventName, ...args) => {
if (window && window.webContents) {
window.webContents.send(eventName, ...args);
} else {
@@ -25,17 +25,15 @@ const registerGrpcEventHandlers = (window) => {
};
grpcClient = new GrpcClient(sendEvent);
-
+
ipcMain.handle('connections-changed', (event) => {
sendEvent('grpc:connections-changed', event);
});
// Start a new gRPC connection
ipcMain.handle('grpc:start-connection', async (event, { request, collection, environment, runtimeVariables }) => {
-
try {
const requestCopy = cloneDeep(request);
-
const preparedRequest = await prepareGrpcRequest(requestCopy, collection, environment, runtimeVariables, {});
@@ -50,11 +48,10 @@ const registerGrpcEventHandlers = (window) => {
collectionPath: collection.pathname,
globalEnvironmentVariables: collection.globalEnvironmentVariables
});
-
// Extract certificate information from the config
const { httpsAgentRequestFields } = certsAndProxyConfig;
-
+
// Configure verify options
const verifyOptions = {
rejectUnauthorized: preferencesUtil.shouldVerifyTls()
@@ -68,17 +65,17 @@ const registerGrpcEventHandlers = (window) => {
const pfx = httpsAgentRequestFields.pfx;
const requestSent = {
- type: "request",
+ type: 'request',
url: preparedRequest.url,
method: preparedRequest.method,
methodType: preparedRequest.methodType,
headers: preparedRequest.headers,
body: preparedRequest.body,
timestamp: Date.now()
- }
+ };
// Start gRPC connection with the processed request and certificates
await grpcClient.startConnection({
- request: preparedRequest,
+ request: preparedRequest,
collection,
rootCertificate,
privateKey,
@@ -89,7 +86,7 @@ const registerGrpcEventHandlers = (window) => {
});
sendEvent('grpc:request', preparedRequest.uid, collection.uid, requestSent);
-
+
// Send OAuth credentials update if available
if (preparedRequest?.oauth2Credentials) {
window.webContents.send('main:credentials-update', {
@@ -98,7 +95,7 @@ const registerGrpcEventHandlers = (window) => {
collectionUid: collection.uid,
credentialsId: preparedRequest.oauth2Credentials?.credentialsId,
...(preparedRequest.oauth2Credentials?.folderUid ? { folderUid: preparedRequest.oauth2Credentials.folderUid } : { itemUid: preparedRequest.uid }),
- debugInfo: preparedRequest.oauth2Credentials.debugInfo,
+ debugInfo: preparedRequest.oauth2Credentials.debugInfo
});
}
@@ -171,7 +168,7 @@ const registerGrpcEventHandlers = (window) => {
try {
const requestCopy = cloneDeep(request);
const preparedRequest = await prepareGrpcRequest(requestCopy, collection, environment, runtimeVariables);
-
+
// Get certificates and proxy configuration
const certsAndProxyConfig = await getCertsAndProxyConfig({
collectionUid: collection.uid,
@@ -186,7 +183,7 @@ const registerGrpcEventHandlers = (window) => {
// Extract certificate information from the config
const { httpsAgentRequestFields } = certsAndProxyConfig;
-
+
// Configure verify options
const verifyOptions = {
rejectUnauthorized: preferencesUtil.shouldVerifyTls()
@@ -199,7 +196,6 @@ const registerGrpcEventHandlers = (window) => {
const passphrase = httpsAgentRequestFields.passphrase;
const pfx = httpsAgentRequestFields.pfx;
-
// Send OAuth credentials update if available
if (preparedRequest?.oauth2Credentials) {
window.webContents.send('main:credentials-update', {
@@ -208,24 +204,23 @@ const registerGrpcEventHandlers = (window) => {
collectionUid: collection.uid,
credentialsId: preparedRequest.oauth2Credentials?.credentialsId,
...(preparedRequest.oauth2Credentials?.folderUid ? { folderUid: preparedRequest.oauth2Credentials.folderUid } : { itemUid: preparedRequest.uid }),
- debugInfo: preparedRequest.oauth2Credentials.debugInfo,
+ debugInfo: preparedRequest.oauth2Credentials.debugInfo
});
}
-
- const methods = await grpcClient.loadMethodsFromReflection({
+ const methods = await grpcClient.loadMethodsFromReflection({
request: preparedRequest,
collectionUid: collection.uid,
- rootCertificate,
- privateKey,
- certificateChain,
+ rootCertificate,
+ privateKey,
+ certificateChain,
passphrase,
pfx,
verifyOptions,
sendEvent
});
-
- return { success: true, methods: safeParseJSON(safeStringifyJSON(methods))};
+
+ return { success: true, methods: safeParseJSON(safeStringifyJSON(methods)) };
} catch (error) {
console.error('Error loading gRPC methods from reflection:', error);
return { success: false, error: error.message };
@@ -236,7 +231,7 @@ const registerGrpcEventHandlers = (window) => {
ipcMain.handle('grpc:load-methods-proto', async (event, { filePath, includeDirs }) => {
try {
const methods = await grpcClient.loadMethodsFromProtoFile(filePath, includeDirs);
- return { success: true, methods: safeParseJSON(safeStringifyJSON(methods))};
+ return { success: true, methods: safeParseJSON(safeStringifyJSON(methods)) };
} catch (error) {
console.error('Error loading gRPC methods from proto file:', error);
return { success: false, error: error.message };
@@ -252,24 +247,24 @@ const registerGrpcEventHandlers = (window) => {
// Parse existing message if provided
existingMessage: existingMessage ? safeParseJSON(existingMessage) : null
});
-
+
if (!result.success) {
- return {
- success: false,
- error: result.error || 'Failed to generate sample message'
+ return {
+ success: false,
+ error: result.error || 'Failed to generate sample message'
};
}
-
+
// Convert the message to a JSON string for safe transfer through IPC
- return {
- success: true,
- message: JSON.stringify(result.message, null, 2)
+ return {
+ success: true,
+ message: JSON.stringify(result.message, null, 2)
};
} catch (error) {
console.error('Error generating gRPC sample message:', error);
- return {
- success: false,
- error: error.message || 'Failed to generate sample message'
+ return {
+ success: false,
+ error: error.message || 'Failed to generate sample message'
};
}
});
@@ -286,7 +281,7 @@ const registerGrpcEventHandlers = (window) => {
};
let caCertFilePath, certFilePath, keyFilePath;
- if(preferencesUtil.shouldUseCustomCaCertificate()) {
+ if (preferencesUtil.shouldUseCustomCaCertificate()) {
caCertFilePath = preferencesUtil.getCustomCaCertificateFilePath();
}
@@ -333,11 +328,11 @@ if (app && typeof app.on === 'function') {
if (grpcClient && typeof grpcClient.clearAllConnections === 'function') {
try {
grpcClient.clearAllConnections();
- } catch (error) {
- console.error('Error clearing gRPC connections:', error);
+ } catch (error) {
+ console.error('Error clearing gRPC connections:', error);
+ }
}
- }
-});
+ });
}
-module.exports = registerGrpcEventHandlers
+module.exports = registerGrpcEventHandlers;
diff --git a/packages/bruno-electron/src/ipc/network/index.js b/packages/bruno-electron/src/ipc/network/index.js
index 6a02ab366..030937b96 100644
--- a/packages/bruno-electron/src/ipc/network/index.js
+++ b/packages/bruno-electron/src/ipc/network/index.js
@@ -54,7 +54,7 @@ const saveCookies = (url, headers) => {
}
}
}
-}
+};
const getJsSandboxRuntime = (collection) => {
const securityConfig = get(collection, 'securityConfig', {});
@@ -126,7 +126,7 @@ const configureRequest = async (
// Get followRedirects setting, default to true for backward compatibility
const followRedirects = request.settings?.followRedirects ?? true;
-
+
// Get maxRedirects from request settings, fallback to request.maxRedirects, then default to 5
let requestMaxRedirects = request.settings?.maxRedirects ?? request.maxRedirects ?? 5;
@@ -153,7 +153,7 @@ const configureRequest = async (
});
if (request.ntlmConfig) {
- axiosInstance=NtlmClient(request.ntlmConfig,axiosInstance.defaults)
+ axiosInstance = NtlmClient(request.ntlmConfig, axiosInstance.defaults);
delete request.ntlmConfig;
}
@@ -168,14 +168,12 @@ const configureRequest = async (
request.oauth2Credentials = { credentials, url: oauth2Url, collectionUid, credentialsId, debugInfo, folderUid: request.oauth2Credentials?.folderUid };
if (tokenPlacement == 'header' && credentials?.access_token) {
request.headers['Authorization'] = `${tokenHeaderPrefix} ${credentials.access_token}`.trim();
- }
- else {
+ } else {
try {
const url = new URL(request.url);
url?.searchParams?.set(tokenQueryKey, credentials?.access_token);
request.url = url?.toString();
- }
- catch(error) {}
+ } catch (error) {}
}
break;
case 'implicit':
@@ -184,14 +182,12 @@ const configureRequest = async (
request.oauth2Credentials = { credentials, url: oauth2Url, collectionUid, credentialsId, debugInfo, folderUid: request.oauth2Credentials?.folderUid };
if (tokenPlacement == 'header') {
request.headers['Authorization'] = `${tokenHeaderPrefix} ${credentials?.access_token}`;
- }
- else {
+ } else {
try {
const url = new URL(request.url);
url?.searchParams?.set(tokenQueryKey, credentials?.access_token);
request.url = url?.toString();
- }
- catch(error) {}
+ } catch (error) {}
}
break;
case 'client_credentials':
@@ -200,14 +196,12 @@ const configureRequest = async (
request.oauth2Credentials = { credentials, url: oauth2Url, collectionUid, credentialsId, debugInfo, folderUid: request.oauth2Credentials?.folderUid };
if (tokenPlacement == 'header' && credentials?.access_token) {
request.headers['Authorization'] = `${tokenHeaderPrefix} ${credentials.access_token}`.trim();
- }
- else {
+ } else {
try {
const url = new URL(request.url);
url?.searchParams?.set(tokenQueryKey, credentials?.access_token);
request.url = url?.toString();
- }
- catch(error) {}
+ } catch (error) {}
}
break;
case 'password':
@@ -216,14 +210,12 @@ const configureRequest = async (
request.oauth2Credentials = { credentials, url: oauth2Url, collectionUid, credentialsId, debugInfo, folderUid: request.oauth2Credentials?.folderUid };
if (tokenPlacement == 'header' && credentials?.access_token) {
request.headers['Authorization'] = `${tokenHeaderPrefix} ${credentials.access_token}`.trim();
- }
- else {
+ } else {
try {
const url = new URL(request.url);
url?.searchParams?.set(tokenQueryKey, credentials?.access_token);
request.url = url?.toString();
- }
- catch(error) {}
+ } catch (error) {}
}
break;
}
@@ -248,28 +240,28 @@ const configureRequest = async (
const cookieString = getCookieStringForUrl(request.url);
if (cookieString && typeof cookieString === 'string' && cookieString.length) {
const existingCookieHeaderName = Object.keys(request.headers).find(
- name => name.toLowerCase() === 'cookie'
+ (name) => name.toLowerCase() === 'cookie'
);
const existingCookieString = existingCookieHeaderName ? request.headers[existingCookieHeaderName] : '';
-
+
// Helper function to parse cookies into an object
const parseCookies = (str) => str.split(';').reduce((cookies, cookie) => {
- const [name, ...rest] = cookie.split('=');
- if (name && name.trim()) {
- cookies[name.trim()] = rest.join('=').trim();
- }
- return cookies;
+ const [name, ...rest] = cookie.split('=');
+ if (name && name.trim()) {
+ cookies[name.trim()] = rest.join('=').trim();
+ }
+ return cookies;
}, {});
-
+
const mergedCookies = {
- ...parseCookies(existingCookieString),
- ...parseCookies(cookieString),
+ ...parseCookies(existingCookieString),
+ ...parseCookies(cookieString)
};
-
+
const combinedCookieString = Object.entries(mergedCookies)
- .map(([name, value]) => `${name}=${value}`)
- .join('; ');
-
+ .map(([name, value]) => `${name}=${value}`)
+ .join('; ');
+
request.headers[existingCookieHeaderName || 'Cookie'] = combinedCookieString;
}
}
@@ -388,10 +380,10 @@ const registerNetworkIpc = (mainWindow) => {
};
const notifyScriptExecution = ({
- channel, // 'main:run-request-event' | 'main:run-folder-event'
- basePayload, // request-level or runner-level identifiers
- scriptType, // 'pre-request' | 'post-response' | 'test'
- error // optional Error
+ channel, // 'main:run-request-event' | 'main:run-folder-event'
+ basePayload, // request-level or runner-level identifiers
+ scriptType, // 'pre-request' | 'post-response' | 'test'
+ error // optional Error
}) => {
mainWindow.webContents.send(channel, {
type: `${scriptType}-script-execution`,
@@ -509,7 +501,7 @@ const registerNetworkIpc = (mainWindow) => {
// run post-response script
const responseScript = get(request, 'script.res');
let scriptResult;
- const collectionName = collection?.name
+ const collectionName = collection?.name;
if (responseScript?.length) {
const scriptRuntime = new ScriptRuntime({ runtime: scriptingConfig?.runtime });
scriptResult = await scriptRuntime.runResponseScript(
@@ -566,13 +558,13 @@ const registerNetworkIpc = (mainWindow) => {
itemPathname = `${itemPathname}.${format}`;
}
const _item = cloneDeep(findItemInCollectionByPathname(collection, itemPathname));
- if(_item) {
+ if (_item) {
const res = await runRequest({ item: _item, collection, envVars, processEnvVars, runtimeVariables, runInBackground: true });
resolve(res);
}
reject(`bru.runRequest: invalid request path - ${itemPathname}`);
});
- }
+ };
!runInBackground && mainWindow.webContents.send('main:run-request-event', {
type: 'request-queued',
@@ -664,7 +656,7 @@ const registerNetworkIpc = (mainWindow) => {
data: requestData,
dataBuffer: requestDataBuffer,
timestamp: Date.now()
- }
+ };
!runInBackground && mainWindow.webContents.send('main:run-request-event', {
type: 'request-sent',
@@ -682,7 +674,7 @@ const registerNetworkIpc = (mainWindow) => {
collectionUid,
credentialsId: request?.oauth2Credentials?.credentialsId,
...(request?.oauth2Credentials?.folderUid ? { folderUid: request.oauth2Credentials.folderUid } : { itemUid: item.uid }),
- debugInfo: request?.oauth2Credentials?.debugInfo,
+ debugInfo: request?.oauth2Credentials?.debugInfo
});
}
@@ -733,7 +725,7 @@ const registerNetworkIpc = (mainWindow) => {
statusText: error.statusText,
error: error.message || ERROR_OCCURRED_WHILE_EXECUTING_REQUEST,
timeline: error.timeline
- }
+ };
}
}
@@ -922,7 +914,7 @@ const registerNetworkIpc = (mainWindow) => {
timeline: error?.timeline
};
}
- }
+ };
/**
* Extract prompt variables from a request
@@ -1021,7 +1013,7 @@ const registerNetworkIpc = (mainWindow) => {
});
// handler for fetch-gql-schema
- ipcMain.handle('fetch-gql-schema', fetchGqlSchemaHandler)
+ ipcMain.handle('fetch-gql-schema', fetchGqlSchemaHandler);
ipcMain.handle(
'renderer:run-collection-folder',
@@ -1055,13 +1047,13 @@ const registerNetworkIpc = (mainWindow) => {
itemPathname = `${itemPathname}.${format}`;
}
const _item = cloneDeep(findItemInCollectionByPathname(collection, itemPathname));
- if(_item) {
- const res = await runRequest({ item: _item, collection, envVars, processEnvVars, runtimeVariables, runInBackground: true });
+ if (_item) {
+ const res = await runRequest({ item: _item, collection, envVars, processEnvVars, runtimeVariables, runInBackground: true });
resolve(res);
}
reject(`bru.runRequest: invalid request path - ${itemPathname}`);
});
- }
+ };
if (!folder) {
folder = collection;
@@ -1088,9 +1080,8 @@ const registerNetworkIpc = (mainWindow) => {
}
});
-
// sort requests by seq property
- folderRequests = sortByNameThenSequence(folderRequests)
+ folderRequests = sortByNameThenSequence(folderRequests);
}
// Filter requests based on tags
@@ -1099,7 +1090,7 @@ const registerNetworkIpc = (mainWindow) => {
const excludeTags = tags.exclude ? tags.exclude : [];
folderRequests = folderRequests.filter(({ tags: requestTags = [], draft }) => {
requestTags = draft?.tags || requestTags || [];
- return isRequestTagsIncluded(requestTags, includeTags, excludeTags)
+ return isRequestTagsIncluded(requestTags, includeTags, excludeTags);
});
}
@@ -1261,7 +1252,7 @@ const registerNetworkIpc = (mainWindow) => {
data: requestData,
dataBuffer: requestDataBuffer,
timestamp: Date.now()
- }
+ };
// todo:
// i have no clue why electron can't send the request object
@@ -1293,7 +1284,7 @@ const registerNetworkIpc = (mainWindow) => {
collectionUid,
credentialsId: request?.oauth2Credentials?.credentialsId,
...(request?.oauth2Credentials?.folderUid ? { folderUid: request.oauth2Credentials.folderUid } : { itemUid: item.uid }),
- debugInfo: request?.oauth2Credentials?.debugInfo,
+ debugInfo: request?.oauth2Credentials?.debugInfo
});
collection.oauth2Credentials = updateCollectionOauth2Credentials({
@@ -1380,7 +1371,7 @@ const registerNetworkIpc = (mainWindow) => {
size: Buffer.byteLength(dataBuffer),
data: error.response.data,
responseTime: error.response.responseTime,
- timeline: error.response.timeline,
+ timeline: error.response.timeline
};
// if we get a response from the server, we consider it as a success
@@ -1468,7 +1459,7 @@ const registerNetworkIpc = (mainWindow) => {
}
const testFile = get(request, 'tests');
- const collectionName = collection?.name
+ const collectionName = collection?.name;
if (typeof testFile === 'string') {
let testResults = null;
let testError = null;
@@ -1490,7 +1481,7 @@ const registerNetworkIpc = (mainWindow) => {
);
} catch (error) {
testError = error;
-
+
if (error.partialResults) {
testResults = error.partialResults;
} else {
@@ -1524,7 +1515,7 @@ const registerNetworkIpc = (mainWindow) => {
mainWindow.webContents.send('main:global-environment-variables-update', {
globalEnvironmentVariables: testResults.globalEnvironmentVariables
});
-
+
collection.globalEnvironmentVariables = testResults.globalEnvironmentVariables;
notifyScriptExecution({
@@ -1553,7 +1544,7 @@ const registerNetworkIpc = (mainWindow) => {
collectionUid,
folderUid,
statusText: 'collection run was terminated!',
- runCompletionTime: new Date().toISOString(),
+ runCompletionTime: new Date().toISOString()
});
break;
}
@@ -1570,7 +1561,7 @@ const registerNetworkIpc = (mainWindow) => {
if (nextRequestIdx >= 0) {
currentRequestIndex = nextRequestIdx;
} else {
- console.error("Could not find request with name '" + nextRequestName + "'");
+ console.error('Could not find request with name \'' + nextRequestName + '\'');
currentRequestIndex++;
}
} else {
@@ -1583,10 +1574,10 @@ const registerNetworkIpc = (mainWindow) => {
type: 'testrun-ended',
collectionUid,
folderUid,
- runCompletionTime: new Date().toISOString(),
+ runCompletionTime: new Date().toISOString()
});
} catch (error) {
- console.log("error", error);
+ console.log('error', error);
deleteCancelToken(cancelTokenUid);
mainWindow.webContents.send('main:run-folder-event', {
type: 'testrun-ended',
@@ -1651,7 +1642,7 @@ const registerNetworkIpc = (mainWindow) => {
const filePath = await chooseFileToSave(mainWindow, path.join(dirPath, fileName));
if (filePath) {
const encoding = getEncodingFormat();
- const data = Buffer.from(response.dataBuffer, 'base64')
+ const data = Buffer.from(response.dataBuffer, 'base64');
if (encoding === 'utf-8') {
await writeFile(filePath, data);
} else {
@@ -1683,14 +1674,13 @@ const executeRequestOnFailHandler = async (request, error) => {
}
};
-
const registerAllNetworkIpc = (mainWindow) => {
registerNetworkIpc(mainWindow);
registerGrpcEventHandlers(mainWindow);
registerWsEventHandlers(mainWindow);
-}
+};
-module.exports = registerAllNetworkIpc
+module.exports = registerAllNetworkIpc;
module.exports.configureRequest = configureRequest;
module.exports.getCertsAndProxyConfig = getCertsAndProxyConfig;
module.exports.fetchGqlSchemaHandler = fetchGqlSchemaHandler;
diff --git a/packages/bruno-electron/src/ipc/network/interpolate-vars.js b/packages/bruno-electron/src/ipc/network/interpolate-vars.js
index bbfdb0a44..f071b6194 100644
--- a/packages/bruno-electron/src/ipc/network/interpolate-vars.js
+++ b/packages/bruno-electron/src/ipc/network/interpolate-vars.js
@@ -105,7 +105,7 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
if (typeof contentType === 'string') {
/*
- We explicitly avoid interpolating buffer values because the file content is read as a buffer object in raw body mode.
+ We explicitly avoid interpolating buffer values because the file content is read as a buffer object in raw body mode.
Even if the selected file's content type is JSON, this prevents the buffer object from being interpolated.
*/
if (contentType.includes('json') && !Buffer.isBuffer(request.data)) {
@@ -134,7 +134,7 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
} else if (contentType === 'multipart/form-data') {
if (Array.isArray(request?.data) && !(request.data instanceof FormData)) {
try {
- request.data = request?.data?.map(d => ({
+ request.data = request?.data?.map((d) => ({
...d,
value: _interpolate(d?.value)
}));
@@ -151,7 +151,7 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
if (request?.pathParams?.length) {
let url = request.url;
- const urlSearchRaw = getRawQueryString(request.url)
+ const urlSearchRaw = getRawQueryString(request.url);
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = `http://${url}`;
}
@@ -300,7 +300,7 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
if (request.oauth2.additionalParameters) {
// Interpolate authorization parameters
if (Array.isArray(request.oauth2.additionalParameters.authorization)) {
- request.oauth2.additionalParameters.authorization.forEach(param => {
+ request.oauth2.additionalParameters.authorization.forEach((param) => {
if (param && param.enabled !== false) {
param.name = _interpolate(param.name) || '';
param.value = _interpolate(param.value) || '';
@@ -310,7 +310,7 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
// Interpolate token parameters
if (Array.isArray(request.oauth2.additionalParameters.token)) {
- request.oauth2.additionalParameters.token.forEach(param => {
+ request.oauth2.additionalParameters.token.forEach((param) => {
if (param && param.enabled !== false) {
param.name = _interpolate(param.name) || '';
param.value = _interpolate(param.value) || '';
@@ -320,7 +320,7 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
// Interpolate refresh parameters
if (Array.isArray(request.oauth2.additionalParameters.refresh)) {
- request.oauth2.additionalParameters.refresh.forEach(param => {
+ request.oauth2.additionalParameters.refresh.forEach((param) => {
if (param && param.enabled !== false) {
param.name = _interpolate(param.name) || '';
param.value = _interpolate(param.value) || '';
@@ -356,10 +356,10 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
if (request.ntlmConfig) {
request.ntlmConfig.username = _interpolate(request.ntlmConfig.username) || '';
request.ntlmConfig.password = _interpolate(request.ntlmConfig.password) || '';
- request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || '';
+ request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || '';
}
- if(request?.auth) delete request.auth;
+ if (request?.auth) delete request.auth;
return request;
};
diff --git a/packages/bruno-electron/src/ipc/network/prepare-gql-introspection-request.js b/packages/bruno-electron/src/ipc/network/prepare-gql-introspection-request.js
index 158a71dc6..d4910e4ee 100644
--- a/packages/bruno-electron/src/ipc/network/prepare-gql-introspection-request.js
+++ b/packages/bruno-electron/src/ipc/network/prepare-gql-introspection-request.js
@@ -17,7 +17,7 @@ const prepareGqlIntrospectionRequest = (endpoint, resolvedVars, request, collect
url: endpoint,
headers: {
...mapHeaders(request.headers, get(collectionRoot, 'request.headers', []), resolvedVars),
- Accept: 'application/json',
+ 'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify(queryParams)
diff --git a/packages/bruno-electron/src/ipc/network/prepare-request.js b/packages/bruno-electron/src/ipc/network/prepare-request.js
index 6c451a7f1..2990f9530 100644
--- a/packages/bruno-electron/src/ipc/network/prepare-request.js
+++ b/packages/bruno-electron/src/ipc/network/prepare-request.js
@@ -310,14 +310,14 @@ const prepareRequest = async (item, collection = {}, abortController) => {
const headers = {};
let contentTypeDefined = false;
let url = request.url;
-
+
each(get(collectionRoot, 'request.headers', []), (h) => {
if (h.enabled && h.name?.toLowerCase() === 'content-type') {
contentTypeDefined = true;
return false;
}
});
-
+
const scriptFlow = collection?.brunoConfig?.scripts?.flow ?? 'sandwich';
const requestTreePath = getTreePathFromCollectionToItem(collection, item);
if (requestTreePath && requestTreePath.length > 0) {
@@ -330,7 +330,6 @@ const prepareRequest = async (item, collection = {}, abortController) => {
request.promptVariables = collection?.promptVariables || {};
}
-
each(get(request, 'headers', []), (h) => {
if (h.enabled && h.name.length > 0) {
headers[h.name] = h.value;
@@ -390,17 +389,17 @@ const prepareRequest = async (item, collection = {}, abortController) => {
if (!contentTypeDefined) {
axiosRequest.headers['content-type'] = 'application/octet-stream'; // Default headers for binary file uploads
}
-
+
const bodyFile = find(request.body.file, (param) => param.selected);
if (bodyFile) {
let { filePath, contentType } = bodyFile;
-
+
axiosRequest.headers['content-type'] = contentType;
if (filePath) {
if (!path.isAbsolute(filePath)) {
filePath = path.join(collectionPath, filePath);
}
-
+
try {
// Large files can cause "JavaScript heap out of memory" errors when loaded entirely into memory.
if (isLargeFile(filePath, STREAMING_FILE_SIZE_THRESHOLD)) {
@@ -447,7 +446,7 @@ const prepareRequest = async (item, collection = {}, abortController) => {
// if the mode is 'none' then set the content-type header to false. #1693
if (request.body.mode === 'none' && request.auth.mode !== 'awsv4') {
- if(!contentTypeDefined) {
+ if (!contentTypeDefined) {
axiosRequest.headers['content-type'] = false;
}
}
@@ -476,4 +475,4 @@ const prepareRequest = async (item, collection = {}, abortController) => {
module.exports = {
prepareRequest,
setAuthHeaders
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-electron/src/ipc/preferences.js b/packages/bruno-electron/src/ipc/preferences.js
index 3cf95c6f4..79bffbc36 100644
--- a/packages/bruno-electron/src/ipc/preferences.js
+++ b/packages/bruno-electron/src/ipc/preferences.js
@@ -19,11 +19,10 @@ const registerPreferencesIpc = (mainWindow, watcher, lastOpenedCollections) => {
// load global environments
const globalEnvironments = globalEnvironmentsStore.getGlobalEnvironments();
let activeGlobalEnvironmentUid = globalEnvironmentsStore.getActiveGlobalEnvironmentUid();
- activeGlobalEnvironmentUid = globalEnvironments?.find(env => env?.uid == activeGlobalEnvironmentUid) ? activeGlobalEnvironmentUid : null;
+ activeGlobalEnvironmentUid = globalEnvironments?.find((env) => env?.uid == activeGlobalEnvironmentUid) ? activeGlobalEnvironmentUid : null;
mainWindow.webContents.send('main:load-global-environments', { globalEnvironments, activeGlobalEnvironmentUid });
- }
- catch(error) {
- console.error("Error occured while fetching global environements!");
+ } catch (error) {
+ console.error('Error occured while fetching global environements!');
console.error(error);
}
diff --git a/packages/bruno-electron/src/store/cookies.js b/packages/bruno-electron/src/store/cookies.js
index 3b6953991..4051cc05d 100644
--- a/packages/bruno-electron/src/store/cookies.js
+++ b/packages/bruno-electron/src/store/cookies.js
@@ -57,12 +57,11 @@ class CookiesStore {
const decryptedCookies = [];
// Filter and decrypt cookies
- Object.values(cookieStore).forEach(domainCookies => {
+ Object.values(cookieStore).forEach((domainCookies) => {
if (!Array.isArray(domainCookies)) return;
- domainCookies.forEach(cookie => {
+ domainCookies.forEach((cookie) => {
try {
-
// Create cookie with decrypted value
const decryptedCookie = {
...cookie,
@@ -87,7 +86,7 @@ class CookiesStore {
try {
// Organize cookies by domain
const cookiesByDomain = {};
- cookies.cookies.forEach(cookie => {
+ cookies.cookies.forEach((cookie) => {
try {
if (!cookiesByDomain[cookie.domain]) {
cookiesByDomain[cookie.domain] = [];
@@ -152,7 +151,6 @@ class CookiesStore {
try {
const serialized = cookieJar.serializeSync();
this.setCookies(serialized);
-
} catch (err) {
console.warn('Failed to save cookie jar:', err);
} finally {
@@ -182,7 +180,6 @@ class CookiesStore {
this.#saveTimerId = null;
}, DEBOUNCE_MS);
}
-
}
// Create singleton instance
@@ -191,4 +188,4 @@ const cookiesStore = new CookiesStore();
module.exports = {
cookiesStore,
CookiesStore
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-electron/src/store/global-environments.js b/packages/bruno-electron/src/store/global-environments.js
index 981cb8de5..0bdeb6957 100644
--- a/packages/bruno-electron/src/store/global-environments.js
+++ b/packages/bruno-electron/src/store/global-environments.js
@@ -34,12 +34,12 @@ class GlobalEnvironmentsStore {
}
encryptGlobalEnvironmentVariables({ globalEnvironments }) {
- return globalEnvironments?.map(env => {
- const variables = env.variables?.map(v => ({
+ return globalEnvironments?.map((env) => {
+ const variables = env.variables?.map((v) => ({
...v,
value: v?.secret ? encryptStringSafe(v.value).value : v?.value
})) || [];
-
+
return {
...env,
variables
@@ -48,27 +48,27 @@ class GlobalEnvironmentsStore {
}
decryptGlobalEnvironmentVariables({ globalEnvironments }) {
- return globalEnvironments?.map(env => {
- const variables = env.variables?.map(v => ({
+ return globalEnvironments?.map((env) => {
+ const variables = env.variables?.map((v) => ({
...v,
value: v?.secret ? decryptStringSafe(v.value).value : v?.value
})) || [];
-
+
return {
...env,
variables
};
});
}
-
+
getGlobalEnvironments() {
let globalEnvironments = this.store.get('environments', []);
// Previously, a bug caused environment variables to be saved without a type.
// Since that issue is now fixed, this code ensures that anyone who imported
// data before the fix will have the missing types added retroactively.
- globalEnvironments?.forEach(env => {
- env?.variables?.forEach(v => {
+ globalEnvironments?.forEach((env) => {
+ env?.variables?.forEach((v) => {
if (!v.type) {
v.type = 'text';
}
@@ -99,7 +99,7 @@ class GlobalEnvironmentsStore {
addGlobalEnvironment({ uid, name, variables = [] }) {
let globalEnvironments = this.getGlobalEnvironments();
- const existingEnvironment = globalEnvironments.find(env => env?.name == name);
+ const existingEnvironment = globalEnvironments.find((env) => env?.name == name);
if (existingEnvironment) {
throw new Error('Environment with the same name already exists');
}
@@ -113,27 +113,26 @@ class GlobalEnvironmentsStore {
saveGlobalEnvironment({ environmentUid: globalEnvironmentUid, variables }) {
let globalEnvironments = this.getGlobalEnvironments();
- const environment = globalEnvironments.find(env => env?.uid == globalEnvironmentUid);
- globalEnvironments = globalEnvironments.filter(env => env?.uid !== globalEnvironmentUid);
+ const environment = globalEnvironments.find((env) => env?.uid == globalEnvironmentUid);
+ globalEnvironments = globalEnvironments.filter((env) => env?.uid !== globalEnvironmentUid);
if (environment) {
environment.variables = variables;
}
globalEnvironments.push(environment);
this.setGlobalEnvironments(globalEnvironments);
-
}
-
+
renameGlobalEnvironment({ environmentUid: globalEnvironmentUid, name }) {
let globalEnvironments = this.getGlobalEnvironments();
- const environment = globalEnvironments.find(env => env?.uid == globalEnvironmentUid);
- globalEnvironments = globalEnvironments.filter(env => env?.uid !== globalEnvironmentUid);
+ const environment = globalEnvironments.find((env) => env?.uid == globalEnvironmentUid);
+ globalEnvironments = globalEnvironments.filter((env) => env?.uid !== globalEnvironmentUid);
if (environment) {
environment.name = name;
}
globalEnvironments.push(environment);
this.setGlobalEnvironments(globalEnvironments);
}
-
+
copyGlobalEnvironment({ uid, name, variables }) {
let globalEnvironments = this.getGlobalEnvironments();
globalEnvironments.push({
@@ -143,26 +142,26 @@ class GlobalEnvironmentsStore {
});
this.setGlobalEnvironments(globalEnvironments);
}
-
+
selectGlobalEnvironment({ environmentUid: globalEnvironmentUid }) {
let globalEnvironments = this.getGlobalEnvironments();
- const environment = globalEnvironments.find(env => env?.uid == globalEnvironmentUid);
+ const environment = globalEnvironments.find((env) => env?.uid == globalEnvironmentUid);
if (environment) {
this.setActiveGlobalEnvironmentUid(globalEnvironmentUid);
} else {
this.setActiveGlobalEnvironmentUid(null);
}
}
-
+
deleteGlobalEnvironment({ environmentUid }) {
let globalEnvironments = this.getGlobalEnvironments();
let activeGlobalEnvironmentUid = this.getActiveGlobalEnvironmentUid();
- globalEnvironments = globalEnvironments.filter(env => env?.uid !== environmentUid);
+ globalEnvironments = globalEnvironments.filter((env) => env?.uid !== environmentUid);
if (environmentUid == activeGlobalEnvironmentUid) {
- this.setActiveGlobalEnvironmentUid(null);
+ this.setActiveGlobalEnvironmentUid(null);
}
this.setGlobalEnvironments(globalEnvironments);
- }
+ }
}
const globalEnvironmentsStore = new GlobalEnvironmentsStore();
diff --git a/packages/bruno-electron/src/store/last-opened-collections.js b/packages/bruno-electron/src/store/last-opened-collections.js
index 8705e9dfd..ca5423605 100644
--- a/packages/bruno-electron/src/store/last-opened-collections.js
+++ b/packages/bruno-electron/src/store/last-opened-collections.js
@@ -14,7 +14,7 @@ class LastOpenedCollections {
getAll() {
let collections = this.store.get('lastOpenedCollections') || [];
- collections = collections.map(collection => path.resolve(collection));
+ collections = collections.map((collection) => path.resolve(collection));
return collections;
}
diff --git a/packages/bruno-electron/src/store/oauth2.js b/packages/bruno-electron/src/store/oauth2.js
index d85573bc8..41522e37d 100644
--- a/packages/bruno-electron/src/store/oauth2.js
+++ b/packages/bruno-electron/src/store/oauth2.js
@@ -117,7 +117,7 @@ class Oauth2Store {
getCredentialsForCollection({ collectionUid, url, credentialsId }) {
try {
let oauth2DataForCollection = this.getOauth2DataOfCollection({ collectionUid, url });
- let credentials = oauth2DataForCollection?.credentials?.find(c => (c?.url == url) && (c?.credentialsId == credentialsId));
+ let credentials = oauth2DataForCollection?.credentials?.find((c) => (c?.url == url) && (c?.credentialsId == credentialsId));
if (!credentials?.data) return null;
const decryptionResult = decryptStringSafe(credentials?.data);
const decryptedCredentialsData = safeParseJSON(decryptionResult.value);
@@ -132,7 +132,7 @@ class Oauth2Store {
const encryptionResult = encryptStringSafe(safeStringifyJSON(credentials));
const encryptedCredentialsData = encryptionResult.value;
let oauth2DataForCollection = this.getOauth2DataOfCollection({ collectionUid, url });
- let filteredCredentials = oauth2DataForCollection?.credentials?.filter(c => (c?.url !== url) || (c?.credentialsId !== credentialsId));
+ let filteredCredentials = oauth2DataForCollection?.credentials?.filter((c) => (c?.url !== url) || (c?.credentialsId !== credentialsId));
if (!filteredCredentials) filteredCredentials = [];
filteredCredentials.push({
url,
@@ -153,7 +153,7 @@ class Oauth2Store {
clearCredentialsForCollection({ collectionUid, url, credentialsId }) {
try {
let oauth2DataForCollection = this.getOauth2DataOfCollection({ collectionUid, url });
- let filteredCredentials = oauth2DataForCollection?.credentials?.filter(c => (c?.url !== url) || (c?.credentialsId !== credentialsId));
+ let filteredCredentials = oauth2DataForCollection?.credentials?.filter((c) => (c?.url !== url) || (c?.credentialsId !== credentialsId));
let newOauth2DataForCollection = {
...oauth2DataForCollection,
credentials: filteredCredentials
diff --git a/packages/bruno-electron/src/store/ui-state-snapshot.js b/packages/bruno-electron/src/store/ui-state-snapshot.js
index a130c36de..565b952ab 100644
--- a/packages/bruno-electron/src/store/ui-state-snapshot.js
+++ b/packages/bruno-electron/src/store/ui-state-snapshot.js
@@ -19,7 +19,7 @@ class UiStateSnapshotStore {
getCollectionByPathname({ pathname }) {
let collections = this.getCollections();
- let collection = collections.find(c => c?.pathname === pathname);
+ let collection = collections.find((c) => c?.pathname === pathname);
if (!collection) {
collection = { pathname };
collections.push(collection);
@@ -32,7 +32,7 @@ class UiStateSnapshotStore {
setCollectionByPathname({ collection }) {
let collections = this.getCollections();
- collections = collections.filter(c => c?.pathname !== collection.pathname);
+ collections = collections.filter((c) => c?.pathname !== collection.pathname);
collections.push({ ...collection });
this.saveCollections(collections);
@@ -46,7 +46,7 @@ class UiStateSnapshotStore {
}
update({ type, data }) {
- switch(type) {
+ switch (type) {
case 'COLLECTION_ENVIRONMENT':
const { collectionPath, environmentName } = data;
this.updateCollectionEnvironment({ collectionPath, environmentName });
diff --git a/packages/bruno-electron/src/utils/collection-import.js b/packages/bruno-electron/src/utils/collection-import.js
index 069085452..4880b0884 100644
--- a/packages/bruno-electron/src/utils/collection-import.js
+++ b/packages/bruno-electron/src/utils/collection-import.js
@@ -11,11 +11,11 @@ const { stringifyRequestViaWorker, stringifyCollection, stringifyEnvironment, st
async function findUniqueFolderName(baseName, collectionLocation, counter = 0) {
const folderName = counter === 0 ? baseName : `${baseName} - ${counter}`;
const collectionPath = path.join(collectionLocation, sanitizeName(folderName));
-
+
if (fs.existsSync(collectionPath)) {
return findUniqueFolderName(baseName, collectionLocation, counter + 1);
}
-
+
return folderName;
}
diff --git a/packages/bruno-electron/src/utils/collection.js b/packages/bruno-electron/src/utils/collection.js
index 888e63fa4..b123736c7 100644
--- a/packages/bruno-electron/src/utils/collection.js
+++ b/packages/bruno-electron/src/utils/collection.js
@@ -87,7 +87,7 @@ const mergeVars = (collection, request, requestTreePath = []) => {
request.folderVariables = folderVariables;
request.requestVariables = requestVariables;
- if(request?.vars) {
+ if (request?.vars) {
request.vars.req = Array.from(reqVars, ([name, value]) => ({
name,
value,
@@ -254,8 +254,8 @@ const parseBruFileMeta = (data) => {
const metaContent = match[1].trim();
const lines = metaContent.replace(/\r\n/g, '\n').split('\n');
const metaJson = {};
- lines.forEach(line => {
- const [key, value] = line.split(':').map(str => str.trim());
+ lines.forEach((line) => {
+ const [key, value] = line.split(':').map((str) => str.trim());
if (key && value) {
metaJson[key] = isNaN(value) ? value : Number(value);
}
@@ -302,7 +302,7 @@ const parseBruFileMeta = (data) => {
console.error('Error reading file:', err);
return null;
}
-}
+};
// Parse YML file meta information
const parseYmlFileMeta = (data) => {
@@ -452,7 +452,7 @@ const transformRequestToSaveToFilesystem = (item) => {
if (_item.type === 'grpc-request') {
itemToSave.request.methodType = _item.request.methodType;
itemToSave.request.protoPath = _item.request.protoPath;
- delete itemToSave.request.params
+ delete itemToSave.request.params;
}
// Only process params for non-gRPC requests
@@ -489,7 +489,7 @@ const transformRequestToSaveToFilesystem = (item) => {
if (itemToSave.request.body.mode === 'grpc') {
itemToSave.request.body = {
...itemToSave.request.body,
- grpc: itemToSave.request.body.grpc.map(({name, content}, index) => ({
+ grpc: itemToSave.request.body.grpc.map(({ name, content }, index) => ({
name: name ? name : `message ${index + 1}`,
content: replaceTabsWithSpaces(content)
}))
@@ -497,7 +497,7 @@ const transformRequestToSaveToFilesystem = (item) => {
}
return itemToSave;
-}
+};
const sortCollection = (collection) => {
const items = collection.items || [];
@@ -603,7 +603,7 @@ const mergeAuth = (collection, request, requestTreePath) => {
// If request is set to inherit, use the effective auth from collection/folders
if (request.auth.mode === 'inherit') {
request.auth = effectiveAuth;
-
+
// For OAuth2, we need to handle credentials properly
if (effectiveAuth.mode === 'oauth2') {
if (lastFolderWithAuth) {
@@ -653,17 +653,17 @@ const resolveInheritedSettings = (settings) => {
return resolvedSettings;
};
-const sortByNameThenSequence = items => {
- const isSeqValid = seq => Number.isFinite(seq) && Number.isInteger(seq) && seq > 0;
+const sortByNameThenSequence = (items) => {
+ const isSeqValid = (seq) => Number.isFinite(seq) && Number.isInteger(seq) && seq > 0;
// Sort folders alphabetically by name
const alphabeticallySorted = [...items].sort((a, b) => a.name && b.name && a.name.localeCompare(b.name));
// Extract folders without 'seq'
- const withoutSeq = alphabeticallySorted.filter(f => !isSeqValid(f['seq']));
+ const withoutSeq = alphabeticallySorted.filter((f) => !isSeqValid(f['seq']));
// Extract folders with 'seq' and sort them by 'seq'
- const withSeq = alphabeticallySorted.filter(f => isSeqValid(f['seq'])).sort((a, b) => a.seq - b.seq);
+ const withSeq = alphabeticallySorted.filter((f) => isSeqValid(f['seq'])).sort((a, b) => a.seq - b.seq);
const sortedItems = withoutSeq;
@@ -682,7 +682,7 @@ const sortByNameThenSequence = items => {
const newGroup = Array.isArray(existingItem)
? [...existingItem, item]
: [existingItem, item];
-
+
withoutSeq.splice(position, 1, newGroup);
} else {
// Insert item at the specified position
@@ -718,4 +718,4 @@ module.exports = {
getFormattedCollectionOauth2Credentials,
sortByNameThenSequence,
resolveInheritedSettings
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-electron/src/utils/common.js b/packages/bruno-electron/src/utils/common.js
index 396f40752..bb8c119b4 100644
--- a/packages/bruno-electron/src/utils/common.js
+++ b/packages/bruno-electron/src/utils/common.js
@@ -32,8 +32,8 @@ const parseJson = async (obj) => {
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
- if (typeof value === "object" && value !== null) {
- if (seen.has(value)) return "[Circular]";
+ if (typeof value === 'object' && value !== null) {
+ if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
diff --git a/packages/bruno-electron/src/utils/encryption.js b/packages/bruno-electron/src/utils/encryption.js
index 54c1a7cc9..4f80f8cd5 100644
--- a/packages/bruno-electron/src/utils/encryption.js
+++ b/packages/bruno-electron/src/utils/encryption.js
@@ -67,7 +67,6 @@ function aes256Decrypt(data, passkey = null) {
}
}
-
// electron safe storage encryption and decryption functions
function safeStorageEncrypt(str) {
let encryptedStringBuffer = safeStorage.encryptString(str);
diff --git a/packages/bruno-electron/src/utils/filesystem.js b/packages/bruno-electron/src/utils/filesystem.js
index 0f105a828..f6d725e6d 100644
--- a/packages/bruno-electron/src/utils/filesystem.js
+++ b/packages/bruno-electron/src/utils/filesystem.js
@@ -40,11 +40,10 @@ const isDirectory = (dirPath) => {
const hasSubDirectories = (dir) => {
const files = fs.readdirSync(dir);
- return files.some(file => fs.statSync(path.join(dir, file)).isDirectory());
+ return files.some((file) => fs.statSync(path.join(dir, file)).isDirectory());
};
const normalizeAndResolvePath = (pathname) => {
-
if (isWSLPath(pathname)) {
return normalizeWSLPath(pathname);
}
@@ -64,8 +63,7 @@ const normalizeAndResolvePath = (pathname) => {
function isWSLPath(pathname) {
// Check if the path starts with the WSL prefix
// eg. "\\wsl.localhost\Ubuntu\home\user\bruno\collection\scripting\api\req\getHeaders.bru"
- return pathname.startsWith('\\\\') || pathname.startsWith('//') || pathname.startsWith('/wsl.localhost/') || pathname.startsWith('\\wsl.localhost');
-
+ return pathname.startsWith('\\\\') || pathname.startsWith('//') || pathname.startsWith('/wsl.localhost/') || pathname.startsWith('\\wsl.localhost');
}
function normalizeWSLPath(pathname) {
@@ -74,11 +72,10 @@ function normalizeWSLPath(pathname) {
return pathname.replace(/^\/wsl.localhost/, '\\\\wsl.localhost').replace(/\//g, '\\');
}
-
const writeFile = async (pathname, content, isBinary = false) => {
try {
await safeWriteFile(pathname, content, {
- encoding: !isBinary ? "utf-8" : null
+ encoding: !isBinary ? 'utf-8' : null
});
} catch (err) {
console.error(`Error writing file at ${pathname}:`, err);
@@ -230,23 +227,22 @@ const getCollectionFormat = (collectionPath) => {
};
const validateName = (name) => {
- const invalidCharacters = /[<>:"/\\|?*\x00-\x1F]/g; // keeping this for informational purpose
- const reservedDeviceNames = /^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$/i;
- const firstCharacter = /^[^\s\-<>:"/\\|?*\x00-\x1F]/; // no space, hyphen and `invalidCharacters`
- const middleCharacters = /^[^<>:"/\\|?*\x00-\x1F]*$/; // no `invalidCharacters`
- const lastCharacter = /[^.\s<>:"/\\|?*\x00-\x1F]$/; // no dot, space and `invalidCharacters`
- if (name.length > 255) return false; // max name length
+ const invalidCharacters = /[<>:"/\\|?*\x00-\x1F]/g; // keeping this for informational purpose
+ const reservedDeviceNames = /^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$/i;
+ const firstCharacter = /^[^\s\-<>:"/\\|?*\x00-\x1F]/; // no space, hyphen and `invalidCharacters`
+ const middleCharacters = /^[^<>:"/\\|?*\x00-\x1F]*$/; // no `invalidCharacters`
+ const lastCharacter = /[^.\s<>:"/\\|?*\x00-\x1F]$/; // no dot, space and `invalidCharacters`
+ if (name.length > 255) return false; // max name length
- if (reservedDeviceNames.test(name)) return false; // windows reserved names
+ if (reservedDeviceNames.test(name)) return false; // windows reserved names
- return (
- firstCharacter.test(name) &&
- middleCharacters.test(name) &&
- lastCharacter.test(name)
- );
+ return (
+ firstCharacter.test(name)
+ && middleCharacters.test(name)
+ && lastCharacter.test(name)
+ );
};
-
const safeToRename = (oldPath, newPath) => {
try {
// If the new path doesn't exist, it's safe to rename
@@ -309,11 +305,11 @@ const getCollectionStats = async (directoryPath) => {
maxFileSize = sizeInMB(maxFileSize);
return { size, filesCount, maxFileSize };
-}
+};
const sizeInMB = (size) => {
return size / (1024 * 1024);
-}
+};
const getSafePathToWrite = (filePath) => {
const MAX_FILENAME_LENGTH = 255; // Common limit on most filesystems
@@ -321,12 +317,12 @@ const getSafePathToWrite = (filePath) => {
let ext = path.extname(filePath);
let base = path.basename(filePath, ext);
if (base.length + ext.length > MAX_FILENAME_LENGTH) {
- base = sanitizeName(base);
- base = base.slice(0, MAX_FILENAME_LENGTH - ext.length);
+ base = sanitizeName(base);
+ base = base.slice(0, MAX_FILENAME_LENGTH - ext.length);
}
let safePath = path.join(dir, base + ext);
return safePath;
-}
+};
async function safeWriteFile(filePath, data, options) {
const safePath = getSafePathToWrite(filePath);
@@ -353,7 +349,7 @@ const copyPath = async (source, destination) => {
if (targetPathExists) {
throw new Error(`Cannot copy, ${path.basename(source)} already exists in ${path.basename(destination)}`);
}
-
+
const copy = async (source, destination) => {
const stat = await fsPromises.lstat(source);
if (stat.isDirectory()) {
@@ -367,10 +363,10 @@ const copyPath = async (source, destination) => {
} else {
await fsPromises.copyFile(source, destination);
}
- }
+ };
await copy(source, targetPath);
-}
+};
// Recursively removes a source .
const removePath = async (source) => {
@@ -385,7 +381,7 @@ const removePath = async (source) => {
} else {
await fsPromises.unlink(source);
}
-}
+};
// Recursively gets paths.
const getPaths = async (source) => {
@@ -400,10 +396,10 @@ const getPaths = async (source) => {
await _getPaths(entryPath);
}
}
- }
+ };
await _getPaths(source);
return paths;
-}
+};
/**
* Checks if a file is larger than a given threshold.
diff --git a/packages/bruno-electron/src/utils/oauth2.js b/packages/bruno-electron/src/utils/oauth2.js
index cf33efc15..9d512de6b 100644
--- a/packages/bruno-electron/src/utils/oauth2.js
+++ b/packages/bruno-electron/src/utils/oauth2.js
@@ -12,7 +12,7 @@ const persistOauth2Credentials = ({ collectionUid, url, credentials, credentials
if (credentials?.error || !credentials?.access_token) return;
const enhancedCredentials = {
...credentials,
- created_at: Date.now(),
+ created_at: Date.now()
};
oauth2Store.updateCredentialsForCollection({ collectionUid, url, credentials: enhancedCredentials, credentialsId });
};
@@ -25,8 +25,7 @@ const getStoredOauth2Credentials = ({ collectionUid, url, credentialsId }) => {
try {
const credentials = oauth2Store.getCredentialsForCollection({ collectionUid, url, credentialsId });
return credentials;
- }
- catch (error) {
+ } catch (error) {
return null;
}
};
@@ -44,7 +43,7 @@ const isTokenExpired = (credentials) => {
const safeParseJSONBuffer = (data) => {
return safeParseJSON(Buffer.isBuffer(data) ? data.toString() : data);
-}
+};
const getCredentialsFromTokenUrl = async ({ requestConfig, certsAndProxyConfig }) => {
const { proxyMode, proxyConfig, httpsAgentRequestFields, interpolationOptions } = certsAndProxyConfig;
@@ -70,14 +69,13 @@ const getCredentialsFromTokenUrl = async ({ requestConfig, certsAndProxyConfig }
statusText: responseStatusText,
timeline
}
- }
- }
- catch (error) {
+ };
+ } catch (error) {
if (error.response) {
const { response, config } = error;
const { url: responseUrl, headers: responseHeaders, status: responseStatus, statusText: responseStatusText, data: responseData, timeline } = response || {};
const { url: requestUrl, headers: requestHeaders, data: requestData } = config || {};
- const errorResponseData = safeStringifyJSON(safeParseJSONBuffer(responseData))
+ const errorResponseData = safeStringifyJSON(safeParseJSONBuffer(responseData));
requestDetails = {
request: {
url: requestUrl,
@@ -96,8 +94,7 @@ const getCredentialsFromTokenUrl = async ({ requestConfig, certsAndProxyConfig }
timestamp: Date.now()
}
};
- }
- else if (error?.code) {
+ } else if (error?.code) {
// error.config is not available here
const { url: requestUrl, headers: requestHeaders, data: requestData } = requestConfig;
requestDetails = {
@@ -123,11 +120,11 @@ const getCredentialsFromTokenUrl = async ({ requestConfig, certsAndProxyConfig }
requestId: Date.now().toString(),
fromCache: false,
completed: true,
- requests: [], // No sub-requests in this context
+ requests: [] // No sub-requests in this context
};
return { credentials: parsedResponseData, requestDetails };
-}
+};
// AUTHORIZATION CODE
@@ -148,10 +145,10 @@ const getOAuth2TokenUsingAuthorizationCode = async ({ request, collectionUid, fo
credentialsId,
autoRefreshToken,
autoFetchToken,
- additionalParameters,
+ additionalParameters
} = oAuth;
const url = requestCopy?.oauth2?.accessTokenUrl;
-
+
// Validate required fields
if (!authorizationUrl) {
return {
@@ -249,20 +246,20 @@ const getOAuth2TokenUsingAuthorizationCode = async ({ request, collectionUid, fo
axiosRequestConfig.method = 'POST';
axiosRequestConfig.headers = {
'content-type': 'application/x-www-form-urlencoded',
- 'Accept': 'application/json',
+ 'Accept': 'application/json'
};
- if (credentialsPlacement === "basic_auth_header") {
+ if (credentialsPlacement === 'basic_auth_header') {
axiosRequestConfig.headers['Authorization'] = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;
}
const data = {
grant_type: 'authorization_code',
code: authorizationCode,
- redirect_uri: callbackUrl,
+ redirect_uri: callbackUrl
};
- if (credentialsPlacement !== "basic_auth_header") {
+ if (credentialsPlacement !== 'basic_auth_header') {
data.client_id = clientId;
}
- if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== "basic_auth_header") {
+ if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== 'basic_auth_header') {
data.client_secret = clientSecret;
}
if (pkce) {
@@ -316,7 +313,7 @@ const getOAuth2AuthorizationCode = (request, codeChallenge, collectionUid) => {
authorizationUrlWithQueryParams.searchParams.append('state', state);
}
if (additionalParameters?.authorization?.length) {
- additionalParameters.authorization.forEach(param => {
+ additionalParameters.authorization.forEach((param) => {
if (param.enabled && param.name) {
if (param.sendIn === 'queryparams') {
authorizationUrlWithQueryParams.searchParams.append(param.name, param.value || '');
@@ -324,7 +321,7 @@ const getOAuth2AuthorizationCode = (request, codeChallenge, collectionUid) => {
}
});
}
-
+
try {
const authorizeUrl = authorizationUrlWithQueryParams.toString();
const { authorizationCode, debugInfo } = await authorizeUserInWindow({
@@ -344,14 +341,14 @@ const getAdditionalHeaders = (params) => {
if (!params || !params.length) {
return {};
}
-
+
const headers = {};
- params.forEach(param => {
+ params.forEach((param) => {
if (param.enabled && param.name && param.sendIn === 'headers') {
headers[param.name] = param.value || '';
}
});
-
+
return headers;
};
@@ -368,7 +365,7 @@ const getOAuth2TokenUsingClientCredentials = async ({ request, collectionUid, fo
credentialsId,
autoRefreshToken,
autoFetchToken,
- additionalParameters,
+ additionalParameters
} = oAuth;
const url = requestCopy?.oauth2?.accessTokenUrl;
@@ -448,18 +445,18 @@ const getOAuth2TokenUsingClientCredentials = async ({ request, collectionUid, fo
axiosRequestConfig.method = 'POST';
axiosRequestConfig.headers = {
'content-type': 'application/x-www-form-urlencoded',
- 'Accept': 'application/json',
+ 'Accept': 'application/json'
};
- if (credentialsPlacement === "basic_auth_header" && clientSecret && clientSecret.trim() !== '') {
+ if (credentialsPlacement === 'basic_auth_header' && clientSecret && clientSecret.trim() !== '') {
axiosRequestConfig.headers['Authorization'] = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;
}
const data = {
- grant_type: 'client_credentials',
+ grant_type: 'client_credentials'
};
- if (credentialsPlacement !== "basic_auth_header") {
+ if (credentialsPlacement !== 'basic_auth_header') {
data.client_id = clientId;
}
- if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== "basic_auth_header") {
+ if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== 'basic_auth_header') {
data.client_secret = clientSecret;
}
if (scope && scope.trim() !== '') {
@@ -497,7 +494,7 @@ const getOAuth2TokenUsingPasswordCredentials = async ({ request, collectionUid,
credentialsId,
autoRefreshToken,
autoFetchToken,
- additionalParameters,
+ additionalParameters
} = oAuth;
const url = requestCopy?.oauth2?.accessTokenUrl;
@@ -595,20 +592,20 @@ const getOAuth2TokenUsingPasswordCredentials = async ({ request, collectionUid,
axiosRequestConfig.method = 'POST';
axiosRequestConfig.headers = {
'content-type': 'application/x-www-form-urlencoded',
- 'Accept': 'application/json',
+ 'Accept': 'application/json'
};
- if (credentialsPlacement === "basic_auth_header" && clientSecret && clientSecret.trim() !== '') {
+ if (credentialsPlacement === 'basic_auth_header' && clientSecret && clientSecret.trim() !== '') {
axiosRequestConfig.headers['Authorization'] = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;
}
const data = {
grant_type: 'password',
username,
- password,
+ password
};
- if (credentialsPlacement !== "basic_auth_header") {
+ if (credentialsPlacement !== 'basic_auth_header') {
data.client_id = clientId;
}
- if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== "basic_auth_header") {
+ if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== 'basic_auth_header') {
data.client_secret = clientSecret;
}
if (scope && scope.trim() !== '') {
@@ -644,12 +641,12 @@ const refreshOauth2Token = async ({ requestCopy, collectionUid, certsAndProxyCon
} else {
const data = {
grant_type: 'refresh_token',
- refresh_token: credentials.refresh_token,
+ refresh_token: credentials.refresh_token
};
- if (credentialsPlacement !== "basic_auth_header") {
+ if (credentialsPlacement !== 'basic_auth_header') {
data.client_id = clientId;
}
- if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== "basic_auth_header") {
+ if (clientSecret && clientSecret.trim() !== '' && credentialsPlacement !== 'basic_auth_header') {
data.client_secret = clientSecret;
}
let axiosRequestConfig = {};
@@ -658,7 +655,7 @@ const refreshOauth2Token = async ({ requestCopy, collectionUid, certsAndProxyCon
'content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
};
- if (credentialsPlacement === "basic_auth_header") {
+ if (credentialsPlacement === 'basic_auth_header') {
axiosRequestConfig.headers['Authorization'] = `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`;
}
axiosRequestConfig.url = url;
@@ -703,7 +700,7 @@ const generateCodeChallenge = (codeVerifier) => {
// Apply additional parameters to a request
const applyAdditionalParameters = (requestCopy, data, params = []) => {
- params.forEach(param => {
+ params.forEach((param) => {
if (!param.enabled || !param.name) {
return;
}
@@ -718,8 +715,7 @@ const applyAdditionalParameters = (requestCopy, data, params = []) => {
let url = new URL(requestCopy.url);
url.searchParams.append(param.name, param.value || '');
requestCopy.url = url.href;
- }
- catch (error) {
+ } catch (error) {
console.error('invalid token/refresh url', requestCopy.url);
}
break;
@@ -729,7 +725,7 @@ const applyAdditionalParameters = (requestCopy, data, params = []) => {
break;
}
});
-}
+};
const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceFetch = false }) => {
const { oauth2 = {} } = request;
@@ -766,21 +762,21 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
// Check if we already have valid credentials
if (!forceFetch) {
try {
- const storedCredentials = getStoredOauth2Credentials({
- collectionUid,
- url: authorizationUrl,
- credentialsId
+ const storedCredentials = getStoredOauth2Credentials({
+ collectionUid,
+ url: authorizationUrl,
+ credentialsId
});
-
+
if (storedCredentials) {
// Token exists
if (!isTokenExpired(storedCredentials)) {
// Token is valid, use it
- return {
+ return {
collectionUid,
- credentials: storedCredentials,
- url: authorizationUrl,
- credentialsId
+ credentials: storedCredentials,
+ url: authorizationUrl,
+ credentialsId
};
} else {
// Token is expired - unlike other grant types, implicit flow doesn't support refresh tokens
@@ -789,11 +785,11 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
clearOauth2Credentials({ collectionUid, url: authorizationUrl, credentialsId });
} else {
// Proceed with expired token
- return {
+ return {
collectionUid,
- credentials: storedCredentials,
- url: authorizationUrl,
- credentialsId
+ credentials: storedCredentials,
+ url: authorizationUrl,
+ credentialsId
};
}
}
@@ -801,11 +797,11 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
// No stored credentials
if (!autoFetchToken) {
// Don't fetch token if autoFetchToken is disabled
- return {
+ return {
collectionUid,
- credentials: null,
- url: authorizationUrl,
- credentialsId
+ credentials: null,
+ url: authorizationUrl,
+ credentialsId
};
}
// Otherwise proceed to fetch new token
@@ -827,7 +823,7 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
authorizationUrlWithQueryParams.searchParams.append('state', state);
}
if (additionalParameters?.authorization?.length) {
- additionalParameters.authorization.forEach(param => {
+ additionalParameters.authorization.forEach((param) => {
if (param.enabled && param.name) {
if (param.sendIn === 'queryparams') {
authorizationUrlWithQueryParams.searchParams.append(param.name, param.value || '');
@@ -837,7 +833,7 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
}
const authorizeUrl = authorizationUrlWithQueryParams.toString();
-
+
try {
const { implicitTokens, debugInfo } = await authorizeUserInWindow({
authorizeUrl,
@@ -856,7 +852,7 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
debugInfo
};
}
-
+
const credentials = {
access_token: implicitTokens.access_token,
token_type: implicitTokens.token_type || 'Bearer',
@@ -876,7 +872,7 @@ const getOAuth2TokenUsingImplicitGrant = async ({ request, collectionUid, forceF
credentials,
credentialsId
});
-
+
return {
collectionUid,
credentials,
diff --git a/packages/bruno-electron/src/utils/parse.js b/packages/bruno-electron/src/utils/parse.js
index 655b9e6f7..d8aacfa5a 100644
--- a/packages/bruno-electron/src/utils/parse.js
+++ b/packages/bruno-electron/src/utils/parse.js
@@ -39,4 +39,4 @@ async function parseLargeRequestWithRedaction(bruContent) {
return parsedData;
}
-module.exports = { parseLargeRequestWithRedaction };
\ No newline at end of file
+module.exports = { parseLargeRequestWithRedaction };
diff --git a/packages/bruno-electron/src/utils/proxy-util.js b/packages/bruno-electron/src/utils/proxy-util.js
index dd42541fb..dacbfa98f 100644
--- a/packages/bruno-electron/src/utils/proxy-util.js
+++ b/packages/bruno-electron/src/utils/proxy-util.js
@@ -87,7 +87,6 @@ class PatchedHttpsProxyAgent extends HttpsProxyAgent {
function createTimelineAgentClass(BaseAgentClass) {
return class extends BaseAgentClass {
constructor(options, timeline) {
-
let caCertificatesCount = options.caCertificatesCount || {};
delete options.caCertificatesCount;
@@ -97,7 +96,7 @@ function createTimelineAgentClass(BaseAgentClass) {
// Ensure TLS options are properly set
const tlsOptions = {
...agentOptions,
- rejectUnauthorized: agentOptions.rejectUnauthorized ?? true,
+ rejectUnauthorized: agentOptions.rejectUnauthorized ?? true
};
super(proxyUri, tlsOptions);
this.timeline = Array.isArray(timeline) ? timeline : [];
@@ -108,20 +107,20 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'info',
- message: `SSL validation: ${tlsOptions.rejectUnauthorized ? 'enabled' : 'disabled'}`,
+ message: `SSL validation: ${tlsOptions.rejectUnauthorized ? 'enabled' : 'disabled'}`
});
// Log the proxy details
this.timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Using proxy: ${proxyUri}`,
+ message: `Using proxy: ${proxyUri}`
});
} else {
// This is a regular HTTPS agent case
const tlsOptions = {
...options,
- rejectUnauthorized: options.rejectUnauthorized ?? true,
+ rejectUnauthorized: options.rejectUnauthorized ?? true
};
super(tlsOptions);
this.timeline = Array.isArray(timeline) ? timeline : [];
@@ -132,14 +131,13 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'info',
- message: `SSL validation: ${tlsOptions.rejectUnauthorized ? 'enabled' : 'disabled'}`,
+ message: `SSL validation: ${tlsOptions.rejectUnauthorized ? 'enabled' : 'disabled'}`
});
}
this.caCertificatesCount = caCertificatesCount;
}
-
createConnection(options, callback) {
const { host, port } = options;
@@ -148,7 +146,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: `ALPN: offers ${this.alpnProtocols.join(', ')}`,
+ message: `ALPN: offers ${this.alpnProtocols.join(', ')}`
});
}
@@ -160,14 +158,14 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: `CA Certificates: ${rootCerts} root, ${systemCerts} system, ${extraCerts} extra, ${customCerts} custom`,
+ message: `CA Certificates: ${rootCerts} root, ${systemCerts} system, ${extraCerts} extra, ${customCerts} custom`
});
// Log "Trying host:port..."
this.timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Trying ${host}:${port}...`,
+ message: `Trying ${host}:${port}...`
});
let socket;
@@ -177,7 +175,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'error',
- message: `Error creating connection: ${error.message}`,
+ message: `Error creating connection: ${error.message}`
});
error.timeline = this.timeline;
throw error;
@@ -189,13 +187,13 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'error',
- message: `DNS lookup error for ${host}: ${err.message}`,
+ message: `DNS lookup error for ${host}: ${err.message}`
});
} else {
this.timeline.push({
timestamp: new Date(),
type: 'info',
- message: `DNS lookup: ${host} -> ${address}`,
+ message: `DNS lookup: ${host} -> ${address}`
});
}
});
@@ -207,7 +205,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'info',
- message: `Connected to ${host} (${address}) port ${remotePort}`,
+ message: `Connected to ${host} (${address}) port ${remotePort}`
});
});
@@ -219,7 +217,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: `SSL connection using ${protocol} / ${cipherSuite}`,
+ message: `SSL connection using ${protocol} / ${cipherSuite}`
});
// ALPN protocol
@@ -227,7 +225,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: `ALPN: server accepted ${alpnProtocol}`,
+ message: `ALPN: server accepted ${alpnProtocol}`
});
// Server certificate
@@ -236,41 +234,41 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: `Server certificate:`,
+ message: `Server certificate:`
});
if (cert.subject) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: ` subject: ${Object.entries(cert.subject).map(([k, v]) => `${k}=${v}`).join(', ')}`,
+ message: ` subject: ${Object.entries(cert.subject).map(([k, v]) => `${k}=${v}`).join(', ')}`
});
}
if (cert.valid_from) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: ` start date: ${cert.valid_from}`,
+ message: ` start date: ${cert.valid_from}`
});
}
if (cert.valid_to) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: ` expire date: ${cert.valid_to}`,
+ message: ` expire date: ${cert.valid_to}`
});
}
if (cert.subjectaltname) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: ` subjectAltName: ${cert.subjectaltname}`,
+ message: ` subjectAltName: ${cert.subjectaltname}`
});
}
if (cert.issuer) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: ` issuer: ${Object.entries(cert.issuer).map(([k, v]) => `${k}=${v}`).join(', ')}`,
+ message: ` issuer: ${Object.entries(cert.issuer).map(([k, v]) => `${k}=${v}`).join(', ')}`
});
}
@@ -278,7 +276,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'tls',
- message: `SSL certificate verify ok.`,
+ message: `SSL certificate verify ok.`
});
}
});
@@ -287,7 +285,7 @@ function createTimelineAgentClass(BaseAgentClass) {
this.timeline.push({
timestamp: new Date(),
type: 'error',
- message: `Socket error: ${err.message}`,
+ message: `Socket error: ${err.message}`
});
});
@@ -302,7 +300,7 @@ function setupProxyAgents({
proxyConfig,
httpsAgentRequestFields,
interpolationOptions,
- timeline,
+ timeline
}) {
// Ensure TLS options are properly set
const tlsOptions = {
@@ -311,7 +309,7 @@ function setupProxyAgents({
secureProtocol: undefined,
// Allow Node.js to choose the protocol
minVersion: 'TLSv1',
- rejectUnauthorized: httpsAgentRequestFields.rejectUnauthorized !== undefined ? httpsAgentRequestFields.rejectUnauthorized : true,
+ rejectUnauthorized: httpsAgentRequestFields.rejectUnauthorized !== undefined ? httpsAgentRequestFields.rejectUnauthorized : true
};
if (proxyMode === 'on') {
@@ -367,7 +365,7 @@ function setupProxyAgents({
new URL(https_proxy);
const TimelineHttpsProxyAgent = createTimelineAgentClass(PatchedHttpsProxyAgent);
requestConfig.httpsAgent = new TimelineHttpsProxyAgent(
- { proxy: https_proxy,...tlsOptions },
+ { proxy: https_proxy, ...tlsOptions },
timeline
);
} else {
@@ -387,7 +385,6 @@ function setupProxyAgents({
}
}
-
module.exports = {
shouldUseProxy,
PatchedHttpsProxyAgent,
diff --git a/packages/bruno-electron/src/utils/tests/collection-utils.spec.js b/packages/bruno-electron/src/utils/tests/collection-utils.spec.js
index 3ed1a633c..f1383b1b4 100644
--- a/packages/bruno-electron/src/utils/tests/collection-utils.spec.js
+++ b/packages/bruno-electron/src/utils/tests/collection-utils.spec.js
@@ -2,7 +2,6 @@ const { transformRequestToSaveToFilesystem } = require('../collection');
describe('transformRequestToSaveToFilesystem', () => {
it('should preserve all relevant fields when transforming request', () => {
-
const testItem = {
uid: 'test-uid-123',
type: 'http-request',
@@ -78,7 +77,7 @@ describe('transformRequestToSaveToFilesystem', () => {
expect(result.name).toBe(testItem.name);
expect(result.seq).toBe(testItem.seq);
expect(result.settings).toEqual(testItem.settings);
-
+
// Verify tags are preserved (this is the main focus)
expect(result.tags).toEqual(['smoke', 'regression', 'api']);
expect(result.tags).toHaveLength(3);
@@ -167,7 +166,7 @@ describe('transformRequestToSaveToFilesystem', () => {
expect(result.uid).toBe('draft-uid-789');
expect(result.name).toBe('Draft Request Modified');
expect(result.settings).toEqual({ enableEncodeUrl: true });
-
+
// Verify draft tags are preserved
expect(result.tags).toEqual(['draft', 'wip', 'modified']);
expect(result.tags).toContain('modified');
diff --git a/packages/bruno-electron/src/utils/tests/filesystem/index.spec.js b/packages/bruno-electron/src/utils/tests/filesystem/index.spec.js
index 60add1b57..be8401a62 100644
--- a/packages/bruno-electron/src/utils/tests/filesystem/index.spec.js
+++ b/packages/bruno-electron/src/utils/tests/filesystem/index.spec.js
@@ -24,14 +24,13 @@ describe('File System Operations', () => {
describe('copyPath and removePath', () => {
it('should move files and folder items multiple times', async () => {
-
{
const sourcePath = path.join(tempDir, 'folder_1', 'file_2.bru');
const destDir = path.join(tempDir, 'folder_1', 'folder_1_1');
await copyPath(sourcePath, destDir);
await removePath(sourcePath);
}
-
+
{
const sourcePath = path.join(tempDir, 'folder_2');
const destDir = path.join(tempDir, 'folder_1', 'folder_1_1');
@@ -57,7 +56,6 @@ describe('File System Operations', () => {
expect(result).toBe(true);
});
-
it('should throw an error move file/folder if the destination has the same filename', async () => {
{
const sourcePath = path.join(tempDir, 'folder_1', 'file_dup.bru');
@@ -65,11 +63,9 @@ describe('File System Operations', () => {
await expect(copyPath(sourcePath, destDir)).rejects.toThrow();
}
});
-
});
});
-
// create folders and files recursively based on the defined json structure
const createFilesAndFolders = async (dir, filesAndFolders) => {
for (const item of filesAndFolders) {
@@ -81,7 +77,7 @@ const createFilesAndFolders = async (dir, filesAndFolders) => {
await fs.writeFile(itemPath, item.content);
}
}
-}
+};
// if a file/folder doesnt exist, return false
// should only contain files and folders that are defined in the json structure
@@ -93,18 +89,18 @@ const verifyFilesAndFolders = async (dir, filesAndFolders) => {
}
for (const file of files) {
const itemPath = path.join(dir, file);
- const item = filesAndFolders.find(f => f.name === file);
+ const item = filesAndFolders.find((f) => f.name === file);
if (!item) {
return false;
}
if (item.type === 'folder') {
return await verify(itemPath, item.files);
} else {
- return await fs.readFile(itemPath, 'utf8').then(content => content === item.content);
+ return await fs.readFile(itemPath, 'utf8').then((content) => content === item.content);
}
}
return true;
- }
+ };
try {
const verified = await verify(dir, filesAndFolders);
@@ -113,4 +109,4 @@ const verifyFilesAndFolders = async (dir, filesAndFolders) => {
console.error(error);
return false;
}
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-electron/src/utils/tests/fixtures/filesystem/copypath-removepath.js b/packages/bruno-electron/src/utils/tests/fixtures/filesystem/copypath-removepath.js
index ea08f8d25..49ad66e45 100644
--- a/packages/bruno-electron/src/utils/tests/fixtures/filesystem/copypath-removepath.js
+++ b/packages/bruno-electron/src/utils/tests/fixtures/filesystem/copypath-removepath.js
@@ -1,155 +1,155 @@
const initialCollectionStructure = [
{
- "name": "folder_1",
- "type": "folder",
- "files": [
+ name: 'folder_1',
+ type: 'folder',
+ files: [
{
- "name": "file_1.bru",
- "type": "file",
- "content": "file_1_content"
+ name: 'file_1.bru',
+ type: 'file',
+ content: 'file_1_content'
},
{
- "name": "file_2.bru",
- "type": "file",
- "content": "file_2_content"
+ name: 'file_2.bru',
+ type: 'file',
+ content: 'file_2_content'
},
{
- "name": "folder_1_1",
- "type": "folder",
- "files": [
+ name: 'folder_1_1',
+ type: 'folder',
+ files: [
{
- "name": "file_1_1.bru",
- "type": "file",
- "content": "file_1_1_content"
+ name: 'file_1_1.bru',
+ type: 'file',
+ content: 'file_1_1_content'
},
{
- "name": "file_1_2.bru",
- "type": "file",
- "content": "file_1_2_content"
+ name: 'file_1_2.bru',
+ type: 'file',
+ content: 'file_1_2_content'
}
]
},
{
- "name": "file_1_3.bru",
- "type": "file",
- "content": "file_1_3_content"
+ name: 'file_1_3.bru',
+ type: 'file',
+ content: 'file_1_3_content'
},
{
- "name": "file_dup.bru",
- "type": "file",
- "content": "file_dup_content"
+ name: 'file_dup.bru',
+ type: 'file',
+ content: 'file_dup_content'
}
- ],
+ ]
},
{
- "name": "folder_2",
- "type": "folder",
- "files": [
+ name: 'folder_2',
+ type: 'folder',
+ files: [
{
- "name": "file_2_1.bru",
- "type": "file",
- "content": "file_2_1_content"
+ name: 'file_2_1.bru',
+ type: 'file',
+ content: 'file_2_1_content'
},
{
- "name": "file_2_2.bru",
- "type": "file",
- "content": "file_2_2_content"
+ name: 'file_2_2.bru',
+ type: 'file',
+ content: 'file_2_2_content'
},
{
- "name": "folder_2_1",
- "type": "folder",
- "files": [
+ name: 'folder_2_1',
+ type: 'folder',
+ files: [
{
- "name": "file_2_1_1.bru",
- "type": "file",
- "content": "file_2_1_1_content"
+ name: 'file_2_1_1.bru',
+ type: 'file',
+ content: 'file_2_1_1_content'
}
]
}
]
},
{
- "name": "file_dup.bru",
- "type": "file",
- "content": "file_dup_content"
+ name: 'file_dup.bru',
+ type: 'file',
+ content: 'file_dup_content'
}
];
const finalCollectionStructure = [
{
- "name": "folder_1",
- "type": "folder",
- "files": [
+ name: 'folder_1',
+ type: 'folder',
+ files: [
{
- "name": "file_1.bru",
- "type": "file",
- "content": "file_1_content"
+ name: 'file_1.bru',
+ type: 'file',
+ content: 'file_1_content'
},
{
- "name": "folder_1_1",
- "type": "folder",
- "files": [
+ name: 'folder_1_1',
+ type: 'folder',
+ files: [
{
- "name": "file_1_1.bru",
- "type": "file",
- "content": "file_1_1_content"
+ name: 'file_1_1.bru',
+ type: 'file',
+ content: 'file_1_1_content'
},
{
- "name": "file_1_2.bru",
- "type": "file",
- "content": "file_1_2_content"
+ name: 'file_1_2.bru',
+ type: 'file',
+ content: 'file_1_2_content'
},
{
- "name": "file_2.bru",
- "type": "file",
- "content": "file_2_content"
+ name: 'file_2.bru',
+ type: 'file',
+ content: 'file_2_content'
},
{
- "name": "folder_2",
- "type": "folder",
- "files": [
+ name: 'folder_2',
+ type: 'folder',
+ files: [
{
- "name": "file_2_1.bru",
- "type": "file",
- "content": "file_2_1_content"
+ name: 'file_2_1.bru',
+ type: 'file',
+ content: 'file_2_1_content'
}
]
}
]
},
{
- "name": "file_1_3.bru",
- "type": "file",
- "content": "file_1_3_content"
+ name: 'file_1_3.bru',
+ type: 'file',
+ content: 'file_1_3_content'
},
{
- "name": "file_2_2.bru",
- "type": "file",
- "content": "file_2_2_content"
+ name: 'file_2_2.bru',
+ type: 'file',
+ content: 'file_2_2_content'
},
{
- "name": "file_dup.bru",
- "type": "file",
- "content": "file_dup_content"
- }
- ],
- },
- {
- "name": "folder_2_1",
- "type": "folder",
- "files": [
- {
- "name": "file_2_1_1.bru",
- "type": "file",
- "content": "file_2_1_1_content"
+ name: 'file_dup.bru',
+ type: 'file',
+ content: 'file_dup_content'
}
]
},
{
- "name": "file_dup.bru",
- "type": "file",
- "content": "file_dup_content"
+ name: 'folder_2_1',
+ type: 'folder',
+ files: [
+ {
+ name: 'file_2_1_1.bru',
+ type: 'file',
+ content: 'file_2_1_1_content'
+ }
+ ]
+ },
+ {
+ name: 'file_dup.bru',
+ type: 'file',
+ content: 'file_dup_content'
}
];
-module.exports = { initialCollectionStructure, finalCollectionStructure };
\ No newline at end of file
+module.exports = { initialCollectionStructure, finalCollectionStructure };
diff --git a/packages/bruno-electron/src/utils/window.js b/packages/bruno-electron/src/utils/window.js
index 949a2aaa2..f62d2dd40 100644
--- a/packages/bruno-electron/src/utils/window.js
+++ b/packages/bruno-electron/src/utils/window.js
@@ -36,10 +36,10 @@ const isPositionValid = (bounds) => {
const area = getArea(bounds);
return (
- bounds.x >= area.x &&
- bounds.y >= area.y &&
- bounds.x + bounds.width <= area.x + area.width &&
- bounds.y + bounds.height <= area.y + area.height
+ bounds.x >= area.x
+ && bounds.y >= area.y
+ && bounds.x + bounds.width <= area.x + area.width
+ && bounds.y + bounds.height <= area.y + area.height
);
};
diff --git a/packages/bruno-electron/tests/network/execute-request-error-handler.spec.js b/packages/bruno-electron/tests/network/execute-request-error-handler.spec.js
index 3fe168adb..897da0da3 100644
--- a/packages/bruno-electron/tests/network/execute-request-error-handler.spec.js
+++ b/packages/bruno-electron/tests/network/execute-request-error-handler.spec.js
@@ -14,26 +14,26 @@ describe('executeRequestOnFailHandler', () => {
it('should do nothing when request is null', async () => {
const error = new Error('Test error');
-
+
await executeRequestOnFailHandler(null, error);
-
+
expect(consoleSpy).not.toHaveBeenCalled();
});
it('should do nothing when request is undefined', async () => {
const error = new Error('Test error');
-
+
await executeRequestOnFailHandler(undefined, error);
-
+
expect(consoleSpy).not.toHaveBeenCalled();
});
it('should do nothing when onFailHandler is not a function', async () => {
const request = { onFailHandler: 'not a function' };
const error = new Error('Test error');
-
+
await executeRequestOnFailHandler(request, error);
-
+
expect(consoleSpy).not.toHaveBeenCalled();
});
@@ -41,9 +41,9 @@ describe('executeRequestOnFailHandler', () => {
const mockHandler = jest.fn();
const request = { onFailHandler: mockHandler };
const error = new Error('Test error');
-
+
await executeRequestOnFailHandler(request, error);
-
+
expect(mockHandler).toHaveBeenCalledWith(error);
expect(mockHandler).toHaveBeenCalledTimes(1);
expect(consoleSpy).not.toHaveBeenCalled();
@@ -98,15 +98,15 @@ describe('executeRequestOnFailHandler', () => {
} catch (err) {
error = err;
}
-
+
// Verify this is actually a hard error (no response)
expect(error.response).toBeUndefined();
-
+
await executeRequestOnFailHandler(request, error);
-
+
expect(mockHandler).toHaveBeenCalledWith(error);
const passedError = mockHandler.mock.calls[0][0];
expect(passedError.response).toBeUndefined(); // Should be undefined for hard errors
expect(passedError.code).toBe('ECONNABORTED'); // Connection aborted due to timeout
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-electron/tests/network/fetch-gql-schema-handler.spec.js b/packages/bruno-electron/tests/network/fetch-gql-schema-handler.spec.js
index 8831ba48b..97f5a81d5 100644
--- a/packages/bruno-electron/tests/network/fetch-gql-schema-handler.spec.js
+++ b/packages/bruno-electron/tests/network/fetch-gql-schema-handler.spec.js
@@ -365,7 +365,5 @@ describe('fetchGqlSchemaHandler - variable precedence', () => {
request,
collection.root
);
- })
+ });
});
-
-
diff --git a/packages/bruno-electron/tests/network/index.spec.js b/packages/bruno-electron/tests/network/index.spec.js
index a01955386..5fa443132 100644
--- a/packages/bruno-electron/tests/network/index.spec.js
+++ b/packages/bruno-electron/tests/network/index.spec.js
@@ -1,13 +1,13 @@
const { configureRequest } = require('../../src/ipc/network/index');
describe('index: configureRequest', () => {
- it("Should add 'http://' to the URL if no protocol is specified", async () => {
+ it('Should add \'http://\' to the URL if no protocol is specified', async () => {
const request = { method: 'GET', url: 'test-domain', body: {} };
await configureRequest(null, {}, request, null, null, null, null);
expect(request.url).toEqual('http://test-domain');
});
- it("Should NOT add 'http://' to the URL if a protocol is specified", async () => {
+ it('Should NOT add \'http://\' to the URL if a protocol is specified', async () => {
const request = { method: 'GET', url: 'ftp://test-domain', body: {} };
await configureRequest(null, {}, request, null, null, null, null);
expect(request.url).toEqual('ftp://test-domain');
diff --git a/packages/bruno-electron/tests/network/interpolate-vars.spec.js b/packages/bruno-electron/tests/network/interpolate-vars.spec.js
index 5fcd2ed1b..003928a11 100644
--- a/packages/bruno-electron/tests/network/interpolate-vars.spec.js
+++ b/packages/bruno-electron/tests/network/interpolate-vars.spec.js
@@ -3,28 +3,28 @@ const interpolateVars = require('../../src/ipc/network/interpolate-vars');
describe('interpolate-vars: interpolateVars', () => {
describe('Interpolates string', () => {
describe('With environment variables', () => {
- it("If there's a var with only alphanumeric characters in its name", async () => {
+ it('If there\'s a var with only alphanumeric characters in its name', async () => {
const request = { method: 'GET', url: '{{testUrl1}}' };
const result = interpolateVars(request, { testUrl1: 'test.com' }, null, null);
expect(result.url).toEqual('test.com');
});
- it("If there's a var with a '.' in its name", async () => {
+ it('If there\'s a var with a \'.\' in its name', async () => {
const request = { method: 'GET', url: '{{test.url}}' };
const result = interpolateVars(request, { 'test.url': 'test.com' }, null, null);
expect(result.url).toEqual('test.com');
});
- it("If there's a var with a '-' in its name", async () => {
+ it('If there\'s a var with a \'-\' in its name', async () => {
const request = { method: 'GET', url: '{{test-url}}' };
const result = interpolateVars(request, { 'test-url': 'test.com' }, null, null);
expect(result.url).toEqual('test.com');
});
- it("If there's a var with a '_' in its name", async () => {
+ it('If there\'s a var with a \'_\' in its name', async () => {
const request = { method: 'GET', url: '{{test_url}}' };
const result = interpolateVars(request, { test_url: 'test.com' }, null, null);
@@ -32,10 +32,10 @@ describe('interpolate-vars: interpolateVars', () => {
});
it('If there are multiple variables', async () => {
- const body =
- '{\n "firstElem": {{body-var-1}},\n "secondElem": [{{body.var.2}}],\n "thirdElem": {\n "fourthElem": {{body_var_3}},\n "{{varAsKey}}": {{valueForKey}} }}';
- const expectedBody =
- '{\n "firstElem": Test1,\n "secondElem": [Test2],\n "thirdElem": {\n "fourthElem": Test3,\n "TestKey": TestValueForKey }}';
+ const body
+ = '{\n "firstElem": {{body-var-1}},\n "secondElem": [{{body.var.2}}],\n "thirdElem": {\n "fourthElem": {{body_var_3}},\n "{{varAsKey}}": {{valueForKey}} }}';
+ const expectedBody
+ = '{\n "firstElem": Test1,\n "secondElem": [Test2],\n "thirdElem": {\n "fourthElem": Test3,\n "TestKey": TestValueForKey }}';
const request = { method: 'POST', url: 'test', data: body, headers: { 'content-type': 'json' } };
const result = interpolateVars(
@@ -43,9 +43,9 @@ describe('interpolate-vars: interpolateVars', () => {
{
'body-var-1': 'Test1',
'body.var.2': 'Test2',
- body_var_3: 'Test3',
- varAsKey: 'TestKey',
- valueForKey: 'TestValueForKey'
+ 'body_var_3': 'Test3',
+ 'varAsKey': 'TestKey',
+ 'valueForKey': 'TestValueForKey'
},
null,
null
@@ -188,7 +188,7 @@ describe('interpolate-vars: interpolateVars', () => {
* It should NOT turn process env vars into literal segments.
* Otherwise, Handlebars will try to access the var literally
*/
- it("If there's a var that starts with 'process.env.'", async () => {
+ it('If there\'s a var that starts with \'process.env.\'', async () => {
const request = { method: 'GET', url: '{{process.env.TEST_VAR}}' };
const result = interpolateVars(request, null, null, { TEST_VAR: 'test.com' });
@@ -255,21 +255,21 @@ describe('interpolate-vars: interpolateVars', () => {
describe('Does NOT interpolate string', () => {
describe('With environment variables', () => {
- it("If it's not a var (no braces)", async () => {
+ it('If it\'s not a var (no braces)', async () => {
const request = { method: 'GET', url: 'test' };
const result = interpolateVars(request, { 'test.url': 'test.com' }, null, null);
expect(result.url).toEqual('test');
});
- it("If it's not a var (only 1 set of braces)", async () => {
+ it('If it\'s not a var (only 1 set of braces)', async () => {
const request = { method: 'GET', url: '{test.url}' };
const result = interpolateVars(request, { 'test.url': 'test.com' }, null, null);
expect(result.url).toEqual('{test.url}');
});
- it("If it's not a var (1 opening & 2 closing braces)", async () => {
+ it('If it\'s not a var (1 opening & 2 closing braces)', async () => {
const request = { method: 'GET', url: '{test.url}}' };
const result = interpolateVars(request, { 'test.url': 'test.com' }, null, null);
diff --git a/packages/bruno-electron/tests/network/prepare-request.spec.js b/packages/bruno-electron/tests/network/prepare-request.spec.js
index ec14ad3c0..89ba9c520 100644
--- a/packages/bruno-electron/tests/network/prepare-request.spec.js
+++ b/packages/bruno-electron/tests/network/prepare-request.spec.js
@@ -39,4 +39,4 @@ describe('prepare-request: prepareRequest', () => {
expect(result.headers['content-type']).toEqual('application/json');
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-electron/tests/prepare-request.test.js b/packages/bruno-electron/tests/prepare-request.test.js
index 9830b45c3..fbbc477dc 100644
--- a/packages/bruno-electron/tests/prepare-request.test.js
+++ b/packages/bruno-electron/tests/prepare-request.test.js
@@ -26,21 +26,21 @@ describe('setAuthHeaders', () => {
beforeEach(() => {
// Reset all mocks
jest.clearAllMocks();
-
+
// Reset crypto mock to return predictable values
crypto.randomBytes.mockReturnValue(Buffer.from('1234567890abcdef', 'hex'));
-
+
// Setup default mock objects
mockAxiosRequest = {
headers: {}
};
-
+
mockRequest = {
auth: {
mode: 'none'
}
};
-
+
mockCollectionRoot = {
request: {
auth: null
@@ -50,10 +50,10 @@ describe('setAuthHeaders', () => {
// Setup a more sophisticated mock for lodash get function
mockGet.mockImplementation((obj, path, defaultValue) => {
if (!obj) return defaultValue;
-
+
const keys = path.split('.');
let current = obj;
-
+
for (const key of keys) {
if (current && typeof current === 'object' && key in current) {
current = current[key];
@@ -61,7 +61,7 @@ describe('setAuthHeaders', () => {
return defaultValue;
}
}
-
+
return current;
});
});
@@ -79,7 +79,7 @@ describe('setAuthHeaders', () => {
profileName: 'default'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -102,7 +102,7 @@ describe('setAuthHeaders', () => {
password: 'testpass'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -120,7 +120,7 @@ describe('setAuthHeaders', () => {
token: 'test-token'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -136,7 +136,7 @@ describe('setAuthHeaders', () => {
password: 'testpass'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -156,7 +156,7 @@ describe('setAuthHeaders', () => {
domain: 'testdomain'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -176,7 +176,7 @@ describe('setAuthHeaders', () => {
password: 'testpass'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -193,7 +193,7 @@ describe('setAuthHeaders', () => {
placement: 'header'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -210,7 +210,7 @@ describe('setAuthHeaders', () => {
placement: 'queryparams'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -231,7 +231,7 @@ describe('setAuthHeaders', () => {
placement: 'header'
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -263,7 +263,7 @@ describe('setAuthHeaders', () => {
additionalParameters: { authorization: [], token: [], refresh: [] }
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -312,7 +312,7 @@ describe('setAuthHeaders', () => {
additionalParameters: { authorization: [], token: [], refresh: [] }
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -357,7 +357,7 @@ describe('setAuthHeaders', () => {
additionalParameters: { authorization: [], token: [], refresh: [] }
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -398,7 +398,7 @@ describe('setAuthHeaders', () => {
additionalParameters: { authorization: [], token: [], refresh: [] }
}
};
-
+
mockRequest.auth.mode = 'inherit';
const result = setAuthHeaders(mockAxiosRequest, mockRequest, mockCollectionRoot);
@@ -434,7 +434,7 @@ describe('setAuthHeaders', () => {
region: 'us-east-1',
profileName: 'default'
}
- }
+ };
mockRequest.auth = {
mode: 'awsv4',
awsv4: {
@@ -624,7 +624,7 @@ describe('setAuthHeaders', () => {
});
});
- test('should set OAuth2 password grant at request level', () => {
+ test('should set OAuth2 password grant at request level', () => {
mockCollectionRoot.request.auth = {
mode: 'oauth2',
oauth2: {
@@ -702,7 +702,7 @@ describe('setAuthHeaders', () => {
username: 'collectionuser',
password: 'collectionpass',
clientId: 'collection-client',
- clientSecret: 'collection-secret',
+ clientSecret: 'collection-secret'
}
};
mockRequest.auth = {
diff --git a/packages/bruno-electron/tests/store/global-environments.test.js b/packages/bruno-electron/tests/store/global-environments.test.js
index b01e762fb..a5dd323ac 100644
--- a/packages/bruno-electron/tests/store/global-environments.test.js
+++ b/packages/bruno-electron/tests/store/global-environments.test.js
@@ -13,20 +13,20 @@ describe('global environment variable type backward compatibility', () => {
const mockGlobalEnvironments = [
{
uid: 'yDlwWe3qgimPG20G7AbF7',
- name: "Test Environment",
+ name: 'Test Environment',
variables: [
{
uid: 'b6BIHGaCrm4m97YA2dIdx',
- name: "regular_var",
- value: "regular_value",
+ name: 'regular_var',
+ value: 'regular_value',
enabled: true,
secret: false
// Missing: type field
},
{
uid: 'yQTqanPoMdRjKnHyIOZNc',
- name: "secret_var",
- value: "secret_value",
+ name: 'secret_var',
+ value: 'secret_value',
enabled: true,
secret: true
// Missing: type field
@@ -42,8 +42,8 @@ describe('global environment variable type backward compatibility', () => {
expect(processedEnvironments).toHaveLength(1);
expect(processedEnvironments[0].variables).toHaveLength(2);
- const regularVar = processedEnvironments[0].variables.find(v => v.name === 'regular_var');
- const secretVar = processedEnvironments[0].variables.find(v => v.name === 'secret_var');
+ const regularVar = processedEnvironments[0].variables.find((v) => v.name === 'regular_var');
+ const secretVar = processedEnvironments[0].variables.find((v) => v.name === 'secret_var');
expect(regularVar.name).toBe('regular_var');
expect(regularVar.type).toBe('text');
diff --git a/packages/bruno-electron/tests/utils/collection.spec.js b/packages/bruno-electron/tests/utils/collection.spec.js
index 363537db6..2653f97f3 100644
--- a/packages/bruno-electron/tests/utils/collection.spec.js
+++ b/packages/bruno-electron/tests/utils/collection.spec.js
@@ -1,4 +1,4 @@
-const { parseBruFileMeta } = require("../../src/utils/collection");
+const { parseBruFileMeta } = require('../../src/utils/collection');
describe('parseBruFileMeta', () => {
test('parses valid meta block correctly', () => {
@@ -285,4 +285,4 @@ describe('parseBruFileMeta', () => {
}
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-electron/tests/utils/common.spec.js b/packages/bruno-electron/tests/utils/common.spec.js
index ded1dbebb..81e620e78 100644
--- a/packages/bruno-electron/tests/utils/common.spec.js
+++ b/packages/bruno-electron/tests/utils/common.spec.js
@@ -6,13 +6,13 @@ describe('utils: flattenDataForDotNotation', () => {
const input = {
person: {
name: 'John',
- age: 30,
- },
+ age: 30
+ }
};
const expectedOutput = {
'person.name': 'John',
- 'person.age': 30,
+ 'person.age': 30
};
expect(flattenDataForDotNotation(input)).toEqual(expectedOutput);
@@ -22,65 +22,65 @@ describe('utils: flattenDataForDotNotation', () => {
const input = {
users: [
{ name: 'Alice', age: 25 },
- { name: 'Bob', age: 28 },
- ],
+ { name: 'Bob', age: 28 }
+ ]
};
-
+
const expectedOutput = {
'users[0].name': 'Alice',
'users[0].age': 25,
'users[1].name': 'Bob',
- 'users[1].age': 28,
+ 'users[1].age': 28
};
-
+
expect(flattenDataForDotNotation(input)).toEqual(expectedOutput);
});
-
+
test('Flatten an empty object', () => {
const input = {};
-
+
const expectedOutput = {};
-
+
expect(flattenDataForDotNotation(input)).toEqual(expectedOutput);
});
-
+
test('Flatten an object with nested objects', () => {
const input = {
person: {
name: 'Alice',
address: {
city: 'New York',
- zipcode: '10001',
- },
- },
+ zipcode: '10001'
+ }
+ }
};
-
+
const expectedOutput = {
'person.name': 'Alice',
'person.address.city': 'New York',
- 'person.address.zipcode': '10001',
+ 'person.address.zipcode': '10001'
};
-
+
expect(flattenDataForDotNotation(input)).toEqual(expectedOutput);
});
-
+
test('Flatten an object with arrays of objects', () => {
const input = {
teams: [
{ name: 'Team A', members: ['Alice', 'Bob'] },
- { name: 'Team B', members: ['Charlie', 'David'] },
- ],
+ { name: 'Team B', members: ['Charlie', 'David'] }
+ ]
};
-
+
const expectedOutput = {
'teams[0].name': 'Team A',
'teams[0].members[0]': 'Alice',
'teams[0].members[1]': 'Bob',
'teams[1].name': 'Team B',
'teams[1].members[0]': 'Charlie',
- 'teams[1].members[1]': 'David',
+ 'teams[1].members[1]': 'David'
};
-
+
expect(flattenDataForDotNotation(input)).toEqual(expectedOutput);
});
});
diff --git a/packages/bruno-filestore/src/formats/bru/index.ts b/packages/bruno-filestore/src/formats/bru/index.ts
index 0078428b4..ba000e1d6 100644
--- a/packages/bruno-filestore/src/formats/bru/index.ts
+++ b/packages/bruno-filestore/src/formats/bru/index.ts
@@ -160,8 +160,8 @@ export const stringifyBruRequest = (json: any): string => {
mode: 'json',
json: '{}'
});
- } // For gRPC, add gRPC-specific structure but maintain field names
- else if (type === 'grpc') {
+ } else if (type === 'grpc') {
+ // For gRPC, add gRPC-specific structure but maintain field names
bruJson.grpc = {
url: _.get(json, 'request.url'),
auth: _.get(json, 'request.auth.mode', 'none'),
diff --git a/packages/bruno-filestore/src/formats/bru/utils/oauth2-additional-params.ts b/packages/bruno-filestore/src/formats/bru/utils/oauth2-additional-params.ts
index 54a613807..1102ce675 100644
--- a/packages/bruno-filestore/src/formats/bru/utils/oauth2-additional-params.ts
+++ b/packages/bruno-filestore/src/formats/bru/utils/oauth2-additional-params.ts
@@ -5,7 +5,7 @@ export interface T_OAuth2AdditionalParam {
name: string;
value: string;
enabled: boolean;
- sendIn: T_Oauth2ParameterSendInType
+ sendIn: T_Oauth2ParameterSendInType;
}
export interface T_OAuth2AdditionalParameters {
@@ -43,16 +43,16 @@ const PARAMETER_MAPPINGS: T_Oauth2ParameterMapping[] = [
// Authorization parameters (only for authorization_code grant type)
{ type: 'authorization', sendIn: 'headers', source: 'oauth2_additional_parameters_auth_req_headers' },
{ type: 'authorization', sendIn: 'queryparams', source: 'oauth2_additional_parameters_auth_req_queryparams' },
-
+
// Token parameters (for all grant types)
{ type: 'token', sendIn: 'headers', source: 'oauth2_additional_parameters_access_token_req_headers' },
{ type: 'token', sendIn: 'queryparams', source: 'oauth2_additional_parameters_access_token_req_queryparams' },
{ type: 'token', sendIn: 'body', source: 'oauth2_additional_parameters_access_token_req_bodyvalues' },
-
+
// Refresh parameters (for grant types that support refresh)
{ type: 'refresh', sendIn: 'headers', source: 'oauth2_additional_parameters_refresh_token_req_headers' },
{ type: 'refresh', sendIn: 'queryparams', source: 'oauth2_additional_parameters_refresh_token_req_queryparams' },
- { type: 'refresh', sendIn: 'body', source: 'oauth2_additional_parameters_refresh_token_req_bodyvalues' },
+ { type: 'refresh', sendIn: 'body', source: 'oauth2_additional_parameters_refresh_token_req_bodyvalues' }
];
/**
@@ -62,8 +62,8 @@ const mapParametersFromSource = (sourceParams: any[], sendIn: T_Oauth2ParameterS
if (!sourceParams?.length) {
return [];
}
-
- return sourceParams.map(param => ({
+
+ return sourceParams.map((param) => ({
...param,
sendIn
}));
@@ -81,7 +81,7 @@ const shouldIncludeParameterType = (type: T_Oauth2ParameterType, grantType: stri
if (type === 'token' || type === 'refresh') {
return grantType !== 'implicit';
}
-
+
// Token and refresh parameters are valid for all grant types
return true;
};
@@ -90,15 +90,15 @@ const shouldIncludeParameterType = (type: T_Oauth2ParameterType, grantType: stri
* Collects all parameters for a specific type (authorization, token, or refresh)
*/
const collectParametersForType = (
- json: T_BruJson,
- type: T_Oauth2ParameterType,
+ json: T_BruJson,
+ type: T_Oauth2ParameterType,
grantType: string
): T_OAuth2AdditionalParam[] => {
if (!shouldIncludeParameterType(type, grantType)) {
return [];
}
- const relevantMappings = PARAMETER_MAPPINGS.filter(mapping => mapping.type === type);
+ const relevantMappings = PARAMETER_MAPPINGS.filter((mapping) => mapping.type === type);
const allParams: T_OAuth2AdditionalParam[] = [];
for (const mapping of relevantMappings) {
@@ -113,29 +113,28 @@ const collectParametersForType = (
/**
* This function extracts OAuth2 additional parameters from various sources in the bru json data and organizes
* them into a structured format based on their usage context (authorization, token, refresh).
- *
+ *
* @param json - json object containing OAuth2 configuration and additional parameters
* @returns OAuth2 additional parameters
*/
-export const getOauth2AdditionalParameters = (json: T_BruJson): T_OAuth2AdditionalParameters => {
+export const getOauth2AdditionalParameters = (json: T_BruJson): T_OAuth2AdditionalParameters => {
const grantType = json.auth.oauth2.grantType;
const additionalParameters: T_OAuth2AdditionalParameters = {};
try {
// Collect parameters for each type
const parameterTypes: T_Oauth2ParameterType[] = ['authorization', 'token', 'refresh'];
-
+
for (const type of parameterTypes) {
const params = collectParametersForType(json, type, grantType);
if (params.length > 0) {
additionalParameters[type] = params;
}
}
- }
- catch(error) {
+ } catch (error) {
console.error(error);
- console.error("Error while getting the oauth2 additional parameters!");
+ console.error('Error while getting the oauth2 additional parameters!');
}
-
+
return additionalParameters;
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-filestore/src/formats/bru/utils/request-parse-and-redact-body-data.ts b/packages/bruno-filestore/src/formats/bru/utils/request-parse-and-redact-body-data.ts
index 6e2313575..99b4e5c69 100644
--- a/packages/bruno-filestore/src/formats/bru/utils/request-parse-and-redact-body-data.ts
+++ b/packages/bruno-filestore/src/formats/bru/utils/request-parse-and-redact-body-data.ts
@@ -7,11 +7,11 @@ export const bruRequestParseAndRedactBodyData = (bruFileContent: string) => {
try {
// Define the patterns that indicate the start of different body types
const bodyTypePatterns = [
- "body:json {",
- "body:text {",
- "body:xml {",
- "body:sparql {",
- "body:graphql {"
+ 'body:json {',
+ 'body:text {',
+ 'body:xml {',
+ 'body:sparql {',
+ 'body:graphql {'
];
// Normalize line endings to LF
@@ -37,30 +37,30 @@ export const bruRequestParseAndRedactBodyData = (bruFileContent: string) => {
// Split the file content into blocks
let fileContentBlocks = bruFileContent.split(`${EOL}}${EOL}`);
- fileContentBlocks = fileContentBlocks.filter(Boolean).map(_ => _.trim());
+ fileContentBlocks = fileContentBlocks.filter(Boolean).map((_) => _.trim());
// Extract body blocks and their content
const extractedBodyBlocks = fileContentBlocks
- .filter(block => bodyTypePatterns.some(pattern => block.startsWith(pattern)))
+ .filter((block) => bodyTypePatterns.some((pattern) => block.startsWith(pattern)))
.reduce((bodyContentMap: Record, bodyBlock) => {
// Extract the body type (json, text, xml, etc.) from the first line
const firstLine = bodyBlock.split(EOL)[0];
const bodyType = firstLine.split(`body:`)[1].split(/\s/)[0];
-
+
// Extract the body content (everything between the opening and closing braces)
const bodyContentLines = bodyBlock.split(EOL).slice(1);
const rawBodyContent = bodyContentLines.join(EOL);
-
+
// Remove indentation from the body content
const cleanBodyContent = removeLeadingIndentation(rawBodyContent);
-
+
bodyContentMap[bodyType] = cleanBodyContent;
return bodyContentMap;
}, {});
// Filter out body blocks to get the remaining file content
- const fileContentWithoutBodyBlocks = fileContentBlocks.filter(block =>
- !bodyTypePatterns.some(pattern => block.startsWith(pattern))
+ const fileContentWithoutBodyBlocks = fileContentBlocks.filter((block) =>
+ !bodyTypePatterns.some((pattern) => block.startsWith(pattern))
);
return {
@@ -74,4 +74,4 @@ export const bruRequestParseAndRedactBodyData = (bruFileContent: string) => {
extractedBodyContent: {}
};
}
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-filestore/src/index.ts b/packages/bruno-filestore/src/index.ts
index cb10c357a..b76ab102e 100644
--- a/packages/bruno-filestore/src/index.ts
+++ b/packages/bruno-filestore/src/index.ts
@@ -130,10 +130,9 @@ export const stringifyEnvironment = (envObj: BrunoEnvironment, options: Stringif
throw new Error(`Unsupported format: ${options.format}`);
};
-
export const parseDotEnv = (content: string): Record => {
return dotenvToJson(content);
};
export { BruParserWorker };
-export * from './types';
\ No newline at end of file
+export * from './types';
diff --git a/packages/bruno-filestore/src/types.ts b/packages/bruno-filestore/src/types.ts
index 42162b819..41246cd50 100644
--- a/packages/bruno-filestore/src/types.ts
+++ b/packages/bruno-filestore/src/types.ts
@@ -19,4 +19,4 @@ export interface WorkerTask {
export interface Lane {
maxSize: number;
-}
\ No newline at end of file
+}
diff --git a/packages/bruno-filestore/src/types/bruno-lang.d.ts b/packages/bruno-filestore/src/types/bruno-lang.d.ts
index 257d6e8a0..a04dccb76 100644
--- a/packages/bruno-filestore/src/types/bruno-lang.d.ts
+++ b/packages/bruno-filestore/src/types/bruno-lang.d.ts
@@ -6,4 +6,4 @@ declare module '@usebruno/lang' {
export function collectionBruToJson(bruContent: string): any;
export function jsonToCollectionBru(jsonData: any): string;
export function dotenvToJson(envContent: string): Record;
-}
\ No newline at end of file
+}
diff --git a/packages/bruno-filestore/src/workers/WorkerQueue/index.ts b/packages/bruno-filestore/src/workers/WorkerQueue/index.ts
index bb248ee3f..1751505b0 100644
--- a/packages/bruno-filestore/src/workers/WorkerQueue/index.ts
+++ b/packages/bruno-filestore/src/workers/WorkerQueue/index.ts
@@ -21,14 +21,14 @@ class WorkerQueue {
}
async getWorkerForScriptPath(scriptPath: string) {
- if (!this.workers) this.workers = {};
+ if (!this.workers) this.workers = {};
let worker = this.workers[scriptPath];
if (!worker || worker.threadId === -1) {
this.workers[scriptPath] = worker = new Worker(scriptPath);
}
return worker;
}
-
+
async enqueue(task: QueuedTask) {
const { priority, scriptPath, data, taskType } = task;
@@ -40,9 +40,9 @@ class WorkerQueue {
}
async processQueue() {
- if (this.isProcessing || this.queue.length === 0){
+ if (this.isProcessing || this.queue.length === 0) {
return;
- }
+ }
this.isProcessing = true;
const { scriptPath, data, taskType, resolve, reject } = this.queue.shift() as QueuedTask;
@@ -61,12 +61,12 @@ class WorkerQueue {
async runWorker({ scriptPath, data, taskType }: { scriptPath: string; data: any; taskType: 'parse' | 'stringify' }) {
return new Promise(async (resolve, reject) => {
let worker = await this.getWorkerForScriptPath(scriptPath);
-
+
const messageHandler = (data: any) => {
worker.off('message', messageHandler);
worker.off('error', errorHandler);
worker.off('exit', exitHandler);
-
+
if (data?.error) {
reject(new Error(data?.error));
} else {
@@ -89,7 +89,7 @@ class WorkerQueue {
delete this.workers[scriptPath];
reject(new Error(`Worker stopped with exit code ${code}`));
};
-
+
worker.on('message', messageHandler);
worker.on('error', errorHandler);
worker.on('exit', exitHandler);
@@ -99,16 +99,16 @@ class WorkerQueue {
}
async cleanup() {
- const promises = Object.values(this.workers).map(worker => {
+ const promises = Object.values(this.workers).map((worker) => {
if (worker.threadId !== -1) {
return worker.terminate();
}
return Promise.resolve();
});
-
+
await Promise.allSettled(promises);
this.workers = {};
}
}
-export default WorkerQueue;
\ No newline at end of file
+export default WorkerQueue;
diff --git a/packages/bruno-filestore/src/workers/index.ts b/packages/bruno-filestore/src/workers/index.ts
index f080f08a8..126039e19 100644
--- a/packages/bruno-filestore/src/workers/index.ts
+++ b/packages/bruno-filestore/src/workers/index.ts
@@ -4,27 +4,27 @@ import path from 'node:path';
const sizeInMB = (size: number): number => {
return size / (1024 * 1024);
-}
+};
const getSize = (data: any): number => {
return sizeInMB(typeof data === 'string' ? Buffer.byteLength(data, 'utf8') : Buffer.byteLength(JSON.stringify(data), 'utf8'));
-}
+};
/**
* Lanes are used to determine which worker queue to use based on the size of the data.
- *
+ *
* The first lane is for smaller files (<0.1MB), the second lane is for larger files (>=0.1MB).
* This helps with parsing performance.
*/
const LANES: Lane[] = [{
maxSize: 0.005
-},{
+}, {
maxSize: 0.1
-},{
+}, {
maxSize: 1
-},{
+}, {
maxSize: 10
-},{
+}, {
maxSize: 100
}];
@@ -38,7 +38,7 @@ class BruParserWorker {
private workerQueues: WorkerQueueWithSize[];
constructor() {
- this.workerQueues = LANES?.map(lane => ({
+ this.workerQueues = LANES?.map((lane) => ({
maxSize: lane?.maxSize,
workerQueue: new WorkerQueue()
}));
@@ -47,7 +47,7 @@ class BruParserWorker {
private getWorkerQueue(size: number): WorkerQueue {
// Find the first queue that can handle the given size
// or fallback to the last queue for largest files
- const queueForSize = this.workerQueues.find((queue) =>
+ const queueForSize = this.workerQueues.find((queue) =>
queue.maxSize >= size
);
@@ -58,12 +58,12 @@ class BruParserWorker {
const size = getSize(data);
const workerQueue = this.getWorkerQueue(size);
const workerScriptPath = path.join(__dirname, './workers/worker-script.js');
-
+
return workerQueue.enqueue({
data: { data, format },
priority: size,
scriptPath: workerScriptPath,
- taskType,
+ taskType
});
}
@@ -76,11 +76,11 @@ class BruParserWorker {
}
async cleanup(): Promise {
- const cleanupPromises = this.workerQueues.map(({ workerQueue }) =>
+ const cleanupPromises = this.workerQueues.map(({ workerQueue }) =>
workerQueue.cleanup()
);
await Promise.allSettled(cleanupPromises);
}
}
-export default BruParserWorker;
\ No newline at end of file
+export default BruParserWorker;
diff --git a/packages/bruno-filestore/src/workers/worker-script.ts b/packages/bruno-filestore/src/workers/worker-script.ts
index 8fee2861c..84c26f604 100644
--- a/packages/bruno-filestore/src/workers/worker-script.ts
+++ b/packages/bruno-filestore/src/workers/worker-script.ts
@@ -38,4 +38,4 @@ parentPort?.on('message', async (message: WorkerMessage) => {
console.error('Worker error:', error);
parentPort?.postMessage({ error: error?.message });
}
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-js/src/bru.js b/packages/bruno-js/src/bru.js
index 25ed3fba0..27c00da33 100644
--- a/packages/bruno-js/src/bru.js
+++ b/packages/bruno-js/src/bru.js
@@ -23,7 +23,7 @@ class Bru {
this.cookies = {
jar: () => {
const cookieJar = createCookieJar();
-
+
return {
getCookie: (url, cookieName, callback) => {
const interpolatedUrl = this.interpolate(url);
@@ -225,8 +225,8 @@ class Bru {
if (variableNameRegex.test(key) === false) {
throw new Error(
- `Variable name: "${key}" contains invalid characters!` +
- ' Names must only contain alpha-numeric characters, "-", "_", "."'
+ `Variable name: "${key}" contains invalid characters!`
+ + ' Names must only contain alpha-numeric characters, "-", "_", "."'
);
}
@@ -236,8 +236,8 @@ class Bru {
getVar(key) {
if (variableNameRegex.test(key) === false) {
throw new Error(
- `Variable name: "${key}" contains invalid characters!` +
- ' Names must only contain alpha-numeric characters, "-", "_", "."'
+ `Variable name: "${key}" contains invalid characters!`
+ + ' Names must only contain alpha-numeric characters, "-", "_", "."'
);
}
diff --git a/packages/bruno-js/src/bruno-request.js b/packages/bruno-js/src/bruno-request.js
index 9738ada1f..12275fd53 100644
--- a/packages/bruno-js/src/bruno-request.js
+++ b/packages/bruno-js/src/bruno-request.js
@@ -6,7 +6,7 @@ class BrunoRequest {
* - req.headers
* - req.timeout
* - req.body
- *
+ *
* Above shorthands are useful for accessing the request properties directly in the scripts
* It must be noted that the user cannot set these properties directly.
* They should use the respective setter methods to set these properties.
@@ -22,9 +22,9 @@ class BrunoRequest {
/**
* We automatically parse the JSON body if the content type is JSON
* This is to make it easier for the user to access the body directly
- *
+ *
* It must be noted that the request data is always a string and is what gets sent over the network
- * If the user wants to access the raw data, they can use getBody({raw: true}) method
+ * If the user wants to access the raw data, they can use getBody({raw: true}) method
*/
const isJson = this.hasJSONContentType(this.req.headers);
if (isJson) {
@@ -44,6 +44,7 @@ class BrunoRequest {
getMethod() {
return this.req.method;
}
+
getAuthMode() {
if (this.req?.oauth2) {
return 'oauth2';
@@ -92,7 +93,7 @@ class BrunoRequest {
/**
* Get the body of the request
- *
+ *
* We automatically parse and return the JSON body if the content type is JSON
* If the user wants the raw body, they can pass the raw option as true
*/
@@ -116,7 +117,7 @@ class BrunoRequest {
* Otherwise
* - We set the request data as the data itself
* - We set the body property as the data itself
- *
+ *
* If the user wants to override this behavior, they can pass the raw option as true
*/
setBody(data, options = {}) {
@@ -149,7 +150,7 @@ class BrunoRequest {
this.timeout = timeout;
this.req.timeout = timeout;
}
-
+
onFail(callback) {
if (typeof callback === 'function') {
this.req.onFailHandler = callback;
@@ -177,7 +178,6 @@ class BrunoRequest {
__isObject(obj) {
return obj !== null && typeof obj === 'object';
}
-
disableParsingResponseJson() {
this.req.__brunoDisableParsingResponseJson = true;
diff --git a/packages/bruno-js/src/bruno-response.js b/packages/bruno-js/src/bruno-response.js
index 2a482c5e7..bdd091153 100644
--- a/packages/bruno-js/src/bruno-response.js
+++ b/packages/bruno-js/src/bruno-response.js
@@ -65,7 +65,7 @@ class BrunoResponse {
const { data, dataBuffer, headers } = this.res;
let bodySize = 0;
-
+
// Use raw received bytes
if (Buffer.isBuffer(dataBuffer)) {
bodySize = dataBuffer.length;
@@ -94,7 +94,6 @@ class BrunoResponse {
const headerSize = Buffer.byteLength(headerLines.join('\r\n'));
return { header: headerSize, body: bodySize, total: headerSize + bodySize };
-
}
getDataBuffer() {
diff --git a/packages/bruno-js/src/runtime/test-runtime.js b/packages/bruno-js/src/runtime/test-runtime.js
index bfdfeb578..f2d1764ab 100644
--- a/packages/bruno-js/src/runtime/test-runtime.js
+++ b/packages/bruno-js/src/runtime/test-runtime.js
@@ -76,7 +76,7 @@ class TestRuntime {
};
}
- if(runRequestByItemPathname) {
+ if (runRequestByItemPathname) {
context.bru.runRequest = runRequestByItemPathname;
}
diff --git a/packages/bruno-js/src/sandbox/node-vm/index.js b/packages/bruno-js/src/sandbox/node-vm/index.js
index 1e0a04798..aecfd9d8b 100644
--- a/packages/bruno-js/src/sandbox/node-vm/index.js
+++ b/packages/bruno-js/src/sandbox/node-vm/index.js
@@ -98,7 +98,6 @@ async function runScriptInNodeVm({
return;
}
-
/**
* Creates a custom require function with enhanced security and local module support
* @param {Object} options - Configuration options
diff --git a/packages/bruno-js/src/sandbox/quickjs/index.js b/packages/bruno-js/src/sandbox/quickjs/index.js
index c95381a15..ebe42bb83 100644
--- a/packages/bruno-js/src/sandbox/quickjs/index.js
+++ b/packages/bruno-js/src/sandbox/quickjs/index.js
@@ -24,7 +24,7 @@ const toNumber = (value) => {
};
const removeQuotes = (str) => {
- if ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith("'") && str.endsWith("'"))) {
+ if ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith('\'') && str.endsWith('\''))) {
return str.slice(1, -1);
}
return str;
@@ -36,7 +36,7 @@ const executeQuickJsVm = ({ script: externalScript, context: externalContext, sc
}
externalScript = externalScript?.trim();
- if(scriptType === 'template-literal') {
+ if (scriptType === 'template-literal') {
if (!isNaN(Number(externalScript))) {
const number = Number(externalScript);
diff --git a/packages/bruno-js/src/sandbox/quickjs/shims/bru.js b/packages/bruno-js/src/sandbox/quickjs/shims/bru.js
index 4a67a80f8..0029c3b59 100644
--- a/packages/bruno-js/src/sandbox/quickjs/shims/bru.js
+++ b/packages/bruno-js/src/sandbox/quickjs/shims/bru.js
@@ -296,7 +296,7 @@ const addBruShimToContext = (vm, bru) => {
const promise = vm.newPromise();
const dumpedUrl = vm.dump(url);
const dumpedNameOrObj = vm.dump(nameOrCookieObj);
-
+
// Check if the second argument is an object (cookie object case)
if (typeof dumpedNameOrObj === 'object' && dumpedNameOrObj !== null) {
// Cookie object case: setCookie(url, cookieObject, callback)
@@ -318,7 +318,7 @@ const addBruShimToContext = (vm, bru) => {
}
});
}
-
+
promise.settled.then(vm.runtime.executePendingJobs);
return promise.handle;
});
@@ -326,7 +326,7 @@ const addBruShimToContext = (vm, bru) => {
const _setCookiesFn = vm.newFunction('_setCookies', (url, cookiesArray) => {
const promise = vm.newPromise();
-
+
nativeJar.setCookies(vm.dump(url), vm.dump(cookiesArray), (err) => {
if (err) {
promise.reject(marshallToVm(cleanJson(err), vm));
diff --git a/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.js b/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.js
index 50933d5fe..3dc8d8b4e 100644
--- a/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.js
+++ b/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.js
@@ -10,7 +10,7 @@ const addCryptoUtilsShimToContext = async (vm) => {
let randomBytesHandle = vm.newFunction('randomBytes', function (sizeHandle) {
try {
let size = vm.dump(sizeHandle);
-
+
if (typeof size !== 'number') {
throw new TypeError('The "size" argument must be of type number');
}
@@ -30,15 +30,14 @@ const addCryptoUtilsShimToContext = async (vm) => {
}
const buffer = crypto.randomBytes(size);
-
+
const byteArray = Array.from(buffer);
-
+
return marshallToVm(byteArray, vm);
-
} catch (error) {
const vmError = vm.newError(error.message);
vm.setProp(vmError, 'name', vm.newString(error.name));
-
+
throw vmError;
}
});
@@ -48,7 +47,7 @@ const addCryptoUtilsShimToContext = async (vm) => {
// Receive the serialized array data directly
const serializedArray = vm.dump(arrayHandle);
const typedArray = deserializeTypedArray(serializedArray);
-
+
if (typedArray.length === 0) {
return marshallToVm([], vm);
}
@@ -62,11 +61,10 @@ const addCryptoUtilsShimToContext = async (vm) => {
const byteArray = Array.from(typedArray);
return marshallToVm(byteArray, vm);
-
} catch (error) {
const vmError = vm.newError(error.message);
vm.setProp(vmError, 'name', vm.newString(error.name));
-
+
throw vmError;
}
});
@@ -101,4 +99,4 @@ const addCryptoUtilsShimToContext = async (vm) => {
`);
};
-module.exports = addCryptoUtilsShimToContext;
\ No newline at end of file
+module.exports = addCryptoUtilsShimToContext;
diff --git a/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.spec.js b/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.spec.js
index 969ef514d..822a60264 100644
--- a/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.spec.js
+++ b/packages/bruno-js/src/sandbox/quickjs/shims/lib/crypto-utils.spec.js
@@ -27,7 +27,7 @@ describe('crypto-utils shims tests', () => {
const handle = vm.unwrapResult(result);
const type = vm.dump(handle);
handle.dispose();
-
+
expect(type).toBe('function');
});
@@ -36,7 +36,7 @@ describe('crypto-utils shims tests', () => {
const handle = vm.unwrapResult(result);
const type = vm.dump(handle);
handle.dispose();
-
+
expect(type).toBe('function');
});
@@ -45,7 +45,7 @@ describe('crypto-utils shims tests', () => {
const handle = vm.unwrapResult(result);
const length = vm.dump(handle);
handle.dispose();
-
+
expect(length).toBe(8);
});
@@ -54,7 +54,7 @@ describe('crypto-utils shims tests', () => {
const handle = vm.unwrapResult(result);
const hexLength = vm.dump(handle);
handle.dispose();
-
+
expect(hexLength).toBe(8); // 4 bytes = 8 hex chars
});
@@ -67,7 +67,7 @@ describe('crypto-utils shims tests', () => {
const handle = vm.unwrapResult(result);
const length = vm.dump(handle);
handle.dispose();
-
+
expect(length).toBe(5);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-js/src/sandbox/quickjs/shims/lib/utils.js b/packages/bruno-js/src/sandbox/quickjs/shims/lib/utils.js
index 757d14c52..dae5b2c38 100644
--- a/packages/bruno-js/src/sandbox/quickjs/shims/lib/utils.js
+++ b/packages/bruno-js/src/sandbox/quickjs/shims/lib/utils.js
@@ -45,4 +45,4 @@ function deserializeTypedArray(obj) {
module.exports = {
serializeTypedArray,
deserializeTypedArray
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-js/src/utils.js b/packages/bruno-js/src/utils.js
index c24a4f6ba..e92ea5653 100644
--- a/packages/bruno-js/src/utils.js
+++ b/packages/bruno-js/src/utils.js
@@ -89,7 +89,7 @@ const evaluateJsTemplateLiteral = (templateLiteral, context) => {
return templateLiteral.slice(1, -1);
}
- if (templateLiteral.startsWith("'") && templateLiteral.endsWith("'")) {
+ if (templateLiteral.startsWith('\'') && templateLiteral.endsWith('\'')) {
return templateLiteral.slice(1, -1);
}
@@ -197,18 +197,18 @@ const cleanCircularJson = (data) => {
try {
// Handle circular references by keeping track of seen objects
const seen = new WeakSet();
-
+
const replacer = (key, value) => {
// Skip non-objects and null
if (typeof value !== 'object' || value === null) {
return value;
}
-
+
// Detect circular reference
if (seen.has(value)) {
return '[Circular Reference]';
}
-
+
seen.add(value);
return value;
};
diff --git a/packages/bruno-js/src/utils/results.js b/packages/bruno-js/src/utils/results.js
index 0ed38638a..d59d81d25 100644
--- a/packages/bruno-js/src/utils/results.js
+++ b/packages/bruno-js/src/utils/results.js
@@ -7,7 +7,7 @@ const getResultsSummary = (results) => {
total: results.length,
passed: 0,
failed: 0,
- skipped: 0,
+ skipped: 0
};
results.forEach((r) => {
@@ -34,7 +34,7 @@ const setupBruTestMethods = (bru, __brunoTestResults, assertionResults) => {
const summary = getResultsSummary(results);
return {
summary,
- results: results.map(r => ({
+ results: results.map((r) => ({
status: r.status,
description: r.description,
expected: r.expected,
@@ -49,7 +49,7 @@ const setupBruTestMethods = (bru, __brunoTestResults, assertionResults) => {
const summary = getResultsSummary(results);
return {
summary,
- results: results.map(r => ({
+ results: results.map((r) => ({
status: r.status,
lhsExpr: r.lhsExpr,
rhsExpr: r.rhsExpr,
@@ -77,4 +77,4 @@ module.exports = {
getResultsSummary,
createBruTestResultMethods,
setupBruTestMethods
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-js/tests/runtime.spec.js b/packages/bruno-js/tests/runtime.spec.js
index a2d4d072d..352be604f 100644
--- a/packages/bruno-js/tests/runtime.spec.js
+++ b/packages/bruno-js/tests/runtime.spec.js
@@ -182,7 +182,7 @@ describe('runtime', () => {
it('should throw error when trying to persist non-string values', async () => {
const script = `bru.setEnvVar('number', 42, {persist: true});`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
await expect(runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env))
.rejects.toThrow('Persistent environment variables must be strings. Received number for key "number".');
});
@@ -190,7 +190,7 @@ describe('runtime', () => {
it('should throw error when trying to persist boolean values', async () => {
const script = `bru.setEnvVar('isActive', true, {persist: true});`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
await expect(runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env))
.rejects.toThrow('Persistent environment variables must be strings. Received boolean for key "isActive".');
});
@@ -198,7 +198,7 @@ describe('runtime', () => {
it('should throw error when trying to persist object values', async () => {
const script = `bru.setEnvVar('config', {port: 3000}, {persist: true});`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
await expect(runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env))
.rejects.toThrow('Persistent environment variables must be strings. Received object for key "config".');
});
@@ -206,7 +206,7 @@ describe('runtime', () => {
it('should throw error when trying to persist array values', async () => {
const script = `bru.setEnvVar('items', ['item1', 'item2'], {persist: true});`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
await expect(runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env))
.rejects.toThrow('Persistent environment variables must be strings. Received object for key "items".');
});
@@ -214,9 +214,9 @@ describe('runtime', () => {
it('should allow string values when persist is true', async () => {
const script = `bru.setEnvVar('api_key', 'abc123', {persist: true});`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
-
+
expect(result.envVariables.api_key).toBe('abc123');
});
@@ -228,21 +228,21 @@ describe('runtime', () => {
bru.setEnvVar('array', [1, 2, 3], {persist: false});
`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables.number).toBe(42);
expect(result.envVariables.boolean).toBe(true);
- expect(result.envVariables.object).toEqual({key: 'value'});
+ expect(result.envVariables.object).toEqual({ key: 'value' });
expect(result.envVariables.array).toEqual([1, 2, 3]);
});
it('should allow non-string values when persist is not specified', async () => {
const script = `bru.setEnvVar('number', 42);`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
-
+
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
-
+
expect(result.envVariables.number).toBe(42);
});
});
diff --git a/packages/bruno-js/tests/utils.spec.js b/packages/bruno-js/tests/utils.spec.js
index b7c6e6022..6d1fa070d 100644
--- a/packages/bruno-js/tests/utils.spec.js
+++ b/packages/bruno-js/tests/utils.spec.js
@@ -76,7 +76,7 @@ describe('utils', () => {
});
it('should be ok picking extra vars from strings', () => {
- const expr = "'hello' + ' ' + res.data.pets[0]";
+ const expr = '\'hello\' + \' \' + res.data.pets[0]';
const result = evaluateJsExpression(expr, context);
expect(result).toBe('hello bruno');
// extra var hello is harmless
@@ -125,7 +125,7 @@ describe('utils', () => {
const expr = 'res["__bruno__functionInnerContext"].toUpperCase()';
expect(() => evaluateJsExpression(expr, context)).toThrow(SyntaxError);
expect(() => evaluateJsExpression(expr, context)).toThrow(
- "Identifier '__bruno__functionInnerContext' has already been declared"
+ 'Identifier \'__bruno__functionInnerContext\' has already been declared'
);
});
});
diff --git a/packages/bruno-lang/v1/tests/bru-to-json.spec.js b/packages/bruno-lang/v1/tests/bru-to-json.spec.js
index b2d48d21a..b14d8f411 100644
--- a/packages/bruno-lang/v1/tests/bru-to-json.spec.js
+++ b/packages/bruno-lang/v1/tests/bru-to-json.spec.js
@@ -82,8 +82,8 @@ describe('bruToJson', () => {
}
]
},
- script: "const foo='bar';",
- tests: "bruno.test('200 ok', () => {});"
+ script: 'const foo=\'bar\';',
+ tests: 'bruno.test(\'200 ok\', () => {});'
}
});
});
diff --git a/packages/bruno-lang/v1/tests/json-to-bru.spec.js b/packages/bruno-lang/v1/tests/json-to-bru.spec.js
index 9b2b71356..b432148fa 100644
--- a/packages/bruno-lang/v1/tests/json-to-bru.spec.js
+++ b/packages/bruno-lang/v1/tests/json-to-bru.spec.js
@@ -79,8 +79,8 @@ describe('bruToJson', () => {
}
]
},
- script: "const foo='bar';",
- tests: "bruno.test('200 ok', () => {});"
+ script: 'const foo=\'bar\';',
+ tests: 'bruno.test(\'200 ok\', () => {});'
}
};
diff --git a/packages/bruno-lang/v2/src/bruToJson.js b/packages/bruno-lang/v2/src/bruToJson.js
index 35018a910..17c9bf97d 100644
--- a/packages/bruno-lang/v2/src/bruToJson.js
+++ b/packages/bruno-lang/v2/src/bruToJson.js
@@ -233,7 +233,6 @@ const fileExtractContentType = (pair) => {
}
};
-
const mapPairListToKeyValPairsMultipart = (pairList = [], parseEnabled = true) => {
const pairs = mapPairListToKeyValPairs(pairList, parseEnabled);
@@ -257,10 +256,10 @@ const mapPairListToKeyValPairsFile = (pairList = [], parseEnabled = true) => {
fileExtractContentType(pair);
if (pair.value.startsWith('@file(') && pair.value.endsWith(')')) {
- let filePath = pair.value.replace(/^@file\(/, '').replace(/\)$/, '');
+ let filePath = pair.value.replace(/^@file\(/, '').replace(/\)$/, '');
pair.filePath = filePath;
- pair.selected = pair.enabled
-
+ pair.selected = pair.enabled;
+
// Remove pair.value as it only contains the file path reference
delete pair.value;
// Remove pair.name as it is auto-generated (e.g., file1, file2, file3, etc.)
@@ -365,7 +364,7 @@ const sem = grammar.createSemantics().addAttribute('ast', {
},
quoted_key(disabled, _1, chars, _2) {
// unquote
- return (disabled? disabled.sourceString : "") + chars.ast.join("");
+ return (disabled ? disabled.sourceString : '') + chars.ast.join('');
},
key(chars) {
return chars.sourceString ? chars.sourceString.trim() : '';
@@ -404,10 +403,10 @@ const sem = grammar.createSemantics().addAttribute('ast', {
return chars.sourceString ? chars.sourceString.trim() : '';
},
list(_1, _2, _3, listitems, _4, _5, _6, _7) {
- return listitems.ast.flat()
+ return listitems.ast.flat();
},
listitems(listitem, _1, rest) {
- return [listitem.ast, ...rest.ast]
+ return [listitem.ast, ...rest.ast];
},
listitem(_1, textchar, _2) {
return textchar.sourceString;
@@ -430,7 +429,7 @@ const sem = grammar.createSemantics().addAttribute('ast', {
tagend(_1, _2) {
return '';
},
- _terminal(){
+ _terminal() {
return this.sourceString;
},
multilinetextblockdelimiter(_) {
@@ -717,7 +716,7 @@ const sem = grammar.createSemantics().addAttribute('ast', {
}
}
};
- },
+ },
authOAuth2(_1, dictionary) {
const auth = mapPairListToKeyValPairs(dictionary.ast, false);
const grantTypeKey = _.find(auth, { name: 'grant_type' });
@@ -761,56 +760,56 @@ const sem = grammar.createSemantics().addAttribute('ast', {
autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
}
: grantTypeKey?.value && grantTypeKey?.value == 'authorization_code'
- ? {
- grantType: grantTypeKey ? grantTypeKey.value : '',
- callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
- authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
- accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
- refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
- clientId: clientIdKey ? clientIdKey.value : '',
- clientSecret: clientSecretKey ? clientSecretKey.value : '',
- scope: scopeKey ? scopeKey.value : '',
- state: stateKey ? stateKey.value : '',
- pkce: pkceKey ? safeParseJson(pkceKey?.value) ?? false : false,
- credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
- credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
- tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
- tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
- tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
- autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
- autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
- }
- : grantTypeKey?.value && grantTypeKey?.value == 'client_credentials'
- ? {
- grantType: grantTypeKey ? grantTypeKey.value : '',
- accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
- refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
- clientId: clientIdKey ? clientIdKey.value : '',
- clientSecret: clientSecretKey ? clientSecretKey.value : '',
- scope: scopeKey ? scopeKey.value : '',
- credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
- credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
- tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
- tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
- tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
- autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
- autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
- }
- : grantTypeKey?.value && grantTypeKey?.value == 'implicit'
- ? {
- grantType: grantTypeKey ? grantTypeKey.value : '',
- callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
- authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
- clientId: clientIdKey ? clientIdKey.value : '',
- scope: scopeKey ? scopeKey.value : '',
- state: stateKey ? stateKey.value : '',
- credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
- tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
- tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
- tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
- autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
- }
- : {}
+ ? {
+ grantType: grantTypeKey ? grantTypeKey.value : '',
+ callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
+ authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
+ accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
+ refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
+ clientId: clientIdKey ? clientIdKey.value : '',
+ clientSecret: clientSecretKey ? clientSecretKey.value : '',
+ scope: scopeKey ? scopeKey.value : '',
+ state: stateKey ? stateKey.value : '',
+ pkce: pkceKey ? safeParseJson(pkceKey?.value) ?? false : false,
+ credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
+ credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
+ tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
+ tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
+ tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
+ autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
+ autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
+ }
+ : grantTypeKey?.value && grantTypeKey?.value == 'client_credentials'
+ ? {
+ grantType: grantTypeKey ? grantTypeKey.value : '',
+ accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
+ refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
+ clientId: clientIdKey ? clientIdKey.value : '',
+ clientSecret: clientSecretKey ? clientSecretKey.value : '',
+ scope: scopeKey ? scopeKey.value : '',
+ credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
+ credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
+ tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
+ tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
+ tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
+ autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
+ autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
+ }
+ : grantTypeKey?.value && grantTypeKey?.value == 'implicit'
+ ? {
+ grantType: grantTypeKey ? grantTypeKey.value : '',
+ callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
+ authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
+ clientId: clientIdKey ? clientIdKey.value : '',
+ scope: scopeKey ? scopeKey.value : '',
+ state: stateKey ? stateKey.value : '',
+ credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
+ tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
+ tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
+ tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
+ autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true
+ }
+ : {}
}
};
},
@@ -1039,10 +1038,10 @@ const sem = grammar.createSemantics().addAttribute('ast', {
const pairs = mapPairListToKeyValPairs(dictionary.ast, false);
const namePair = _.find(pairs, { name: 'name' });
const contentPair = _.find(pairs, { name: 'content' });
-
+
const messageName = namePair ? namePair.value : '';
const messageContent = contentPair ? contentPair.value : '';
-
+
return {
body: {
mode: 'grpc',
@@ -1092,7 +1091,7 @@ const parser = (input) => {
const match = grammar.match(input);
if (match.succeeded()) {
- let ast = sem(match).ast
+ let ast = sem(match).ast;
return ast;
} else {
diff --git a/packages/bruno-lang/v2/src/collectionBruToJson.js b/packages/bruno-lang/v2/src/collectionBruToJson.js
index 4d0ce8d6c..8fe6eced4 100644
--- a/packages/bruno-lang/v2/src/collectionBruToJson.js
+++ b/packages/bruno-lang/v2/src/collectionBruToJson.js
@@ -366,56 +366,56 @@ const sem = grammar.createSemantics().addAttribute('ast', {
autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
}
: grantTypeKey?.value && grantTypeKey?.value == 'authorization_code'
- ? {
- grantType: grantTypeKey ? grantTypeKey.value : '',
- callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
- authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
- accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
- refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
- clientId: clientIdKey ? clientIdKey.value : '',
- clientSecret: clientSecretKey ? clientSecretKey.value : '',
- scope: scopeKey ? scopeKey.value : '',
- state: stateKey ? stateKey.value : '',
- pkce: pkceKey ? safeParseJson(pkceKey?.value) ?? false : false,
- credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
- credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
- tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
- tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
- tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
- autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
- autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
- }
- : grantTypeKey?.value && grantTypeKey?.value == 'implicit'
- ? {
- grantType: grantTypeKey ? grantTypeKey.value : '',
- callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
- authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
- clientId: clientIdKey ? clientIdKey.value : '',
- scope: scopeKey ? scopeKey.value : '',
- state: stateKey ? stateKey.value : '',
- credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
- tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
- tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
- tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
- autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
- }
- : grantTypeKey?.value && grantTypeKey?.value == 'client_credentials'
- ? {
- grantType: grantTypeKey ? grantTypeKey.value : '',
- accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
- refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
- clientId: clientIdKey ? clientIdKey.value : '',
- clientSecret: clientSecretKey ? clientSecretKey.value : '',
- scope: scopeKey ? scopeKey.value : '',
- credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
- credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
- tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
- tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
- tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
- autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
- autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
- }
- : {}
+ ? {
+ grantType: grantTypeKey ? grantTypeKey.value : '',
+ callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
+ authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
+ accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
+ refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
+ clientId: clientIdKey ? clientIdKey.value : '',
+ clientSecret: clientSecretKey ? clientSecretKey.value : '',
+ scope: scopeKey ? scopeKey.value : '',
+ state: stateKey ? stateKey.value : '',
+ pkce: pkceKey ? safeParseJson(pkceKey?.value) ?? false : false,
+ credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
+ credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
+ tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
+ tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
+ tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
+ autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
+ autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
+ }
+ : grantTypeKey?.value && grantTypeKey?.value == 'implicit'
+ ? {
+ grantType: grantTypeKey ? grantTypeKey.value : '',
+ callbackUrl: callbackUrlKey ? callbackUrlKey.value : '',
+ authorizationUrl: authorizationUrlKey ? authorizationUrlKey.value : '',
+ clientId: clientIdKey ? clientIdKey.value : '',
+ scope: scopeKey ? scopeKey.value : '',
+ state: stateKey ? stateKey.value : '',
+ credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
+ tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
+ tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
+ tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
+ autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true
+ }
+ : grantTypeKey?.value && grantTypeKey?.value == 'client_credentials'
+ ? {
+ grantType: grantTypeKey ? grantTypeKey.value : '',
+ accessTokenUrl: accessTokenUrlKey ? accessTokenUrlKey.value : '',
+ refreshTokenUrl: refreshTokenUrlKey ? refreshTokenUrlKey.value : '',
+ clientId: clientIdKey ? clientIdKey.value : '',
+ clientSecret: clientSecretKey ? clientSecretKey.value : '',
+ scope: scopeKey ? scopeKey.value : '',
+ credentialsPlacement: credentialsPlacementKey?.value ? credentialsPlacementKey.value : 'body',
+ credentialsId: credentialsIdKey?.value ? credentialsIdKey.value : 'credentials',
+ tokenPlacement: tokenPlacementKey?.value ? tokenPlacementKey.value : 'header',
+ tokenHeaderPrefix: tokenHeaderPrefixKey?.value ? tokenHeaderPrefixKey.value : '',
+ tokenQueryKey: tokenQueryKeyKey?.value ? tokenQueryKeyKey.value : 'access_token',
+ autoFetchToken: autoFetchTokenKey ? safeParseJson(autoFetchTokenKey?.value) ?? true : true,
+ autoRefreshToken: autoRefreshTokenKey ? safeParseJson(autoRefreshTokenKey?.value) ?? false : false
+ }
+ : {}
}
};
},
@@ -472,8 +472,8 @@ const sem = grammar.createSemantics().addAttribute('ast', {
password
}
}
- }
- },
+ };
+ },
authapikey(_1, dictionary) {
const auth = mapPairListToKeyValPairs(dictionary.ast, false);
diff --git a/packages/bruno-lang/v2/src/jsonToBru.js b/packages/bruno-lang/v2/src/jsonToBru.js
index b7decd9ef..420ca90d7 100644
--- a/packages/bruno-lang/v2/src/jsonToBru.js
+++ b/packages/bruno-lang/v2/src/jsonToBru.js
@@ -3,8 +3,8 @@ const _ = require('lodash');
const { indentString, getValueString, getKeyString, getValueUrl } = require('./utils');
const jsonToExampleBru = require('./example/jsonToBru');
-const enabled = (items = [], key = "enabled") => items.filter((item) => item[key]);
-const disabled = (items = [], key = "enabled") => items.filter((item) => !item[key]);
+const enabled = (items = [], key = 'enabled') => items.filter((item) => item[key]);
+const disabled = (items = [], key = 'enabled') => items.filter((item) => !item[key]);
// remove the last line if two new lines are found
const stripLastLine = (text) => {
@@ -59,21 +59,21 @@ const jsonToBru = (json) => {
bru += `\n}\n\n`;
}
- if(grpc && grpc.url) {
- bru += `grpc {
+ if (grpc && grpc.url) {
+ bru += `grpc {
url: ${grpc.url}`;
- if(grpc.method && grpc.method.length) {
+ if (grpc.method && grpc.method.length) {
bru += `
method: ${grpc.method}`;
}
- if(grpc.body && grpc.body.length) {
+ if (grpc.body && grpc.body.length) {
bru += `
body: ${grpc.body}`;
}
- if(grpc.protoPath && grpc.protoPath.length) {
+ if (grpc.protoPath && grpc.protoPath.length) {
bru += `
protoPath: ${grpc.protoPath}`;
}
@@ -119,7 +119,6 @@ const jsonToBru = (json) => {
`;
}
-
if (params && params.length) {
const queryParams = params.filter((param) => param.type === 'query');
const pathParams = params.filter((param) => param.type === 'path');
@@ -244,7 +243,6 @@ ${indentString(`password: ${auth?.digest?.password || ''}`)}
`;
}
-
if (auth && auth.ntlm) {
bru += `auth:ntlm {
${indentString(`username: ${auth?.ntlm?.username || ''}`)}
@@ -350,106 +348,106 @@ ${indentString(`auto_fetch_token: ${(auth?.oauth2?.autoFetchToken ?? true).toStr
if (auth?.oauth2?.additionalParameters) {
const { authorization: authorizationParams, token: tokenParams, refresh: refreshParams } = auth?.oauth2?.additionalParameters;
- const authorizationHeaders = authorizationParams?.filter(p => p?.sendIn == 'headers');
+ const authorizationHeaders = authorizationParams?.filter((p) => p?.sendIn == 'headers');
if (authorizationHeaders?.length) {
bru += `auth:oauth2:additional_params:auth_req:headers {
${indentString(
authorizationHeaders
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const authorizationQueryParams = authorizationParams?.filter(p => p?.sendIn == 'queryparams');
+ const authorizationQueryParams = authorizationParams?.filter((p) => p?.sendIn == 'queryparams');
if (authorizationQueryParams?.length) {
bru += `auth:oauth2:additional_params:auth_req:queryparams {
${indentString(
authorizationQueryParams
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const tokenHeaders = tokenParams?.filter(p => p?.sendIn == 'headers');
+ const tokenHeaders = tokenParams?.filter((p) => p?.sendIn == 'headers');
if (tokenHeaders?.length) {
bru += `auth:oauth2:additional_params:access_token_req:headers {
${indentString(
tokenHeaders
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const tokenQueryParams = tokenParams?.filter(p => p?.sendIn == 'queryparams');
+ const tokenQueryParams = tokenParams?.filter((p) => p?.sendIn == 'queryparams');
if (tokenQueryParams?.length) {
bru += `auth:oauth2:additional_params:access_token_req:queryparams {
${indentString(
tokenQueryParams
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const tokenBodyValues = tokenParams?.filter(p => p?.sendIn == 'body');
+ const tokenBodyValues = tokenParams?.filter((p) => p?.sendIn == 'body');
if (tokenBodyValues?.length) {
bru += `auth:oauth2:additional_params:access_token_req:body {
${indentString(
tokenBodyValues
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const refreshHeaders = refreshParams?.filter(p => p?.sendIn == 'headers');
+ const refreshHeaders = refreshParams?.filter((p) => p?.sendIn == 'headers');
if (refreshHeaders?.length) {
bru += `auth:oauth2:additional_params:refresh_token_req:headers {
${indentString(
refreshHeaders
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const refreshQueryParams = refreshParams?.filter(p => p?.sendIn == 'queryparams');
+ const refreshQueryParams = refreshParams?.filter((p) => p?.sendIn == 'queryparams');
if (refreshQueryParams?.length) {
bru += `auth:oauth2:additional_params:refresh_token_req:queryparams {
${indentString(
refreshQueryParams
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const refreshBodyValues = refreshParams?.filter(p => p?.sendIn == 'body');
+ const refreshBodyValues = refreshParams?.filter((p) => p?.sendIn == 'body');
if (refreshBodyValues?.length) {
bru += `auth:oauth2:additional_params:refresh_token_req:body {
${indentString(
refreshBodyValues
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
@@ -528,8 +526,8 @@ ${indentString(body.sparql)}
multipartForms
.map((item) => {
const enabled = item.enabled ? '' : '~';
- const contentType =
- item.contentType && item.contentType !== '' ? ' @contentType(' + item.contentType + ')' : '';
+ const contentType
+ = item.contentType && item.contentType !== '' ? ' @contentType(' + item.contentType + ')' : '';
if (item.type === 'text') {
return `${enabled}${getKeyString(item.name)}: ${getValueString(item.value)}${contentType}`;
@@ -550,21 +548,20 @@ ${indentString(body.sparql)}
bru += '\n}\n\n';
}
-
if (body && body.file && body.file.length) {
bru += `body:file {`;
- const files = enabled(body.file, "selected").concat(disabled(body.file, "selected"));
+ const files = enabled(body.file, 'selected').concat(disabled(body.file, 'selected'));
if (files.length) {
bru += `\n${indentString(
files
.map((item) => {
const selected = item.selected ? '' : '~';
- const contentType =
- item.contentType && item.contentType !== '' ? ' @contentType(' + item.contentType + ')' : '';
+ const contentType
+ = item.contentType && item.contentType !== '' ? ' @contentType(' + item.contentType + ')' : '';
const filePath = item.filePath || '';
const value = `@file(${filePath})`;
- const itemName = "file";
+ const itemName = 'file';
return `${selected}${itemName}: ${value}${contentType}`;
})
.join('\n')
@@ -590,15 +587,15 @@ ${indentString(body.sparql)}
// Convert each gRPC message to a separate body:grpc block
if (Array.isArray(body.grpc)) {
body.grpc.forEach((m) => {
- const {name, content} = m;
-
+ const { name, content } = m;
+
bru += `body:grpc {\n`;
-
+
bru += `${indentString(`name: ${getValueString(name)}`)}\n`;
-
+
// Convert content to JSON string if it's an object
let jsonValue = typeof content === 'object' ? JSON.stringify(content, null, 2) : content || '{}';
-
+
// Wrap content with triple quotes for multiline support, without extra indentation
bru += `${indentString(`content: '''\n${indentString(jsonValue)}\n'''`)}\n`;
bru += '}\n\n';
diff --git a/packages/bruno-lang/v2/src/jsonToCollectionBru.js b/packages/bruno-lang/v2/src/jsonToCollectionBru.js
index 5016611c0..cc5428996 100644
--- a/packages/bruno-lang/v2/src/jsonToCollectionBru.js
+++ b/packages/bruno-lang/v2/src/jsonToCollectionBru.js
@@ -122,9 +122,9 @@ ${indentString(`password: ${auth.digest.password}`)}
`;
}
-
-if (auth && auth.ntlm) {
- bru += `auth:ntlm {
+
+ if (auth && auth.ntlm) {
+ bru += `auth:ntlm {
${indentString(`username: ${auth.ntlm.username}`)}
${indentString(`password: ${auth.ntlm.password}`)}
${indentString(`domain: ${auth.ntlm.domain}`)}
@@ -237,105 +237,105 @@ ${indentString(`auto_refresh_token: ${(auth?.oauth2?.autoRefreshToken ?? false).
if (auth?.oauth2?.additionalParameters) {
const { authorization: authorizationParams, token: tokenParams, refresh: refreshParams } = auth?.oauth2?.additionalParameters;
- const authorizationHeaders = authorizationParams?.filter(p => p?.sendIn == 'headers');
+ const authorizationHeaders = authorizationParams?.filter((p) => p?.sendIn == 'headers');
if (authorizationHeaders?.length) {
bru += `auth:oauth2:additional_params:auth_req:headers {
${indentString(
authorizationHeaders
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const authorizationQueryParams = authorizationParams?.filter(p => p?.sendIn == 'queryparams');
+ const authorizationQueryParams = authorizationParams?.filter((p) => p?.sendIn == 'queryparams');
if (authorizationQueryParams?.length) {
bru += `auth:oauth2:additional_params:auth_req:queryparams {
${indentString(
authorizationQueryParams
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const tokenHeaders = tokenParams?.filter(p => p?.sendIn == 'headers');
+ const tokenHeaders = tokenParams?.filter((p) => p?.sendIn == 'headers');
if (tokenHeaders?.length) {
bru += `auth:oauth2:additional_params:access_token_req:headers {
${indentString(
tokenHeaders
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const tokenQueryParams = tokenParams?.filter(p => p?.sendIn == 'queryparams');
+ const tokenQueryParams = tokenParams?.filter((p) => p?.sendIn == 'queryparams');
if (tokenQueryParams?.length) {
bru += `auth:oauth2:additional_params:access_token_req:queryparams {
${indentString(
tokenQueryParams
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n'))}
}
`;
}
- const tokenBodyValues = tokenParams?.filter(p => p?.sendIn == 'body');
+ const tokenBodyValues = tokenParams?.filter((p) => p?.sendIn == 'body');
if (tokenBodyValues?.length) {
bru += `auth:oauth2:additional_params:access_token_req:body {
${indentString(
tokenBodyValues
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const refreshHeaders = refreshParams?.filter(p => p?.sendIn == 'headers');
+ const refreshHeaders = refreshParams?.filter((p) => p?.sendIn == 'headers');
if (refreshHeaders?.length) {
bru += `auth:oauth2:additional_params:refresh_token_req:headers {
${indentString(
refreshHeaders
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const refreshQueryParams = refreshParams?.filter(p => p?.sendIn == 'queryparams');
+ const refreshQueryParams = refreshParams?.filter((p) => p?.sendIn == 'queryparams');
if (refreshQueryParams?.length) {
bru += `auth:oauth2:additional_params:refresh_token_req:queryparams {
${indentString(
refreshQueryParams
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
}
- const refreshBodyValues = refreshParams?.filter(p => p?.sendIn == 'body');
+ const refreshBodyValues = refreshParams?.filter((p) => p?.sendIn == 'body');
if (refreshBodyValues?.length) {
bru += `auth:oauth2:additional_params:refresh_token_req:body {
${indentString(
refreshBodyValues
- .filter(item => item?.name?.length)
+ .filter((item) => item?.name?.length)
.map((item) => `${item.enabled ? '' : '~'}${getKeyString(item.name)}: ${getValueString(item.value)}`)
.join('\n')
- )}
+)}
}
`;
diff --git a/packages/bruno-lang/v2/src/utils.js b/packages/bruno-lang/v2/src/utils.js
index 5b666cc68..cff670015 100644
--- a/packages/bruno-lang/v2/src/utils.js
+++ b/packages/bruno-lang/v2/src/utils.js
@@ -7,7 +7,6 @@ const safeParseJson = (json) => {
}
};
-
const indentString = (str, levels = 1) => {
if (!str || !str.length) {
return str || '';
diff --git a/packages/bruno-lang/v2/tests/list.spec.js b/packages/bruno-lang/v2/tests/list.spec.js
index 19804779f..abf52767c 100644
--- a/packages/bruno-lang/v2/tests/list.spec.js
+++ b/packages/bruno-lang/v2/tests/list.spec.js
@@ -4,7 +4,6 @@
const parser = require('../src/bruToJson');
describe('List Support in BruFile Blocks', () => {
-
describe('Basic List Functionality', () => {
describe('Valid List Syntax', () => {
it('should parse simple list with proper indentation', () => {
@@ -21,7 +20,7 @@ meta {
meta: {
seq: 1,
tags: ['tag_1', 'tag_2'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -42,9 +41,9 @@ meta {
const expected = {
meta: {
seq: 1,
- name: "request_name",
+ name: 'request_name',
tags: ['regression', 'smoke_test'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -65,7 +64,7 @@ meta {
meta: {
seq: 1,
tags: ['tag_1', 'tag_2', 'tag_3'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -87,7 +86,7 @@ meta {
meta: {
seq: 1,
tags: ['tag-with-hyphens', 'tag_with_underscores', 'tag123numbers', 'CamelCaseTag'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -227,9 +226,9 @@ meta {
const expected = {
meta: {
seq: 1,
- name: "[some name]",
+ name: '[some name]',
tags: ['actual_list_item'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -249,9 +248,9 @@ meta {
const expected = {
meta: {
seq: 1,
- name: "[ this is the name ]",
+ name: '[ this is the name ]',
tags: ['tag_1', 'tag_2'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -285,10 +284,10 @@ meta {
const output = parser(input);
const expected = {
meta: {
- name: "API Test",
+ name: 'API Test',
tags: ['api', 'integration', 'v1'],
seq: 1,
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -313,7 +312,7 @@ meta {
seq: 1,
categories: ['user-management', 'auth'],
environments: ['staging', 'production'],
- type: "http"
+ type: 'http'
}
};
expect(output).toEqual(expected);
@@ -344,10 +343,10 @@ body:text {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -388,10 +387,10 @@ body:text {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -432,10 +431,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -476,10 +475,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -520,10 +519,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -570,10 +569,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -616,10 +615,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -650,10 +649,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -696,10 +695,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -761,10 +760,10 @@ body:json {
const expected = {
meta: {
- name: "[name]",
+ name: '[name]',
tags: [
- "tag_1",
- "tag_2"
+ 'tag_1',
+ 'tag_2'
],
seq: 1,
type: 'http'
@@ -795,4 +794,4 @@ body:json {
expect(output).toEqual(expected);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-lang/v2/tests/oauth2-additional-params.spec.js b/packages/bruno-lang/v2/tests/oauth2-additional-params.spec.js
index c38ea7ef0..2cbbac4f0 100644
--- a/packages/bruno-lang/v2/tests/oauth2-additional-params.spec.js
+++ b/packages/bruno-lang/v2/tests/oauth2-additional-params.spec.js
@@ -63,7 +63,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
`.trim();
const result = bruToJson(input);
-
+
// Verify all config types are present
expect(result).toHaveProperty('oauth2_additional_parameters_auth_req_headers');
expect(result).toHaveProperty('oauth2_additional_parameters_auth_req_queryparams');
@@ -94,7 +94,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-auth-header-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_auth_req_queryparams).toEqual([{
name: 'auth-query-param',
value: 'auth-query-param-value',
@@ -104,7 +104,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-auth-query-param-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_access_token_req_headers).toEqual([{
name: 'token-header',
value: 'token-header-value',
@@ -114,7 +114,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-token-header-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_access_token_req_queryparams).toEqual([{
name: 'token-query-param',
value: 'token-query-param-value',
@@ -124,7 +124,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-token-query-param-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_access_token_req_bodyvalues).toEqual([{
name: 'token-body',
value: 'token-body-value',
@@ -134,7 +134,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-token-body-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_refresh_token_req_headers).toEqual([{
name: 'refresh-header',
value: 'refresh-header-value',
@@ -144,7 +144,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-refresh-header-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_refresh_token_req_queryparams).toEqual([{
name: 'refresh-query-param',
value: 'refresh-query-param-value',
@@ -154,7 +154,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-refresh-query-param-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_refresh_token_req_bodyvalues).toEqual([{
name: 'refresh-body',
value: 'refresh-body-value',
@@ -224,7 +224,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
`.trim();
const result = collectionBruToJson(input);
-
+
// Verify all config types are present
expect(result).toHaveProperty('oauth2_additional_parameters_auth_req_headers');
expect(result).toHaveProperty('oauth2_additional_parameters_auth_req_queryparams');
@@ -255,7 +255,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-auth-header-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_auth_req_queryparams).toEqual([{
name: 'auth-query-param',
value: 'auth-query-param-value',
@@ -265,7 +265,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-auth-query-param-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_access_token_req_headers).toEqual([{
name: 'token-header',
value: 'token-header-value',
@@ -275,7 +275,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-token-header-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_access_token_req_queryparams).toEqual([{
name: 'token-query-param',
value: 'token-query-param-value',
@@ -285,7 +285,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-token-query-param-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_access_token_req_bodyvalues).toEqual([{
name: 'token-body',
value: 'token-body-value',
@@ -295,7 +295,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-token-body-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_refresh_token_req_headers).toEqual([{
name: 'refresh-header',
value: 'refresh-header-value',
@@ -305,7 +305,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-refresh-header-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_refresh_token_req_queryparams).toEqual([{
name: 'refresh-query-param',
value: 'refresh-query-param-value',
@@ -315,7 +315,7 @@ auth:oauth2:additional_params:refresh_token_req:body {
value: 'disabled-refresh-query-param-value',
enabled: false
}]);
-
+
expect(result.oauth2_additional_parameters_refresh_token_req_bodyvalues).toEqual([{
name: 'refresh-body',
value: 'refresh-body-value',
@@ -326,4 +326,4 @@ auth:oauth2:additional_params:refresh_token_req:body {
enabled: false
}]);
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-lang/v2/tests/script.spec.js b/packages/bruno-lang/v2/tests/script.spec.js
index 7d4f50b53..232db4c74 100644
--- a/packages/bruno-lang/v2/tests/script.spec.js
+++ b/packages/bruno-lang/v2/tests/script.spec.js
@@ -14,7 +14,7 @@ script:pre-request {
const output = parser(input);
const expected = {
script: {
- req: "$req.setHeader('Content-Type', 'application/json');"
+ req: '$req.setHeader(\'Content-Type\', \'application/json\');'
}
};
expect(output).toEqual(expected);
diff --git a/packages/bruno-lang/v2/tests/utils.spec.js b/packages/bruno-lang/v2/tests/utils.spec.js
index e63c96c3b..6ac249f0f 100644
--- a/packages/bruno-lang/v2/tests/utils.spec.js
+++ b/packages/bruno-lang/v2/tests/utils.spec.js
@@ -6,7 +6,7 @@ describe('getValueString', () => {
});
it('wraps multiline value in triple quotes with indentation', () => {
- expect(getValueString('line1\nline2\nline3')).toBe("'''\n line1\n line2\n line3\n'''");
+ expect(getValueString('line1\nline2\nline3')).toBe('\'\'\'\n line1\n line2\n line3\n\'\'\'');
});
it('normalizes different newline types', () => {
diff --git a/packages/bruno-requests/babel.config.js b/packages/bruno-requests/babel.config.js
index d19d38b94..ca92638f5 100644
--- a/packages/bruno-requests/babel.config.js
+++ b/packages/bruno-requests/babel.config.js
@@ -1,6 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
- '@babel/preset-typescript',
- ],
-};
\ No newline at end of file
+ '@babel/preset-typescript'
+ ]
+};
diff --git a/packages/bruno-requests/jest.config.js b/packages/bruno-requests/jest.config.js
index ae522cdc8..417b96c60 100644
--- a/packages/bruno-requests/jest.config.js
+++ b/packages/bruno-requests/jest.config.js
@@ -1,6 +1,6 @@
module.exports = {
transform: {
- '^.+\\.(ts|js)$': 'babel-jest',
+ '^.+\\.(ts|js)$': 'babel-jest'
},
transformIgnorePatterns: [
'/node_modules/(?!(lodash-es|is-ip|ip-regex|super-regex|function-timeout|time-span|convert-hrtime|clone-regexp|is-regexp)/)'
@@ -10,4 +10,4 @@ module.exports = {
'**/*.(test|spec).(ts|js)'
],
moduleFileExtensions: ['ts', 'js', 'json']
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-requests/rollup.config.js b/packages/bruno-requests/rollup.config.js
index bd0907f29..0d00804a1 100644
--- a/packages/bruno-requests/rollup.config.js
+++ b/packages/bruno-requests/rollup.config.js
@@ -7,7 +7,6 @@ const peerDepsExternal = require('rollup-plugin-peer-deps-external');
const json = require('@rollup/plugin-json');
const packageJson = require('./package.json');
-
module.exports = [
{
input: 'src/index.ts',
@@ -30,14 +29,14 @@ module.exports = [
nodeResolve({
extensions: ['.js', '.ts', '.tsx', '.json', '.css'],
dedupe: ['@grpc/grpc-js'],
- preferBuiltins: true
+ preferBuiltins: true
}),
json(),
commonjs({
transformMixedEsModules: true
}),
typescript({ tsconfig: './tsconfig.json' }),
- terser(),
+ terser()
],
external: ['axios', 'qs', 'ws', 'debug']
}
diff --git a/packages/bruno-requests/src/auth/digestauth-helper.js b/packages/bruno-requests/src/auth/digestauth-helper.js
index e104b795f..f8d4f0f7c 100644
--- a/packages/bruno-requests/src/auth/digestauth-helper.js
+++ b/packages/bruno-requests/src/auth/digestauth-helper.js
@@ -23,8 +23,8 @@ function containsDigestHeader(response) {
function containsAuthorizationHeader(originalRequest) {
return Boolean(
- originalRequest.headers['Authorization'] ||
- originalRequest.headers['authorization']
+ originalRequest.headers['Authorization']
+ || originalRequest.headers['authorization']
);
}
@@ -53,9 +53,9 @@ export function addDigestInterceptor(axiosInstance, request) {
originalRequest._retry = true;
if (
- error.response?.status === 401 &&
- containsDigestHeader(error.response) &&
- !containsAuthorizationHeader(originalRequest)
+ error.response?.status === 401
+ && containsDigestHeader(error.response)
+ && !containsAuthorizationHeader(originalRequest)
) {
console.debug('Processing Digest Authentication Challenge');
console.debug(error.response.headers['www-authenticate']);
@@ -77,7 +77,7 @@ export function addDigestInterceptor(axiosInstance, request) {
return Promise.reject(error);
}
- console.debug("Auth Details: \n", authDetails);
+ console.debug('Auth Details: \n', authDetails);
const nonceCount = '00000001';
const cnonce = crypto.randomBytes(24).toString('hex');
@@ -113,7 +113,7 @@ export function addDigestInterceptor(axiosInstance, request) {
`realm="${authDetails.realm}"`,
`nonce="${authDetails.nonce}"`,
`uri="${uri}"`,
- `response="${response}"`,
+ `response="${response}"`
];
if (authDetails.qop && authDetails.qop.split(',').map((q) => q.trim().toLowerCase()).includes('auth')) {
diff --git a/packages/bruno-requests/src/auth/digestauth-helper.spec.js b/packages/bruno-requests/src/auth/digestauth-helper.spec.js
index 4eb3a405a..c77195905 100644
--- a/packages/bruno-requests/src/auth/digestauth-helper.spec.js
+++ b/packages/bruno-requests/src/auth/digestauth-helper.spec.js
@@ -55,4 +55,4 @@ describe('Digest Auth with query params', () => {
// Expected to include both pathname and query
expect(uri).toBe('/resource?foo=bar&baz=qux');
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-requests/src/auth/index.ts b/packages/bruno-requests/src/auth/index.ts
index 082ca796b..a19151532 100644
--- a/packages/bruno-requests/src/auth/index.ts
+++ b/packages/bruno-requests/src/auth/index.ts
@@ -1,2 +1,2 @@
export { addDigestInterceptor } from './digestauth-helper';
-export { getOAuth2Token } from './oauth2-helper';
\ No newline at end of file
+export { getOAuth2Token } from './oauth2-helper';
diff --git a/packages/bruno-requests/src/auth/oauth2-helper.ts b/packages/bruno-requests/src/auth/oauth2-helper.ts
index 09ab59e79..be3fc1457 100644
--- a/packages/bruno-requests/src/auth/oauth2-helper.ts
+++ b/packages/bruno-requests/src/auth/oauth2-helper.ts
@@ -337,7 +337,7 @@ export const getOAuth2Token = async (oauth2Config: OAuth2Config, tokenStore: Tok
// Check if we already have credentials stored
const existingToken = await tokenStore.getCredential({ url: accessTokenUrl, credentialsId });
-
+
if (existingToken) {
// Check if token is expired
if (!isTokenExpired(existingToken)) {
diff --git a/packages/bruno-requests/src/cookies/index.spec.ts b/packages/bruno-requests/src/cookies/index.spec.ts
index 22071828d..1edb76efd 100644
--- a/packages/bruno-requests/src/cookies/index.spec.ts
+++ b/packages/bruno-requests/src/cookies/index.spec.ts
@@ -69,7 +69,7 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
// Verify all cookies were set
const retrievedCookies = (await jar.getCookies(testUrl)) as Cookie[];
expect(retrievedCookies).toHaveLength(3);
-
+
const cookieNames = retrievedCookies.map((c: Cookie) => c.key);
expect(cookieNames).toContain('cookie1');
expect(cookieNames).toContain('cookie2');
@@ -81,15 +81,15 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
await jar.setCookie(testUrl, 'auth', 'token123');
await jar.setCookie(testUrl, 'session', 'sess456');
await jar.setCookie(testUrl, 'prefs', 'theme=dark');
-
+
const cookies = (await jar.getCookies(testUrl)) as Cookie[];
expect(cookies).toHaveLength(3);
-
+
const cookieMap = (cookies as Cookie[]).reduce>((map, cookie: Cookie) => {
map[cookie.key] = cookie.value;
return map;
}, {} as Record);
-
+
expect(cookieMap.auth).toBe('token123');
expect(cookieMap.session).toBe('sess456');
expect(cookieMap.prefs).toBe('theme=dark');
@@ -101,10 +101,10 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
// Set two cookies
await jar.setCookie(testUrl, 'keep', 'keepValue');
await jar.setCookie(testUrl, 'remove', 'removeValue');
-
+
// Delete one cookie
await jar.deleteCookie(testUrl, 'remove');
-
+
// Verify only one cookie remains
const cookies = (await jar.getCookies(testUrl)) as Cookie[];
expect(cookies).toHaveLength(1);
@@ -116,10 +116,10 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
// Set multiple cookies
await jar.setCookie(testUrl, 'cookie1', 'value1');
await jar.setCookie(testUrl, 'cookie2', 'value2');
-
+
// Delete all cookies for the URL
await jar.deleteCookies(testUrl);
-
+
// Verify no cookies remain
const cookies = (await jar.getCookies(testUrl)) as Cookie[];
expect(cookies).toHaveLength(0);
@@ -129,14 +129,14 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
// Set cookies for multiple URLs
await jar.setCookie('https://site1.com', 'cookie1', 'value1');
await jar.setCookie('https://site2.com', 'cookie2', 'value2');
-
+
// Clear entire jar
await jar.clear();
-
+
// Verify no cookies remain for any URL
const cookies1 = (await jar.getCookies('https://site1.com')) as Cookie[];
const cookies2 = (await jar.getCookies('https://site2.com')) as Cookie[];
-
+
expect(cookies1).toHaveLength(0);
expect(cookies2).toHaveLength(0);
});
@@ -164,17 +164,17 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
test('Authentication workflow example', async () => {
const apiUrl = 'https://api.example.com';
const authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
-
+
// Simulate login - set auth cookie
await jar.setCookie(apiUrl, 'authToken', authToken);
-
+
// Later in the session - retrieve auth token
const cookie = (await jar.getCookie(apiUrl, 'authToken'))!;
expect(cookie.value).toBe(authToken);
-
+
// Simulate logout - remove auth cookie
await jar.deleteCookie(apiUrl, 'authToken');
-
+
// Verify cookie is gone
const deletedCookie = await jar.getCookie(apiUrl, 'authToken');
expect(deletedCookie).toBeNull();
@@ -182,29 +182,29 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
test('Session management with multiple cookies', async () => {
const sessionUrl = 'https://app.example.com';
-
+
// Set session cookies
const sessionCookies = [
{ key: 'sessionId', value: 'sess_123', httpOnly: true },
{ key: 'csrfToken', value: 'csrf_456' },
{ key: 'userPrefs', value: JSON.stringify({ theme: 'dark', lang: 'en' }) }
];
-
+
await jar.setCookies(sessionUrl, sessionCookies);
-
+
// Retrieve all session cookies
const cookies = (await jar.getCookies(sessionUrl)) as Cookie[];
expect(cookies).toHaveLength(3);
-
+
// Find specific cookies
const sessionCookie = cookies.find((c: Cookie) => c.key === 'sessionId')!;
const csrfCookie = cookies.find((c: Cookie) => c.key === 'csrfToken')!;
const prefsCookie = cookies.find((c: Cookie) => c.key === 'userPrefs')!;
-
+
expect(sessionCookie.value).toBe('sess_123');
expect(sessionCookie.httpOnly).toBe(true);
expect(csrfCookie.value).toBe('csrf_456');
-
+
const prefs = JSON.parse(prefsCookie.value);
expect(prefs.theme).toBe('dark');
expect(prefs.lang).toBe('en');
@@ -212,23 +212,23 @@ describe('Bruno Cookie Jar Wrapper - API Examples', () => {
test('Cookie path handling', async () => {
const baseUrl = 'https://example.com';
-
+
// Set cookies with different paths
await jar.setCookie(baseUrl, { key: 'global', value: 'global_val', path: '/' });
await jar.setCookie(baseUrl, { key: 'api', value: 'api_val', path: '/api' });
await jar.setCookie(baseUrl, { key: 'admin', value: 'admin_val', path: '/admin' });
-
+
const rootCookies = (await jar.getCookies(baseUrl + '/')) as Cookie[];
const globalCookie = rootCookies.find((c: Cookie) => c.key === 'global')!;
expect(globalCookie).toBeTruthy();
expect(globalCookie.value).toBe('global_val');
-
+
const apiCookies = (await jar.getCookies(baseUrl + '/api/users')) as Cookie[];
expect(apiCookies.length).toBeGreaterThanOrEqual(2);
-
+
const apiCookieNames = apiCookies.map((c: Cookie) => c.key);
expect(apiCookieNames).toContain('global');
expect(apiCookieNames).toContain('api');
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-requests/src/cookies/index.ts b/packages/bruno-requests/src/cookies/index.ts
index dfd9482bc..629727953 100644
--- a/packages/bruno-requests/src/cookies/index.ts
+++ b/packages/bruno-requests/src/cookies/index.ts
@@ -15,7 +15,7 @@ const addCookieToJar = (setCookieHeader: string, requestUrl: string): void => {
const getCookiesForUrl = (url: string) => {
return cookieJar.getCookiesSync(url, {
- secure: isPotentiallyTrustworthyOrigin(url),
+ secure: isPotentiallyTrustworthyOrigin(url)
} as any);
};
@@ -37,7 +37,7 @@ const getDomainsWithCookies = (): Promise {
// Handle null domain by skipping the cookie
if (!cookie.domain) return;
-
+
if (!domainCookieMap[cookie.domain]) {
domainCookieMap[cookie.domain] = [cookie];
} else {
@@ -163,7 +163,7 @@ const createCookieString = (cookieObj: any): string => {
cookieString += `; Domain=${cookieObj.domain}`;
}
return cookieString;
-}
+};
const saveCookies = (url: string, headers: any) => {
if (headers['set-cookie']) {
@@ -180,7 +180,7 @@ const saveCookies = (url: string, headers: any) => {
const cookieJarWrapper = () => {
return {
-
+
// Get the full cookie object for the given URL & name.
getCookie: function (
url: string,
@@ -213,7 +213,7 @@ const cookieJarWrapper = () => {
});
});
},
-
+
// Get all cookies that would be sent to the given URL.
getCookies: function (url: string, callback?: (err: Error | null | undefined, cookies?: Cookie[]) => void) {
if (!url) {
@@ -263,7 +263,7 @@ const cookieJarWrapper = () => {
const cookie = new Cookie({
key: cookieName,
value: cookieValue,
- domain: new URL(url).hostname,
+ domain: new URL(url).hostname
});
cookieJar.setCookieSync(cookie, url, { ignoreError: true });
@@ -279,7 +279,7 @@ const cookieJarWrapper = () => {
const base = {
domain: new URL(url).hostname,
- ...obj,
+ ...obj
} as any;
const processedCookie = createCookieObj(base);
@@ -314,7 +314,6 @@ const cookieJarWrapper = () => {
});
},
-
setCookies: function (
url: string,
cookiesArray: any[],
@@ -365,7 +364,6 @@ const cookieJarWrapper = () => {
});
},
-
clear: function (callback?: (err?: Error | undefined) => void) {
if (callback) {
// Callback mode
@@ -483,7 +481,6 @@ const cookieJarWrapper = () => {
} as const;
};
-
const cookiesModule = {
cookieJar,
addCookieToJar,
@@ -502,4 +499,4 @@ const cookiesModule = {
saveCookies
};
-export default cookiesModule;
\ No newline at end of file
+export default cookiesModule;
diff --git a/packages/bruno-requests/src/grpc/grpc-client.js b/packages/bruno-requests/src/grpc/grpc-client.js
index 55ecb5762..695be3eec 100644
--- a/packages/bruno-requests/src/grpc/grpc-client.js
+++ b/packages/bruno-requests/src/grpc/grpc-client.js
@@ -66,7 +66,7 @@ const safeJsonParse = (jsonString, context = 'JSON string') => {
console.error(errorMessage, { originalString: jsonString, parseError: error });
throw new Error(errorMessage);
}
-}
+};
const processGrpcMetadata = (metadata) => {
return Object.entries(metadata).map(([name, value]) => {
@@ -92,16 +92,16 @@ const processGrpcMetadata = (metadata) => {
const getParsedGrpcUrlObject = (url) => {
const isUnixSocket = (str) => str.startsWith('unix:');
- //const isXdsUrl = str => str.startsWith('xds:');
+ // const isXdsUrl = str => str.startsWith('xds:');
// By default, secure protocol grpcs is set if not specified, localhost is set to insecure (grpc://)
const addProtocolIfMissing = (str) => {
if (str.includes('://')) return str;
-
+
// For localhost, default to insecure (grpc://) for local development
if (str.includes('localhost') || str.includes('127.0.0.1')) {
return `grpc://${str}`;
}
-
+
// For other hosts, default to secure
return `grpcs://${str}`;
};
@@ -491,9 +491,8 @@ class GrpcClient {
try {
method = this.#getMethodFromPath(methodPath);
} catch (error) {
-
/* Attempt to refresh methods as fallback
- * In an ideal case, the stored metadata from local storage should be received from the client side,
+ * In an ideal case, the stored metadata from local storage should be received from the client side,
* however, this approach causes serialization failure as the method definition loses its requestSerialize function while saving to local storage
* so we are using reflection as a fallback
*/
@@ -536,8 +535,8 @@ class GrpcClient {
messages = messages.map(({ content }) => safeJsonParse(content, 'message content'));
} catch (parseError) {
console.error('Failed to parse gRPC message content:', parseError);
- this.eventCallback('grpc:error', request.uid, collection.uid, {
- error: parseError
+ this.eventCallback('grpc:error', request.uid, collection.uid, {
+ error: parseError
});
return; // Exit early to prevent sending invalid data
}
@@ -572,7 +571,7 @@ class GrpcClient {
if (connection) {
let parsedBody;
-
+
// Parse the body if it's a string, with error handling
if (typeof body === 'string') {
try {
@@ -580,8 +579,8 @@ class GrpcClient {
} catch (parseError) {
// Log the error and notify the client
console.error('Failed to parse message body:', parseError);
- this.eventCallback('grpc:error', requestId, collectionUid, {
- error: parseError
+ this.eventCallback('grpc:error', requestId, collectionUid, {
+ error: parseError
});
return; // Exit early to prevent sending invalid data
}
@@ -730,7 +729,7 @@ class GrpcClient {
generateSampleMessage(methodPath, options = {}) {
try {
let method;
-
+
// First, try to use the methodMetadata from options if provided
if (options.methodMetadata) {
method = options.methodMetadata;
@@ -742,7 +741,7 @@ class GrpcClient {
error: `Method ${methodPath} not found in cache, please refresh the methods`
};
}
-
+
// Get the method definition from cache
method = this.methods.get(methodPath);
}
diff --git a/packages/bruno-requests/src/grpc/grpcMessageGenerator.js b/packages/bruno-requests/src/grpc/grpcMessageGenerator.js
index 8b736c498..e7b66aa25 100644
--- a/packages/bruno-requests/src/grpc/grpcMessageGenerator.js
+++ b/packages/bruno-requests/src/grpc/grpcMessageGenerator.js
@@ -8,12 +8,12 @@ import { faker } from '@faker-js/faker';
*/
const generateSampleMessageFromFields = (fields, options = {}) => {
const result = {};
-
+
if (!fields || !Array.isArray(fields)) {
return {};
}
-
- fields.forEach(field => {
+
+ fields.forEach((field) => {
// Generate a value based on field name and type
if (field.type === 'TYPE_MESSAGE') {
// Handle nested message
@@ -21,7 +21,7 @@ const generateSampleMessageFromFields = (fields, options = {}) => {
if (field.label === 'LABEL_REPEATED') {
// Generate array of nested messages
const count = options.arraySize || faker.number.int({ min: 1, max: 3 });
- result[field.name] = Array.from({ length: count }, () =>
+ result[field.name] = Array.from({ length: count }, () =>
generateSampleMessageFromFields(field.messageType.field, options)
);
} else {
@@ -37,7 +37,7 @@ const generateSampleMessageFromFields = (fields, options = {}) => {
} else {
// Generate value based on primitive type and name
let value;
-
+
switch (field.type) {
case 'TYPE_DOUBLE':
case 'TYPE_FLOAT':
@@ -57,7 +57,7 @@ const generateSampleMessageFromFields = (fields, options = {}) => {
value = faker.datatype.boolean();
break;
case 'TYPE_STRING':
- value = faker.lorem.word()
+ value = faker.lorem.word();
break;
case 'TYPE_BYTES':
value = Buffer.from(faker.string.alpha({ length: { min: 5, max: 10 } })).toString('base64');
@@ -75,7 +75,7 @@ const generateSampleMessageFromFields = (fields, options = {}) => {
}
}
});
-
+
return result;
};
@@ -90,15 +90,14 @@ const getMethodRequestFields = (method) => {
if (method.requestType?.type?.field) {
return method.requestType.type.field;
}
-
+
if (method.requestType?.field) {
return method.requestType.field;
}
-
+
if (method.requestType?.type) {
return method.requestType.type;
}
-
} catch (error) {
console.error('Error extracting method request fields:', error);
return null;
@@ -116,17 +115,17 @@ export const generateGrpcSampleMessage = (method, options = {}) => {
if (!method) {
return {};
}
-
+
const fields = getMethodRequestFields(method);
-
+
if (fields) {
return generateSampleMessageFromFields(fields, options);
}
-
+
// If method exists but no field information could be extracted,
// generate a generic message that matches common patterns
return {};
} catch (error) {
console.error('Error generating gRPC sample message:', error);
}
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-requests/src/grpc/index.ts b/packages/bruno-requests/src/grpc/index.ts
index 060b54bb6..e866c8395 100644
--- a/packages/bruno-requests/src/grpc/index.ts
+++ b/packages/bruno-requests/src/grpc/index.ts
@@ -1,2 +1,2 @@
export { GrpcClient } from './grpc-client';
-export { generateGrpcSampleMessage } from './grpcMessageGenerator';
\ No newline at end of file
+export { generateGrpcSampleMessage } from './grpcMessageGenerator';
diff --git a/packages/bruno-requests/src/index.ts b/packages/bruno-requests/src/index.ts
index c30e41772..ad751f0ce 100644
--- a/packages/bruno-requests/src/index.ts
+++ b/packages/bruno-requests/src/index.ts
@@ -5,4 +5,4 @@ export { default as cookies } from './cookies';
export { getCACertificates } from './utils/ca-cert';
-export * as scripting from './scripting';
\ No newline at end of file
+export * as scripting from './scripting';
diff --git a/packages/bruno-requests/src/network/axios-instance.ts b/packages/bruno-requests/src/network/axios-instance.ts
index 6ae868c3f..7e764427f 100644
--- a/packages/bruno-requests/src/network/axios-instance.ts
+++ b/packages/bruno-requests/src/network/axios-instance.ts
@@ -3,11 +3,11 @@ import http from 'node:http';
import https from 'node:https';
/**
- *
+ *
* @param {Object} customRequestConfig options - partial AxiosRequestConfig
- *
+ *
* @returns {import('axios').AxiosInstance} Configured Axios instance
- *
+ *
* @example
* const instance = makeAxiosInstance({
* maxRedirects: 0,
@@ -20,11 +20,11 @@ import https from 'node:https';
type ModifiedInternalAxiosRequestConfig = InternalAxiosRequestConfig & {
startTime: number;
-}
+};
type ModifiedAxiosResponse = AxiosResponse & {
responseTime: number;
-}
+};
const baseRequestConfig: Partial = {
proxy: false,
@@ -45,7 +45,7 @@ const baseRequestConfig: Partial = {
return data;
}
-}
+};
const makeAxiosInstance = (customRequestConfig?: AxiosRequestConfig) => {
customRequestConfig = customRequestConfig || {};
@@ -58,7 +58,7 @@ const makeAxiosInstance = (customRequestConfig?: AxiosRequestConfig) => {
const modifiedConfig: ModifiedInternalAxiosRequestConfig = {
...config,
startTime: Date.now()
- }
+ };
return modifiedConfig;
});
diff --git a/packages/bruno-requests/src/network/index.ts b/packages/bruno-requests/src/network/index.ts
index 7d72cb7d1..19548a4e5 100644
--- a/packages/bruno-requests/src/network/index.ts
+++ b/packages/bruno-requests/src/network/index.ts
@@ -1 +1 @@
-export { makeAxiosInstance } from './axios-instance';
\ No newline at end of file
+export { makeAxiosInstance } from './axios-instance';
diff --git a/packages/bruno-requests/src/scripting/index.ts b/packages/bruno-requests/src/scripting/index.ts
index 5ec4ee97b..7dd459330 100644
--- a/packages/bruno-requests/src/scripting/index.ts
+++ b/packages/bruno-requests/src/scripting/index.ts
@@ -1 +1 @@
-export { default as sendRequest } from './send-request';
\ No newline at end of file
+export { default as sendRequest } from './send-request';
diff --git a/packages/bruno-requests/src/scripting/send-request.ts b/packages/bruno-requests/src/scripting/send-request.ts
index 8afedeaf3..926e8143e 100644
--- a/packages/bruno-requests/src/scripting/send-request.ts
+++ b/packages/bruno-requests/src/scripting/send-request.ts
@@ -12,16 +12,13 @@ const sendRequest = async (requestConfig: AxiosRequestConfig, callback: T_SendRe
const response = await axiosInstance(requestConfig);
try {
await callback(null, response);
- }
- catch(error) {
+ } catch (error) {
return Promise.reject(error);
}
- }
- catch (error) {
+ } catch (error) {
try {
await callback(error, null);
- }
- catch(err) {
+ } catch (err) {
return Promise.reject(err);
}
}
diff --git a/packages/bruno-requests/src/utils/ca-cert.ts b/packages/bruno-requests/src/utils/ca-cert.ts
index a8112bdab..ff92b85bf 100644
--- a/packages/bruno-requests/src/utils/ca-cert.ts
+++ b/packages/bruno-requests/src/utils/ca-cert.ts
@@ -4,7 +4,7 @@ import * as fs from 'node:fs';
type T_CACertificatesOptions = {
caCertFilePath?: string;
shouldKeepDefaultCerts?: boolean;
-}
+};
type T_CACertificatesResult = {
caCertificates: string;
@@ -14,7 +14,7 @@ type T_CACertificatesResult = {
custom: number;
extra: number;
};
-}
+};
let systemCertsCache: string[] | undefined;
@@ -70,20 +70,20 @@ function getNodeExtraCACerts(): string[] {
/**
* Get CA certificates
- *
+ *
* Generic function to get CA certificates
* - System CA certificates (From OS)
* - Root CA certificates (From Node)
* - Custom CA certificates (From user-provided file)
* - NODE_EXTRA_CA_CERTS (From environment variable)
- *
+ *
* If no custom CA certificate file path is provided
* โ return system CA certificates and root certificates + NODE_EXTRA_CA_CERTS
- *
+ *
* If custom CA certificate file path is provided
* โ use custom CA certificate file + NODE_EXTRA_CA_CERTS
* โ ignore system + root certificates if shouldKeepDefaultCerts is false
- *
+ *
* @param caCertFilePath - path to custom CA certificate file
* @param shouldKeepDefaultCerts - whether to keep default CA certificates
* @returns {T_CACertificatesResult} - CA certificates and their count
@@ -97,14 +97,13 @@ const getCACertificates = ({ caCertFilePath, shouldKeepDefaultCerts = true }: T_
root: 0,
custom: 0,
extra: 0
- }
+ };
let systemCerts: string[] = [];
let rootCerts: string[] = [];
let customCerts: string[] = [];
let nodeExtraCerts: string[] = [];
-
// handle user-provided custom CA certificate file with optional default certificates
if (caCertFilePath) {
// validate custom CA certificate file
@@ -153,13 +152,13 @@ const getCACertificates = ({ caCertFilePath, shouldKeepDefaultCerts = true }: T_
return {
caCertificates,
caCertificatesCount
- }
+ };
} catch (err) {
console.error('Error configuring CA certificates:', (err as Error).message);
throw err; // Re-throw certificate loading errors as they're critical
}
-}
+};
export {
getCACertificates
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-requests/src/utils/url-validation.spec.ts b/packages/bruno-requests/src/utils/url-validation.spec.ts
index b2b35e602..e0804c2ff 100644
--- a/packages/bruno-requests/src/utils/url-validation.spec.ts
+++ b/packages/bruno-requests/src/utils/url-validation.spec.ts
@@ -130,4 +130,4 @@ describe('isPotentiallyTrustworthyOrigin', () => {
expect(isPotentiallyTrustworthyOrigin('wss://localhost')).toBe(true);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/bruno-requests/src/utils/url-validation.ts b/packages/bruno-requests/src/utils/url-validation.ts
index 1a94bcfdc..4e2a35353 100644
--- a/packages/bruno-requests/src/utils/url-validation.ts
+++ b/packages/bruno-requests/src/utils/url-validation.ts
@@ -64,4 +64,4 @@ const isPotentiallyTrustworthyOrigin = (urlString: string): boolean => {
return isLocalHostname(hostname);
};
-export { isPotentiallyTrustworthyOrigin };
\ No newline at end of file
+export { isPotentiallyTrustworthyOrigin };
diff --git a/packages/bruno-schema-types/src/collection/collection.ts b/packages/bruno-schema-types/src/collection/collection.ts
index 389133b67..196d15d01 100644
--- a/packages/bruno-schema-types/src/collection/collection.ts
+++ b/packages/bruno-schema-types/src/collection/collection.ts
@@ -20,4 +20,3 @@ export interface Collection {
brunoConfig?: Record | null;
root?: FolderRoot | null;
}
-
diff --git a/packages/bruno-schema-types/src/collection/environment.ts b/packages/bruno-schema-types/src/collection/environment.ts
index ebd46ecf6..90fdbfaf3 100644
--- a/packages/bruno-schema-types/src/collection/environment.ts
+++ b/packages/bruno-schema-types/src/collection/environment.ts
@@ -16,4 +16,3 @@ export interface Environment {
}
export type Environments = Environment[];
-
diff --git a/packages/bruno-schema-types/src/collection/examples.ts b/packages/bruno-schema-types/src/collection/examples.ts
index b5077e876..0dcf34db1 100644
--- a/packages/bruno-schema-types/src/collection/examples.ts
+++ b/packages/bruno-schema-types/src/collection/examples.ts
@@ -32,4 +32,3 @@ export interface Example {
request?: ExampleRequest | null;
response?: ExampleResponse | null;
}
-
diff --git a/packages/bruno-schema-types/src/collection/folder.ts b/packages/bruno-schema-types/src/collection/folder.ts
index c3725d670..f9c88df82 100644
--- a/packages/bruno-schema-types/src/collection/folder.ts
+++ b/packages/bruno-schema-types/src/collection/folder.ts
@@ -21,4 +21,3 @@ export interface FolderRoot {
docs?: string | null;
meta?: FolderMeta | null;
}
-
diff --git a/packages/bruno-schema-types/src/collection/index.ts b/packages/bruno-schema-types/src/collection/index.ts
index 50fc245cb..644235e9e 100644
--- a/packages/bruno-schema-types/src/collection/index.ts
+++ b/packages/bruno-schema-types/src/collection/index.ts
@@ -19,4 +19,3 @@ export type {
WebSocketItemSettings
} from './item';
export type { Collection, RunnerResult } from './collection';
-
diff --git a/packages/bruno-schema-types/src/collection/item.ts b/packages/bruno-schema-types/src/collection/item.ts
index 603832ade..bdf3b3346 100644
--- a/packages/bruno-schema-types/src/collection/item.ts
+++ b/packages/bruno-schema-types/src/collection/item.ts
@@ -3,13 +3,13 @@ import type { Request } from '../requests';
import type { Example } from './examples';
import type { FolderRoot } from './folder';
-export type ItemType =
- | 'http-request'
- | 'graphql-request'
- | 'folder'
- | 'js'
- | 'grpc-request'
- | 'ws-request';
+export type ItemType
+ = | 'http-request'
+ | 'graphql-request'
+ | 'folder'
+ | 'js'
+ | 'grpc-request'
+ | 'ws-request';
export interface HttpItemSettings {
encodeUrl?: boolean | null;
@@ -42,4 +42,3 @@ export interface Item {
filename?: string | null;
pathname?: string | null;
}
-
diff --git a/packages/bruno-schema-types/src/common/auth.ts b/packages/bruno-schema-types/src/common/auth.ts
index db6833f47..b620d64b3 100644
--- a/packages/bruno-schema-types/src/common/auth.ts
+++ b/packages/bruno-schema-types/src/common/auth.ts
@@ -38,11 +38,11 @@ export interface AuthApiKey {
placement?: 'header' | 'queryparams' | null;
}
-export type OAuthGrantType =
- | 'client_credentials'
- | 'password'
- | 'authorization_code'
- | 'implicit';
+export type OAuthGrantType
+ = | 'client_credentials'
+ | 'password'
+ | 'authorization_code'
+ | 'implicit';
export interface OAuthAdditionalParameter {
name?: string | null;
@@ -80,17 +80,17 @@ export interface OAuth2 {
additionalParameters?: OAuthAdditionalParameters | null;
}
-export type AuthMode =
- | 'inherit'
- | 'none'
- | 'awsv4'
- | 'basic'
- | 'bearer'
- | 'digest'
- | 'ntlm'
- | 'oauth2'
- | 'wsse'
- | 'apikey';
+export type AuthMode
+ = | 'inherit'
+ | 'none'
+ | 'awsv4'
+ | 'basic'
+ | 'bearer'
+ | 'digest'
+ | 'ntlm'
+ | 'oauth2'
+ | 'wsse'
+ | 'apikey';
export interface Auth {
mode: AuthMode;
@@ -103,4 +103,3 @@ export interface Auth {
wsse?: AuthWsse | null;
apikey?: AuthApiKey | null;
}
-
diff --git a/packages/bruno-schema-types/src/common/file.ts b/packages/bruno-schema-types/src/common/file.ts
index 49460c2b2..1f95c7e24 100644
--- a/packages/bruno-schema-types/src/common/file.ts
+++ b/packages/bruno-schema-types/src/common/file.ts
@@ -8,4 +8,3 @@ export interface FileEntry {
}
export type FileList = FileEntry[];
-
diff --git a/packages/bruno-schema-types/src/common/graphql.ts b/packages/bruno-schema-types/src/common/graphql.ts
index ee732d454..233e16219 100644
--- a/packages/bruno-schema-types/src/common/graphql.ts
+++ b/packages/bruno-schema-types/src/common/graphql.ts
@@ -2,4 +2,3 @@ export interface GraphqlBody {
query?: string | null;
variables?: string | null;
}
-
diff --git a/packages/bruno-schema-types/src/common/index.ts b/packages/bruno-schema-types/src/common/index.ts
index f6ee39f81..d19826f59 100644
--- a/packages/bruno-schema-types/src/common/index.ts
+++ b/packages/bruno-schema-types/src/common/index.ts
@@ -20,4 +20,3 @@ export type {
OAuthAdditionalParameter,
OAuthAdditionalParameters
} from './auth';
-
diff --git a/packages/bruno-schema-types/src/common/key-value.ts b/packages/bruno-schema-types/src/common/key-value.ts
index af11a703e..8007393f2 100644
--- a/packages/bruno-schema-types/src/common/key-value.ts
+++ b/packages/bruno-schema-types/src/common/key-value.ts
@@ -10,4 +10,3 @@ export interface KeyValue {
description?: string | null;
enabled?: boolean;
}
-
diff --git a/packages/bruno-schema-types/src/common/multipart-form.ts b/packages/bruno-schema-types/src/common/multipart-form.ts
index 8b01f68c8..75200868d 100644
--- a/packages/bruno-schema-types/src/common/multipart-form.ts
+++ b/packages/bruno-schema-types/src/common/multipart-form.ts
@@ -11,4 +11,3 @@ export interface MultipartFormEntry {
}
export type MultipartForm = MultipartFormEntry[];
-
diff --git a/packages/bruno-schema-types/src/common/scripts.ts b/packages/bruno-schema-types/src/common/scripts.ts
index 2cde97b38..612325388 100644
--- a/packages/bruno-schema-types/src/common/scripts.ts
+++ b/packages/bruno-schema-types/src/common/scripts.ts
@@ -2,4 +2,3 @@ export interface Script {
req?: string | null;
res?: string | null;
}
-
diff --git a/packages/bruno-schema-types/src/common/uid.ts b/packages/bruno-schema-types/src/common/uid.ts
index a0e46a3e9..d9228c3d1 100644
--- a/packages/bruno-schema-types/src/common/uid.ts
+++ b/packages/bruno-schema-types/src/common/uid.ts
@@ -2,4 +2,3 @@
* Unique identifier used across Bruno collections.
*/
export type UID = string;
-
diff --git a/packages/bruno-schema-types/src/common/variables.ts b/packages/bruno-schema-types/src/common/variables.ts
index 976aefcc0..8d45d1401 100644
--- a/packages/bruno-schema-types/src/common/variables.ts
+++ b/packages/bruno-schema-types/src/common/variables.ts
@@ -13,4 +13,3 @@ export interface Variable {
}
export type Variables = Variable[] | null;
-
diff --git a/packages/bruno-schema-types/src/index.ts b/packages/bruno-schema-types/src/index.ts
index aa1492588..cdc9ee116 100644
--- a/packages/bruno-schema-types/src/index.ts
+++ b/packages/bruno-schema-types/src/index.ts
@@ -8,4 +8,4 @@ export type {
Environment as BrunoEnvironment,
Environments as BrunoEnvironments
} from './collection';
-export type { Request as BrunoRequest } from './requests';
\ No newline at end of file
+export type { Request as BrunoRequest } from './requests';
diff --git a/packages/bruno-schema-types/src/requests/grpc.ts b/packages/bruno-schema-types/src/requests/grpc.ts
index 95501a0e5..20fd70a91 100644
--- a/packages/bruno-schema-types/src/requests/grpc.ts
+++ b/packages/bruno-schema-types/src/requests/grpc.ts
@@ -1,11 +1,11 @@
import type { KeyValue, Script, Variables, Auth } from '../common';
-export type GrpcMethodType =
- | 'unary'
- | 'client-streaming'
- | 'server-streaming'
- | 'bidi-streaming'
- | '';
+export type GrpcMethodType
+ = | 'unary'
+ | 'client-streaming'
+ | 'server-streaming'
+ | 'bidi-streaming'
+ | '';
export interface GrpcMessage {
name?: string | null;
@@ -34,4 +34,3 @@ export interface GrpcRequest {
tests?: string | null;
docs?: string | null;
}
-
diff --git a/packages/bruno-schema-types/src/requests/http.ts b/packages/bruno-schema-types/src/requests/http.ts
index 2cd34efd3..76a387a2e 100644
--- a/packages/bruno-schema-types/src/requests/http.ts
+++ b/packages/bruno-schema-types/src/requests/http.ts
@@ -14,16 +14,16 @@ export interface HttpRequestParam extends KeyValue {
type: HttpRequestParamType;
}
-export type HttpRequestBodyMode =
- | 'none'
- | 'json'
- | 'text'
- | 'xml'
- | 'formUrlEncoded'
- | 'multipartForm'
- | 'graphql'
- | 'sparql'
- | 'file';
+export type HttpRequestBodyMode
+ = | 'none'
+ | 'json'
+ | 'text'
+ | 'xml'
+ | 'formUrlEncoded'
+ | 'multipartForm'
+ | 'graphql'
+ | 'sparql'
+ | 'file';
export interface HttpRequestBody {
mode: HttpRequestBodyMode;
@@ -53,4 +53,3 @@ export interface HttpRequest {
tests?: string | null;
docs?: string | null;
}
-
diff --git a/packages/bruno-schema-types/src/requests/index.ts b/packages/bruno-schema-types/src/requests/index.ts
index a5233a5ef..4b726734a 100644
--- a/packages/bruno-schema-types/src/requests/index.ts
+++ b/packages/bruno-schema-types/src/requests/index.ts
@@ -24,4 +24,3 @@ export type {
} from './websocket';
export type Request = HttpRequest | GrpcRequest | WebSocketRequest;
-
diff --git a/packages/bruno-schema-types/src/requests/websocket.ts b/packages/bruno-schema-types/src/requests/websocket.ts
index f0a998104..1781ebfc8 100644
--- a/packages/bruno-schema-types/src/requests/websocket.ts
+++ b/packages/bruno-schema-types/src/requests/websocket.ts
@@ -25,4 +25,3 @@ export interface WebSocketRequest {
tests?: string | null;
docs?: string | null;
}
-
diff --git a/packages/bruno-tests/collection/lib/constants.js b/packages/bruno-tests/collection/lib/constants.js
index 2f0e62f37..826014e83 100644
--- a/packages/bruno-tests/collection/lib/constants.js
+++ b/packages/bruno-tests/collection/lib/constants.js
@@ -2,4 +2,4 @@ const PI = 3.14;
module.exports = {
PI
-};
\ No newline at end of file
+};
diff --git a/packages/bruno-tests/collection/scripting/inbuilt modules/utils.js b/packages/bruno-tests/collection/scripting/inbuilt modules/utils.js
index 855cad82d..569b73393 100644
--- a/packages/bruno-tests/collection/scripting/inbuilt modules/utils.js
+++ b/packages/bruno-tests/collection/scripting/inbuilt modules/utils.js
@@ -3,40 +3,36 @@ const isUint8Array = (val) => {
// developer mode [node:vm]
const util = require('node:util');
return util.types.isUint8Array(val);
- }
- catch (err) {
+ } catch (err) {
// node:util not present in safe mode [quickjs]
return val instanceof Uint8Array;
}
-}
+};
const getRandomValuesFunction = (typedArray) => {
try {
// developer mode [node:vm]
const crypto = require('node:crypto');
return crypto.getRandomValues(typedArray);
- }
- catch (err) {
+ } catch (err) {
// node:crypto not present in safe mode [quickjs] - uses shim
return crypto.getRandomValues(typedArray);
}
-}
+};
const randomBytesFunction = (num) => {
try {
// developer mode [node:vm]
const crypto = require('node:crypto');
return crypto.randomBytes(num);
- }
- catch (err) {
+ } catch (err) {
// node:crypto not present in safe mode [quickjs] - uses shim
return crypto.randomBytes(num);
}
-}
-
+};
module.exports = {
isUint8Array,
getRandomValuesFunction,
randomBytesFunction
-}
\ No newline at end of file
+};
diff --git a/packages/bruno-tests/src/echo/index.js b/packages/bruno-tests/src/echo/index.js
index a9425b305..044065536 100644
--- a/packages/bruno-tests/src/echo/index.js
+++ b/packages/bruno-tests/src/echo/index.js
@@ -52,7 +52,7 @@ router.get('/iso-enc', (req, res) => {
return res.send(Buffer.from(responseText, 'latin1'));
});
-router.post("/custom", (req, res) => {
+router.post('/custom', (req, res) => {
const { headers, content, contentBase64, contentJSON, type } = req.body || {};
res._headers = {};
diff --git a/packages/bruno-tests/src/redirect/index.js b/packages/bruno-tests/src/redirect/index.js
index f9dac57c8..7fdf6b526 100644
--- a/packages/bruno-tests/src/redirect/index.js
+++ b/packages/bruno-tests/src/redirect/index.js
@@ -8,8 +8,8 @@ const parseMultipartFormData = (req) => {
const parts = formDataParser.parse(req);
const parsedBody = {};
const files = [];
-
- parts.forEach(part => {
+
+ parts.forEach((part) => {
if (part.filename) {
files.push({
fieldname: part.name,
@@ -21,7 +21,7 @@ const parseMultipartFormData = (req) => {
parsedBody[part.name] = part.value;
}
});
-
+
return { body: parsedBody, files };
} catch (error) {
console.error('Error parsing multipart form data:', error);
@@ -35,11 +35,11 @@ router.post('/multipart-redirect-source', function (req, res) {
console.log('Multipart redirect source endpoint hit');
console.log('Method:', req.method);
console.log('Headers:', req.headers);
-
+
const { body, files } = parseMultipartFormData(req);
console.log('Parsed Body:', body);
console.log('Files:', files);
-
+
res.status(308).location('/api/redirect/multipart-redirect-target').send('Permanently moved');
});
@@ -47,11 +47,11 @@ router.post('/multipart-redirect-target', function (req, res) {
console.log('Multipart redirect target endpoint hit');
console.log('Method:', req.method);
console.log('Headers:', req.headers);
-
+
const { body, files } = parseMultipartFormData(req);
console.log('Parsed Body:', body);
console.log('Files:', files);
-
+
res.json({
status: 'success',
method: req.method,
diff --git a/packages/bruno-tests/src/utils/xmlParser.js b/packages/bruno-tests/src/utils/xmlParser.js
index ed765c077..4825d4cd1 100644
--- a/packages/bruno-tests/src/utils/xmlParser.js
+++ b/packages/bruno-tests/src/utils/xmlParser.js
@@ -3,7 +3,7 @@ const { XMLParser } = require('fast-xml-parser');
const xmlParser = () => {
const parser = new XMLParser({
ignoreAttributes: false,
- allowBooleanAttributes: true,
+ allowBooleanAttributes: true
});
return (req, res, next) => {
@@ -27,4 +27,4 @@ const xmlParser = () => {
};
};
-module.exports = xmlParser;
\ No newline at end of file
+module.exports = xmlParser;
diff --git a/playwright/electron.ts b/playwright/electron.ts
index 89f73f25d..1fcd80964 100644
--- a/playwright/electron.ts
+++ b/playwright/electron.ts
@@ -4,7 +4,7 @@ const { _electron: electron } = require('playwright');
const electronAppPath = path.join(__dirname, '../packages/bruno-electron');
exports.startApp = async () => {
- const app = await electron.launch({
+ const app = await electron.launch({
args: [electronAppPath]
});
const context = await app.context();
diff --git a/tests/collection/create/create-collection.spec.ts b/tests/collection/create/create-collection.spec.ts
index 56124a41f..30557e4a0 100644
--- a/tests/collection/create/create-collection.spec.ts
+++ b/tests/collection/create/create-collection.spec.ts
@@ -37,4 +37,4 @@ test.describe('Create collection', () => {
// Verify the response
await expect(page.getByRole('main')).toContainText('200 OK');
});
-});
\ No newline at end of file
+});
diff --git a/tests/collection/moving-requests/tag-persistence.spec.ts b/tests/collection/moving-requests/tag-persistence.spec.ts
index 78681d6b9..6785791d9 100644
--- a/tests/collection/moving-requests/tag-persistence.spec.ts
+++ b/tests/collection/moving-requests/tag-persistence.spec.ts
@@ -51,7 +51,7 @@ test.describe('Tag persistence', () => {
// Move the request-3 request to just above request-1 within the same collection
const r3Request = page.locator('.collection-item-name').filter({ hasText: 'request-3' });
const r1Request = page.locator('.collection-item-name').filter({ hasText: 'request-1' });
-
+
await expect(r3Request).toBeVisible();
await expect(r1Request).toBeVisible();
@@ -100,7 +100,7 @@ test.describe('Tag persistence', () => {
await page.locator('.collection-item-name').filter({ hasText: 'folder-1' }).hover();
await page.locator('.collection-item-name').filter({ hasText: 'folder-1' }).locator('.menu-icon').click();
- await page.locator('.dropdown-item').getByText('New Request').click()
+ await page.locator('.dropdown-item').getByText('New Request').click();
await page.getByRole('textbox', { name: 'Request Name' }).fill('request-1');
await page.locator('#new-request-url textarea').fill('https://httpfaker.org/api/echo');
await page.getByRole('button', { name: 'Create' }).click();
@@ -110,7 +110,7 @@ test.describe('Tag persistence', () => {
.filter({ hasText: 'folder-1' }).hover();
await page.locator('.collection-item-name')
.filter({ hasText: 'folder-1' }).locator('.menu-icon').click();
- await page.locator('.dropdown-item').getByText('New Request').click()
+ await page.locator('.dropdown-item').getByText('New Request').click();
await page.getByRole('textbox', { name: 'Request Name' }).fill('request-2');
await page.locator('#new-request-url textarea').fill('https://httpfaker.org/api/echo');
await page.getByRole('button', { name: 'Create' }).click();
@@ -145,12 +145,12 @@ test.describe('Tag persistence', () => {
await page.getByRole('textbox', { name: 'Request Name' }).fill('request-3');
await page.locator('#new-request-url textarea').fill('https://httpfaker.org/api/echo');
await page.getByRole('button', { name: 'Create' }).click();
-
+
// Drag and drop request-2 request to folder-2 folder
const r2Request = page.locator('.collection-item-name').filter({ hasText: 'request-2' });
const f2Folder = page.locator('.collection-item-name').filter({ hasText: 'folder-2' });
await r2Request.dragTo(f2Folder);
-
+
// Verify the requests are still in the collection and request-2 is now in folder-2 folder
await expect(page.locator('.collection-item-name').filter({ hasText: 'request-2' })).toBeVisible();
await expect(page.locator('.collection-item-name').filter({ hasText: 'folder-2' })).toBeVisible();
diff --git a/tests/cookies/corrupted-passkey.spec.ts b/tests/cookies/corrupted-passkey.spec.ts
index 02c2a5010..dcdd72984 100644
--- a/tests/cookies/corrupted-passkey.spec.ts
+++ b/tests/cookies/corrupted-passkey.spec.ts
@@ -23,7 +23,7 @@ test('should handle corrupted passkey and still display saved cookie list', asyn
await page1.getByRole('button', { name: 'Save' }).click();
await expect(page1.getByText('example.com')).toBeVisible();
-
+
await app1.close();
// 2. Corrupt the encryptedPasskey in cookies.json
diff --git a/tests/environments/multiline-variables/write-multiline-variable.spec.ts b/tests/environments/multiline-variables/write-multiline-variable.spec.ts
index 1127ed369..6d4f63a18 100644
--- a/tests/environments/multiline-variables/write-multiline-variable.spec.ts
+++ b/tests/environments/multiline-variables/write-multiline-variable.spec.ts
@@ -70,8 +70,8 @@ test.describe('Multiline Variables - Write Test', () => {
await expect(page.locator('.response-status-code')).toContainText('200');
// verify multiline JSON variable resolution in response
- const expectedBody =
- '{\n "user": {\n "name": "John Doe",\n "email": "john@example.com",\n "preferences": {\n "theme": "dark",\n "notifications": true\n }\n },\n "metadata": {\n "created": "2025-09-03",\n "version": "1.0"\n }\n}';
+ const expectedBody
+ = '{\n "user": {\n "name": "John Doe",\n "email": "john@example.com",\n "preferences": {\n "theme": "dark",\n "notifications": true\n }\n },\n "metadata": {\n "created": "2025-09-03",\n "version": "1.0"\n }\n}';
await expect(page.locator('.response-pane')).toContainText(`"body": ${JSON.stringify(expectedBody)}`);
});
diff --git a/tests/footer/notifications/notifications.spec.js b/tests/footer/notifications/notifications.spec.js
index 238afcc98..51da3805b 100644
--- a/tests/footer/notifications/notifications.spec.js
+++ b/tests/footer/notifications/notifications.spec.js
@@ -4,22 +4,22 @@ test.describe('Notifications Modal', () => {
test('should open notifications modal when clicking bell icon and close with close button', async ({ page }) => {
// Get the notification bell icon in the status bar
const notificationBell = page.getByLabel('Check all Notifications');
-
+
// Click on the bell icon to open notifications
await notificationBell.click();
-
+
// Get modal elements
const notificationsModal = page.locator('.bruno-modal');
const modalCloseButton = notificationsModal.locator('div.bruno-modal-header div.close');
-
+
// Verify modal is visible and has the correct title
await expect(notificationsModal).toBeVisible();
await expect(notificationsModal.locator('.bruno-modal-header-title')).toContainText('NOTIFICATIONS');
-
+
// Click the close button
await modalCloseButton.click();
-
+
// Verify modal is closed
await expect(notificationsModal).not.toBeVisible();
});
-});
\ No newline at end of file
+});
diff --git a/tests/footer/sidebar-toggle/sidebar-toggle.spec.js b/tests/footer/sidebar-toggle/sidebar-toggle.spec.js
index d8e7dfb21..01f1a2ac1 100644
--- a/tests/footer/sidebar-toggle/sidebar-toggle.spec.js
+++ b/tests/footer/sidebar-toggle/sidebar-toggle.spec.js
@@ -6,14 +6,14 @@ test.describe('Sidebar Toggle', () => {
const sidebar = page.locator('aside.sidebar');
const toggleButton = page.getByLabel('Toggle Sidebar');
const dragHandle = page.locator('.sidebar-drag-handle');
-
+
// Initial state - sidebar and drag handle should be visible
await expect(sidebar).toBeVisible();
await expect(dragHandle).toBeVisible();
-
+
// Click toggle to hide sidebar
await toggleButton.click();
-
+
// Wait for transition to complete and verify sidebar and drag handle are hidden
await expect(sidebar).not.toBeVisible();
await expect(dragHandle).not.toBeVisible();
@@ -21,10 +21,10 @@ test.describe('Sidebar Toggle', () => {
// Verify the sidebar has collapsed width
const sidebarBox = await sidebar.boundingBox();
expect(sidebarBox?.width).toBe(0);
-
+
// Click toggle again to show sidebar
await toggleButton.click();
-
+
// Wait for transition and verify sidebar and drag handle are visible again
await expect(sidebar).toBeVisible();
await expect(dragHandle).toBeVisible();
@@ -33,4 +33,4 @@ test.describe('Sidebar Toggle', () => {
const expandedSidebarBox = await sidebar.boundingBox();
expect(expandedSidebarBox?.width).toBeGreaterThan(0);
});
-});
\ No newline at end of file
+});
diff --git a/tests/onboarding/sample-collection.spec.ts b/tests/onboarding/sample-collection.spec.ts
index 5c842c90e..c709b8034 100644
--- a/tests/onboarding/sample-collection.spec.ts
+++ b/tests/onboarding/sample-collection.spec.ts
@@ -7,30 +7,29 @@ const env = {
test.describe('Onboarding', () => {
test('should create sample collection on first launch', async ({ launchElectronApp, createTmpDir }) => {
-
// Use a fresh app instance to avoid contamination from previous tests
const userDataPath = await createTmpDir('onboarding-fresh');
const app = await launchElectronApp({ userDataPath, dotEnv: env });
const page = await app.firstWindow();
-
+
// Verify sample collection appears in sidebar
const sampleCollection = page.locator('#sidebar-collection-name').getByText('Sample API Collection');
await expect(sampleCollection).toBeVisible();
-
+
// Click on the sample collection to open it
await sampleCollection.click();
const modeSaveButton = page.getByRole('button', { name: 'Save' });
await expect(modeSaveButton).toBeVisible();
await modeSaveButton.click();
-
+
// Verify the sample request is visible and clickable
const request = page.locator('.collection-item-name').getByText('Get Users');
await expect(request).toBeVisible();
await request.click();
-
+
// Verify the URL is set correctly
await expect(page.locator('#request-url')).toContainText('https://jsonplaceholder.typicode.com/users');
-
+
// Clean up
await app.close();
});
@@ -40,7 +39,7 @@ test.describe('Onboarding', () => {
const userDataPath = await createTmpDir('duplicate-collections');
const app = await launchElectronApp({ userDataPath, dotEnv: env });
const page = await app.firstWindow();
-
+
// First launch - verify sample collection is created
const sampleCollection = page.locator('#sidebar-collection-name').getByText('Sample API Collection');
await expect(sampleCollection).toBeVisible();
@@ -48,12 +47,12 @@ test.describe('Onboarding', () => {
const modeSaveButton = page.getByRole('button', { name: 'Save' });
await expect(modeSaveButton).toBeVisible();
await modeSaveButton.click();
-
+
// Verify the sample request
const request = page.locator('.collection-item-name').getByText('Get Users');
await expect(request).toBeVisible();
await request.click();
-
+
// Verify the URL is set correctly
await expect(page.locator('#request-url')).toContainText('https://jsonplaceholder.typicode.com/users');
@@ -67,16 +66,16 @@ test.describe('Onboarding', () => {
// Verify only one sample collection exists
const sampleCollections = newPage.locator('#sidebar-collection-name').getByText('Sample API Collection');
await expect(sampleCollections).toHaveCount(1);
-
+
// Verify the collection still works after restart
await sampleCollections.click();
const request2 = newPage.locator('.collection-item-name').getByText('Get Users');
await expect(request2).toBeVisible();
await request2.click();
-
+
// Verify the URL is still correct after restart
await expect(newPage.locator('#request-url')).toContainText('https://jsonplaceholder.typicode.com/users');
-
+
// Clean up
await newApp.close();
});
@@ -85,29 +84,28 @@ test.describe('Onboarding', () => {
const userDataPath = await createTmpDir('first-launch');
const app = await launchElectronApp({ userDataPath, dotEnv: env });
const page = await app.firstWindow();
-
+
// First launch - sample collection should be created
const sampleCollection = page.locator('.collection-name').filter({ hasText: 'Sample API Collection' });
await expect(sampleCollection).toBeVisible();
-
+
// User closes the sample collection (hover on the collection and open context menu)
await sampleCollection.hover();
await sampleCollection.locator('.collection-actions .icon').click();
-
// Close the sample collection
const closeOption = page.locator('.dropdown-item').getByText('Close');
await expect(closeOption).toBeVisible();
await closeOption.click();
-
+
// Handle the confirmation dialog - click the 'Close' button to confirm
const confirmCloseButton = page.locator('.bruno-modal').getByRole('button', { name: 'Close' });
await expect(confirmCloseButton).toBeVisible();
await confirmCloseButton.click();
-
+
// Verify collection is closed (no longer visible in sidebar)
await expect(sampleCollection).not.toBeVisible();
-
+
// Restart app - sample collection should NOT be recreated
const newApp = await reuseOrLaunchElectronApp({ userDataPath, dotEnv: env });
const newPage = await newApp.firstWindow();
@@ -127,7 +125,7 @@ test.describe('Onboarding', () => {
// This test simulates old users who already have a collection opened
const brunoTestbench = page.locator('#sidebar-collection-name').getByText('bruno-testbench');
await expect(brunoTestbench).toBeVisible();
-
+
// Verify no sample collection was created since user already has collections
const sampleCollection = page.locator('#sidebar-collection-name').getByText('Sample API Collection');
await expect(sampleCollection).not.toBeVisible();
diff --git a/tests/preferences/support-links.spec.js b/tests/preferences/support-links.spec.js
index d3a585c67..550b4ba02 100644
--- a/tests/preferences/support-links.spec.js
+++ b/tests/preferences/support-links.spec.js
@@ -1,27 +1,27 @@
import { test, expect } from '../../playwright';
test('Should verify all support links with correct URL in preference > Support tab', async ({ page }) => {
- // Open Preferences
- await page.getByLabel('Open Preferences').click();
-
- // Go to Support tab
- await page.getByRole('tab', { name: 'Support' }).click();
+ // Open Preferences
+ await page.getByLabel('Open Preferences').click();
- // Verify all support links with correct URL
- const locator_twitter = page.getByRole('link', { name: 'Twitter' });
- expect(await locator_twitter.getAttribute('href')).toEqual('https://twitter.com/use_bruno');
+ // Go to Support tab
+ await page.getByRole('tab', { name: 'Support' }).click();
- const locator_github = page.getByRole('link', { name: 'GitHub', exact: true });
- expect(await locator_github.getAttribute('href')).toEqual('https://github.com/usebruno/bruno');
+ // Verify all support links with correct URL
+ const locator_twitter = page.getByRole('link', { name: 'Twitter' });
+ expect(await locator_twitter.getAttribute('href')).toEqual('https://twitter.com/use_bruno');
- const locator_discord = page.getByRole('link', { name: 'Discord', exact: true });
- expect(await locator_discord.getAttribute('href')).toEqual('https://discord.com/invite/KgcZUncpjq');
+ const locator_github = page.getByRole('link', { name: 'GitHub', exact: true });
+ expect(await locator_github.getAttribute('href')).toEqual('https://github.com/usebruno/bruno');
- const locator_reportissues = page.getByRole('link', { name: 'Report Issues', exact: true });
- expect(await locator_reportissues.getAttribute('href')).toEqual('https://github.com/usebruno/bruno/issues');
+ const locator_discord = page.getByRole('link', { name: 'Discord', exact: true });
+ expect(await locator_discord.getAttribute('href')).toEqual('https://discord.com/invite/KgcZUncpjq');
- const locator_documentation = page.getByRole('link', { name: 'Documentation', exact: true });
- expect(await locator_documentation.getAttribute('href')).toEqual('https://docs.usebruno.com');
+ const locator_reportissues = page.getByRole('link', { name: 'Report Issues', exact: true });
+ expect(await locator_reportissues.getAttribute('href')).toEqual('https://github.com/usebruno/bruno/issues');
+
+ const locator_documentation = page.getByRole('link', { name: 'Documentation', exact: true });
+ expect(await locator_documentation.getAttribute('href')).toEqual('https://docs.usebruno.com');
await page.locator('[data-test-id="modal-close-button"]').click();
});
diff --git a/tests/runner/collection-run.ts b/tests/runner/collection-run.ts
index 8ac19857c..1f7a01db5 100644
--- a/tests/runner/collection-run.ts
+++ b/tests/runner/collection-run.ts
@@ -66,4 +66,4 @@ test.describe.parallel('Collection Run', () => {
await expect(failed).toBe(0);
await expect(passed).toBe(totalRequests - skipped - failed);
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/basic-ssl/tests/basic-ssl-success/basic-ssl-success.spec.ts b/tests/ssl/basic-ssl/tests/basic-ssl-success/basic-ssl-success.spec.ts
index 85131cee3..292d59167 100644
--- a/tests/ssl/basic-ssl/tests/basic-ssl-success/basic-ssl-success.spec.ts
+++ b/tests/ssl/basic-ssl/tests/basic-ssl-success/basic-ssl-success.spec.ts
@@ -37,4 +37,4 @@ test.describe.serial('basic ssl success', () => {
skipped: 0
});
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/basic-ssl/tests/self-signed-rejected/self-signed-rejected.spec.ts b/tests/ssl/basic-ssl/tests/self-signed-rejected/self-signed-rejected.spec.ts
index 489177144..b9ceda07c 100644
--- a/tests/ssl/basic-ssl/tests/self-signed-rejected/self-signed-rejected.spec.ts
+++ b/tests/ssl/basic-ssl/tests/self-signed-rejected/self-signed-rejected.spec.ts
@@ -37,4 +37,4 @@ test.describe.serial('self signed rejected', () => {
skipped: 0
});
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/basic-ssl/tests/self-signed-success-with-validation-disabled/self-signed-success-with-validation-disabled.spec.ts b/tests/ssl/basic-ssl/tests/self-signed-success-with-validation-disabled/self-signed-success-with-validation-disabled.spec.ts
index 4b2543db8..4ce7da761 100644
--- a/tests/ssl/basic-ssl/tests/self-signed-success-with-validation-disabled/self-signed-success-with-validation-disabled.spec.ts
+++ b/tests/ssl/basic-ssl/tests/self-signed-success-with-validation-disabled/self-signed-success-with-validation-disabled.spec.ts
@@ -37,4 +37,4 @@ test.describe.serial('self signed success with validation disabled', () => {
skipped: 0
});
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/custom-ca-certs/server/helpers/certs.js b/tests/ssl/custom-ca-certs/server/helpers/certs.js
index 259a4f25e..c8a9a385a 100644
--- a/tests/ssl/custom-ca-certs/server/helpers/certs.js
+++ b/tests/ssl/custom-ca-certs/server/helpers/certs.js
@@ -11,10 +11,10 @@ function createCertsDir(certsDir) {
function generateCertificates(certsDir) {
execCommand('openssl version');
-
+
// Generate CA private key
execCommand('openssl genrsa -out ca-key.pem 4096', certsDir);
-
+
// Create CA configuration file with proper CA extensions and subject (LibreSSL/OpenSSL compatible)
const caConfigContent = `[req]
distinguished_name = req_distinguished_name
@@ -33,15 +33,15 @@ basicConstraints = critical, CA:TRUE
keyUsage = critical, keyCertSign, cRLSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always`;
-
+
fs.writeFileSync(path.join(certsDir, 'ca.conf'), caConfigContent);
-
+
// Generate CA certificate with proper CA extensions using config file (no -subj needed)
execCommand('openssl req -new -x509 -key ca-key.pem -out ca-cert.pem -days 3650 -config ca.conf', certsDir);
-
+
// Generate server private key and CSR
execCommand('openssl genrsa -out localhost-key.pem 4096', certsDir);
-
+
// Create server CSR configuration file
const serverCsrConfigContent = `[req]
distinguished_name = req_distinguished_name
@@ -53,10 +53,10 @@ ST = Dev
L = Local
O = Local Dev
CN = localhost`;
-
+
fs.writeFileSync(path.join(certsDir, 'localhost-csr.conf'), serverCsrConfigContent);
execCommand('openssl req -new -key localhost-key.pem -out localhost.csr -config localhost-csr.conf', certsDir);
-
+
// Create server certificate configuration file (LibreSSL/OpenSSL compatible)
const serverConfigContent = `[req]
distinguished_name = req_distinguished_name
@@ -83,27 +83,27 @@ DNS.2 = localhost.localdomain
IP.1 = 127.0.0.1
IP.2 = ::1
IP.3 = ::ffff:127.0.0.1`;
-
+
fs.writeFileSync(path.join(certsDir, 'localhost.conf'), serverConfigContent);
execCommand('openssl x509 -req -in localhost.csr -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out localhost-cert.pem -days 730 -extensions v3_req -extfile localhost.conf', certsDir);
-
+
const platform = detectPlatform();
if (platform === 'windows') {
execCommand('openssl x509 -in ca-cert.pem -outform DER -out ca-cert.der', certsDir);
execCommand('openssl pkcs12 -export -out localhost.p12 -inkey localhost-key.pem -in localhost-cert.pem -certfile ca-cert.pem -password pass:', certsDir);
execCommand('openssl x509 -in localhost-cert.pem -outform DER -out localhost-cert.der', certsDir);
}
-
+
if (platform !== 'windows') {
execCommand('chmod 600 ca-key.pem localhost-key.pem', certsDir);
execCommand('chmod 644 ca-cert.pem localhost-cert.pem', certsDir);
}
-
- ['localhost.csr', 'localhost.conf', 'localhost-csr.conf', 'ca.conf', 'ca-cert.srl'].forEach(file => {
+
+ ['localhost.csr', 'localhost.conf', 'localhost-csr.conf', 'ca.conf', 'ca-cert.srl'].forEach((file) => {
const filePath = path.join(certsDir, file);
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
});
-
+
// Validate certificate chain
validateCertificateChain(certsDir);
}
@@ -112,29 +112,29 @@ function validateCertificateChain(certsDir) {
try {
// Verify CA certificate is valid and has proper CA extensions
const caVerifyOutput = execCommandSilent('openssl x509 -in ca-cert.pem -text -noout', certsDir).toString();
-
+
if (!caVerifyOutput.includes('CA:TRUE')) {
throw new Error('CA certificate missing basicConstraints=CA:TRUE');
}
-
+
if (!caVerifyOutput.includes('Certificate Sign')) {
throw new Error('CA certificate missing keyCertSign in keyUsage');
}
-
+
// Verify server certificate is valid and signed by CA
const serverVerifyOutput = execCommandSilent('openssl x509 -in localhost-cert.pem -text -noout', certsDir).toString();
-
+
if (!serverVerifyOutput.includes('CA:FALSE')) {
throw new Error('Server certificate should have basicConstraints=CA:FALSE');
}
-
+
if (!serverVerifyOutput.includes('TLS Web Server Authentication')) {
throw new Error('Server certificate missing serverAuth in extendedKeyUsage');
}
-
+
// Verify certificate chain
execCommandSilent('openssl verify -CAfile ca-cert.pem localhost-cert.pem', certsDir);
-
+
console.log('โ
Certificate chain validation passed');
} catch (error) {
console.error('โ Certificate validation failed:', error.message);
@@ -193,7 +193,7 @@ function verifyCertificates(certsDir) {
const platform = detectPlatform();
// Core PEM files required for all platforms
const requiredFiles = ['ca-cert.pem', 'ca-key.pem', 'localhost-cert.pem', 'localhost-key.pem'];
-
+
// Verify required PEM files exist
for (const file of requiredFiles) {
const filePath = path.join(certsDir, file);
@@ -201,7 +201,7 @@ function verifyCertificates(certsDir) {
throw new Error(`missing certificate file: ${file}`);
}
}
-
+
// Check Windows-specific files but don't require them (they're optional fallbacks)
if (platform === 'windows') {
const windowsFiles = ['ca-cert.der', 'localhost.p12', 'localhost-cert.der'];
@@ -222,4 +222,3 @@ module.exports = {
addCAToTruststore,
verifyCertificates
};
-
diff --git a/tests/ssl/custom-ca-certs/server/helpers/platform.js b/tests/ssl/custom-ca-certs/server/helpers/platform.js
index b1c88882e..806347a87 100644
--- a/tests/ssl/custom-ca-certs/server/helpers/platform.js
+++ b/tests/ssl/custom-ca-certs/server/helpers/platform.js
@@ -2,18 +2,18 @@ const { execSync } = require('node:child_process');
const os = require('node:os');
function execCommand(command, cwd = process.cwd()) {
- return execSync(command, {
- cwd,
+ return execSync(command, {
+ cwd,
stdio: 'inherit',
- timeout: 30000
+ timeout: 30000
});
}
function execCommandSilent(command, cwd = process.cwd()) {
- return execSync(command, {
- cwd,
+ return execSync(command, {
+ cwd,
stdio: 'pipe',
- timeout: 30000
+ timeout: 30000
});
}
@@ -29,7 +29,7 @@ function detectPlatform() {
function killProcessOnPort(port) {
const platform = detectPlatform();
-
+
try {
switch (platform) {
case 'macos':
@@ -57,4 +57,4 @@ module.exports = {
execCommandSilent,
detectPlatform,
killProcessOnPort
-};
\ No newline at end of file
+};
diff --git a/tests/ssl/custom-ca-certs/server/index.js b/tests/ssl/custom-ca-certs/server/index.js
index 4f22a7a7d..7d0725e83 100644
--- a/tests/ssl/custom-ca-certs/server/index.js
+++ b/tests/ssl/custom-ca-certs/server/index.js
@@ -6,11 +6,11 @@ const https = require('node:https');
const { killProcessOnPort } = require('./helpers/platform');
function createServer(certsDir, port = 8090) {
- const serverOptions = {
+ const serverOptions = {
key: fs.readFileSync(path.join(certsDir, 'localhost-key.pem')),
cert: fs.readFileSync(path.join(certsDir, 'localhost-cert.pem')),
ca: fs.readFileSync(path.join(certsDir, 'ca-cert.pem'))
- }
+ };
const server = https.createServer(serverOptions, (req, res) => {
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
@@ -31,9 +31,9 @@ function createServer(certsDir, port = 8090) {
function shutdownServer(server, cleanup) {
const shutdown = (signal) => {
console.log(`๐ Received ${signal}, shutting down`);
-
+
if (cleanup) cleanup();
-
+
if (server) {
server.close(() => process.exit(0));
} else {
@@ -56,11 +56,10 @@ async function startServer() {
console.log(`๐ Creating server on port ${port}`);
const server = await createServer(certsDir, port);
-
+
shutdownServer(server, () => {
console.log('โจ Server cleanup completed');
});
-
} catch (error) {
console.error('โ Server startup failed:', error.message);
process.exit(1);
@@ -71,4 +70,4 @@ if (require.main === module) {
startServer();
}
-module.exports = { startServer };
\ No newline at end of file
+module.exports = { startServer };
diff --git a/tests/ssl/custom-ca-certs/server/scripts/generate-certs.js b/tests/ssl/custom-ca-certs/server/scripts/generate-certs.js
index f470f77b8..9028e3748 100644
--- a/tests/ssl/custom-ca-certs/server/scripts/generate-certs.js
+++ b/tests/ssl/custom-ca-certs/server/scripts/generate-certs.js
@@ -13,7 +13,7 @@ const {
*/
async function setup() {
console.log('๐ง Setting up CA certificates for test server');
-
+
const certsDir = path.join(__dirname, '..', 'certs');
try {
diff --git a/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config-with-defaults/custom-invalid-ca-cert-in-config-with-defaults.spec.ts b/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config-with-defaults/custom-invalid-ca-cert-in-config-with-defaults.spec.ts
index b34314214..6ca570362 100644
--- a/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config-with-defaults/custom-invalid-ca-cert-in-config-with-defaults.spec.ts
+++ b/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config-with-defaults/custom-invalid-ca-cert-in-config-with-defaults.spec.ts
@@ -37,4 +37,4 @@ test.describe('custom invalid ca cert added to the config and keep default ca ce
skipped: 0
});
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config/custom-invalid-ca-cert-in-config.spec.ts b/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config/custom-invalid-ca-cert-in-config.spec.ts
index 825bcc63c..602c12b7f 100644
--- a/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config/custom-invalid-ca-cert-in-config.spec.ts
+++ b/tests/ssl/custom-ca-certs/tests/custom-invalid-ca-cert-in-config/custom-invalid-ca-cert-in-config.spec.ts
@@ -37,4 +37,4 @@ test.describe.serial('custom invalid ca cert added to the config and NO default
skipped: 0
});
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config-with-defaults/custom-valid-ca-cert-in-config-with-defaults.spec.ts b/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config-with-defaults/custom-valid-ca-cert-in-config-with-defaults.spec.ts
index 3811355c4..23c17354b 100644
--- a/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config-with-defaults/custom-valid-ca-cert-in-config-with-defaults.spec.ts
+++ b/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config-with-defaults/custom-valid-ca-cert-in-config-with-defaults.spec.ts
@@ -37,4 +37,4 @@ test.describe('custom valid ca cert added to the config and keep default ca cert
skipped: 0
});
});
-});
\ No newline at end of file
+});
diff --git a/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config/custom-valid-ca-cert-in-config.spec.ts b/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config/custom-valid-ca-cert-in-config.spec.ts
index 603976275..7675401ce 100644
--- a/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config/custom-valid-ca-cert-in-config.spec.ts
+++ b/tests/ssl/custom-ca-certs/tests/custom-valid-ca-cert-in-config/custom-valid-ca-cert-in-config.spec.ts
@@ -37,4 +37,4 @@ test.describe('custom valid ca cert added to the config and NO default ca certs'
skipped: 0
});
});
-});
\ No newline at end of file
+});
|