diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index fddeae6e..b18db1b8 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,7 +1,17 @@ # Description + -# Contribution Checklist: +### Contribution Checklist: + +- [ ] **The pull request only addresses one issue or adds one feature.** - [ ] **The pull request does not introduce any breaking changes** +- [ ] **I have added screenshots or gifs to help explain the change if applicable.** - [ ] **I have read the [contribution guidelines](https://github.com/usebruno/bruno/blob/main/contributing.md).** - [ ] **Create an issue and link to the pull request.** + +Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests. + +### Publishing to New Package Managers + +Please see [here](../publishing.md) for more information. diff --git a/.github/workflows/release-snap.yml b/.github/workflows/release-snap.yml index 2e730508..b71e8848 100644 --- a/.github/workflows/release-snap.yml +++ b/.github/workflows/release-snap.yml @@ -27,7 +27,10 @@ jobs: run: npm install --legacy-peer-deps - name: Build Electron app - run: npm run build:electron:snap + run: | + npm run build:bruno-query + npm run build:graphql-docs + npm run build:electron:snap - name: Install Snapcraft run: | diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 86a9e0eb..a2c73bee 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -5,18 +5,16 @@ on: pull_request: branches: [main] jobs: - test: + tests: timeout-minutes: 60 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-node@v3 with: - node-version: 16 - - name: Check package-lock.json - run: npm ci + node-version-file: '.nvmrc' - name: Install dependencies - run: npm i --legacy-peer-deps + run: npm ci --legacy-peer-deps - name: Test Package bruno-query run: npm run test --workspace=packages/bruno-query - name: Build Package bruno-query @@ -33,3 +31,15 @@ jobs: run: npm run test --workspace=packages/bruno-cli - name: Test Package bruno-electron run: npm run test --workspace=packages/bruno-electron + + prettier: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v3 + with: + node-version-file: '.nvmrc' + - name: Install dependencies + run: npm ci --legacy-peer-deps + - name: Run Prettier + run: npm run test:prettier:web diff --git a/contributing.md b/contributing.md index abfcce4d..92e05809 100644 --- a/contributing.md +++ b/contributing.md @@ -1,4 +1,4 @@ -**English** | [Русский](/contributing_ru.md) +**English** | [Українська](/contributing_ua.md) | [Русский](/contributing_ru.md) | [Türkçe](/contributing_tr.md) | [Deutsch](/contributing_de.md) ## Lets make bruno better, together !! @@ -33,5 +33,5 @@ Please reference [development.md](docs/development.md) for instructions on runni - Please follow the format of creating branches - feature/[feature name]: This branch should contain changes for a specific feature - Example: feature/dark-mode - - bugfix/[bug name]: This branch should container only bug fixes for a specific bug + - bugfix/[bug name]: This branch should contain only bug fixes for a specific bug - Example bugfix/bug-1 diff --git a/contributing_de.md b/contributing_de.md new file mode 100644 index 00000000..e189b6e9 --- /dev/null +++ b/contributing_de.md @@ -0,0 +1,37 @@ +[English](/contributing.md) | [Українська](/contributing_ua.md) | [Русский](/contributing_ru.md) | [Türkçe](/contributing_tr.md) | **Deutsch** + +## Lass uns Bruno noch besser machen, gemeinsam !! + +Ich freue mich, dass Du Bruno verbessern möchtest. Hier findest Du eine Anleitung, mit der Du Bruno auf Deinem Computer einrichten kannst. + +### Technologie Stack + +Bruno ist mit NextJs und React erstellt. Außerdem benötigen wir electron für die Desktop Version (die lokale Sammlungen unterstützt). + +Bibliotheken die wir benutzen + +- CSS - Tailwind +- Code Editoren - Codemirror +- State Management - Redux +- Icons - Tabler Icons +- Formulare - formik +- Schema Validierung - Yup +- Request Client - axios +- Dateisystem Watcher - chokidar + +### Abhängigkeiten + +Du benötigst [Node v18.x oder die neuste LTS Version](https://nodejs.org/en/) und npm 8.x. Wir benutzen npm workspaces in dem Projekt. + +### Lass uns coden + +Eine Anleitung zum Ausführen einer lokalen Entwicklungsumgebung findest Du in [development.md](docs/development_de.md). + +### Pull Request erstellen + +- Bitte halte die PRs klein und begrenzt auf eine Sache +- Bitte halte Dich beim Erstellen eines Branches an das folgende Format + - feature/[feature name]: Dieser Branch soll Änderungen für ein bestimmtes Feature enthalten + - Beispiel: feature/dark-mode + - bugfix/[bug name]: Dieser Branch soll ausschließlich Bugfixes für einen bestimmten Bug enthalten + - Beispiel: bugfix/bug-1 diff --git a/contributing_ru.md b/contributing_ru.md index 31640816..fa8e787c 100644 --- a/contributing_ru.md +++ b/contributing_ru.md @@ -1,4 +1,4 @@ -[English](/contributing.md) | **Русский** +[English](/contributing.md) | [Українська](/contributing_ua.md) | **Русский** | [Türkçe](/contributing_tr.md) | [Deutsch](/contributing_de.md) ## Давайте вместе сделаем Бруно лучше!!! @@ -34,4 +34,4 @@ Bruno построен с использованием NextJs и React. Мы т - feature/[название функции]: Эта ветка должна содержать изменения для конкретной функции - Пример: feature/dark-mode - bugfix/[название ошибки]: Эта ветка должна содержать только исправления для конкретной ошибки - - Пример bugfix/bug-1 \ No newline at end of file + - Пример bugfix/bug-1 diff --git a/contributing_tr.md b/contributing_tr.md new file mode 100644 index 00000000..c73c21f0 --- /dev/null +++ b/contributing_tr.md @@ -0,0 +1,37 @@ +[English](/readme.md) | [Українська](/contributing_ua.md) | [Русский](/contributing_ru.md) | **Türkçe** | [Deutsch](/contributing_de.md) + +## Bruno'yu birlikte daha iyi hale getirelim !! + +Bruno'yu geliştirmek istemenizden mutluluk duyuyorum. Aşağıda, bruno'yu bilgisayarınıza getirmeye başlamak için yönergeler bulunmaktadır. + +### Kullanılan Teknolojiler + +Bruno, NextJs ve React kullanılarak oluşturulmuştur. Ayrıca bir masaüstü sürümü (yerel koleksiyonları destekleyen) göndermek için electron kullanıyoruz + +Kullandığımız kütüphaneler + +- CSS - Tailwind +- Kod Düzenleyiciler - Codemirror +- Durum Yönetimi - Redux +- Iconlar - Tabler Simgeleri +- Formlar - formik +- Şema Doğrulama - Yup +- İstek İstemcisi - axios +- Dosya Sistemi İzleyicisi - chokidar + +### Bağımlılıklar + +[Node v18.x veya en son LTS sürümüne](https://nodejs.org/en/) ve npm 8.x'e ihtiyacınız olacaktır. Projede npm çalışma alanlarını kullanıyoruz + +### Kodlamaya başlayalım + +Yerel geliştirme ortamının çalıştırılmasına ilişkin talimatlar için lütfen [development.md](docs/development.md) adresine başvurun. + +### Pull Request Oluşturma + +- Lütfen PR'ları küçük tutun ve tek bir şeye odaklanın +- Lütfen şube oluşturma formatını takip edin + - feature/[özellik adı]: Bu dal belirli bir özellik için değişiklikler içermelidir + - Örnek: feature/dark-mode + - bugfix/[hata adı]: Bu dal yalnızca belirli bir hata için hata düzeltmelerini içermelidir + - Örnek bugfix/bug-1 diff --git a/contributing_ua.md b/contributing_ua.md new file mode 100644 index 00000000..c3ed9f5f --- /dev/null +++ b/contributing_ua.md @@ -0,0 +1,37 @@ +[English](/contributing.md) | **Українська** | [Русский](/contributing_ru.md) | [Türkçe](/contributing_tr.md) | [Deutsch](/contributing_de.md) + +## Давайте зробимо Bruno краще, разом !! + +Я дуже радий що Ви бажаєте покращити Bruno. Нижче наведені вказівки як розпочати розробку Bruno на Вашому комп'ютері. + +### Стек технологій + +Bruno побудований на NextJs та React. Також для десктопної версії (яка підтримує локальні колекції) використовується Electron + +Бібліотеки, які ми використовуємо + +- CSS - Tailwind +- Редактори коду - Codemirror +- Керування станом - Redux +- Іконки - Tabler Icons +- Форми - formik +- Валідація по схемі - Yup +- Клієнт запитів - axios +- Спостерігач за файловою системою - chokidar + +### Залежності + +Вам знадобиться [Node v18.x або остання LTS версія](https://nodejs.org/en/) та npm 8.x. Ми використовуєм npm workspaces в цьому проекті + +### Починаєм писати код + +Будь ласка, зверніться до [development_ua.md](docs/development_ua.md) за інструкціями щодо запуску локального середовища розробки. + +### Створення Pull Request-ів + +- Будь ласка, робіть PR-и маленькими і сфокусованими на одній речі +- Будь ласка, слідуйте формату назв гілок + - feature/[назва feature]: Така гілка має містити зміни лише щодо конкретної feature + - Приклад: feature/dark-mode + - bugfix/[назва баґу]: Така гілка має містити лише виправлення конкретного багу + - Приклад: bugfix/bug-1 diff --git a/docs/development.md b/docs/development.md index c1c402e0..0eaedf0c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,4 +1,4 @@ -**English** | [Русский](/docs/development_ru.md) +**English** | [Українська](/docs/development_ua.md) | [Русский](/docs/development_ru.md) | [Deutsch](/docs/development_de.md) ## Development diff --git a/docs/development_de.md b/docs/development_de.md new file mode 100644 index 00000000..bb762027 --- /dev/null +++ b/docs/development_de.md @@ -0,0 +1,55 @@ +[English](/docs/development.md) | [Українська](/docs/development_ua.md) | [Русский](/docs/development_ru.md) | **Deutsch** + +## Entwicklung + +Bruno wird als Desktop-Anwendung entwickelt. Um die App zu starten, musst Du zuerst die NextJs-App in einem Terminal ausführen und anschließend in einem anderen Terminal die Electron-App. + +### Abhängigkeiten + +- NodeJS v18 + +### Lokales Entwickeln + +```bash +# use nodejs 18 version +nvm use + +# install deps +npm i --legacy-peer-deps + +# build graphql docs +npm run build:graphql-docs + +# build bruno query +npm run build:bruno-query + +# run next app (terminal 1) +npm run dev:web + +# run electron app (terminal 2) +npm run dev:electron +``` + +### Troubleshooting + +Es kann sein, dass Du einen `Unsupported platform`-Fehler bekommst, wenn Du `npm install` ausführst. Um dies zu beheben, musst Du `node_modules` und `package-lock.json` löschen und `npm install` erneut ausführen. Dies sollte alle notwendigen Pakete installieren, die zum Ausführen der Anwendung benötigt werden. + +```shell +# Delete node_modules in sub-directories +find ./ -type d -name "node_modules" -print0 | while read -d $'\0' dir; do + rm -rf "$dir" +done + +# Delete package-lock in sub-directories +find . -type f -name "package-lock.json" -delete +``` + +### Testen + +```bash +# bruno-schema +npm test --workspace=packages/bruno-schema + +# bruno-lang +npm test --workspace=packages/bruno-lang +``` diff --git a/docs/development_ru.md b/docs/development_ru.md index 4d4e3a80..9ec11e84 100644 --- a/docs/development_ru.md +++ b/docs/development_ru.md @@ -1,4 +1,4 @@ -[English](/docs/development.md) | **Русский** +[English](/docs/development.md) | [Українська](/docs/development_ua.md) | **Русский** | [Deutsch](/docs/development_de.md) ## Разработка diff --git a/docs/development_ua.md b/docs/development_ua.md new file mode 100644 index 00000000..d3cfdc5e --- /dev/null +++ b/docs/development_ua.md @@ -0,0 +1,55 @@ +[English](/docs/development.md) | **Українська** | [Русский](/docs/development_ru.md) | [Deutsch](/docs/development_de.md) + +## Розробка + +Bruno розробляється як декстопний застосунок. Вам потрібно запустити nextjs в одній сесії терміналу, та запустити застосунок Electron в іншій сесії терміналу. + +### Залежності + +- NodeJS v18 + +### Локальна розробка + +```bash +# Використовуйте nodejs 18-ї версії +nvm use + +# встановіть залежності +npm i --legacy-peer-deps + +# зберіть документацію graphql +npm run build:graphql-docs + +# зберіть bruno query +npm run build:bruno-query + +# запустіть додаток next (термінал 1) +npm run dev:web + +# запустіть додаток електрон (термінал 2) +npm run dev:electron +``` + +### Усунення несправностей + +Ви можете зтикнутись із помилкою `Unsupported platform` коли запускаєте `npm install`. Щоб усунути цю проблему, вам потрібно видалити `node_modules` та `package-lock.json`, і тоді запустити `npm install`. Це має встановити всі потрібні для запуску додатку пекеджі. + +```shell +# Видаліть node_modules в піддиректоріях +find ./ -type d -name "node_modules" -print0 | while read -d $'\0' dir; do + rm -rf "$dir" +done + +# Видаліть package-lock в піддиректоріях +find . -type f -name "package-lock.json" -delete +``` + +### Тестування + +```bash +# bruno-schema +npm test --workspace=packages/bruno-schema + +# bruno-lang +npm test --workspace=packages/bruno-lang +``` diff --git a/package-lock.json b/package-lock.json index e8f35901..5dddfd54 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5534,75 +5534,6 @@ "node": ">=10.12.0" } }, - "node_modules/autoprefixer": { - "version": "10.4.16", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.16.tgz", - "integrity": "sha512-7vd3UC6xKp0HLfua5IjZlcXvGAGy7cBAXTg2lyQ/8WpNhd6SiZ8Be+xm3FyBSYJx5GKcpRCzBh7RH4/0dnY+uQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/autoprefixer" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "peer": true, - "dependencies": { - "browserslist": "^4.21.10", - "caniuse-lite": "^1.0.30001538", - "fraction.js": "^4.3.6", - "normalize-range": "^0.1.2", - "picocolors": "^1.0.0", - "postcss-value-parser": "^4.2.0" - }, - "bin": { - "autoprefixer": "bin/autoprefixer" - }, - "engines": { - "node": "^10 || ^12 || >=14" - }, - "peerDependencies": { - "postcss": "^8.1.0" - } - }, - "node_modules/autoprefixer/node_modules/browserslist": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.1.tgz", - "integrity": "sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "peer": true, - "dependencies": { - "caniuse-lite": "^1.0.30001541", - "electron-to-chromium": "^1.4.535", - "node-releases": "^2.0.13", - "update-browserslist-db": "^1.0.13" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, "node_modules/aws-sign2": { "version": "0.7.0", "dev": true, @@ -5998,6 +5929,7 @@ }, "node_modules/browserslist": { "version": "4.21.4", + "dev": true, "funding": [ { "type": "opencollective", @@ -7919,7 +7851,8 @@ "node_modules/electron-to-chromium": { "version": "1.4.554", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.554.tgz", - "integrity": "sha512-Q0umzPJjfBrrj8unkONTgbKQXzXRrH7sVV7D9ea2yBV3Oaogz991yhbpfvo2LMNkJItmruXTEzVpP9cp7vaIiQ==" + "integrity": "sha512-Q0umzPJjfBrrj8unkONTgbKQXzXRrH7sVV7D9ea2yBV3Oaogz991yhbpfvo2LMNkJItmruXTEzVpP9cp7vaIiQ==", + "dev": true }, "node_modules/electron-util": { "version": "0.17.2", @@ -8664,19 +8597,6 @@ "node": ">= 0.6" } }, - "node_modules/fraction.js": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", - "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", - "peer": true, - "engines": { - "node": "*" - }, - "funding": { - "type": "patreon", - "url": "https://github.com/sponsors/rawify" - } - }, "node_modules/fresh": { "version": "0.5.2", "license": "MIT", @@ -11856,7 +11776,8 @@ "node_modules/node-releases": { "version": "2.0.13", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", - "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==" + "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", + "dev": true }, "node_modules/normalize-package-data": { "version": "2.5.0", @@ -11889,15 +11810,6 @@ "node": ">=0.10.0" } }, - "node_modules/normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", - "peer": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/normalize-url": { "version": "6.1.0", "dev": true, @@ -15843,6 +15755,7 @@ "version": "1.0.13", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", + "dev": true, "funding": [ { "type": "opencollective", @@ -16534,7 +16447,7 @@ "@tabler/icons": "^1.46.0", "@tippyjs/react": "^4.2.6", "@usebruno/graphql-docs": "0.1.0", - "@usebruno/schema": "0.5.0", + "@usebruno/schema": "0.6.0", "axios": "^0.26.0", "classnames": "^2.3.1", "codemirror": "^5.65.2", @@ -16625,11 +16538,11 @@ }, "packages/bruno-cli": { "name": "@usebruno/cli", - "version": "0.14.0", + "version": "0.15.1", "license": "MIT", "dependencies": { - "@usebruno/js": "0.8.0", - "@usebruno/lang": "0.8.0", + "@usebruno/js": "0.9.1", + "@usebruno/lang": "0.9.0", "axios": "^1.5.1", "chai": "^4.3.7", "chalk": "^3.0.0", @@ -16717,17 +16630,16 @@ }, "packages/bruno-electron": { "name": "bruno", - "version": "v0.24.0", + "version": "v0.27.1", "dependencies": { "@aws-sdk/credential-providers": "^3.425.0", - "@usebruno/js": "0.8.0", - "@usebruno/lang": "0.8.0", - "@usebruno/schema": "0.5.0", + "@usebruno/js": "0.9.1", + "@usebruno/lang": "0.9.0", + "@usebruno/schema": "0.6.0", "about-window": "^1.15.2", "aws4-axios": "^3.3.0", "axios": "^1.5.1", "chai": "^4.3.7", - "chai-string": "^1.5.0", "chokidar": "^3.5.3", "decomment": "^0.9.5", "dotenv": "^16.0.3", @@ -16742,6 +16654,7 @@ "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.2", "is-valid-path": "^0.1.1", + "js-yaml": "^4.1.0", "lodash": "^4.17.21", "mustache": "^4.2.0", "nanoid": "3.3.4", @@ -16776,6 +16689,11 @@ "node": ">= 14" } }, + "packages/bruno-electron/node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, "packages/bruno-electron/node_modules/aws4-axios": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/aws4-axios/-/aws4-axios-3.3.0.tgz", @@ -16892,6 +16810,17 @@ "node": ">= 14" } }, + "packages/bruno-electron/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "packages/bruno-electron/node_modules/uuid": { "version": "9.0.0", "license": "MIT", @@ -16928,7 +16857,7 @@ }, "packages/bruno-js": { "name": "@usebruno/js", - "version": "0.8.0", + "version": "0.9.1", "license": "MIT", "dependencies": { "@usebruno/query": "0.1.0", @@ -16937,6 +16866,7 @@ "axios": "^0.26.0", "btoa": "^1.2.1", "chai": "^4.3.7", + "chai-string": "^1.5.0", "crypto-js": "^4.1.1", "handlebars": "^4.7.8", "json-query": "^2.2.2", @@ -16977,7 +16907,7 @@ }, "packages/bruno-lang": { "name": "@usebruno/lang", - "version": "0.8.0", + "version": "0.9.0", "license": "MIT", "dependencies": { "arcsecond": "^5.0.0", @@ -17014,7 +16944,7 @@ }, "packages/bruno-schema": { "name": "@usebruno/schema", - "version": "0.5.0", + "version": "0.6.0", "license": "MIT", "peerDependencies": { "yup": "^0.32.11" @@ -20578,7 +20508,7 @@ "@tabler/icons": "^1.46.0", "@tippyjs/react": "^4.2.6", "@usebruno/graphql-docs": "0.1.0", - "@usebruno/schema": "0.5.0", + "@usebruno/schema": "0.6.0", "axios": "^0.26.0", "babel-loader": "^8.2.3", "classnames": "^2.3.1", @@ -20660,8 +20590,8 @@ "@usebruno/cli": { "version": "file:packages/bruno-cli", "requires": { - "@usebruno/js": "0.8.0", - "@usebruno/lang": "0.8.0", + "@usebruno/js": "0.9.1", + "@usebruno/lang": "0.9.0", "axios": "^1.5.1", "chai": "^4.3.7", "chalk": "^3.0.0", @@ -20756,6 +20686,7 @@ "axios": "^0.26.0", "btoa": "^1.2.1", "chai": "^4.3.7", + "chai-string": "^1.5.0", "crypto-js": "^4.1.1", "handlebars": "^4.7.8", "json-query": "^2.2.2", @@ -21307,34 +21238,6 @@ "atomically": { "version": "1.7.0" }, - "autoprefixer": { - "version": "10.4.16", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.16.tgz", - "integrity": "sha512-7vd3UC6xKp0HLfua5IjZlcXvGAGy7cBAXTg2lyQ/8WpNhd6SiZ8Be+xm3FyBSYJx5GKcpRCzBh7RH4/0dnY+uQ==", - "peer": true, - "requires": { - "browserslist": "^4.21.10", - "caniuse-lite": "^1.0.30001538", - "fraction.js": "^4.3.6", - "normalize-range": "^0.1.2", - "picocolors": "^1.0.0", - "postcss-value-parser": "^4.2.0" - }, - "dependencies": { - "browserslist": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.1.tgz", - "integrity": "sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==", - "peer": true, - "requires": { - "caniuse-lite": "^1.0.30001541", - "electron-to-chromium": "^1.4.535", - "node-releases": "^2.0.13", - "update-browserslist-db": "^1.0.13" - } - } - } - }, "aws-sign2": { "version": "0.7.0", "dev": true @@ -21596,6 +21499,7 @@ }, "browserslist": { "version": "4.21.4", + "dev": true, "requires": { "caniuse-lite": "^1.0.30001400", "electron-to-chromium": "^1.4.251", @@ -21607,14 +21511,13 @@ "version": "file:packages/bruno-electron", "requires": { "@aws-sdk/credential-providers": "^3.425.0", - "@usebruno/js": "0.8.0", - "@usebruno/lang": "0.8.0", - "@usebruno/schema": "0.5.0", + "@usebruno/js": "0.9.1", + "@usebruno/lang": "0.9.0", + "@usebruno/schema": "0.6.0", "about-window": "^1.15.2", "aws4-axios": "^3.3.0", "axios": "^1.5.1", "chai": "^4.3.7", - "chai-string": "^1.5.0", "chokidar": "^3.5.3", "decomment": "^0.9.5", "dmg-license": "^1.0.11", @@ -21633,6 +21536,7 @@ "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.2", "is-valid-path": "^0.1.1", + "js-yaml": "^4.1.0", "lodash": "^4.17.21", "mustache": "^4.2.0", "nanoid": "3.3.4", @@ -21654,6 +21558,11 @@ "debug": "^4.3.4" } }, + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, "aws4-axios": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/aws4-axios/-/aws4-axios-3.3.0.tgz", @@ -21724,6 +21633,14 @@ "debug": "4" } }, + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "requires": { + "argparse": "^2.0.1" + } + }, "uuid": { "version": "9.0.0" } @@ -22948,7 +22865,8 @@ "electron-to-chromium": { "version": "1.4.554", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.554.tgz", - "integrity": "sha512-Q0umzPJjfBrrj8unkONTgbKQXzXRrH7sVV7D9ea2yBV3Oaogz991yhbpfvo2LMNkJItmruXTEzVpP9cp7vaIiQ==" + "integrity": "sha512-Q0umzPJjfBrrj8unkONTgbKQXzXRrH7sVV7D9ea2yBV3Oaogz991yhbpfvo2LMNkJItmruXTEzVpP9cp7vaIiQ==", + "dev": true }, "electron-util": { "version": "0.17.2", @@ -23429,12 +23347,6 @@ "forwarded": { "version": "0.2.0" }, - "fraction.js": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", - "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", - "peer": true - }, "fresh": { "version": "0.5.2" }, @@ -25443,7 +25355,8 @@ "node-releases": { "version": "2.0.13", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", - "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==" + "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", + "dev": true }, "normalize-package-data": { "version": "2.5.0", @@ -25468,12 +25381,6 @@ "normalize-path": { "version": "3.0.0" }, - "normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", - "peer": true - }, "normalize-url": { "version": "6.1.0", "dev": true @@ -27920,6 +27827,7 @@ "version": "1.0.13", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", + "dev": true, "requires": { "escalade": "^3.1.1", "picocolors": "^1.0.0" diff --git a/package.json b/package.json index 311da85f..eab3cd9d 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "build:electron:snap": "./scripts/build-electron.sh snap", "test:e2e": "npx playwright test", "test:report": "npx playwright show-report", + "test:prettier:web": "npm run test:prettier --workspace=packages/bruno-app", "prepare": "husky install" }, "overrides": { diff --git a/packages/bruno-app/package.json b/packages/bruno-app/package.json index ea4e9434..b23d7459 100644 --- a/packages/bruno-app/package.json +++ b/packages/bruno-app/package.json @@ -8,6 +8,7 @@ "start": "next start", "lint": "next lint", "test": "jest", + "test:prettier": "prettier --check \"./src/**/*.{js,jsx,json,ts,tsx}\"", "prettier": "prettier --write \"./src/**/*.{js,jsx,json,ts,tsx}\"" }, "dependencies": { @@ -18,7 +19,7 @@ "@tabler/icons": "^1.46.0", "@tippyjs/react": "^4.2.6", "@usebruno/graphql-docs": "0.1.0", - "@usebruno/schema": "0.5.0", + "@usebruno/schema": "0.6.0", "axios": "^0.26.0", "classnames": "^2.3.1", "codemirror": "^5.65.2", diff --git a/packages/bruno-app/src/components/CodeEditor/StyledWrapper.js b/packages/bruno-app/src/components/CodeEditor/StyledWrapper.js index fe0f4cc1..3623d406 100644 --- a/packages/bruno-app/src/components/CodeEditor/StyledWrapper.js +++ b/packages/bruno-app/src/components/CodeEditor/StyledWrapper.js @@ -5,6 +5,7 @@ const StyledWrapper = styled.div` background: ${(props) => props.theme.codemirror.bg}; border: solid 1px ${(props) => props.theme.codemirror.border}; font-family: ${(props) => (props.font ? props.font : 'default')}; + line-break: anywhere; } .CodeMirror-overlayscroll-horizontal div, diff --git a/packages/bruno-app/src/components/CollectionSettings/Docs/index.js b/packages/bruno-app/src/components/CollectionSettings/Docs/index.js index ca15cb3a..f759af2e 100644 --- a/packages/bruno-app/src/components/CollectionSettings/Docs/index.js +++ b/packages/bruno-app/src/components/CollectionSettings/Docs/index.js @@ -1,7 +1,7 @@ import 'github-markdown-css/github-markdown.css'; import get from 'lodash/get'; import { updateCollectionDocs } from 'providers/ReduxStore/slices/collections'; -import { useTheme } from 'providers/Theme/index'; +import { useTheme } from 'providers/Theme'; import { useState } from 'react'; import { useDispatch } from 'react-redux'; import { saveCollectionRoot } from 'providers/ReduxStore/slices/collections/actions'; diff --git a/packages/bruno-app/src/components/CollectionSettings/ProxySettings/index.js b/packages/bruno-app/src/components/CollectionSettings/ProxySettings/index.js index 8bd1ece4..2ed25b1e 100644 --- a/packages/bruno-app/src/components/CollectionSettings/ProxySettings/index.js +++ b/packages/bruno-app/src/components/CollectionSettings/ProxySettings/index.js @@ -1,13 +1,55 @@ import React, { useEffect } from 'react'; import { useFormik } from 'formik'; -import * as Yup from 'yup'; - +import Tooltip from 'components/Tooltip'; import StyledWrapper from './StyledWrapper'; +import * as Yup from 'yup'; +import toast from 'react-hot-toast'; const ProxySettings = ({ proxyConfig, onUpdate }) => { + const proxySchema = Yup.object({ + enabled: Yup.string().oneOf(['global', 'true', 'false']), + protocol: Yup.string().oneOf(['http', 'https', 'socks4', 'socks5']), + hostname: Yup.string() + .when('enabled', { + is: true, + then: (hostname) => hostname.required('Specify the hostname for your proxy.'), + otherwise: (hostname) => hostname.nullable() + }) + .max(1024), + port: Yup.number() + .when('enabled', { + is: true, + then: (port) => port.required('Specify port between 1 and 65535').typeError('Specify port between 1 and 65535'), + otherwise: (port) => port.nullable().transform((_, val) => (val ? Number(val) : null)) + }) + .min(1) + .max(65535), + auth: Yup.object() + .when('enabled', { + is: true, + then: Yup.object({ + enabled: Yup.boolean(), + username: Yup.string() + .when('enabled', { + is: true, + then: (username) => username.required('Specify username for proxy authentication.') + }) + .max(1024), + password: Yup.string() + .when('enabled', { + is: true, + then: (password) => password.required('Specify password for proxy authentication.') + }) + .max(1024) + }) + }) + .optional(), + bypassProxy: Yup.string().optional().max(1024) + }); + const formik = useFormik({ initialValues: { - enabled: proxyConfig.enabled || false, + enabled: proxyConfig.enabled || 'global', protocol: proxyConfig.protocol || 'http', hostname: proxyConfig.hostname || '', port: proxyConfig.port || '', @@ -15,27 +57,33 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => { enabled: proxyConfig.auth ? proxyConfig.auth.enabled || false : false, username: proxyConfig.auth ? proxyConfig.auth.username || '' : '', password: proxyConfig.auth ? proxyConfig.auth.password || '' : '' - } + }, + bypassProxy: proxyConfig.bypassProxy || '' }, - validationSchema: Yup.object({ - enabled: Yup.boolean(), - protocol: Yup.string().oneOf(['http', 'https', 'socks5']), - hostname: Yup.string().max(1024), - port: Yup.number().min(0).max(65535), - auth: Yup.object({ - enabled: Yup.boolean(), - username: Yup.string().max(1024), - password: Yup.string().max(1024) - }) - }), + validationSchema: proxySchema, onSubmit: (values) => { - onUpdate(values); + proxySchema + .validate(values, { abortEarly: true }) + .then((validatedProxy) => { + // serialize 'enabled' to boolean + if (validatedProxy.enabled === 'true') { + validatedProxy.enabled = true; + } else if (validatedProxy.enabled === 'false') { + validatedProxy.enabled = false; + } + + onUpdate(validatedProxy); + }) + .catch((error) => { + let errMsg = error.message || 'Preferences validation error'; + toast.error(errMsg); + }); } }); useEffect(() => { formik.setValues({ - enabled: proxyConfig.enabled || false, + enabled: proxyConfig.enabled === true ? 'true' : proxyConfig.enabled === false ? 'false' : 'global', protocol: proxyConfig.protocol || 'http', hostname: proxyConfig.hostname || '', port: proxyConfig.port || '', @@ -43,18 +91,66 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => { enabled: proxyConfig.auth ? proxyConfig.auth.enabled || false : false, username: proxyConfig.auth ? proxyConfig.auth.username || '' : '', password: proxyConfig.auth ? proxyConfig.auth.password || '' : '' - } + }, + bypassProxy: proxyConfig.bypassProxy || '' }); }, [proxyConfig]); return ( +

