Compare commits
137 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
451c8b9dde | ||
|
|
b7682db9a3 | ||
|
|
7e2d72c4e3 | ||
|
|
28bb460409 | ||
|
|
56d635166b | ||
|
|
f6a7257104 | ||
|
|
1fce060ef7 | ||
|
|
5c966e5a95 | ||
|
|
0520ef5d43 | ||
|
|
25b110778a | ||
|
|
327bf84e57 | ||
|
|
1c48b309b5 | ||
|
|
7c5dec821d | ||
|
|
dcd8f6c08a | ||
|
|
31f9a63c3b | ||
|
|
e902b67a63 | ||
|
|
b11c72fde4 | ||
|
|
07b90c6ae3 | ||
|
|
ba6163b6d8 | ||
|
|
8055b625d0 | ||
|
|
3a61ffbbb0 | ||
|
|
f8478677c5 | ||
|
|
f5094c5a94 | ||
|
|
8300187566 | ||
|
|
cd8ab3616e | ||
|
|
be0c92b755 | ||
|
|
c34ea20406 | ||
|
|
6e9b1db196 | ||
|
|
d83aabd2be | ||
|
|
d46479cd22 | ||
|
|
19cae33382 | ||
|
|
267cd079ad | ||
|
|
19c1efc73e | ||
|
|
dfa9a22861 | ||
|
|
533f9bacc4 | ||
|
|
0358748729 | ||
|
|
1540d0a5a5 | ||
|
|
d177e164f1 | ||
|
|
f1355c9d15 | ||
|
|
485a9ea47c | ||
|
|
dbc606fb53 | ||
|
|
a00b4ae232 | ||
|
|
998b5cf78a | ||
|
|
b4deae6e8d | ||
|
|
87fdf17010 | ||
|
|
c6975a9e8b | ||
|
|
b44ac55bc2 | ||
|
|
9c65c95ba9 | ||
|
|
7beb9f4e69 | ||
|
|
dbecd74f46 | ||
|
|
6826ee1672 | ||
|
|
a12ae7ef56 | ||
|
|
dbc100409d | ||
|
|
6b87cd9655 | ||
|
|
7ce2cdc9cc | ||
|
|
1f4e38b7a7 | ||
|
|
0013a0797b | ||
|
|
5e9b14dc0b | ||
|
|
b7cfb0db13 | ||
|
|
8948bfbf45 | ||
|
|
4218e90bf4 | ||
|
|
2172d7ac60 | ||
|
|
5e45cb4908 | ||
|
|
d662883fdd | ||
|
|
f83f3d4682 | ||
|
|
e03c745093 | ||
|
|
73b9d699ed | ||
|
|
5a7b9aba2f | ||
|
|
cf433b26a5 | ||
|
|
573035b17d | ||
|
|
a267c0c53f | ||
|
|
328563f4e6 | ||
|
|
3844fec968 | ||
|
|
8557a2477b | ||
|
|
d02519ab74 | ||
|
|
1a1751c23e | ||
|
|
17de0678b0 | ||
|
|
20bb89de33 | ||
|
|
8a634b1056 | ||
|
|
57f231ca00 | ||
|
|
cb1c0e4d8c | ||
|
|
2152cf87d7 | ||
|
|
8662b230e7 | ||
|
|
3a8a6484c7 | ||
|
|
f92594a16d | ||
|
|
7969fcb76c | ||
|
|
eafefb1894 | ||
|
|
9a94a15c82 | ||
|
|
757d28c235 | ||
|
|
6c79c1ef3f | ||
|
|
7262eccac5 | ||
|
|
4989a5f759 | ||
|
|
0b0b05d29c | ||
|
|
b3d6d87bee | ||
|
|
6abbdc8726 | ||
|
|
b9613591f8 | ||
|
|
eb555989ac | ||
|
|
b77f1375fd | ||
|
|
3c438b3da7 | ||
|
|
df15543c80 | ||
|
|
73ad86c6b9 | ||
|
|
615de8b3cc | ||
|
|
2418bd0672 | ||
|
|
b3414ee60f | ||
|
|
8fe50959b9 | ||
|
|
523e7dcf16 | ||
|
|
7951f3a7bd | ||
|
|
c6666b9623 | ||
|
|
fa98351e30 | ||
|
|
3c8be3f5b9 | ||
|
|
eb3d1c409b | ||
|
|
46b049c72b | ||
|
|
fec64b5c02 | ||
|
|
8c3ed60579 | ||
|
|
907e09a417 | ||
|
|
28c6af8f94 | ||
|
|
f8b0510d08 | ||
|
|
5f99b7df05 | ||
|
|
158877b355 | ||
|
|
8b84545b67 | ||
|
|
0e28079965 | ||
|
|
5d5f9cc943 | ||
|
|
b71bc2cc92 | ||
|
|
23191dcfc3 | ||
|
|
372b15689d | ||
|
|
5c6d6fb7e4 | ||
|
|
835a2e93e9 | ||
|
|
93c6f6d611 | ||
|
|
b445261b32 | ||
|
|
685b59cee9 | ||
|
|
38529cc89e | ||
|
|
0d98b95b61 | ||
|
|
e044dcae3e | ||
|
|
b5b7b1638d | ||
|
|
9d6ac8a107 | ||
|
|
6440df492e | ||
|
|
2cdd97cabb |
13
.github/workflows/release.yml
vendored
@@ -62,7 +62,7 @@ jobs:
|
||||
|
||||
- name: install dependencies (windows only)
|
||||
if: matrix.platform == 'windows-latest'
|
||||
run: cargo install --force trusted-signing-cli --version 0.5.0
|
||||
run: cargo install --force trusted-signing-cli
|
||||
|
||||
- name: Install NPM Dependencies
|
||||
run: npm ci
|
||||
@@ -72,9 +72,16 @@ jobs:
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Some things (eg. WASM package) requires building before lint will work
|
||||
- name: Run bootstrap
|
||||
run: npm run bootstrap
|
||||
|
||||
- name: Run lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Set version
|
||||
run: npm run replace-version
|
||||
env:
|
||||
@@ -106,5 +113,5 @@ jobs:
|
||||
releaseName: 'Release __VERSION__'
|
||||
releaseBody: '[Changelog __VERSION__](https://yaak.app/blog/__VERSION__)'
|
||||
releaseDraft: true
|
||||
prerelease: false
|
||||
args: ${{ matrix.args }}
|
||||
prerelease: true
|
||||
args: '${{ matrix.args }} --config ./src-tauri/tauri.release.conf.json'
|
||||
|
||||
44
.github/workflows/sponsors.yml
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
name: Generate Sponsors README
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: 30 15 * * 0-6
|
||||
permissions:
|
||||
contents: write
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout 🛎️
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Generate Sponsors
|
||||
uses: JamesIves/github-sponsors-readme-action@v1
|
||||
with:
|
||||
token: ${{ secrets.SPONSORS_PAT }}
|
||||
file: 'README.md'
|
||||
maximum: 1999
|
||||
template: '<a href="https://github.com/{{{ login }}}"><img src="{{{ avatarUrl }}}" width="50px" alt="User avatar: {{{ login }}}" /></a> '
|
||||
active-only: false
|
||||
include-private: true
|
||||
marker: 'sponsors-base'
|
||||
|
||||
- name: Generate Sponsors
|
||||
uses: JamesIves/github-sponsors-readme-action@v1
|
||||
with:
|
||||
token: ${{ secrets.SPONSORS_PAT }}
|
||||
file: 'README.md'
|
||||
minimum: 2000
|
||||
template: '<a href="https://github.com/{{{ login }}}"><img src="{{{ avatarUrl }}}" width="80px" alt="User avatar: {{{ login }}}" /></a> '
|
||||
active-only: false
|
||||
include-private: true
|
||||
marker: 'sponsors-premium'
|
||||
|
||||
# ⚠️ Note: You can use any deployment step here to automatically push the README
|
||||
# changes back to your branch.
|
||||
- name: Commit Changes
|
||||
uses: JamesIves/github-pages-deploy-action@v4
|
||||
with:
|
||||
branch: main
|
||||
force: false
|
||||
folder: '.'
|
||||
82
README.md
@@ -1,34 +1,70 @@
|
||||
# Yaak API Client
|
||||
<p align="center">
|
||||
<a href="https://github.com/JamesIves/github-sponsors-readme-action">
|
||||
<img width="200px" src="https://github.com/mountain-loop/yaak/raw/main/src-tauri/icons/icon.png">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
Yaak is a desktop API client for interacting with REST, GraphQL, Server Sent Events (SSE), WebSocket, and gRPC
|
||||
APIs. It's built using [Tauri](https://tauri.app), Rust, and ReactJS.
|
||||
<h1 align="center">
|
||||
💫 Yaak ➟ Desktop API Client 💫
|
||||
</h1>
|
||||
|
||||
<p align="center">
|
||||
A fast, privacy-first API client for REST, GraphQL, SSE, WebSocket, and gRPC – built with Tauri, Rust, and React.
|
||||
</p>
|
||||
<p align="center">
|
||||
Development is funded by community-purchased <a href="https://yaak.app/pricing">licenses</a>. You can also <a href="https://github.com/sponsors/gschier">become a sponsor</a> to have your logo appear below. 💖
|
||||
</p>
|
||||
<br>
|
||||
|
||||
|
||||
|
||||
<p align="center">
|
||||
<!-- sponsors-premium --><a href="https://github.com/MVST-Solutions"><img src="https://github.com/MVST-Solutions.png" width="80px" alt="User avatar: MVST-Solutions" /></a> <a href="https://github.com/dharsanb"><img src="https://github.com/dharsanb.png" width="80px" alt="User avatar: dharsanb" /></a> <a href="https://github.com/railwayapp"><img src="https://github.com/railwayapp.png" width="80px" alt="User avatar: railwayapp" /></a> <a href="https://github.com/caseyamcl"><img src="https://github.com/caseyamcl.png" width="80px" alt="User avatar: caseyamcl" /></a> <a href="https://github.com/andriyor"><img src="https://github.com/andriyor.png" width="80px" alt="User avatar: andriyor" /></a> <a href="https://github.com/"><img src="https://raw.githubusercontent.com/JamesIves/github-sponsors-readme-action/dev/.github/assets/placeholder.png" width="80px" alt="User avatar: " /></a> <!-- sponsors-premium -->
|
||||
</p>
|
||||
<p align="center">
|
||||
<!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https://github.com/seanwash.png" width="50px" alt="User avatar: seanwash" /></a> <a href="https://github.com/jerath"><img src="https://github.com/jerath.png" width="50px" alt="User avatar: jerath" /></a> <a href="https://github.com/itsa-sh"><img src="https://github.com/itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a> <a href="https://github.com/dmmulroy"><img src="https://github.com/dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a> <a href="https://github.com/timcole"><img src="https://github.com/timcole.png" width="50px" alt="User avatar: timcole" /></a> <a href="https://github.com/VLZH"><img src="https://github.com/VLZH.png" width="50px" alt="User avatar: VLZH" /></a> <a href="https://github.com/terasaka2k"><img src="https://github.com/terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a> <a href="https://github.com/majudhu"><img src="https://github.com/majudhu.png" width="50px" alt="User avatar: majudhu" /></a> <!-- sponsors-base -->
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
|
||||
## Features
|
||||
|
||||
Yaak is an offline-first API client designed to stay out of your way while giving you everything you need when you need it.
|
||||
Built with [Tauri](https://tauri.app), Rust, and React, it’s fast, lightweight, and private. No telemetry, no VC funding, and no cloud lock-in.
|
||||
|
||||
|
||||
### 🌐 Work with any API
|
||||
|
||||
- Import collections from Postman, Insomnia, OpenAPI, Swagger, or Curl.
|
||||
- Send requests via REST, GraphQL, gRPC, WebSocket, or Server-Sent Events.
|
||||
- Filter and inspect responses with JSONPath or XPath.
|
||||
|
||||
### 🔐 Stay secure
|
||||
- Use OAuth 2.0, JWT, Basic Auth, or custom plugins for authentication.
|
||||
- Secure sensitive values with encrypted secrets.
|
||||
- Store secrets in your OS keychain.
|
||||
|
||||
### ☁️ Organize & collaborate
|
||||
- Group requests into workspaces and nested folders.
|
||||
- Use environment variables to switch between dev, staging, and prod.
|
||||
- Mirror workspaces to your filesystem for versioning in Git or syncing with Dropbox.
|
||||
|
||||
### 🧩 Extend & customize
|
||||
- Insert dynamic values like UUIDs or timestamps with template tags.
|
||||
- Pick from built-in themes or build your own.
|
||||
- Create plugins to extend authentication, template tags, or the UI.
|
||||
|
||||

|
||||
|
||||
## Contribution Policy
|
||||
|
||||
Yaak is open source, but only accepting contributions for bug fixes. To get started,
|
||||
Yaak is open source but only accepting contributions for bug fixes. To get started,
|
||||
visit [`DEVELOPMENT.md`](DEVELOPMENT.md) for tips on setting up your environment.
|
||||
|
||||
## Feature Overview
|
||||
|
||||
- 🪂 Import data from Postman, Insomnia, OpenAPI, Swagger, or Curl.<br/>
|
||||
- 📤 Send requests via REST, GraphQL, Server Sent Events (SSE), WebSockets, or gRPC.<br/>
|
||||
- 🔐 Automatically authorize requests with OAuth 2.0, JWT tokens, Basic Auth, and more.<br/>
|
||||
- 🔎 Filter response bodies using JSONPath or XPath queries.<br/>
|
||||
- ⛓️ Chain together multiple requests to dynamically reference values.<br/>
|
||||
- 📂 Organize requests into workspaces and nested folders.<br/>
|
||||
- 🧮 Use environment variables to easily switch between Prod and Dev.<br/>
|
||||
- 🛡️ Secure arbitrary text values with end-to-end encryption<br/>
|
||||
- 🏷️ Send dynamic values like UUIDs or timestamps using template tags.<br/>
|
||||
- 🎨 Choose from many of the included themes, or make your own.<br/>
|
||||
- 💽 Mirror workspace data to a directory for integration with Git or Dropbox.<br/>
|
||||
- 📜 View response history for each request.<br/>
|
||||
- 🔌 Create your own plugins for authentication, template tags, and more!<br/>
|
||||
- 🛜 Configure a proxy to access firewall-blocked APIs
|
||||
|
||||
## Useful Resources
|
||||
|
||||
- [Feedback and Bug Reports](https://feedback.yaak.app)
|
||||
- [Documentation](https://feedback.yaak.app/help)
|
||||
- [Yaak vs Postman](https://yaak.app/blog/postman-alternative)
|
||||
- [Yaak vs Postman](https://yaak.app/alternatives/postman)
|
||||
- [Yaak vs Bruno](https://yaak.app/alternatives/bruno)
|
||||
- [Yaak vs Insomnia](https://yaak.app/alternatives/insomnia)
|
||||
|
||||
862
package-lock.json
generated
21
package.json
@@ -7,25 +7,26 @@
|
||||
"url": "git+https://github.com/mountain-loop/yaak.git"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/common-lib",
|
||||
"packages/plugin-runtime",
|
||||
"packages/plugin-runtime-types",
|
||||
"packages/common-lib",
|
||||
"plugins/action-copy-curl",
|
||||
"plugins/action-copy-grpcurl",
|
||||
"plugins/auth-apikey",
|
||||
"plugins/auth-aws",
|
||||
"plugins/auth-basic",
|
||||
"plugins/auth-bearer",
|
||||
"plugins/auth-jwt",
|
||||
"plugins/auth-oauth2",
|
||||
"plugins/action-copy-curl",
|
||||
"plugins/action-copy-grpcurl",
|
||||
"plugins/filter-jsonpath",
|
||||
"plugins/filter-xpath",
|
||||
"plugins/importer-curl",
|
||||
"plugins/importer-insomnia",
|
||||
"plugins/importer-openapi",
|
||||
"plugins/importer-postman",
|
||||
"plugins/importer-postman-environment",
|
||||
"plugins/importer-yaak",
|
||||
"plugins/template-function-cookie",
|
||||
"plugins/template-function-timestamp",
|
||||
"plugins/template-function-encode",
|
||||
"plugins/template-function-fs",
|
||||
"plugins/template-function-hash",
|
||||
@@ -34,12 +35,14 @@
|
||||
"plugins/template-function-regex",
|
||||
"plugins/template-function-request",
|
||||
"plugins/template-function-response",
|
||||
"plugins/template-function-timestamp",
|
||||
"plugins/template-function-uuid",
|
||||
"plugins/template-function-xml",
|
||||
"plugins/themes-yaak",
|
||||
"src-tauri",
|
||||
"src-tauri/yaak-crypto",
|
||||
"src-tauri/yaak-git",
|
||||
"src-tauri/yaak-fonts",
|
||||
"src-tauri/yaak-git",
|
||||
"src-tauri/yaak-license",
|
||||
"src-tauri/yaak-mac-window",
|
||||
"src-tauri/yaak-models",
|
||||
@@ -53,10 +56,14 @@
|
||||
"scripts": {
|
||||
"start": "npm run app-dev",
|
||||
"app-build": "tauri build",
|
||||
"app-dev": "tauri dev --no-watch --config ./src-tauri/tauri-dev.conf.json",
|
||||
"app-dev": "tauri dev --no-watch --config ./src-tauri/tauri.development.conf.json",
|
||||
"migration": "node scripts/create-migration.cjs",
|
||||
"build": "npm run --workspaces --if-present build",
|
||||
"build-plugins": "npm run --workspaces --if-present build",
|
||||
"test": "npm run --workspaces --if-present test",
|
||||
"icons": "run-p icons:*",
|
||||
"icons:dev": "tauri icon src-tauri/icons/icon-dev.png --output src-tauri/icons/dev",
|
||||
"icons:release": "tauri icon src-tauri/icons/icon.png --output src-tauri/icons/release",
|
||||
"bootstrap": "run-p bootstrap:* && npm run --workspaces --if-present bootstrap",
|
||||
"bootstrap:vendor-node": "node scripts/vendor-node.cjs",
|
||||
"bootstrap:vendor-plugins": "node scripts/vendor-plugins.cjs",
|
||||
@@ -74,7 +81,7 @@
|
||||
"@eslint/compat": "^1.3.0",
|
||||
"@eslint/eslintrc": "^3.3.1",
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@tauri-apps/cli": "2.4.1",
|
||||
"@tauri-apps/cli": "^2.8.4",
|
||||
"@typescript-eslint/eslint-plugin": "^8.27.0",
|
||||
"@typescript-eslint/parser": "^8.27.0",
|
||||
"@yaakapp/cli": "^0.2.7",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@yaakapp/api",
|
||||
"version": "0.6.6",
|
||||
"version": "0.7.0",
|
||||
"keywords": [
|
||||
"api-client",
|
||||
"insomnia-alternative",
|
||||
|
||||
@@ -4,8 +4,6 @@ import type { JsonValue } from "./serde_json/JsonValue.js";
|
||||
|
||||
export type BootRequest = { dir: string, watch: boolean, };
|
||||
|
||||
export type BootResponse = { name: string, version: string, };
|
||||
|
||||
export type CallGrpcRequestActionArgs = { grpcRequest: GrpcRequest, protoFiles: Array<string>, };
|
||||
|
||||
export type CallGrpcRequestActionRequest = { index: number, pluginRefId: string, args: CallGrpcRequestActionArgs, };
|
||||
@@ -363,7 +361,11 @@ export type GetKeyValueRequest = { key: string, };
|
||||
|
||||
export type GetKeyValueResponse = { value?: string, };
|
||||
|
||||
export type GetTemplateFunctionsResponse = { functions: Array<TemplateFunction>, pluginRefId: string, };
|
||||
export type GetTemplateFunctionConfigRequest = { contextId: string, name: string, values: { [key in string]?: JsonPrimitive }, };
|
||||
|
||||
export type GetTemplateFunctionConfigResponse = { function: TemplateFunction, pluginRefId: string, };
|
||||
|
||||
export type GetTemplateFunctionSummaryResponse = { functions: Array<TemplateFunction>, pluginRefId: string, };
|
||||
|
||||
export type GetThemesRequest = Record<string, never>;
|
||||
|
||||
@@ -387,7 +389,7 @@ export type ImportResponse = { resources: ImportResources, };
|
||||
|
||||
export type InternalEvent = { id: string, pluginRefId: string, pluginName: string, replyId: string | null, windowContext: PluginWindowContext, payload: InternalEventPayload, };
|
||||
|
||||
export type InternalEventPayload = { "type": "boot_request" } & BootRequest | { "type": "boot_response" } & BootResponse | { "type": "reload_request" } & EmptyPayload | { "type": "reload_response" } & BootResponse | { "type": "terminate_request" } | { "type": "terminate_response" } | { "type": "import_request" } & ImportRequest | { "type": "import_response" } & ImportResponse | { "type": "filter_request" } & FilterRequest | { "type": "filter_response" } & FilterResponse | { "type": "export_http_request_request" } & ExportHttpRequestRequest | { "type": "export_http_request_response" } & ExportHttpRequestResponse | { "type": "send_http_request_request" } & SendHttpRequestRequest | { "type": "send_http_request_response" } & SendHttpRequestResponse | { "type": "list_cookie_names_request" } & ListCookieNamesRequest | { "type": "list_cookie_names_response" } & ListCookieNamesResponse | { "type": "get_cookie_value_request" } & GetCookieValueRequest | { "type": "get_cookie_value_response" } & GetCookieValueResponse | { "type": "get_http_request_actions_request" } & EmptyPayload | { "type": "get_http_request_actions_response" } & GetHttpRequestActionsResponse | { "type": "call_http_request_action_request" } & CallHttpRequestActionRequest | { "type": "get_grpc_request_actions_request" } & EmptyPayload | { "type": "get_grpc_request_actions_response" } & GetGrpcRequestActionsResponse | { "type": "call_grpc_request_action_request" } & CallGrpcRequestActionRequest | { "type": "get_template_functions_request" } | { "type": "get_template_functions_response" } & GetTemplateFunctionsResponse | { "type": "call_template_function_request" } & CallTemplateFunctionRequest | { "type": "call_template_function_response" } & CallTemplateFunctionResponse | { "type": "get_http_authentication_summary_request" } & EmptyPayload | { "type": "get_http_authentication_summary_response" } & GetHttpAuthenticationSummaryResponse | { "type": "get_http_authentication_config_request" } & GetHttpAuthenticationConfigRequest | { "type": "get_http_authentication_config_response" } & GetHttpAuthenticationConfigResponse | { "type": "call_http_authentication_request" } & CallHttpAuthenticationRequest | { "type": "call_http_authentication_response" } & CallHttpAuthenticationResponse | { "type": "call_http_authentication_action_request" } & CallHttpAuthenticationActionRequest | { "type": "call_http_authentication_action_response" } & EmptyPayload | { "type": "copy_text_request" } & CopyTextRequest | { "type": "copy_text_response" } & EmptyPayload | { "type": "render_http_request_request" } & RenderHttpRequestRequest | { "type": "render_http_request_response" } & RenderHttpRequestResponse | { "type": "render_grpc_request_request" } & RenderGrpcRequestRequest | { "type": "render_grpc_request_response" } & RenderGrpcRequestResponse | { "type": "get_key_value_request" } & GetKeyValueRequest | { "type": "get_key_value_response" } & GetKeyValueResponse | { "type": "set_key_value_request" } & SetKeyValueRequest | { "type": "set_key_value_response" } & SetKeyValueResponse | { "type": "delete_key_value_request" } & DeleteKeyValueRequest | { "type": "delete_key_value_response" } & DeleteKeyValueResponse | { "type": "open_window_request" } & OpenWindowRequest | { "type": "window_navigate_event" } & WindowNavigateEvent | { "type": "window_close_event" } | { "type": "close_window_request" } & CloseWindowRequest | { "type": "template_render_request" } & TemplateRenderRequest | { "type": "template_render_response" } & TemplateRenderResponse | { "type": "show_toast_request" } & ShowToastRequest | { "type": "show_toast_response" } & EmptyPayload | { "type": "prompt_text_request" } & PromptTextRequest | { "type": "prompt_text_response" } & PromptTextResponse | { "type": "get_http_request_by_id_request" } & GetHttpRequestByIdRequest | { "type": "get_http_request_by_id_response" } & GetHttpRequestByIdResponse | { "type": "find_http_responses_request" } & FindHttpResponsesRequest | { "type": "find_http_responses_response" } & FindHttpResponsesResponse | { "type": "get_themes_request" } & GetThemesRequest | { "type": "get_themes_response" } & GetThemesResponse | { "type": "empty_response" } & EmptyPayload | { "type": "error_response" } & ErrorResponse;
|
||||
export type InternalEventPayload = { "type": "boot_request" } & BootRequest | { "type": "boot_response" } | { "type": "reload_response" } & ReloadResponse | { "type": "terminate_request" } | { "type": "terminate_response" } | { "type": "import_request" } & ImportRequest | { "type": "import_response" } & ImportResponse | { "type": "filter_request" } & FilterRequest | { "type": "filter_response" } & FilterResponse | { "type": "export_http_request_request" } & ExportHttpRequestRequest | { "type": "export_http_request_response" } & ExportHttpRequestResponse | { "type": "send_http_request_request" } & SendHttpRequestRequest | { "type": "send_http_request_response" } & SendHttpRequestResponse | { "type": "list_cookie_names_request" } & ListCookieNamesRequest | { "type": "list_cookie_names_response" } & ListCookieNamesResponse | { "type": "get_cookie_value_request" } & GetCookieValueRequest | { "type": "get_cookie_value_response" } & GetCookieValueResponse | { "type": "get_http_request_actions_request" } & EmptyPayload | { "type": "get_http_request_actions_response" } & GetHttpRequestActionsResponse | { "type": "call_http_request_action_request" } & CallHttpRequestActionRequest | { "type": "get_grpc_request_actions_request" } & EmptyPayload | { "type": "get_grpc_request_actions_response" } & GetGrpcRequestActionsResponse | { "type": "call_grpc_request_action_request" } & CallGrpcRequestActionRequest | { "type": "get_template_function_summary_request" } & EmptyPayload | { "type": "get_template_function_summary_response" } & GetTemplateFunctionSummaryResponse | { "type": "get_template_function_config_request" } & GetTemplateFunctionConfigRequest | { "type": "get_template_function_config_response" } & GetTemplateFunctionConfigResponse | { "type": "call_template_function_request" } & CallTemplateFunctionRequest | { "type": "call_template_function_response" } & CallTemplateFunctionResponse | { "type": "get_http_authentication_summary_request" } & EmptyPayload | { "type": "get_http_authentication_summary_response" } & GetHttpAuthenticationSummaryResponse | { "type": "get_http_authentication_config_request" } & GetHttpAuthenticationConfigRequest | { "type": "get_http_authentication_config_response" } & GetHttpAuthenticationConfigResponse | { "type": "call_http_authentication_request" } & CallHttpAuthenticationRequest | { "type": "call_http_authentication_response" } & CallHttpAuthenticationResponse | { "type": "call_http_authentication_action_request" } & CallHttpAuthenticationActionRequest | { "type": "call_http_authentication_action_response" } & EmptyPayload | { "type": "copy_text_request" } & CopyTextRequest | { "type": "copy_text_response" } & EmptyPayload | { "type": "render_http_request_request" } & RenderHttpRequestRequest | { "type": "render_http_request_response" } & RenderHttpRequestResponse | { "type": "render_grpc_request_request" } & RenderGrpcRequestRequest | { "type": "render_grpc_request_response" } & RenderGrpcRequestResponse | { "type": "template_render_request" } & TemplateRenderRequest | { "type": "template_render_response" } & TemplateRenderResponse | { "type": "get_key_value_request" } & GetKeyValueRequest | { "type": "get_key_value_response" } & GetKeyValueResponse | { "type": "set_key_value_request" } & SetKeyValueRequest | { "type": "set_key_value_response" } & SetKeyValueResponse | { "type": "delete_key_value_request" } & DeleteKeyValueRequest | { "type": "delete_key_value_response" } & DeleteKeyValueResponse | { "type": "open_window_request" } & OpenWindowRequest | { "type": "window_navigate_event" } & WindowNavigateEvent | { "type": "window_close_event" } | { "type": "close_window_request" } & CloseWindowRequest | { "type": "show_toast_request" } & ShowToastRequest | { "type": "show_toast_response" } & EmptyPayload | { "type": "prompt_text_request" } & PromptTextRequest | { "type": "prompt_text_response" } & PromptTextResponse | { "type": "get_http_request_by_id_request" } & GetHttpRequestByIdRequest | { "type": "get_http_request_by_id_response" } & GetHttpRequestByIdResponse | { "type": "find_http_responses_request" } & FindHttpResponsesRequest | { "type": "find_http_responses_response" } & FindHttpResponsesResponse | { "type": "get_themes_request" } & GetThemesRequest | { "type": "get_themes_response" } & GetThemesResponse | { "type": "empty_response" } & EmptyPayload | { "type": "error_response" } & ErrorResponse;
|
||||
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
|
||||
@@ -419,6 +421,8 @@ required?: boolean, };
|
||||
|
||||
export type PromptTextResponse = { value: string | null, };
|
||||
|
||||
export type ReloadResponse = { silent: boolean, };
|
||||
|
||||
export type RenderGrpcRequestRequest = { grpcRequest: GrpcRequest, purpose: RenderPurpose, };
|
||||
|
||||
export type RenderGrpcRequestResponse = { grpcRequest: GrpcRequest, };
|
||||
@@ -437,7 +441,7 @@ export type SetKeyValueRequest = { key: string, value: string, };
|
||||
|
||||
export type SetKeyValueResponse = {};
|
||||
|
||||
export type ShowToastRequest = { message: string, color?: Color, icon?: Icon, };
|
||||
export type ShowToastRequest = { message: string, color?: Color, icon?: Icon, timeout?: number, };
|
||||
|
||||
export type TemplateFunction = { name: string, description?: string,
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type Environment = { model: "environment", id: string, workspaceId: string, createdAt: string, updatedAt: string, name: string, public: boolean, base: boolean, variables: Array<EnvironmentVariable>, color: string | null, };
|
||||
export type Environment = { model: "environment", id: string, workspaceId: string, createdAt: string, updatedAt: string, name: string, public: boolean, parentModel: string, parentId: string | null, variables: Array<EnvironmentVariable>, color: string | null, };
|
||||
|
||||
export type EnvironmentVariable = { enabled?: boolean, name: string, value: string, id?: string, };
|
||||
|
||||
|
||||
@@ -61,4 +61,7 @@ export interface Context {
|
||||
templates: {
|
||||
render<T extends JsonValue>(args: TemplateRenderRequest & { data: T }): Promise<T>;
|
||||
};
|
||||
plugin: {
|
||||
reload(): void;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import {
|
||||
CallTemplateFunctionArgs,
|
||||
FormInput,
|
||||
GetHttpAuthenticationConfigRequest,
|
||||
TemplateFunction,
|
||||
} from "../bindings/gen_events";
|
||||
import { Context } from "./Context";
|
||||
TemplateFunctionArg,
|
||||
} from '../bindings/gen_events';
|
||||
import { MaybePromise } from '../helpers';
|
||||
import { Context } from './Context';
|
||||
|
||||
export type DynamicTemplateFunctionArg = FormInput & {
|
||||
dynamic(
|
||||
ctx: Context,
|
||||
args: GetHttpAuthenticationConfigRequest,
|
||||
): MaybePromise<Partial<FormInput> | undefined | null>;
|
||||
};
|
||||
|
||||
export type TemplateFunctionPlugin = TemplateFunction & {
|
||||
onRender(
|
||||
ctx: Context,
|
||||
args: CallTemplateFunctionArgs,
|
||||
): Promise<string | null>;
|
||||
args: (TemplateFunctionArg | DynamicTemplateFunctionArg)[];
|
||||
onRender(ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null>;
|
||||
};
|
||||
|
||||
@@ -6,12 +6,16 @@ import type { ImporterPlugin } from './ImporterPlugin';
|
||||
import type { TemplateFunctionPlugin } from './TemplateFunctionPlugin';
|
||||
import type { ThemePlugin } from './ThemePlugin';
|
||||
|
||||
export type { Context } from './Context';
|
||||
import type { Context } from './Context';
|
||||
|
||||
export type { Context };
|
||||
|
||||
/**
|
||||
* The global structure of a Yaak plugin
|
||||
*/
|
||||
export type PluginDefinition = {
|
||||
init?: (ctx: Context) => void | Promise<void>;
|
||||
dispose?: () => void | Promise<void>;
|
||||
importer?: ImporterPlugin;
|
||||
themes?: ThemePlugin[];
|
||||
filter?: FilterPlugin;
|
||||
|
||||
@@ -21,7 +21,7 @@ export class PluginHandle {
|
||||
this.#instance.postMessage(event);
|
||||
}
|
||||
|
||||
terminate() {
|
||||
this.#instance.terminate();
|
||||
async terminate() {
|
||||
await this.#instance.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
BootRequest,
|
||||
BootResponse,
|
||||
DeleteKeyValueResponse,
|
||||
FindHttpResponsesResponse,
|
||||
FormInput,
|
||||
@@ -56,19 +55,19 @@ export class PluginInstance {
|
||||
// Reload plugin if the JS or package.json changes
|
||||
const windowContextNone: PluginWindowContext = { type: 'none' };
|
||||
|
||||
this.#mod = {};
|
||||
this.#mod = {} as any;
|
||||
this.#pkg = JSON.parse(readFileSync(this.#pathPkg(), 'utf8'));
|
||||
|
||||
const bootResponse: BootResponse = {
|
||||
name: this.#pkg.name ?? 'unknown',
|
||||
version: this.#pkg.version ?? '0.0.1',
|
||||
};
|
||||
|
||||
const fileChangeCallback = async () => {
|
||||
await this.#mod?.dispose?.();
|
||||
this.#importModule();
|
||||
await this.#mod?.init?.(this.#newCtx({ type: 'none' }));
|
||||
return this.#sendPayload(
|
||||
windowContextNone,
|
||||
{ type: 'reload_response', ...bootResponse },
|
||||
{
|
||||
type: 'reload_response',
|
||||
silent: false,
|
||||
},
|
||||
null,
|
||||
);
|
||||
};
|
||||
@@ -85,23 +84,20 @@ export class PluginInstance {
|
||||
this.#appToPluginEvents.emit(event);
|
||||
}
|
||||
|
||||
terminate() {
|
||||
async terminate() {
|
||||
await this.#mod?.dispose?.();
|
||||
this.#unimportModule();
|
||||
}
|
||||
|
||||
async #onMessage(event: InternalEvent) {
|
||||
const ctx = this.#newCtx(event);
|
||||
const ctx = this.#newCtx(event.windowContext);
|
||||
|
||||
const { windowContext, payload, id: replyId } = event;
|
||||
|
||||
try {
|
||||
if (payload.type === 'boot_request') {
|
||||
// console.log('Plugin initialized', pkg.name, { capabilities, enableWatch });
|
||||
const payload: InternalEventPayload = {
|
||||
type: 'boot_response',
|
||||
name: this.#pkg.name ?? 'unknown',
|
||||
version: this.#pkg.version ?? '0.0.1',
|
||||
};
|
||||
this.#sendPayload(windowContext, payload, replyId);
|
||||
await this.#mod?.init?.(ctx);
|
||||
this.#sendPayload(windowContext, { type: 'boot_response' }, replyId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -109,6 +105,7 @@ export class PluginInstance {
|
||||
const payload: InternalEventPayload = {
|
||||
type: 'terminate_response',
|
||||
};
|
||||
await this.terminate();
|
||||
this.#sendPayload(windowContext, payload, replyId);
|
||||
return;
|
||||
}
|
||||
@@ -189,20 +186,55 @@ export class PluginInstance {
|
||||
}
|
||||
|
||||
if (
|
||||
payload.type === 'get_template_functions_request' &&
|
||||
payload.type === 'get_template_function_summary_request' &&
|
||||
Array.isArray(this.#mod?.templateFunctions)
|
||||
) {
|
||||
const reply: TemplateFunction[] = this.#mod.templateFunctions.map((templateFunction) => {
|
||||
return {
|
||||
...migrateTemplateFunctionSelectOptions(templateFunction),
|
||||
// Add everything except render
|
||||
onRender: undefined,
|
||||
};
|
||||
});
|
||||
const functions: TemplateFunction[] = this.#mod.templateFunctions.map(
|
||||
(templateFunction) => {
|
||||
return {
|
||||
...migrateTemplateFunctionSelectOptions(templateFunction),
|
||||
// Add everything except render
|
||||
onRender: undefined,
|
||||
};
|
||||
},
|
||||
);
|
||||
const replyPayload: InternalEventPayload = {
|
||||
type: 'get_template_functions_response',
|
||||
type: 'get_template_function_summary_response',
|
||||
pluginRefId: this.#workerData.pluginRefId,
|
||||
functions: reply,
|
||||
functions,
|
||||
};
|
||||
this.#sendPayload(windowContext, replyPayload, replyId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
payload.type === 'get_template_function_config_request' &&
|
||||
Array.isArray(this.#mod?.templateFunctions)
|
||||
) {
|
||||
let templateFunction = this.#mod.templateFunctions.find((f) => f.name === payload.name);
|
||||
if (templateFunction == null) {
|
||||
this.#sendEmpty(windowContext, replyId);
|
||||
return;
|
||||
}
|
||||
|
||||
templateFunction = migrateTemplateFunctionSelectOptions(templateFunction);
|
||||
// @ts-ignore
|
||||
delete templateFunction.onRender;
|
||||
const resolvedArgs: TemplateFunctionArg[] = [];
|
||||
for (const arg of templateFunction.args) {
|
||||
if (arg && 'dynamic' in arg) {
|
||||
const dynamicAttrs = await arg.dynamic(ctx, payload);
|
||||
const { dynamic, ...other } = arg;
|
||||
resolvedArgs.push({ ...other, ...dynamicAttrs } as TemplateFunctionArg);
|
||||
} else if (arg) {
|
||||
resolvedArgs.push(arg);
|
||||
}
|
||||
templateFunction.args = resolvedArgs;
|
||||
}
|
||||
const replyPayload: InternalEventPayload = {
|
||||
type: 'get_template_function_config_response',
|
||||
pluginRefId: this.#workerData.pluginRefId,
|
||||
function: templateFunction,
|
||||
};
|
||||
this.#sendPayload(windowContext, replyPayload, replyId);
|
||||
return;
|
||||
@@ -332,10 +364,6 @@ export class PluginInstance {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.type === 'reload_request') {
|
||||
this.#importModule();
|
||||
}
|
||||
} catch (err) {
|
||||
const error = `${err}`.replace(/^Error:\s*/g, '');
|
||||
console.log('Plugin call threw exception', payload.type, '→', error);
|
||||
@@ -447,11 +475,11 @@ export class PluginInstance {
|
||||
this.#sendEvent(eventToSend);
|
||||
}
|
||||
|
||||
#newCtx(event: InternalEvent): Context {
|
||||
#newCtx(windowContext: PluginWindowContext): Context {
|
||||
return {
|
||||
clipboard: {
|
||||
copyText: async (text) => {
|
||||
await this.#sendAndWaitForReply(event.windowContext, {
|
||||
await this.#sendAndWaitForReply(windowContext, {
|
||||
type: 'copy_text_request',
|
||||
text,
|
||||
});
|
||||
@@ -459,8 +487,10 @@ export class PluginInstance {
|
||||
},
|
||||
toast: {
|
||||
show: async (args) => {
|
||||
await this.#sendAndWaitForReply(event.windowContext, {
|
||||
await this.#sendAndWaitForReply(windowContext, {
|
||||
type: 'show_toast_request',
|
||||
// Handle default here because null/undefined both convert to None in Rust translation
|
||||
timeout: args.timeout === undefined ? 5000 : args.timeout,
|
||||
...args,
|
||||
});
|
||||
},
|
||||
@@ -476,21 +506,21 @@ export class PluginInstance {
|
||||
onClose?.();
|
||||
}
|
||||
};
|
||||
this.#sendAndListenForEvents(event.windowContext, payload, onEvent);
|
||||
this.#sendAndListenForEvents(windowContext, payload, onEvent);
|
||||
return {
|
||||
close: () => {
|
||||
const closePayload: InternalEventPayload = {
|
||||
type: 'close_window_request',
|
||||
label: args.label,
|
||||
};
|
||||
this.#sendPayload(event.windowContext, closePayload, null);
|
||||
this.#sendPayload(windowContext, closePayload, null);
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
prompt: {
|
||||
text: async (args) => {
|
||||
const reply: PromptTextResponse = await this.#sendAndWaitForReply(event.windowContext, {
|
||||
const reply: PromptTextResponse = await this.#sendAndWaitForReply(windowContext, {
|
||||
type: 'prompt_text_request',
|
||||
...args,
|
||||
});
|
||||
@@ -504,7 +534,7 @@ export class PluginInstance {
|
||||
...args,
|
||||
} as const;
|
||||
const { httpResponses } = await this.#sendAndWaitForReply<FindHttpResponsesResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return httpResponses;
|
||||
@@ -517,7 +547,7 @@ export class PluginInstance {
|
||||
...args,
|
||||
} as const;
|
||||
const { grpcRequest } = await this.#sendAndWaitForReply<RenderGrpcRequestResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return grpcRequest;
|
||||
@@ -530,7 +560,7 @@ export class PluginInstance {
|
||||
...args,
|
||||
} as const;
|
||||
const { httpRequest } = await this.#sendAndWaitForReply<GetHttpRequestByIdResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return httpRequest;
|
||||
@@ -541,7 +571,7 @@ export class PluginInstance {
|
||||
...args,
|
||||
} as const;
|
||||
const { httpResponse } = await this.#sendAndWaitForReply<SendHttpRequestResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return httpResponse;
|
||||
@@ -552,7 +582,7 @@ export class PluginInstance {
|
||||
...args,
|
||||
} as const;
|
||||
const { httpRequest } = await this.#sendAndWaitForReply<RenderHttpRequestResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return httpRequest;
|
||||
@@ -565,7 +595,7 @@ export class PluginInstance {
|
||||
...args,
|
||||
} as const;
|
||||
const { value } = await this.#sendAndWaitForReply<GetCookieValueResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return value;
|
||||
@@ -573,7 +603,7 @@ export class PluginInstance {
|
||||
listNames: async () => {
|
||||
const payload = { type: 'list_cookie_names_request' } as const;
|
||||
const { names } = await this.#sendAndWaitForReply<ListCookieNamesResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return names;
|
||||
@@ -587,7 +617,7 @@ export class PluginInstance {
|
||||
render: async (args) => {
|
||||
const payload = { type: 'template_render_request', ...args } as const;
|
||||
const result = await this.#sendAndWaitForReply<TemplateRenderResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return result.data as any;
|
||||
@@ -597,7 +627,7 @@ export class PluginInstance {
|
||||
get: async <T>(key: string) => {
|
||||
const payload = { type: 'get_key_value_request', key } as const;
|
||||
const result = await this.#sendAndWaitForReply<GetKeyValueResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return result.value ? (JSON.parse(result.value) as T) : undefined;
|
||||
@@ -609,17 +639,22 @@ export class PluginInstance {
|
||||
key,
|
||||
value: valueStr,
|
||||
};
|
||||
await this.#sendAndWaitForReply<GetKeyValueResponse>(event.windowContext, payload);
|
||||
await this.#sendAndWaitForReply<GetKeyValueResponse>(windowContext, payload);
|
||||
},
|
||||
delete: async (key: string) => {
|
||||
const payload = { type: 'delete_key_value_request', key } as const;
|
||||
const result = await this.#sendAndWaitForReply<DeleteKeyValueResponse>(
|
||||
event.windowContext,
|
||||
windowContext,
|
||||
payload,
|
||||
);
|
||||
return result.deleted;
|
||||
},
|
||||
},
|
||||
plugin: {
|
||||
reload: () => {
|
||||
this.#sendPayload({ type: 'none' }, { type: 'reload_response', silent: true }, null);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ async function handleIncoming(msg: string) {
|
||||
}
|
||||
|
||||
if (pluginEvent.payload.type === 'terminate_request') {
|
||||
plugin.terminate();
|
||||
await plugin.terminate();
|
||||
console.log('Terminated plugin worker', pluginEvent.pluginRefId);
|
||||
delete plugins[pluginEvent.pluginRefId];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { TemplateFunction } from '@yaakapp/api';
|
||||
import { TemplateFunctionPlugin } from '@yaakapp/api/lib/plugins/TemplateFunctionPlugin';
|
||||
|
||||
export function migrateTemplateFunctionSelectOptions(f: TemplateFunction): TemplateFunction {
|
||||
export function migrateTemplateFunctionSelectOptions(
|
||||
f: TemplateFunctionPlugin,
|
||||
): TemplateFunctionPlugin {
|
||||
const migratedArgs = f.args.map((a) => {
|
||||
if (a.type === 'select') {
|
||||
a.options = a.options.map((o) => ({
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint": "tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,18 +34,18 @@ export async function convertToCurl(request: Partial<HttpRequest>) {
|
||||
let finalUrl = request.url || '';
|
||||
const urlParams = (request.urlParameters ?? []).filter(onlyEnabled);
|
||||
if (urlParams.length > 0) {
|
||||
// Build url
|
||||
// Build url
|
||||
const [base, hash] = finalUrl.split('#');
|
||||
const separator = base!.includes('?') ? '&' : '?';
|
||||
const queryString = urlParams
|
||||
.map(p => `${encodeURIComponent(p.name)}=${encodeURIComponent(p.value)}`)
|
||||
.map((p) => `${encodeURIComponent(p.name)}=${encodeURIComponent(p.value)}`)
|
||||
.join('&');
|
||||
finalUrl = base + separator + queryString + (hash ? `#${hash}` : '');
|
||||
}
|
||||
|
||||
|
||||
xs.push(quote(finalUrl));
|
||||
xs.push(NEWLINE);
|
||||
|
||||
|
||||
// Add headers
|
||||
for (const h of (request.headers ?? []).filter(onlyEnabled)) {
|
||||
xs.push('--header', quote(`${h.name}: ${h.value}`));
|
||||
@@ -53,7 +53,11 @@ export async function convertToCurl(request: Partial<HttpRequest>) {
|
||||
}
|
||||
|
||||
// Add form params
|
||||
if (Array.isArray(request.body?.form)) {
|
||||
const type = request.bodyType ?? 'none';
|
||||
if (
|
||||
(type === 'multipart/form-data' || type === 'application/x-www-form-urlencoded') &&
|
||||
Array.isArray(request.body?.form)
|
||||
) {
|
||||
const flag = request.bodyType === 'multipart/form-data' ? '--form' : '--data';
|
||||
for (const p of (request.body?.form ?? []).filter(onlyEnabled)) {
|
||||
if (p.file) {
|
||||
@@ -65,14 +69,14 @@ export async function convertToCurl(request: Partial<HttpRequest>) {
|
||||
}
|
||||
xs.push(NEWLINE);
|
||||
}
|
||||
} else if (typeof request.body?.query === 'string') {
|
||||
} else if (type === 'graphql' && typeof request.body?.query === 'string') {
|
||||
const body = {
|
||||
query: request.body.query || '',
|
||||
variables: maybeParseJSON(request.body.variables, undefined),
|
||||
};
|
||||
xs.push('--data', quote(JSON.stringify(body)));
|
||||
xs.push(NEWLINE);
|
||||
} else if (typeof request.body?.text === 'string') {
|
||||
} else if (type !== 'none' && typeof request.body?.text === 'string') {
|
||||
xs.push('--data', quote(request.body.text));
|
||||
xs.push(NEWLINE);
|
||||
}
|
||||
@@ -89,7 +93,9 @@ export async function convertToCurl(request: Partial<HttpRequest>) {
|
||||
|
||||
// Add bearer authentication
|
||||
if (request.authenticationType === 'bearer') {
|
||||
xs.push('--header', quote(`Authorization: Bearer ${request.authentication?.token ?? ''}`));
|
||||
const value =
|
||||
`${request.authentication?.prefix ?? 'Bearer'} ${request.authentication?.token ?? ''}`.trim();
|
||||
xs.push('--header', quote(`Authorization: ${value}`));
|
||||
xs.push(NEWLINE);
|
||||
}
|
||||
|
||||
@@ -116,4 +122,4 @@ function maybeParseJSON<T>(v: string, fallback: T) {
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,7 @@ describe('exporter-curl', () => {
|
||||
{ name: 'c', value: 'ccc', enabled: false },
|
||||
],
|
||||
}),
|
||||
).toEqual(
|
||||
[`curl 'https://yaak.app/?a=aaa&b=bbb'`].join(` \\n `),
|
||||
);
|
||||
).toEqual([`curl 'https://yaak.app?a=aaa&b=bbb'`].join(` \\n `));
|
||||
});
|
||||
|
||||
test('Exports GET with params and hash', async () => {
|
||||
@@ -27,9 +25,7 @@ describe('exporter-curl', () => {
|
||||
{ name: 'c', value: 'ccc', enabled: false },
|
||||
],
|
||||
}),
|
||||
).toEqual(
|
||||
[`curl 'https://yaak.app/path?a=aaa&b=bbb#section'`].join(` \\n `),
|
||||
);
|
||||
).toEqual([`curl 'https://yaak.app/path?a=aaa&b=bbb#section'`].join(` \\n `));
|
||||
});
|
||||
test('Exports POST with url form data', async () => {
|
||||
expect(
|
||||
@@ -62,7 +58,10 @@ describe('exporter-curl', () => {
|
||||
},
|
||||
}),
|
||||
).toEqual(
|
||||
[`curl -X POST 'https://yaak.app'`, `--data '{"query":"{foo,bar}","variables":{"a":"aaa","b":"bbb"}}'`].join(` \\\n `),
|
||||
[
|
||||
`curl -X POST 'https://yaak.app'`,
|
||||
`--data '{"query":"{foo,bar}","variables":{"a":"aaa","b":"bbb"}}'`,
|
||||
].join(` \\\n `),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -206,6 +205,34 @@ describe('exporter-curl', () => {
|
||||
).toEqual([`curl 'https://yaak.app'`, `--header 'Authorization: Bearer tok'`].join(` \\\n `));
|
||||
});
|
||||
|
||||
test('Bearer auth with custom prefix', async () => {
|
||||
expect(
|
||||
await convertToCurl({
|
||||
url: 'https://yaak.app',
|
||||
authenticationType: 'bearer',
|
||||
authentication: {
|
||||
token: 'abc123',
|
||||
prefix: 'Token',
|
||||
},
|
||||
}),
|
||||
).toEqual(
|
||||
[`curl 'https://yaak.app'`, `--header 'Authorization: Token abc123'`].join(` \\\n `),
|
||||
);
|
||||
});
|
||||
|
||||
test('Bearer auth with empty prefix', async () => {
|
||||
expect(
|
||||
await convertToCurl({
|
||||
url: 'https://yaak.app',
|
||||
authenticationType: 'bearer',
|
||||
authentication: {
|
||||
token: 'xyz789',
|
||||
prefix: '',
|
||||
},
|
||||
}),
|
||||
).toEqual([`curl 'https://yaak.app'`, `--header 'Authorization: xyz789'`].join(` \\\n `));
|
||||
});
|
||||
|
||||
test('Broken bearer auth', async () => {
|
||||
expect(
|
||||
await convertToCurl({
|
||||
@@ -216,6 +243,18 @@ describe('exporter-curl', () => {
|
||||
password: 'pass',
|
||||
},
|
||||
}),
|
||||
).toEqual([`curl 'https://yaak.app'`, `--header 'Authorization: Bearer '`].join(` \\\n `));
|
||||
).toEqual([`curl 'https://yaak.app'`, `--header 'Authorization: Bearer'`].join(` \\\n `));
|
||||
});
|
||||
});
|
||||
|
||||
test('Stale body data', async () => {
|
||||
expect(
|
||||
await convertToCurl({
|
||||
url: 'https://yaak.app',
|
||||
bodyType: 'none',
|
||||
body: {
|
||||
text: 'ignore me',
|
||||
},
|
||||
}),
|
||||
).toEqual([`curl 'https://yaak.app'`].join(` \\\n `));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,8 +41,8 @@ export async function convert(request: Partial<GrpcRequest>, allProtoFiles: stri
|
||||
if (protoDir) {
|
||||
inferredIncludes.add(protoDir);
|
||||
} else {
|
||||
inferredIncludes.add(path.join(f, '..'));
|
||||
inferredIncludes.add(path.join(f, '..', '..'));
|
||||
inferredIncludes.add(path.posix.join(f, '..'));
|
||||
inferredIncludes.add(path.posix.join(f, '..', '..'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
49
plugins/auth-aws/README.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# AWS Signature Version 4 Auth
|
||||
|
||||
A plugin for authenticating AWS-compatible requests using the
|
||||
[AWS Signature Version 4 signing process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html).
|
||||
This enables secure, signed requests to AWS services (or any S3-compatible APIs like
|
||||
Cloudflare R2).
|
||||
|
||||

|
||||
|
||||
## Overview
|
||||
|
||||
This plugin provides AWS Signature authentication for API requests in Yaak. SigV4 is used
|
||||
by nearly all AWS APIs to verify the authenticity and integrity of requests using
|
||||
cryptographic signatures.
|
||||
|
||||
With this plugin, you can securely sign requests to AWS services such as S3, STS, Lambda,
|
||||
API Gateway, DynamoDB, and more. You can also authenticate against S3-compatible services
|
||||
like **Cloudflare R2**, **MinIO**, or **Wasabi**.
|
||||
|
||||
## How AWS Signature Version 4 Works
|
||||
|
||||
SigV4 signs requests by creating a hash of key request components (method, URL, headers,
|
||||
and optionally the payload) using your AWS credentials. The resulting HMAC signature is
|
||||
added in the `Authorization` header along with credential scope metadata.
|
||||
|
||||
Example header:
|
||||
|
||||
```
|
||||
Authorization: AWS4-HMAC-SHA256 Credential=AKIA…/20251011/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-date, Signature=abcdef123456…
|
||||
```
|
||||
|
||||
Each request must include a timestamp (`X-Amz-Date`) and may include a session token if
|
||||
using temporary credentials.
|
||||
|
||||
## Configuration
|
||||
|
||||
The plugin presents the following fields:
|
||||
|
||||
- **Access Key ID** – Your AWS access key identifier
|
||||
- **Secret Access Key** – The secret associated with the access key
|
||||
- **Session Token** *(optional)* – Used for temporary or assumed-role credentials (treated as secret)
|
||||
- **Region** – AWS region (e.g., `us-east-1`)
|
||||
- **Service** – AWS service identifier (e.g., `sts`, `s3`, `execute-api`)
|
||||
|
||||
## Usage
|
||||
|
||||
1. Configure a request, folder, or workspace to use **AWS SigV4 Authentication**
|
||||
2. Enter your AWS credentials and target service/region
|
||||
3. The plugin will automatically sign outgoing requests with valid SigV4 headers
|
||||
23
plugins/auth-aws/package.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@yaak/auth-aws",
|
||||
"displayName": "AWS SigV4",
|
||||
"description": "Authenticate requests using AWS SigV4 signing",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/mountain-loop/yaak.git",
|
||||
"directory": "plugins/auth-aws"
|
||||
},
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"aws4": "^1.13.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/aws4": "^1.11.6"
|
||||
}
|
||||
}
|
||||
BIN
plugins/auth-aws/screenshot.png
Normal file
|
After Width: | Height: | Size: 790 KiB |
97
plugins/auth-aws/src/index.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { CallHttpAuthenticationResponse } from '@yaakapp-internal/plugins';
|
||||
import type { PluginDefinition } from '@yaakapp/api';
|
||||
import aws4 from 'aws4';
|
||||
import type { Request } from 'aws4';
|
||||
import { URL } from 'node:url';
|
||||
|
||||
export const plugin: PluginDefinition = {
|
||||
authentication: {
|
||||
name: 'auth-aws-sig-v4',
|
||||
label: 'AWS Signature',
|
||||
shortLabel: 'AWS v4',
|
||||
args: [
|
||||
{ name: 'accessKeyId', label: 'Access Key ID', type: 'text', password: true },
|
||||
{
|
||||
name: 'secretAccessKey',
|
||||
label: 'Secret Access Key',
|
||||
type: 'text',
|
||||
password: true,
|
||||
},
|
||||
{
|
||||
name: 'service',
|
||||
label: 'Service Name',
|
||||
type: 'text',
|
||||
defaultValue: 'sts',
|
||||
placeholder: 'sts',
|
||||
description: 'The service that is receiving the request (sts, s3, sqs, ...)',
|
||||
},
|
||||
{
|
||||
name: 'region',
|
||||
label: 'Region',
|
||||
type: 'text',
|
||||
placeholder: 'us-east-1',
|
||||
description: 'The region that is receiving the request (defaults to us-east-1)',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
name: 'sessionToken',
|
||||
label: 'Session Token',
|
||||
type: 'text',
|
||||
password: true,
|
||||
optional: true,
|
||||
description: 'Only required if you are using temporary credentials',
|
||||
},
|
||||
],
|
||||
onApply(_ctx, { values, ...args }): CallHttpAuthenticationResponse {
|
||||
const accessKeyId = String(values.accessKeyId || '');
|
||||
const secretAccessKey = String(values.secretAccessKey || '');
|
||||
const sessionToken = String(values.sessionToken || '') || undefined;
|
||||
|
||||
const url = new URL(args.url);
|
||||
|
||||
const headers: NonNullable<Request['headers']> = {};
|
||||
for (const headerName of ['content-type', 'host', 'x-amz-date', 'x-amz-security-token']) {
|
||||
const v = args.headers.find((h) => h.name.toLowerCase() === headerName);
|
||||
if (v != null) {
|
||||
headers[headerName] = v.value;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Support body signing here
|
||||
headers['x-amz-content-sha256'] = 'UNSIGNED-PAYLOAD';
|
||||
|
||||
const signature = aws4.sign(
|
||||
{
|
||||
host: url.host,
|
||||
method: args.method,
|
||||
path: url.pathname + (url.search || '') || undefined,
|
||||
service: String(values.service || 'sts') || undefined,
|
||||
region: String(values.region || 'us-east-1') || undefined,
|
||||
headers,
|
||||
},
|
||||
{
|
||||
accessKeyId,
|
||||
secretAccessKey,
|
||||
sessionToken,
|
||||
},
|
||||
);
|
||||
|
||||
// After signing, aws4 will set:
|
||||
// - opts.headers["Authorization"]
|
||||
// - opts.headers["X-Amz-Date"]
|
||||
// - optionally content sha256 header etc
|
||||
|
||||
console.log('ADDING STUFF', signature);
|
||||
|
||||
if (signature.headers == null) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
setHeaders: Object.entries(signature.headers)
|
||||
.filter(([name]) => name !== 'content-type') // Don't add this because we already have it
|
||||
.map(([name, value]) => ({ name, value: String(value || '') })),
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
3
plugins/auth-aws/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json"
|
||||
}
|
||||
@@ -12,6 +12,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { fetchAccessToken } from '../fetchAccessToken';
|
||||
import { getOrRefreshAccessToken } from '../getOrRefreshAccessToken';
|
||||
import type { AccessToken, TokenStoreArgs } from '../store';
|
||||
import { getDataDirKey, storeToken } from '../store';
|
||||
import { extractCode } from '../util';
|
||||
|
||||
export const PKCE_SHA256 = 'S256';
|
||||
export const PKCE_PLAIN = 'plain';
|
||||
@@ -79,7 +80,6 @@ export async function getAuthorizationCode(
|
||||
authorizationUrl.searchParams.set('code_challenge_method', pkce.challengeMethod);
|
||||
}
|
||||
|
||||
const logsEnabled = (await ctx.store.get('enable_logs')) ?? false;
|
||||
const dataDirKey = await getDataDirKey(ctx, contextId);
|
||||
const authorizationUrlStr = authorizationUrl.toString();
|
||||
console.log('[oauth2] Authorizing', authorizationUrlStr);
|
||||
@@ -88,27 +88,26 @@ export async function getAuthorizationCode(
|
||||
const code = await new Promise<string>(async (resolve, reject) => {
|
||||
let foundCode = false;
|
||||
const { close } = await ctx.window.openUrl({
|
||||
dataDirKey,
|
||||
url: authorizationUrlStr,
|
||||
label: 'oauth-authorization-url',
|
||||
dataDirKey,
|
||||
async onClose() {
|
||||
if (!foundCode) {
|
||||
reject(new Error('Authorization window closed'));
|
||||
}
|
||||
},
|
||||
async onNavigate({ url: urlStr }) {
|
||||
const url = new URL(urlStr);
|
||||
if (logsEnabled) console.log('[oauth2] Navigated to', urlStr);
|
||||
|
||||
if (url.searchParams.has('error')) {
|
||||
let code;
|
||||
try {
|
||||
code = extractCode(urlStr, redirectUri);
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
close();
|
||||
return reject(new Error(`Failed to authorize: ${url.searchParams.get('error')}`));
|
||||
return;
|
||||
}
|
||||
|
||||
const code = url.searchParams.get('code');
|
||||
if (!code) {
|
||||
console.log('[oauth2] Code not found');
|
||||
return; // Could be one of many redirects in a chain, so skip it
|
||||
return;
|
||||
}
|
||||
|
||||
// Close the window here, because we don't need it anymore!
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Context } from '@yaakapp/api';
|
||||
import type { AccessToken, AccessTokenRawResponse } from '../store';
|
||||
import { getToken, storeToken } from '../store';
|
||||
import type { AccessToken, AccessTokenRawResponse} from '../store';
|
||||
import { getDataDirKey , getToken, storeToken } from '../store';
|
||||
import { isTokenExpired } from '../util';
|
||||
|
||||
export async function getImplicit(
|
||||
@@ -60,7 +60,9 @@ export async function getImplicit(
|
||||
const newToken = await new Promise<AccessToken>(async (resolve, reject) => {
|
||||
let foundAccessToken = false;
|
||||
const authorizationUrlStr = authorizationUrl.toString();
|
||||
const dataDirKey = await getDataDirKey(ctx, contextId);
|
||||
const { close } = await ctx.window.openUrl({
|
||||
dataDirKey,
|
||||
url: authorizationUrlStr,
|
||||
label: 'oauth-authorization-url',
|
||||
async onClose() {
|
||||
|
||||
@@ -6,8 +6,8 @@ import type {
|
||||
PluginDefinition,
|
||||
} from '@yaakapp/api';
|
||||
import {
|
||||
genPkceCodeVerifier,
|
||||
DEFAULT_PKCE_METHOD,
|
||||
genPkceCodeVerifier,
|
||||
getAuthorizationCode,
|
||||
PKCE_PLAIN,
|
||||
PKCE_SHA256,
|
||||
@@ -125,17 +125,6 @@ export const plugin: PluginDefinition = {
|
||||
await resetDataDirKey(ctx, contextId);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Toggle Debug Logs',
|
||||
async onSelect(ctx) {
|
||||
const enableLogs = !(await ctx.store.get('enable_logs'));
|
||||
await ctx.store.set('enable_logs', enableLogs);
|
||||
await ctx.toast.show({
|
||||
message: `Debug logs ${enableLogs ? 'enabled' : 'disabled'}`,
|
||||
color: 'info',
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
args: [
|
||||
{
|
||||
@@ -271,6 +260,12 @@ export const plugin: PluginDefinition = {
|
||||
label: 'Advanced',
|
||||
inputs: [
|
||||
{ type: 'text', name: 'scope', label: 'Scope', optional: true },
|
||||
{
|
||||
type: 'text',
|
||||
name: 'headerName',
|
||||
label: 'Header Name',
|
||||
defaultValue: 'Authorization',
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
name: 'headerPrefix',
|
||||
@@ -397,15 +392,9 @@ export const plugin: PluginDefinition = {
|
||||
throw new Error('Invalid grant type ' + grantType);
|
||||
}
|
||||
|
||||
const headerName = stringArg(values, 'headerName') || 'Authorization';
|
||||
const headerValue = `${headerPrefix} ${token.response[tokenName]}`.trim();
|
||||
return {
|
||||
setHeaders: [
|
||||
{
|
||||
name: 'Authorization',
|
||||
value: headerValue,
|
||||
},
|
||||
],
|
||||
};
|
||||
return { setHeaders: [{ name: headerName, value: headerValue }] };
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -3,3 +3,83 @@ import type { AccessToken } from './store';
|
||||
export function isTokenExpired(token: AccessToken) {
|
||||
return token.expiresAt && Date.now() > token.expiresAt;
|
||||
}
|
||||
|
||||
export function extractCode(urlStr: string, redirectUri: string | null): string | null {
|
||||
const url = new URL(urlStr);
|
||||
|
||||
if (!urlMatchesRedirect(url, redirectUri)) {
|
||||
console.log('[oauth2] URL does not match redirect origin/path; skipping.');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Prefer query param; fall back to fragment if query lacks it
|
||||
|
||||
const query = url.searchParams;
|
||||
const queryError = query.get('error');
|
||||
const queryDesc = query.get('error_description');
|
||||
const queryUri = query.get('error_uri');
|
||||
|
||||
let hashParams: URLSearchParams | null = null;
|
||||
if (url.hash && url.hash.length > 1) {
|
||||
hashParams = new URLSearchParams(url.hash.slice(1));
|
||||
}
|
||||
const hashError = hashParams?.get('error');
|
||||
const hashDesc = hashParams?.get('error_description');
|
||||
const hashUri = hashParams?.get('error_uri');
|
||||
|
||||
const error = queryError || hashError;
|
||||
if (error) {
|
||||
const desc = queryDesc || hashDesc;
|
||||
const uri = queryUri || hashUri;
|
||||
let message = `Failed to authorize: ${error}`;
|
||||
if (desc) message += ` (${desc})`;
|
||||
if (uri) message += ` [${uri}]`;
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const queryCode = query.get('code');
|
||||
if (queryCode) return queryCode;
|
||||
|
||||
const hashCode = hashParams?.get('code');
|
||||
if (hashCode) return hashCode;
|
||||
|
||||
console.log('[oauth2] Code not found');
|
||||
return null;
|
||||
}
|
||||
|
||||
export function urlMatchesRedirect(url: URL, redirectUrl: string | null): boolean {
|
||||
if (!redirectUrl) return true;
|
||||
|
||||
let redirect;
|
||||
try {
|
||||
redirect = new URL(redirectUrl);
|
||||
} catch {
|
||||
console.log('[oauth2] Invalid redirect URI; skipping.');
|
||||
return false;
|
||||
}
|
||||
|
||||
const sameProtocol = url.protocol === redirect.protocol;
|
||||
|
||||
const sameHost = url.hostname.toLowerCase() === redirect.hostname.toLowerCase();
|
||||
|
||||
const normalizePort = (u: URL) =>
|
||||
(u.protocol === 'https:' && (!u.port || u.port === '443')) ||
|
||||
(u.protocol === 'http:' && (!u.port || u.port === '80'))
|
||||
? ''
|
||||
: u.port;
|
||||
|
||||
const samePort = normalizePort(url) === normalizePort(redirect);
|
||||
|
||||
const normPath = (p: string) => {
|
||||
const withLeading = p.startsWith('/') ? p : `/${p}`;
|
||||
// strip trailing slashes, keep root as "/"
|
||||
return withLeading.replace(/\/+$/g, '') || '/';
|
||||
};
|
||||
|
||||
// Require redirect path to be a prefix of the navigated URL path
|
||||
const urlPath = normPath(url.pathname);
|
||||
const redirectPath = normPath(redirect.pathname);
|
||||
const pathMatches = urlPath === redirectPath || urlPath.startsWith(`${redirectPath}/`);
|
||||
|
||||
return sameProtocol && sameHost && samePort && pathMatches;
|
||||
}
|
||||
|
||||
109
plugins/auth-oauth2/tests/util.test.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { extractCode } from '../src/util';
|
||||
|
||||
describe('extractCode', () => {
|
||||
test('extracts code from query when same origin + path', () => {
|
||||
const url = 'https://app.example.com/cb?code=abc123&state=xyz';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBe('abc123');
|
||||
});
|
||||
|
||||
test('extracts code from query with weird path', () => {
|
||||
const url = 'https://app.example.com/cbwithextra?code=abc123&state=xyz';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBeNull();
|
||||
});
|
||||
|
||||
test('allows trailing slash differences', () => {
|
||||
expect(extractCode('https://app.example.com/cb/?code=abc', 'https://app.example.com/cb')).toBe(
|
||||
'abc',
|
||||
);
|
||||
expect(extractCode('https://app.example.com/cb?code=abc', 'https://app.example.com/cb/')).toBe(
|
||||
'abc',
|
||||
);
|
||||
});
|
||||
|
||||
test('treats default ports as equal (https:443, http:80)', () => {
|
||||
expect(
|
||||
extractCode('https://app.example.com/cb?code=abc', 'https://app.example.com:443/cb'),
|
||||
).toBe('abc');
|
||||
expect(extractCode('http://app.example.com/cb?code=abc', 'http://app.example.com:80/cb')).toBe(
|
||||
'abc',
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects different port', () => {
|
||||
expect(
|
||||
extractCode('https://app.example.com/cb?code=abc', 'https://app.example.com:8443/cb'),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects different hostname (including subdomain changes)', () => {
|
||||
expect(
|
||||
extractCode('https://evil.example.com/cb?code=abc', 'https://app.example.com/cb'),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test('requires path to start with redirect path (ignoring query/hash)', () => {
|
||||
// same origin but wrong path -> null
|
||||
expect(
|
||||
extractCode('https://app.example.com/other?code=abc', 'https://app.example.com/cb'),
|
||||
).toBeNull();
|
||||
|
||||
// deeper subpath under the redirect path -> allowed (prefix match)
|
||||
expect(
|
||||
extractCode('https://app.example.com/cb/deep?code=abc', 'https://app.example.com/cb'),
|
||||
).toBe('abc');
|
||||
});
|
||||
|
||||
test('works with custom schemes', () => {
|
||||
expect(extractCode('myapp://cb?code=abc', 'myapp://cb')).toBe('abc');
|
||||
});
|
||||
|
||||
test('prefers query over fragment when both present', () => {
|
||||
const url = 'https://app.example.com/cb?code=queryCode#code=hashCode';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBe('queryCode');
|
||||
});
|
||||
|
||||
test('extracts code from fragment when query lacks code', () => {
|
||||
const url = 'https://app.example.com/cb#code=fromHash&state=xyz';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBe('fromHash');
|
||||
});
|
||||
|
||||
test('returns null if no code present (query or fragment)', () => {
|
||||
const url = 'https://app.example.com/cb?state=only';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBeNull();
|
||||
});
|
||||
|
||||
test('returns null when provider reports an error', () => {
|
||||
const url = 'https://app.example.com/cb?error=access_denied&error_description=oopsy';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(() => extractCode(url, redirect)).toThrow('Failed to authorize: access_denied');
|
||||
});
|
||||
|
||||
test('when redirectUri is null, extracts code from any URL', () => {
|
||||
expect(extractCode('https://random.example.com/whatever?code=abc', null)).toBe('abc');
|
||||
});
|
||||
|
||||
test('handles extra params gracefully', () => {
|
||||
const url = 'https://app.example.com/cb?foo=1&bar=2&code=abc&baz=3';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBe('abc');
|
||||
});
|
||||
|
||||
test('ignores fragment noise when code is in query', () => {
|
||||
const url = 'https://app.example.com/cb?code=abc#some=thing';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBe('abc');
|
||||
});
|
||||
|
||||
// If you decide NOT to support fragment-based codes, flip these to expect null or mark as .skip
|
||||
test('supports fragment-only code for response_mode=fragment providers', () => {
|
||||
const url = 'https://app.example.com/cb#state=xyz&code=abc';
|
||||
const redirect = 'https://app.example.com/cb';
|
||||
expect(extractCode(url, redirect)).toBe('abc');
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsonpath-plus": "^10.3.0"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xmldom/xmldom": "^0.9.8",
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint": "tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
},
|
||||
"dependencies": {
|
||||
"shell-quote": "^1.8.1"
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
},
|
||||
"dependencies": {
|
||||
"yaml": "^2.4.2"
|
||||
|
||||
@@ -30,18 +30,25 @@ export function convertInsomniaV5(parsed: any) {
|
||||
model: 'workspace',
|
||||
name: parsed.name,
|
||||
description: meta.description || undefined,
|
||||
...importHeaders(parsed),
|
||||
...importAuthentication(parsed),
|
||||
});
|
||||
|
||||
// Import environments
|
||||
resources.environments.push(
|
||||
importEnvironment(parsed.environments, meta.id, true),
|
||||
...(parsed.environments.subEnvironments ?? []).map((r: any) => importEnvironment(r, meta.id)),
|
||||
);
|
||||
|
||||
// Import folders
|
||||
const nextFolder = (children: any[], parentId: string) => {
|
||||
for (const child of children ?? []) {
|
||||
if (!isJSObject(child)) continue;
|
||||
|
||||
if (Array.isArray(child.children)) {
|
||||
resources.folders.push(importFolder(child, meta.id, parentId));
|
||||
const { folder, environment } = importFolder(child, meta.id, parentId);
|
||||
resources.folders.push(folder);
|
||||
if (environment) resources.environments.push(environment);
|
||||
nextFolder(child.children, child.meta.id);
|
||||
} else if (child.method) {
|
||||
resources.httpRequests.push(importHttpRequest(child, meta.id, parentId));
|
||||
@@ -191,8 +198,8 @@ function importWebsocketRequest(
|
||||
};
|
||||
}
|
||||
|
||||
function importHeaders(r: any) {
|
||||
const headers = (r.headers ?? [])
|
||||
function importHeaders(obj: any) {
|
||||
const headers = (obj.headers ?? [])
|
||||
.map((h: any) => ({
|
||||
enabled: !h.disabled,
|
||||
name: h.name ?? '',
|
||||
@@ -202,19 +209,19 @@ function importHeaders(r: any) {
|
||||
return { headers } as const;
|
||||
}
|
||||
|
||||
function importAuthentication(r: any) {
|
||||
function importAuthentication(obj: any) {
|
||||
let authenticationType: string | null = null;
|
||||
let authentication = {};
|
||||
if (r.authentication?.type === 'bearer') {
|
||||
if (obj.authentication?.type === 'bearer') {
|
||||
authenticationType = 'bearer';
|
||||
authentication = {
|
||||
token: convertSyntax(r.authentication.token),
|
||||
token: convertSyntax(obj.authentication.token),
|
||||
};
|
||||
} else if (r.authentication?.type === 'basic') {
|
||||
} else if (obj.authentication?.type === 'basic') {
|
||||
authenticationType = 'basic';
|
||||
authentication = {
|
||||
username: convertSyntax(r.authentication.username),
|
||||
password: convertSyntax(r.authentication.password),
|
||||
username: convertSyntax(obj.authentication.username),
|
||||
password: convertSyntax(obj.authentication.password),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -225,22 +232,50 @@ function importFolder(
|
||||
f: any,
|
||||
workspaceId: string,
|
||||
parentId: string,
|
||||
): PartialImportResources['folders'][0] {
|
||||
): {
|
||||
folder: PartialImportResources['folders'][0];
|
||||
environment: PartialImportResources['environments'][0] | null;
|
||||
} {
|
||||
const id = f.meta?.id ?? f._id;
|
||||
const created = f.meta?.created ?? f.created;
|
||||
const updated = f.meta?.modified ?? f.updated;
|
||||
const sortKey = f.meta?.sortKey ?? f.sortKey;
|
||||
|
||||
let environment: PartialImportResources['environments'][0] | null = null;
|
||||
if (Object.keys(f.environment ?? {}).length > 0) {
|
||||
environment = {
|
||||
id: convertId(id + 'folder'),
|
||||
createdAt: created ? new Date(created).toISOString().replace('Z', '') : undefined,
|
||||
updatedAt: updated ? new Date(updated).toISOString().replace('Z', '') : undefined,
|
||||
workspaceId: convertId(workspaceId),
|
||||
public: true,
|
||||
parentModel: 'folder',
|
||||
parentId: convertId(id),
|
||||
model: 'environment',
|
||||
name: 'Folder Environment',
|
||||
variables: Object.entries(f.environment ?? {}).map(([name, value]) => ({
|
||||
enabled: true,
|
||||
name,
|
||||
value: `${value}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
model: 'folder',
|
||||
id: convertId(id),
|
||||
createdAt: created ? new Date(created).toISOString().replace('Z', '') : undefined,
|
||||
updatedAt: updated ? new Date(updated).toISOString().replace('Z', '') : undefined,
|
||||
folderId: parentId === workspaceId ? null : convertId(parentId),
|
||||
sortPriority: sortKey,
|
||||
workspaceId: convertId(workspaceId),
|
||||
description: f.description || undefined,
|
||||
name: f.name,
|
||||
folder: {
|
||||
model: 'folder',
|
||||
id: convertId(id),
|
||||
createdAt: created ? new Date(created).toISOString().replace('Z', '') : undefined,
|
||||
updatedAt: updated ? new Date(updated).toISOString().replace('Z', '') : undefined,
|
||||
folderId: parentId === workspaceId ? null : convertId(parentId),
|
||||
sortPriority: sortKey,
|
||||
workspaceId: convertId(workspaceId),
|
||||
description: f.description || undefined,
|
||||
name: f.name,
|
||||
...importAuthentication(f),
|
||||
...importHeaders(f),
|
||||
},
|
||||
environment,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -263,7 +298,8 @@ function importEnvironment(
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
sortPriority: sortKey, // Will be added to Yaak later
|
||||
base: isParent ?? e.parentId === workspaceId,
|
||||
parentModel: isParent ? 'workspace' : 'environment',
|
||||
parentId: null,
|
||||
model: 'environment',
|
||||
name: e.name,
|
||||
variables: Object.entries(e.data ?? {}).map(([name, value]) => ({
|
||||
|
||||
@@ -38,6 +38,8 @@ collection:
|
||||
name: foo
|
||||
value: bar
|
||||
disabled: false
|
||||
environment:
|
||||
folder_env_var: testing
|
||||
- name: New Request
|
||||
meta:
|
||||
id: req_e3f8cdbd58784a539dd4c1e127d73451
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"resources": {
|
||||
"environments": [
|
||||
{
|
||||
"base": true,
|
||||
"createdAt": "2025-05-14T04:45:24.903",
|
||||
"id": "GENERATE_ID::env_e46dc73e8ccda30ca132153e8f11183bd08119ce",
|
||||
"model": "environment",
|
||||
@@ -10,6 +9,26 @@
|
||||
"public": true,
|
||||
"updatedAt": "2025-05-14T04:45:24.903",
|
||||
"variables": [],
|
||||
"workspaceId": "GENERATE_ID::wrk_9717dd1c9e0c4b2e9ed6d2abcf3bd45c",
|
||||
"parentId": null,
|
||||
"parentModel": "workspace"
|
||||
},
|
||||
{
|
||||
"createdAt": "2025-05-16T16:48:12.298",
|
||||
"id": "GENERATE_ID::fld_296933ea4ea84783a775d199997e9be7folder",
|
||||
"model": "environment",
|
||||
"name": "Folder Environment",
|
||||
"parentId": "GENERATE_ID::fld_296933ea4ea84783a775d199997e9be7",
|
||||
"parentModel": "folder",
|
||||
"public": true,
|
||||
"updatedAt": "2025-05-16T16:49:02.427",
|
||||
"variables": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "folder_env_var",
|
||||
"value": "testing"
|
||||
}
|
||||
],
|
||||
"workspaceId": "GENERATE_ID::wrk_9717dd1c9e0c4b2e9ed6d2abcf3bd45c"
|
||||
}
|
||||
],
|
||||
@@ -22,7 +41,16 @@
|
||||
"name": "My Folder",
|
||||
"sortPriority": -1747414092298,
|
||||
"updatedAt": "2025-05-16T16:49:02.427",
|
||||
"workspaceId": "GENERATE_ID::wrk_9717dd1c9e0c4b2e9ed6d2abcf3bd45c"
|
||||
"workspaceId": "GENERATE_ID::wrk_9717dd1c9e0c4b2e9ed6d2abcf3bd45c",
|
||||
"authentication": {},
|
||||
"authenticationType": null,
|
||||
"headers": [
|
||||
{
|
||||
"enabled": true,
|
||||
"name": "foo",
|
||||
"value": "bar"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"grpcRequests": [],
|
||||
@@ -80,7 +108,10 @@
|
||||
"id": "GENERATE_ID::wrk_9717dd1c9e0c4b2e9ed6d2abcf3bd45c",
|
||||
"model": "workspace",
|
||||
"name": "Debugging",
|
||||
"updatedAt": "2025-05-14T04:45:24.902"
|
||||
"updatedAt": "2025-05-14T04:45:24.902",
|
||||
"authentication": {},
|
||||
"authenticationType": null,
|
||||
"headers": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
{
|
||||
"createdAt": "2025-01-13T15:15:43.767",
|
||||
"updatedAt": "2025-01-13T15:15:55.209",
|
||||
"base": true,
|
||||
"public": true,
|
||||
"id": "GENERATE_ID::env_20945044d3c8497ca8b717bef750987e",
|
||||
"model": "environment",
|
||||
"name": "Base Environment",
|
||||
"parentId": null,
|
||||
"parentModel": "workspace",
|
||||
"variables": [
|
||||
{
|
||||
"enabled": true,
|
||||
@@ -21,11 +22,12 @@
|
||||
{
|
||||
"createdAt": "2025-01-13T15:15:58.515",
|
||||
"updatedAt": "2025-01-13T15:16:34.705",
|
||||
"base": false,
|
||||
"public": true,
|
||||
"id": "GENERATE_ID::env_6f7728bb7fc04d558d668e954d756ea2",
|
||||
"model": "environment",
|
||||
"name": "Production",
|
||||
"parentId": null,
|
||||
"parentModel": "environment",
|
||||
"sortPriority": 1736781358515,
|
||||
"variables": [
|
||||
{
|
||||
@@ -39,8 +41,9 @@
|
||||
{
|
||||
"createdAt": "2025-01-13T15:16:14.707",
|
||||
"updatedAt": "2025-01-13T15:16:31.078",
|
||||
"base": false,
|
||||
"public": true,
|
||||
"parentId": null,
|
||||
"parentModel": "environment",
|
||||
"id": "GENERATE_ID::env_976a8b6eb5d44fb6a20150f65c32d243",
|
||||
"model": "environment",
|
||||
"name": "Staging",
|
||||
@@ -64,7 +67,10 @@
|
||||
"model": "folder",
|
||||
"name": "Top Level",
|
||||
"sortPriority": -1736781404718,
|
||||
"workspaceId": "GENERATE_ID::wrk_c1eacfa750a04f3ea9985ef28043fa53"
|
||||
"workspaceId": "GENERATE_ID::wrk_c1eacfa750a04f3ea9985ef28043fa53",
|
||||
"authentication": {},
|
||||
"authenticationType": null,
|
||||
"headers": []
|
||||
}
|
||||
],
|
||||
"grpcRequests": [
|
||||
@@ -165,7 +171,10 @@
|
||||
"description": "This is the description",
|
||||
"id": "GENERATE_ID::wrk_c1eacfa750a04f3ea9985ef28043fa53",
|
||||
"model": "workspace",
|
||||
"name": "Dummy"
|
||||
"name": "Dummy",
|
||||
"authentication": {},
|
||||
"authenticationType": null,
|
||||
"headers": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
},
|
||||
"dependencies": {
|
||||
"openapi-to-postmanv2": "^5.0.0",
|
||||
|
||||
14
plugins/importer-postman-environment/package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@yaak/importer-postman-environment",
|
||||
"displayName": "Postman Environment Importer",
|
||||
"description": "Import environments from Postman",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"main": "./build/index.js",
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
138
plugins/importer-postman-environment/src/index.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import type {
|
||||
Context,
|
||||
Environment,
|
||||
PartialImportResources,
|
||||
PluginDefinition,
|
||||
Workspace,
|
||||
} from '@yaakapp/api';
|
||||
import type { ImportPluginResponse } from '@yaakapp/api/lib/plugins/ImporterPlugin';
|
||||
|
||||
type AtLeast<T, K extends keyof T> = Partial<T> & Pick<T, K>;
|
||||
|
||||
interface ExportResources {
|
||||
workspaces: AtLeast<Workspace, 'name' | 'id' | 'model'>[];
|
||||
environments: AtLeast<Environment, 'name' | 'id' | 'model' | 'workspaceId'>[];
|
||||
}
|
||||
|
||||
export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: 'Postman Environment',
|
||||
description: 'Import postman environment exports',
|
||||
onImport(_ctx: Context, args: { text: string }) {
|
||||
return convertPostmanEnvironment(args.text);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function convertPostmanEnvironment(contents: string): ImportPluginResponse | undefined {
|
||||
const root = parseJSONToRecord(contents);
|
||||
if (root == null) return;
|
||||
|
||||
// Validate that it looks like a Postman Environment export
|
||||
const values = toArray<{
|
||||
key?: string;
|
||||
value?: unknown;
|
||||
enabled?: boolean;
|
||||
description?: string;
|
||||
type?: string;
|
||||
}>(root.values);
|
||||
const scope = root._postman_variable_scope;
|
||||
const hasEnvMarkers = typeof scope === 'string';
|
||||
|
||||
if (values.length === 0 || (!hasEnvMarkers && typeof root.name !== 'string')) {
|
||||
// Not a Postman environment file, skip
|
||||
return;
|
||||
}
|
||||
|
||||
const exportResources: ExportResources = {
|
||||
workspaces: [],
|
||||
environments: [],
|
||||
};
|
||||
|
||||
const envVariables = values
|
||||
.map((v) => ({
|
||||
enabled: v.enabled ?? true,
|
||||
name: String(v.key ?? ''),
|
||||
value: String(v.value),
|
||||
description: v.description ? String(v.description) : null,
|
||||
}))
|
||||
.filter((v) => v.name.length > 0);
|
||||
|
||||
const environment: ExportResources['environments'][0] = {
|
||||
model: 'environment',
|
||||
id: generateId('environment'),
|
||||
name: root.name ? String(root.name) : 'Environment',
|
||||
workspaceId: 'CURRENT_WORKSPACE',
|
||||
parentModel: 'environment',
|
||||
parentId: null,
|
||||
variables: envVariables,
|
||||
};
|
||||
exportResources.environments.push(environment);
|
||||
|
||||
const resources = deleteUndefinedAttrs(
|
||||
convertTemplateSyntax(exportResources),
|
||||
) as PartialImportResources;
|
||||
|
||||
return { resources };
|
||||
}
|
||||
|
||||
function parseJSONToRecord<T>(jsonStr: string): Record<string, T> | null {
|
||||
try {
|
||||
return toRecord(JSON.parse(jsonStr));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function toRecord<T>(value: Record<string, T> | unknown): Record<string, T> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
return value as Record<string, T>;
|
||||
}
|
||||
return {} as Record<string, T>;
|
||||
}
|
||||
|
||||
function toArray<T>(value: unknown): T[] {
|
||||
if (Object.prototype.toString.call(value) === '[object Array]') return value as T[];
|
||||
else return [] as T[];
|
||||
}
|
||||
|
||||
/** Recursively render all nested object properties */
|
||||
function convertTemplateSyntax<T>(obj: T): T {
|
||||
if (typeof obj === 'string') {
|
||||
return obj.replace(
|
||||
/{{\s*(_\.)?([^}]*)\s*}}/g,
|
||||
(_m, _dot, expr) => '${[' + expr.trim() + ']}',
|
||||
) as T;
|
||||
} else if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(convertTemplateSyntax) as T;
|
||||
} else if (typeof obj === 'object' && obj != null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj as Record<string, unknown>).map(([k, v]) => [k, convertTemplateSyntax(v)]),
|
||||
) as T;
|
||||
} else {
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteUndefinedAttrs<T>(obj: T): T {
|
||||
if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(deleteUndefinedAttrs) as T;
|
||||
} else if (typeof obj === 'object' && obj != null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj as Record<string, unknown>)
|
||||
.filter(([, v]) => v !== undefined)
|
||||
.map(([k, v]) => [k, deleteUndefinedAttrs(v)]),
|
||||
) as T;
|
||||
} else {
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
const idCount: Partial<Record<string, number>> = {};
|
||||
|
||||
function generateId(model: string): string {
|
||||
idCount[model] = (idCount[model] ?? -1) + 1;
|
||||
return `GENERATE_ID::${model.toUpperCase()}_${idCount[model]}`;
|
||||
}
|
||||
|
||||
export default plugin;
|
||||
27
plugins/importer-postman-environment/tests/fixtures/environment.input.json
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"id": "123",
|
||||
"name": "My Environment",
|
||||
"values": [
|
||||
{
|
||||
"key": "baseUrl",
|
||||
"value": "https://api.example.com",
|
||||
"type": "default",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"key": "token",
|
||||
"value": "{{ access_token }}",
|
||||
"type": "default",
|
||||
"description": "Access token for the API.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"key": "disabled",
|
||||
"type": "secret",
|
||||
"value": "hello",
|
||||
"enabled": false
|
||||
}
|
||||
],
|
||||
"_postman_variable_scope": "environment",
|
||||
"_postman_exported_using": "PostmanRuntime/1.0.0"
|
||||
}
|
||||
35
plugins/importer-postman-environment/tests/fixtures/environment.output.json
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"resources": {
|
||||
"workspaces": [],
|
||||
"environments": [
|
||||
{
|
||||
"id": "GENERATE_ID::ENVIRONMENT_0",
|
||||
"model": "environment",
|
||||
"name": "My Environment",
|
||||
"variables": [
|
||||
{
|
||||
"enabled": true,
|
||||
"description": null,
|
||||
"name": "baseUrl",
|
||||
"value": "https://api.example.com"
|
||||
},
|
||||
{
|
||||
"enabled": true,
|
||||
"description": "Access token for the API.",
|
||||
"name": "token",
|
||||
"value": "${[access_token]}"
|
||||
},
|
||||
{
|
||||
"enabled": false,
|
||||
"description": null,
|
||||
"name": "disabled",
|
||||
"value": "hello"
|
||||
}
|
||||
],
|
||||
"workspaceId": "CURRENT_WORKSPACE",
|
||||
"parentId": null,
|
||||
"parentModel": "environment"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
22
plugins/importer-postman-environment/tests/index.test.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { convertPostmanEnvironment } from '../src';
|
||||
|
||||
describe('importer-postman-environment', () => {
|
||||
const p = path.join(__dirname, 'fixtures');
|
||||
const fixtures = fs.readdirSync(p);
|
||||
|
||||
for (const fixture of fixtures) {
|
||||
if (fixture.includes('.output')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
test('Imports ' + fixture, () => {
|
||||
const contents = fs.readFileSync(path.join(p, fixture), 'utf-8');
|
||||
const expected = fs.readFileSync(path.join(p, fixture.replace('.input', '.output')), 'utf-8');
|
||||
const result = convertPostmanEnvironment(contents);
|
||||
expect(result).toEqual(JSON.parse(expected));
|
||||
});
|
||||
}
|
||||
});
|
||||
3
plugins/importer-postman-environment/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json"
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint": "tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,9 +57,11 @@ export function convertPostman(contents: string): ImportPluginResponse | undefin
|
||||
|
||||
const rawDescription = info.description;
|
||||
const description =
|
||||
typeof rawDescription === 'object' && rawDescription !== null && 'content' in rawDescription
|
||||
typeof rawDescription === 'object' && rawDescription != null && 'content' in rawDescription
|
||||
? String(rawDescription.content)
|
||||
: String(rawDescription);
|
||||
: rawDescription == null
|
||||
? undefined
|
||||
: String(rawDescription);
|
||||
|
||||
const workspace: ExportResources['workspaces'][0] = {
|
||||
model: 'workspace',
|
||||
@@ -75,6 +77,8 @@ export function convertPostman(contents: string): ImportPluginResponse | undefin
|
||||
id: generateId('environment'),
|
||||
name: 'Global Variables',
|
||||
workspaceId: workspace.id,
|
||||
parentModel: 'workspace',
|
||||
parentId: null,
|
||||
variables:
|
||||
toArray<{ key: string; value: string }>(root.variable).map((v) => ({
|
||||
name: v.key,
|
||||
@@ -372,7 +376,7 @@ function toArray<T>(value: unknown): T[] {
|
||||
/** Recursively render all nested object properties */
|
||||
function convertTemplateSyntax<T>(obj: T): T {
|
||||
if (typeof obj === 'string') {
|
||||
return obj.replace(/{{\s*(_\.)?([^}]+)\s*}}/g, '${[$2]}') as T;
|
||||
return obj.replace(/{{\s*(_\.)?([^}]*)\s*}}/g, (_m, _dot, expr) => '${[' + expr.trim() + ']}') as T;
|
||||
} else if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(convertTemplateSyntax) as T;
|
||||
} else if (typeof obj === 'object' && obj != null) {
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
"model": "environment",
|
||||
"name": "Global Variables",
|
||||
"variables": [],
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_0"
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_0",
|
||||
"parentId": null,
|
||||
"parentModel": "workspace"
|
||||
}
|
||||
],
|
||||
"httpRequests": [
|
||||
@@ -25,6 +27,7 @@
|
||||
"name": "Request 1",
|
||||
"method": "GET",
|
||||
"url": "",
|
||||
"sortPriority": 2,
|
||||
"urlParameters": [],
|
||||
"body": {},
|
||||
"bodyType": null,
|
||||
@@ -39,6 +42,7 @@
|
||||
"folderId": "GENERATE_ID::FOLDER_0",
|
||||
"name": "Request 2",
|
||||
"method": "GET",
|
||||
"sortPriority": 3,
|
||||
"url": "",
|
||||
"urlParameters": [],
|
||||
"body": {},
|
||||
@@ -52,6 +56,7 @@
|
||||
"id": "GENERATE_ID::HTTP_REQUEST_2",
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_0",
|
||||
"folderId": null,
|
||||
"sortPriority": 4,
|
||||
"name": "Request 3",
|
||||
"method": "GET",
|
||||
"url": "",
|
||||
@@ -69,6 +74,7 @@
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_0",
|
||||
"id": "GENERATE_ID::FOLDER_0",
|
||||
"name": "Top Folder",
|
||||
"sortPriority": 0,
|
||||
"folderId": null
|
||||
},
|
||||
{
|
||||
@@ -76,6 +82,7 @@
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_0",
|
||||
"id": "GENERATE_ID::FOLDER_1",
|
||||
"name": "Nested Folder",
|
||||
"sortPriority": 1,
|
||||
"folderId": "GENERATE_ID::FOLDER_0"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_1",
|
||||
"model": "environment",
|
||||
"name": "Global Variables",
|
||||
"parentId": null,
|
||||
"parentModel": "workspace",
|
||||
"variables": [
|
||||
{
|
||||
"name": "COLLECTION VARIABLE",
|
||||
@@ -28,6 +30,7 @@
|
||||
"workspaceId": "GENERATE_ID::WORKSPACE_1",
|
||||
"folderId": null,
|
||||
"name": "Form URL",
|
||||
"sortPriority": 0,
|
||||
"method": "POST",
|
||||
"url": "example.com/:foo/:bar",
|
||||
"urlParameters": [
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,20 @@ export function migrateImport(contents: string) {
|
||||
}
|
||||
}
|
||||
|
||||
return { resources: parsed.resources }; // Should already be in the correct format
|
||||
// Migrate v4 to v5
|
||||
for (const environment of parsed.resources.environments ?? []) {
|
||||
if ('base' in environment && environment.base && environment.parentModel == null) {
|
||||
environment.parentModel = 'workspace';
|
||||
environment.parentId = null;
|
||||
delete environment.base;
|
||||
} else if ('base' in environment && !environment.base && environment.parentModel == null) {
|
||||
environment.parentModel = 'environment';
|
||||
environment.parentId = null;
|
||||
delete environment.base;
|
||||
}
|
||||
}
|
||||
|
||||
return { resources: parsed.resources };
|
||||
}
|
||||
|
||||
function isJSObject(obj: unknown) {
|
||||
|
||||
@@ -31,16 +31,20 @@ describe('importer-yaak', () => {
|
||||
JSON.stringify({
|
||||
yaakSchema: 2,
|
||||
resources: {
|
||||
environments: [{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Production',
|
||||
variables: [{ name: 'E1', value: 'E1!' }],
|
||||
}],
|
||||
workspaces: [{
|
||||
id: 'w_1',
|
||||
variables: [{ name: 'W1', value: 'W1!' }],
|
||||
}],
|
||||
environments: [
|
||||
{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Production',
|
||||
variables: [{ name: 'E1', value: 'E1!' }],
|
||||
},
|
||||
],
|
||||
workspaces: [
|
||||
{
|
||||
id: 'w_1',
|
||||
variables: [{ name: 'W1', value: 'W1!' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -48,21 +52,98 @@ describe('importer-yaak', () => {
|
||||
expect(imported).toEqual(
|
||||
expect.objectContaining({
|
||||
resources: {
|
||||
workspaces: [{
|
||||
id: 'w_1',
|
||||
}],
|
||||
environments: [{
|
||||
id: 'e_1',
|
||||
base: false,
|
||||
workspaceId: 'w_1',
|
||||
name: 'Production',
|
||||
variables: [{ name: 'E1', value: 'E1!' }],
|
||||
}, {
|
||||
id: 'GENERATE_ID::base_env_w_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Global Variables',
|
||||
variables: [{ name: 'W1', value: 'W1!' }],
|
||||
}],
|
||||
workspaces: [
|
||||
{
|
||||
id: 'w_1',
|
||||
},
|
||||
],
|
||||
environments: [
|
||||
{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Production',
|
||||
variables: [{ name: 'E1', value: 'E1!' }],
|
||||
parentModel: 'environment',
|
||||
parentId: null,
|
||||
},
|
||||
{
|
||||
id: 'GENERATE_ID::base_env_w_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Global Variables',
|
||||
variables: [{ name: 'W1', value: 'W1!' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('converts schema 4 to 5', () => {
|
||||
const imported = migrateImport(
|
||||
JSON.stringify({
|
||||
yaakSchema: 2,
|
||||
resources: {
|
||||
environments: [
|
||||
{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
base: false,
|
||||
name: 'Production',
|
||||
variables: [{ name: 'E1', value: 'E1!' }],
|
||||
},
|
||||
{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
base: true,
|
||||
name: 'Global Variables',
|
||||
variables: [{ name: 'G1', value: 'G1!' }],
|
||||
},
|
||||
],
|
||||
folders: [
|
||||
{
|
||||
id: 'f_1',
|
||||
},
|
||||
],
|
||||
workspaces: [
|
||||
{
|
||||
id: 'w_1',
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(imported).toEqual(
|
||||
expect.objectContaining({
|
||||
resources: {
|
||||
workspaces: [
|
||||
{
|
||||
id: 'w_1',
|
||||
},
|
||||
],
|
||||
folders: [
|
||||
{
|
||||
id: 'f_1',
|
||||
},
|
||||
],
|
||||
environments: [
|
||||
{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Production',
|
||||
variables: [{ name: 'E1', value: 'E1!' }],
|
||||
parentModel: 'environment',
|
||||
parentId: null,
|
||||
},
|
||||
{
|
||||
id: 'e_1',
|
||||
workspaceId: 'w_1',
|
||||
name: 'Global Variables',
|
||||
parentModel: 'workspace',
|
||||
parentId: null,
|
||||
variables: [{ name: 'G1', value: 'G1!' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,39 @@
|
||||
import type { CallTemplateFunctionArgs, Context, PluginDefinition } from '@yaakapp/api';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const options = [
|
||||
{ label: 'ASCII', value: 'ascii' },
|
||||
{ label: 'UTF-8', value: 'utf8' },
|
||||
{ label: 'UTF-16 LE', value: 'utf16le' },
|
||||
{ label: 'Base64', value: 'base64' },
|
||||
{ label: 'Base64 URL-safe', value: 'base64url' },
|
||||
{ label: 'Latin-1', value: 'latin1' },
|
||||
{ label: 'Hexadecimal', value: 'hex' },
|
||||
];
|
||||
export const plugin: PluginDefinition = {
|
||||
templateFunctions: [
|
||||
{
|
||||
name: 'fs.readFile',
|
||||
description: 'Read the contents of a file as utf-8',
|
||||
args: [{ title: 'Select File', type: 'file', name: 'path', label: 'File' }],
|
||||
args: [
|
||||
{ title: 'Select File', type: 'file', name: 'path', label: 'File' },
|
||||
{
|
||||
title: 'Select encoding',
|
||||
type: 'select',
|
||||
name: 'encoding',
|
||||
label: 'Encoding',
|
||||
defaultValue: 'utf8',
|
||||
description: 'Specifies how the file’s bytes are decoded into text when read',
|
||||
options,
|
||||
},
|
||||
],
|
||||
async onRender(_ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
||||
if (!args.values.path) return null;
|
||||
if (!args.values.path || !args.values.encoding) return null;
|
||||
|
||||
try {
|
||||
return fs.promises.readFile(String(args.values.path ?? ''), 'utf-8');
|
||||
return fs.promises.readFile(String(args.values.path ?? ''), {
|
||||
encoding: String(args.values.encoding ?? 'utf-8') as BufferEncoding,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsonpath-plus": "^10.3.0"
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HttpUrlParameter } from '@yaakapp-internal/models';
|
||||
import type { AnyModel, HttpUrlParameter } from '@yaakapp-internal/models';
|
||||
import type { CallTemplateFunctionArgs, Context, PluginDefinition } from '@yaakapp/api';
|
||||
|
||||
export const plugin: PluginDefinition = {
|
||||
@@ -96,5 +96,59 @@ export const plugin: PluginDefinition = {
|
||||
return renderedValue;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'request.name',
|
||||
args: [
|
||||
{
|
||||
name: 'requestId',
|
||||
label: 'Http Request',
|
||||
type: 'http_request',
|
||||
},
|
||||
],
|
||||
async onRender(ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
||||
const requestId = String(args.values.requestId ?? 'n/a');
|
||||
const httpRequest = await ctx.httpRequest.getById({ id: requestId });
|
||||
if (httpRequest == null) return null;
|
||||
|
||||
return resolvedModelName(httpRequest);
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// TODO: Use a common function for this, but it fails to build on windows during CI if I try importing it here
|
||||
export function resolvedModelName(r: AnyModel | null): string {
|
||||
if (r == null) return '';
|
||||
|
||||
if (!('url' in r) || r.model === 'plugin') {
|
||||
return 'name' in r ? r.name : '';
|
||||
}
|
||||
|
||||
// Return name if it has one
|
||||
if ('name' in r && r.name) {
|
||||
return r.name;
|
||||
}
|
||||
|
||||
// Replace variable syntax with variable name
|
||||
const withoutVariables = r.url.replace(/\$\{\[\s*([^\]\s]+)\s*]}/g, '$1');
|
||||
if (withoutVariables.trim() === '') {
|
||||
return r.model === 'http_request'
|
||||
? r.bodyType && r.bodyType === 'graphql'
|
||||
? 'GraphQL Request'
|
||||
: 'HTTP Request'
|
||||
: r.model === 'websocket_request'
|
||||
? 'WebSocket Request'
|
||||
: 'gRPC Request';
|
||||
}
|
||||
|
||||
// GRPC gets nice short names
|
||||
if (r.model === 'grpc_request' && r.service != null && r.method != null) {
|
||||
const shortService = r.service.split('.').pop();
|
||||
return `${shortService}/${r.method}`;
|
||||
}
|
||||
|
||||
// Strip unnecessary protocol
|
||||
const withoutProto = withoutVariables.replace(/^(http|https|ws|wss):\/\//, '');
|
||||
|
||||
return withoutProto;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsonpath-plus": "^10.3.0",
|
||||
|
||||
@@ -3,25 +3,44 @@ import type {
|
||||
CallTemplateFunctionArgs,
|
||||
Context,
|
||||
FormInput,
|
||||
GetHttpAuthenticationConfigRequest,
|
||||
HttpResponse,
|
||||
PluginDefinition,
|
||||
RenderPurpose,
|
||||
} from '@yaakapp/api';
|
||||
import type { DynamicTemplateFunctionArg } from '@yaakapp/api/lib/plugins/TemplateFunctionPlugin';
|
||||
import { JSONPath } from 'jsonpath-plus';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import xpath from 'xpath';
|
||||
|
||||
const BEHAVIOR_TTL = 'ttl';
|
||||
const BEHAVIOR_ALWAYS = 'always';
|
||||
const BEHAVIOR_SMART = 'smart';
|
||||
|
||||
const behaviorArg: FormInput = {
|
||||
type: 'select',
|
||||
name: 'behavior',
|
||||
label: 'Sending Behavior',
|
||||
defaultValue: 'smart',
|
||||
options: [
|
||||
{ label: 'When no responses', value: 'smart' },
|
||||
{ label: 'Always', value: 'always' },
|
||||
{ label: 'When no responses', value: BEHAVIOR_SMART },
|
||||
{ label: 'Always', value: BEHAVIOR_ALWAYS },
|
||||
{ label: 'When expired', value: BEHAVIOR_TTL },
|
||||
],
|
||||
};
|
||||
|
||||
const ttlArg: DynamicTemplateFunctionArg = {
|
||||
type: 'text',
|
||||
name: 'ttl',
|
||||
label: 'Expiration Time (seconds)',
|
||||
placeholder: '0',
|
||||
description: 'Resend the request when the latest response is older than this many seconds, or if there are no responses yet.',
|
||||
dynamic(_ctx: Context, { values }: GetHttpAuthenticationConfigRequest) {
|
||||
const show = values.behavior === BEHAVIOR_TTL;
|
||||
return { hidden: !show };
|
||||
},
|
||||
};
|
||||
|
||||
const requestArg: FormInput = {
|
||||
type: 'http_request',
|
||||
name: 'request',
|
||||
@@ -42,6 +61,7 @@ export const plugin: PluginDefinition = {
|
||||
placeholder: 'Content-Type',
|
||||
},
|
||||
behaviorArg,
|
||||
ttlArg,
|
||||
],
|
||||
async onRender(ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
||||
if (!args.values.request || !args.values.header) return null;
|
||||
@@ -50,6 +70,7 @@ export const plugin: PluginDefinition = {
|
||||
requestId: String(args.values.request || ''),
|
||||
purpose: args.purpose,
|
||||
behavior: args.values.behavior ? String(args.values.behavior) : null,
|
||||
ttl: String(args.values.ttl || ''),
|
||||
});
|
||||
if (response == null) return null;
|
||||
|
||||
@@ -72,6 +93,7 @@ export const plugin: PluginDefinition = {
|
||||
placeholder: '$.books[0].id or /books[0]/id',
|
||||
},
|
||||
behaviorArg,
|
||||
ttlArg,
|
||||
],
|
||||
async onRender(ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
||||
if (!args.values.request || !args.values.path) return null;
|
||||
@@ -80,6 +102,7 @@ export const plugin: PluginDefinition = {
|
||||
requestId: String(args.values.request || ''),
|
||||
purpose: args.purpose,
|
||||
behavior: args.values.behavior ? String(args.values.behavior) : null,
|
||||
ttl: String(args.values.ttl || ''),
|
||||
});
|
||||
if (response == null) return null;
|
||||
|
||||
@@ -113,7 +136,7 @@ export const plugin: PluginDefinition = {
|
||||
name: 'response.body.raw',
|
||||
description: 'Access the entire response body, as text',
|
||||
aliases: ['response'],
|
||||
args: [requestArg, behaviorArg],
|
||||
args: [requestArg, behaviorArg, ttlArg],
|
||||
async onRender(ctx: Context, args: CallTemplateFunctionArgs): Promise<string | null> {
|
||||
if (!args.values.request) return null;
|
||||
|
||||
@@ -121,6 +144,7 @@ export const plugin: PluginDefinition = {
|
||||
requestId: String(args.values.request || ''),
|
||||
purpose: args.purpose,
|
||||
behavior: args.values.behavior ? String(args.values.behavior) : null,
|
||||
ttl: String(args.values.ttl || ''),
|
||||
});
|
||||
if (response == null) return null;
|
||||
|
||||
@@ -177,9 +201,11 @@ async function getResponse(
|
||||
requestId,
|
||||
behavior,
|
||||
purpose,
|
||||
ttl,
|
||||
}: {
|
||||
requestId: string;
|
||||
behavior: string | null;
|
||||
ttl: string | null;
|
||||
purpose: RenderPurpose;
|
||||
},
|
||||
): Promise<HttpResponse | null> {
|
||||
@@ -203,7 +229,11 @@ async function getResponse(
|
||||
const finalBehavior = behavior === 'always' && purpose === 'preview' ? 'smart' : behavior;
|
||||
|
||||
// Send if no responses and "smart," or "always"
|
||||
if ((finalBehavior === 'smart' && response == null) || finalBehavior === 'always') {
|
||||
if (
|
||||
(finalBehavior === 'smart' && response == null) ||
|
||||
finalBehavior === 'always' ||
|
||||
(finalBehavior === BEHAVIOR_TTL && shouldSendExpired(response, ttl))
|
||||
) {
|
||||
// NOTE: Render inside this conditional, or we'll get infinite recursion (render->render->...)
|
||||
const renderedHttpRequest = await ctx.httpRequest.render({ httpRequest, purpose });
|
||||
response = await ctx.httpRequest.send({ httpRequest: renderedHttpRequest });
|
||||
@@ -211,3 +241,12 @@ async function getResponse(
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
function shouldSendExpired(response: HttpResponse | null, ttl: string | null): boolean {
|
||||
if (response == null) return true;
|
||||
const ttlSeconds = parseInt(ttl || '0');
|
||||
if (isNaN(ttlSeconds)) throw new Error(`Invalid TTL "${ttl}"`);
|
||||
const nowMillis = Date.now();
|
||||
const respMillis = new Date(response.createdAt + 'Z').getTime();
|
||||
return respMillis + ttlSeconds * 1000 < nowMillis;
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint": "tsc --noEmit && eslint . --ext .ts,.tsx",
|
||||
"test": "vitest --run tests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@date-fns/tz": "^1.4.1",
|
||||
"date-fns": "^4.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { TemplateFunctionArg } from '@yaakapp-internal/plugins';
|
||||
import type { PluginDefinition } from '@yaakapp/api';
|
||||
|
||||
import type { ContextFn } from 'date-fns';
|
||||
import {
|
||||
addDays,
|
||||
addHours,
|
||||
@@ -24,7 +25,8 @@ const dateArg: TemplateFunctionArg = {
|
||||
name: 'date',
|
||||
label: 'Timestamp',
|
||||
optional: true,
|
||||
description: 'Can be a timestamp in milliseconds, ISO string, or anything parseable by JS `new Date()`',
|
||||
description:
|
||||
'Can be a timestamp in milliseconds, ISO string, or anything parseable by JS `new Date()`',
|
||||
placeholder: new Date().toISOString(),
|
||||
};
|
||||
|
||||
@@ -148,8 +150,12 @@ export function calculateDatetime(args: { date?: string; expression?: string }):
|
||||
return jsDate.toISOString();
|
||||
}
|
||||
|
||||
export function formatDatetime(args: { date?: string; format?: string }): string {
|
||||
const { date, format = 'yyyy-MM-dd HH:mm:ss' } = args;
|
||||
export function formatDatetime(args: {
|
||||
date?: string;
|
||||
format?: string;
|
||||
in?: ContextFn<Date>;
|
||||
}): string {
|
||||
const { date, format } = args;
|
||||
const d = parseDateString(date ?? '');
|
||||
return formatDate(d, String(format));
|
||||
return formatDate(d, String(format || 'yyyy-MM-dd HH:mm:ss'), { in: args.in });
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { calculateDatetime, formatDatetime } from '../src';
|
||||
import { tz } from "@date-fns/tz";
|
||||
|
||||
describe('formatDatetime', () => {
|
||||
it('returns formatted current date', () => {
|
||||
@@ -13,12 +14,12 @@ describe('formatDatetime', () => {
|
||||
});
|
||||
|
||||
it('returns formatted specific timestamp', () => {
|
||||
const result = formatDatetime({ date: '1752435296000' });
|
||||
const result = formatDatetime({ date: '1752435296000', in: tz('America/Vancouver') });
|
||||
expect(result).toBe('2025-07-13 12:34:56');
|
||||
});
|
||||
|
||||
it('returns formatted specific timestamp with decimals', () => {
|
||||
const result = formatDatetime({ date: '1752435296000.19' });
|
||||
const result = formatDatetime({ date: '1752435296000.19', in: tz('America/Vancouver') });
|
||||
expect(result).toBe('2025-07-13 12:34:56');
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"uuid": "^11.1.0"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xmldom/xmldom": "^0.9.8",
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"lint": "eslint . --ext .ts,.tsx"
|
||||
"lint":"tsc --noEmit && eslint . --ext .ts,.tsx"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,49 @@ import type { PluginDefinition } from '@yaakapp/api';
|
||||
|
||||
export const plugin: PluginDefinition = {
|
||||
themes: [
|
||||
{
|
||||
id: 'high-contrast',
|
||||
label: 'High Contrast Light',
|
||||
dark: false,
|
||||
base: {
|
||||
surface: 'white',
|
||||
surfaceHighlight: 'hsl(218,24%,93%)',
|
||||
text: 'black',
|
||||
textSubtle: 'hsl(217,24%,40%)',
|
||||
textSubtlest: 'hsl(217,24%,40%)',
|
||||
border: 'hsl(217,22%,50%)',
|
||||
borderSubtle: 'hsl(217,22%,60%)',
|
||||
primary: 'hsl(267,67%,47%)',
|
||||
secondary: 'hsl(218,18%,53%)',
|
||||
info: 'hsl(206,100%,36%)',
|
||||
success: 'hsl(155,100%,26%)',
|
||||
notice: 'hsl(45,100%,31%)',
|
||||
warning: 'hsl(30,99%,34%)',
|
||||
danger: 'hsl(334,100%,35%)',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'high-contrast-dark',
|
||||
label: 'High Contrast Dark',
|
||||
dark: true,
|
||||
base: {
|
||||
surface: 'hsl(0,0%,0%)',
|
||||
surfaceHighlight: 'hsl(0,0%,20%)',
|
||||
text: 'hsl(0,0%,100%)',
|
||||
textSubtle: 'hsl(0,0%,90%)',
|
||||
textSubtlest: 'hsl(0,0%,80%)',
|
||||
selection: 'hsl(276,100%,30%)',
|
||||
surfaceActive: 'hsl(276,100%,30%)',
|
||||
border: 'hsl(0,0%,60%)',
|
||||
primary: 'hsl(266,100%,85%)',
|
||||
secondary: 'hsl(242,20%,72%)',
|
||||
info: 'hsl(208,100%,83%)',
|
||||
success: 'hsl(150,100%,63%)',
|
||||
notice: 'hsl(49,100%,77%)',
|
||||
warning: 'hsl(28,100%,73%)',
|
||||
danger: 'hsl(343,100%,79%)',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'catppuccin-frappe',
|
||||
label: 'Catppuccin Frappé',
|
||||
@@ -595,5 +638,112 @@ export const plugin: PluginDefinition = {
|
||||
danger: 'hsl(343,81%,75%)',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'rose-pine',
|
||||
label: 'Rosé Pine',
|
||||
dark: true,
|
||||
base: {
|
||||
surface: 'hsl(249,22%,12%)',
|
||||
text: 'hsl(245,50%,91%)',
|
||||
textSubtle: 'hsl(248,15%,61%)',
|
||||
textSubtlest: 'hsl(249,12%,47%)',
|
||||
primary: 'hsl(267,57%,78%)',
|
||||
secondary: 'hsl(249,12%,47%)',
|
||||
info: 'hsl(199,49%,60%)',
|
||||
success: 'hsl(180,43%,73%)',
|
||||
notice: 'hsl(35,88%,72%)',
|
||||
warning: 'hsl(1,74%,79%)',
|
||||
danger: 'hsl(343,76%,68%)',
|
||||
},
|
||||
components: {
|
||||
responsePane: {
|
||||
surface: 'hsl(247,23%,15%)',
|
||||
},
|
||||
sidebar: {
|
||||
surface: 'hsl(247,23%,15%)',
|
||||
},
|
||||
menu: {
|
||||
surface: 'hsl(248,21%,26%)',
|
||||
textSubtle: 'hsl(248,15%,66%)',
|
||||
textSubtlest: 'hsl(249,12%,52%)',
|
||||
border: 'hsl(248,21%,35%)',
|
||||
borderSubtle: 'hsl(248,21%,33%)',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'rose-pine-moon',
|
||||
label: 'Rosé Pine Moon',
|
||||
dark: true,
|
||||
base: {
|
||||
surface: 'hsl(246,24%,17%)',
|
||||
text: 'hsl(245,50%,91%)',
|
||||
textSubtle: 'hsl(248,15%,61%)',
|
||||
textSubtlest: 'hsl(249,12%,47%)',
|
||||
primary: 'hsl(267,57%,78%)',
|
||||
secondary: 'hsl(248,15%,61%)',
|
||||
info: 'hsl(197,48%,60%)',
|
||||
success: 'hsl(197,48%,60%)',
|
||||
notice: 'hsl(35,88%,72%)',
|
||||
warning: 'hsl(2,66%,75%)',
|
||||
danger: 'hsl(343,76%,68%)',
|
||||
},
|
||||
components: {
|
||||
responsePane: {
|
||||
surface: 'hsl(247,24%,20%)',
|
||||
},
|
||||
sidebar: {
|
||||
surface: 'hsl(247,24%,20%)',
|
||||
},
|
||||
menu: {
|
||||
surface: 'hsl(248,21%,26%)',
|
||||
textSubtle: 'hsl(248,15%,61%)',
|
||||
textSubtlest: 'hsl(249,12%,55%)',
|
||||
border: 'hsl(248,21%,35%)',
|
||||
borderSubtle: 'hsl(248,21%,31%)',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'rose-pine-dawn',
|
||||
label: 'Rosé Pine Dawn',
|
||||
dark: false,
|
||||
base: {
|
||||
surface: 'hsl(32,57%,95%)',
|
||||
border: 'hsl(10,9%,86%)',
|
||||
surfaceHighlight: 'hsl(25,35%,93%)',
|
||||
text: 'hsl(248,19%,40%)',
|
||||
textSubtle: 'hsl(248,12%,52%)',
|
||||
textSubtlest: 'hsl(257,9%,61%)',
|
||||
primary: 'hsl(271,27%,56%)',
|
||||
secondary: 'hsl(249,12%,47%)',
|
||||
info: 'hsl(197,52%,36%)',
|
||||
success: 'hsl(188,31%,45%)',
|
||||
notice: 'hsl(34,64%,49%)',
|
||||
warning: 'hsl(2,47%,64%)',
|
||||
danger: 'hsl(343,35%,55%)',
|
||||
},
|
||||
components: {
|
||||
responsePane: {
|
||||
border: 'hsl(20,12%,90%)',
|
||||
},
|
||||
sidebar: {
|
||||
border: 'hsl(20,12%,90%)',
|
||||
},
|
||||
appHeader: {
|
||||
border: 'hsl(20,12%,90%)',
|
||||
},
|
||||
input: {
|
||||
border: 'hsl(10,9%,86%)',
|
||||
},
|
||||
dialog: {
|
||||
border: 'hsl(20,12%,90%)',
|
||||
},
|
||||
menu: {
|
||||
surface: 'hsl(28,40%,92%)',
|
||||
border: 'hsl(10,9%,86%)',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
619
src-tauri/Cargo.lock
generated
@@ -32,42 +32,46 @@ strip = true # Automatically strip symbols from the binary.
|
||||
|
||||
[features]
|
||||
cargo-clippy = []
|
||||
default = []
|
||||
updater = []
|
||||
license = ["yaak-license"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.2.0", features = [] }
|
||||
tauri-build = { version = "2.5.0", features = [] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
openssl-sys = { version = "0.9.105", features = ["vendored"] } # For Ubuntu installation to work
|
||||
|
||||
[dependencies]
|
||||
charset = "0.1.5"
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
cookie = "0.18.1"
|
||||
encoding_rs = "0.8.35"
|
||||
eventsource-client = { git = "https://github.com/yaakapp/rust-eventsource-client", version = "0.14.0" }
|
||||
http = { version = "1.2.0", default-features = false }
|
||||
log = "0.4.27"
|
||||
md5 = "0.8.0"
|
||||
mime_guess = "2.0.5"
|
||||
rand = "0.9.0"
|
||||
reqwest = { workspace = true, features = ["multipart", "cookies", "gzip", "brotli", "deflate", "json", "rustls-tls-manual-roots-no-provider", "socks"] }
|
||||
reqwest = { workspace = true, features = ["multipart", "cookies", "gzip", "brotli", "deflate", "json", "rustls-tls-manual-roots-no-provider", "socks", "http2"] }
|
||||
reqwest_cookie_store = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true, features = ["raw_value"] }
|
||||
tauri = { workspace = true, features = ["devtools", "protocol-asset"] }
|
||||
tauri-plugin-clipboard-manager = "2.3.0"
|
||||
tauri-plugin-deep-link = "2.4.3"
|
||||
tauri-plugin-dialog = { workspace = true }
|
||||
tauri-plugin-fs = "2.4.0"
|
||||
tauri-plugin-log = { version = "2.6.0", features = ["colored"] }
|
||||
tauri-plugin-opener = "2.4.0"
|
||||
tauri-plugin-os = "2.3.0"
|
||||
tauri-plugin-fs = "2.4.2"
|
||||
tauri-plugin-log = { version = "2.7.0", features = ["colored"] }
|
||||
tauri-plugin-opener = "2.5.0"
|
||||
tauri-plugin-os = "2.3.1"
|
||||
tauri-plugin-shell = { workspace = true }
|
||||
tauri-plugin-deep-link = "2.4.0"
|
||||
tauri-plugin-single-instance = { version = "2.3.0", features = ["deep-link"] }
|
||||
tauri-plugin-single-instance = { version = "2.3.4", features = ["deep-link"] }
|
||||
tauri-plugin-updater = "2.9.0"
|
||||
tauri-plugin-window-state = "2.3.0"
|
||||
tauri-plugin-window-state = "2.4.0"
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
tokio-stream = "0.1.17"
|
||||
ts-rs = { workspace = true }
|
||||
uuid = "1.12.1"
|
||||
yaak-common = { workspace = true }
|
||||
yaak-crypto = { workspace = true }
|
||||
@@ -75,7 +79,7 @@ yaak-fonts = { workspace = true }
|
||||
yaak-git = { path = "yaak-git" }
|
||||
yaak-grpc = { path = "yaak-grpc" }
|
||||
yaak-http = { workspace = true }
|
||||
yaak-license = { path = "yaak-license" }
|
||||
yaak-license = { path = "yaak-license", optional = true }
|
||||
yaak-mac-window = { path = "yaak-mac-window" }
|
||||
yaak-models = { workspace = true }
|
||||
yaak-plugins = { workspace = true }
|
||||
@@ -85,22 +89,23 @@ yaak-templates = { workspace = true }
|
||||
yaak-ws = { path = "yaak-ws" }
|
||||
|
||||
[workspace.dependencies]
|
||||
chrono = "0.4.41"
|
||||
chrono = "0.4.42"
|
||||
hex = "0.4.3"
|
||||
keyring = "3.6.3"
|
||||
reqwest = "0.12.20"
|
||||
serde = "1.0.219"
|
||||
serde_json = "1.0.140"
|
||||
tauri = "2.6.2"
|
||||
tauri-plugin = "2.3.0"
|
||||
tauri-plugin-dialog = "2.3.0"
|
||||
tauri-plugin-shell = "2.3.0"
|
||||
tokio = "1.45.1"
|
||||
thiserror = "2.0.12"
|
||||
ts-rs = "11.0.1"
|
||||
reqwest_cookie_store = "0.8.0"
|
||||
rustls = { version = "0.23.27", default-features = false }
|
||||
rustls-platform-verifier = "0.6.0"
|
||||
rustls = { version = "0.23.33", default-features = false }
|
||||
rustls-platform-verifier = "0.6.1"
|
||||
serde = "1.0.228"
|
||||
serde_json = "1.0.145"
|
||||
sha2 = "0.10.9"
|
||||
tauri = "2.9.0"
|
||||
tauri-plugin = "2.5.0"
|
||||
tauri-plugin-dialog = "2.4.0"
|
||||
tauri-plugin-shell = "2.3.1"
|
||||
thiserror = "2.0.17"
|
||||
tokio = "1.48.0"
|
||||
ts-rs = "11.1.0"
|
||||
yaak-common = { path = "yaak-common" }
|
||||
yaak-crypto = { path = "yaak-crypto" }
|
||||
yaak-fonts = { path = "yaak-fonts" }
|
||||
|
||||
11
src-tauri/bindings/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type UpdateInfo = { replyEventId: string, version: string, downloaded: boolean, };
|
||||
|
||||
export type UpdateResponse = { "type": "ack" } | { "type": "action", action: UpdateResponseAction, };
|
||||
|
||||
export type UpdateResponseAction = "install" | "skip";
|
||||
|
||||
export type YaakNotification = { timestamp: string, timeout: number | null, id: string, title: string | null, message: string, color: string | null, action: YaakNotificationAction | null, };
|
||||
|
||||
export type YaakNotificationAction = { label: string, url: string, };
|
||||
@@ -1,8 +1,6 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/capabilities.json",
|
||||
"identifier": "main",
|
||||
"description": "Main permissions",
|
||||
"local": true,
|
||||
"identifier": "default",
|
||||
"description": "Default capabilities for all build variants",
|
||||
"windows": [
|
||||
"*"
|
||||
],
|
||||
@@ -11,6 +9,7 @@
|
||||
"core:event:allow-emit",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-unlisten",
|
||||
"core:path:allow-resolve-directory",
|
||||
"os:allow-os-type",
|
||||
"clipboard-manager:allow-clear",
|
||||
"clipboard-manager:allow-write-text",
|
||||
@@ -54,7 +53,6 @@
|
||||
"yaak-crypto:default",
|
||||
"yaak-fonts:default",
|
||||
"yaak-git:default",
|
||||
"yaak-license:default",
|
||||
"yaak-mac-window:default",
|
||||
"yaak-models:default",
|
||||
"yaak-plugins:default",
|
||||
BIN
src-tauri/icons/dev/64x64.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 21 KiB |
BIN
src-tauri/icons/release/64x64.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 51 KiB |
6
src-tauri/package.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "@yaakapp-internal/tauri",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"main": "bindings/index.ts"
|
||||
}
|
||||
@@ -1,16 +1,27 @@
|
||||
use encoding_rs::SHIFT_JIS;
|
||||
use log::debug;
|
||||
use mime_guess::{Mime, mime};
|
||||
use std::path::Path;
|
||||
use std::str::FromStr;
|
||||
use tokio::fs;
|
||||
use yaak_models::models::HttpResponse;
|
||||
|
||||
pub async fn read_response_body<'a>(
|
||||
response: HttpResponse,
|
||||
) -> Option<String> {
|
||||
let body_path = match response.body_path {
|
||||
None => return None,
|
||||
Some(p) => p,
|
||||
};
|
||||
pub async fn read_response_body(body_path: impl AsRef<Path>, content_type: &str) -> Option<String> {
|
||||
let body = fs::read(body_path).await.ok()?;
|
||||
let body_charset = parse_charset(content_type).unwrap_or("utf-8".to_string());
|
||||
debug!("body_charset: {}", body_charset);
|
||||
if let Some(decoder) = charset::Charset::for_label(body_charset.as_bytes()) {
|
||||
debug!("Using decoder for charset: {}", body_charset);
|
||||
let (cow, real_encoding, exist_replace) = decoder.decode(&body);
|
||||
debug!(
|
||||
"Decoded body with charset: {}, real_encoding: {:?}, exist_replace: {}",
|
||||
body_charset, real_encoding, exist_replace
|
||||
);
|
||||
return cow.into_owned().into();
|
||||
}
|
||||
|
||||
let body = fs::read(body_path).await.unwrap();
|
||||
let (s, _, _) = SHIFT_JIS.decode(body.as_slice());
|
||||
Some(s.to_string())
|
||||
Some(String::from_utf8_lossy(&body).to_string())
|
||||
}
|
||||
|
||||
fn parse_charset(content_type: &str) -> Option<String> {
|
||||
let mime: Mime = Mime::from_str(content_type).ok()?;
|
||||
mime.get_param(mime::CHARSET).map(|v| v.to_string())
|
||||
}
|
||||
|
||||
@@ -19,9 +19,13 @@ pub enum Error {
|
||||
#[error(transparent)]
|
||||
GitError(#[from] yaak_git::error::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
TokioTimeoutElapsed(#[from] tokio::time::error::Elapsed),
|
||||
|
||||
#[error(transparent)]
|
||||
WebsocketError(#[from] yaak_ws::error::Error),
|
||||
|
||||
#[cfg(feature = "license")]
|
||||
#[error(transparent)]
|
||||
LicenseError(#[from] yaak_license::error::Error),
|
||||
|
||||
@@ -31,6 +35,9 @@ pub enum Error {
|
||||
#[error(transparent)]
|
||||
CommonError(#[from] yaak_common::error::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
ClipboardError(#[from] tauri_plugin_clipboard_manager::Error),
|
||||
|
||||
#[error("Updater error: {0}")]
|
||||
UpdaterError(#[from] tauri_plugin_updater::Error),
|
||||
|
||||
|
||||
@@ -1,48 +1,74 @@
|
||||
use chrono::{NaiveDateTime, Utc};
|
||||
use log::debug;
|
||||
use std::sync::OnceLock;
|
||||
use tauri::{AppHandle, Runtime};
|
||||
use yaak_models::query_manager::QueryManagerExt;
|
||||
use yaak_models::util::UpdateSource;
|
||||
|
||||
const NAMESPACE: &str = "analytics";
|
||||
const NUM_LAUNCHES_KEY: &str = "num_launches";
|
||||
const LAST_VERSION_KEY: &str = "last_tracked_version";
|
||||
const PREV_VERSION_KEY: &str = "last_tracked_version_prev";
|
||||
const VERSION_SINCE_KEY: &str = "last_tracked_version_since";
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct LaunchEventInfo {
|
||||
pub current_version: String,
|
||||
pub previous_version: String,
|
||||
pub launched_after_update: bool,
|
||||
pub version_since: NaiveDateTime,
|
||||
pub user_since: NaiveDateTime,
|
||||
pub num_launches: i32,
|
||||
}
|
||||
|
||||
pub async fn store_launch_history<R: Runtime>(app_handle: &AppHandle<R>) -> LaunchEventInfo {
|
||||
let last_tracked_version_key = "last_tracked_version";
|
||||
static LAUNCH_INFO: OnceLock<LaunchEventInfo> = OnceLock::new();
|
||||
|
||||
let mut info = LaunchEventInfo::default();
|
||||
pub fn get_or_upsert_launch_info<R: Runtime>(app_handle: &AppHandle<R>) -> &LaunchEventInfo {
|
||||
LAUNCH_INFO.get_or_init(|| {
|
||||
let now = Utc::now().naive_utc();
|
||||
let mut info = LaunchEventInfo {
|
||||
version_since: app_handle.db().get_key_value_dte(NAMESPACE, VERSION_SINCE_KEY, now),
|
||||
current_version: app_handle.package_info().version.to_string(),
|
||||
user_since: app_handle.db().get_settings().created_at,
|
||||
num_launches: app_handle.db().get_key_value_int(NAMESPACE, NUM_LAUNCHES_KEY, 0) + 1,
|
||||
|
||||
info.num_launches = get_num_launches(app_handle).await + 1;
|
||||
info.current_version = app_handle.package_info().version.to_string();
|
||||
// The rest will be set below
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
app_handle
|
||||
.with_tx(|tx| {
|
||||
info.previous_version =
|
||||
tx.get_key_value_string(NAMESPACE, last_tracked_version_key, "");
|
||||
app_handle
|
||||
.with_tx(|tx| {
|
||||
// Load the previously tracked version
|
||||
let curr_db = tx.get_key_value_str(NAMESPACE, LAST_VERSION_KEY, "");
|
||||
let prev_db = tx.get_key_value_str(NAMESPACE, PREV_VERSION_KEY, "");
|
||||
|
||||
if !info.previous_version.is_empty() {
|
||||
info.launched_after_update = info.current_version != info.previous_version;
|
||||
};
|
||||
// We just updated if the app version is different from the last tracked version we stored
|
||||
if !curr_db.is_empty() && info.current_version != curr_db {
|
||||
info.launched_after_update = true;
|
||||
}
|
||||
|
||||
// Update key values
|
||||
// If we just updated, track the previous version as the "previous" current version
|
||||
if info.launched_after_update {
|
||||
info.previous_version = curr_db.clone();
|
||||
info.version_since = now;
|
||||
} else {
|
||||
info.previous_version = prev_db.clone();
|
||||
}
|
||||
|
||||
let source = &UpdateSource::Background;
|
||||
let version = info.current_version.as_str();
|
||||
tx.set_key_value_string(NAMESPACE, last_tracked_version_key, version, source);
|
||||
tx.set_key_value_int(NAMESPACE, NUM_LAUNCHES_KEY, info.num_launches, source);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Rotate stored versions: move previous into the "prev" slot before overwriting
|
||||
let source = &UpdateSource::Background;
|
||||
|
||||
info
|
||||
}
|
||||
|
||||
pub async fn get_num_launches<R: Runtime>(app_handle: &AppHandle<R>) -> i32 {
|
||||
app_handle.db().get_key_value_int(NAMESPACE, NUM_LAUNCHES_KEY, 0)
|
||||
tx.set_key_value_str(NAMESPACE, PREV_VERSION_KEY, &info.previous_version, source);
|
||||
tx.set_key_value_str(NAMESPACE, LAST_VERSION_KEY, &info.current_version, source);
|
||||
tx.set_key_value_dte(NAMESPACE, VERSION_SINCE_KEY, info.version_since, source);
|
||||
tx.set_key_value_int(NAMESPACE, NUM_LAUNCHES_KEY, info.num_launches, source);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
debug!("Initialized launch info");
|
||||
|
||||
info
|
||||
})
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ use yaak_plugins::events::{
|
||||
};
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||
use yaak_templates::{RenderErrorBehavior, RenderOptions};
|
||||
|
||||
pub async fn send_http_request<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
@@ -43,14 +44,14 @@ pub async fn send_http_request<R: Runtime>(
|
||||
) -> Result<HttpResponse> {
|
||||
let app_handle = window.app_handle().clone();
|
||||
let plugin_manager = app_handle.state::<PluginManager>();
|
||||
let (settings, workspace) = {
|
||||
let db = window.db();
|
||||
let settings = db.get_settings();
|
||||
let workspace = db.get_workspace(&unrendered_request.workspace_id)?;
|
||||
(settings, workspace)
|
||||
};
|
||||
let base_environment =
|
||||
app_handle.db().get_base_environment(&unrendered_request.workspace_id)?;
|
||||
let settings = window.db().get_settings();
|
||||
let workspace = window.db().get_workspace(&unrendered_request.workspace_id)?;
|
||||
let environment_id = environment.map(|e| e.id);
|
||||
let environment_chain = window.db().resolve_environments(
|
||||
&unrendered_request.workspace_id,
|
||||
unrendered_request.folder_id.as_deref(),
|
||||
environment_id.as_deref(),
|
||||
)?;
|
||||
|
||||
let response_id = og_response.id.clone();
|
||||
let response = Arc::new(Mutex::new(og_response.clone()));
|
||||
@@ -76,20 +77,21 @@ pub async fn send_http_request<R: Runtime>(
|
||||
RenderPurpose::Send,
|
||||
);
|
||||
|
||||
let request =
|
||||
match render_http_request(&resolved_request, &base_environment, environment.as_ref(), &cb)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return Ok(response_err(
|
||||
&app_handle,
|
||||
&*response.lock().await,
|
||||
e.to_string(),
|
||||
&update_source,
|
||||
));
|
||||
}
|
||||
};
|
||||
let opt = RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
};
|
||||
|
||||
let request = match render_http_request(&resolved_request, environment_chain, &cb, &opt).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return Ok(response_err(
|
||||
&app_handle,
|
||||
&*response.lock().await,
|
||||
e.to_string(),
|
||||
&update_source,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut url_string = request.url.clone();
|
||||
|
||||
@@ -111,7 +113,7 @@ pub async fn send_http_request<R: Runtime>(
|
||||
.referer(false)
|
||||
.tls_info(true);
|
||||
|
||||
let tls_config = yaak_http::tls::get_config(workspace.setting_validate_certificates);
|
||||
let tls_config = yaak_http::tls::get_config(workspace.setting_validate_certificates, true);
|
||||
client_builder = client_builder.use_preconfigured_tls(tls_config);
|
||||
|
||||
match settings.proxy {
|
||||
|
||||
@@ -28,7 +28,7 @@ pub(crate) async fn import_data<R: Runtime>(
|
||||
.workspaces
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.id = maybe_gen_id::<Workspace>(v.id.as_str(), &mut id_map);
|
||||
v.id = maybe_gen_id::<Workspace, R>(window, v.id.as_str(), &mut id_map);
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -37,8 +37,22 @@ pub(crate) async fn import_data<R: Runtime>(
|
||||
.environments
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.id = maybe_gen_id::<Environment>(v.id.as_str(), &mut id_map);
|
||||
v.workspace_id = maybe_gen_id::<Workspace>(v.workspace_id.as_str(), &mut id_map);
|
||||
v.id = maybe_gen_id::<Environment, R>(window, v.id.as_str(), &mut id_map);
|
||||
v.workspace_id =
|
||||
maybe_gen_id::<Workspace, R>(window, v.workspace_id.as_str(), &mut id_map);
|
||||
match (v.parent_model.as_str(), v.parent_id.clone().as_deref()) {
|
||||
("folder", Some(parent_id)) => {
|
||||
v.parent_id = Some(maybe_gen_id::<Folder, R>(window, &parent_id, &mut id_map));
|
||||
}
|
||||
("", _) => {
|
||||
// Fix any empty ones
|
||||
v.parent_model = "workspace".to_string();
|
||||
}
|
||||
_ => {
|
||||
// Parent ID only required for the folder case
|
||||
v.parent_id = None;
|
||||
}
|
||||
};
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -47,9 +61,10 @@ pub(crate) async fn import_data<R: Runtime>(
|
||||
.folders
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.id = maybe_gen_id::<Folder>(v.id.as_str(), &mut id_map);
|
||||
v.workspace_id = maybe_gen_id::<Workspace>(v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder>(v.folder_id, &mut id_map);
|
||||
v.id = maybe_gen_id::<Folder, R>(window, v.id.as_str(), &mut id_map);
|
||||
v.workspace_id =
|
||||
maybe_gen_id::<Workspace, R>(window, v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder, R>(window, v.folder_id, &mut id_map);
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -58,9 +73,10 @@ pub(crate) async fn import_data<R: Runtime>(
|
||||
.http_requests
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.id = maybe_gen_id::<HttpRequest>(v.id.as_str(), &mut id_map);
|
||||
v.workspace_id = maybe_gen_id::<Workspace>(v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder>(v.folder_id, &mut id_map);
|
||||
v.id = maybe_gen_id::<HttpRequest, R>(window, v.id.as_str(), &mut id_map);
|
||||
v.workspace_id =
|
||||
maybe_gen_id::<Workspace, R>(window, v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder, R>(window, v.folder_id, &mut id_map);
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -69,9 +85,10 @@ pub(crate) async fn import_data<R: Runtime>(
|
||||
.grpc_requests
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.id = maybe_gen_id::<GrpcRequest>(v.id.as_str(), &mut id_map);
|
||||
v.workspace_id = maybe_gen_id::<Workspace>(v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder>(v.folder_id, &mut id_map);
|
||||
v.id = maybe_gen_id::<GrpcRequest, R>(window, v.id.as_str(), &mut id_map);
|
||||
v.workspace_id =
|
||||
maybe_gen_id::<Workspace, R>(window, v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder, R>(window, v.folder_id, &mut id_map);
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -80,9 +97,10 @@ pub(crate) async fn import_data<R: Runtime>(
|
||||
.websocket_requests
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.id = maybe_gen_id::<WebsocketRequest>(v.id.as_str(), &mut id_map);
|
||||
v.workspace_id = maybe_gen_id::<Workspace>(v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder>(v.folder_id, &mut id_map);
|
||||
v.id = maybe_gen_id::<WebsocketRequest, R>(window, v.id.as_str(), &mut id_map);
|
||||
v.workspace_id =
|
||||
maybe_gen_id::<Workspace, R>(window, v.workspace_id.as_str(), &mut id_map);
|
||||
v.folder_id = maybe_gen_id_opt::<Folder, R>(window, v.folder_id, &mut id_map);
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
extern crate core;
|
||||
use crate::encoding::read_response_body;
|
||||
use crate::error::Error::GenericError;
|
||||
use crate::error::Result;
|
||||
use crate::grpc::{build_metadata, metadata_to_map, resolve_grpc_request};
|
||||
use crate::http_request::{resolve_http_request, send_http_request};
|
||||
use crate::import::import_data;
|
||||
@@ -26,28 +27,24 @@ use tauri_plugin_log::{Builder, Target, TargetKind};
|
||||
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::block_in_place;
|
||||
use tokio::time;
|
||||
use yaak_common::window::WorkspaceWindowTrait;
|
||||
use yaak_grpc::manager::{DynamicMessage, GrpcHandle};
|
||||
use yaak_grpc::{Code, ServiceDefinition, deserialize_message, serialize_message};
|
||||
use yaak_models::models::{
|
||||
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent, GrpcEventType,
|
||||
GrpcRequest, HttpRequest, HttpResponse, HttpResponseState, Plugin, Workspace, WorkspaceMeta,
|
||||
AnyModel, CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent,
|
||||
GrpcEventType, GrpcRequest, HttpRequest, HttpResponse, HttpResponseState, Plugin, Workspace,
|
||||
WorkspaceMeta,
|
||||
};
|
||||
use yaak_models::query_manager::QueryManagerExt;
|
||||
use yaak_models::util::{BatchUpsertResult, UpdateSource, get_workspace_export_resources};
|
||||
use yaak_plugins::events::{
|
||||
CallGrpcRequestActionArgs, CallGrpcRequestActionRequest, CallHttpRequestActionArgs,
|
||||
CallHttpRequestActionRequest, Color, FilterResponse, GetGrpcRequestActionsResponse,
|
||||
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse,
|
||||
GetHttpRequestActionsResponse, GetTemplateFunctionsResponse, InternalEvent,
|
||||
InternalEventPayload, JsonPrimitive, PluginWindowContext, RenderPurpose, ShowToastRequest,
|
||||
};
|
||||
use yaak_plugins::events::{CallGrpcRequestActionArgs, CallGrpcRequestActionRequest, CallHttpRequestActionArgs, CallHttpRequestActionRequest, Color, FilterResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse, GetTemplateFunctionSummaryResponse, GetTemplateFunctionConfigResponse, InternalEvent, InternalEventPayload, JsonPrimitive, PluginWindowContext, RenderPurpose, ShowToastRequest};
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
use yaak_plugins::plugin_meta::PluginMetadata;
|
||||
use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||
use yaak_sse::sse::ServerSentEvent;
|
||||
use yaak_templates::format::format_json;
|
||||
use yaak_templates::{Tokens, transform_args};
|
||||
use yaak_templates::{RenderErrorBehavior, RenderOptions, Tokens, transform_args};
|
||||
|
||||
mod commands;
|
||||
mod encoding;
|
||||
@@ -72,6 +69,8 @@ struct AppMetaData {
|
||||
name: String,
|
||||
app_data_dir: String,
|
||||
app_log_dir: String,
|
||||
feature_updater: bool,
|
||||
feature_license: bool,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -84,6 +83,8 @@ async fn cmd_metadata(app_handle: AppHandle) -> YaakResult<AppMetaData> {
|
||||
name: app_handle.package_info().name.to_string(),
|
||||
app_data_dir: app_data_dir.to_string_lossy().to_string(),
|
||||
app_log_dir: app_log_dir.to_string_lossy().to_string(),
|
||||
feature_license: cfg!(feature = "license"),
|
||||
feature_updater: cfg!(feature = "updater"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -110,20 +111,19 @@ async fn cmd_render_template<R: Runtime>(
|
||||
workspace_id: &str,
|
||||
environment_id: Option<&str>,
|
||||
) -> YaakResult<String> {
|
||||
let environment = match environment_id {
|
||||
Some(id) => app_handle.db().get_environment(id).ok(),
|
||||
None => None,
|
||||
};
|
||||
let base_environment = app_handle.db().get_base_environment(&workspace_id)?;
|
||||
let environment_chain =
|
||||
app_handle.db().resolve_environments(workspace_id, None, environment_id)?;
|
||||
let result = render_template(
|
||||
template,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
environment_chain,
|
||||
&PluginTemplateCallback::new(
|
||||
&app_handle,
|
||||
&PluginWindowContext::new(&window),
|
||||
RenderPurpose::Preview,
|
||||
),
|
||||
&RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(result)
|
||||
@@ -147,26 +147,27 @@ async fn cmd_grpc_reflect<R: Runtime>(
|
||||
app_handle: AppHandle<R>,
|
||||
grpc_handle: State<'_, Mutex<GrpcHandle>>,
|
||||
) -> YaakResult<Vec<ServiceDefinition>> {
|
||||
let environment = match environment_id {
|
||||
Some(id) => app_handle.db().get_environment(id).ok(),
|
||||
None => None,
|
||||
};
|
||||
let unrendered_request = app_handle.db().get_grpc_request(request_id)?;
|
||||
let (resolved_request, auth_context_id) = resolve_grpc_request(&window, &unrendered_request)?;
|
||||
|
||||
let base_environment =
|
||||
app_handle.db().get_base_environment(&unrendered_request.workspace_id)?;
|
||||
let environment_chain = app_handle.db().resolve_environments(
|
||||
&unrendered_request.workspace_id,
|
||||
unrendered_request.folder_id.as_deref(),
|
||||
environment_id,
|
||||
)?;
|
||||
let workspace = app_handle.db().get_workspace(&unrendered_request.workspace_id)?;
|
||||
|
||||
let req = render_grpc_request(
|
||||
&resolved_request,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
environment_chain,
|
||||
&PluginTemplateCallback::new(
|
||||
&app_handle,
|
||||
&PluginWindowContext::new(&window),
|
||||
RenderPurpose::Send,
|
||||
),
|
||||
&RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -196,25 +197,26 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
grpc_handle: State<'_, Mutex<GrpcHandle>>,
|
||||
) -> YaakResult<String> {
|
||||
let environment = match environment_id {
|
||||
Some(id) => app_handle.db().get_environment(id).ok(),
|
||||
None => None,
|
||||
};
|
||||
let unrendered_request = app_handle.db().get_grpc_request(request_id)?;
|
||||
let (resolved_request, auth_context_id) = resolve_grpc_request(&window, &unrendered_request)?;
|
||||
let base_environment =
|
||||
app_handle.db().get_base_environment(&unrendered_request.workspace_id)?;
|
||||
let environment_chain = app_handle.db().resolve_environments(
|
||||
&unrendered_request.workspace_id,
|
||||
unrendered_request.folder_id.as_deref(),
|
||||
environment_id,
|
||||
)?;
|
||||
let workspace = app_handle.db().get_workspace(&unrendered_request.workspace_id)?;
|
||||
|
||||
let request = render_grpc_request(
|
||||
&resolved_request,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
environment_chain.clone(),
|
||||
&PluginTemplateCallback::new(
|
||||
&app_handle,
|
||||
&PluginWindowContext::new(&window),
|
||||
RenderPurpose::Send,
|
||||
),
|
||||
&RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -300,9 +302,8 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let cb = {
|
||||
let cancelled_rx = cancelled_rx.clone();
|
||||
let app_handle = app_handle.clone();
|
||||
let environment_chain = environment_chain.clone();
|
||||
let window = window.clone();
|
||||
let base_environment = base_environment.clone();
|
||||
let environment = environment.clone();
|
||||
let base_msg = base_msg.clone();
|
||||
let method_desc = method_desc.clone();
|
||||
|
||||
@@ -327,17 +328,20 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let app_handle = app_handle.clone();
|
||||
let base_msg = base_msg.clone();
|
||||
let method_desc = method_desc.clone();
|
||||
let environment_chain = environment_chain.clone();
|
||||
let msg = block_in_place(|| {
|
||||
tauri::async_runtime::block_on(async {
|
||||
render_template(
|
||||
msg.as_str(),
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
environment_chain,
|
||||
&PluginTemplateCallback::new(
|
||||
&app_handle,
|
||||
&PluginWindowContext::new(&window),
|
||||
RenderPurpose::Send,
|
||||
),
|
||||
&RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("Failed to render template")
|
||||
@@ -396,17 +400,20 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
let window = window.clone();
|
||||
let app_handle = app_handle.clone();
|
||||
let base_event = base_msg.clone();
|
||||
let environment_chain = environment_chain.clone();
|
||||
let req = request.clone();
|
||||
let msg = if req.message.is_empty() { "{}".to_string() } else { req.message };
|
||||
let msg = render_template(
|
||||
msg.as_str(),
|
||||
&base_environment.clone(),
|
||||
environment.as_ref(),
|
||||
environment_chain,
|
||||
&PluginTemplateCallback::new(
|
||||
&app_handle,
|
||||
&PluginWindowContext::new(&window),
|
||||
RenderPurpose::Send,
|
||||
),
|
||||
&RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -691,6 +698,12 @@ async fn cmd_grpc_go<R: Runtime>(
|
||||
Ok(conn.id)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_restart<R: Runtime>(app_handle: AppHandle<R>) -> YaakResult<()> {
|
||||
app_handle.request_restart();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_send_ephemeral_request<R: Runtime>(
|
||||
mut request: HttpRequest,
|
||||
@@ -726,33 +739,40 @@ async fn cmd_format_json(text: &str) -> YaakResult<String> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_filter_response<R: Runtime>(
|
||||
async fn cmd_http_response_body<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
app_handle: AppHandle<R>,
|
||||
response_id: &str,
|
||||
plugin_manager: State<'_, PluginManager>,
|
||||
filter: &str,
|
||||
response: HttpResponse,
|
||||
filter: Option<&str>,
|
||||
) -> YaakResult<FilterResponse> {
|
||||
let response = app_handle.db().get_http_response(response_id)?;
|
||||
|
||||
if let None = response.body_path {
|
||||
return Err(GenericError("Response body path not set".to_string()));
|
||||
}
|
||||
|
||||
let mut content_type = "".to_string();
|
||||
for header in response.headers.iter() {
|
||||
if header.name.to_lowercase() == "content-type" {
|
||||
content_type = header.value.to_string().to_lowercase();
|
||||
break;
|
||||
let body_path = match response.body_path {
|
||||
None => {
|
||||
return Err(GenericError("Response body path not set".to_string()));
|
||||
}
|
||||
}
|
||||
Some(p) => p,
|
||||
};
|
||||
|
||||
let body = read_response_body(response)
|
||||
let content_type = response
|
||||
.headers
|
||||
.iter()
|
||||
.find_map(|h| {
|
||||
if h.name.eq_ignore_ascii_case("content-type") { Some(h.value.as_str()) } else { None }
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let body = read_response_body(&body_path, content_type)
|
||||
.await
|
||||
.ok_or(GenericError("Failed to find response body".to_string()))?;
|
||||
|
||||
// TODO: Have plugins register their own content type (regex?)
|
||||
Ok(plugin_manager.filter_data(&window, filter, &body, &content_type).await?)
|
||||
match filter {
|
||||
Some(filter) if !filter.is_empty() => {
|
||||
Ok(plugin_manager.filter_data(&window, filter, &body, content_type).await?)
|
||||
}
|
||||
_ => Ok(FilterResponse {
|
||||
content: body,
|
||||
error: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -801,11 +821,36 @@ async fn cmd_grpc_request_actions<R: Runtime>(
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_template_functions<R: Runtime>(
|
||||
async fn cmd_template_function_summaries<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
plugin_manager: State<'_, PluginManager>,
|
||||
) -> YaakResult<Vec<GetTemplateFunctionsResponse>> {
|
||||
Ok(plugin_manager.get_template_functions(&window).await?)
|
||||
) -> YaakResult<Vec<GetTemplateFunctionSummaryResponse>> {
|
||||
let results = plugin_manager.get_template_function_summaries(&window).await?;
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_template_function_config<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
plugin_manager: State<'_, PluginManager>,
|
||||
function_name: &str,
|
||||
values: HashMap<String, JsonPrimitive>,
|
||||
model: AnyModel,
|
||||
environment_id: Option<&str>,
|
||||
) -> YaakResult<GetTemplateFunctionConfigResponse> {
|
||||
let (workspace_id, folder_id) = match model.clone() {
|
||||
AnyModel::HttpRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::GrpcRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::WebsocketRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::Folder(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::Workspace(m) => (m.id, None),
|
||||
m => {
|
||||
return Err(GenericError(format!("Unsupported model to call template functions {m:?}")));
|
||||
}
|
||||
};
|
||||
let environment_chain =
|
||||
window.db().resolve_environments(&workspace_id, folder_id.as_deref(), environment_id)?;
|
||||
Ok(plugin_manager.get_template_function_config(&window, function_name, environment_chain, values, model.id()).await?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -823,30 +868,25 @@ async fn cmd_get_http_authentication_config<R: Runtime>(
|
||||
plugin_manager: State<'_, PluginManager>,
|
||||
auth_name: &str,
|
||||
values: HashMap<String, JsonPrimitive>,
|
||||
request_id: &str,
|
||||
model: AnyModel,
|
||||
environment_id: Option<&str>,
|
||||
workspace_id: &str,
|
||||
) -> YaakResult<GetHttpAuthenticationConfigResponse> {
|
||||
let base_environment = window.db().get_base_environment(&workspace_id)?;
|
||||
let environment = match environment_id {
|
||||
Some(id) => match window.db().get_environment(id) {
|
||||
Ok(env) => Some(env),
|
||||
Err(e) => {
|
||||
warn!("Failed to find environment by id {id} {}", e);
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
let (workspace_id, folder_id) = match model.clone() {
|
||||
AnyModel::HttpRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::GrpcRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::WebsocketRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::Folder(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::Workspace(m) => (m.id, None),
|
||||
m => {
|
||||
return Err(GenericError(format!("Unsupported model to call auth config {m:?}")));
|
||||
}
|
||||
};
|
||||
|
||||
let environment_chain =
|
||||
window.db().resolve_environments(&workspace_id, folder_id.as_deref(), environment_id)?;
|
||||
|
||||
Ok(plugin_manager
|
||||
.get_http_authentication_config(
|
||||
&window,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
auth_name,
|
||||
values,
|
||||
request_id,
|
||||
)
|
||||
.get_http_authentication_config(&window, environment_chain, auth_name, values, model.id())
|
||||
.await?)
|
||||
}
|
||||
|
||||
@@ -897,30 +937,29 @@ async fn cmd_call_http_authentication_action<R: Runtime>(
|
||||
auth_name: &str,
|
||||
action_index: i32,
|
||||
values: HashMap<String, JsonPrimitive>,
|
||||
model_id: &str,
|
||||
workspace_id: &str,
|
||||
model: AnyModel,
|
||||
environment_id: Option<&str>,
|
||||
) -> YaakResult<()> {
|
||||
let base_environment = window.db().get_base_environment(&workspace_id)?;
|
||||
let environment = match environment_id {
|
||||
Some(id) => match window.db().get_environment(id) {
|
||||
Ok(env) => Some(env),
|
||||
Err(e) => {
|
||||
warn!("Failed to find environment by id {id} {}", e);
|
||||
None
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
let (workspace_id, folder_id) = match model.clone() {
|
||||
AnyModel::HttpRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::GrpcRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::WebsocketRequest(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::Folder(m) => (m.workspace_id, m.folder_id),
|
||||
AnyModel::Workspace(m) => (m.id, None),
|
||||
m => {
|
||||
return Err(GenericError(format!("Unsupported model to call auth {m:?}")));
|
||||
}
|
||||
};
|
||||
let environment_chain =
|
||||
window.db().resolve_environments(&workspace_id, folder_id.as_deref(), environment_id)?;
|
||||
Ok(plugin_manager
|
||||
.call_http_authentication_action(
|
||||
&window,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
environment_chain,
|
||||
auth_name,
|
||||
action_index,
|
||||
values,
|
||||
model_id,
|
||||
&model.id(),
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
@@ -987,6 +1026,35 @@ async fn cmd_save_response<R: Runtime>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_send_folder<R: Runtime>(
|
||||
app_handle: AppHandle<R>,
|
||||
window: WebviewWindow<R>,
|
||||
environment_id: Option<String>,
|
||||
cookie_jar_id: Option<String>,
|
||||
folder_id: &str,
|
||||
) -> YaakResult<()> {
|
||||
let requests = app_handle.db().list_http_requests_for_folder_recursive(folder_id)?;
|
||||
for request in requests {
|
||||
let app_handle = app_handle.clone();
|
||||
let window = window.clone();
|
||||
let environment_id = environment_id.clone();
|
||||
let cookie_jar_id = cookie_jar_id.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = cmd_send_http_request(
|
||||
app_handle,
|
||||
window,
|
||||
environment_id.as_deref(),
|
||||
cookie_jar_id.as_deref(),
|
||||
request,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_send_http_request<R: Runtime>(
|
||||
app_handle: AppHandle<R>,
|
||||
@@ -1194,13 +1262,13 @@ async fn cmd_new_child_window(
|
||||
title: &str,
|
||||
inner_size: (f64, f64),
|
||||
) -> YaakResult<()> {
|
||||
window::create_child_window(&parent_window, url, label, title, inner_size);
|
||||
window::create_child_window(&parent_window, url, label, title, inner_size)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_new_main_window(app_handle: AppHandle, url: &str) -> YaakResult<()> {
|
||||
window::create_main_window(&app_handle, url);
|
||||
window::create_main_window(&app_handle, url)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1210,7 +1278,12 @@ async fn cmd_check_for_updates<R: Runtime>(
|
||||
yaak_updater: State<'_, Mutex<YaakUpdater>>,
|
||||
) -> YaakResult<bool> {
|
||||
let update_mode = get_update_mode(&window).await?;
|
||||
Ok(yaak_updater.lock().await.check_now(&window, update_mode, UpdateTrigger::User).await?)
|
||||
let settings = window.db().get_settings();
|
||||
Ok(yaak_updater
|
||||
.lock()
|
||||
.await
|
||||
.check_now(&window, update_mode, settings.auto_download_updates, UpdateTrigger::User)
|
||||
.await?)
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
@@ -1257,11 +1330,9 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_window_state::Builder::default().build())
|
||||
.plugin(tauri_plugin_deep_link::init())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_updater::Builder::default().build())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_os::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(yaak_license::init())
|
||||
.plugin(yaak_mac_window::init())
|
||||
.plugin(yaak_models::init())
|
||||
.plugin(yaak_plugins::init())
|
||||
@@ -1271,6 +1342,16 @@ pub fn run() {
|
||||
.plugin(yaak_ws::init())
|
||||
.plugin(yaak_sync::init());
|
||||
|
||||
#[cfg(feature = "license")]
|
||||
{
|
||||
builder = builder.plugin(yaak_license::init());
|
||||
}
|
||||
|
||||
#[cfg(feature = "updater")]
|
||||
{
|
||||
builder = builder.plugin(tauri_plugin_updater::Builder::default().build());
|
||||
}
|
||||
|
||||
builder
|
||||
.setup(|app| {
|
||||
{
|
||||
@@ -1291,6 +1372,7 @@ pub fn run() {
|
||||
),
|
||||
color: Some(Color::Danger),
|
||||
icon: None,
|
||||
timeout: None,
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -1330,7 +1412,7 @@ pub fn run() {
|
||||
cmd_delete_send_history,
|
||||
cmd_dismiss_notification,
|
||||
cmd_export_data,
|
||||
cmd_filter_response,
|
||||
cmd_http_response_body,
|
||||
cmd_format_json,
|
||||
cmd_get_http_authentication_summaries,
|
||||
cmd_get_http_authentication_config,
|
||||
@@ -1348,10 +1430,13 @@ pub fn run() {
|
||||
cmd_plugin_info,
|
||||
cmd_reload_plugins,
|
||||
cmd_render_template,
|
||||
cmd_restart,
|
||||
cmd_save_response,
|
||||
cmd_send_ephemeral_request,
|
||||
cmd_send_http_request,
|
||||
cmd_template_functions,
|
||||
cmd_send_folder,
|
||||
cmd_template_function_config,
|
||||
cmd_template_function_summaries,
|
||||
cmd_template_tokens_to_string,
|
||||
//
|
||||
//
|
||||
@@ -1369,7 +1454,7 @@ pub fn run() {
|
||||
let _ = window::create_main_window(app_handle, "/");
|
||||
let h = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let info = history::store_launch_history(&h).await;
|
||||
let info = history::get_or_upsert_launch_info(&h);
|
||||
debug!("Launched Yaak {:?}", info);
|
||||
});
|
||||
|
||||
@@ -1387,16 +1472,27 @@ pub fn run() {
|
||||
label,
|
||||
..
|
||||
} => {
|
||||
let w = app_handle.get_webview_window(&label).unwrap();
|
||||
let h = app_handle.clone();
|
||||
// Run update check whenever the window is focused
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let val: State<'_, Mutex<YaakUpdater>> = h.state();
|
||||
let update_mode = get_update_mode(&w).await.unwrap();
|
||||
if let Err(e) = val.lock().await.maybe_check(&w, update_mode).await {
|
||||
warn!("Failed to check for updates {e:?}");
|
||||
};
|
||||
});
|
||||
if cfg!(feature = "updater") {
|
||||
// Run update check whenever the window is focused
|
||||
let w = app_handle.get_webview_window(&label).unwrap();
|
||||
let h = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let settings = w.db().get_settings();
|
||||
if settings.autoupdate {
|
||||
time::sleep(Duration::from_secs(3)).await; // Wait a bit so it's not so jarring
|
||||
let val: State<'_, Mutex<YaakUpdater>> = h.state();
|
||||
let update_mode = get_update_mode(&w).await.unwrap();
|
||||
if let Err(e) = val
|
||||
.lock()
|
||||
.await
|
||||
.maybe_check(&w, settings.auto_download_updates, update_mode)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to check for updates {e:?}");
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
let h = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
@@ -1458,7 +1554,30 @@ fn monitor_plugin_events<R: Runtime>(app_handle: &AppHandle<R>) {
|
||||
// We might have recursive back-and-forth calls between app and plugin, so we don't
|
||||
// want to block here
|
||||
tauri::async_runtime::spawn(async move {
|
||||
plugin_events::handle_plugin_event(&app_handle, &event, &plugin).await;
|
||||
let ev = plugin_events::handle_plugin_event(&app_handle, &event, &plugin).await;
|
||||
|
||||
let ev = match ev {
|
||||
Ok(Some(ev)) => ev,
|
||||
Ok(None) => return,
|
||||
Err(e) => {
|
||||
warn!("Failed to handle plugin event: {e:?}");
|
||||
let _ = app_handle.emit(
|
||||
"show_toast",
|
||||
InternalEventPayload::ShowToastRequest(ShowToastRequest {
|
||||
message: e.to_string(),
|
||||
color: Some(Color::Danger),
|
||||
icon: None,
|
||||
timeout: Some(30000),
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let plugin_manager: State<'_, PluginManager> = app_handle.state();
|
||||
if let Err(e) = plugin_manager.reply(&event, &ev).await {
|
||||
warn!("Failed to reply to plugin manager: {:?}", e)
|
||||
}
|
||||
});
|
||||
}
|
||||
plugin_manager.unsubscribe(rx_id.as_str()).await;
|
||||
@@ -1466,7 +1585,7 @@ fn monitor_plugin_events<R: Runtime>(app_handle: &AppHandle<R>) {
|
||||
}
|
||||
|
||||
async fn call_frontend<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
window: &WebviewWindow<R>,
|
||||
event: &InternalEvent,
|
||||
) -> Option<InternalEventPayload> {
|
||||
window.emit_to(window.label(), "plugin_event", event.clone()).unwrap();
|
||||
@@ -1493,11 +1612,16 @@ async fn call_frontend<R: Runtime>(
|
||||
fn get_window_from_window_context<R: Runtime>(
|
||||
app_handle: &AppHandle<R>,
|
||||
window_context: &PluginWindowContext,
|
||||
) -> Option<WebviewWindow<R>> {
|
||||
) -> Result<WebviewWindow<R>> {
|
||||
let label = match window_context {
|
||||
PluginWindowContext::Label { label, .. } => label,
|
||||
PluginWindowContext::None => {
|
||||
return app_handle.webview_windows().iter().next().map(|(_, w)| w.to_owned());
|
||||
return app_handle
|
||||
.webview_windows()
|
||||
.iter()
|
||||
.next()
|
||||
.map(|(_, w)| w.to_owned())
|
||||
.ok_or(GenericError("No windows open".to_string()));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1510,7 +1634,7 @@ fn get_window_from_window_context<R: Runtime>(
|
||||
error!("Failed to find window by {window_context:?}");
|
||||
}
|
||||
|
||||
window
|
||||
Ok(window.ok_or(GenericError(format!("Failed to find window for {}", label)))?)
|
||||
}
|
||||
|
||||
fn workspace_from_window<R: Runtime>(window: &WebviewWindow<R>) -> Option<Workspace> {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
use std::time::SystemTime;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::history::get_num_launches;
|
||||
use crate::history::get_or_upsert_launch_info;
|
||||
use chrono::{DateTime, Utc};
|
||||
use log::debug;
|
||||
use reqwest::Method;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
|
||||
use ts_rs::TS;
|
||||
use yaak_common::api_client::yaak_api_client;
|
||||
use yaak_common::platform::get_os;
|
||||
use yaak_license::{LicenseCheckStatus, check_license};
|
||||
use yaak_models::query_manager::QueryManagerExt;
|
||||
use yaak_models::util::UpdateSource;
|
||||
|
||||
@@ -24,18 +24,22 @@ pub struct YaakNotifier {
|
||||
last_check: SystemTime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "index.ts")]
|
||||
pub struct YaakNotification {
|
||||
timestamp: DateTime<Utc>,
|
||||
timeout: Option<f64>,
|
||||
id: String,
|
||||
title: Option<String>,
|
||||
message: String,
|
||||
color: Option<String>,
|
||||
action: Option<YaakNotificationAction>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default, TS)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "index.ts")]
|
||||
pub struct YaakNotificationAction {
|
||||
label: String,
|
||||
url: String,
|
||||
@@ -73,23 +77,31 @@ impl YaakNotifier {
|
||||
|
||||
self.last_check = SystemTime::now();
|
||||
|
||||
let license_check = match check_license(window).await? {
|
||||
LicenseCheckStatus::PersonalUse { .. } => "personal".to_string(),
|
||||
LicenseCheckStatus::CommercialUse => "commercial".to_string(),
|
||||
LicenseCheckStatus::InvalidLicense => "invalid_license".to_string(),
|
||||
LicenseCheckStatus::Trialing { .. } => "trialing".to_string(),
|
||||
#[cfg(feature = "license")]
|
||||
let license_check = {
|
||||
use yaak_license::{check_license, LicenseCheckStatus};
|
||||
match check_license(window).await {
|
||||
Ok(LicenseCheckStatus::PersonalUse { .. }) => "personal".to_string(),
|
||||
Ok(LicenseCheckStatus::CommercialUse) => "commercial".to_string(),
|
||||
Ok(LicenseCheckStatus::InvalidLicense) => "invalid_license".to_string(),
|
||||
Ok(LicenseCheckStatus::Trialing { .. }) => "trialing".to_string(),
|
||||
Err(_) => "unknown".to_string(),
|
||||
}
|
||||
};
|
||||
let settings = window.db().get_settings();
|
||||
let num_launches = get_num_launches(app_handle).await;
|
||||
let info = app_handle.package_info().clone();
|
||||
#[cfg(not(feature = "license"))]
|
||||
let license_check = "disabled".to_string();
|
||||
|
||||
let launch_info = get_or_upsert_launch_info(app_handle);
|
||||
let req = yaak_api_client(app_handle)?
|
||||
.request(Method::GET, "https://notify.yaak.app/notifications")
|
||||
.query(&[
|
||||
("version", info.version.to_string().as_str()),
|
||||
("launches", num_launches.to_string().as_str()),
|
||||
("installed", settings.created_at.format("%Y-%m-%d").to_string().as_str()),
|
||||
("version", &launch_info.current_version),
|
||||
("version_prev", &launch_info.previous_version),
|
||||
("launches", &launch_info.num_launches.to_string()),
|
||||
("installed", &launch_info.user_since.format("%Y-%m-%d").to_string()),
|
||||
("license", &license_check),
|
||||
("platform", get_os()),
|
||||
("updates", &get_updater_status(app_handle).to_string()),
|
||||
("platform", &get_os().to_string()),
|
||||
]);
|
||||
let resp = req.send().await?;
|
||||
if resp.status() != 200 {
|
||||
@@ -119,3 +131,32 @@ async fn get_kv<R: Runtime>(app_handle: &AppHandle<R>) -> Result<Vec<String>> {
|
||||
Some(v) => Ok(serde_json::from_str(&v.value)?),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_updater_status<R: Runtime>(app_handle: &AppHandle<R>) -> &'static str {
|
||||
#[cfg(not(feature = "updater"))]
|
||||
{
|
||||
// Updater is not enabled as a Rust feature
|
||||
return "missing";
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "updater", target_os = "linux"))]
|
||||
{
|
||||
let settings = app_handle.db().get_settings();
|
||||
if !settings.autoupdate {
|
||||
// Updates are explicitly disabled
|
||||
"disabled"
|
||||
} else if std::env::var("APPIMAGE").is_err() {
|
||||
// Updates are enabled, but unsupported
|
||||
"unsupported"
|
||||
} else {
|
||||
// Updates are enabled and supported
|
||||
"enabled"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "updater", not(target_os = "linux")))]
|
||||
{
|
||||
let settings = app_handle.db().get_settings();
|
||||
if settings.autoupdate { "enabled" } else { "disabled" }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::error::Result;
|
||||
use crate::http_request::send_http_request;
|
||||
use crate::render::{render_grpc_request, render_http_request, render_json_value};
|
||||
use crate::window::{CreateWindowConfig, create_window};
|
||||
@@ -7,133 +8,137 @@ use crate::{
|
||||
};
|
||||
use chrono::Utc;
|
||||
use cookie::Cookie;
|
||||
use log::warn;
|
||||
use tauri::{AppHandle, Emitter, Manager, Runtime, State};
|
||||
use log::error;
|
||||
use tauri::{AppHandle, Emitter, Manager, Runtime};
|
||||
use tauri_plugin_clipboard_manager::ClipboardExt;
|
||||
use yaak_common::window::WorkspaceWindowTrait;
|
||||
use yaak_models::models::{HttpResponse, Plugin};
|
||||
use yaak_models::queries::any_request::AnyRequest;
|
||||
use yaak_models::query_manager::QueryManagerExt;
|
||||
use yaak_models::util::UpdateSource;
|
||||
use yaak_plugins::events::{
|
||||
Color, DeleteKeyValueResponse, EmptyPayload, FindHttpResponsesResponse, GetCookieValueResponse,
|
||||
GetHttpRequestByIdResponse, GetKeyValueResponse, Icon, InternalEvent, InternalEventPayload,
|
||||
ListCookieNamesResponse, PluginWindowContext, RenderGrpcRequestResponse,
|
||||
Color, DeleteKeyValueResponse, EmptyPayload, ErrorResponse, FindHttpResponsesResponse,
|
||||
GetCookieValueResponse, GetHttpRequestByIdResponse, GetKeyValueResponse, Icon, InternalEvent,
|
||||
InternalEventPayload, ListCookieNamesResponse, PluginWindowContext, RenderGrpcRequestResponse,
|
||||
RenderHttpRequestResponse, SendHttpRequestResponse, SetKeyValueResponse, ShowToastRequest,
|
||||
TemplateRenderResponse, WindowNavigateEvent,
|
||||
};
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
use yaak_plugins::plugin_handle::PluginHandle;
|
||||
use yaak_plugins::template_callback::PluginTemplateCallback;
|
||||
use yaak_templates::{RenderErrorBehavior, RenderOptions};
|
||||
|
||||
pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
app_handle: &AppHandle<R>,
|
||||
event: &InternalEvent,
|
||||
plugin_handle: &PluginHandle,
|
||||
) {
|
||||
) -> Result<Option<InternalEventPayload>> {
|
||||
// debug!("Got event to app {event:?}");
|
||||
let window_context = event.window_context.to_owned();
|
||||
let response_event: Option<InternalEventPayload> = match event.clone().payload {
|
||||
match event.clone().payload {
|
||||
InternalEventPayload::CopyTextRequest(req) => {
|
||||
app_handle
|
||||
.clipboard()
|
||||
.write_text(req.text.as_str())
|
||||
.expect("Failed to write text to clipboard");
|
||||
Some(InternalEventPayload::CopyTextResponse(EmptyPayload {}))
|
||||
app_handle.clipboard().write_text(req.text.as_str())?;
|
||||
Ok(Some(InternalEventPayload::CopyTextResponse(EmptyPayload {})))
|
||||
}
|
||||
InternalEventPayload::ShowToastRequest(req) => {
|
||||
match window_context {
|
||||
PluginWindowContext::Label { label, .. } => app_handle
|
||||
.emit_to(label, "show_toast", req)
|
||||
.expect("Failed to emit show_toast to window"),
|
||||
_ => app_handle.emit("show_toast", req).expect("Failed to emit show_toast"),
|
||||
PluginWindowContext::Label { label, .. } => {
|
||||
app_handle.emit_to(label, "show_toast", req)?
|
||||
}
|
||||
_ => app_handle.emit("show_toast", req)?,
|
||||
};
|
||||
Some(InternalEventPayload::ShowToastResponse(EmptyPayload {}))
|
||||
Ok(Some(InternalEventPayload::ShowToastResponse(EmptyPayload {})))
|
||||
}
|
||||
InternalEventPayload::PromptTextRequest(_) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for render");
|
||||
call_frontend(window, event).await
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
Ok(call_frontend(&window, event).await)
|
||||
}
|
||||
InternalEventPayload::FindHttpResponsesRequest(req) => {
|
||||
let http_responses = app_handle
|
||||
.db()
|
||||
.list_http_responses_for_request(&req.request_id, req.limit.map(|l| l as u64))
|
||||
.unwrap_or_default();
|
||||
Some(InternalEventPayload::FindHttpResponsesResponse(FindHttpResponsesResponse {
|
||||
Ok(Some(InternalEventPayload::FindHttpResponsesResponse(FindHttpResponsesResponse {
|
||||
http_responses,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::GetHttpRequestByIdRequest(req) => {
|
||||
let http_request = app_handle.db().get_http_request(&req.id).ok();
|
||||
Some(InternalEventPayload::GetHttpRequestByIdResponse(GetHttpRequestByIdResponse {
|
||||
Ok(Some(InternalEventPayload::GetHttpRequestByIdResponse(GetHttpRequestByIdResponse {
|
||||
http_request,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::RenderGrpcRequestRequest(req) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for render grpc request");
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
|
||||
let workspace =
|
||||
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
|
||||
let environment = environment_from_window(&window);
|
||||
let base_environment = app_handle
|
||||
.db()
|
||||
.get_base_environment(&workspace.id)
|
||||
.expect("Failed to get base environment");
|
||||
let environment_id = environment_from_window(&window).map(|e| e.id);
|
||||
let environment_chain = window.db().resolve_environments(
|
||||
&workspace.id,
|
||||
req.grpc_request.folder_id.as_deref(),
|
||||
environment_id.as_deref(),
|
||||
)?;
|
||||
let cb = PluginTemplateCallback::new(app_handle, &window_context, req.purpose);
|
||||
let grpc_request = render_grpc_request(
|
||||
&req.grpc_request,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
&cb,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to render grpc request");
|
||||
Some(InternalEventPayload::RenderGrpcRequestResponse(RenderGrpcRequestResponse {
|
||||
let opt = RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
};
|
||||
let grpc_request =
|
||||
render_grpc_request(&req.grpc_request, environment_chain, &cb, &opt).await?;
|
||||
Ok(Some(InternalEventPayload::RenderGrpcRequestResponse(RenderGrpcRequestResponse {
|
||||
grpc_request,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::RenderHttpRequestRequest(req) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for render http request");
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
|
||||
let workspace =
|
||||
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
|
||||
let environment = environment_from_window(&window);
|
||||
let base_environment = app_handle
|
||||
.db()
|
||||
.get_base_environment(&workspace.id)
|
||||
.expect("Failed to get base environment");
|
||||
let environment_id = environment_from_window(&window).map(|e| e.id);
|
||||
let environment_chain = window.db().resolve_environments(
|
||||
&workspace.id,
|
||||
req.http_request.folder_id.as_deref(),
|
||||
environment_id.as_deref(),
|
||||
)?;
|
||||
let cb = PluginTemplateCallback::new(app_handle, &window_context, req.purpose);
|
||||
let http_request = render_http_request(
|
||||
&req.http_request,
|
||||
&base_environment,
|
||||
environment.as_ref(),
|
||||
&cb,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to render http request");
|
||||
Some(InternalEventPayload::RenderHttpRequestResponse(RenderHttpRequestResponse {
|
||||
let opt = &RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
};
|
||||
let http_request =
|
||||
render_http_request(&req.http_request, environment_chain, &cb, &opt).await?;
|
||||
Ok(Some(InternalEventPayload::RenderHttpRequestResponse(RenderHttpRequestResponse {
|
||||
http_request,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::TemplateRenderRequest(req) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for render");
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
|
||||
let workspace =
|
||||
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
|
||||
let environment = environment_from_window(&window);
|
||||
let base_environment = app_handle
|
||||
.db()
|
||||
.get_base_environment(&workspace.id)
|
||||
.expect("Failed to get base environment");
|
||||
let environment_id = environment_from_window(&window).map(|e| e.id);
|
||||
let folder_id = if let Some(id) = window.request_id() {
|
||||
match window.db().get_any_request(&id) {
|
||||
Ok(AnyRequest::HttpRequest(r)) => r.folder_id,
|
||||
Ok(AnyRequest::GrpcRequest(r)) => r.folder_id,
|
||||
Ok(AnyRequest::WebsocketRequest(r)) => r.folder_id,
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let environment_chain = window.db().resolve_environments(
|
||||
&workspace.id,
|
||||
folder_id.as_deref(),
|
||||
environment_id.as_deref(),
|
||||
)?;
|
||||
let cb = PluginTemplateCallback::new(app_handle, &window_context, req.purpose);
|
||||
let data = render_json_value(req.data, &base_environment, environment.as_ref(), &cb)
|
||||
.await
|
||||
.expect("Failed to render template");
|
||||
Some(InternalEventPayload::TemplateRenderResponse(TemplateRenderResponse { data }))
|
||||
let opt = RenderOptions {
|
||||
error_behavior: RenderErrorBehavior::Throw,
|
||||
};
|
||||
let data = render_json_value(req.data, environment_chain, &cb, &opt).await?;
|
||||
Ok(Some(InternalEventPayload::TemplateRenderResponse(TemplateRenderResponse { data })))
|
||||
}
|
||||
InternalEventPayload::ErrorResponse(resp) => {
|
||||
error!("Plugin error: {}: {:?}", resp.error, resp);
|
||||
let toast_event = plugin_handle.build_event_to_send(
|
||||
&window_context,
|
||||
&InternalEventPayload::ShowToastRequest(ShowToastRequest {
|
||||
@@ -143,15 +148,15 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
resp.error
|
||||
),
|
||||
color: Some(Color::Danger),
|
||||
timeout: Some(30000),
|
||||
..Default::default()
|
||||
}),
|
||||
None,
|
||||
);
|
||||
Box::pin(handle_plugin_event(app_handle, &toast_event, plugin_handle)).await;
|
||||
None
|
||||
Box::pin(handle_plugin_event(app_handle, &toast_event, plugin_handle)).await
|
||||
}
|
||||
InternalEventPayload::ReloadResponse(r) => {
|
||||
let plugins = app_handle.db().list_plugins().unwrap();
|
||||
InternalEventPayload::ReloadResponse(req) => {
|
||||
let plugins = app_handle.db().list_plugins()?;
|
||||
for plugin in plugins {
|
||||
if plugin.directory != plugin_handle.dir {
|
||||
continue;
|
||||
@@ -161,23 +166,28 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
updated_at: Utc::now().naive_utc(), // TODO: Add reloaded_at field to use instead
|
||||
..plugin
|
||||
};
|
||||
app_handle.db().upsert_plugin(&new_plugin, &UpdateSource::Plugin).unwrap();
|
||||
app_handle.db().upsert_plugin(&new_plugin, &UpdateSource::Plugin)?;
|
||||
}
|
||||
|
||||
if !req.silent {
|
||||
let info = plugin_handle.info();
|
||||
let toast_event = plugin_handle.build_event_to_send(
|
||||
&window_context,
|
||||
&InternalEventPayload::ShowToastRequest(ShowToastRequest {
|
||||
message: format!("Reloaded plugin {}@{}", info.name, info.version),
|
||||
icon: Some(Icon::Info),
|
||||
timeout: Some(3000),
|
||||
..Default::default()
|
||||
}),
|
||||
None,
|
||||
);
|
||||
Box::pin(handle_plugin_event(app_handle, &toast_event, plugin_handle)).await
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
let toast_event = plugin_handle.build_event_to_send(
|
||||
&window_context,
|
||||
&InternalEventPayload::ShowToastRequest(ShowToastRequest {
|
||||
message: format!("Reloaded plugin {}@{}", r.name, r.version),
|
||||
icon: Some(Icon::Info),
|
||||
..Default::default()
|
||||
}),
|
||||
None,
|
||||
);
|
||||
Box::pin(handle_plugin_event(app_handle, &toast_event, plugin_handle)).await;
|
||||
None
|
||||
}
|
||||
InternalEventPayload::SendHttpRequestRequest(req) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for sending HTTP request");
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
let mut http_request = req.http_request;
|
||||
let workspace =
|
||||
workspace_from_window(&window).expect("Failed to get workspace_id from window URL");
|
||||
@@ -191,20 +201,17 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
let http_response = if http_request.id.is_empty() {
|
||||
HttpResponse::default()
|
||||
} else {
|
||||
window
|
||||
.db()
|
||||
.upsert_http_response(
|
||||
&HttpResponse {
|
||||
request_id: http_request.id.clone(),
|
||||
workspace_id: http_request.workspace_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::Plugin,
|
||||
)
|
||||
.unwrap()
|
||||
window.db().upsert_http_response(
|
||||
&HttpResponse {
|
||||
request_id: http_request.id.clone(),
|
||||
workspace_id: http_request.workspace_id.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&UpdateSource::Plugin,
|
||||
)?
|
||||
};
|
||||
|
||||
let result = send_http_request(
|
||||
let http_response = send_http_request(
|
||||
&window,
|
||||
&http_request,
|
||||
&http_response,
|
||||
@@ -212,32 +219,36 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
cookie_jar,
|
||||
&mut tokio::sync::watch::channel(false).1, // No-op cancel channel
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
|
||||
let http_response = match result {
|
||||
Ok(r) => r,
|
||||
Err(_e) => return,
|
||||
};
|
||||
|
||||
Some(InternalEventPayload::SendHttpRequestResponse(SendHttpRequestResponse {
|
||||
Ok(Some(InternalEventPayload::SendHttpRequestResponse(SendHttpRequestResponse {
|
||||
http_response,
|
||||
}))
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::OpenWindowRequest(req) => {
|
||||
let label = req.label;
|
||||
let (navigation_tx, mut navigation_rx) = tokio::sync::mpsc::channel(128);
|
||||
let (close_tx, mut close_rx) = tokio::sync::mpsc::channel(128);
|
||||
let win_config = CreateWindowConfig {
|
||||
url: &req.url,
|
||||
label: &label.clone(),
|
||||
title: &req.title.unwrap_or_default(),
|
||||
label: &req.label,
|
||||
title: &req.title.clone().unwrap_or_default(),
|
||||
navigation_tx: Some(navigation_tx),
|
||||
close_tx: Some(close_tx),
|
||||
inner_size: req.size.map(|s| (s.width, s.height)),
|
||||
data_dir_key: req.data_dir_key,
|
||||
inner_size: req.size.clone().map(|s| (s.width, s.height)),
|
||||
data_dir_key: req.data_dir_key.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
create_window(app_handle, win_config);
|
||||
if let Err(e) = create_window(app_handle, win_config) {
|
||||
let error_event = plugin_handle.build_event_to_send(
|
||||
&window_context,
|
||||
&InternalEventPayload::ErrorResponse(ErrorResponse {
|
||||
error: format!("Failed to create window: {:?}", e),
|
||||
}),
|
||||
None,
|
||||
);
|
||||
return Box::pin(handle_plugin_event(app_handle, &error_event, plugin_handle))
|
||||
.await;
|
||||
}
|
||||
|
||||
{
|
||||
let event_id = event.id.clone();
|
||||
@@ -272,32 +283,33 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
});
|
||||
}
|
||||
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
InternalEventPayload::CloseWindowRequest(req) => {
|
||||
if let Some(window) = app_handle.webview_windows().get(&req.label) {
|
||||
window.close().expect("Failed to close window");
|
||||
window.close()?;
|
||||
}
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
InternalEventPayload::SetKeyValueRequest(req) => {
|
||||
let name = plugin_handle.info().name;
|
||||
app_handle.db().set_plugin_key_value(&name, &req.key, &req.value);
|
||||
Some(InternalEventPayload::SetKeyValueResponse(SetKeyValueResponse {}))
|
||||
Ok(Some(InternalEventPayload::SetKeyValueResponse(SetKeyValueResponse {})))
|
||||
}
|
||||
InternalEventPayload::GetKeyValueRequest(req) => {
|
||||
let name = plugin_handle.info().name;
|
||||
let value = app_handle.db().get_plugin_key_value(&name, &req.key).map(|v| v.value);
|
||||
Some(InternalEventPayload::GetKeyValueResponse(GetKeyValueResponse { value }))
|
||||
Ok(Some(InternalEventPayload::GetKeyValueResponse(GetKeyValueResponse { value })))
|
||||
}
|
||||
InternalEventPayload::DeleteKeyValueRequest(req) => {
|
||||
let name = plugin_handle.info().name;
|
||||
let deleted = app_handle.db().delete_plugin_key_value(&name, &req.key).unwrap();
|
||||
Some(InternalEventPayload::DeleteKeyValueResponse(DeleteKeyValueResponse { deleted }))
|
||||
let deleted = app_handle.db().delete_plugin_key_value(&name, &req.key)?;
|
||||
Ok(Some(InternalEventPayload::DeleteKeyValueResponse(DeleteKeyValueResponse {
|
||||
deleted,
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::ListCookieNamesRequest(_req) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for listing cookies");
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
let names = match cookie_jar_from_window(&window) {
|
||||
None => Vec::new(),
|
||||
Some(j) => j
|
||||
@@ -306,11 +318,12 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
.filter_map(|c| Cookie::parse(c.raw_cookie).ok().map(|c| c.name().to_string()))
|
||||
.collect(),
|
||||
};
|
||||
Some(InternalEventPayload::ListCookieNamesResponse(ListCookieNamesResponse { names }))
|
||||
Ok(Some(InternalEventPayload::ListCookieNamesResponse(ListCookieNamesResponse {
|
||||
names,
|
||||
})))
|
||||
}
|
||||
InternalEventPayload::GetCookieValueRequest(req) => {
|
||||
let window = get_window_from_window_context(app_handle, &window_context)
|
||||
.expect("Failed to find window for listing cookies");
|
||||
let window = get_window_from_window_context(app_handle, &window_context)?;
|
||||
let value = match cookie_jar_from_window(&window) {
|
||||
None => None,
|
||||
Some(j) => j.cookies.into_iter().find_map(|c| match Cookie::parse(c.raw_cookie) {
|
||||
@@ -320,15 +333,8 @@ pub(crate) async fn handle_plugin_event<R: Runtime>(
|
||||
_ => None,
|
||||
}),
|
||||
};
|
||||
Some(InternalEventPayload::GetCookieValueResponse(GetCookieValueResponse { value }))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(e) = response_event {
|
||||
let plugin_manager: State<'_, PluginManager> = app_handle.state();
|
||||
if let Err(e) = plugin_manager.reply(&event, &e).await {
|
||||
warn!("Failed to reply to plugin manager: {:?}", e)
|
||||
Ok(Some(InternalEventPayload::GetCookieValueResponse(GetCookieValueResponse { value })))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,56 +1,56 @@
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use yaak_http::apply_path_placeholders;
|
||||
use yaak_models::models::{
|
||||
Environment, GrpcRequest, HttpRequest, HttpRequestHeader, HttpUrlParameter,
|
||||
};
|
||||
use yaak_models::render::make_vars_hashmap;
|
||||
use yaak_templates::{parse_and_render, render_json_value_raw, TemplateCallback};
|
||||
use yaak_templates::{RenderOptions, TemplateCallback, parse_and_render, render_json_value_raw};
|
||||
|
||||
pub async fn render_template<T: TemplateCallback>(
|
||||
template: &str,
|
||||
base_environment: &Environment,
|
||||
environment: Option<&Environment>,
|
||||
environment_chain: Vec<Environment>,
|
||||
cb: &T,
|
||||
opt: &RenderOptions,
|
||||
) -> yaak_templates::error::Result<String> {
|
||||
let vars = &make_vars_hashmap(base_environment, environment);
|
||||
render(template, vars, cb).await
|
||||
let vars = &make_vars_hashmap(environment_chain);
|
||||
parse_and_render(template, vars, cb, &opt).await
|
||||
}
|
||||
|
||||
pub async fn render_json_value<T: TemplateCallback>(
|
||||
value: Value,
|
||||
base_environment: &Environment,
|
||||
environment: Option<&Environment>,
|
||||
environment_chain: Vec<Environment>,
|
||||
cb: &T,
|
||||
opt: &RenderOptions,
|
||||
) -> yaak_templates::error::Result<Value> {
|
||||
let vars = &make_vars_hashmap(base_environment, environment);
|
||||
render_json_value_raw(value, vars, cb).await
|
||||
let vars = &make_vars_hashmap(environment_chain);
|
||||
render_json_value_raw(value, vars, cb, opt).await
|
||||
}
|
||||
|
||||
pub async fn render_grpc_request<T: TemplateCallback>(
|
||||
r: &GrpcRequest,
|
||||
base_environment: &Environment,
|
||||
environment: Option<&Environment>,
|
||||
environment_chain: Vec<Environment>,
|
||||
cb: &T,
|
||||
opt: &RenderOptions,
|
||||
) -> yaak_templates::error::Result<GrpcRequest> {
|
||||
let vars = &make_vars_hashmap(base_environment, environment);
|
||||
let vars = &make_vars_hashmap(environment_chain);
|
||||
|
||||
let mut metadata = Vec::new();
|
||||
for p in r.metadata.clone() {
|
||||
metadata.push(HttpRequestHeader {
|
||||
enabled: p.enabled,
|
||||
name: render(p.name.as_str(), vars, cb).await?,
|
||||
value: render(p.value.as_str(), vars, cb).await?,
|
||||
name: parse_and_render(p.name.as_str(), vars, cb, &opt).await?,
|
||||
value: parse_and_render(p.value.as_str(), vars, cb, &opt).await?,
|
||||
id: p.id,
|
||||
})
|
||||
}
|
||||
|
||||
let mut authentication = BTreeMap::new();
|
||||
for (k, v) in r.authentication.clone() {
|
||||
authentication.insert(k, render_json_value_raw(v, vars, cb).await?);
|
||||
authentication.insert(k, render_json_value_raw(v, vars, cb, &opt).await?);
|
||||
}
|
||||
|
||||
let url = render(r.url.as_str(), vars, cb).await?;
|
||||
let url = parse_and_render(r.url.as_str(), vars, cb, &opt).await?;
|
||||
|
||||
Ok(GrpcRequest {
|
||||
url,
|
||||
@@ -62,18 +62,18 @@ pub async fn render_grpc_request<T: TemplateCallback>(
|
||||
|
||||
pub async fn render_http_request<T: TemplateCallback>(
|
||||
r: &HttpRequest,
|
||||
base_environment: &Environment,
|
||||
environment: Option<&Environment>,
|
||||
environment_chain: Vec<Environment>,
|
||||
cb: &T,
|
||||
opt: &RenderOptions,
|
||||
) -> yaak_templates::error::Result<HttpRequest> {
|
||||
let vars = &make_vars_hashmap(base_environment, environment);
|
||||
let vars = &make_vars_hashmap(environment_chain);
|
||||
|
||||
let mut url_parameters = Vec::new();
|
||||
for p in r.url_parameters.clone() {
|
||||
url_parameters.push(HttpUrlParameter {
|
||||
enabled: p.enabled,
|
||||
name: render(p.name.as_str(), vars, cb).await?,
|
||||
value: render(p.value.as_str(), vars, cb).await?,
|
||||
name: parse_and_render(p.name.as_str(), vars, cb, &opt).await?,
|
||||
value: parse_and_render(p.value.as_str(), vars, cb, &opt).await?,
|
||||
id: p.id,
|
||||
})
|
||||
}
|
||||
@@ -82,23 +82,23 @@ pub async fn render_http_request<T: TemplateCallback>(
|
||||
for p in r.headers.clone() {
|
||||
headers.push(HttpRequestHeader {
|
||||
enabled: p.enabled,
|
||||
name: render(p.name.as_str(), vars, cb).await?,
|
||||
value: render(p.value.as_str(), vars, cb).await?,
|
||||
name: parse_and_render(p.name.as_str(), vars, cb, &opt).await?,
|
||||
value: parse_and_render(p.value.as_str(), vars, cb, &opt).await?,
|
||||
id: p.id,
|
||||
})
|
||||
}
|
||||
|
||||
let mut body = BTreeMap::new();
|
||||
for (k, v) in r.body.clone() {
|
||||
body.insert(k, render_json_value_raw(v, vars, cb).await?);
|
||||
body.insert(k, render_json_value_raw(v, vars, cb, &opt).await?);
|
||||
}
|
||||
|
||||
let mut authentication = BTreeMap::new();
|
||||
for (k, v) in r.authentication.clone() {
|
||||
authentication.insert(k, render_json_value_raw(v, vars, cb).await?);
|
||||
authentication.insert(k, render_json_value_raw(v, vars, cb, &opt).await?);
|
||||
}
|
||||
|
||||
let url = render(r.url.clone().as_str(), vars, cb).await?;
|
||||
let url = parse_and_render(r.url.clone().as_str(), vars, cb, &opt).await?;
|
||||
|
||||
// This doesn't fit perfectly with the concept of "rendering" but it kind of does
|
||||
let (url, url_parameters) = apply_path_placeholders(&url, url_parameters);
|
||||
@@ -112,11 +112,3 @@ pub async fn render_http_request<T: TemplateCallback>(
|
||||
..r.to_owned()
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn render<T: TemplateCallback>(
|
||||
template: &str,
|
||||
vars: &HashMap<String, String>,
|
||||
cb: &T,
|
||||
) -> yaak_templates::error::Result<String> {
|
||||
parse_and_render(template, vars, cb).await
|
||||
}
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::time::SystemTime;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use crate::error::Result;
|
||||
use log::info;
|
||||
use tauri::{Manager, Runtime, WebviewWindow};
|
||||
use log::{debug, error, info, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{Emitter, Listener, Manager, Runtime, WebviewWindow};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons};
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
use tauri_plugin_updater::{Update, UpdaterExt};
|
||||
use tokio::task::block_in_place;
|
||||
use tokio::time::sleep;
|
||||
use ts_rs::TS;
|
||||
use yaak_models::query_manager::QueryManagerExt;
|
||||
use yaak_models::util::generate_id;
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
|
||||
use crate::error::Error::GenericError;
|
||||
use crate::is_dev;
|
||||
|
||||
const MAX_UPDATE_CHECK_HOURS_STABLE: u64 = 12;
|
||||
@@ -48,6 +54,7 @@ impl UpdateMode {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum UpdateTrigger {
|
||||
Background,
|
||||
User,
|
||||
@@ -64,13 +71,22 @@ impl YaakUpdater {
|
||||
&mut self,
|
||||
window: &WebviewWindow<R>,
|
||||
mode: UpdateMode,
|
||||
auto_download: bool,
|
||||
update_trigger: UpdateTrigger,
|
||||
) -> Result<bool> {
|
||||
// Only AppImage supports updates on Linux, so skip if it's not
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if std::env::var("APPIMAGE").is_err() {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
let settings = window.db().get_settings();
|
||||
let update_key = format!("{:x}", md5::compute(settings.id));
|
||||
self.last_update_check = SystemTime::now();
|
||||
|
||||
info!("Checking for updates mode={}", mode);
|
||||
info!("Checking for updates mode={} autodl={}", mode, auto_download);
|
||||
|
||||
let w = window.clone();
|
||||
let update_check_result = w
|
||||
@@ -105,42 +121,44 @@ impl YaakUpdater {
|
||||
None => false,
|
||||
Some(update) => {
|
||||
let w = window.clone();
|
||||
w.dialog()
|
||||
.message(format!(
|
||||
"{} is available. Would you like to download and install it now?",
|
||||
update.version
|
||||
))
|
||||
.buttons(MessageDialogButtons::OkCancelCustom(
|
||||
"Download".to_string(),
|
||||
"Later".to_string(),
|
||||
))
|
||||
.title("Update Available")
|
||||
.show(|confirmed| {
|
||||
if !confirmed {
|
||||
return;
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// Force native updater if specified (useful if a release broke the UI)
|
||||
let native_install_mode =
|
||||
update.raw_json.get("install_mode").map(|v| v.as_str()).unwrap_or_default()
|
||||
== Some("native");
|
||||
if native_install_mode {
|
||||
start_native_update(&w, &update).await;
|
||||
return;
|
||||
}
|
||||
|
||||
// If it's a background update, try downloading it first
|
||||
if update_trigger == UpdateTrigger::Background && auto_download {
|
||||
info!("Downloading update {} in background", update.version);
|
||||
if let Err(e) = download_update_idempotent(&w, &update).await {
|
||||
error!("Failed to download {}: {}", update.version, e);
|
||||
}
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match update.download_and_install(|_, _| {}, || {}).await {
|
||||
Ok(_) => {
|
||||
if w.dialog()
|
||||
.message("Would you like to restart the app?")
|
||||
.title("Update Installed")
|
||||
.buttons(MessageDialogButtons::OkCancelCustom(
|
||||
"Restart".to_string(),
|
||||
"Later".to_string(),
|
||||
))
|
||||
.blocking_show()
|
||||
{
|
||||
w.app_handle().restart();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
w.dialog()
|
||||
.message(format!("The update failed to install: {}", e));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
match start_integrated_update(&w, &update).await {
|
||||
Ok(UpdateResponseAction::Skip) => {
|
||||
info!("Confirmed {}: skipped", update.version);
|
||||
}
|
||||
Ok(UpdateResponseAction::Install) => {
|
||||
info!("Confirmed {}: install", update.version);
|
||||
if let Err(e) = install_update_maybe_download(&w, &update).await {
|
||||
error!("Failed to install: {e}");
|
||||
return;
|
||||
};
|
||||
|
||||
info!("Installed {}", update.version);
|
||||
finish_integrated_update(&w, &update).await;
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to notify frontend, falling back: {e}",);
|
||||
start_native_update(&w, &update).await;
|
||||
}
|
||||
};
|
||||
});
|
||||
true
|
||||
}
|
||||
};
|
||||
@@ -150,6 +168,7 @@ impl YaakUpdater {
|
||||
pub async fn maybe_check<R: Runtime>(
|
||||
&mut self,
|
||||
window: &WebviewWindow<R>,
|
||||
auto_download: bool,
|
||||
mode: UpdateMode,
|
||||
) -> Result<bool> {
|
||||
let update_period_seconds = match mode {
|
||||
@@ -163,11 +182,206 @@ impl YaakUpdater {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Don't check if dev
|
||||
// Don't check if development (can still with manual user trigger)
|
||||
if is_dev() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
self.check_now(window, mode, UpdateTrigger::Background).await
|
||||
self.check_now(window, mode, auto_download, UpdateTrigger::Background).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Default, TS)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "index.ts")]
|
||||
struct UpdateInfo {
|
||||
reply_event_id: String,
|
||||
version: String,
|
||||
downloaded: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", tag = "type")]
|
||||
#[ts(export, export_to = "index.ts")]
|
||||
enum UpdateResponse {
|
||||
Ack,
|
||||
Action { action: UpdateResponseAction },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "index.ts")]
|
||||
enum UpdateResponseAction {
|
||||
Install,
|
||||
Skip,
|
||||
}
|
||||
|
||||
async fn finish_integrated_update<R: Runtime>(window: &WebviewWindow<R>, update: &Update) {
|
||||
if let Err(e) = window.emit_to(window.label(), "update_installed", update.version.to_string()) {
|
||||
warn!("Failed to notify frontend of update install: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_integrated_update<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
update: &Update,
|
||||
) -> Result<UpdateResponseAction> {
|
||||
let download_path = ensure_download_path(window, update)?;
|
||||
debug!("Download path: {}", download_path.display());
|
||||
let downloaded = download_path.exists();
|
||||
let ack_wait = Duration::from_secs(3);
|
||||
let reply_id = generate_id();
|
||||
|
||||
// 1) Start listening BEFORE emitting to avoid missing a fast reply
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<UpdateResponse>();
|
||||
let w_for_listener = window.clone();
|
||||
|
||||
let event_id = w_for_listener.listen(reply_id.clone(), move |ev| {
|
||||
match serde_json::from_str::<UpdateResponse>(ev.payload()) {
|
||||
Ok(UpdateResponse::Ack) => {
|
||||
let _ = tx.send(UpdateResponse::Ack);
|
||||
}
|
||||
Ok(UpdateResponse::Action { action }) => {
|
||||
let _ = tx.send(UpdateResponse::Action { action });
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to parse update reply from frontend: {e:?}");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Make sure we always unlisten
|
||||
struct Unlisten<'a, R: Runtime> {
|
||||
win: &'a WebviewWindow<R>,
|
||||
id: tauri::EventId,
|
||||
}
|
||||
impl<'a, R: Runtime> Drop for Unlisten<'a, R> {
|
||||
fn drop(&mut self) {
|
||||
self.win.unlisten(self.id);
|
||||
}
|
||||
}
|
||||
let _guard = Unlisten {
|
||||
win: window,
|
||||
id: event_id,
|
||||
};
|
||||
|
||||
// 2) Emit the event now that listener is in place
|
||||
let info = UpdateInfo {
|
||||
version: update.version.to_string(),
|
||||
downloaded,
|
||||
reply_event_id: reply_id,
|
||||
};
|
||||
window
|
||||
.emit_to(window.label(), "update_available", &info)
|
||||
.map_err(|e| GenericError(format!("Failed to emit update_available: {e}")))?;
|
||||
|
||||
// 3) Two-stage timeout: first wait for ack, then wait for final action
|
||||
// --- Phase 1: wait for ACK with timeout ---
|
||||
let ack_timer = sleep(ack_wait);
|
||||
tokio::pin!(ack_timer);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
msg = rx.recv() => match msg {
|
||||
Some(UpdateResponse::Ack) => break, // proceed to Phase 2
|
||||
Some(UpdateResponse::Action{action}) => return Ok(action), // user was fast
|
||||
None => return Err(GenericError("frontend channel closed before ack".into())),
|
||||
},
|
||||
_ = &mut ack_timer => {
|
||||
return Err(GenericError("timed out waiting for frontend ack".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Phase 2: wait forever for final action ---
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Some(UpdateResponse::Action { action }) => return Ok(action),
|
||||
Some(UpdateResponse::Ack) => { /* ignore extra acks */ }
|
||||
None => return Err(GenericError("frontend channel closed before action".into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_native_update<R: Runtime>(window: &WebviewWindow<R>, update: &Update) {
|
||||
// If the frontend doesn't respond, fallback to native dialogs
|
||||
let confirmed = window
|
||||
.dialog()
|
||||
.message(format!(
|
||||
"{} is available. Would you like to download and install it now?",
|
||||
update.version
|
||||
))
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Download".to_string(), "Later".to_string()))
|
||||
.title("Update Available")
|
||||
.blocking_show();
|
||||
if !confirmed {
|
||||
return;
|
||||
}
|
||||
|
||||
match update.download_and_install(|_, _| {}, || {}).await {
|
||||
Ok(()) => {
|
||||
if window
|
||||
.dialog()
|
||||
.message("Would you like to restart the app?")
|
||||
.title("Update Installed")
|
||||
.buttons(MessageDialogButtons::OkCancelCustom(
|
||||
"Restart".to_string(),
|
||||
"Later".to_string(),
|
||||
))
|
||||
.blocking_show()
|
||||
{
|
||||
window.app_handle().request_restart();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
window.dialog().message(format!("The update failed to install: {}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn download_update_idempotent<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
update: &Update,
|
||||
) -> Result<PathBuf> {
|
||||
let dl_path = ensure_download_path(window, update)?;
|
||||
|
||||
if dl_path.exists() {
|
||||
info!("{} already downloaded to {}", update.version, dl_path.display());
|
||||
return Ok(dl_path);
|
||||
}
|
||||
|
||||
info!("{} downloading: {}", update.version, dl_path.display());
|
||||
let dl_bytes = update.download(|_, _| {}, || {}).await?;
|
||||
std::fs::write(&dl_path, dl_bytes)
|
||||
.map_err(|e| GenericError(format!("Failed to write update: {e}")))?;
|
||||
|
||||
info!("{} downloaded", update.version);
|
||||
|
||||
Ok(dl_path)
|
||||
}
|
||||
|
||||
pub async fn install_update_maybe_download<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
update: &Update,
|
||||
) -> Result<()> {
|
||||
let dl_path = download_update_idempotent(window, update).await?;
|
||||
let update_bytes = std::fs::read(&dl_path)?;
|
||||
update.install(update_bytes.as_slice())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn ensure_download_path<R: Runtime>(
|
||||
window: &WebviewWindow<R>,
|
||||
update: &Update,
|
||||
) -> Result<PathBuf> {
|
||||
// Ensure dir exists
|
||||
let base_dir = window.path().app_cache_dir()?.join("updates");
|
||||
std::fs::create_dir_all(&base_dir)?;
|
||||
|
||||
// Generate name based on signature
|
||||
let sig_digest = md5::compute(&update.signature);
|
||||
let name = format!("yaak-{}-{:x}", update.version, sig_digest);
|
||||
let dl_path = base_dir.join(name);
|
||||
|
||||
Ok(dl_path)
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
|
||||
message: format!("Installed {name}@{}", pv.version),
|
||||
color: Some(Color::Success),
|
||||
icon: None,
|
||||
timeout: Some(5000),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
@@ -90,6 +91,7 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
|
||||
message: "Failed to import data".to_string(),
|
||||
color: Some(Color::Danger),
|
||||
icon: None,
|
||||
timeout: None,
|
||||
},
|
||||
)?;
|
||||
return Ok(());
|
||||
@@ -103,6 +105,7 @@ pub(crate) async fn handle_deep_link<R: Runtime>(
|
||||
message: format!("Imported data for {} workspaces", results.workspaces.len()),
|
||||
color: Some(Color::Success),
|
||||
icon: None,
|
||||
timeout: Some(5000),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::error::Result;
|
||||
use crate::window_menu::app_menu;
|
||||
use log::{info, warn};
|
||||
use rand::random;
|
||||
@@ -32,9 +33,9 @@ pub(crate) struct CreateWindowConfig<'s> {
|
||||
pub(crate) fn create_window<R: Runtime>(
|
||||
handle: &AppHandle<R>,
|
||||
config: CreateWindowConfig,
|
||||
) -> WebviewWindow<R> {
|
||||
) -> Result<WebviewWindow<R>> {
|
||||
#[allow(unused_variables)]
|
||||
let menu = app_menu(handle).unwrap();
|
||||
let menu = app_menu(handle)?;
|
||||
|
||||
// This causes the window to not be clickable (in AppImage), so disable on Linux
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
@@ -48,19 +49,19 @@ pub(crate) fn create_window<R: Runtime>(
|
||||
.resizable(true)
|
||||
.visible(false) // To prevent theme flashing, the frontend code calls show() immediately after configuring the theme
|
||||
.fullscreen(false)
|
||||
.disable_drag_drop_handler() // Required for frontend Dnd on windows
|
||||
.min_inner_size(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT);
|
||||
|
||||
if let Some(key) = config.data_dir_key {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
use std::fs;
|
||||
let dir = handle.path().temp_dir().unwrap().join("yaak_sessions").join(key);
|
||||
fs::create_dir_all(dir.clone()).unwrap();
|
||||
let safe_key = format!("{:x}", md5::compute(key.as_bytes()));
|
||||
let dir = handle.path().app_data_dir()?.join("window-sessions").join(safe_key);
|
||||
fs::create_dir_all(&dir)?;
|
||||
win_builder = win_builder.data_directory(dir);
|
||||
}
|
||||
|
||||
// macOS doesn't support data dir so must use this fn instead
|
||||
// macOS doesn't support `data_directory()` so must use this fn instead
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let hash = md5::compute(key.as_bytes());
|
||||
@@ -108,11 +109,11 @@ pub(crate) fn create_window<R: Runtime>(
|
||||
|
||||
if let Some(w) = handle.webview_windows().get(config.label) {
|
||||
info!("Webview with label {} already exists. Focusing existing", config.label);
|
||||
w.set_focus().unwrap();
|
||||
return w.to_owned();
|
||||
w.set_focus()?;
|
||||
return Ok(w.to_owned());
|
||||
}
|
||||
|
||||
let win = win_builder.build().unwrap();
|
||||
let win = win_builder.build()?;
|
||||
|
||||
if let Some(tx) = config.close_tx {
|
||||
win.on_window_event(move |event| match event {
|
||||
@@ -174,10 +175,10 @@ pub(crate) fn create_window<R: Runtime>(
|
||||
}
|
||||
});
|
||||
|
||||
win
|
||||
Ok(win)
|
||||
}
|
||||
|
||||
pub(crate) fn create_main_window(handle: &AppHandle, url: &str) -> WebviewWindow {
|
||||
pub(crate) fn create_main_window(handle: &AppHandle, url: &str) -> Result<WebviewWindow> {
|
||||
let mut counter = 0;
|
||||
let label = loop {
|
||||
let label = format!("{MAIN_WINDOW_PREFIX}{counter}");
|
||||
@@ -211,13 +212,13 @@ pub(crate) fn create_child_window(
|
||||
label: &str,
|
||||
title: &str,
|
||||
inner_size: (f64, f64),
|
||||
) -> WebviewWindow {
|
||||
) -> Result<WebviewWindow> {
|
||||
let app_handle = parent_window.app_handle();
|
||||
let label = format!("{OTHER_WINDOW_PREFIX}_{label}");
|
||||
let scale_factor = parent_window.scale_factor().unwrap();
|
||||
let scale_factor = parent_window.scale_factor()?;
|
||||
|
||||
let current_pos = parent_window.inner_position().unwrap().to_logical::<f64>(scale_factor);
|
||||
let current_size = parent_window.inner_size().unwrap().to_logical::<f64>(scale_factor);
|
||||
let current_pos = parent_window.inner_position()?.to_logical::<f64>(scale_factor);
|
||||
let current_size = parent_window.inner_size()?.to_logical::<f64>(scale_factor);
|
||||
|
||||
// Position the new window in the middle of the parent
|
||||
let position = (
|
||||
@@ -235,7 +236,7 @@ pub(crate) fn create_child_window(
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let child_window = create_window(&app_handle, config);
|
||||
let child_window = create_window(&app_handle, config)?;
|
||||
|
||||
// NOTE: These listeners will remain active even when the windows close. Unfortunately,
|
||||
// there's no way to unlisten to events for now, so we just have to be defensive.
|
||||
@@ -272,5 +273,5 @@ pub(crate) fn create_child_window(
|
||||
});
|
||||
}
|
||||
|
||||
child_window
|
||||
Ok(child_window)
|
||||
}
|
||||
|
||||
BIN
src-tauri/static/greg.jpeg
Normal file
|
After Width: | Height: | Size: 10 KiB |