Proxy Settings

-
+ `} + tooltipId="request-var" + /> - +
+ + + +
+
@@ -132,7 +239,9 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => { onChange={formik.handleChange} value={formik.values.port} /> - {formik.touched.port && formik.errors.port ?
{formik.errors.port}
: null} + {formik.touched.port && formik.errors.port ? ( +
{formik.errors.port}
+ ) : null}
@@ -183,10 +292,30 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => { onChange={formik.handleChange} /> {formik.touched.auth?.password && formik.errors.auth?.password ? ( -
{formik.errors.auth.password}
+
{formik.errors.auth.password}
) : null}
+
+ + + {formik.touched.bypassProxy && formik.errors.bypassProxy ? ( +
{formik.errors.bypassProxy}
+ ) : null} +
setOpenImportModal(true)}> - + Import
diff --git a/packages/bruno-app/src/components/Preferences/General/index.js b/packages/bruno-app/src/components/Preferences/General/index.js index 2dbcfab7..00e91df7 100644 --- a/packages/bruno-app/src/components/Preferences/General/index.js +++ b/packages/bruno-app/src/components/Preferences/General/index.js @@ -1,67 +1,103 @@ -import React, { useState } from 'react'; +import React from 'react'; +import { useFormik } from 'formik'; import { useSelector, useDispatch } from 'react-redux'; import { savePreferences } from 'providers/ReduxStore/slices/app'; import StyledWrapper from './StyledWrapper'; +import * as Yup from 'yup'; +import toast from 'react-hot-toast'; const General = ({ close }) => { const preferences = useSelector((state) => state.app.preferences); const dispatch = useDispatch(); - const [sslVerification, setSslVerification] = useState(preferences.request.sslVerification); - const [timeout, setTimeout] = useState(preferences.request.timeout); + const preferencesSchema = Yup.object().shape({ + sslVerification: Yup.boolean(), + timeout: Yup.mixed() + .transform((value, originalValue) => { + return originalValue === '' ? undefined : value; + }) + .nullable() + .test('isNumber', 'Request Timeout must be a number', (value) => { + return value === undefined || !isNaN(value); + }) + .test('isValidTimeout', 'Request Timeout must be equal or greater than 0', (value) => { + return value === undefined || Number(value) >= 0; + }) + }); - const handleSave = () => { + const formik = useFormik({ + initialValues: { + sslVerification: preferences.request.sslVerification, + timeout: preferences.request.timeout + }, + validationSchema: preferencesSchema, + onSubmit: async (values) => { + try { + const newPreferences = await preferencesSchema.validate(values, { abortEarly: true }); + handleSave(newPreferences); + } catch (error) { + console.error('Preferences validation error:', error.message); + } + } + }); + + const handleSave = (newPreferences) => { dispatch( savePreferences({ ...preferences, request: { - sslVerification, - timeout + sslVerification: newPreferences.sslVerification, + timeout: newPreferences.timeout } }) - ).then(() => { - close(); - }); - }; - - const handleTimeoutChange = (value) => { - const validTimeout = isNaN(Number(value)) ? timeout : Number(value); - setTimeout(validTimeout); + ) + .then(() => { + close(); + }) + .catch((err) => console.log(err) && toast.error('Failed to update preferences')); }; return ( -
- - setSslVerification(!sslVerification)} - className="mousetrap mr-0" - /> -
-
- - handleTimeoutChange(e.target.value)} - defaultValue={timeout === 0 ? '' : timeout} - /> -
- -
- -
+ +
+ + +
+
+ + +
+ {formik.touched.timeout && formik.errors.timeout ? ( +
{formik.errors.timeout}
+ ) : null} +
+ +
+
); }; diff --git a/packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js b/packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js new file mode 100644 index 00000000..42d06266 --- /dev/null +++ b/packages/bruno-app/src/components/Preferences/ProxySettings/StyledWrapper.js @@ -0,0 +1,25 @@ +import styled from 'styled-components'; + +const StyledWrapper = styled.div` + .settings-label { + width: 80px; + } + + .textbox { + border: 1px solid #ccc; + padding: 0.15rem 0.45rem; + box-shadow: none; + outline: none; + transition: border-color ease-in-out 0.1s; + border-radius: 3px; + background-color: ${(props) => props.theme.modal.input.bg}; + border: 1px solid ${(props) => props.theme.modal.input.border}; + + &:focus { + border: solid 1px ${(props) => props.theme.modal.input.focusBorder} !important; + outline: none !important; + } + } +`; + +export default StyledWrapper; diff --git a/packages/bruno-app/src/components/Preferences/ProxySettings/index.js b/packages/bruno-app/src/components/Preferences/ProxySettings/index.js new file mode 100644 index 00000000..6b3fb787 --- /dev/null +++ b/packages/bruno-app/src/components/Preferences/ProxySettings/index.js @@ -0,0 +1,292 @@ +import React, { useEffect } from 'react'; +import { useFormik } from 'formik'; +import * as Yup from 'yup'; +import toast from 'react-hot-toast'; +import { savePreferences } from 'providers/ReduxStore/slices/app'; + +import StyledWrapper from './StyledWrapper'; +import { useDispatch, useSelector } from 'react-redux'; + +const ProxySettings = ({ close }) => { + const preferences = useSelector((state) => state.app.preferences); + const dispatch = useDispatch(); + + const proxySchema = Yup.object({ + enabled: Yup.boolean(), + protocol: Yup.string().required().oneOf(['http', 'https', 'socks4', 'socks5']), + hostname: Yup.string() + .when('enabled', { + is: true, + then: (hostname) => hostname.required('Specify the hostname for your proxy.'), + otherwise: (hostname) => hostname.nullable() + }) + .max(1024), + port: Yup.number() + .when('enabled', { + is: true, + then: (port) => port.required('Specify port between 1 and 65535').typeError('Specify port between 1 and 65535'), + otherwise: (port) => port.nullable().transform((_, val) => (val ? Number(val) : null)) + }) + .min(1) + .max(65535), + auth: Yup.object() + .when('enabled', { + is: true, + then: Yup.object({ + enabled: Yup.boolean(), + username: Yup.string() + .when(['enabled'], { + is: true, + then: (username) => username.required('Specify username for proxy authentication.') + }) + .max(1024), + password: Yup.string() + .when('enabled', { + is: true, + then: (password) => password.required('Specify password for proxy authentication.') + }) + .max(1024) + }) + }) + .optional(), + bypassProxy: Yup.string().optional().max(1024) + }); + + const formik = useFormik({ + initialValues: { + enabled: preferences.proxy.enabled || false, + protocol: preferences.proxy.protocol || 'http', + hostname: preferences.proxy.hostname || '', + port: preferences.proxy.port || 0, + auth: { + enabled: preferences.proxy.auth ? preferences.proxy.auth.enabled || false : false, + username: preferences.proxy.auth ? preferences.proxy.auth.username || '' : '', + password: preferences.proxy.auth ? preferences.proxy.auth.password || '' : '' + }, + bypassProxy: preferences.proxy.bypassProxy || '' + }, + validationSchema: proxySchema, + onSubmit: (values) => { + onUpdate(values); + } + }); + + const onUpdate = (values) => { + proxySchema + .validate(values, { abortEarly: true }) + .then((validatedProxy) => { + dispatch( + savePreferences({ + ...preferences, + proxy: validatedProxy + }) + ).then(() => { + close(); + }); + }) + .catch((error) => { + let errMsg = error.message || 'Preferences validation error'; + toast.error(errMsg); + }); + }; + + useEffect(() => { + formik.setValues({ + enabled: preferences.proxy.enabled || false, + protocol: preferences.proxy.protocol || 'http', + hostname: preferences.proxy.hostname || '', + port: preferences.proxy.port || '', + auth: { + enabled: preferences.proxy.auth ? preferences.proxy.auth.enabled || false : false, + username: preferences.proxy.auth ? preferences.proxy.auth.username || '' : '', + password: preferences.proxy.auth ? preferences.proxy.auth.password || '' : '' + }, + bypassProxy: preferences.proxy.bypassProxy || '' + }); + }, [preferences]); + + return ( + +

Global Proxy Settings

+
+
+ + +
+
+ +
+ + + + +
+
+
+ + + {formik.touched.hostname && formik.errors.hostname ? ( +
{formik.errors.hostname}
+ ) : null} +
+
+ + + {formik.touched.port && formik.errors.port ? ( +
{formik.errors.port}
+ ) : null} +
+
+ + +
+
+
+ + + {formik.touched.auth?.username && formik.errors.auth?.username ? ( +
{formik.errors.auth.username}
+ ) : null} +
+
+ + + {formik.touched.auth?.password && formik.errors.auth?.password ? ( +
{formik.errors.auth.password}
+ ) : null} +
+
+
+ + + {formik.touched.bypassProxy && formik.errors.bypassProxy ? ( +
{formik.errors.bypassProxy}
+ ) : null} +
+
+ +
+
+
+ ); +}; + +export default ProxySettings; diff --git a/packages/bruno-app/src/components/Preferences/index.js b/packages/bruno-app/src/components/Preferences/index.js index 217b3c57..843fd822 100644 --- a/packages/bruno-app/src/components/Preferences/index.js +++ b/packages/bruno-app/src/components/Preferences/index.js @@ -5,6 +5,7 @@ import Support from './Support'; import General from './General'; import Font from './Font'; import Theme from './Theme'; +import Proxy from './ProxySettings'; import StyledWrapper from './StyledWrapper'; const Preferences = ({ onClose }) => { @@ -22,6 +23,10 @@ const Preferences = ({ onClose }) => { return ; } + case 'proxy': { + return ; + } + case 'theme': { return ; } @@ -49,6 +54,9 @@ const Preferences = ({ onClose }) => {
setTab('font')}> Font
+
setTab('proxy')}> + Proxy +
setTab('support')}> Support
diff --git a/packages/bruno-app/src/components/RequestPane/FormUrlEncodedParams/index.js b/packages/bruno-app/src/components/RequestPane/FormUrlEncodedParams/index.js index 3cf5842e..6d1d5be2 100644 --- a/packages/bruno-app/src/components/RequestPane/FormUrlEncodedParams/index.js +++ b/packages/bruno-app/src/components/RequestPane/FormUrlEncodedParams/index.js @@ -107,6 +107,7 @@ const FormUrlEncodedParams = ({ item, collection }) => { 'value' ) } + allowNewlines={true} onRun={handleRun} collection={collection} /> diff --git a/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js b/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js index 29c46de7..98845b55 100644 --- a/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js +++ b/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js @@ -36,12 +36,7 @@ const GraphQLRequestPane = ({ item, collection, leftPaneWidth, onSchemaLoad, tog const request = item.draft ? item.draft.request : item.request; - let { - schema, - loadSchema, - isLoading: isSchemaLoading, - error: schemaError - } = useGraphqlSchema(url, environment, request, collection); + let { schema, loadSchema, isLoading: isSchemaLoading } = useGraphqlSchema(url, environment, request, collection); const loadGqlSchema = () => { if (!isSchemaLoading) { diff --git a/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/useGraphqlSchema.js b/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/useGraphqlSchema.js index e28ea5bc..c824c575 100644 --- a/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/useGraphqlSchema.js +++ b/packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/useGraphqlSchema.js @@ -26,7 +26,12 @@ const useGraphqlSchema = (endpoint, environment, request, collection) => { const loadSchema = () => { setIsLoading(true); fetchGqlSchema(endpoint, environment, request, collection) - .then((res) => res.data) + .then((res) => { + if (!res || res.status !== 200) { + return Promise.reject(new Error(res.statusText)); + } + return res.data; + }) .then((s) => { if (s && s.data) { setSchema(buildClientSchema(s.data)); @@ -40,7 +45,7 @@ const useGraphqlSchema = (endpoint, environment, request, collection) => { .catch((err) => { setIsLoading(false); setError(err); - toast.error('Error occurred while loading GraphQL Schema'); + toast.error(`Error occurred while loading GraphQL Schema: ${err.message}`); }); }; diff --git a/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/StyledWrapper.js b/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/StyledWrapper.js index e7277452..3d571b4b 100644 --- a/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/StyledWrapper.js +++ b/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/StyledWrapper.js @@ -4,7 +4,7 @@ const Wrapper = styled.div` font-size: 0.8125rem; .body-mode-selector { - background: ${(props) => props.theme.requestTabPanel.bodyModeSelect.color}; + background: transparent; border-radius: 3px; .dropdown-item { @@ -15,6 +15,10 @@ const Wrapper = styled.div` .label-item { padding: 0.2rem 0.6rem !important; } + + .selected-body-mode { + color: ${(props) => props.theme.colors.text.yellow}; + } } .caret { diff --git a/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/index.js b/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/index.js index 0d3b63df..ef000431 100644 --- a/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/index.js +++ b/packages/bruno-app/src/components/RequestPane/RequestBody/RequestBodyMode/index.js @@ -6,16 +6,19 @@ import { useDispatch } from 'react-redux'; import { updateRequestBodyMode } from 'providers/ReduxStore/slices/collections'; import { humanizeRequestBodyMode } from 'utils/collections'; import StyledWrapper from './StyledWrapper'; +import { updateRequestBody } from 'providers/ReduxStore/slices/collections/index'; +import { toastError } from 'utils/common/error'; const RequestBodyMode = ({ item, collection }) => { const dispatch = useDispatch(); const dropdownTippyRef = useRef(); const onDropdownCreate = (ref) => (dropdownTippyRef.current = ref); - const bodyMode = item.draft ? get(item, 'draft.request.body.mode') : get(item, 'request.body.mode'); + const body = item.draft ? get(item, 'draft.request.body') : get(item, 'request.body'); + const bodyMode = body?.mode; const Icon = forwardRef((props, ref) => { return ( -
+
{humanizeRequestBodyMode(bodyMode)}
); @@ -31,6 +34,24 @@ const RequestBodyMode = ({ item, collection }) => { ); }; + const onPrettify = () => { + if (body?.json && bodyMode === 'json') { + try { + const bodyJson = JSON.parse(body.json); + const prettyBodyJson = JSON.stringify(bodyJson, null, 2); + dispatch( + updateRequestBody({ + content: prettyBodyJson, + itemUid: item.uid, + collectionUid: collection.uid + }) + ); + } catch (e) { + toastError(new Error('Unable to prettify. Invalid JSON format.')); + } + } + }; + return (
@@ -103,6 +124,11 @@ const RequestBodyMode = ({ item, collection }) => {
+ {bodyMode === 'json' && ( + + )}
); }; diff --git a/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js b/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js new file mode 100644 index 00000000..5ed21ee9 --- /dev/null +++ b/packages/bruno-app/src/components/ResponsePane/QueryResult/QueryResultPreview/index.js @@ -0,0 +1,65 @@ +import CodeEditor from 'components/CodeEditor/index'; +import { get } from 'lodash'; +import { useDispatch, useSelector } from 'react-redux'; +import { sendRequest } from 'providers/ReduxStore/slices/collections/actions'; + +const QueryResultPreview = ({ + previewTab, + allowedPreviewModes, + data, + dataBuffer, + formattedData, + item, + contentType, + collection, + mode, + disableRunEventListener, + storedTheme +}) => { + const preferences = useSelector((state) => state.app.preferences); + const dispatch = useDispatch(); + + // Fail safe, so we don't render anything with an invalid tab + if (!allowedPreviewModes.includes(previewTab)) { + return null; + } + + const onRun = () => { + if (disableRunEventListener) { + return; + } + dispatch(sendRequest(item, collection.uid)); + }; + + switch (previewTab) { + case 'preview-web': { + const webViewSrc = data.replace('', ``); + return ( + + ); + } + case 'preview-image': { + return ; + } + default: + case 'raw': { + return ( + + ); + } + } +}; + +export default QueryResultPreview; diff --git a/packages/bruno-app/src/components/ResponsePane/QueryResult/index.js b/packages/bruno-app/src/components/ResponsePane/QueryResult/index.js index bb29abd3..18b9ec2c 100644 --- a/packages/bruno-app/src/components/ResponsePane/QueryResult/index.js +++ b/packages/bruno-app/src/components/ResponsePane/QueryResult/index.js @@ -1,137 +1,106 @@ import React from 'react'; -import get from 'lodash/get'; -import CodeEditor from 'components/CodeEditor'; -import { useTheme } from 'providers/Theme'; -import { useDispatch, useSelector } from 'react-redux'; -import { sendRequest } from 'providers/ReduxStore/slices/collections/actions'; import classnames from 'classnames'; import { getContentType, safeStringifyJSON, safeParseXML } from 'utils/common'; import { getCodeMirrorModeBasedOnContentType } from 'utils/common/codemirror'; +import QueryResultPreview from './QueryResultPreview'; import StyledWrapper from './StyledWrapper'; import { useState } from 'react'; import { useMemo } from 'react'; +import { useEffect } from 'react'; +import { useTheme } from 'providers/Theme/index'; -const QueryResult = ({ item, collection, data, width, disableRunEventListener, headers, error }) => { - const { storedTheme } = useTheme(); - const preferences = useSelector((state) => state.app.preferences); - const [tab, setTab] = useState('preview'); - const dispatch = useDispatch(); +const formatResponse = (data, mode) => { + if (!data) { + return ''; + } + + if (mode.includes('json')) { + return safeStringifyJSON(data, true); + } + + if (mode.includes('xml')) { + let parsed = safeParseXML(data, { collapseContent: true }); + if (typeof parsed === 'string') { + return parsed; + } + + return safeStringifyJSON(parsed, true); + } + + if (['text', 'html'].includes(mode) || typeof data === 'string') { + return data; + } + + return safeStringifyJSON(data); +}; + +const QueryResult = ({ item, collection, data, dataBuffer, width, disableRunEventListener, headers, error }) => { const contentType = getContentType(headers); const mode = getCodeMirrorModeBasedOnContentType(contentType); + const formattedData = formatResponse(data, mode); + const { storedTheme } = useTheme(); - const formatResponse = (data, mode) => { - if (!data) { - return ''; + const allowedPreviewModes = useMemo(() => { + // Always show raw + const allowedPreviewModes = ['raw']; + + if (mode.includes('html') && typeof data === 'string') { + allowedPreviewModes.unshift('preview-web'); + } else if (mode.includes('image')) { + allowedPreviewModes.unshift('preview-image'); } - if (mode.includes('json')) { - return safeStringifyJSON(data, true); + return allowedPreviewModes; + }, [mode, data, formattedData]); + + const [previewTab, setPreviewTab] = useState(allowedPreviewModes[0]); + // Ensure the active Tab is always allowed + useEffect(() => { + if (!allowedPreviewModes.includes(previewTab)) { + setPreviewTab(allowedPreviewModes[0]); } + }, [previewTab, allowedPreviewModes]); - if (mode.includes('xml')) { - let parsed = safeParseXML(data, { collapseContent: true }); - - if (typeof parsed === 'string') { - return parsed; - } - - return safeStringifyJSON(parsed, true); - } - - if (['text', 'html'].includes(mode)) { - if (typeof data === 'string') { - return data; - } - - return safeStringifyJSON(data); - } - - if (mode.includes('image')) { - return item.requestSent.url; - } - - // final fallback - if (typeof data === 'string') { - return data; - } - - return safeStringifyJSON(data); - }; - - const value = formatResponse(data, mode); - - const onRun = () => { - if (disableRunEventListener) { - return; - } - dispatch(sendRequest(item, collection.uid)); - }; - - const getTabClassname = (tabName) => { - return classnames(`select-none ${tabName}`, { - active: tabName === tab, - 'cursor-pointer': tabName !== tab - }); - }; - - const getTabs = () => { - if (!mode.includes('html')) { + const tabs = useMemo(() => { + if (allowedPreviewModes.length === 1) { return null; } - return ( - <> -
setTab('raw')}> - Raw -
-
setTab('preview')}> - Preview -
- - ); - }; - - const activeResult = useMemo(() => { - if ( - tab === 'preview' && - mode.includes('html') && - item.requestSent && - item.requestSent.url && - typeof data === 'string' - ) { - // Add the Base tag to the head so content loads properly. This also needs the correct CSP settings - const webViewSrc = data.replace('', ``); - return ( - - ); - } else if (mode.includes('image')) { - return image; - } - - return ( - - ); - }, [tab, collection, storedTheme, onRun, value, mode]); + return allowedPreviewModes.map((previewMode) => ( +
setPreviewTab(previewMode)} + key={previewMode} + > + {previewMode.replace(/-(.*)/, ' ')} +
+ )); + }, [allowedPreviewModes, previewTab]); return (
- {getTabs()} + {tabs}
- {error ? {error} : activeResult} + {error ? ( + {error} + ) : ( + + )}
); }; diff --git a/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js b/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js index 2500474c..b956b081 100644 --- a/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js +++ b/packages/bruno-app/src/components/ResponsePane/ResponseSize/index.js @@ -13,6 +13,10 @@ const ResponseSize = ({ size }) => { sizeToDisplay = size + 'B'; } - return {sizeToDisplay}; + return ( + + {sizeToDisplay} + + ); }; export default ResponseSize; diff --git a/packages/bruno-app/src/components/ResponsePane/index.js b/packages/bruno-app/src/components/ResponsePane/index.js index e1cfab2c..dbae1550 100644 --- a/packages/bruno-app/src/components/ResponsePane/index.js +++ b/packages/bruno-app/src/components/ResponsePane/index.js @@ -41,8 +41,10 @@ const ResponsePane = ({ rightPaneWidth, item, collection }) => { collection={collection} width={rightPaneWidth} data={response.data} + dataBuffer={response.dataBuffer} headers={response.headers} error={response.error} + key={item.filename} /> ); } diff --git a/packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js b/packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js index 2c4f28b2..aeba867f 100644 --- a/packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js +++ b/packages/bruno-app/src/components/RunnerResults/ResponsePane/index.js @@ -34,7 +34,9 @@ const ResponsePane = ({ rightPaneWidth, item, collection }) => { width={rightPaneWidth} disableRunEventListener={true} data={responseReceived.data} + dataBuffer={responseReceived.dataBuffer} headers={responseReceived.headers} + key={item.filename} /> ); } diff --git a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js index 0b33941f..31186e38 100644 --- a/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js +++ b/packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js @@ -87,45 +87,52 @@ const CollectionItem = ({ item, collection, searchText }) => { 'item-focused-in-tab': item.uid == activeTabUid }); + const scrollToTheActiveTab = () => { + const activeTab = document.querySelector('.request-tab.active'); + if (activeTab) { + activeTab.scrollIntoView({ behavior: 'smooth', block: 'start' }); + } + }; + const handleClick = (event) => { - switch (event.button) { - case 0: // left click - if (isItemARequest(item)) { - dispatch(hideHomePage()); - if (itemIsOpenedInTabs(item, tabs)) { - dispatch( - focusTab({ - uid: item.uid - }) - ); - return; - } - dispatch( - addTab({ - uid: item.uid, - collectionUid: collection.uid, - requestPaneTab: getDefaultRequestPaneTab(item) - }) - ); - return; - } + //scroll to the active tab + setTimeout(scrollToTheActiveTab, 50); + + if (isItemARequest(item)) { + dispatch(hideHomePage()); + if (itemIsOpenedInTabs(item, tabs)) { dispatch( - collectionFolderClicked({ - itemUid: item.uid, - collectionUid: collection.uid + focusTab({ + uid: item.uid }) ); return; - case 2: // right click - const _menuDropdown = dropdownTippyRef.current; - if (_menuDropdown) { - let menuDropdownBehavior = 'show'; - if (_menuDropdown.state.isShown) { - menuDropdownBehavior = 'hide'; - } - _menuDropdown[menuDropdownBehavior](); - } - return; + } + dispatch( + addTab({ + uid: item.uid, + collectionUid: collection.uid, + requestPaneTab: getDefaultRequestPaneTab(item) + }) + ); + return; + } + dispatch( + collectionFolderClicked({ + itemUid: item.uid, + collectionUid: collection.uid + }) + ); + }; + + const handleRightClick = (event) => { + const _menuDropdown = dropdownTippyRef.current; + if (_menuDropdown) { + let menuDropdownBehavior = 'show'; + if (_menuDropdown.state.isShown) { + menuDropdownBehavior = 'hide'; + } + _menuDropdown[menuDropdownBehavior](); } }; @@ -203,7 +210,8 @@ const CollectionItem = ({ item, collection, searchText }) => { ? indents.map((i) => { return (
{ }) : null}
{ return ( - Are you sure you want to remove this collection? + Are you sure you want to remove collection {collection.name} ? ); }; diff --git a/packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js b/packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js index 37683d6e..bf7d41d6 100644 --- a/packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js +++ b/packages/bruno-app/src/components/Sidebar/Collections/Collection/index.js @@ -66,20 +66,17 @@ const Collection = ({ collection, searchText }) => { }); const handleClick = (event) => { + dispatch(collectionClicked(collection.uid)); + }; + + const handleRightClick = (event) => { const _menuDropdown = menuDropdownTippyRef.current; - switch (event.button) { - case 0: // left click - dispatch(collectionClicked(collection.uid)); - return; - case 2: // right click - if (_menuDropdown) { - let menuDropdownBehavior = 'show'; - if (_menuDropdown.state.isShown) { - menuDropdownBehavior = 'hide'; - } - _menuDropdown[menuDropdownBehavior](); - } - return; + if (_menuDropdown) { + let menuDropdownBehavior = 'show'; + if (_menuDropdown.state.isShown) { + menuDropdownBehavior = 'hide'; + } + _menuDropdown[menuDropdownBehavior](); } }; @@ -138,7 +135,11 @@ const Collection = ({ collection, searchText }) => { setCollectionPropertiesModal(false)} /> )}
-
+
{ name="collectionName" ref={inputRef} className="block textbox mt-2 w-full" - onChange={formik.handleChange} + onChange={(e) => { + formik.handleChange(e); + if (formik.values.collectionName === formik.values.collectionFolderName) { + formik.setFieldValue('collectionFolderName', e.target.value); + } + }} autoComplete="off" autoCorrect="off" autoCapitalize="off" diff --git a/packages/bruno-app/src/components/Sidebar/ImportCollection/index.js b/packages/bruno-app/src/components/Sidebar/ImportCollection/index.js index 185e3c5c..ecfc4183 100644 --- a/packages/bruno-app/src/components/Sidebar/ImportCollection/index.js +++ b/packages/bruno-app/src/components/Sidebar/ImportCollection/index.js @@ -2,6 +2,7 @@ import React from 'react'; import importBrunoCollection from 'utils/importers/bruno-collection'; import importPostmanCollection from 'utils/importers/postman-collection'; import importInsomniaCollection from 'utils/importers/insomnia-collection'; +import importOpenapiCollection from 'utils/importers/openapi-collection'; import { toastError } from 'utils/common/error'; import Modal from 'components/Modal'; @@ -30,6 +31,14 @@ const ImportCollection = ({ onClose, handleSubmit }) => { .catch((err) => toastError(err, 'Insomnia Import collection failed')); }; + const handleImportOpenapiCollection = () => { + importOpenapiCollection() + .then((collection) => { + handleSubmit(collection); + }) + .catch((err) => toastError(err, 'OpenAPI v3 Import collection failed')); + }; + return (
@@ -42,6 +51,9 @@ const ImportCollection = ({ onClose, handleSubmit }) => {
Insomnia Collection
+
+ OpenAPI V3 Spec +
); diff --git a/packages/bruno-app/src/components/Sidebar/index.js b/packages/bruno-app/src/components/Sidebar/index.js index a27ef632..89076197 100644 --- a/packages/bruno-app/src/components/Sidebar/index.js +++ b/packages/bruno-app/src/components/Sidebar/index.js @@ -105,7 +105,7 @@ const Sidebar = () => { Star
-
v0.25.0
+
v0.27.2
diff --git a/packages/bruno-app/src/components/SingleLineEditor/index.js b/packages/bruno-app/src/components/SingleLineEditor/index.js index bee59b2d..fb3bff21 100644 --- a/packages/bruno-app/src/components/SingleLineEditor/index.js +++ b/packages/bruno-app/src/components/SingleLineEditor/index.js @@ -57,6 +57,7 @@ class SingleLineEditor extends Component { } componentDidMount() { // Initialize CodeMirror as a single line editor + /** @type {import("codemirror").Editor} */ this.editor = CodeMirror(this.editorRef.current, { lineWrapping: false, lineNumbers: false, @@ -84,7 +85,10 @@ class SingleLineEditor extends Component { } }, 'Alt-Enter': () => { - if (this.props.onRun) { + if (this.props.allowNewlines) { + this.editor.setValue(this.editor.getValue() + '\n'); + this.editor.setCursor({ line: this.editor.lineCount(), ch: 0 }); + } else if (this.props.onRun) { this.props.onRun(); } }, diff --git a/packages/bruno-app/src/components/Tooltip/index.js b/packages/bruno-app/src/components/Tooltip/index.js index b1ca2643..d5ab5c41 100644 --- a/packages/bruno-app/src/components/Tooltip/index.js +++ b/packages/bruno-app/src/components/Tooltip/index.js @@ -18,7 +18,7 @@ const Tooltip = ({ text, tooltipId }) => { - + ); }; diff --git a/packages/bruno-app/src/components/Welcome/index.js b/packages/bruno-app/src/components/Welcome/index.js index 27851653..adfce3dd 100644 --- a/packages/bruno-app/src/components/Welcome/index.js +++ b/packages/bruno-app/src/components/Welcome/index.js @@ -2,7 +2,7 @@ import { useState } from 'react'; import toast from 'react-hot-toast'; import { useDispatch } from 'react-redux'; import { openCollection, importCollection } from 'providers/ReduxStore/slices/collections/actions'; -import { IconBrandGithub, IconPlus, IconUpload, IconFolders, IconSpeakerphone, IconBook } from '@tabler/icons'; +import { IconBrandGithub, IconPlus, IconDownload, IconFolders, IconSpeakerphone, IconBook } from '@tabler/icons'; import Bruno from 'components/Bruno'; import CreateCollection from 'components/Sidebar/CreateCollection'; @@ -69,7 +69,7 @@ const Welcome = () => { Open Collection
setImportCollectionModalOpen(true)}> - + Import Collection diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/app.js b/packages/bruno-app/src/providers/ReduxStore/slices/app.js index c3a3aa5a..6f5c849f 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/app.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/app.js @@ -9,7 +9,8 @@ const initialState = { showHomePage: false, preferences: { request: { - sslVerification: true + sslVerification: true, + timeout: 0 }, font: { codeFont: 'default' 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 38e3c30e..20a68b80 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js @@ -21,7 +21,7 @@ import { } from 'utils/collections'; import { collectionSchema, itemSchema, environmentSchema, environmentsSchema } from '@usebruno/schema'; import { waitForNextTick } from 'utils/common'; -import { getDirectoryName, isWindowsOS } from 'utils/common/platform'; +import { getDirectoryName, isWindowsOS, PATH_SEPARATOR } from 'utils/common/platform'; import { sendNetworkRequest, cancelNetworkRequest } from 'utils/network'; import { @@ -31,7 +31,6 @@ import { requestCancelled, responseReceived, newItem as _newItem, - renameItem as _renameItem, cloneItem as _cloneItem, deleteItem as _deleteItem, saveRequest as _saveRequest, @@ -48,8 +47,6 @@ import { resolveRequestFilename } from 'utils/common/platform'; import { parseQueryParams, splitOnFirst } from 'utils/url/index'; import { each } from 'lodash'; -const PATH_SEPARATOR = path.sep; - export const renameCollection = (newName, collectionUid) => (dispatch, getState) => { const state = getState(); const collection = findCollectionByUid(state.collections.collections, collectionUid); @@ -186,11 +183,6 @@ export const cancelRequest = (cancelTokenUid, item, collection) => (dispatch) => .catch((err) => console.log(err)); }; -// todo: this can be directly put inside the collections/index.js file -// the coding convention is to put only actions that need ipc in this file -export const sortCollections = (order) => (dispatch) => { - dispatch(_sortCollections(order)); -}; export const runCollectionFolder = (collectionUid, folderUid, recursive) => (dispatch, getState) => { const state = getState(); const collection = findCollectionByUid(state.collections.collections, collectionUid); @@ -308,19 +300,7 @@ export const renameItem = (newName, itemUid, collectionUid) => (dispatch, getSta } const { ipcRenderer } = window; - ipcRenderer - .invoke('renderer:rename-item', item.pathname, newPathname, newName) - .then(() => { - // In case of Mac and Linux, we get the unlinkDir and addDir IPC events from electron which takes care of updating the state - // But in windows we don't get those events, so we need to update the state manually - // This looks like an issue in our watcher library chokidar - // GH: https://github.com/usebruno/bruno/issues/251 - if (isWindowsOS()) { - dispatch(_renameItem({ newName, itemUid, collectionUid })); - } - resolve(); - }) - .catch(reject); + ipcRenderer.invoke('renderer:rename-item', item.pathname, newPathname, newName).then(resolve).catch(reject); }); }; @@ -405,13 +385,6 @@ export const deleteItem = (itemUid, collectionUid) => (dispatch, getState) => { ipcRenderer .invoke('renderer:delete-item', item.pathname, item.type) .then(() => { - // In case of Mac and Linux, we get the unlinkDir IPC event from electron which takes care of updating the state - // But in windows we don't get those events, so we need to update the state manually - // This looks like an issue in our watcher library chokidar - // GH: https://github.com/usebruno/bruno/issues/265 - if (isWindowsOS()) { - dispatch(_deleteItem({ itemUid, collectionUid })); - } resolve(); }) .catch((error) => reject(error)); @@ -420,6 +393,9 @@ export const deleteItem = (itemUid, collectionUid) => (dispatch, getState) => { }); }; +export const sortCollections = (payload) => (dispatch) => { + dispatch(_sortCollections(payload)); +}; export const moveItem = (collectionUid, draggedItemUid, targetItemUid) => (dispatch, getState) => { const state = getState(); const collection = findCollectionByUid(state.collections.collections, collectionUid); 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 c60b3e68..4ad30d20 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js @@ -1,4 +1,3 @@ -import path from 'path'; import { uuid } from 'utils/common'; import find from 'lodash/find'; import map from 'lodash/map'; @@ -25,9 +24,7 @@ import { areItemsTheSameExceptSeqUpdate } from 'utils/collections'; import { parseQueryParams, stringifyQueryParams } from 'utils/url'; -import { getSubdirectoriesFromRoot, getDirectoryName } from 'utils/common/platform'; - -const PATH_SEPARATOR = path.sep; +import { getSubdirectoriesFromRoot, getDirectoryName, PATH_SEPARATOR } from 'utils/common/platform'; const initialState = { collections: [], diff --git a/packages/bruno-app/src/utils/common/platform.js b/packages/bruno-app/src/utils/common/platform.js index 771daaf1..03ff9539 100644 --- a/packages/bruno-app/src/utils/common/platform.js +++ b/packages/bruno-app/src/utils/common/platform.js @@ -48,3 +48,5 @@ export const isMacOS = () => { return osFamily.includes('os x'); }; + +export const PATH_SEPARATOR = isWindowsOS() ? '\\' : '/'; diff --git a/packages/bruno-app/src/utils/importers/insomnia-collection.js b/packages/bruno-app/src/utils/importers/insomnia-collection.js index 8b7b7fb6..8d8113b4 100644 --- a/packages/bruno-app/src/utils/importers/insomnia-collection.js +++ b/packages/bruno-app/src/utils/importers/insomnia-collection.js @@ -1,3 +1,4 @@ +import jsyaml from 'js-yaml'; import each from 'lodash/each'; import get from 'lodash/get'; import fileDialog from 'file-dialog'; @@ -8,7 +9,22 @@ import { validateSchema, transformItemsInCollection, hydrateSeqInCollection } fr const readFile = (files) => { return new Promise((resolve, reject) => { const fileReader = new FileReader(); - fileReader.onload = (e) => resolve(e.target.result); + fileReader.onload = (e) => { + try { + // try to load JSON + const parsedData = JSON.parse(e.target.result); + resolve(parsedData); + } catch (jsonError) { + // not a valid JSOn, try yaml + try { + const parsedData = jsyaml.load(e.target.result); + resolve(parsedData); + } catch (yamlError) { + console.error('Error parsing the file :', jsonError, yamlError); + reject(new BrunoError('Import collection failed')); + } + } + }; fileReader.onerror = (err) => reject(err); fileReader.readAsText(files[0]); }); @@ -167,7 +183,7 @@ const parseInsomniaCollection = (data) => { return new Promise((resolve, reject) => { try { - const insomniaExport = JSON.parse(data); + const insomniaExport = data; const insomniaResources = get(insomniaExport, 'resources', []); const insomniaCollection = insomniaResources.find((resource) => resource._type === 'workspace'); @@ -213,7 +229,7 @@ const parseInsomniaCollection = (data) => { const importCollection = () => { return new Promise((resolve, reject) => { - fileDialog({ accept: 'application/json' }) + fileDialog({ accept: '.json, .yaml, .yml, application/json, application/yaml, application/x-yaml' }) .then(readFile) .then(parseInsomniaCollection) .then(transformItemsInCollection) @@ -221,8 +237,8 @@ const importCollection = () => { .then(validateSchema) .then((collection) => resolve(collection)) .catch((err) => { - console.log(err); - reject(new BrunoError('Import collection failed')); + console.error(err); + reject(new BrunoError('Import collection failed: ' + err.message)); }); }); }; diff --git a/packages/bruno-app/src/utils/importers/openapi-collection.js b/packages/bruno-app/src/utils/importers/openapi-collection.js new file mode 100644 index 00000000..1ca6e25b --- /dev/null +++ b/packages/bruno-app/src/utils/importers/openapi-collection.js @@ -0,0 +1,386 @@ +import jsyaml from 'js-yaml'; +import each from 'lodash/each'; +import get from 'lodash/get'; +import fileDialog from 'file-dialog'; +import { uuid } from 'utils/common'; +import { BrunoError } from 'utils/common/error'; +import { validateSchema, transformItemsInCollection, hydrateSeqInCollection } from './common'; + +const readFile = (files) => { + return new Promise((resolve, reject) => { + const fileReader = new FileReader(); + fileReader.onload = (e) => { + try { + // try to load JSON + const parsedData = JSON.parse(e.target.result); + resolve(parsedData); + } catch (jsonError) { + // not a valid JSOn, try yaml + try { + const parsedData = jsyaml.load(e.target.result); + resolve(parsedData); + } catch (yamlError) { + console.error('Error parsing the file :', jsonError, yamlError); + reject(new BrunoError('Import collection failed')); + } + } + }; + fileReader.onerror = (err) => reject(err); + fileReader.readAsText(files[0]); + }); +}; + +const ensureUrl = (url) => { + let protUrl = url.startsWith('http') ? url : `http://${url}`; + // replace any double or triple slashes + return protUrl.replace(/([^:]\/)\/+/g, '$1'); +}; + +const buildEmptyJsonBody = (bodySchema) => { + let _jsonBody = {}; + each(bodySchema.properties || {}, (prop, name) => { + if (prop.type === 'object') { + _jsonBody[name] = buildEmptyJsonBody(prop); + // handle arrays + } else if (prop.type === 'array') { + _jsonBody[name] = []; + } else { + _jsonBody[name] = ''; + } + }); + return _jsonBody; +}; + +const transformOpenapiRequestItem = (request) => { + let _operationObject = request.operationObject; + + let operationName = _operationObject.operationId || _operationObject.summary || _operationObject.description; + if (!operationName) { + operationName = `${request.method} ${request.path}`; + } + + const brunoRequestItem = { + uid: uuid(), + name: operationName, + type: 'http-request', + request: { + url: ensureUrl(request.global.server + '/' + request.path), + method: request.method.toUpperCase(), + auth: { + mode: 'none', + basic: null, + bearer: null + }, + headers: [], + params: [], + body: { + mode: 'none', + json: null, + text: null, + xml: null, + formUrlEncoded: [], + multipartForm: [] + } + } + }; + + each(_operationObject.parameters || [], (param) => { + if (param.in === 'query') { + brunoRequestItem.request.params.push({ + uid: uuid(), + name: param.name, + value: '', + description: param.description || '', + enabled: param.required + }); + } else if (param.in === 'header') { + brunoRequestItem.request.headers.push({ + uid: uuid(), + name: param.name, + value: '', + description: param.description || '', + enabled: param.required + }); + } + }); + + let auth; + // allow operation override + if (_operationObject.security && _operationObject.security.length > 0) { + let schemeName = Object.keys(_operationObject.security[0])[0]; + auth = request.global.security.getScheme(schemeName); + } else if (request.global.security.supported.length > 0) { + auth = request.global.security.supported[0]; + } + + if (auth) { + if (auth.type === 'http' && auth.scheme === 'basic') { + brunoRequestItem.request.auth.mode = 'basic'; + brunoRequestItem.request.auth.basic = { + username: '{{username}}', + password: '{{password}}' + }; + } else if (auth.type === 'http' && auth.scheme === 'bearer') { + brunoRequestItem.request.auth.mode = 'bearer'; + brunoRequestItem.request.auth.bearer = { + token: '{{token}}' + }; + } else if (auth.type === 'apiKey' && auth.in === 'header') { + brunoRequestItem.request.headers.push({ + uid: uuid(), + name: auth.name, + value: '{{apiKey}}', + description: 'Authentication header', + enabled: true + }); + } + } + + // TODO: handle allOf/anyOf/oneOf + if (_operationObject.requestBody) { + let content = get(_operationObject, 'requestBody.content', {}); + let mimeType = Object.keys(content)[0]; + let body = content[mimeType] || {}; + let bodySchema = body.schema; + if (mimeType === 'application/json') { + brunoRequestItem.request.body.mode = 'json'; + if (bodySchema && bodySchema.type === 'object') { + let _jsonBody = buildEmptyJsonBody(bodySchema); + brunoRequestItem.request.body.json = JSON.stringify(_jsonBody, null, 2); + } + } else if (mimeType === 'application/x-www-form-urlencoded') { + brunoRequestItem.request.body.mode = 'formUrlEncoded'; + if (bodySchema && bodySchema.type === 'object') { + each(bodySchema.properties || {}, (prop, name) => { + brunoRequestItem.request.body.formUrlEncoded.push({ + uid: uuid(), + name: name, + value: '', + description: prop.description || '', + enabled: true + }); + }); + } + } else if (mimeType === 'multipart/form-data') { + brunoRequestItem.request.body.mode = 'multipartForm'; + if (bodySchema && bodySchema.type === 'object') { + each(bodySchema.properties || {}, (prop, name) => { + brunoRequestItem.request.body.multipartForm.push({ + uid: uuid(), + name: name, + value: '', + description: prop.description || '', + enabled: true + }); + }); + } + } else if (mimeType === 'text/plain') { + brunoRequestItem.request.body.mode = 'text'; + brunoRequestItem.request.body.text = ''; + } else if (mimeType === 'text/xml') { + brunoRequestItem.request.body.mode = 'xml'; + brunoRequestItem.request.body.xml = ''; + } + } + + return brunoRequestItem; +}; + +const resolveRefs = (spec, components = spec.components) => { + if (!spec || typeof spec !== 'object') { + return spec; + } + + if (Array.isArray(spec)) { + return spec.map((item) => resolveRefs(item, components)); + } + + if ('$ref' in spec) { + const refPath = spec.$ref; + + if (refPath.startsWith('#/components/')) { + // Local reference within components + const refKeys = refPath.replace('#/components/', '').split('/'); + let ref = components; + + for (const key of refKeys) { + if (ref[key]) { + ref = ref[key]; + } else { + // Handle invalid references gracefully? + return spec; + } + } + + return resolveRefs(ref, components); + } else { + // Handle external references (not implemented here) + // You would need to fetch the external reference and resolve it. + // Example: Fetch and resolve an external reference from a URL. + } + } + + // Recursively resolve references in nested objects + for (const prop in spec) { + spec[prop] = resolveRefs(spec[prop], components); + } + + return spec; +}; + +const groupRequestsByTags = (requests) => { + let _groups = {}; + let ungrouped = []; + each(requests, (request) => { + let tags = request.operationObject.tags || []; + if (tags.length > 0) { + let tag = tags[0]; // take first tag + if (!_groups[tag]) { + _groups[tag] = []; + } + _groups[tag].push(request); + } else { + ungrouped.push(request); + } + }); + + let groups = Object.keys(_groups).map((groupName) => { + return { + name: groupName, + requests: _groups[groupName] + }; + }); + + return [groups, ungrouped]; +}; + +const getDefaultUrl = (serverObject) => { + let url = serverObject.url; + if (serverObject.variables) { + each(serverObject.variables, (variable, variableName) => { + let sub = variable.default || (variable.enum ? variable.enum[0] : `{{${variableName}}}`); + url = url.replace(`{${variableName}}`, sub); + }); + } + return url; +}; + +const getSecurity = (apiSpec) => { + let supportedSchemes = apiSpec.security || []; + if (supportedSchemes.length === 0) { + return { + supported: [] + }; + } + + let securitySchemes = get(apiSpec, 'components.securitySchemes', {}); + if (Object.keys(securitySchemes) === 0) { + return { + supported: [] + }; + } + + return { + supported: supportedSchemes.map((scheme) => { + var schemeName = Object.keys(scheme)[0]; + return securitySchemes[schemeName]; + }), + schemes: securitySchemes, + getScheme: (schemeName) => { + return securitySchemes[schemeName]; + } + }; +}; + +const parseOpenApiCollection = (data) => { + const brunoCollection = { + name: '', + uid: uuid(), + version: '1', + items: [], + environments: [] + }; + + return new Promise((resolve, reject) => { + try { + const collectionData = resolveRefs(data); + if (!collectionData) { + reject(new BrunoError('Invalid OpenAPI collection. Failed to resolve refs.')); + return; + } + + // Currently parsing of openapi spec is "do your best", that is + // allows "invalid" openapi spec + + // assumes v3 if not defined. v2 no supported yet + if (collectionData.openapi && !collectionData.openapi.startsWith('3')) { + reject(new BrunoError('Only OpenAPI v3 is supported currently.')); + return; + } + + // TODO what if info.title not defined? + brunoCollection.name = collectionData.info.title; + let servers = collectionData.servers || []; + let baseUrl = servers[0] ? getDefaultUrl(servers[0]) : ''; + 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, + operationObject: operationObject, + global: { + server: baseUrl, + security: securityConfig + } + }; + }); + }) + .reduce((acc, val) => acc.concat(val), []); // flatten + + let [groups, ungroupedRequests] = groupRequestsByTags(allRequests); + let brunoFolders = groups.map((group) => { + return { + uid: uuid(), + name: group.name, + type: 'folder', + items: group.requests.map(transformOpenapiRequestItem) + }; + }); + + let ungroupedItems = ungroupedRequests.map(transformOpenapiRequestItem); + let brunoCollectionItems = brunoFolders.concat(ungroupedItems); + brunoCollection.items = brunoCollectionItems; + resolve(brunoCollection); + } catch (err) { + console.error(err); + reject(new BrunoError('An error occurred while parsing the OpenAPI collection')); + } + }); +}; + +const importCollection = () => { + return new Promise((resolve, reject) => { + fileDialog({ accept: '.json, .yaml, .yml, application/json, application/yaml, application/x-yaml' }) + .then(readFile) + .then(parseOpenApiCollection) + .then(transformItemsInCollection) + .then(hydrateSeqInCollection) + .then(validateSchema) + .then((collection) => resolve(collection)) + .catch((err) => { + console.error(err); + reject(new BrunoError('Import collection failed: ' + err.message)); + }); + }); +}; + +export default importCollection; diff --git a/packages/bruno-app/src/utils/importers/postman-collection.js b/packages/bruno-app/src/utils/importers/postman-collection.js index 7fd36dad..499196bd 100644 --- a/packages/bruno-app/src/utils/importers/postman-collection.js +++ b/packages/bruno-app/src/utils/importers/postman-collection.js @@ -62,6 +62,31 @@ const importPostmanV2CollectionItem = (brunoParent, item) => { } }; + if (i.event) { + i.event.forEach((event) => { + if (event.listen === 'prerequest' && event.script && event.script.exec) { + if (!brunoRequestItem.request.script) { + brunoRequestItem.request.script = {}; + } + if (Array.isArray(event.script.exec[0])) { + brunoRequestItem.request.script.req = event.script.exec[0].map((line) => `// ${line}`).join('\n'); + } else { + brunoRequestItem.request.script.req = `// ${event.script.exec[0]} `; + } + } + if (event.listen === 'test' && event.script && event.script.exec) { + if (!brunoRequestItem.request.tests) { + brunoRequestItem.request.tests = {}; + } + if (Array.isArray(event.script.exec[0])) { + brunoRequestItem.request.tests = event.script.exec[0].map((line) => `// ${line}`).join('\n'); + } else { + brunoRequestItem.request.tests = `// ${event.script.exec[0]} `; + } + } + }); + } + const bodyMode = get(i, 'request.body.mode'); if (bodyMode) { if (bodyMode === 'formdata') { diff --git a/packages/bruno-app/src/utils/network/index.js b/packages/bruno-app/src/utils/network/index.js index 8952e198..ffd66743 100644 --- a/packages/bruno-app/src/utils/network/index.js +++ b/packages/bruno-app/src/utils/network/index.js @@ -8,8 +8,10 @@ export const sendNetworkRequest = async (item, collection, environment, collecti resolve({ state: 'success', data: response.data, + // Note that the Buffer is encoded as a base64 string, because Buffers / TypedArrays are not allowed in the redux store + dataBuffer: response.dataBuffer, headers: Object.entries(response.headers), - size: getResponseSize(response), + size: response.size, status: response.status, statusText: response.statusText, duration: response.duration @@ -31,10 +33,6 @@ const sendHttpRequest = async (item, collection, environment, collectionVariable }); }; -const getResponseSize = (response) => { - return response.headers['content-length'] || Buffer.byteLength(safeStringifyJSON(response.data)) || 0; -}; - export const fetchGqlSchema = async (endpoint, environment, request, collection) => { return new Promise((resolve, reject) => { const { ipcRenderer } = window; @@ -45,6 +43,8 @@ export const fetchGqlSchema = async (endpoint, environment, request, collection) export const cancelNetworkRequest = async (cancelTokenUid) => { return new Promise((resolve, reject) => { + const { ipcRenderer } = window; + ipcRenderer.invoke('cancel-http-request', cancelTokenUid).then(resolve).catch(reject); }); }; diff --git a/packages/bruno-cli/package.json b/packages/bruno-cli/package.json index f36459c7..54fb85fb 100644 --- a/packages/bruno-cli/package.json +++ b/packages/bruno-cli/package.json @@ -1,6 +1,6 @@ { "name": "@usebruno/cli", - "version": "0.14.0", + "version": "0.15.1", "license": "MIT", "main": "src/index.js", "bin": { @@ -24,8 +24,8 @@ "package.json" ], "dependencies": { - "@usebruno/js": "0.8.0", - "@usebruno/lang": "0.8.0", + "@usebruno/js": "0.9.1", + "@usebruno/lang": "0.9.0", "axios": "^1.5.1", "chai": "^4.3.7", "chalk": "^3.0.0", diff --git a/packages/bruno-cli/src/commands/run.js b/packages/bruno-cli/src/commands/run.js index e9b98e9e..43aae38d 100644 --- a/packages/bruno-cli/src/commands/run.js +++ b/packages/bruno-cli/src/commands/run.js @@ -162,9 +162,7 @@ const getCollectionRoot = (dir) => { } const content = fs.readFileSync(collectionRootPath, 'utf8'); - const json = collectionBruToJson(content); - - return json; + return collectionBruToJson(content); }; const builder = async (yargs) => { diff --git a/packages/bruno-cli/src/runner/prepare-request.js b/packages/bruno-cli/src/runner/prepare-request.js index 5568ae31..ace3b310 100644 --- a/packages/bruno-cli/src/runner/prepare-request.js +++ b/packages/bruno-cli/src/runner/prepare-request.js @@ -88,6 +88,13 @@ const prepareRequest = (request, collectionRoot) => { axiosRequest.data = request.body.xml; } + if (request.body.mode === 'sparql') { + if (!contentTypeDefined) { + axiosRequest.headers['content-type'] = 'application/sparql-query'; + } + axiosRequest.data = request.body.sparql; + } + if (request.body.mode === 'formUrlEncoded') { axiosRequest.headers['content-type'] = 'application/x-www-form-urlencoded'; const params = {}; diff --git a/packages/bruno-cli/src/runner/run-single-request.js b/packages/bruno-cli/src/runner/run-single-request.js index d6f3107a..cc0012fc 100644 --- a/packages/bruno-cli/src/runner/run-single-request.js +++ b/packages/bruno-cli/src/runner/run-single-request.js @@ -12,10 +12,10 @@ const { ScriptRuntime, TestRuntime, VarsRuntime, AssertRuntime } = require('@use const { stripExtension } = require('../utils/filesystem'); const { getOptions } = require('../utils/bru'); const https = require('https'); -const { HttpsProxyAgent } = require('https-proxy-agent'); const { HttpProxyAgent } = require('http-proxy-agent'); const { SocksProxyAgent } = require('socks-proxy-agent'); const { makeAxiosInstance } = require('../utils/axios-instance'); +const { shouldUseProxy, PatchedHttpsProxyAgent } = require('../utils/proxy-util'); const runSingleRequest = async function ( filename, @@ -48,7 +48,7 @@ const runSingleRequest = async function ( // run pre-request vars const preRequestVars = get(bruJson, 'request.vars.req'); - if (preRequestVars && preRequestVars.length) { + if (preRequestVars?.length) { const varsRuntime = new VarsRuntime(); varsRuntime.runPreRequestVars( preRequestVars, @@ -65,7 +65,7 @@ const runSingleRequest = async function ( get(collectionRoot, 'request.script.req'), get(bruJson, 'request.script.req') ]).join(os.EOL); - if (requestScriptFile && requestScriptFile.length) { + if (requestScriptFile?.length) { const scriptRuntime = new ScriptRuntime(); const result = await scriptRuntime.runRequestScript( decomment(requestScriptFile), @@ -91,36 +91,56 @@ const runSingleRequest = async function ( if (insecure) { httpsAgentRequestFields['rejectUnauthorized'] = false; } else { - const cacertArray = [options['cacert'], process.env.SSL_CERT_FILE, process.env.NODE_EXTRA_CA_CERTS]; - const cacert = cacertArray.find((el) => el); - if (cacert && cacert.length > 1) { + const caCertArray = [options['cacert'], process.env.SSL_CERT_FILE, process.env.NODE_EXTRA_CA_CERTS]; + const caCert = caCertArray.find((el) => el); + if (caCert && caCert.length > 1) { try { - caCrt = fs.readFileSync(cacert); - httpsAgentRequestFields['ca'] = caCrt; + httpsAgentRequestFields['ca'] = fs.readFileSync(caCert); } catch (err) { - console.log('Error reading CA cert file:' + cacert, err); + console.log('Error reading CA cert file:' + caCert, err); + } + } + } + + const interpolationOptions = { + envVars: envVariables, + collectionVariables, + processEnvVars + }; + + // client certificate config + const clientCertConfig = get(brunoConfig, 'clientCertificates.certs', []); + for (let clientCert of clientCertConfig) { + const domain = interpolateString(clientCert.domain, interpolationOptions); + const certFilePath = interpolateString(clientCert.certFilePath, interpolationOptions); + const keyFilePath = interpolateString(clientCert.keyFilePath, interpolationOptions); + if (domain && certFilePath && keyFilePath) { + const hostRegex = '^https:\\/\\/' + domain.replaceAll('.', '\\.').replaceAll('*', '.*'); + + if (request.url.match(hostRegex)) { + try { + httpsAgentRequestFields['cert'] = fs.readFileSync(certFilePath); + httpsAgentRequestFields['key'] = fs.readFileSync(keyFilePath); + } catch (err) { + console.log('Error reading cert/key file', err); + } + httpsAgentRequestFields['passphrase'] = interpolateString(clientCert.passphrase, interpolationOptions); + break; } } } // set proxy if enabled const proxyEnabled = get(brunoConfig, 'proxy.enabled', false); - if (proxyEnabled) { - let proxyUri; - const interpolationOptions = { - envVars: envVariables, - collectionVariables, - processEnvVars - }; - + const shouldProxy = shouldUseProxy(request.url, get(brunoConfig, 'proxy.bypassProxy', '')); + if (proxyEnabled && shouldProxy) { const proxyProtocol = interpolateString(get(brunoConfig, 'proxy.protocol'), interpolationOptions); const proxyHostname = interpolateString(get(brunoConfig, 'proxy.hostname'), interpolationOptions); const proxyPort = interpolateString(get(brunoConfig, 'proxy.port'), interpolationOptions); const proxyAuthEnabled = get(brunoConfig, 'proxy.auth.enabled', false); const socksEnabled = proxyProtocol.includes('socks'); - interpolateString; - + let proxyUri; if (proxyAuthEnabled) { const proxyAuthUsername = interpolateString(get(brunoConfig, 'proxy.auth.username'), interpolationOptions); const proxyAuthPassword = interpolateString(get(brunoConfig, 'proxy.auth.password'), interpolationOptions); @@ -132,16 +152,13 @@ const runSingleRequest = async function ( if (socksEnabled) { const socksProxyAgent = new SocksProxyAgent(proxyUri); - request.httpsAgent = socksProxyAgent; - request.httpAgent = socksProxyAgent; } else { - request.httpsAgent = new HttpsProxyAgent( + request.httpsAgent = new PatchedHttpsProxyAgent( proxyUri, Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined ); - request.httpAgent = new HttpProxyAgent(proxyUri); } } else if (Object.keys(httpsAgentRequestFields).length > 0) { @@ -167,7 +184,7 @@ const runSingleRequest = async function ( responseTime = response.headers.get('request-duration'); response.headers.delete('request-duration'); } catch (err) { - if (err && err.response) { + if (err?.response) { response = err.response; // Prevents the duration on leaking to the actual result @@ -204,7 +221,7 @@ const runSingleRequest = async function ( // run post-response vars const postResponseVars = get(bruJson, 'request.vars.res'); - if (postResponseVars && postResponseVars.length) { + if (postResponseVars?.length) { const varsRuntime = new VarsRuntime(); varsRuntime.runPostResponseVars( postResponseVars, @@ -222,7 +239,7 @@ const runSingleRequest = async function ( get(collectionRoot, 'request.script.res'), get(bruJson, 'request.script.res') ]).join(os.EOL); - if (responseScriptFile && responseScriptFile.length) { + if (responseScriptFile?.length) { const scriptRuntime = new ScriptRuntime(); const result = await scriptRuntime.runResponseScript( decomment(responseScriptFile), @@ -283,7 +300,7 @@ const runSingleRequest = async function ( testResults = get(result, 'results', []); } - if (testResults && testResults.length) { + if (testResults?.length) { each(testResults, (testResult) => { if (testResult.status === 'pass') { console.log(chalk.green(` ✓ `) + chalk.dim(testResult.description)); diff --git a/packages/bruno-cli/src/utils/axios-instance.js b/packages/bruno-cli/src/utils/axios-instance.js index 286ffc0f..22515648 100644 --- a/packages/bruno-cli/src/utils/axios-instance.js +++ b/packages/bruno-cli/src/utils/axios-instance.js @@ -4,10 +4,10 @@ const axios = require('axios'); * Function that configures axios with timing interceptors * Important to note here that the timings are not completely accurate. * @see https://github.com/axios/axios/issues/695 - * @returns {import('axios').AxiosStatic} + * @returns {axios.AxiosInstance} */ function makeAxiosInstance() { - /** @type {import('axios').AxiosStatic} */ + /** @type {axios.AxiosInstance} */ const instance = axios.create(); instance.interceptors.request.use((config) => { @@ -26,9 +26,7 @@ function makeAxiosInstance() { if (error.response) { const end = Date.now(); const start = error.config.headers['request-start-time']; - if (error.response) { - error.response.headers['request-duration'] = end - start; - } + error.response.headers['request-duration'] = end - start; } return Promise.reject(error); } diff --git a/packages/bruno-cli/src/utils/proxy-util.js b/packages/bruno-cli/src/utils/proxy-util.js new file mode 100644 index 00000000..729e0335 --- /dev/null +++ b/packages/bruno-cli/src/utils/proxy-util.js @@ -0,0 +1,85 @@ +const parseUrl = require('url').parse; +const { isEmpty } = require('lodash'); +const { HttpsProxyAgent } = require('https-proxy-agent'); + +const DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; +/** + * check for proxy bypass, copied form 'proxy-from-env' + */ +const shouldUseProxy = (url, proxyBypass) => { + if (proxyBypass === '*') { + return false; // Never proxy if wildcard is set. + } + + // use proxy if no proxyBypass is set + if (!proxyBypass || typeof proxyBypass !== 'string' || isEmpty(proxyBypass.trim())) { + return true; + } + + const parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; + let proto = parsedUrl.protocol; + let hostname = parsedUrl.host; + let port = parsedUrl.port; + if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { + return false; // Don't proxy URLs without a valid scheme or host. + } + + proto = proto.split(':', 1)[0]; + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, ''); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + + return proxyBypass.split(/[,;\s]/).every(function (dontProxyFor) { + if (!dontProxyFor) { + return true; // Skip zero-length hosts. + } + const parsedProxy = dontProxyFor.match(/^(.+):(\d+)$/); + let parsedProxyHostname = parsedProxy ? parsedProxy[1] : dontProxyFor; + const parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; // Skip if ports don't match. + } + + if (!/^[.*]/.test(parsedProxyHostname)) { + // No wildcards, so stop proxying if there is an exact match. + return hostname !== parsedProxyHostname; + } + + if (parsedProxyHostname.charAt(0) === '*') { + // Remove leading wildcard. + parsedProxyHostname = parsedProxyHostname.slice(1); + } + // Stop proxying if the hostname ends with the no_proxy host. + return !hostname.endsWith(parsedProxyHostname); + }); +}; + +/** + * Patched version of HttpsProxyAgent to get around a bug that ignores + * options like ca and rejectUnauthorized when upgrading the socket to TLS: + * https://github.com/TooTallNate/proxy-agents/issues/194 + */ +class PatchedHttpsProxyAgent extends HttpsProxyAgent { + constructor(proxy, opts) { + super(proxy, opts); + this.constructorOpts = opts; + } + + async connect(req, opts) { + const combinedOpts = { ...this.constructorOpts, ...opts }; + return super.connect(req, combinedOpts); + } +} + +module.exports = { + shouldUseProxy, + PatchedHttpsProxyAgent +}; diff --git a/packages/bruno-electron/package.json b/packages/bruno-electron/package.json index 70a74326..83f6005c 100644 --- a/packages/bruno-electron/package.json +++ b/packages/bruno-electron/package.json @@ -1,5 +1,5 @@ { - "version": "v0.25.0", + "version": "v0.27.2", "name": "bruno", "description": "Opensource API Client for Exploring and Testing APIs", "homepage": "https://www.usebruno.com", @@ -20,14 +20,13 @@ }, "dependencies": { "@aws-sdk/credential-providers": "^3.425.0", - "@usebruno/js": "0.8.0", - "@usebruno/lang": "0.8.0", - "@usebruno/schema": "0.5.0", + "@usebruno/js": "0.9.1", + "@usebruno/lang": "0.9.0", + "@usebruno/schema": "0.6.0", "about-window": "^1.15.2", "aws4-axios": "^3.3.0", "axios": "^1.5.1", "chai": "^4.3.7", - "chai-string": "^1.5.0", "chokidar": "^3.5.3", "decomment": "^0.9.5", "dotenv": "^16.0.3", @@ -42,6 +41,7 @@ "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.2", "is-valid-path": "^0.1.1", + "js-yaml": "^4.1.0", "lodash": "^4.17.21", "mustache": "^4.2.0", "nanoid": "3.3.4", diff --git a/packages/bruno-electron/src/app/menu-template.js b/packages/bruno-electron/src/app/menu-template.js index 6b470772..cc0f1267 100644 --- a/packages/bruno-electron/src/app/menu-template.js +++ b/packages/bruno-electron/src/app/menu-template.js @@ -44,7 +44,7 @@ const template = [ }, { role: 'window', - submenu: [{ role: 'minimize' }, { role: 'close' }] + submenu: [{ role: 'minimize' }, { role: 'close', accelerator: 'CommandOrControl+Shift+Q' }] }, { role: 'help', diff --git a/packages/bruno-electron/src/index.js b/packages/bruno-electron/src/index.js index 2199122d..f7cb3acc 100644 --- a/packages/bruno-electron/src/index.js +++ b/packages/bruno-electron/src/index.js @@ -10,7 +10,7 @@ const registerNetworkIpc = require('./ipc/network'); const registerCollectionsIpc = require('./ipc/collection'); const registerPreferencesIpc = require('./ipc/preferences'); const Watcher = require('./app/watcher'); -const { loadWindowState, saveWindowState } = require('./utils/window'); +const { loadWindowState, saveBounds, saveMaximized } = require('./utils/window'); const lastOpenedCollections = new LastOpenedCollections(); @@ -33,7 +33,7 @@ let watcher; // Prepare the renderer once the app is ready app.on('ready', async () => { - const { x, y, width, height } = loadWindowState(); + const { maximized, x, y, width, height } = loadWindowState(); mainWindow = new BrowserWindow({ x, @@ -55,6 +55,10 @@ app.on('ready', async () => { // autoHideMenuBar: true }); + if (maximized) { + mainWindow.maximize(); + } + const url = isDev ? 'http://localhost:3000' : format({ @@ -66,8 +70,17 @@ app.on('ready', async () => { mainWindow.loadURL(url); watcher = new Watcher(); - mainWindow.on('resize', () => saveWindowState(mainWindow)); - mainWindow.on('move', () => saveWindowState(mainWindow)); + const handleBoundsChange = () => { + if (!mainWindow.isMaximized()) { + saveBounds(mainWindow); + } + }; + + mainWindow.on('resize', handleBoundsChange); + mainWindow.on('move', handleBoundsChange); + + mainWindow.on('maximize', () => saveMaximized(true)); + mainWindow.on('unmaximize', () => saveMaximized(false)); mainWindow.webContents.on('new-window', function (e, url) { e.preventDefault(); @@ -75,7 +88,7 @@ app.on('ready', async () => { }); // register all ipc handlers - registerNetworkIpc(mainWindow, watcher, lastOpenedCollections); + registerNetworkIpc(mainWindow); registerCollectionsIpc(mainWindow, watcher, lastOpenedCollections); registerPreferencesIpc(mainWindow, watcher, lastOpenedCollections); }); diff --git a/packages/bruno-electron/src/ipc/collection.js b/packages/bruno-electron/src/ipc/collection.js index b4acd5eb..ab92d50b 100644 --- a/packages/bruno-electron/src/ipc/collection.js +++ b/packages/bruno-electron/src/ipc/collection.js @@ -32,9 +32,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection // browse directory ipcMain.handle('renderer:browse-directory', async (event, pathname, request) => { try { - const dirPath = await browseDirectory(mainWindow); - - return dirPath; + return await browseDirectory(mainWindow); } catch (error) { return Promise.reject(error); } @@ -67,8 +65,6 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection mainWindow.webContents.send('main:collection-opened', dirPath, uid, brunoConfig); ipcMain.emit('main:collection-opened', mainWindow, dirPath, uid); - - return; } catch (error) { return Promise.reject(error); } @@ -93,8 +89,6 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection collectionPathname, newName }); - - return; } catch (error) { return Promise.reject(error); } @@ -311,7 +305,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection fs.unlinkSync(pathname); } else { - return Promise.reject(error); + return Promise.reject(); } } catch (error) { return Promise.reject(error); diff --git a/packages/bruno-electron/src/ipc/network/awsv4auth-helper.js b/packages/bruno-electron/src/ipc/network/awsv4auth-helper.js index e3c99062..4a2ff5aa 100644 --- a/packages/bruno-electron/src/ipc/network/awsv4auth-helper.js +++ b/packages/bruno-electron/src/ipc/network/awsv4auth-helper.js @@ -5,7 +5,7 @@ function isStrPresent(str) { return str && str !== '' && str !== 'undefined'; } -async function resolveCredentials(request) { +async function resolveAwsV4Credentials(request) { const awsv4 = request.awsv4config; if (isStrPresent(awsv4.profileName)) { try { @@ -52,5 +52,5 @@ function addAwsV4Interceptor(axiosInstance, request) { module.exports = { addAwsV4Interceptor, - resolveCredentials + resolveAwsV4Credentials }; diff --git a/packages/bruno-electron/src/ipc/network/axios-instance.js b/packages/bruno-electron/src/ipc/network/axios-instance.js index f4810bec..22515648 100644 --- a/packages/bruno-electron/src/ipc/network/axios-instance.js +++ b/packages/bruno-electron/src/ipc/network/axios-instance.js @@ -4,10 +4,10 @@ const axios = require('axios'); * Function that configures axios with timing interceptors * Important to note here that the timings are not completely accurate. * @see https://github.com/axios/axios/issues/695 - * @returns {import('axios').AxiosStatic} + * @returns {axios.AxiosInstance} */ function makeAxiosInstance() { - /** @type {import('axios').AxiosStatic} */ + /** @type {axios.AxiosInstance} */ const instance = axios.create(); instance.interceptors.request.use((config) => { diff --git a/packages/bruno-electron/src/ipc/network/index.js b/packages/bruno-electron/src/ipc/network/index.js index 2995e574..8fd08b34 100644 --- a/packages/bruno-electron/src/ipc/network/index.js +++ b/packages/bruno-electron/src/ipc/network/index.js @@ -16,14 +16,14 @@ const { uuid } = require('../../utils/common'); const interpolateVars = require('./interpolate-vars'); const { interpolateString } = require('./interpolate-string'); const { sortFolder, getAllRequestsInFolderRecursively } = require('./helper'); -const { getPreferences } = require('../../store/preferences'); +const { preferencesUtil } = require('../../store/preferences'); const { getProcessEnvVars } = require('../../store/process-env'); const { getBrunoConfig } = require('../../store/bruno-config'); -const { HttpsProxyAgent } = require('https-proxy-agent'); const { HttpProxyAgent } = require('http-proxy-agent'); const { SocksProxyAgent } = require('socks-proxy-agent'); const { makeAxiosInstance } = require('./axios-instance'); -const { addAwsV4Interceptor, resolveCredentials } = require('./awsv4auth-helper'); +const { addAwsV4Interceptor, resolveAwsV4Credentials } = require('./awsv4auth-helper'); +const { shouldUseProxy, PatchedHttpsProxyAgent } = require('../../utils/proxy-util'); // override the default escape function to prevent escaping Mustache.escape = function (value) { @@ -83,7 +83,254 @@ const getSize = (data) => { return 0; }; +const configureRequest = async (collectionUid, request, envVars, collectionVariables, processEnvVars) => { + const httpsAgentRequestFields = {}; + if (!preferencesUtil.shouldVerifyTls()) { + httpsAgentRequestFields['rejectUnauthorized'] = false; + } + + const brunoConfig = getBrunoConfig(collectionUid); + const interpolationOptions = { + envVars, + collectionVariables, + processEnvVars + }; + + // client certificate config + const clientCertConfig = get(brunoConfig, 'clientCertificates.certs', []); + for (let clientCert of clientCertConfig) { + const domain = interpolateString(clientCert.domain, interpolationOptions); + const certFilePath = interpolateString(clientCert.certFilePath, interpolationOptions); + const keyFilePath = interpolateString(clientCert.keyFilePath, interpolationOptions); + if (domain && certFilePath && keyFilePath) { + const hostRegex = '^https:\\/\\/' + domain.replaceAll('.', '\\.').replaceAll('*', '.*'); + + if (request.url.match(hostRegex)) { + try { + httpsAgentRequestFields['cert'] = fs.readFileSync(certFilePath); + httpsAgentRequestFields['key'] = fs.readFileSync(keyFilePath); + } catch (err) { + console.log('Error reading cert/key file', err); + } + httpsAgentRequestFields['passphrase'] = interpolateString(clientCert.passphrase, interpolationOptions); + break; + } + } + } + + // proxy configuration + let proxyConfig = get(brunoConfig, 'proxy', {}); + let proxyEnabled = get(proxyConfig, 'enabled', false); + if (proxyEnabled === 'global') { + proxyConfig = preferencesUtil.getGlobalProxyConfig(); + proxyEnabled = get(proxyConfig, 'enabled', false); + } + const shouldProxy = shouldUseProxy(request.url, get(proxyConfig, 'bypassProxy', '')); + if (proxyEnabled === true && shouldProxy) { + const proxyProtocol = interpolateString(get(proxyConfig, 'protocol'), interpolationOptions); + const proxyHostname = interpolateString(get(proxyConfig, 'hostname'), interpolationOptions); + const proxyPort = interpolateString(get(proxyConfig, 'port'), interpolationOptions); + const proxyAuthEnabled = get(proxyConfig, 'auth.enabled', false); + const socksEnabled = proxyProtocol.includes('socks'); + + let proxyUri; + if (proxyAuthEnabled) { + const proxyAuthUsername = interpolateString(get(proxyConfig, 'auth.username'), interpolationOptions); + const proxyAuthPassword = interpolateString(get(proxyConfig, 'auth.password'), interpolationOptions); + + proxyUri = `${proxyProtocol}://${proxyAuthUsername}:${proxyAuthPassword}@${proxyHostname}:${proxyPort}`; + } else { + proxyUri = `${proxyProtocol}://${proxyHostname}:${proxyPort}`; + } + + if (socksEnabled) { + const socksProxyAgent = new SocksProxyAgent(proxyUri); + request.httpsAgent = socksProxyAgent; + request.httpAgent = socksProxyAgent; + } else { + request.httpsAgent = new PatchedHttpsProxyAgent( + proxyUri, + Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined + ); + request.httpAgent = new HttpProxyAgent(proxyUri); + } + } else if (Object.keys(httpsAgentRequestFields).length > 0) { + request.httpsAgent = new https.Agent({ + ...httpsAgentRequestFields + }); + } + + const axiosInstance = makeAxiosInstance(); + + if (request.awsv4config) { + request.awsv4config = await resolveAwsV4Credentials(request); + addAwsV4Interceptor(axiosInstance, request); + delete request.awsv4config; + } + + request.timeout = preferencesUtil.getRequestTimeout(); + + return axiosInstance; +}; + +const parseDataFromResponse = (response) => { + const dataBuffer = Buffer.from(response.data); + // Parse the charset from content type: https://stackoverflow.com/a/33192813 + const charset = /charset=([^()<>@,;:\"/[\]?.=\s]*)/i.exec(response.headers['Content-Type'] || ''); + // Overwrite the original data for backwards compatability + let data = dataBuffer.toString(charset || 'utf-8'); + // Try to parse response to JSON, this can quitly fail + try { + data = JSON.parse(response.data); + } catch {} + + return { data, dataBuffer }; +}; + const registerNetworkIpc = (mainWindow) => { + const onConsoleLog = (type, args) => { + console[type](...args); + + mainWindow.webContents.send('main:console-log', { + type, + args + }); + }; + + const runPreRequest = async ( + request, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig + ) => { + // run pre-request vars + const preRequestVars = get(request, 'vars.req', []); + if (preRequestVars?.length) { + const varsRuntime = new VarsRuntime(); + const result = varsRuntime.runPreRequestVars( + preRequestVars, + request, + envVars, + collectionVariables, + collectionPath, + processEnvVars + ); + + if (result) { + mainWindow.webContents.send('main:script-environment-update', { + envVariables: result.envVariables, + collectionVariables: result.collectionVariables, + requestUid, + collectionUid + }); + } + } + + // run pre-request script + let scriptResult; + const requestScript = compact([get(collectionRoot, 'request.script.req'), get(request, 'script.req')]).join(os.EOL); + if (requestScript?.length) { + const scriptRuntime = new ScriptRuntime(); + scriptResult = await scriptRuntime.runRequestScript( + decomment(requestScript), + request, + envVars, + collectionVariables, + collectionPath, + onConsoleLog, + processEnvVars, + scriptingConfig + ); + + mainWindow.webContents.send('main:script-environment-update', { + envVariables: scriptResult.envVariables, + collectionVariables: scriptResult.collectionVariables, + requestUid, + collectionUid + }); + } + + // interpolate variables inside request + interpolateVars(request, envVars, collectionVariables, processEnvVars); + + // stringify the request url encoded params + if (request.headers['content-type'] === 'application/x-www-form-urlencoded') { + request.data = qs.stringify(request.data); + } + + return scriptResult; + }; + + const runPostResponse = async ( + request, + response, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig + ) => { + // run post-response vars + const postResponseVars = get(request, 'vars.res', []); + if (postResponseVars?.length) { + const varsRuntime = new VarsRuntime(); + const result = varsRuntime.runPostResponseVars( + postResponseVars, + request, + response, + envVars, + collectionVariables, + collectionPath, + processEnvVars + ); + + if (result) { + mainWindow.webContents.send('main:script-environment-update', { + envVariables: result.envVariables, + collectionVariables: result.collectionVariables, + requestUid, + collectionUid + }); + } + } + + // run post-response script + let scriptResult; + const responseScript = compact([get(collectionRoot, 'request.script.res'), get(request, 'script.res')]).join( + os.EOL + ); + if (responseScript?.length) { + const scriptRuntime = new ScriptRuntime(); + scriptResult = await scriptRuntime.runResponseScript( + decomment(responseScript), + request, + response, + envVars, + collectionVariables, + collectionPath, + onConsoleLog, + processEnvVars, + scriptingConfig + ); + + mainWindow.webContents.send('main:script-environment-update', { + envVariables: scriptResult.envVariables, + collectionVariables: scriptResult.collectionVariables, + requestUid, + collectionUid + }); + } + return scriptResult; + }; + // handler for sending http request ipcMain.handle('send-http-request', async (event, item, collection, environment, collectionVariables) => { const collectionUid = collection.uid; @@ -91,15 +338,6 @@ const registerNetworkIpc = (mainWindow) => { const cancelTokenUid = uuid(); const requestUid = uuid(); - const onConsoleLog = (type, args) => { - console[type](...args); - - mainWindow.webContents.send('main:console-log', { - type, - args - }); - }; - mainWindow.webContents.send('main:run-request-event', { type: 'request-queued', requestUid, @@ -117,79 +355,21 @@ const registerNetworkIpc = (mainWindow) => { const scriptingConfig = get(brunoConfig, 'scripts', {}); try { - // make axios work in node using form data - // reference: https://github.com/axios/axios/issues/1006#issuecomment-320165427 - if (request.headers && request.headers['content-type'] === 'multipart/form-data') { - const form = new FormData(); - forOwn(request.data, (value, key) => { - form.append(key, value); - }); - extend(request.headers, form.getHeaders()); - request.data = form; - } - const cancelToken = axios.CancelToken.source(); request.cancelToken = cancelToken.token; saveCancelToken(cancelTokenUid, cancelToken); - // run pre-request vars - const preRequestVars = get(request, 'vars.req', []); - if (preRequestVars && preRequestVars.length) { - const varsRuntime = new VarsRuntime(); - const result = varsRuntime.runPreRequestVars( - preRequestVars, - request, - envVars, - collectionVariables, - collectionPath, - processEnvVars - ); - - if (result) { - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - requestUid, - collectionUid - }); - } - } - - const preferences = getPreferences(); - const timeout = get(preferences, 'request.timeout', 0); - request.timeout = timeout; - - // run pre-request script - const requestScript = compact([get(collectionRoot, 'request.script.req'), get(request, 'script.req')]).join( - os.EOL + await runPreRequest( + request, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig ); - if (requestScript && requestScript.length) { - const scriptRuntime = new ScriptRuntime(); - const result = await scriptRuntime.runRequestScript( - decomment(requestScript), - request, - envVars, - collectionVariables, - collectionPath, - onConsoleLog, - processEnvVars, - scriptingConfig - ); - - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - requestUid, - collectionUid - }); - } - - interpolateVars(request, envVars, collectionVariables, processEnvVars); - - // stringify the request url encoded params - if (request.headers['content-type'] === 'application/x-www-form-urlencoded') { - request.data = qs.stringify(request.data); - } // todo: // i have no clue why electron can't send the request object @@ -209,143 +389,62 @@ const registerNetworkIpc = (mainWindow) => { cancelTokenUid }); - const sslVerification = get(preferences, 'request.sslVerification', true); - const httpsAgentRequestFields = {}; - if (!sslVerification) { - httpsAgentRequestFields['rejectUnauthorized'] = false; - } - - const brunoConfig = getBrunoConfig(collectionUid); - const interpolationOptions = { + const axiosInstance = await configureRequest( + collectionUid, + request, envVars, collectionVariables, processEnvVars - }; - - // client certificate config - const clientCertConfig = get(brunoConfig, 'clientCertificates.certs', []); - - for (clientCert of clientCertConfig) { - const domain = interpolateString(clientCert.domain, interpolationOptions); - const certFilePath = interpolateString(clientCert.certFilePath, interpolationOptions); - const keyFilePath = interpolateString(clientCert.keyFilePath, interpolationOptions); - if (domain && certFilePath && keyFilePath) { - const hostRegex = '^https:\\/\\/' + domain.replaceAll('.', '\\.').replaceAll('*', '.*'); - - if (request.url.match(hostRegex)) { - try { - httpsAgentRequestFields['cert'] = fs.readFileSync(certFilePath); - httpsAgentRequestFields['key'] = fs.readFileSync(keyFilePath); - } catch (err) { - console.log('Error reading cert/key file', err); - } - httpsAgentRequestFields['passphrase'] = interpolateString(clientCert.passphrase, interpolationOptions); - break; - } - } - } - - // proxy configuration - const proxyEnabled = get(brunoConfig, 'proxy.enabled', false); - if (proxyEnabled) { - let proxyUri; - - const proxyProtocol = interpolateString(get(brunoConfig, 'proxy.protocol'), interpolationOptions); - const proxyHostname = interpolateString(get(brunoConfig, 'proxy.hostname'), interpolationOptions); - const proxyPort = interpolateString(get(brunoConfig, 'proxy.port'), interpolationOptions); - const proxyAuthEnabled = get(brunoConfig, 'proxy.auth.enabled', false); - const socksEnabled = proxyProtocol.includes('socks'); - - if (proxyAuthEnabled) { - const proxyAuthUsername = interpolateString(get(brunoConfig, 'proxy.auth.username'), interpolationOptions); - const proxyAuthPassword = interpolateString(get(brunoConfig, 'proxy.auth.password'), interpolationOptions); - - proxyUri = `${proxyProtocol}://${proxyAuthUsername}:${proxyAuthPassword}@${proxyHostname}:${proxyPort}`; - } else { - proxyUri = `${proxyProtocol}://${proxyHostname}:${proxyPort}`; - } - - if (socksEnabled) { - const socksProxyAgent = new SocksProxyAgent(proxyUri); - - request.httpsAgent = socksProxyAgent; - - request.httpAgent = socksProxyAgent; - } else { - request.httpsAgent = new HttpsProxyAgent( - proxyUri, - Object.keys(httpsAgentRequestFields).length > 0 ? { ...httpsAgentRequestFields } : undefined - ); - - request.httpAgent = new HttpProxyAgent(proxyUri); - } - } else if (Object.keys(httpsAgentRequestFields).length > 0) { - request.httpsAgent = new https.Agent({ - ...httpsAgentRequestFields - }); - } - - const axiosInstance = makeAxiosInstance(); - - if (request.awsv4config) { - request.awsv4config = await resolveCredentials(request); - addAwsV4Interceptor(axiosInstance, request); - delete request.awsv4config; - } - - /** @type {import('axios').AxiosResponse} */ - const response = await axiosInstance(request); - - // run post-response vars - const postResponseVars = get(request, 'vars.res', []); - if (postResponseVars && postResponseVars.length) { - const varsRuntime = new VarsRuntime(); - const result = varsRuntime.runPostResponseVars( - postResponseVars, - request, - response, - envVars, - collectionVariables, - collectionPath, - processEnvVars - ); - - if (result) { - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - requestUid, - collectionUid - }); - } - } - - // run post-response script - const responseScript = compact([get(collectionRoot, 'request.script.res'), get(request, 'script.res')]).join( - os.EOL ); - if (responseScript && responseScript.length) { - const scriptRuntime = new ScriptRuntime(); - const result = await scriptRuntime.runResponseScript( - decomment(responseScript), - request, - response, - envVars, - collectionVariables, - collectionPath, - onConsoleLog, - processEnvVars, - scriptingConfig - ); - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - requestUid, - collectionUid - }); + let response, responseTime; + try { + /** @type {import('axios').AxiosResponse} */ + response = await axiosInstance(request); + + // Prevents the duration on leaking to the actual result + responseTime = response.headers.get('request-duration'); + response.headers.delete('request-duration'); + } catch (error) { + deleteCancelToken(cancelTokenUid); + + // if it's a cancel request, don't continue + if (axios.isCancel(error)) { + let error = new Error('Request cancelled'); + error.isCancel = true; + return Promise.reject(error); + } + + if (error?.response) { + response = error.response; + + // Prevents the duration on leaking to the actual result + responseTime = response.headers.get('request-duration'); + response.headers.delete('request-duration'); + } else { + // if it's not a network error, don't continue + return Promise.reject(error); + } } + // Continue with the rest of the request lifecycle - post response vars, script, assertions, tests + + const { data, dataBuffer } = parseDataFromResponse(response); + response.data = data; + + await runPostResponse( + request, + response, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig + ); + // run assertions const assertions = get(request, 'assertions'); if (assertions) { @@ -403,100 +502,18 @@ const registerNetworkIpc = (mainWindow) => { }); } - deleteCancelToken(cancelTokenUid); - // Prevents the duration on leaking to the actual result - const requestDuration = response.headers.get('request-duration'); - response.headers.delete('request-duration'); - return { status: response.status, statusText: response.statusText, headers: response.headers, data: response.data, - duration: requestDuration + dataBuffer: dataBuffer.toString('base64'), + size: Buffer.byteLength(dataBuffer), + duration: responseTime ?? 0 }; } catch (error) { - // todo: better error handling - // need to convey the error to the UI - // and need not be always a network error deleteCancelToken(cancelTokenUid); - if (axios.isCancel(error)) { - let error = new Error('Request cancelled'); - error.isCancel = true; - return Promise.reject(error); - } - - if (error && error.response) { - // run assertions - const assertions = get(request, 'assertions'); - if (assertions) { - const assertRuntime = new AssertRuntime(); - const results = assertRuntime.runAssertions( - assertions, - request, - error.response, - envVars, - collectionVariables, - collectionPath - ); - - mainWindow.webContents.send('main:run-request-event', { - type: 'assertion-results', - results: results, - itemUid: item.uid, - requestUid, - collectionUid - }); - } - - // run tests - const testFile = compact([ - get(collectionRoot, 'request.tests'), - item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests') - ]).join(os.EOL); - if (typeof testFile === 'string') { - const testRuntime = new TestRuntime(); - const testResults = await testRuntime.runTests( - decomment(testFile), - request, - error.response, - envVars, - collectionVariables, - collectionPath, - onConsoleLog, - processEnvVars, - scriptingConfig - ); - - mainWindow.webContents.send('main:run-request-event', { - type: 'test-results', - results: testResults.results, - itemUid: item.uid, - requestUid, - collectionUid - }); - - mainWindow.webContents.send('main:script-environment-update', { - envVariables: testResults.envVariables, - collectionVariables: testResults.collectionVariables, - requestUid, - collectionUid - }); - } - - // Prevents the duration from leaking to the actual result - const requestDuration = error.response.headers.get('request-duration'); - error.response.headers.delete('request-duration'); - return { - status: error.response.status, - statusText: error.response.statusText, - headers: error.response.headers, - data: error.response.data, - duration: requestDuration ?? 0 - }; - } - return Promise.reject(error); } }); @@ -519,21 +536,55 @@ const registerNetworkIpc = (mainWindow) => { const collectionRoot = get(collection, 'root', {}); const preparedRequest = prepareGqlIntrospectionRequest(endpoint, envVars, request, collectionRoot); - const preferences = getPreferences(); - const timeout = get(preferences, 'request.timeout', 0); - request.timeout = timeout; - const sslVerification = get(preferences, 'request.sslVerification', true); + request.timeout = preferencesUtil.getRequestTimeout(); - if (!sslVerification) { + if (!preferencesUtil.shouldVerifyTls()) { request.httpsAgent = new https.Agent({ rejectUnauthorized: false }); } - const processEnvVars = getProcessEnvVars(collection.uid); - interpolateVars(preparedRequest, envVars, collection.collectionVariables, processEnvVars); + const requestUid = uuid(); + const collectionPath = collection.pathname; + const collectionUid = collection.uid; + const collectionVariables = collection.collectionVariables; + const processEnvVars = getProcessEnvVars(collectionUid); + const brunoConfig = getBrunoConfig(collection.uid); + const scriptingConfig = get(brunoConfig, 'scripts', {}); - const response = await axios(preparedRequest); + await runPreRequest( + request, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig + ); + + const axiosInstance = await configureRequest( + collection.uid, + preparedRequest, + envVars, + collection.collectionVariables, + processEnvVars + ); + const response = await axiosInstance(preparedRequest); + + await runPostResponse( + request, + response, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig + ); return { status: response.status, @@ -565,15 +616,6 @@ const registerNetworkIpc = (mainWindow) => { const scriptingConfig = get(brunoConfig, 'scripts', {}); const collectionRoot = get(collection, 'root', {}); - const onConsoleLog = (type, args) => { - console[type](...args); - - mainWindow.webContents.send('main:console-log', { - type, - args - }); - }; - if (!folder) { folder = collection; } @@ -626,77 +668,26 @@ const registerNetworkIpc = (mainWindow) => { const _request = item.draft ? item.draft.request : item.request; const request = prepareRequest(_request, collectionRoot); + const requestUid = uuid(); const processEnvVars = getProcessEnvVars(collectionUid); try { - // make axios work in node using form data - // reference: https://github.com/axios/axios/issues/1006#issuecomment-320165427 - if (request.headers && request.headers['content-type'] === 'multipart/form-data') { - const form = new FormData(); - forOwn(request.data, (value, key) => { - form.append(key, value); - }); - extend(request.headers, form.getHeaders()); - request.data = form; - } - - // run pre-request vars - const preRequestVars = get(request, 'vars.req', []); - if (preRequestVars && preRequestVars.length) { - const varsRuntime = new VarsRuntime(); - const result = varsRuntime.runPreRequestVars( - preRequestVars, - request, - envVars, - collectionVariables, - collectionPath - ); - - if (result) { - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - collectionUid - }); - } - } - - const preferences = getPreferences(); - const timeout = get(preferences, 'request.timeout', 0); - request.timeout = timeout; - const sslVerification = get(preferences, 'request.sslVerification', true); - - // run pre-request script - const requestScript = compact([get(collectionRoot, 'request.script.req'), get(request, 'script.req')]).join( - os.EOL + const preRequestScriptResult = await runPreRequest( + request, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig ); - if (requestScript && requestScript.length) { - const scriptRuntime = new ScriptRuntime(); - const result = await scriptRuntime.runRequestScript( - decomment(requestScript), - request, - envVars, - collectionVariables, - collectionPath, - onConsoleLog, - processEnvVars, - scriptingConfig - ); - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - collectionUid - }); - - if (result?.nextRequestName) { - nextRequestName = result.nextRequestName; - } + if (preRequestScriptResult?.nextRequestName) { + nextRequestName = preRequestScriptResult.nextRequestName; } - // interpolate variables inside request - interpolateVars(request, envVars, collectionVariables, processEnvVars); - // todo: // i have no clue why electron can't send the request object // without safeParseJSON(safeStringifyJSON(request.data)) @@ -711,113 +702,81 @@ const registerNetworkIpc = (mainWindow) => { ...eventData }); - // proxy configuration - const brunoConfig = getBrunoConfig(collectionUid); - const proxyEnabled = get(brunoConfig, 'proxy.enabled', false); - if (proxyEnabled) { - let proxyUri; - const interpolationOptions = { - envVars, - collectionVariables, - processEnvVars - }; + const axiosInstance = await configureRequest( + collectionUid, + request, + envVars, + collectionVariables, + processEnvVars + ); - const proxyProtocol = interpolateString(get(brunoConfig, 'proxy.protocol'), interpolationOptions); - const proxyHostname = interpolateString(get(brunoConfig, 'proxy.hostname'), interpolationOptions); - const proxyPort = interpolateString(get(brunoConfig, 'proxy.port'), interpolationOptions); - const proxyAuthEnabled = get(brunoConfig, 'proxy.auth.enabled', false); - const socksEnabled = proxyProtocol.includes('socks'); - - if (proxyAuthEnabled) { - const proxyAuthUsername = interpolateString( - get(brunoConfig, 'proxy.auth.username'), - interpolationOptions - ); - - const proxyAuthPassword = interpolateString( - get(brunoConfig, 'proxy.auth.password'), - interpolationOptions - ); - - proxyUri = `${proxyProtocol}://${proxyAuthUsername}:${proxyAuthPassword}@${proxyHostname}:${proxyPort}`; - } else { - proxyUri = `${proxyProtocol}://${proxyHostname}:${proxyPort}`; - } - - if (socksEnabled) { - const socksProxyAgent = new SocksProxyAgent(proxyUri); - - request.httpsAgent = socksProxyAgent; - request.httpAgent = socksProxyAgent; - } else { - request.httpsAgent = new HttpsProxyAgent(proxyUri, { - rejectUnauthorized: sslVerification - }); - - request.httpAgent = new HttpProxyAgent(proxyUri); - } - } else if (!sslVerification) { - request.httpsAgent = new https.Agent({ - rejectUnauthorized: false - }); - } - - // send request timeStart = Date.now(); - const response = await axios(request); - timeEnd = Date.now(); + let response; + try { + /** @type {import('axios').AxiosResponse} */ + response = await axiosInstance(request); + timeEnd = Date.now(); - // run post-response vars - const postResponseVars = get(request, 'vars.res', []); - if (postResponseVars && postResponseVars.length) { - const varsRuntime = new VarsRuntime(); - const result = varsRuntime.runPostResponseVars( - postResponseVars, - request, - response, - envVars, - collectionVariables, - collectionPath, - processEnvVars - ); + const { data, dataBuffer } = parseDataFromResponse(response); + response.data = data; - if (result) { - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - collectionUid + mainWindow.webContents.send('main:run-folder-event', { + type: 'response-received', + responseReceived: { + status: response.status, + statusText: response.statusText, + headers: Object.entries(response.headers), + duration: timeEnd - timeStart, + dataBuffer: dataBuffer.toString('base64'), + size: Buffer.byteLength(dataBuffer), + data: response.data + }, + ...eventData + }); + } catch (error) { + if (error?.response) { + const { data, dataBuffer } = parseDataFromResponse(error.response); + error.response.data = data; + + timeEnd = Date.now(); + response = { + status: error.response.status, + statusText: error.response.statusText, + headers: Object.entries(error.response.headers), + duration: timeEnd - timeStart, + dataBuffer: dataBuffer.toString('base64'), + size: Buffer.byteLength(dataBuffer), + data: error.response.data + }; + + // if we get a response from the server, we consider it as a success + mainWindow.webContents.send('main:run-folder-event', { + type: 'response-received', + error: error ? error.message : 'An error occurred while running the request', + responseReceived: response, + ...eventData }); + } else { + // if it's not a network error, don't continue + throw Promise.reject(error); } } - // run response script - const responseScript = compact([ - get(collectionRoot, 'request.script.res'), - get(request, 'script.res') - ]).join(os.EOL); - if (responseScript && responseScript.length) { - const scriptRuntime = new ScriptRuntime(); - const result = await scriptRuntime.runResponseScript( - decomment(responseScript), - request, - response, - envVars, - collectionVariables, - collectionPath, - onConsoleLog, - processEnvVars, - scriptingConfig - ); + const postRequestScriptResult = await runPostResponse( + request, + response, + requestUid, + envVars, + collectionPath, + collectionRoot, + collectionUid, + collectionVariables, + processEnvVars, + scriptingConfig + ); - mainWindow.webContents.send('main:script-environment-update', { - envVariables: result.envVariables, - collectionVariables: result.collectionVariables, - collectionUid - }); - - if (result?.nextRequestName) { - nextRequestName = result.nextRequestName; - } + if (postRequestScriptResult?.nextRequestName) { + nextRequestName = postRequestScriptResult.nextRequestName; } // run assertions @@ -872,105 +831,11 @@ const registerNetworkIpc = (mainWindow) => { collectionUid }); } - - mainWindow.webContents.send('main:run-folder-event', { - type: 'response-received', - ...eventData, - responseReceived: { - status: response.status, - statusText: response.statusText, - headers: Object.entries(response.headers), - duration: timeEnd - timeStart, - size: response.headers['content-length'] || getSize(response.data), - data: response.data - } - }); } catch (error) { - let responseReceived = {}; - let duration = 0; - - if (timeStart && timeEnd) { - duration = timeEnd - timeStart; - } - - if (error && error.response) { - responseReceived = { - status: error.response.status, - statusText: error.response.statusText, - headers: Object.entries(error.response.headers), - duration: duration, - size: error.response.headers['content-length'] || getSize(error.response.data), - data: error.response.data - }; - - // run assertions - const assertions = get(item, 'request.assertions'); - if (assertions) { - const assertRuntime = new AssertRuntime(); - const results = assertRuntime.runAssertions( - assertions, - request, - error.response, - envVars, - collectionVariables, - collectionPath - ); - - mainWindow.webContents.send('main:run-folder-event', { - type: 'assertion-results', - assertionResults: results, - itemUid: item.uid, - collectionUid - }); - } - - // run tests - const testFile = compact([ - get(collectionRoot, 'request.tests'), - item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests') - ]).join(os.EOL); - if (typeof testFile === 'string') { - const testRuntime = new TestRuntime(); - const testResults = await testRuntime.runTests( - decomment(testFile), - request, - error.response, - envVars, - collectionVariables, - collectionPath, - onConsoleLog, - processEnvVars, - scriptingConfig - ); - - mainWindow.webContents.send('main:run-folder-event', { - type: 'test-results', - testResults: testResults.results, - ...eventData - }); - - mainWindow.webContents.send('main:script-environment-update', { - envVariables: testResults.envVariables, - collectionVariables: testResults.collectionVariables, - collectionUid - }); - } - - // if we get a response from the server, we consider it as a success - mainWindow.webContents.send('main:run-folder-event', { - type: 'response-received', - error: error ? error.message : 'An error occurred while running the request', - responseReceived: responseReceived, - ...eventData - }); - - continue; - } - mainWindow.webContents.send('main:run-folder-event', { type: 'error', error: error ? error.message : 'An error occurred while running the request', - responseReceived: responseReceived, + responseReceived: {}, ...eventData }); } diff --git a/packages/bruno-electron/src/ipc/network/prepare-request.js b/packages/bruno-electron/src/ipc/network/prepare-request.js index 3beab80f..6e3f123c 100644 --- a/packages/bruno-electron/src/ipc/network/prepare-request.js +++ b/packages/bruno-electron/src/ipc/network/prepare-request.js @@ -84,7 +84,8 @@ const prepareRequest = (request, collectionRoot) => { let axiosRequest = { method: request.method, url: request.url, - headers: headers + headers: headers, + responseType: 'arraybuffer' }; axiosRequest = setAuthHeaders(axiosRequest, request, collectionRoot); @@ -136,6 +137,15 @@ const prepareRequest = (request, collectionRoot) => { each(enabledParams, (p) => (params[p.name] = p.value)); axiosRequest.headers['content-type'] = 'multipart/form-data'; axiosRequest.data = params; + + // make axios work in node using form data + // reference: https://github.com/axios/axios/issues/1006#issuecomment-320165427 + const form = new FormData(); + forOwn(axiosRequest.data, (value, key) => { + form.append(key, value); + }); + extend(axiosRequest.headers, form.getHeaders()); + axiosRequest.data = form; } if (request.body.mode === 'graphql') { diff --git a/packages/bruno-electron/src/ipc/preferences.js b/packages/bruno-electron/src/ipc/preferences.js index f93ec5e6..679c74e3 100644 --- a/packages/bruno-electron/src/ipc/preferences.js +++ b/packages/bruno-electron/src/ipc/preferences.js @@ -2,7 +2,7 @@ const { ipcMain } = require('electron'); const { getPreferences, savePreferences } = require('../store/preferences'); const { isDirectory } = require('../utils/filesystem'); const { openCollection } = require('../app/collections'); - +``; const registerPreferencesIpc = (mainWindow, watcher, lastOpenedCollections) => { ipcMain.handle('renderer:ready', async (event) => { // load preferences @@ -15,7 +15,7 @@ const registerPreferencesIpc = (mainWindow, watcher, lastOpenedCollections) => { if (lastOpened && lastOpened.length) { for (let collectionPath of lastOpened) { if (isDirectory(collectionPath)) { - openCollection(mainWindow, watcher, collectionPath, { + await openCollection(mainWindow, watcher, collectionPath, { dontSendDisplayErrors: true }); } diff --git a/packages/bruno-electron/src/store/preferences.js b/packages/bruno-electron/src/store/preferences.js index 0a94f4cb..56db5d9a 100644 --- a/packages/bruno-electron/src/store/preferences.js +++ b/packages/bruno-electron/src/store/preferences.js @@ -1,5 +1,12 @@ const Yup = require('yup'); const Store = require('electron-store'); +const { get } = require('lodash'); + +/** + * The preferences are stored in the electron store 'preferences.json'. + * The electron process uses this module to get the preferences. + * + */ const defaultPreferences = { request: { @@ -8,6 +15,18 @@ const defaultPreferences = { }, font: { codeFont: 'default' + }, + proxy: { + enabled: false, + protocol: 'http', + hostname: '', + port: null, + auth: { + enabled: false, + username: '', + password: '' + }, + bypassProxy: '' } }; @@ -18,6 +37,18 @@ const preferencesSchema = Yup.object().shape({ }), font: Yup.object().shape({ codeFont: Yup.string().nullable() + }), + proxy: Yup.object({ + enabled: Yup.boolean(), + protocol: Yup.string().oneOf(['http', 'https', 'socks4', 'socks5']), + hostname: Yup.string().max(1024), + port: Yup.number().min(1).max(65535).nullable(), + auth: Yup.object({ + enabled: Yup.boolean(), + username: Yup.string().max(1024), + password: Yup.string().max(1024) + }).optional(), + bypassProxy: Yup.string().optional().max(1024) }) }); @@ -61,7 +92,20 @@ const savePreferences = async (newPreferences) => { }); }; +const preferencesUtil = { + shouldVerifyTls: () => { + return get(getPreferences(), 'request.sslVerification', true); + }, + getRequestTimeout: () => { + return get(getPreferences(), 'request.timeout', 0); + }, + getGlobalProxyConfig: () => { + return get(getPreferences(), 'proxy', {}); + } +}; + module.exports = { getPreferences, - savePreferences + savePreferences, + preferencesUtil }; diff --git a/packages/bruno-electron/src/store/window-state.js b/packages/bruno-electron/src/store/window-state.js index 90bf7b8c..425aef87 100644 --- a/packages/bruno-electron/src/store/window-state.js +++ b/packages/bruno-electron/src/store/window-state.js @@ -3,6 +3,8 @@ const Store = require('electron-store'); const DEFAULT_WINDOW_WIDTH = 1280; const DEFAULT_WINDOW_HEIGHT = 768; +const DEFAULT_MAXIMIZED = false; + class WindowStateStore { constructor() { this.store = new Store({ @@ -25,6 +27,14 @@ class WindowStateStore { setBounds(bounds) { this.store.set('window-bounds', bounds); } + + getMaximized() { + return this.store.get('maximized') || DEFAULT_MAXIMIZED; + } + + setMaximized(isMaximized) { + this.store.set('maximized', isMaximized); + } } module.exports = WindowStateStore; diff --git a/packages/bruno-electron/src/utils/proxy-util.js b/packages/bruno-electron/src/utils/proxy-util.js new file mode 100644 index 00000000..ef64d37a --- /dev/null +++ b/packages/bruno-electron/src/utils/proxy-util.js @@ -0,0 +1,85 @@ +const parseUrl = require('url').parse; +const { isEmpty } = require('lodash'); +const { HttpsProxyAgent } = require('https-proxy-agent'); + +const DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; +/** + * check for proxy bypass, copied form 'proxy-from-env' + */ +const shouldUseProxy = (url, proxyBypass) => { + if (proxyBypass === '*') { + return false; // Never proxy if wildcard is set. + } + + // use proxy if no proxyBypass is set + if (!proxyBypass || typeof proxyBypass !== 'string' || isEmpty(proxyBypass.trim())) { + return true; + } + + const parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; + let proto = parsedUrl.protocol; + let hostname = parsedUrl.host; + let port = parsedUrl.port; + if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { + return false; // Don't proxy URLs without a valid scheme or host. + } + + proto = proto.split(':', 1)[0]; + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, ''); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + + return proxyBypass.split(/[,;\s]/).every(function (dontProxyFor) { + if (!dontProxyFor) { + return true; // Skip zero-length hosts. + } + const parsedProxy = dontProxyFor.match(/^(.+):(\d+)$/); + let parsedProxyHostname = parsedProxy ? parsedProxy[1] : dontProxyFor; + const parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; // Skip if ports don't match. + } + + if (!/^[.*]/.test(parsedProxyHostname)) { + // No wildcards, so stop proxying if there is an exact match. + return hostname !== parsedProxyHostname; + } + + if (parsedProxyHostname.charAt(0) === '*') { + // Remove leading wildcard. + parsedProxyHostname = parsedProxyHostname.slice(1); + } + // Stop proxying if the hostname ends with the no_proxy host. + return !hostname.endsWith(parsedProxyHostname); + }); +}; + +/** + * Patched version of HttpsProxyAgent to get around a bug that ignores options + * such as ca and rejectUnauthorized when upgrading the proxied socket to TLS: + * https://github.com/TooTallNate/proxy-agents/issues/194 + */ +class PatchedHttpsProxyAgent extends HttpsProxyAgent { + constructor(proxy, opts) { + super(proxy, opts); + this.constructorOpts = opts; + } + + async connect(req, opts) { + const combinedOpts = { ...this.constructorOpts, ...opts }; + return super.connect(req, combinedOpts); + } +} + +module.exports = { + shouldUseProxy, + PatchedHttpsProxyAgent +}; diff --git a/packages/bruno-electron/src/utils/window.js b/packages/bruno-electron/src/utils/window.js index d824141d..949a2aaa 100644 --- a/packages/bruno-electron/src/utils/window.js +++ b/packages/bruno-electron/src/utils/window.js @@ -7,12 +7,14 @@ const DEFAULT_WINDOW_WIDTH = 1280; const DEFAULT_WINDOW_HEIGHT = 768; const loadWindowState = () => { + const maximized = windowStateStore.getMaximized(); const bounds = windowStateStore.getBounds(); const positionValid = isPositionValid(bounds); const sizeValid = isSizeValid(bounds); return { + maximized, x: bounds.x && positionValid ? bounds.x : undefined, y: bounds.y && positionValid ? bounds.y : undefined, width: bounds.width && sizeValid ? bounds.width : DEFAULT_WINDOW_WIDTH, @@ -20,12 +22,16 @@ const loadWindowState = () => { }; }; -const saveWindowState = (window) => { +const saveBounds = (window) => { const bounds = window.getBounds(); windowStateStore.setBounds(bounds); }; +const saveMaximized = (isMaximized) => { + windowStateStore.setMaximized(isMaximized); +}; + const isPositionValid = (bounds) => { const area = getArea(bounds); @@ -49,5 +55,6 @@ const getArea = (bounds) => { module.exports = { loadWindowState, - saveWindowState + saveBounds, + saveMaximized }; diff --git a/packages/bruno-electron/tests/utils/proxy-util.spec.js b/packages/bruno-electron/tests/utils/proxy-util.spec.js new file mode 100644 index 00000000..ac1d5a94 --- /dev/null +++ b/packages/bruno-electron/tests/utils/proxy-util.spec.js @@ -0,0 +1,50 @@ +const { shouldUseProxy } = require('../../src/utils/proxy-util'); + +test('no proxy necessary - star', () => { + const url = 'http://wwww.example.org/test'; + const noProxy = '*'; + + expect(shouldUseProxy(url, noProxy)).toEqual(false); +}); + +test('no proxy necessary - no noProxy bypass', () => { + const url = 'http://wwww.example.org/test'; + const noProxy = ''; + + expect(shouldUseProxy(url, noProxy)).toEqual(true); +}); + +test('no proxy necessary - wildcard match', () => { + const url = 'http://wwww.example.org/test'; + const noProxy = '*example.org'; + + expect(shouldUseProxy(url, noProxy)).toEqual(false); +}); + +test('no proxy necessary - direct proxy', () => { + const url = 'http://wwww.example.org/test'; + const noProxy = 'wwww.example.org'; + + expect(shouldUseProxy(url, noProxy)).toEqual(false); +}); + +test('no proxy necessary - multiple proxy', () => { + const url = 'http://wwww.example.org/test'; + const noProxy = 'www.example.com,wwww.example.org'; + + expect(shouldUseProxy(url, noProxy)).toEqual(false); +}); + +test('proxy necessary - no proxy match multiple', () => { + const url = 'https://wwww.example.test/test'; + const noProxy = 'www.example.com,wwww.example.org'; + + expect(shouldUseProxy(url, noProxy)).toEqual(true); +}); + +test('proxy necessary - no proxy match', () => { + const url = 'https://wwww.example.test/test'; + const noProxy = 'www.example.com'; + + expect(shouldUseProxy(url, noProxy)).toEqual(true); +}); diff --git a/packages/bruno-js/package.json b/packages/bruno-js/package.json index 00ccdcb1..d8161c9e 100644 --- a/packages/bruno-js/package.json +++ b/packages/bruno-js/package.json @@ -1,6 +1,6 @@ { "name": "@usebruno/js", - "version": "0.8.0", + "version": "0.9.1", "license": "MIT", "main": "src/index.js", "files": [ @@ -20,6 +20,7 @@ "axios": "^0.26.0", "btoa": "^1.2.1", "chai": "^4.3.7", + "chai-string": "^1.5.0", "crypto-js": "^4.1.1", "handlebars": "^4.7.8", "json-query": "^2.2.2", diff --git a/packages/bruno-js/src/interpolate-string.js b/packages/bruno-js/src/interpolate-string.js new file mode 100644 index 00000000..22910c1a --- /dev/null +++ b/packages/bruno-js/src/interpolate-string.js @@ -0,0 +1,55 @@ +const Handlebars = require('handlebars'); +const { forOwn, cloneDeep } = require('lodash'); + +const interpolateEnvVars = (str, processEnvVars) => { + if (!str || !str.length || typeof str !== 'string') { + return str; + } + + const template = Handlebars.compile(str, { noEscape: true }); + + return template({ + process: { + env: { + ...processEnvVars + } + } + }); +}; + +const interpolateString = (str, { envVariables, collectionVariables, processEnvVars }) => { + if (!str || !str.length || typeof str !== 'string') { + return str; + } + + processEnvVars = processEnvVars || {}; + collectionVariables = collectionVariables || {}; + + // we clone envVariables because we don't want to modify the original object + envVariables = envVariables ? cloneDeep(envVariables) : {}; + + // envVariables can inturn have values as {{process.env.VAR_NAME}} + // so we need to interpolate envVariables first with processEnvVars + forOwn(envVariables, (value, key) => { + envVariables[key] = interpolateEnvVars(value, processEnvVars); + }); + + const template = Handlebars.compile(str, { noEscape: true }); + + // collectionVariables take precedence over envVariables + const combinedVars = { + ...envVariables, + ...collectionVariables, + process: { + env: { + ...processEnvVars + } + } + }; + + return template(combinedVars); +}; + +module.exports = { + interpolateString +}; diff --git a/packages/bruno-js/src/runtime/assert-runtime.js b/packages/bruno-js/src/runtime/assert-runtime.js index 06f6adab..36fd7c9f 100644 --- a/packages/bruno-js/src/runtime/assert-runtime.js +++ b/packages/bruno-js/src/runtime/assert-runtime.js @@ -4,6 +4,7 @@ const { nanoid } = require('nanoid'); const Bru = require('../bru'); const BrunoRequest = require('../bruno-request'); const { evaluateJsTemplateLiteral, evaluateJsExpression, createResponseParser } = require('../utils'); +const { interpolateString } = require('../interpolate-string'); const { expect } = chai; chai.use(require('chai-string')); @@ -161,17 +162,27 @@ const evaluateRhsOperand = (rhsOperand, operator, context) => { return; } + const interpolationContext = { + collectionVariables: context.bru.collectionVariables, + envVariables: context.bru.envVariables, + processEnvVars: context.bru.processEnvVars + }; + // gracefully allow both a,b as well as [a, b] if (operator === 'in' || operator === 'notIn') { if (rhsOperand.startsWith('[') && rhsOperand.endsWith(']')) { rhsOperand = rhsOperand.substring(1, rhsOperand.length - 1); } - return rhsOperand.split(',').map((v) => evaluateJsTemplateLiteral(v.trim(), context)); + return rhsOperand + .split(',') + .map((v) => evaluateJsTemplateLiteral(interpolateString(v.trim(), interpolationContext), context)); } if (operator === 'between') { - const [lhs, rhs] = rhsOperand.split(',').map((v) => evaluateJsTemplateLiteral(v.trim(), context)); + const [lhs, rhs] = rhsOperand + .split(',') + .map((v) => evaluateJsTemplateLiteral(interpolateString(v.trim(), interpolationContext), context)); return [lhs, rhs]; } @@ -181,10 +192,10 @@ const evaluateRhsOperand = (rhsOperand, operator, context) => { rhsOperand = rhsOperand.substring(1, rhsOperand.length - 1); } - return rhsOperand; + return interpolateString(rhsOperand, interpolationContext); } - return evaluateJsTemplateLiteral(rhsOperand, context); + return evaluateJsTemplateLiteral(interpolateString(rhsOperand, interpolationContext), context); }; class AssertRuntime { diff --git a/packages/bruno-lang/package.json b/packages/bruno-lang/package.json index 2e4b3df0..0096efad 100644 --- a/packages/bruno-lang/package.json +++ b/packages/bruno-lang/package.json @@ -1,6 +1,6 @@ { "name": "@usebruno/lang", - "version": "0.8.0", + "version": "0.9.0", "license": "MIT", "main": "src/index.js", "files": [ diff --git a/packages/bruno-lang/v2/src/bruToJson.js b/packages/bruno-lang/v2/src/bruToJson.js index 5ce65eba..d8d51d3b 100644 --- a/packages/bruno-lang/v2/src/bruToJson.js +++ b/packages/bruno-lang/v2/src/bruToJson.js @@ -104,7 +104,7 @@ const mapPairListToKeyValPairs = (pairList = [], parseEnabled = true) => { } return _.map(pairList[0], (pair) => { let name = _.keys(pair)[0]; - let value = pair[name]; + let value = decodeURIComponent(pair[name]); if (!parseEnabled) { return { diff --git a/packages/bruno-lang/v2/src/jsonToBru.js b/packages/bruno-lang/v2/src/jsonToBru.js index 757406b7..56b5ec47 100644 --- a/packages/bruno-lang/v2/src/jsonToBru.js +++ b/packages/bruno-lang/v2/src/jsonToBru.js @@ -154,7 +154,7 @@ ${indentString(body.sparql)} if (enabled(body.formUrlEncoded).length) { bru += `\n${indentString( enabled(body.formUrlEncoded) - .map((item) => `${item.name}: ${item.value}`) + .map((item) => `${item.name}: ${encodeURIComponent(item.value)}`) .join('\n') )}`; } @@ -162,7 +162,7 @@ ${indentString(body.sparql)} if (disabled(body.formUrlEncoded).length) { bru += `\n${indentString( disabled(body.formUrlEncoded) - .map((item) => `~${item.name}: ${item.value}`) + .map((item) => `~${item.name}: ${encodeURIComponent(item.value)}`) .join('\n') )}`; } diff --git a/packages/bruno-schema/package.json b/packages/bruno-schema/package.json index f927a326..b1ff8db8 100644 --- a/packages/bruno-schema/package.json +++ b/packages/bruno-schema/package.json @@ -1,6 +1,6 @@ { "name": "@usebruno/schema", - "version": "0.5.0", + "version": "0.6.0", "license": "MIT", "main": "src/index.js", "files": [ diff --git a/publishing.md b/publishing.md new file mode 100644 index 00000000..f7db8a32 --- /dev/null +++ b/publishing.md @@ -0,0 +1,6 @@ +### Publishing Bruno to a new package manager + +While our code is open source and available for everyone to use, we kindly request that you reach out to us before considering publication on new package managers. As the creator of Bruno, I hold the trademark `Bruno` for this project and would like to manage its distribution. If you'd like to see Bruno on a new package manager, please raise a Github issue. + +While, majority of our features are free and open source (which covers REST and GraphQL Apis) +We strive to strike a harmonious balance between open-source principles and sustainability - https://github.com/usebruno/bruno/discussions/269 diff --git a/readme.md b/readme.md index 8021a5b7..ce41f699 100644 --- a/readme.md +++ b/readme.md @@ -10,7 +10,7 @@ [![Website](https://img.shields.io/badge/Website-Visit-blue)](https://www.usebruno.com) [![Download](https://img.shields.io/badge/Download-Latest-brightgreen)](https://www.usebruno.com/downloads) -**English** | [Русский](/readme_ru.md) +**English** | [Українська](/readme_ua.md) | [Русский](/readme_ru.md) | [Türkçe](/readme_tr.md) | [Deutsch](/readme_de.md) Bruno is a new and innovative API client, aimed at revolutionizing the status quo represented by Postman and similar tools out there. @@ -38,6 +38,7 @@ Or any version control system of your choice - [Roadmap](https://github.com/usebruno/bruno/discussions/384) - [Documentation](https://docs.usebruno.com) - [Website](https://www.usebruno.com) +- [Pricing](https://www.usebruno.com/pricing) - [Download](https://www.usebruno.com/downloads) ### Showcase 🎥 @@ -52,11 +53,15 @@ Woof! If you like project, hit that ⭐ button !! ### Share Testimonials 📣 -If Bruno has helped you at work and your teams, please don't forget to share your [testimonials on our github discussion](https://github.com/usebruno/bruno/discussions/343) +If Bruno has helped you at work and your teams, please don't forget to share your [testimonials on our GitHub discussion](https://github.com/usebruno/bruno/discussions/343) + +### Publishing to New Package Managers + +Please see [here](publishing.md) for more information. ### Contribute 👩‍💻🧑‍💻 -I am happy that you are looking to improve bruno. Please checkout the [contributing guide](contributing.md) +I am happy that you are looking to improve bruno. Please check out the [contributing guide](contributing.md) Even if you are not able to make contributions via code, please don't hesitate to file bugs and feature requests that needs to be implemented to solve your use case. @@ -72,9 +77,19 @@ Even if you are not able to make contributions via code, please don't hesitate t [Twitter](https://twitter.com/use_bruno)
[Website](https://www.usebruno.com)
-[Discord](https://discord.com/invite/KgcZUncpjq) +[Discord](https://discord.com/invite/KgcZUncpjq)
[LinkedIn](https://www.linkedin.com/company/usebruno) +### Trademark + +**Name** + +`Bruno` is a trademark held by [Anoop M D](https://www.helloanoop.com/) + +**Logo** + +The logo is sourced from [OpenMoji](https://openmoji.org/library/emoji-1F436/). License: CC [BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) + ### License 📄 [MIT](license.md) diff --git a/readme_de.md b/readme_de.md new file mode 100644 index 00000000..2454a7ac --- /dev/null +++ b/readme_de.md @@ -0,0 +1,95 @@ +
+ + +### Bruno - Opensource IDE zum Erkunden und Testen von APIs. + +[![GitHub version](https://badge.fury.io/gh/usebruno%2Fbruno.svg)](https://badge.fury.io/gh/usebruno%bruno) +[![CI](https://github.com/usebruno/bruno/actions/workflows/unit-tests.yml/badge.svg?branch=main)](https://github.com/usebruno/bruno/workflows/unit-tests.yml) +[![Commit Activity](https://img.shields.io/github/commit-activity/m/usebruno/bruno)](https://github.com/usebruno/bruno/pulse) +[![X](https://img.shields.io/twitter/follow/use_bruno?style=social&logo=x)](https://twitter.com/use_bruno) +[![Website](https://img.shields.io/badge/Website-Visit-blue)](https://www.usebruno.com) +[![Download](https://img.shields.io/badge/Download-Latest-brightgreen)](https://www.usebruno.com/downloads) + +[English](/readme.md) | [Українська](/readme_ua.md) | [Русский](/readme_ru.md) | [Türkçe](/readme_tr.md) | **Deutsch** + +Bruno ist ein neuer und innovativer API-Client, der den Status Quo von Postman und ähnlichen Tools revolutionieren soll. + +Bruno speichert Deine Sammlungen direkt in einem Ordner in Deinem Dateisystem. Wir verwenden eine einfache Textauszeichnungssprache - Bru - um Informationen über API-Anfragen zu speichern. + +Du kannst Git oder eine andere Versionskontrolle deiner Wahl verwenden, um an deinen API-Sammlungen gemeinsam mit anderen zu arbeiten. + +Bruno ist ein reines Offline-Tool. Es gibt keine Pläne, Bruno eine Cloud-Synchronisation hinzuzufügen. Wir schätzen den Schutz Deiner Daten und glauben, dass sie auf Deinem Gerät bleiben sollten. Lies unsere Langzeit-Vision [hier](https://github.com/usebruno/bruno/discussions/269). + +![bruno](assets/images/landing-2.png)

+ +### Einsatz auf verschiedensten Plattformen 🖥️ + +![bruno](assets/images/run-anywhere.png)

+ +### Zusammenarbeiten mit Git 👩‍💻🧑‍💻 + +oder eine Versionskontrolle Deiner Wahl + +![bruno](assets/images/version-control.png)

+ +### Wichtige Links 📌 + +- [Unsere Langzeit-Vision](https://github.com/usebruno/bruno/discussions/269) +- [Roadmap](https://github.com/usebruno/bruno/discussions/384) +- [Dokumentation](https://docs.usebruno.com) +- [Webseite](https://www.usebruno.com) +- [Preise](https://www.usebruno.com/pricing) +- [Download](https://www.usebruno.com/downloads) + +### Showcase 🎥 + +- [Erfahrungsberichte](https://github.com/usebruno/bruno/discussions/343) +- [Wissenswertes](https://github.com/usebruno/bruno/discussions/386) +- [Scriptmania](https://github.com/usebruno/bruno/discussions/385) + +### Unterstützung ❤️ + +Wuff! Wenn Du dieses Projekt magst, klick den ⭐ Button !! + +### Teile Erfahrungsberichte 📣 + +Wenn Bruno Dir bei Deiner Arbeit und in Deinen Teams geholfen hat, vergiss bitte nicht, Deine [Erfahrungsberichte auf unserer GitHub-Diskussion](https://github.com/usebruno/bruno/discussions/343) zu teilen. + +### Veröffentlichung in neuen Paketmanagern + +Bitte [hier](publishing.md) für mehr Informationen lesen. + +### Mitmachen 👩‍💻🧑‍💻 + +Ich freue mich, dass Du Bruno verbessern willst. Bitte schau Dir den [Leitfaden zum Mitmachen](contributing_de.md) an. + +Auch wenn Du nicht in der Lage bist, einen Beitrag in Form von Code zu leisten, zögere bitte nicht, uns Fehler und Funktionswünsche mitzuteilen, die implementiert werden müssen, um Deinen Anwendungsfall zu unterstützen. + +### Autoren + + + +### In Verbindung bleiben 🌐 + +[Twitter](https://twitter.com/use_bruno)
+[Webseite](https://www.usebruno.com)
+[Discord](https://discord.com/invite/KgcZUncpjq)
+[LinkedIn](https://www.linkedin.com/company/usebruno) + +### Markenzeichen + +**Name** + +`Bruno` ist ein Markenzeichen von [Anoop M D](https://www.helloanoop.com/) + +**Logo** + +Das Logo stammt von [OpenMoji](https://openmoji.org/library/emoji-1F436/). Lizenz: CC [BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) + +### Lizenz 📄 + +[MIT](license.md) diff --git a/readme_ru.md b/readme_ru.md index 8c25e5c5..35361765 100644 --- a/readme_ru.md +++ b/readme_ru.md @@ -10,7 +10,7 @@ [![Website](https://img.shields.io/badge/Website-Visit-blue)](https://www.usebruno.com) [![Download](https://img.shields.io/badge/Download-Latest-brightgreen)](https://www.usebruno.com/downloads) -[English](/readme.md) | **Русский** +[English](/readme.md) | [Українська](/readme_ua.md) | **Русский** | [Türkçe](/readme_tr.md) | [Deutsch](/readme_de.md) Bruno - новый и инновационный клиент API, направленный на революцию в установившейся ситуации, представленной Postman и подобными инструментами. diff --git a/readme_tr.md b/readme_tr.md new file mode 100644 index 00000000..ffedde5c --- /dev/null +++ b/readme_tr.md @@ -0,0 +1,80 @@ +
+ + +### Bruno - API'leri keşfetmek ve test etmek için açık kaynaklı IDE. + +[![GitHub sürümü](https://badge.fury.io/gh/usebruno%2Fbruno.svg)](https://badge.fury.io/gh/usebruno%bruno) +[![CI](https://github.com/usebruno/bruno/actions/workflows/unit-tests.yml/badge.svg?branch=main)](https://github.com/usebruno/bruno/workflows/unit-tests.yml) +[![Commit Activity](https://img.shields.io/github/commit-activity/m/usebruno/bruno)](https://github.com/usebruno/bruno/pulse) +[![X](https://img.shields.io/twitter/follow/use_bruno?style=social&logo=x)](https://twitter.com/use_bruno) +[![Web Sitesi](https://img.shields.io/badge/Website-Visit-blue)](https://www.usebruno.com) +[![İndir](https://img.shields.io/badge/Download-Latest-brightgreen)](https://www.usebruno.com/downloads) + +[English](/readme.md) | [Українська](/readme_ua.md) | [Русский](/readme_ru.md) | **Türkçe** | [Deutsch](/readme_de.md) + +Bruno, Postman ve benzeri araçlar tarafından temsil edilen statükoda devrim yaratmayı amaçlayan yeni ve yenilikçi bir API istemcisidir. + +Bruno koleksiyonlarınızı doğrudan dosya sisteminizdeki bir klasörde saklar. API istekleri hakkındaki bilgileri kaydetmek için düz bir metin biçimlendirme dili olan Bru kullanıyoruz. + +API koleksiyonlarınız üzerinde işbirliği yapmak için git veya seçtiğiniz herhangi bir sürüm kontrolünü kullanabilirsiniz. + +Bruno yalnızca çevrimdışıdır. Bruno'ya bulut senkronizasyonu eklemek gibi bir planımız yok. Veri gizliliğinize değer veriyoruz ve cihazınızda kalması gerektiğine inanıyoruz. Uzun vadeli vizyonumuzu okuyun [burada](https://github.com/usebruno/bruno/discussions/269) + +![bruno](assets/images/landing-2.png)

+ +### Birden fazla platformda çalıştırın 🖥️ + +![bruno](assets/images/run-anywhere.png)

+ +### Git üzerinden işbirliği yapın 👩‍💻🧑‍💻 + +Veya seçtiğiniz herhangi bir sürüm kontrol sistemi + +![bruno](assets/images/version-control.png)

+ +### Önemli Bağlantılar 📌 + +- [Uzun Vadeli Vizyonumuz](https://github.com/usebruno/bruno/discussions/269) +- [Yol Haritası](https://github.com/usebruno/bruno/discussions/384) +- [Dokümantasyon](https://docs.usebruno.com) +- [Web sitesi](https://www.usebruno.com) +- [İndir](https://www.usebruno.com/downloads) + +### Vitrin 🎥 + +- [Görüşler](https://github.com/usebruno/bruno/discussions/343) +- [Bilgi Merkezi](https://github.com/usebruno/bruno/discussions/386) +- [Scriptmania](https://github.com/usebruno/bruno/discussions/385) + +### Destek ❤️ + +Woof! Projeyi beğendiyseniz, şu ⭐ düğmesine basın! + +### Referansları Paylaşın 📣 + +Bruno işinizde ve ekiplerinizde size yardımcı olduysa, lütfen [github tartışmamızdaki referanslarınızı](https://github.com/usebruno/bruno/discussions/343) paylaşmayı unutmayın + +### Katkıda Bulunun 👩‍💻🧑‍💻 + +Bruno'yu geliştirmek istemenize sevindim. Lütfen [katkıda bulunma kılavuzu](contributing.md)'na göz atın + +Kod yoluyla katkıda bulunamasanız bile, lütfen kullanım durumunuzu çözmek için uygulanması gereken hataları ve özellik isteklerini bildirmekten çekinmeyin. + +### Katkıda Bulunanlar + + + +### İletişimde Kalın 🌐 + +[Twitter](https://twitter.com/use_bruno)
+[Website](https://www.usebruno.com)
+[Discord](https://discord.com/invite/KgcZUncpjq) +[LinkedIn](https://www.linkedin.com/company/usebruno) + +### Lisans 📄 + +[MIT](license.md) diff --git a/readme_ua.md b/readme_ua.md new file mode 100644 index 00000000..a7dd8919 --- /dev/null +++ b/readme_ua.md @@ -0,0 +1,80 @@ +
+ + +### Bruno - IDE із відкритим кодом для тестування та дослідження API + +[![GitHub version](https://badge.fury.io/gh/usebruno%2Fbruno.svg)](https://badge.fury.io/gh/usebruno%bruno) +[![CI](https://github.com/usebruno/bruno/actions/workflows/unit-tests.yml/badge.svg?branch=main)](https://github.com/usebruno/bruno/workflows/unit-tests.yml) +[![Commit Activity](https://img.shields.io/github/commit-activity/m/usebruno/bruno)](https://github.com/usebruno/bruno/pulse) +[![X](https://img.shields.io/twitter/follow/use_bruno?style=social&logo=x)](https://twitter.com/use_bruno) +[![Website](https://img.shields.io/badge/Website-Visit-blue)](https://www.usebruno.com) +[![Download](https://img.shields.io/badge/Download-Latest-brightgreen)](https://www.usebruno.com/downloads) + +[English](/readme.md) | **Українська** | [Русский](/readme_ru.md) | [Türkçe](/readme_tr.md) | [Deutsch](/readme_de.md) + +Bruno це новий та іноваційний API клієнт, націлений на революційну зміну статус кво, запровадженого інструментами на кшталт Postman. + +Bruno зберігає ваші колекції напряму у теці на вашому диску. Він використовує текстову мову розмітки Bru для збереження інформації про ваші API запити. + +Ви можете використовувати git або будь-яку іншу систему контролю версій щоб спільно працювати над вашими колекціями API запитів. + +Bruno є повністю автономним. Немає жодних планів додавати будь-які синхронізації через хмару, ніколи. Ми цінуємо приватність ваших даних, і вважаєм, що вони мають залишитись лише на вашому комп'ютері. Взнати більше про наше бачення у довготривалій перспективі можна [тут](https://github.com/usebruno/bruno/discussions/269) + +![bruno](assets/images/landing-2.png)

+ +### Кросплатформенність 🖥️ + +![bruno](assets/images/run-anywhere.png)

+ +### Спільна робота через Git 👩‍💻🧑‍💻 + +Або будь-яку іншу систему контролю версій на ваш вибір + +![bruno](assets/images/version-control.png)

+ +### Важливі посилання 📌 + +- [Наше бачення довготривалої перспективи проекту](https://github.com/usebruno/bruno/discussions/269) +- [Дорожня карта проекту](https://github.com/usebruno/bruno/discussions/384) +- [Документація](https://docs.usebruno.com) +- [Сайт](https://www.usebruno.com) +- [Завантаження](https://www.usebruno.com/downloads) + +### Вітрина 🎥 + +- [Відгуки](https://github.com/usebruno/bruno/discussions/343) +- [Хаб знань](https://github.com/usebruno/bruno/discussions/386) +- [Scriptmania](https://github.com/usebruno/bruno/discussions/385) + +### Підтримка ❤️ + +Гав! Якщо вам сподобався проект, тисніть на ⭐ !! + +### Поділитись відгуками 📣 + +Якщо Bruno допоміг вам у вашій роботі і вашим командам, будь ласка не забудьте поділитись вашими [відгуками у github дискусії](https://github.com/usebruno/bruno/discussions/343) + +### Зробити свій внесок 👩‍💻🧑‍💻 + +Я радий що ви бажаєте покращити Bruno. Будь ласка переглянте [інструкцію по контрибуції](contributing_ua.md) + +Навіть якщо ви не можете зробити свій внесок пишучи програмний код, будь ласка не соромтесь рапортувати про помилки і писати запити на новий функціонал, який потрібен вам у вашій роботі. + +### Автори + + + +### Залишайтесь на зв'язку 🌐 + +[Twitter](https://twitter.com/use_bruno)
+[Сайт](https://www.usebruno.com)
+[Discord](https://discord.com/invite/KgcZUncpjq)
+[LinkedIn](https://www.linkedin.com/company/usebruno) + +### Ліцензія 📄 + +[MIT](license.md) diff --git a/scripts/build-electron.js b/scripts/build-electron.js index 363fdf4d..9825c3a0 100644 --- a/scripts/build-electron.js +++ b/scripts/build-electron.js @@ -1,8 +1,7 @@ const os = require('os'); const fs = require('fs-extra'); const util = require('util'); -const exec = util.promisify(require('child_process').exec); - +const spawn = util.promisify(require('child_process').spawn); async function deleteFileIfExists(filePath) { try { @@ -47,6 +46,25 @@ async function removeSourceMapFiles(directory) { } } +async function execCommandWithOutput(command) { + return new Promise(async (resolve, reject) => { + const childProcess = await spawn(command, { + stdio: 'inherit', + shell: true + }); + childProcess.on('error', (error) => { + reject(error); + }); + childProcess.on('exit', (code) => { + if (code === 0) { + resolve(); + } else { + reject(new Error(`Command exited with code ${code}.`)); + } + }); + }); +} + async function main() { try { // Remove out directory @@ -67,13 +85,13 @@ async function main() { for (const file of files) { if (file.endsWith('.html')) { let content = await fs.readFile(`packages/bruno-electron/web/${file}`, 'utf8'); - content = content.replace(/\/_next\//g, '/_next/'); + content = content.replace(/\/_next\//g, '_next/'); await fs.writeFile(`packages/bruno-electron/web/${file}`, content); } } // Remove sourcemaps - await removeSourceMapFiles('packages/bruno-electron/web') + await removeSourceMapFiles('packages/bruno-electron/web'); // Run npm dist command console.log('Building the Electron distribution'); @@ -88,8 +106,7 @@ async function main() { osArg = 'linux'; } - await exec(`npm run dist-${osArg} --workspace=packages/bruno-electron`); - + await execCommandWithOutput(`npm run dist:${osArg} --workspace=packages/bruno-electron`); } catch (error) { console.error('An error occurred:', error); } diff --git a/tests/home.spec.js b/tests/home.spec.js index 6c10905f..0ab8a565 100644 --- a/tests/home.spec.js +++ b/tests/home.spec.js @@ -1,6 +1,6 @@ const { test, expect } = require('@playwright/test'); const { HomePage } = require('../tests/pages/home.page'); -import * as faker from './utils/data-faker'; +const { faker } = require('./utils/data-faker'); test.describe('bruno e2e test', () => { let homePage;