mirror of
https://github.com/storytold/artcraft.git
synced 2026-10-23 10:09:29 -04:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48f80f201b | ||
|
|
86c77e9625 | ||
|
|
776312ef6e | ||
|
|
7da40d5177 | ||
|
|
f06b5098e2 | ||
|
|
eac503af46 | ||
|
|
16932374f5 | ||
|
|
35940a4a63 | ||
|
|
55543b3735 | ||
|
|
3d44e6e29e | ||
|
|
3244b802fa | ||
|
|
5e7a5d2cff | ||
|
|
ecb73e4f80 | ||
|
|
39092fa866 | ||
|
|
ca80275d28 | ||
|
|
8c192b17f1 | ||
|
|
40da6f6500 | ||
|
|
2a3982aa5a | ||
|
|
a1c2b4f5c8 | ||
|
|
213d3f7bd2 | ||
|
|
0788e98b54 | ||
|
|
65c8ddfa91 | ||
|
|
a60e20c0b4 | ||
|
|
54d417f4c5 | ||
|
|
98a74e3a96 | ||
|
|
b537223ffa | ||
|
|
8001f24195 | ||
|
|
778a4e72c8 |
Generated
+38
-6
@@ -840,11 +840,14 @@ version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc2d0cfb2a7388d34f590e76686704c494ed7aaceed62ee1ba35cbf363abc2a5"
|
||||
dependencies = [
|
||||
"brotli 3.5.0",
|
||||
"flate2",
|
||||
"futures-core",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"zstd 0.13.1",
|
||||
"zstd-safe 7.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5345,6 +5348,7 @@ dependencies = [
|
||||
"hyper 1.6.0",
|
||||
"hyper-util",
|
||||
"rustls 0.23.13",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
@@ -9653,6 +9657,7 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls 0.23.13",
|
||||
"rustls-native-certs",
|
||||
"rustls-pemfile 2.1.2",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
@@ -9663,6 +9668,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-socks",
|
||||
"tokio-util",
|
||||
"tower 0.5.2",
|
||||
"tower-service",
|
||||
@@ -9990,6 +9996,19 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fcaf18a4f2be7326cd874a5fa579fae794320a0f388d365dca7e480e55f83f8a"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pemfile 2.1.2",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pemfile"
|
||||
version = "1.0.4"
|
||||
@@ -11299,6 +11318,7 @@ dependencies = [
|
||||
"enums",
|
||||
"enums_public",
|
||||
"errors",
|
||||
"idempotency",
|
||||
"log",
|
||||
"reqwest 0.12.15",
|
||||
"serde",
|
||||
@@ -11307,6 +11327,7 @@ dependencies = [
|
||||
"tokens",
|
||||
"tokio",
|
||||
"url",
|
||||
"uuid 1.8.0",
|
||||
"workspace-build-acceleration",
|
||||
]
|
||||
|
||||
@@ -12176,9 +12197,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin"
|
||||
version = "2.1.1"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4190775d6ff73fe66d9af44c012739a2659720efd9c0e1e56a918678038699d"
|
||||
checksum = "37a5ebe6a610d1b78a94650896e6f7c9796323f408800cef436e0fa0539de601"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"glob",
|
||||
@@ -12217,8 +12238,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "tauri-plugin-http"
|
||||
version = "2.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40dcd6c922a1885e1f0bcebc6768fec6e005bd4b9001c5d90a2f5d4cab297729"
|
||||
dependencies = [
|
||||
"bytes 1.10.0",
|
||||
"cookie_store",
|
||||
@@ -12234,6 +12253,7 @@ dependencies = [
|
||||
"tauri-plugin-fs",
|
||||
"thiserror 2.0.12",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
"urlpattern",
|
||||
]
|
||||
@@ -12350,9 +12370,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.3.1"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f037e66c7638cc0a2213f61566932b9a06882b8346486579c90e4b019bac447"
|
||||
checksum = "b2900399c239a471bcff7f15c4399eb1a8c4fe511ba2853e07c996d771a5e0a4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli 7.0.0",
|
||||
@@ -12835,6 +12855,18 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-socks"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d4770b8024672c1101b3f6733eab95b18007dbe0847a8afe341fcf79e06043f"
|
||||
dependencies = [
|
||||
"either",
|
||||
"futures-util",
|
||||
"thiserror 1.0.63",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-stream"
|
||||
version = "0.1.16"
|
||||
|
||||
@@ -118,6 +118,7 @@ members = [
|
||||
"crates/vendor/candle/candle-transformers",
|
||||
"crates/vendor/candle/tensor-tools",
|
||||
"crates/vendor/limitation",
|
||||
"crates/vendor/tauri-plugin-http",
|
||||
# NB(bt,2023-12-12): Newrelic keeps breaking with upgrades. Kill for now.
|
||||
#"crates/vendor/newrelic-telemetry-sdk-rust",
|
||||
|
||||
@@ -173,6 +174,7 @@ serde_derive = "1.0.219"
|
||||
serde_json = "1.0.140"
|
||||
serde_yaml = "0.9.1"
|
||||
sha3 = "0.10.8"
|
||||
tauri = { version = "2.4.1", features = ["unstable"] }
|
||||
thiserror = "2.0.12"
|
||||
toml = "0.8.20"
|
||||
url = { version = "2.5.4", features = ["serde"] }
|
||||
@@ -183,6 +185,7 @@ enums = { path = "crates/_types/enums" }
|
||||
enums_public = { path = "crates/_types/enums_public" }
|
||||
errors = { path = "crates/lib/errors" }
|
||||
filesys = { path = "crates/lib/files/filesys" }
|
||||
idempotency = { path = "crates/lib/idempotency" }
|
||||
images = { path = "crates/lib/files/images" }
|
||||
memory_caching = { path = "crates/lib/caching/memory_caching" }
|
||||
memory_store = { path = "crates/lib/caching/memory_store" }
|
||||
|
||||
@@ -53,14 +53,16 @@ serde = { workspace = true }
|
||||
serde_derive = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
tauri = { version = "2.4.1", features = ["unstable"] }
|
||||
tauri-plugin-http = "2.0.0"
|
||||
tauri = { workspace = true }
|
||||
tauri-plugin-log = "2.3.1"
|
||||
tempdir = "0.3.7"
|
||||
tempfile = "3.18.0"
|
||||
tokio = { version = "1.42", features = ["rt", "rt-multi-thread", "fs"] }
|
||||
tokio-util = { version = "0.7", features = ["codec"] }
|
||||
|
||||
# NB: We need to vendor this in so that we can access the cookies inside via the private API
|
||||
tauri-plugin-http = { path = "../../vendor/tauri-plugin-http" }
|
||||
|
||||
# NB: The version of the `discord-rich-presence` crate (0.2.5) last published has non-Send/Sync error
|
||||
# types and can't do threading. We need to wait for a new version to unpin from Git.
|
||||
discord-rich-presence = { git = "https://github.com/vionya/discord-rich-presence" }
|
||||
|
||||
@@ -80,6 +80,7 @@ pub fn run() {
|
||||
let app_data_root_3 = app_data_root_2.clone();
|
||||
let app_data_root_4 = app_data_root_2.clone();
|
||||
let sora_creds_manager_3 = sora_creds_manager_2.clone();
|
||||
let storyteller_creds_manager_3 = storyteller_creds_manager.clone();
|
||||
|
||||
match MainWindowSize::from_filesystem_configs(&app_data_root_3) {
|
||||
Ok(None) => {}
|
||||
@@ -97,7 +98,7 @@ pub fn run() {
|
||||
|
||||
tauri::async_runtime::spawn(sora_session_login_thread(app_2, app_data_root_2, sora_creds_manager_2));
|
||||
tauri::async_runtime::spawn(main_window_thread(app_3, app_data_root_3, storyteller_creds_manager_2));
|
||||
tauri::async_runtime::spawn(sora_task_polling_thread(app_data_root_4, sora_creds_manager_3, sora_task_queue_2));
|
||||
tauri::async_runtime::spawn(sora_task_polling_thread(app_data_root_4, sora_creds_manager_3, storyteller_creds_manager_3, sora_task_queue_2));
|
||||
tauri::async_runtime::spawn(discord_presence_thread());
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -24,6 +24,7 @@ pub async fn main_window_thread(
|
||||
for (window_name, window) in app.windows() {
|
||||
if window_name == MAIN_WINDOW_NAME {
|
||||
let result = handle_main_window(
|
||||
&app,
|
||||
&window,
|
||||
&app_data_root,
|
||||
&storyteller_creds_manager,
|
||||
@@ -40,6 +41,7 @@ pub async fn main_window_thread(
|
||||
}
|
||||
|
||||
pub async fn handle_main_window(
|
||||
app: &AppHandle,
|
||||
window: &Window,
|
||||
app_data_root: &AppDataRoot,
|
||||
storyteller_creds_manager: &StorytellerCredentialManager,
|
||||
@@ -48,7 +50,7 @@ pub async fn handle_main_window(
|
||||
) -> AnyhowResult<()> {
|
||||
loop {
|
||||
log_errors(persist_window_resize_task(window, app_data_root, window_size_slot).await);
|
||||
log_errors(persist_storyteller_cookies_task(window, app_data_root, storyteller_creds_manager, app_startup_time).await);
|
||||
log_errors(persist_storyteller_cookies_task(app, storyteller_creds_manager, app_startup_time).await);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1_000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
+41
-46
@@ -1,18 +1,21 @@
|
||||
use crate::state::app_startup_time::AppStartupTime;
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::storyteller::storyteller_credential_manager::StorytellerCredentialManager;
|
||||
use crate::threads::sora_session_login_thread::LOGIN_WINDOW_NAME;
|
||||
use anyhow::anyhow;
|
||||
use chrono::TimeDelta;
|
||||
use errors::AnyhowResult;
|
||||
use log::{debug, error, info};
|
||||
use once_cell::sync::Lazy;
|
||||
use reqwest::Url;
|
||||
use std::fs;
|
||||
use chrono::TimeDelta;
|
||||
use std::sync::LockResult;
|
||||
use storyteller_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
|
||||
use storyteller_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use storyteller_client::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
use tauri::{AppHandle, Manager, Webview, Window};
|
||||
use crate::state::app_startup_time::AppStartupTime;
|
||||
use tauri_plugin_http::reqwest_cookie_store::CookieStore;
|
||||
use tauri_plugin_http::Http;
|
||||
|
||||
const MAIN_WEBVIEW_NAME: &str = "main";
|
||||
|
||||
@@ -29,82 +32,74 @@ const SESSION_COOKIE_NAME : &str = "session";
|
||||
const RACE_CONDITION_WAIT_TIME: TimeDelta = TimeDelta::milliseconds(5000);
|
||||
|
||||
pub async fn persist_storyteller_cookies_task(
|
||||
window: &Window,
|
||||
app_data_root: &AppDataRoot,
|
||||
app: &AppHandle,
|
||||
storyteller_credential_manager: &StorytellerCredentialManager,
|
||||
app_startup_time: &AppStartupTime,
|
||||
) -> AnyhowResult<()> {
|
||||
|
||||
if app_startup_time.time_delta_since() < RACE_CONDITION_WAIT_TIME {
|
||||
// NB: There's an issue when the "main window thread" inquires about the
|
||||
// webview cookies shortly after app startup. When it attempts to dump the
|
||||
// cookies within a few milliseconds of app launch, it deadlocks and the
|
||||
// app never launches correctly. The entire webview goes blank and the app
|
||||
// freezes. This hack seems to fix the problem.
|
||||
return Ok(())
|
||||
}
|
||||
//if app_startup_time.time_delta_since() < RACE_CONDITION_WAIT_TIME {
|
||||
// // NB: There's an issue when the "main window thread" inquires about the
|
||||
// // webview cookies shortly after app startup. When it attempts to dump the
|
||||
// // cookies within a few milliseconds of app launch, it deadlocks and the
|
||||
// // app never launches correctly. The entire webview goes blank and the app
|
||||
// // freezes. This hack seems to fix the problem.
|
||||
// return Ok(())
|
||||
//}
|
||||
|
||||
for webview in window.webviews() {
|
||||
let label = webview.label();
|
||||
if label == MAIN_WEBVIEW_NAME {
|
||||
persist_webview_cookies(&webview, app_data_root, storyteller_credential_manager).await?;
|
||||
break;
|
||||
let maybe_http = app.try_state::<Http>();
|
||||
|
||||
let http = match maybe_http {
|
||||
None => {
|
||||
error!("No HTTP plugin found");
|
||||
return Err(anyhow!("No HTTP plugin found"));
|
||||
}
|
||||
Some(http) => http,
|
||||
};
|
||||
|
||||
match http.cookies_jar.store.lock() {
|
||||
Err(err) => {
|
||||
error!("Failed to lock cookie jar: {:?}", err);
|
||||
return Err(anyhow!("Failed to lock cookie jar"));
|
||||
}
|
||||
Ok(cookie_jar) => {
|
||||
sync_tauri_credentials(&cookie_jar, storyteller_credential_manager)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn persist_webview_cookies(
|
||||
webview: &Webview,
|
||||
app_data_root: &AppDataRoot,
|
||||
fn sync_tauri_credentials(
|
||||
cookie_store: &CookieStore,
|
||||
storyteller_credential_manager: &StorytellerCredentialManager,
|
||||
) -> AnyhowResult<()> {
|
||||
let current_webview_credentials = get_storyteller_cookies(webview).await?;
|
||||
let current_http_plugin_credentials = get_credentials_from_cookie_store(cookie_store)?;
|
||||
|
||||
if current_webview_credentials.is_empty() {
|
||||
// TODO: handle logout / cookie deletion
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut replace_credentials = true;
|
||||
|
||||
let maybe_old_credentials = storyteller_credential_manager.get_credentials()?;
|
||||
|
||||
if let Some(old_credentials) = maybe_old_credentials {
|
||||
if old_credentials.equals(¤t_webview_credentials) {
|
||||
if old_credentials.equals(¤t_http_plugin_credentials) {
|
||||
replace_credentials = false;
|
||||
}
|
||||
}
|
||||
|
||||
if replace_credentials {
|
||||
info!("Writing ArtCraft credentials to disk...");
|
||||
storyteller_credential_manager.set_credentials(¤t_webview_credentials)?;
|
||||
storyteller_credential_manager.persist_all_to_disk()?;
|
||||
info!("Syncing ArtCraft credentials ...");
|
||||
storyteller_credential_manager.set_credentials(¤t_http_plugin_credentials)?;
|
||||
// NB: tauri-plugin-http stores the credentials on disk, so we can defer to that for now.
|
||||
//storyteller_credential_manager.persist_all_to_disk()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_storyteller_cookies(webview: &Webview) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
debug!("Getting storyteller cookies...");
|
||||
|
||||
//// FIXME: THIS IS A TOTAL HACK. / DO NOT REMOVE.
|
||||
//// NB: If we don't call a method on the webview, the very next call to get cookies will deadlock.
|
||||
//if let Ok(url) = webview.url() {
|
||||
// debug!("For url: {:?}", url);
|
||||
//}
|
||||
|
||||
let cookies = webview.cookies_for_url(STORYTELLER_ROOT_COOKIE_URL.clone())?;
|
||||
|
||||
info!("Got storyteller cookies: {:?}", cookies);
|
||||
info!("Got storyteller cookies: {:?}", cookies.len());
|
||||
info!("Got storyteller location: {:?}", webview.url());
|
||||
|
||||
pub fn get_credentials_from_cookie_store(cookie_jar: &CookieStore) -> AnyhowResult<StorytellerCredentialSet> {
|
||||
let mut avt_cookie = None;
|
||||
let mut session_cookie = None;
|
||||
|
||||
for cookie in cookies.into_iter() {
|
||||
for cookie in cookie_jar.iter_unexpired() {
|
||||
if let Some(avt) = StorytellerAvtCookie::maybe_from_cookie(&cookie) {
|
||||
avt_cookie = Some(avt);
|
||||
} else if let Some(session) = StorytellerSessionCookie::maybe_from_cookie(&cookie) {
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
use crate::state::data_dir::app_data_root::AppDataRoot;
|
||||
use crate::state::data_dir::trait_data_subdir::DataSubdir;
|
||||
use crate::state::sora::sora_credential_manager::SoraCredentialManager;
|
||||
use crate::state::sora::sora_task_queue::SoraTaskQueue;
|
||||
use crate::state::storyteller::storyteller_credential_manager::StorytellerCredentialManager;
|
||||
use errors::AnyhowResult;
|
||||
use log::{error, info};
|
||||
use openai_sora_client::recipes::list_sora_task_status_with_session_auto_renew::{list_sora_task_status_with_session_auto_renew, StatusRequestArgs};
|
||||
use openai_sora_client::requests::image_gen::image_gen_status::{TaskId, TaskStatus};
|
||||
use openai_sora_client::requests::image_gen::image_gen_status::{Generation, TaskId, TaskStatus};
|
||||
use reqwest::Url;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use tauri::AppHandle;
|
||||
use tempdir::TempDir;
|
||||
use storyteller_client::media_files::upload_image_media_file_from_file::upload_image_media_file_from_file;
|
||||
use storyteller_client::utils::api_host::ApiHost;
|
||||
|
||||
pub async fn sora_task_polling_thread(
|
||||
app_data_root: AppDataRoot,
|
||||
sora_creds_manager: SoraCredentialManager,
|
||||
storyteller_creds_manager: StorytellerCredentialManager,
|
||||
sora_task_queue: SoraTaskQueue,
|
||||
) -> ! {
|
||||
loop {
|
||||
let res = polling_loop(&sora_creds_manager, &sora_task_queue).await;
|
||||
let res = polling_loop(
|
||||
&sora_creds_manager,
|
||||
&storyteller_creds_manager,
|
||||
&sora_task_queue,
|
||||
&app_data_root,
|
||||
).await;
|
||||
if let Err(err) = res {
|
||||
error!("An error occurred: {:?}", err);
|
||||
}
|
||||
@@ -23,7 +38,9 @@ pub async fn sora_task_polling_thread(
|
||||
|
||||
async fn polling_loop(
|
||||
sora_creds_manager: &SoraCredentialManager,
|
||||
storyteller_creds_manager: &StorytellerCredentialManager,
|
||||
sora_task_queue: &SoraTaskQueue,
|
||||
app_data_root: &AppDataRoot,
|
||||
) -> AnyhowResult<()> {
|
||||
loop {
|
||||
if sora_task_queue.is_empty()? {
|
||||
@@ -74,8 +91,26 @@ async fn polling_loop(
|
||||
.collect();
|
||||
|
||||
sora_task_queue.remove_list(&failed_task_ids)?;
|
||||
|
||||
let creds = storyteller_creds_manager.get_credentials_required()?;
|
||||
let api_host = ApiHost::Storyteller;
|
||||
|
||||
// TODO: Handle succeeded tasks.
|
||||
for task in succeeded_tasks.iter() {
|
||||
if !sora_task_queue.contains_key(&task.id)? {
|
||||
continue;
|
||||
}
|
||||
info!("Task succeeded: {:?}", task.id);
|
||||
|
||||
for (i, generation) in task.generations.iter().enumerate() {
|
||||
info!("Downloading generated file...");
|
||||
let download_path = download_generation(generation, &app_data_root).await?;
|
||||
|
||||
info!("Uploading to backend...");
|
||||
let result = upload_image_media_file_from_file(&api_host, Some(&creds), download_path).await?;
|
||||
|
||||
info!("Uploaded to API backend: {:?}", result.media_file_token);
|
||||
}
|
||||
}
|
||||
|
||||
let succeeded_task_ids : Vec<&TaskId> = succeeded_tasks
|
||||
.iter()
|
||||
@@ -87,3 +122,21 @@ async fn polling_loop(
|
||||
tokio::time::sleep(std::time::Duration::from_millis(2_000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn download_generation(generation: &Generation, app_data_root: &AppDataRoot) -> AnyhowResult<PathBuf> {
|
||||
let url = Url::parse(&generation.url)?;
|
||||
|
||||
let response = reqwest::get(&generation.url).await?;
|
||||
let image_bytes = response.bytes().await?;
|
||||
|
||||
let ext = url.path().split(".").last().unwrap_or("png");
|
||||
|
||||
let tempdir = app_data_root.temp_dir().path();
|
||||
let download_filename = format!("{}.{}", generation.id, ext);
|
||||
let download_path = tempdir.join(download_filename);
|
||||
|
||||
let mut file = File::create(&download_path)?;
|
||||
file.write_all(&image_bytes)?;
|
||||
|
||||
Ok(download_path)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# For some reason, we can't pass json files to the tauri dev command
|
||||
[build]
|
||||
frontendDist = "../../../frontend/apps/editor2d/dist"
|
||||
beforeDevCommand = "nx run editor2d:dev"
|
||||
beforeDevCommand = "npx nx run editor2d:dev"
|
||||
devUrl = "http://localhost:5741"
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# For some reason, we can't pass json files to the tauri dev command
|
||||
[build]
|
||||
frontendDist = "../../../frontend/apps/editor2d/dist"
|
||||
beforeDevCommand = "echo 'no dev'"
|
||||
devUrl = "http://localhost:5741"
|
||||
@@ -1,5 +1,5 @@
|
||||
# For some reason, we can't pass json files to the tauri dev command
|
||||
[build]
|
||||
frontendDist = "../../../frontend/apps/editor3d/dist"
|
||||
beforeDevCommand = "nx run editor3d:dev"
|
||||
beforeDevCommand = "npx nx run editor3d:dev"
|
||||
devUrl = "http://localhost:5173"
|
||||
|
||||
@@ -20,7 +20,11 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": null,
|
||||
"headers": {
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp"
|
||||
}
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
@@ -20,6 +20,7 @@ workspace-build-acceleration = { workspace = true }
|
||||
enums = { workspace = true }
|
||||
enums_public = { workspace = true }
|
||||
errors = { workspace = true }
|
||||
idempotency = { workspace = true }
|
||||
tokens = { workspace = true }
|
||||
|
||||
# External
|
||||
@@ -36,7 +37,8 @@ serde_derive = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# HTTP
|
||||
backoff = { version = "0.4.0", features = ["futures"] } # Exponential backoff retry
|
||||
backoff = { version = "0.4.0", features = ["futures"] }
|
||||
uuid = { version = "1.8.0", features = ["v4"] } # Exponential backoff retry
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.38.0", features = ["macros"] }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::io;
|
||||
use errors::AnyhowError;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -33,6 +34,9 @@ pub enum ApiError {
|
||||
|
||||
/// Uncategorized reqwest error.
|
||||
OtherReqwestError(reqwest::Error),
|
||||
|
||||
/// An error doing file I/O (on our side)
|
||||
IoError(io::Error),
|
||||
|
||||
/// Another type of error.
|
||||
Other(AnyhowError),
|
||||
@@ -55,6 +59,8 @@ impl Display for ApiError {
|
||||
// Network errors
|
||||
ApiError::Timeout(msg) => write!(f, "Timeout: {}", msg),
|
||||
ApiError::NetworkError(msg) => write!(f, "Network error: {}", msg),
|
||||
// I/O errors
|
||||
ApiError::IoError(error) => write!(f, "IO error: {}", error),
|
||||
// Other
|
||||
ApiError::OtherReqwestError(error) => write!(f, "Reqwest error: {}", error),
|
||||
ApiError::Other(error) => write!(f, "Other error: {}", error),
|
||||
@@ -79,3 +85,9 @@ impl From<serde_json::Error> for ApiError {
|
||||
ApiError::DeserializationError(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for ApiError {
|
||||
fn from(error: io::Error) -> Self {
|
||||
ApiError::IoError(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,4 +37,8 @@ impl StorytellerAvtCookie {
|
||||
pub fn equals(&self, other: &Self) -> bool {
|
||||
self.cookie == other.cookie
|
||||
}
|
||||
|
||||
pub fn as_cookie_header(&self) -> String {
|
||||
format!("{}={}", AVT_COOKIE_NAME, self.cookie)
|
||||
}
|
||||
}
|
||||
|
||||
+67
@@ -66,4 +66,71 @@ impl StorytellerCredentialSet {
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub fn maybe_as_cookie_header(&self) -> Option<String> {
|
||||
let mut cookies = Vec::new();
|
||||
|
||||
if let Some(avt) = &self.avt {
|
||||
cookies.push(avt.as_cookie_header());
|
||||
}
|
||||
|
||||
if let Some(session) = &self.session {
|
||||
cookies.push(session.as_cookie_header());
|
||||
}
|
||||
|
||||
if cookies.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(cookies.join("; "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
|
||||
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use crate::credentials::storyteller_session_cookie::StorytellerSessionCookie;
|
||||
|
||||
mod cookies_header {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_cookie() {
|
||||
let creds = StorytellerCredentialSet::empty();
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn avt_cookies_header() {
|
||||
let creds = StorytellerCredentialSet::initialize_with_just_avt(
|
||||
StorytellerAvtCookie::new("bob".to_string()),
|
||||
);
|
||||
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, Some("visitor=bob".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cookies_header() {
|
||||
let creds = StorytellerCredentialSet::initialize_with_just_cookie(
|
||||
StorytellerSessionCookie::new("bob".to_string()),
|
||||
);
|
||||
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, Some("session=bob".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_cookies_header() {
|
||||
let creds = StorytellerCredentialSet::initialize(
|
||||
Some(StorytellerAvtCookie::new("bob".to_string())),
|
||||
Some(StorytellerSessionCookie::new("alice".to_string())),
|
||||
);
|
||||
|
||||
let header = creds.maybe_as_cookie_header();
|
||||
assert_eq!(header, Some("visitor=bob; session=alice".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -36,4 +36,8 @@ impl StorytellerSessionCookie {
|
||||
pub fn equals(&self, other: &Self) -> bool {
|
||||
self.cookie == other.cookie
|
||||
}
|
||||
|
||||
pub fn as_cookie_header(&self) -> String {
|
||||
format!("{}={}", SESSION_COOKIE_NAME, self.cookie)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,3 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use log::debug;
|
||||
use serde_derive::{Deserialize};
|
||||
use enums::by_table::media_files::media_file_animation_type::MediaFileAnimationType;
|
||||
use enums::by_table::media_files::media_file_class::MediaFileClass;
|
||||
use enums::by_table::media_files::media_file_engine_category::MediaFileEngineCategory;
|
||||
use enums::by_table::media_files::media_file_type::MediaFileType;
|
||||
use enums::by_table::model_weights::weights_category::WeightsCategory;
|
||||
use enums::common::visibility::Visibility;
|
||||
use enums::no_table::style_transfer::style_transfer_name::StyleTransferName;
|
||||
use enums_public::by_table::model_weights::public_weights_types::PublicWeightsType;
|
||||
use tokens::tokens::batch_generations::BatchGenerationToken;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use tokens::tokens::model_weights::ModelWeightToken;
|
||||
use tokens::tokens::prompts::PromptToken;
|
||||
use crate::api_error::ApiError;
|
||||
use crate::shared_response_types::media_file_cover_image_details::MediaFileCoverImageDetails;
|
||||
use crate::shared_response_types::media_links::MediaLinks;
|
||||
@@ -21,6 +6,21 @@ use crate::shared_response_types::user_details_light::UserDetailsLight;
|
||||
use crate::utils::api_host::ApiHost;
|
||||
use crate::utils::filter_bad_response::filter_bad_response;
|
||||
use crate::utils::http_get_anonymous::http_get_anonymous;
|
||||
use chrono::{DateTime, Utc};
|
||||
use enums::by_table::media_files::media_file_animation_type::MediaFileAnimationType;
|
||||
use enums::by_table::media_files::media_file_class::MediaFileClass;
|
||||
use enums::by_table::media_files::media_file_engine_category::MediaFileEngineCategory;
|
||||
use enums::by_table::media_files::media_file_type::MediaFileType;
|
||||
use enums::by_table::model_weights::weights_category::WeightsCategory;
|
||||
use enums::common::visibility::Visibility;
|
||||
use enums::no_table::style_transfer::style_transfer_name::StyleTransferName;
|
||||
use enums_public::by_table::model_weights::public_weights_types::PublicWeightsType;
|
||||
use log::debug;
|
||||
use serde_derive::Deserialize;
|
||||
use tokens::tokens::batch_generations::BatchGenerationToken;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use tokens::tokens::model_weights::ModelWeightToken;
|
||||
use tokens::tokens::prompts::PromptToken;
|
||||
|
||||
/// Get details about a media file from our backend
|
||||
pub async fn get_media_file(api_host: &ApiHost, media_file_token: &MediaFileToken) -> Result<GetMediaFileSuccessResponse, ApiError> {
|
||||
@@ -205,9 +205,9 @@ pub struct GetMediaFileModelInfo {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use crate::media_files::get_media_file::get_media_file;
|
||||
use crate::utils::api_host::ApiHost;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // Don't run in CI. Requires valid cookie
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
pub mod get_media_file;
|
||||
pub mod get_media_file;
|
||||
pub mod upload_image_media_file_from_file;
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
use crate::api_error::ApiError;
|
||||
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
|
||||
use crate::shared_response_types::media_file_cover_image_details::MediaFileCoverImageDetails;
|
||||
use crate::shared_response_types::media_links::MediaLinks;
|
||||
use crate::shared_response_types::simple_entity_stats::SimpleEntityStats;
|
||||
use crate::shared_response_types::user_details_light::UserDetailsLight;
|
||||
use crate::utils::api_host::ApiHost;
|
||||
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
|
||||
use crate::utils::filter_bad_response::filter_bad_response;
|
||||
use crate::utils::http_get_anonymous::http_get_anonymous;
|
||||
use chrono::{DateTime, Utc};
|
||||
use enums::by_table::media_files::media_file_animation_type::MediaFileAnimationType;
|
||||
use enums::by_table::media_files::media_file_class::MediaFileClass;
|
||||
use enums::by_table::media_files::media_file_engine_category::MediaFileEngineCategory;
|
||||
use enums::by_table::media_files::media_file_type::MediaFileType;
|
||||
use enums::by_table::model_weights::weights_category::WeightsCategory;
|
||||
use enums::common::visibility::Visibility;
|
||||
use enums::no_table::style_transfer::style_transfer_name::StyleTransferName;
|
||||
use enums_public::by_table::model_weights::public_weights_types::PublicWeightsType;
|
||||
use idempotency::uuid::generate_random_uuid;
|
||||
use log::debug;
|
||||
use reqwest::multipart::Form;
|
||||
use reqwest::Client;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use tokens::tokens::batch_generations::BatchGenerationToken;
|
||||
use tokens::tokens::media_files::MediaFileToken;
|
||||
use tokens::tokens::model_weights::ModelWeightToken;
|
||||
use tokens::tokens::prompts::PromptToken;
|
||||
use uuid::uuid;
|
||||
|
||||
/// Upload an image media file from a file.
|
||||
pub async fn upload_image_media_file_from_file<P: AsRef<Path>>(
|
||||
api_host: &ApiHost,
|
||||
maybe_creds: Option<&StorytellerCredentialSet>,
|
||||
path: P,
|
||||
) -> Result<UploadImageMediaFileSuccessResponse, ApiError> {
|
||||
|
||||
let url = get_route(api_host);
|
||||
|
||||
debug!("Requesting {:?}", &url);
|
||||
|
||||
//let mut file = File::open(path)?;
|
||||
|
||||
let client = Client::builder()
|
||||
.gzip(true)
|
||||
.build()?;
|
||||
|
||||
let form = Form::new()
|
||||
.text("uuid_idempotency_token", generate_random_uuid())
|
||||
.file("file", path)
|
||||
.await?;
|
||||
|
||||
let mut request_builder = client.post(url)
|
||||
.header("User-Agent", USER_AGENT)
|
||||
.header("Accept", APPLICATION_JSON);
|
||||
|
||||
if let Some(creds) = maybe_creds {
|
||||
if let Some(header) = &creds.maybe_as_cookie_header() {
|
||||
request_builder = request_builder.header("Cookie", header);
|
||||
}
|
||||
}
|
||||
|
||||
let response = request_builder
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let response = filter_bad_response(response).await?;
|
||||
let response_body = &response.text().await?;
|
||||
|
||||
let media_file = serde_json::from_str(&response_body)?;
|
||||
|
||||
Ok(media_file)
|
||||
}
|
||||
|
||||
fn get_route(api_host: &ApiHost) -> String {
|
||||
let api_hostname = api_host.to_api_hostname();
|
||||
format!("https://{}/v1/media_files/upload/image", api_hostname)
|
||||
}
|
||||
|
||||
// TODO(bt,2025-04-22): Share API definitions between client and server in common crate.
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UploadImageMediaFileSuccessResponse {
|
||||
pub success: bool,
|
||||
pub media_file_token: MediaFileToken,
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
pub const USER_AGENT: &str = "storyteller-client/1.0";
|
||||
|
||||
pub const APPLICATION_JSON : &str = "application/json";
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod api_host;
|
||||
pub mod constants;
|
||||
pub mod filter_bad_response;
|
||||
pub mod http_get_anonymous;
|
||||
pub mod status_codes;
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
# Changelog
|
||||
|
||||
## \[2.4.3]
|
||||
|
||||
- [`37c0477a`](https://github.com/tauri-apps/plugins-workspace/commit/37c0477afe926d326573f1827045875ce8bf8187) ([#2561](https://github.com/tauri-apps/plugins-workspace/pull/2561)) Add `zstd` cargo feature flag to enable `reqwest/zstd` flag.
|
||||
- [`9ebbfb2e`](https://github.com/tauri-apps/plugins-workspace/commit/9ebbfb2e3ccef8e0f277a0c02fe6b399b41feeb6) ([#1978](https://github.com/tauri-apps/plugins-workspace/pull/1978)) Persist cookies to disk and load it on next app start.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs-js@2.2.1`
|
||||
|
||||
## \[2.4.2]
|
||||
|
||||
- [`a15eedf3`](https://github.com/tauri-apps/plugins-workspace/commit/a15eedf37854344f7ffbcb0d373d848563817011) ([#2535](https://github.com/tauri-apps/plugins-workspace/pull/2535) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix `fetch` occasionally throwing an error due to trying to close the underline stream twice.
|
||||
|
||||
## \[2.4.1]
|
||||
|
||||
- [`d3183aa9`](https://github.com/tauri-apps/plugins-workspace/commit/d3183aa99da7ca67e627394132ddeb3b85ccef06) ([#2522](https://github.com/tauri-apps/plugins-workspace/pull/2522) by [@adrieljss](https://github.com/tauri-apps/plugins-workspace/../../adrieljss)) Fix `fetch` blocking until the whole response is read even if it was a streaming response.
|
||||
|
||||
## \[2.4.0]
|
||||
|
||||
- [`cb38f54f`](https://github.com/tauri-apps/plugins-workspace/commit/cb38f54f4a4ef30995283cd82166c62da17bac44) ([#2479](https://github.com/tauri-apps/plugins-workspace/pull/2479) by [@adrieljss](https://github.com/tauri-apps/plugins-workspace/../../adrieljss)) Add stream support for HTTP stream responses.
|
||||
|
||||
## \[2.3.0]
|
||||
|
||||
- [`10513649`](https://github.com/tauri-apps/plugins-workspace/commit/105136494c5a5bf4b1f1cc06cc71815412d17ec8) ([#2204](https://github.com/tauri-apps/plugins-workspace/pull/2204) by [@RickeyWard](https://github.com/tauri-apps/plugins-workspace/../../RickeyWard)) Add `dangerous-settings` feature flag and new JS `danger` option to disable tls hostname/certificate validation.
|
||||
|
||||
## \[2.2.0]
|
||||
|
||||
- [`3a79266b`](https://github.com/tauri-apps/plugins-workspace/commit/3a79266b8cf96a55b1ae6339d725567d45a44b1d) ([#2173](https://github.com/tauri-apps/plugins-workspace/pull/2173) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) Bumped all plugins to `v2.2.0`. From now, the versions for the Rust and JavaScript packages of each plugin will be in sync with each other.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.2.0`
|
||||
|
||||
## \[2.0.2]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs-js@2.0.4`
|
||||
|
||||
## \[2.0.4]
|
||||
|
||||
- [`a3b553dd`](https://github.com/tauri-apps/plugins-workspace/commit/a3b553ddb403771aa699362c4e69a064b7731da5) ([#2079](https://github.com/tauri-apps/plugins-workspace/pull/2079) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Add tracing logs for requestes and responses behind `tracing` feature flag.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.1.0`
|
||||
|
||||
## \[2.0.3]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.3`
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`cfd48b3b`](https://github.com/tauri-apps/plugins-workspace/commit/cfd48b3b2ec0fccfc162197518694ed59ceda22c) ([#1941](https://github.com/tauri-apps/plugins-workspace/pull/1941) by [@Nipsuli](https://github.com/tauri-apps/plugins-workspace/../../Nipsuli)) Allow skipping sending `Origin` header in HTTP requests by setting `Origin` header to an empty string when calling `fetch`.
|
||||
- [`9b2840db`](https://github.com/tauri-apps/plugins-workspace/commit/9b2840db9464cf08db75806270e4441f0af81e5d) ([#1884](https://github.com/tauri-apps/plugins-workspace/pull/1884) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Retain headers order.
|
||||
|
||||
## \[2.0.1]
|
||||
|
||||
- [`a1a82208`](https://github.com/tauri-apps/plugins-workspace/commit/a1a82208ed4ab87f83310be0dc95428aec9ab241) ([#1873](https://github.com/tauri-apps/plugins-workspace/pull/1873) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Downgrade MSRV to 1.77.2 to support Windows 7.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.1`
|
||||
|
||||
## \[2.0.0]
|
||||
|
||||
- [`e2c4dfb6`](https://github.com/tauri-apps/plugins-workspace/commit/e2c4dfb6af43e5dd8d9ceba232c315f5febd55c1) Update to tauri v2 stable release.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0`
|
||||
|
||||
## \[2.0.0-rc.6]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.6`
|
||||
|
||||
## \[2.0.0-rc.5]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.5`
|
||||
|
||||
## \[2.0.0-rc.4]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.4`
|
||||
|
||||
## \[2.0.0-rc.3]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.3`
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.2`
|
||||
|
||||
## \[2.0.0-rc.2]
|
||||
|
||||
- [`e2e97db5`](https://github.com/tauri-apps/plugins-workspace/commit/e2e97db51983267f5be84d4f6f0278d58834d1f5) ([#1701](https://github.com/tauri-apps/plugins-workspace/pull/1701) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri 2.0.0-rc.8
|
||||
|
||||
## \[2.0.0-rc.1]
|
||||
|
||||
- [`84f8bd5e`](https://github.com/tauri-apps/plugins-workspace/commit/84f8bd5e1ef22e664267380b5bbf756ebc5389c3) ([#1662](https://github.com/tauri-apps/plugins-workspace/pull/1662) by [@twlite](https://github.com/tauri-apps/plugins-workspace/../../twlite)) Fixed an issue with abort signal not aborting the fetch request.
|
||||
|
||||
## \[2.0.0-rc.0]
|
||||
|
||||
- [`9887d1`](https://github.com/tauri-apps/plugins-workspace/commit/9887d14bd0e971c4c0f5c1188fc4005d3fc2e29e) Update to tauri RC.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-rc.0`
|
||||
|
||||
## \[2.0.0-beta.9]
|
||||
|
||||
- [`99d6ac0f`](https://github.com/tauri-apps/plugins-workspace/commit/99d6ac0f9506a6a4a1aa59c728157190a7441af6) ([#1606](https://github.com/tauri-apps/plugins-workspace/pull/1606) by [@FabianLars](https://github.com/tauri-apps/plugins-workspace/../../FabianLars)) The JS packages now specify the *minimum* `@tauri-apps/api` version instead of a single exact version.
|
||||
- [`6de87966`](https://github.com/tauri-apps/plugins-workspace/commit/6de87966ecc00ad9d91c25be452f1f46bd2b7e1f) ([#1597](https://github.com/tauri-apps/plugins-workspace/pull/1597) by [@Legend-Master](https://github.com/tauri-apps/plugins-workspace/../../Legend-Master)) Update to tauri beta.25.
|
||||
|
||||
## \[2.0.0-beta.8]
|
||||
|
||||
- [`ac9a25cc`](https://github.com/tauri-apps/plugins-workspace/commit/ac9a25cc12ee2b325f00212ba74316da3369bde5) ([#1395](https://github.com/tauri-apps/plugins-workspace/pull/1395) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix cancelling requests using `AbortSignal`.
|
||||
- [`a6654932`](https://github.com/tauri-apps/plugins-workspace/commit/a66549329c60dea35e3a06a38c357e368c9053a1) ([#1526](https://github.com/tauri-apps/plugins-workspace/pull/1526) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Fix missing `Set-Cookie` headers in the response which meant `request.headers.getSetCookie()` always returned empty array.
|
||||
- [`22a17980`](https://github.com/tauri-apps/plugins-workspace/commit/22a17980ff4f6f8c40adb1b8f4ffc6dae2fe7e30) ([#1537](https://github.com/tauri-apps/plugins-workspace/pull/1537) by [@lucasfernog](https://github.com/tauri-apps/plugins-workspace/../../lucasfernog)) Update to tauri beta.24.
|
||||
|
||||
## \[2.0.0-beta.7]
|
||||
|
||||
- [`76daee7a`](https://github.com/tauri-apps/plugins-workspace/commit/76daee7aafece34de3092c86e531cf9eb1138989) ([#1512](https://github.com/tauri-apps/plugins-workspace/pull/1512) by [@renovate](https://github.com/tauri-apps/plugins-workspace/../../renovate)) Update to tauri beta.23.
|
||||
|
||||
## \[2.0.0-beta.6]
|
||||
|
||||
- [`0f739dbc`](https://github.com/tauri-apps/plugins-workspace/commit/0f739dbc483a1f091977cbe575c3862fd39f8cf1) ([#1392](https://github.com/tauri-apps/plugins-workspace/pull/1392) by [@amrbashir](https://github.com/tauri-apps/plugins-workspace/../../amrbashir)) Allow setting `Origin` header when `unsafe-headers` feature flag is active.
|
||||
|
||||
## \[2.0.0-beta.5]
|
||||
|
||||
- [`9013854f`](https://github.com/tauri-apps/plugins-workspace/commit/9013854f42a49a230b9dbb9d02774765528a923f)([#1382](https://github.com/tauri-apps/plugins-workspace/pull/1382)) Update to tauri beta.22.
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
- [`9d7ae45b`](https://github.com/tauri-apps/plugins-workspace/commit/9d7ae45b0edf9b22c73e7d7c413a784bb35c3d77)([#1354](https://github.com/tauri-apps/plugins-workspace/pull/1354)) Include headers created by browser if not declared by user, which fixes missing headers like `Content-Type` when using `FormData`.
|
||||
- [`430bd6f4`](https://github.com/tauri-apps/plugins-workspace/commit/430bd6f4f379bee5d232ae6b098ae131db7f178a)([#1363](https://github.com/tauri-apps/plugins-workspace/pull/1363)) Update to tauri beta.20.
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`bd1ed590`](https://github.com/tauri-apps/plugins-workspace/commit/bd1ed5903ffcce5500310dac1e59e8c67674ef1e)([#1237](https://github.com/tauri-apps/plugins-workspace/pull/1237)) Update to tauri beta.17.
|
||||
|
||||
## \[2.0.0-beta.6]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.6`
|
||||
|
||||
## \[2.0.0-beta.5]
|
||||
|
||||
- [`500ff10`](https://github.com/tauri-apps/plugins-workspace/commit/500ff10fbd89fdfc73caf9d153029dad567b4ff1)([#1166](https://github.com/tauri-apps/plugins-workspace/pull/1166)) **Breaking change:** Removed the `default-tls` feature flag. The `rustls-tls`, `http2`, `macos-system-configuration`, and `charset` feature flags are now enabled by default.
|
||||
- [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Internally use the webview scoped resources table instead of the app one, so other webviews can't access other webviews resources.
|
||||
- [`7e2fcc5`](https://github.com/tauri-apps/plugins-workspace/commit/7e2fcc5e74df7c3c718e40f75bfb0eafc7d69d8d)([#1146](https://github.com/tauri-apps/plugins-workspace/pull/1146)) Update dependencies to align with tauri 2.0.0-beta.14.
|
||||
- [`e3d41f4`](https://github.com/tauri-apps/plugins-workspace/commit/e3d41f4011bd3ea3ce281bb38bbe31d3709f8e0f)([#1191](https://github.com/tauri-apps/plugins-workspace/pull/1191)) Update for tauri 2.0.0-beta.15.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.5`
|
||||
|
||||
## \[2.0.0-beta.4]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.4`
|
||||
|
||||
## \[2.0.0-beta.3]
|
||||
|
||||
- [`c873e4d`](https://github.com/tauri-apps/plugins-workspace/commit/c873e4d6c74e759742f7c9a88e35cff10a75122a)([#1059](https://github.com/tauri-apps/plugins-workspace/pull/1059)) Fixes scope not allowing subpaths, query parameters and hash when those values are empty.
|
||||
- [`a04ea2f`](https://github.com/tauri-apps/plugins-workspace/commit/a04ea2f38294d5a3987578283badc8eec87a7752)([#1071](https://github.com/tauri-apps/plugins-workspace/pull/1071)) The global API script is now only added to the binary when the `withGlobalTauri` config is true.
|
||||
- [`753c7be`](https://github.com/tauri-apps/plugins-workspace/commit/753c7be0a6a78121d2e88ea0efc3040580c885b4)([#1050](https://github.com/tauri-apps/plugins-workspace/pull/1050)) Add `unsafe-headers` cargo feature flag to allow using [forbidden headers](https://fetch.spec.whatwg.org/#terminology-headers).
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-beta.3`
|
||||
|
||||
## \[2.0.0-beta.2]
|
||||
|
||||
- [`ae56b13`](https://github.com/tauri-apps/plugins-workspace/commit/ae56b13a4d49dbf922b8a0fbb0d557bb63c1d72b)([#983](https://github.com/tauri-apps/plugins-workspace/pull/983)) Allow `User-Agent` header to be set.
|
||||
- [`99bea25`](https://github.com/tauri-apps/plugins-workspace/commit/99bea2559c2c0648c2519c50a18cd124dacef57b)([#1005](https://github.com/tauri-apps/plugins-workspace/pull/1005)) Update to tauri beta.8.
|
||||
|
||||
## \[2.0.0-beta.1]
|
||||
|
||||
- [`569defb`](https://github.com/tauri-apps/plugins-workspace/commit/569defbe9492e38938554bb7bdc1be9151456d21) Update to tauri beta.4.
|
||||
|
||||
## \[2.0.0-beta.0]
|
||||
|
||||
- [`d198c01`](https://github.com/tauri-apps/plugins-workspace/commit/d198c014863ee260cb0de88a14b7fc4356ef7474)([#862](https://github.com/tauri-apps/plugins-workspace/pull/862)) Update to tauri beta.
|
||||
- [`1a34720`](https://github.com/tauri-apps/plugins-workspace/commit/1a347203a54eccc954749d11c4ee81fdd9a0cde7)([#858](https://github.com/tauri-apps/plugins-workspace/pull/858)) Fix http fetch client option init with parameter `connectTimeout`
|
||||
|
||||
## \[2.0.0-alpha.9]
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-alpha.7`
|
||||
|
||||
## \[2.0.0-alpha.6]
|
||||
|
||||
- [`bfa87da`](https://github.com/tauri-apps/plugins-workspace/commit/bfa87da848f9f1da2abae3354eed632881eddf11)([#824](https://github.com/tauri-apps/plugins-workspace/pull/824)) Add `proxy` field to `fetch` options to configure proxy.
|
||||
|
||||
## \[2.0.0-alpha.5]
|
||||
|
||||
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.13.
|
||||
|
||||
## \[2.0.0-alpha.4]
|
||||
|
||||
- [`387c2f9`](https://github.com/tauri-apps/plugins-workspace/commit/387c2f9e0ce4c75c07ffa3fd76391a25b58f5daf)([#802](https://github.com/tauri-apps/plugins-workspace/pull/802)) Update to @tauri-apps/api v2.0.0-alpha.12.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`e438e0a`](https://github.com/tauri-apps/plugins-workspace/commit/e438e0a62d4b430a5159f05f13ecd397dd891a0d)([#676](https://github.com/tauri-apps/plugins-workspace/pull/676)) Update to @tauri-apps/api v2.0.0-alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`5c13736`](https://github.com/tauri-apps/plugins-workspace/commit/5c137365c60790e8d4037d449e8237aa3fffdab0)([#673](https://github.com/tauri-apps/plugins-workspace/pull/673)) Update to @tauri-apps/api v2.0.0-alpha.9.
|
||||
|
||||
## \[2.0.0-alpha.3]
|
||||
|
||||
- [`2cb0fa7`](https://github.com/tauri-apps/plugins-workspace/commit/2cb0fa719b8b1f5ac07dada93520dbbcf637d64c)([#587](https://github.com/tauri-apps/plugins-workspace/pull/587)) Remove `cmd` property which breaks invoke call.
|
||||
- [`4e2cef9`](https://github.com/tauri-apps/plugins-workspace/commit/4e2cef9b702bbbb9cf4ee17de50791cb21f1b2a4)([#593](https://github.com/tauri-apps/plugins-workspace/pull/593)) Update to alpha.12.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Upgraded to `fs@2.0.0-alpha.2`
|
||||
|
||||
## \[2.0.0-alpha.2]
|
||||
|
||||
- [`aec17a9`](https://github.com/tauri-apps/plugins-workspace/commit/aec17a90fc365774c70c4876b94a899416120e26)([#558](https://github.com/tauri-apps/plugins-workspace/pull/558)) Improve response performance by using the new IPC streaming data.
|
||||
|
||||
## \[2.0.0-alpha.1]
|
||||
|
||||
- [`7d9df72`](https://github.com/tauri-apps/plugins-workspace/commit/7d9df7297a221a64d9de945ffc2cd8313d3104dc)([#428](https://github.com/tauri-apps/plugins-workspace/pull/428)) Multipart requests are now handled in JavaScript by the `Request` JavaScript class so you just need to use a `FormData` body and not set the content-type header to `multipart/form-data`. `application/x-www-form-urlencoded` requests must be done manually.
|
||||
- [`7d9df72`](https://github.com/tauri-apps/plugins-workspace/commit/7d9df7297a221a64d9de945ffc2cd8313d3104dc)([#428](https://github.com/tauri-apps/plugins-workspace/pull/428)) The http plugin has been rewritten from scratch and now only exposes a `fetch` function in Javascript and Re-exports `reqwest` crate in Rust. The new `fetch` method tries to be as close and compliant to the `fetch` Web API as possible.
|
||||
- [`d74fc0a`](https://github.com/tauri-apps/plugins-workspace/commit/d74fc0a097996e90a37be8f57d50b7d1f6ca616f)([#555](https://github.com/tauri-apps/plugins-workspace/pull/555)) Update to alpha.11.
|
||||
|
||||
## \[2.0.0-alpha.0]
|
||||
|
||||
- [`717ae67`](https://github.com/tauri-apps/plugins-workspace/commit/717ae670978feb4492fac1f295998b93f2b9347f)([#371](https://github.com/tauri-apps/plugins-workspace/pull/371)) First v2 alpha release!
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
# NB(bt): We've made some changes to the packages and directives.
|
||||
# The original values are commented out.
|
||||
|
||||
[package]
|
||||
name = "tauri-plugin-http"
|
||||
version = "2.4.3"
|
||||
description = "Access an HTTP client written in Rust."
|
||||
#edition = { workspace = true }
|
||||
edition = "2021"
|
||||
#authors = { workspace = true }
|
||||
#license = { workspace = true }
|
||||
#rust-version = { workspace = true }
|
||||
rust-version = "1.77.2"
|
||||
#repository = { workspace = true }
|
||||
links = "tauri-plugin-http"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustc-args = ["--cfg", "docsrs"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[package.metadata.platforms.support]
|
||||
windows = { level = "full", notes = "" }
|
||||
linux = { level = "full", notes = "" }
|
||||
macos = { level = "full", notes = "" }
|
||||
android = { level = "full", notes = "" }
|
||||
ios = { level = "full", notes = "" }
|
||||
|
||||
[build-dependencies]
|
||||
#tauri-plugin = { workspace = true, features = ["build"] }
|
||||
tauri-plugin = { version = "2.2.0", features = ["build"] }
|
||||
#schemars = { workspace = true }
|
||||
schemars = { version = "0.8" }
|
||||
serde = { workspace = true }
|
||||
url = { workspace = true }
|
||||
urlpattern = "0.3"
|
||||
regex = "1"
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tauri = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { version = "1", features = ["sync", "macros"] }
|
||||
#tauri-plugin-fs = { path = "../fs", version = "2.2.1" }
|
||||
tauri-plugin-fs = { version = "2.2.1" }
|
||||
urlpattern = "0.3"
|
||||
regex = "1"
|
||||
http = "1"
|
||||
reqwest = { version = "0.12", default-features = false }
|
||||
url = { workspace = true }
|
||||
data-url = "0.3"
|
||||
cookie_store = { version = "0.21.1", optional = true, features = ["serde"] }
|
||||
bytes = { version = "1.9", optional = true }
|
||||
#tracing = { workspace = true, optional = true }
|
||||
tracing = { version = "0.1", optional = true }
|
||||
|
||||
[features]
|
||||
default = [
|
||||
"rustls-tls",
|
||||
"http2",
|
||||
"charset",
|
||||
"macos-system-configuration",
|
||||
"cookies",
|
||||
]
|
||||
multipart = ["reqwest/multipart"]
|
||||
json = ["reqwest/json"]
|
||||
stream = ["reqwest/stream"]
|
||||
native-tls = ["reqwest/native-tls"]
|
||||
native-tls-vendored = ["reqwest/native-tls-vendored"]
|
||||
native-tls-alpn = ["reqwest/native-tls-alpn"]
|
||||
rustls-tls = ["reqwest/rustls-tls"]
|
||||
rustls-tls-manual-roots = ["reqwest/rustls-tls-manual-roots"]
|
||||
rustls-tls-webpki-roots = ["reqwest/rustls-tls-webpki-roots"]
|
||||
rustls-tls-native-roots = ["reqwest/rustls-tls-native-roots"]
|
||||
blocking = ["reqwest/blocking"]
|
||||
cookies = ["reqwest/cookies", "dep:cookie_store", "dep:bytes"]
|
||||
gzip = ["reqwest/gzip"]
|
||||
brotli = ["reqwest/brotli"]
|
||||
deflate = ["reqwest/deflate"]
|
||||
zstd = ["reqwest/zstd"]
|
||||
trust-dns = ["reqwest/trust-dns"]
|
||||
socks = ["reqwest/socks"]
|
||||
http2 = ["reqwest/http2"]
|
||||
charset = ["reqwest/charset"]
|
||||
macos-system-configuration = ["reqwest/macos-system-configuration"]
|
||||
unsafe-headers = []
|
||||
tracing = ["dep:tracing"]
|
||||
dangerous-settings = []
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
SPDXVersion: SPDX-2.1
|
||||
DataLicense: CC0-1.0
|
||||
PackageName: tauri
|
||||
DataFormat: SPDXRef-1
|
||||
PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy
|
||||
PackageHomePage: https://tauri.app
|
||||
PackageLicenseDeclared: Apache-2.0
|
||||
PackageLicenseDeclared: MIT
|
||||
PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy
|
||||
PackageSummary: <text>Tauri is a rust project that enables developers to make secure
|
||||
and small desktop applications using a web frontend.
|
||||
</text>
|
||||
PackageComment: <text>The package includes the following libraries; see
|
||||
Relationship information.
|
||||
</text>
|
||||
Created: 2019-05-20T09:00:00Z
|
||||
PackageDownloadLocation: git://github.com/tauri-apps/tauri
|
||||
PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git
|
||||
PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git
|
||||
Creator: Person: Daniel Thompson-Yvetot
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 - Present Tauri Apps Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+102
@@ -0,0 +1,102 @@
|
||||

|
||||
|
||||
Access the HTTP client written in Rust.
|
||||
|
||||
| Platform | Supported |
|
||||
| -------- | --------- |
|
||||
| Linux | ✓ |
|
||||
| Windows | ✓ |
|
||||
| macOS | ✓ |
|
||||
| Android | ✓ |
|
||||
| iOS | ✓ |
|
||||
|
||||
## Install
|
||||
|
||||
_This plugin requires a Rust version of at least **1.77.2**_
|
||||
|
||||
There are three general methods of installation that we can recommend.
|
||||
|
||||
1. Use crates.io and npm (easiest, and requires you to trust that our publishing pipeline worked)
|
||||
2. Pull sources directly from Github using git tags / revision hashes (most secure)
|
||||
3. Git submodule install this repo in your tauri project and then use file protocol to ingest the source (most secure, but inconvenient to use)
|
||||
|
||||
Install the Core plugin by adding the following to your `Cargo.toml` file:
|
||||
|
||||
`src-tauri/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tauri-plugin-http = "2.0.0"
|
||||
# alternatively with Git:
|
||||
tauri-plugin-http = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }
|
||||
```
|
||||
|
||||
You can install the JavaScript Guest bindings using your preferred JavaScript package manager:
|
||||
|
||||
> Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use.
|
||||
|
||||
```sh
|
||||
pnpm add @tauri-apps/plugin-http
|
||||
# or
|
||||
npm add @tauri-apps/plugin-http
|
||||
# or
|
||||
yarn add @tauri-apps/plugin-http
|
||||
|
||||
# alternatively with Git:
|
||||
pnpm add https://github.com/tauri-apps/tauri-plugin-http#v2
|
||||
# or
|
||||
npm add https://github.com/tauri-apps/tauri-plugin-http#v2
|
||||
# or
|
||||
yarn add https://github.com/tauri-apps/tauri-plugin-http#v2
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First you need to register the core plugin with Tauri:
|
||||
|
||||
`src-tauri/src/lib.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_http::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
```
|
||||
|
||||
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
|
||||
|
||||
```javascript
|
||||
import { fetch } from '@tauri-apps/plugin-http'
|
||||
const response = await fetch('http://localhost:3003/users/2', {
|
||||
method: 'GET',
|
||||
timeout: 30
|
||||
})
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
PRs accepted. Please make sure to read the Contributing Guide before making a pull request.
|
||||
|
||||
## Partners
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://crabnebula.dev" target="_blank">
|
||||
<img src="https://github.com/tauri-apps/plugins-workspace/raw/v2/.github/sponsors/crabnebula.svg" alt="CrabNebula" width="283">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri).
|
||||
|
||||
## License
|
||||
|
||||
Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy.
|
||||
|
||||
MIT or MIT/Apache 2.0 where applicable.
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Security Policy
|
||||
|
||||
**Do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
**Please use the [Private Vulnerability Disclosure](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability) feature of GitHub.**
|
||||
|
||||
Include as much of the following information:
|
||||
|
||||
- Type of issue (e.g. improper input parsing, privilege escalation, etc.)
|
||||
- The location of the affected source code (tag/branch/commit or direct URL)
|
||||
- Any special configuration required to reproduce the issue
|
||||
- The distribution affected or used to help us with reproduction of the issue
|
||||
- Step-by-step instructions to reproduce the issue
|
||||
- Ideally a reproduction repository
|
||||
- Impact of the issue, including how an attacker might exploit the issue
|
||||
|
||||
We prefer to receive reports in English.
|
||||
|
||||
## Contact
|
||||
|
||||
Please disclose a vulnerability or security relevant issue here: [https://github.com/tauri-apps/plugins-workspace/security/advisories/new](https://github.com/tauri-apps/plugins-workspace/security/advisories/new).
|
||||
|
||||
Alternatively, you can also contact us by email via [security@tauri.app](mailto:security@tauri.app).
|
||||
+1
@@ -0,0 +1 @@
|
||||
if("__TAURI__"in window){var __TAURI_PLUGIN_HTTP__=function(e){"use strict";function t(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function r(e,t,r,n,s){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var n,s,i,a;"function"==typeof SuppressedError&&SuppressedError;const o="__TAURI_TO_IPC_KEY__";class c{constructor(e){n.set(this,void 0),s.set(this,0),i.set(this,[]),a.set(this,void 0),r(this,n,e||(()=>{})),this.id=function(e,t=!1){return window.__TAURI_INTERNALS__.transformCallback(e,t)}((e=>{const o=e.index;if("end"in e)return void(o==t(this,s,"f")?this.cleanupCallback():r(this,a,o));const c=e.message;if(o==t(this,s,"f")){for(t(this,n,"f").call(this,c),r(this,s,t(this,s,"f")+1);t(this,s,"f")in t(this,i,"f");){const e=t(this,i,"f")[t(this,s,"f")];t(this,n,"f").call(this,e),delete t(this,i,"f")[t(this,s,"f")],r(this,s,t(this,s,"f")+1)}t(this,s,"f")===t(this,a,"f")&&this.cleanupCallback()}else t(this,i,"f")[o]=c}))}cleanupCallback(){Reflect.deleteProperty(window,`_${this.id}`)}set onmessage(e){r(this,n,e)}get onmessage(){return t(this,n,"f")}[(n=new WeakMap,s=new WeakMap,i=new WeakMap,a=new WeakMap,o)](){return`__CHANNEL__:${this.id}`}toJSON(){return this[o]()}}async function d(e,t={},r){return window.__TAURI_INTERNALS__.invoke(e,t,r)}const h="Request cancelled";return e.fetch=async function(e,t){const r=t?.signal;if(r?.aborted)throw new Error(h);const n=t?.maxRedirections,s=t?.connectTimeout,i=t?.proxy,a=t?.danger;t&&(delete t.maxRedirections,delete t.connectTimeout,delete t.proxy,delete t.danger);const o=t?.headers?t.headers instanceof Headers?t.headers:new Headers(t.headers):new Headers,f=new Request(e,t),l=await f.arrayBuffer(),u=0!==l.byteLength?Array.from(new Uint8Array(l)):null;for(const[e,t]of f.headers)o.get(e)||o.set(e,t);const _=(o instanceof Headers?Array.from(o.entries()):Array.isArray(o)?o:Object.entries(o)).map((([e,t])=>[e,"string"==typeof t?t:t.toString()]));if(r?.aborted)throw new Error(h);const w=await d("plugin:http|fetch",{clientConfig:{method:f.method,url:f.url,headers:_,data:u,maxRedirections:n,connectTimeout:s,proxy:i,danger:a}}),p=()=>d("plugin:http|fetch_cancel",{rid:w});if(r?.aborted)throw p(),new Error(h);r?.addEventListener("abort",(()=>{p()}));const{status:y,statusText:m,url:b,headers:g,rid:T}=await d("plugin:http|fetch_send",{rid:w}),R=[101,103,204,205,304].includes(y)?null:new ReadableStream({start:e=>{const t=new c;t.onmessage=t=>{if(r?.aborted)return void e.error(h);const n=new Uint8Array(t),s=n[n.byteLength-1],i=n.slice(0,n.byteLength-1);1!=s?e.enqueue(i):e.close()},d("plugin:http|fetch_read_body",{rid:T,streamChannel:t}).catch((t=>{e.error(t)}))}}),A=new Response(R,{status:y,statusText:m});return Object.defineProperty(A,"url",{value:b}),Object.defineProperty(A,"headers",{value:new Headers(g)}),A},e}({});Object.defineProperty(window.__TAURI__,"http",{value:__TAURI_PLUGIN_HTTP__})}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
+67
@@ -0,0 +1,67 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#[path = "src/scope.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod scope;
|
||||
|
||||
const COMMANDS: &[&str] = &["fetch", "fetch_cancel", "fetch_send", "fetch_read_body"];
|
||||
|
||||
/// HTTP scope entry.
|
||||
#[derive(schemars::JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
#[allow(unused)]
|
||||
enum HttpScopeEntry {
|
||||
/// A URL that can be accessed by the webview when using the HTTP APIs.
|
||||
/// Wildcards can be used following the URL pattern standard.
|
||||
///
|
||||
/// See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.
|
||||
///
|
||||
/// Examples:
|
||||
///
|
||||
/// - "https://*" : allows all HTTPS origin on port 443
|
||||
///
|
||||
/// - "https://*:*" : allows all HTTPS origin on any port
|
||||
///
|
||||
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
|
||||
///
|
||||
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
|
||||
Value(String),
|
||||
Object {
|
||||
/// A URL that can be accessed by the webview when using the HTTP APIs.
|
||||
/// Wildcards can be used following the URL pattern standard.
|
||||
///
|
||||
/// See [the URL Pattern spec](https://urlpattern.spec.whatwg.org/) for more information.
|
||||
///
|
||||
/// Examples:
|
||||
///
|
||||
/// - "https://*" : allows all HTTPS origin on port 443
|
||||
///
|
||||
/// - "https://*:*" : allows all HTTPS origin on any port
|
||||
///
|
||||
/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
|
||||
///
|
||||
/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
|
||||
url: String,
|
||||
},
|
||||
}
|
||||
|
||||
// Ensure `HttpScopeEntry` and `scope::EntryRaw` is kept in sync
|
||||
fn _f() {
|
||||
match scope::EntryRaw::Value(String::new()) {
|
||||
scope::EntryRaw::Value(url) => HttpScopeEntry::Value(url),
|
||||
scope::EntryRaw::Object { url } => HttpScopeEntry::Object { url },
|
||||
};
|
||||
match HttpScopeEntry::Value(String::new()) {
|
||||
HttpScopeEntry::Value(url) => scope::EntryRaw::Value(url),
|
||||
HttpScopeEntry::Object { url } => scope::EntryRaw::Object { url },
|
||||
};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tauri_plugin::Builder::new(COMMANDS)
|
||||
.global_api_script_path("./api-iife.js")
|
||||
.global_scope_schema(schemars::schema_for!(HttpScopeEntry))
|
||||
.build();
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
'use strict';
|
||||
|
||||
var core = require('@tauri-apps/api/core');
|
||||
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
/**
|
||||
* Make HTTP requests with the Rust backend.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
|
||||
*
|
||||
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "http:default",
|
||||
* "allow": [{ "url": "https://*.tauri.app" }],
|
||||
* "deny": [{ "url": "https://private.tauri.app" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
const ERROR_REQUEST_CANCELLED = 'Request cancelled';
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function fetch(input, init) {
|
||||
// abort early here if needed
|
||||
const signal = init?.signal;
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const maxRedirections = init?.maxRedirections;
|
||||
const connectTimeout = init?.connectTimeout;
|
||||
const proxy = init?.proxy;
|
||||
const danger = init?.danger;
|
||||
// Remove these fields before creating the request
|
||||
if (init) {
|
||||
delete init.maxRedirections;
|
||||
delete init.connectTimeout;
|
||||
delete init.proxy;
|
||||
delete init.danger;
|
||||
}
|
||||
const headers = init?.headers
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers();
|
||||
const req = new Request(input, init);
|
||||
const buffer = await req.arrayBuffer();
|
||||
const data = buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null;
|
||||
// append new headers created by the browser `Request` implementation,
|
||||
// if not already declared by the caller of this function
|
||||
for (const [key, value] of req.headers) {
|
||||
if (!headers.get(key)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
const headersArray = headers instanceof Headers
|
||||
? Array.from(headers.entries())
|
||||
: Array.isArray(headers)
|
||||
? headers
|
||||
: Object.entries(headers);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const mappedHeaders = headersArray.map(([name, val]) => [
|
||||
name,
|
||||
// we need to ensure we have all header values as strings
|
||||
// eslint-disable-next-line
|
||||
typeof val === 'string' ? val : val.toString()
|
||||
]);
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const rid = await core.invoke('plugin:http|fetch', {
|
||||
clientConfig: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: mappedHeaders,
|
||||
data,
|
||||
maxRedirections,
|
||||
connectTimeout,
|
||||
proxy,
|
||||
danger
|
||||
}
|
||||
});
|
||||
const abort = () => core.invoke('plugin:http|fetch_cancel', { rid });
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
// we don't care about the result of this proimse
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
abort();
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
signal?.addEventListener('abort', () => void abort());
|
||||
const { status, statusText, url, headers: responseHeaders, rid: responseRid } = await core.invoke('plugin:http|fetch_send', {
|
||||
rid
|
||||
});
|
||||
// no body for 101, 103, 204, 205 and 304
|
||||
// see https://fetch.spec.whatwg.org/#null-body-status
|
||||
const body = [101, 103, 204, 205, 304].includes(status)
|
||||
? null
|
||||
: new ReadableStream({
|
||||
start: (controller) => {
|
||||
const streamChannel = new core.Channel();
|
||||
streamChannel.onmessage = (res) => {
|
||||
// close early if aborted
|
||||
if (signal?.aborted) {
|
||||
controller.error(ERROR_REQUEST_CANCELLED);
|
||||
return;
|
||||
}
|
||||
const resUint8 = new Uint8Array(res);
|
||||
const lastByte = resUint8[resUint8.byteLength - 1];
|
||||
const actualRes = resUint8.slice(0, resUint8.byteLength - 1);
|
||||
// close when the signal to close (last byte is 1) is sent from the IPC.
|
||||
if (lastByte == 1) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(actualRes);
|
||||
};
|
||||
// run a non-blocking body stream fetch
|
||||
core.invoke('plugin:http|fetch_read_body', {
|
||||
rid: responseRid,
|
||||
streamChannel
|
||||
}).catch((e) => {
|
||||
controller.error(e);
|
||||
});
|
||||
}
|
||||
});
|
||||
const res = new Response(body, {
|
||||
status,
|
||||
statusText
|
||||
});
|
||||
// Set `Response` properties that are ignored by the
|
||||
// constructor, like url and some headers
|
||||
//
|
||||
// Since url and headers are read only properties
|
||||
// this is the only way to set them.
|
||||
Object.defineProperty(res, 'url', { value: url });
|
||||
Object.defineProperty(res, 'headers', {
|
||||
value: new Headers(responseHeaders)
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
exports.fetch = fetch;
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface Proxy {
|
||||
/**
|
||||
* Proxy all traffic to the passed URL.
|
||||
*/
|
||||
all?: string | ProxyConfig;
|
||||
/**
|
||||
* Proxy all HTTP traffic to the passed URL.
|
||||
*/
|
||||
http?: string | ProxyConfig;
|
||||
/**
|
||||
* Proxy all HTTPS traffic to the passed URL.
|
||||
*/
|
||||
https?: string | ProxyConfig;
|
||||
}
|
||||
export interface ProxyConfig {
|
||||
/**
|
||||
* The URL of the proxy server.
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* Set the `Proxy-Authorization` header using Basic auth.
|
||||
*/
|
||||
basicAuth?: {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
/**
|
||||
* A configuration for filtering out requests that shouldn't be proxied.
|
||||
* Entries are expected to be comma-separated (whitespace between entries is ignored)
|
||||
*/
|
||||
noProxy?: string;
|
||||
}
|
||||
/**
|
||||
* Options to configure the Rust client used to make fetch requests
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface ClientOptions {
|
||||
/**
|
||||
* Defines the maximum number of redirects the client should follow.
|
||||
* If set to 0, no redirects will be followed.
|
||||
*/
|
||||
maxRedirections?: number;
|
||||
/** Timeout in milliseconds */
|
||||
connectTimeout?: number;
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*/
|
||||
proxy?: Proxy;
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*/
|
||||
danger?: DangerousSettings;
|
||||
}
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*
|
||||
* @since 2.3.0
|
||||
*/
|
||||
export interface DangerousSettings {
|
||||
/**
|
||||
* Disables SSL verification.
|
||||
*/
|
||||
acceptInvalidCerts?: boolean;
|
||||
/**
|
||||
* Disables hostname verification.
|
||||
*/
|
||||
acceptInvalidHostnames?: boolean;
|
||||
}
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export declare function fetch(input: URL | Request | string, init?: RequestInit & ClientOptions): Promise<Response>;
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import { invoke, Channel } from '@tauri-apps/api/core';
|
||||
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
/**
|
||||
* Make HTTP requests with the Rust backend.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
|
||||
*
|
||||
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "http:default",
|
||||
* "allow": [{ "url": "https://*.tauri.app" }],
|
||||
* "deny": [{ "url": "https://private.tauri.app" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
const ERROR_REQUEST_CANCELLED = 'Request cancelled';
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
async function fetch(input, init) {
|
||||
// abort early here if needed
|
||||
const signal = init?.signal;
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const maxRedirections = init?.maxRedirections;
|
||||
const connectTimeout = init?.connectTimeout;
|
||||
const proxy = init?.proxy;
|
||||
const danger = init?.danger;
|
||||
// Remove these fields before creating the request
|
||||
if (init) {
|
||||
delete init.maxRedirections;
|
||||
delete init.connectTimeout;
|
||||
delete init.proxy;
|
||||
delete init.danger;
|
||||
}
|
||||
const headers = init?.headers
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers();
|
||||
const req = new Request(input, init);
|
||||
const buffer = await req.arrayBuffer();
|
||||
const data = buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null;
|
||||
// append new headers created by the browser `Request` implementation,
|
||||
// if not already declared by the caller of this function
|
||||
for (const [key, value] of req.headers) {
|
||||
if (!headers.get(key)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
const headersArray = headers instanceof Headers
|
||||
? Array.from(headers.entries())
|
||||
: Array.isArray(headers)
|
||||
? headers
|
||||
: Object.entries(headers);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const mappedHeaders = headersArray.map(([name, val]) => [
|
||||
name,
|
||||
// we need to ensure we have all header values as strings
|
||||
// eslint-disable-next-line
|
||||
typeof val === 'string' ? val : val.toString()
|
||||
]);
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
const rid = await invoke('plugin:http|fetch', {
|
||||
clientConfig: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: mappedHeaders,
|
||||
data,
|
||||
maxRedirections,
|
||||
connectTimeout,
|
||||
proxy,
|
||||
danger
|
||||
}
|
||||
});
|
||||
const abort = () => invoke('plugin:http|fetch_cancel', { rid });
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
// we don't care about the result of this proimse
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
abort();
|
||||
throw new Error(ERROR_REQUEST_CANCELLED);
|
||||
}
|
||||
signal?.addEventListener('abort', () => void abort());
|
||||
const { status, statusText, url, headers: responseHeaders, rid: responseRid } = await invoke('plugin:http|fetch_send', {
|
||||
rid
|
||||
});
|
||||
// no body for 101, 103, 204, 205 and 304
|
||||
// see https://fetch.spec.whatwg.org/#null-body-status
|
||||
const body = [101, 103, 204, 205, 304].includes(status)
|
||||
? null
|
||||
: new ReadableStream({
|
||||
start: (controller) => {
|
||||
const streamChannel = new Channel();
|
||||
streamChannel.onmessage = (res) => {
|
||||
// close early if aborted
|
||||
if (signal?.aborted) {
|
||||
controller.error(ERROR_REQUEST_CANCELLED);
|
||||
return;
|
||||
}
|
||||
const resUint8 = new Uint8Array(res);
|
||||
const lastByte = resUint8[resUint8.byteLength - 1];
|
||||
const actualRes = resUint8.slice(0, resUint8.byteLength - 1);
|
||||
// close when the signal to close (last byte is 1) is sent from the IPC.
|
||||
if (lastByte == 1) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(actualRes);
|
||||
};
|
||||
// run a non-blocking body stream fetch
|
||||
invoke('plugin:http|fetch_read_body', {
|
||||
rid: responseRid,
|
||||
streamChannel
|
||||
}).catch((e) => {
|
||||
controller.error(e);
|
||||
});
|
||||
}
|
||||
});
|
||||
const res = new Response(body, {
|
||||
status,
|
||||
statusText
|
||||
});
|
||||
// Set `Response` properties that are ignored by the
|
||||
// constructor, like url and some headers
|
||||
//
|
||||
// Since url and headers are read only properties
|
||||
// this is the only way to set them.
|
||||
Object.defineProperty(res, 'url', { value: url });
|
||||
Object.defineProperty(res, 'headers', {
|
||||
value: new Headers(responseHeaders)
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
export { fetch };
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Make HTTP requests with the Rust backend.
|
||||
*
|
||||
* ## Security
|
||||
*
|
||||
* This API has a scope configuration that forces you to restrict the URLs that can be accessed using glob patterns.
|
||||
*
|
||||
* For instance, this scope configuration only allows making HTTP requests to all subdomains for `tauri.app` except for `https://private.tauri.app`:
|
||||
* ```json
|
||||
* {
|
||||
* "permissions": [
|
||||
* {
|
||||
* "identifier": "http:default",
|
||||
* "allow": [{ "url": "https://*.tauri.app" }],
|
||||
* "deny": [{ "url": "https://private.tauri.app" }]
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
* ```
|
||||
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Channel, invoke } from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface Proxy {
|
||||
/**
|
||||
* Proxy all traffic to the passed URL.
|
||||
*/
|
||||
all?: string | ProxyConfig
|
||||
/**
|
||||
* Proxy all HTTP traffic to the passed URL.
|
||||
*/
|
||||
http?: string | ProxyConfig
|
||||
/**
|
||||
* Proxy all HTTPS traffic to the passed URL.
|
||||
*/
|
||||
https?: string | ProxyConfig
|
||||
}
|
||||
|
||||
export interface ProxyConfig {
|
||||
/**
|
||||
* The URL of the proxy server.
|
||||
*/
|
||||
url: string
|
||||
/**
|
||||
* Set the `Proxy-Authorization` header using Basic auth.
|
||||
*/
|
||||
basicAuth?: {
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
/**
|
||||
* A configuration for filtering out requests that shouldn't be proxied.
|
||||
* Entries are expected to be comma-separated (whitespace between entries is ignored)
|
||||
*/
|
||||
noProxy?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Options to configure the Rust client used to make fetch requests
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export interface ClientOptions {
|
||||
/**
|
||||
* Defines the maximum number of redirects the client should follow.
|
||||
* If set to 0, no redirects will be followed.
|
||||
*/
|
||||
maxRedirections?: number
|
||||
/** Timeout in milliseconds */
|
||||
connectTimeout?: number
|
||||
/**
|
||||
* Configuration of a proxy that a Client should pass requests to.
|
||||
*/
|
||||
proxy?: Proxy
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*/
|
||||
danger?: DangerousSettings
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for dangerous settings on the client such as disabling SSL verification.
|
||||
*
|
||||
* @since 2.3.0
|
||||
*/
|
||||
export interface DangerousSettings {
|
||||
/**
|
||||
* Disables SSL verification.
|
||||
*/
|
||||
acceptInvalidCerts?: boolean
|
||||
/**
|
||||
* Disables hostname verification.
|
||||
*/
|
||||
acceptInvalidHostnames?: boolean
|
||||
}
|
||||
|
||||
const ERROR_REQUEST_CANCELLED = 'Request cancelled'
|
||||
|
||||
/**
|
||||
* Fetch a resource from the network. It returns a `Promise` that resolves to the
|
||||
* `Response` to that `Request`, whether it is successful or not.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const response = await fetch("http://my.json.host/data.json");
|
||||
* console.log(response.status); // e.g. 200
|
||||
* console.log(response.statusText); // e.g. "OK"
|
||||
* const jsonData = await response.json();
|
||||
* ```
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export async function fetch(
|
||||
input: URL | Request | string,
|
||||
init?: RequestInit & ClientOptions
|
||||
): Promise<Response> {
|
||||
// abort early here if needed
|
||||
const signal = init?.signal
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED)
|
||||
}
|
||||
|
||||
const maxRedirections = init?.maxRedirections
|
||||
const connectTimeout = init?.connectTimeout
|
||||
const proxy = init?.proxy
|
||||
const danger = init?.danger
|
||||
|
||||
// Remove these fields before creating the request
|
||||
if (init) {
|
||||
delete init.maxRedirections
|
||||
delete init.connectTimeout
|
||||
delete init.proxy
|
||||
delete init.danger
|
||||
}
|
||||
|
||||
const headers = init?.headers
|
||||
? init.headers instanceof Headers
|
||||
? init.headers
|
||||
: new Headers(init.headers)
|
||||
: new Headers()
|
||||
|
||||
const req = new Request(input, init)
|
||||
const buffer = await req.arrayBuffer()
|
||||
const data =
|
||||
buffer.byteLength !== 0 ? Array.from(new Uint8Array(buffer)) : null
|
||||
|
||||
// append new headers created by the browser `Request` implementation,
|
||||
// if not already declared by the caller of this function
|
||||
for (const [key, value] of req.headers) {
|
||||
if (!headers.get(key)) {
|
||||
headers.set(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
const headersArray =
|
||||
headers instanceof Headers
|
||||
? Array.from(headers.entries())
|
||||
: Array.isArray(headers)
|
||||
? headers
|
||||
: Object.entries(headers)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const mappedHeaders: Array<[string, string]> = headersArray.map(
|
||||
([name, val]) => [
|
||||
name,
|
||||
// we need to ensure we have all header values as strings
|
||||
// eslint-disable-next-line
|
||||
typeof val === 'string' ? val : (val as any).toString()
|
||||
]
|
||||
)
|
||||
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
throw new Error(ERROR_REQUEST_CANCELLED)
|
||||
}
|
||||
|
||||
const rid = await invoke<number>('plugin:http|fetch', {
|
||||
clientConfig: {
|
||||
method: req.method,
|
||||
url: req.url,
|
||||
headers: mappedHeaders,
|
||||
data,
|
||||
maxRedirections,
|
||||
connectTimeout,
|
||||
proxy,
|
||||
danger
|
||||
}
|
||||
})
|
||||
|
||||
const abort = () => invoke('plugin:http|fetch_cancel', { rid })
|
||||
|
||||
// abort early here if needed
|
||||
if (signal?.aborted) {
|
||||
// we don't care about the result of this proimse
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
abort()
|
||||
throw new Error(ERROR_REQUEST_CANCELLED)
|
||||
}
|
||||
|
||||
signal?.addEventListener('abort', () => void abort())
|
||||
|
||||
interface FetchSendResponse {
|
||||
status: number
|
||||
statusText: string
|
||||
headers: [[string, string]]
|
||||
url: string
|
||||
rid: number
|
||||
}
|
||||
|
||||
const {
|
||||
status,
|
||||
statusText,
|
||||
url,
|
||||
headers: responseHeaders,
|
||||
rid: responseRid
|
||||
} = await invoke<FetchSendResponse>('plugin:http|fetch_send', {
|
||||
rid
|
||||
})
|
||||
|
||||
// no body for 101, 103, 204, 205 and 304
|
||||
// see https://fetch.spec.whatwg.org/#null-body-status
|
||||
const body = [101, 103, 204, 205, 304].includes(status)
|
||||
? null
|
||||
: new ReadableStream({
|
||||
start: (controller) => {
|
||||
const streamChannel = new Channel<ArrayBuffer | number[]>()
|
||||
streamChannel.onmessage = (res: ArrayBuffer | number[]) => {
|
||||
// close early if aborted
|
||||
if (signal?.aborted) {
|
||||
controller.error(ERROR_REQUEST_CANCELLED)
|
||||
return
|
||||
}
|
||||
|
||||
const resUint8 = new Uint8Array(res)
|
||||
const lastByte = resUint8[resUint8.byteLength - 1]
|
||||
const actualRes = resUint8.slice(0, resUint8.byteLength - 1)
|
||||
|
||||
// close when the signal to close (last byte is 1) is sent from the IPC.
|
||||
if (lastByte == 1) {
|
||||
controller.close()
|
||||
return
|
||||
}
|
||||
|
||||
controller.enqueue(actualRes)
|
||||
}
|
||||
|
||||
// run a non-blocking body stream fetch
|
||||
invoke('plugin:http|fetch_read_body', {
|
||||
rid: responseRid,
|
||||
streamChannel
|
||||
}).catch((e) => {
|
||||
controller.error(e)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const res = new Response(body, {
|
||||
status,
|
||||
statusText
|
||||
})
|
||||
|
||||
// Set `Response` properties that are ignored by the
|
||||
// constructor, like url and some headers
|
||||
//
|
||||
// Since url and headers are read only properties
|
||||
// this is the only way to set them.
|
||||
Object.defineProperty(res, 'url', { value: url })
|
||||
Object.defineProperty(res, 'headers', {
|
||||
value: new Headers(responseHeaders)
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@tauri-apps/plugin-http",
|
||||
"version": "2.4.3",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"authors": [
|
||||
"Tauri Programme within The Commons Conservancy"
|
||||
],
|
||||
"repository": "https://github.com/tauri-apps/plugins-workspace",
|
||||
"type": "module",
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"main": "./dist-js/index.cjs",
|
||||
"module": "./dist-js/index.js",
|
||||
"exports": {
|
||||
"types": "./dist-js/index.d.ts",
|
||||
"import": "./dist-js/index.js",
|
||||
"require": "./dist-js/index.cjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c"
|
||||
},
|
||||
"files": [
|
||||
"dist-js",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.0.0"
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch"
|
||||
description = "Enables the fetch command without any pre-configured scope."
|
||||
commands.allow = ["fetch"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch"
|
||||
description = "Denies the fetch command without any pre-configured scope."
|
||||
commands.deny = ["fetch"]
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch-cancel"
|
||||
description = "Enables the fetch_cancel command without any pre-configured scope."
|
||||
commands.allow = ["fetch_cancel"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch-cancel"
|
||||
description = "Denies the fetch_cancel command without any pre-configured scope."
|
||||
commands.deny = ["fetch_cancel"]
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch-read-body"
|
||||
description = "Enables the fetch_read_body command without any pre-configured scope."
|
||||
commands.allow = ["fetch_read_body"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch-read-body"
|
||||
description = "Denies the fetch_read_body command without any pre-configured scope."
|
||||
commands.deny = ["fetch_read_body"]
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
"$schema" = "../../schemas/schema.json"
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-fetch-send"
|
||||
description = "Enables the fetch_send command without any pre-configured scope."
|
||||
commands.allow = ["fetch_send"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-fetch-send"
|
||||
description = "Denies the fetch_send command without any pre-configured scope."
|
||||
commands.deny = ["fetch_send"]
|
||||
@@ -0,0 +1,135 @@
|
||||
## Default Permission
|
||||
|
||||
This permission set configures what kind of
|
||||
fetch operations are available from the http plugin.
|
||||
|
||||
This enables all fetch operations but does not
|
||||
allow explicitly any origins to be fetched. This needs to
|
||||
be manually configured before usage.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
All fetch operations are enabled.
|
||||
|
||||
|
||||
|
||||
#### This default permission set includes the following:
|
||||
|
||||
- `allow-fetch`
|
||||
- `allow-fetch-cancel`
|
||||
- `allow-fetch-read-body`
|
||||
- `allow-fetch-send`
|
||||
|
||||
## Permission Table
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Identifier</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch-cancel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch_cancel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch-cancel`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch_cancel command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch-read-body`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch_read_body command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch-read-body`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch_read_body command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:allow-fetch-send`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Enables the fetch_send command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
|
||||
`http:deny-fetch-send`
|
||||
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Denies the fetch_send command without any pre-configured scope.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -0,0 +1,22 @@
|
||||
"$schema" = "schemas/schema.json"
|
||||
|
||||
[default]
|
||||
description = """
|
||||
This permission set configures what kind of
|
||||
fetch operations are available from the http plugin.
|
||||
|
||||
This enables all fetch operations but does not
|
||||
allow explicitly any origins to be fetched. This needs to
|
||||
be manually configured before usage.
|
||||
|
||||
#### Granted Permissions
|
||||
|
||||
All fetch operations are enabled.
|
||||
|
||||
"""
|
||||
permissions = [
|
||||
"allow-fetch",
|
||||
"allow-fetch-cancel",
|
||||
"allow-fetch-read-body",
|
||||
"allow-fetch-send",
|
||||
]
|
||||
@@ -0,0 +1,354 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "PermissionFile",
|
||||
"description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"default": {
|
||||
"description": "The default permission set for the plugin",
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/DefaultPermission"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"set": {
|
||||
"description": "A list of permissions sets defined",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionSet"
|
||||
}
|
||||
},
|
||||
"permission": {
|
||||
"description": "A list of inlined permissions",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"DefaultPermission": {
|
||||
"description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"PermissionSet": {
|
||||
"description": "A set of direct permissions grouped together under a new name.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"description",
|
||||
"identifier",
|
||||
"permissions"
|
||||
],
|
||||
"properties": {
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does.",
|
||||
"type": "string"
|
||||
},
|
||||
"permissions": {
|
||||
"description": "All permissions this set contains.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/PermissionKind"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Permission": {
|
||||
"description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"identifier"
|
||||
],
|
||||
"properties": {
|
||||
"version": {
|
||||
"description": "The version of the permission.",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint64",
|
||||
"minimum": 1.0
|
||||
},
|
||||
"identifier": {
|
||||
"description": "A unique identifier for the permission.",
|
||||
"type": "string"
|
||||
},
|
||||
"description": {
|
||||
"description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"commands": {
|
||||
"description": "Allowed or denied commands when using this permission.",
|
||||
"default": {
|
||||
"allow": [],
|
||||
"deny": []
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Commands"
|
||||
}
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"description": "Allowed or denied scoped when using this permission.",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Scopes"
|
||||
}
|
||||
]
|
||||
},
|
||||
"platforms": {
|
||||
"description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Target"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Commands": {
|
||||
"description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Allowed command.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Denied command, which takes priority.",
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Scopes": {
|
||||
"description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allow": {
|
||||
"description": "Data that defines what is allowed by the scope.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
"deny": {
|
||||
"description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
|
||||
"type": [
|
||||
"array",
|
||||
"null"
|
||||
],
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Value": {
|
||||
"description": "All supported ACL values.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents a null JSON value.",
|
||||
"type": "null"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`bool`].",
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"description": "Represents a valid ACL [`Number`].",
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/Number"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`String`].",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Represents a list of other [`Value`]s.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Represents a map of [`String`] keys to [`Value`]s.",
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/Value"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"Number": {
|
||||
"description": "A valid ACL number.",
|
||||
"anyOf": [
|
||||
{
|
||||
"description": "Represents an [`i64`].",
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
{
|
||||
"description": "Represents a [`f64`].",
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Target": {
|
||||
"description": "Platform target.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "MacOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"macOS"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Windows.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"windows"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Linux.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Android.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"android"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "iOS.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"iOS"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"PermissionKind": {
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Enables the fetch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch",
|
||||
"markdownDescription": "Enables the fetch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch",
|
||||
"markdownDescription": "Denies the fetch command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the fetch_cancel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch-cancel",
|
||||
"markdownDescription": "Enables the fetch_cancel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch_cancel command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch-cancel",
|
||||
"markdownDescription": "Denies the fetch_cancel command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the fetch_read_body command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch-read-body",
|
||||
"markdownDescription": "Enables the fetch_read_body command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch_read_body command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch-read-body",
|
||||
"markdownDescription": "Denies the fetch_read_body command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the fetch_send command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-fetch-send",
|
||||
"markdownDescription": "Enables the fetch_send command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the fetch_send command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-fetch-send",
|
||||
"markdownDescription": "Denies the fetch_send command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "This permission set configures what kind of\nfetch operations are available from the http plugin.\n\nThis enables all fetch operations but does not\nallow explicitly any origins to be fetched. This needs to\nbe manually configured before usage.\n\n#### Granted Permissions\n\nAll fetch operations are enabled.\n\n\n#### This default permission set includes:\n\n- `allow-fetch`\n- `allow-fetch-cancel`\n- `allow-fetch-read-body`\n- `allow-fetch-send`",
|
||||
"type": "string",
|
||||
"const": "default",
|
||||
"markdownDescription": "This permission set configures what kind of\nfetch operations are available from the http plugin.\n\nThis enables all fetch operations but does not\nallow explicitly any origins to be fetched. This needs to\nbe manually configured before usage.\n\n#### Granted Permissions\n\nAll fetch operations are enabled.\n\n\n#### This default permission set includes:\n\n- `allow-fetch`\n- `allow-fetch-cancel`\n- `allow-fetch-read-body`\n- `allow-fetch-send`"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import { createConfig } from '../../shared/rollup.config.js'
|
||||
|
||||
export default createConfig()
|
||||
+469
@@ -0,0 +1,469 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{future::Future, pin::Pin, str::FromStr, sync::Arc, time::Duration};
|
||||
|
||||
use http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
|
||||
use reqwest::{redirect::Policy, NoProxy};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{
|
||||
async_runtime::Mutex,
|
||||
command,
|
||||
ipc::{Channel, CommandScope, GlobalScope},
|
||||
Manager, ResourceId, ResourceTable, Runtime, State, Webview,
|
||||
};
|
||||
use tokio::sync::oneshot::{channel, Receiver, Sender};
|
||||
|
||||
use crate::{
|
||||
scope::{Entry, Scope},
|
||||
Error, Http, Result,
|
||||
};
|
||||
|
||||
const HTTP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
|
||||
|
||||
struct ReqwestResponse(reqwest::Response);
|
||||
impl tauri::Resource for ReqwestResponse {}
|
||||
|
||||
type CancelableResponseResult = Result<reqwest::Response>;
|
||||
type CancelableResponseFuture =
|
||||
Pin<Box<dyn Future<Output = CancelableResponseResult> + Send + Sync>>;
|
||||
|
||||
struct FetchRequest {
|
||||
fut: Mutex<CancelableResponseFuture>,
|
||||
abort_tx_rid: ResourceId,
|
||||
abort_rx_rid: ResourceId,
|
||||
}
|
||||
impl tauri::Resource for FetchRequest {}
|
||||
|
||||
struct AbortSender(Sender<()>);
|
||||
impl tauri::Resource for AbortRecveiver {}
|
||||
|
||||
impl AbortSender {
|
||||
fn abort(self) {
|
||||
let _ = self.0.send(());
|
||||
}
|
||||
}
|
||||
|
||||
struct AbortRecveiver(Receiver<()>);
|
||||
impl tauri::Resource for AbortSender {}
|
||||
|
||||
trait AddRequest {
|
||||
fn add_request(&mut self, fut: CancelableResponseFuture) -> ResourceId;
|
||||
}
|
||||
|
||||
impl AddRequest for ResourceTable {
|
||||
fn add_request(&mut self, fut: CancelableResponseFuture) -> ResourceId {
|
||||
let (tx, rx) = channel::<()>();
|
||||
let (tx, rx) = (AbortSender(tx), AbortRecveiver(rx));
|
||||
let req = FetchRequest {
|
||||
fut: Mutex::new(fut),
|
||||
abort_tx_rid: self.add(tx),
|
||||
abort_rx_rid: self.add(rx),
|
||||
};
|
||||
self.add(req)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FetchResponse {
|
||||
status: u16,
|
||||
status_text: String,
|
||||
headers: Vec<(String, String)>,
|
||||
url: String,
|
||||
rid: ResourceId,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[allow(dead_code)] //feature flags shoudln't affect api
|
||||
pub struct DangerousSettings {
|
||||
accept_invalid_certs: bool,
|
||||
accept_invalid_hostnames: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientConfig {
|
||||
method: String,
|
||||
url: url::Url,
|
||||
headers: Vec<(String, String)>,
|
||||
data: Option<Vec<u8>>,
|
||||
connect_timeout: Option<u64>,
|
||||
max_redirections: Option<usize>,
|
||||
proxy: Option<Proxy>,
|
||||
danger: Option<DangerousSettings>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Proxy {
|
||||
all: Option<UrlOrConfig>,
|
||||
http: Option<UrlOrConfig>,
|
||||
https: Option<UrlOrConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(untagged)]
|
||||
pub enum UrlOrConfig {
|
||||
Url(String),
|
||||
Config(ProxyConfig),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProxyConfig {
|
||||
url: String,
|
||||
basic_auth: Option<BasicAuth>,
|
||||
no_proxy: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BasicAuth {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn proxy_creator(
|
||||
url_or_config: UrlOrConfig,
|
||||
proxy_fn: fn(String) -> reqwest::Result<reqwest::Proxy>,
|
||||
) -> reqwest::Result<reqwest::Proxy> {
|
||||
match url_or_config {
|
||||
UrlOrConfig::Url(url) => Ok(proxy_fn(url)?),
|
||||
UrlOrConfig::Config(ProxyConfig {
|
||||
url,
|
||||
basic_auth,
|
||||
no_proxy,
|
||||
}) => {
|
||||
let mut proxy = proxy_fn(url)?;
|
||||
if let Some(basic_auth) = basic_auth {
|
||||
proxy = proxy.basic_auth(&basic_auth.username, &basic_auth.password);
|
||||
}
|
||||
if let Some(no_proxy) = no_proxy {
|
||||
proxy = proxy.no_proxy(NoProxy::from_string(&no_proxy));
|
||||
}
|
||||
Ok(proxy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_proxy(
|
||||
proxy: Proxy,
|
||||
mut builder: reqwest::ClientBuilder,
|
||||
) -> crate::Result<reqwest::ClientBuilder> {
|
||||
let Proxy { all, http, https } = proxy;
|
||||
|
||||
if let Some(all) = all {
|
||||
let proxy = proxy_creator(all, reqwest::Proxy::all)?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
if let Some(http) = http {
|
||||
let proxy = proxy_creator(http, reqwest::Proxy::http)?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
if let Some(https) = https {
|
||||
let proxy = proxy_creator(https, reqwest::Proxy::https)?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
Ok(builder)
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn fetch<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
state: State<'_, Http>,
|
||||
client_config: ClientConfig,
|
||||
command_scope: CommandScope<Entry>,
|
||||
global_scope: GlobalScope<Entry>,
|
||||
) -> crate::Result<ResourceId> {
|
||||
let ClientConfig {
|
||||
method,
|
||||
url,
|
||||
headers: headers_raw,
|
||||
data,
|
||||
connect_timeout,
|
||||
max_redirections,
|
||||
proxy,
|
||||
danger,
|
||||
} = client_config;
|
||||
|
||||
let scheme = url.scheme();
|
||||
let method = Method::from_bytes(method.as_bytes())?;
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
for (h, v) in headers_raw {
|
||||
let name = HeaderName::from_str(&h)?;
|
||||
#[cfg(not(feature = "unsafe-headers"))]
|
||||
if is_unsafe_header(&name) {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
eprintln!("[\x1b[33mWARNING\x1b[0m] Skipping {name} header as it is a forbidden header per fetch spec https://fetch.spec.whatwg.org/#terminology-headers");
|
||||
eprintln!("[\x1b[33mWARNING\x1b[0m] if keeping the header is a desired behavior, you can enable `unsafe-headers` feature flag in your Cargo.toml");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
headers.append(name, HeaderValue::from_str(&v)?);
|
||||
}
|
||||
|
||||
match scheme {
|
||||
"http" | "https" => {
|
||||
if Scope::new(
|
||||
command_scope
|
||||
.allows()
|
||||
.iter()
|
||||
.chain(global_scope.allows())
|
||||
.collect(),
|
||||
command_scope
|
||||
.denies()
|
||||
.iter()
|
||||
.chain(global_scope.denies())
|
||||
.collect(),
|
||||
)
|
||||
.is_allowed(&url)
|
||||
{
|
||||
let mut builder = reqwest::ClientBuilder::new();
|
||||
|
||||
if let Some(danger_config) = danger {
|
||||
#[cfg(not(feature = "dangerous-settings"))]
|
||||
{
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
eprintln!("[\x1b[33mWARNING\x1b[0m] using dangerous settings requires `dangerous-settings` feature flag in your Cargo.toml");
|
||||
}
|
||||
let _ = danger_config;
|
||||
return Err(Error::DangerousSettings);
|
||||
}
|
||||
#[cfg(feature = "dangerous-settings")]
|
||||
{
|
||||
builder = builder
|
||||
.danger_accept_invalid_certs(danger_config.accept_invalid_certs)
|
||||
.danger_accept_invalid_hostnames(danger_config.accept_invalid_hostnames)
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(timeout) = connect_timeout {
|
||||
builder = builder.connect_timeout(Duration::from_millis(timeout));
|
||||
}
|
||||
|
||||
if let Some(max_redirections) = max_redirections {
|
||||
builder = builder.redirect(if max_redirections == 0 {
|
||||
Policy::none()
|
||||
} else {
|
||||
Policy::limited(max_redirections)
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(proxy_config) = proxy {
|
||||
builder = attach_proxy(proxy_config, builder)?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
{
|
||||
builder = builder.cookie_provider(state.cookies_jar.clone());
|
||||
}
|
||||
|
||||
let mut request = builder.build()?.request(method.clone(), url);
|
||||
|
||||
// POST and PUT requests should always have a 0 length content-length,
|
||||
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
|
||||
if data.is_none() && matches!(method, Method::POST | Method::PUT) {
|
||||
headers.append(header::CONTENT_LENGTH, HeaderValue::from_str("0")?);
|
||||
}
|
||||
|
||||
if headers.contains_key(header::RANGE) {
|
||||
// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch step 18
|
||||
// If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`)
|
||||
headers.append(header::ACCEPT_ENCODING, HeaderValue::from_str("identity")?);
|
||||
}
|
||||
|
||||
if !headers.contains_key(header::USER_AGENT) {
|
||||
headers.append(header::USER_AGENT, HeaderValue::from_str(HTTP_USER_AGENT)?);
|
||||
}
|
||||
|
||||
// ensure we have an Origin header set
|
||||
if cfg!(not(feature = "unsafe-headers")) || !headers.contains_key(header::ORIGIN) {
|
||||
if let Ok(url) = webview.url() {
|
||||
headers.append(
|
||||
header::ORIGIN,
|
||||
HeaderValue::from_str(&url.origin().ascii_serialization())?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// In case empty origin is passed, remove it. Some services do not like Origin header
|
||||
// so this way we can remove it in explicit way. The default behaviour is still to set it
|
||||
if cfg!(feature = "unsafe-headers")
|
||||
&& headers.get(header::ORIGIN) == Some(&HeaderValue::from_static(""))
|
||||
{
|
||||
headers.remove(header::ORIGIN);
|
||||
};
|
||||
|
||||
if let Some(data) = data {
|
||||
request = request.body(data);
|
||||
}
|
||||
|
||||
request = request.headers(headers);
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::trace!("{:?}", request);
|
||||
|
||||
let fut = async move { request.send().await.map_err(Into::into) };
|
||||
|
||||
let mut resources_table = webview.resources_table();
|
||||
let rid = resources_table.add_request(Box::pin(fut));
|
||||
|
||||
Ok(rid)
|
||||
} else {
|
||||
Err(Error::UrlNotAllowed(url))
|
||||
}
|
||||
}
|
||||
"data" => {
|
||||
let data_url =
|
||||
data_url::DataUrl::process(url.as_str()).map_err(|_| Error::DataUrlError)?;
|
||||
let (body, _) = data_url
|
||||
.decode_to_vec()
|
||||
.map_err(|_| Error::DataUrlDecodeError)?;
|
||||
|
||||
let response = http::Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, data_url.mime_type().to_string())
|
||||
.body(reqwest::Body::from(body))?;
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::trace!("{:?}", response);
|
||||
|
||||
let fut = async move { Ok(reqwest::Response::from(response)) };
|
||||
let mut resources_table = webview.resources_table();
|
||||
let rid = resources_table.add_request(Box::pin(fut));
|
||||
Ok(rid)
|
||||
}
|
||||
_ => Err(Error::SchemeNotSupport(scheme.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub fn fetch_cancel<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> crate::Result<()> {
|
||||
let mut resources_table = webview.resources_table();
|
||||
let req = resources_table.get::<FetchRequest>(rid)?;
|
||||
let abort_tx = resources_table.take::<AbortSender>(req.abort_tx_rid)?;
|
||||
if let Some(abort_tx) = Arc::into_inner(abort_tx) {
|
||||
abort_tx.abort();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn fetch_send<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
rid: ResourceId,
|
||||
) -> crate::Result<FetchResponse> {
|
||||
let (req, abort_rx) = {
|
||||
let mut resources_table = webview.resources_table();
|
||||
let req = resources_table.get::<FetchRequest>(rid)?;
|
||||
let abort_rx = resources_table.take::<AbortRecveiver>(req.abort_rx_rid)?;
|
||||
(req, abort_rx)
|
||||
};
|
||||
|
||||
let Some(abort_rx) = Arc::into_inner(abort_rx) else {
|
||||
return Err(Error::RequestCanceled);
|
||||
};
|
||||
|
||||
let mut fut = req.fut.lock().await;
|
||||
|
||||
let res = tokio::select! {
|
||||
res = fut.as_mut() => res?,
|
||||
_ = abort_rx.0 => {
|
||||
let mut resources_table = webview.resources_table();
|
||||
resources_table.close(rid)?;
|
||||
return Err(Error::RequestCanceled);
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::trace!("{:?}", res);
|
||||
|
||||
let status = res.status();
|
||||
let url = res.url().to_string();
|
||||
let mut headers = Vec::new();
|
||||
for (key, val) in res.headers().iter() {
|
||||
headers.push((
|
||||
key.as_str().into(),
|
||||
String::from_utf8(val.as_bytes().to_vec())?,
|
||||
));
|
||||
}
|
||||
|
||||
let mut resources_table = webview.resources_table();
|
||||
let rid = resources_table.add(ReqwestResponse(res));
|
||||
|
||||
Ok(FetchResponse {
|
||||
status: status.as_u16(),
|
||||
status_text: status.canonical_reason().unwrap_or_default().to_string(),
|
||||
headers,
|
||||
url,
|
||||
rid,
|
||||
})
|
||||
}
|
||||
|
||||
#[command]
|
||||
pub async fn fetch_read_body<R: Runtime>(
|
||||
webview: Webview<R>,
|
||||
rid: ResourceId,
|
||||
stream_channel: Channel<tauri::ipc::InvokeResponseBody>,
|
||||
) -> crate::Result<()> {
|
||||
let res = {
|
||||
let mut resources_table = webview.resources_table();
|
||||
resources_table.take::<ReqwestResponse>(rid)?
|
||||
};
|
||||
|
||||
let mut res = Arc::into_inner(res).unwrap().0;
|
||||
|
||||
// send response through IPC channel
|
||||
while let Some(chunk) = res.chunk().await? {
|
||||
let mut chunk = chunk.to_vec();
|
||||
// append 0 to indicate we are not done yet
|
||||
chunk.push(0);
|
||||
stream_channel.send(tauri::ipc::InvokeResponseBody::Raw(chunk))?;
|
||||
}
|
||||
|
||||
// send 1 to indicate we are done
|
||||
stream_channel.send(tauri::ipc::InvokeResponseBody::Raw(vec![1]))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// forbidden headers per fetch spec https://fetch.spec.whatwg.org/#terminology-headers
|
||||
#[cfg(not(feature = "unsafe-headers"))]
|
||||
fn is_unsafe_header(header: &HeaderName) -> bool {
|
||||
matches!(
|
||||
*header,
|
||||
header::ACCEPT_CHARSET
|
||||
| header::ACCEPT_ENCODING
|
||||
| header::ACCESS_CONTROL_REQUEST_HEADERS
|
||||
| header::ACCESS_CONTROL_REQUEST_METHOD
|
||||
| header::CONNECTION
|
||||
| header::CONTENT_LENGTH
|
||||
| header::COOKIE
|
||||
| header::DATE
|
||||
| header::DNT
|
||||
| header::EXPECT
|
||||
| header::HOST
|
||||
| header::ORIGIN
|
||||
| header::REFERER
|
||||
| header::SET_COOKIE
|
||||
| header::TE
|
||||
| header::TRAILER
|
||||
| header::TRANSFER_ENCODING
|
||||
| header::UPGRADE
|
||||
| header::VIA
|
||||
) || {
|
||||
let lower = header.as_str().to_lowercase();
|
||||
lower.starts_with("proxy-") || lower.starts_with("sec-")
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
use url::Url;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
Network(#[from] reqwest::Error),
|
||||
#[error(transparent)]
|
||||
Http(#[from] http::Error),
|
||||
#[error(transparent)]
|
||||
HttpInvalidHeaderName(#[from] http::header::InvalidHeaderName),
|
||||
#[error(transparent)]
|
||||
HttpInvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
|
||||
/// URL not allowed by the scope.
|
||||
#[error("url not allowed on the configured scope: {0}")]
|
||||
UrlNotAllowed(Url),
|
||||
#[error(transparent)]
|
||||
UrlParseError(#[from] url::ParseError),
|
||||
/// HTTP method error.
|
||||
#[error(transparent)]
|
||||
HttpMethod(#[from] http::method::InvalidMethod),
|
||||
#[error("scheme {0} not supported")]
|
||||
SchemeNotSupport(String),
|
||||
#[error("Request canceled")]
|
||||
RequestCanceled,
|
||||
#[error(transparent)]
|
||||
FsError(#[from] tauri_plugin_fs::Error),
|
||||
#[error("failed to process data url")]
|
||||
DataUrlError,
|
||||
#[error("failed to decode data url into bytes")]
|
||||
DataUrlDecodeError,
|
||||
#[error(transparent)]
|
||||
Tauri(#[from] tauri::Error),
|
||||
#[error(transparent)]
|
||||
Utf8(#[from] std::string::FromUtf8Error),
|
||||
#[error("dangerous settings used but are not enabled")]
|
||||
DangerousSettings,
|
||||
}
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(self.to_string().as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Access the HTTP client written in Rust.
|
||||
|
||||
pub use reqwest;
|
||||
use tauri::{
|
||||
plugin::{Builder, TauriPlugin},
|
||||
Manager, Runtime,
|
||||
};
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
// NB(bt): We're making everything public so we can access it.
|
||||
pub mod commands;
|
||||
pub mod error;
|
||||
#[cfg(feature = "cookies")]
|
||||
pub mod reqwest_cookie_store;
|
||||
pub mod scope;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
const COOKIES_FILENAME: &str = ".cookies";
|
||||
|
||||
// NB(bt): We've vendored in this library so we can poke at the cookie data store.
|
||||
pub struct Http {
|
||||
#[cfg(feature = "cookies")]
|
||||
pub cookies_jar: std::sync::Arc<crate::reqwest_cookie_store::CookieStoreMutex>,
|
||||
}
|
||||
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
Builder::<R>::new("http")
|
||||
.setup(|app, _| {
|
||||
#[cfg(feature = "cookies")]
|
||||
let cookies_jar = {
|
||||
use crate::reqwest_cookie_store::*;
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
|
||||
let cache_dir = app.path().app_cache_dir()?;
|
||||
std::fs::create_dir_all(&cache_dir)?;
|
||||
|
||||
let path = cache_dir.join(COOKIES_FILENAME);
|
||||
let file = File::options()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.read(true)
|
||||
.open(&path)?;
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
CookieStoreMutex::load(path.clone(), reader).unwrap_or_else(|_e| {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!(
|
||||
"failed to load cookie store: {_e}, falling back to empty store"
|
||||
);
|
||||
CookieStoreMutex::new(path, Default::default())
|
||||
})
|
||||
};
|
||||
|
||||
let state = Http {
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies_jar: std::sync::Arc::new(cookies_jar),
|
||||
};
|
||||
|
||||
app.manage(state);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.on_event(|app, event| {
|
||||
#[cfg(feature = "cookies")]
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
let state = app.state::<Http>();
|
||||
|
||||
match state.cookies_jar.request_save() {
|
||||
Ok(rx) => {
|
||||
let _ = rx.recv();
|
||||
}
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("failed to save cookie jar: {_e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::fetch,
|
||||
commands::fetch_cancel,
|
||||
commands::fetch_send,
|
||||
commands::fetch_read_body
|
||||
])
|
||||
.build()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// taken from https://github.com/pfernie/reqwest_cookie_store/blob/2ec4afabcd55e24d3afe3f0626ee6dc97bed938d/src/lib.rs
|
||||
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{mpsc::Receiver, Mutex},
|
||||
};
|
||||
|
||||
// NB(bt): Re-export these for reuse
|
||||
pub use cookie_store::{CookieStore, RawCookie, RawCookieParseError};
|
||||
use reqwest::header::HeaderValue;
|
||||
|
||||
fn set_cookies(
|
||||
cookie_store: &mut CookieStore,
|
||||
cookie_headers: &mut dyn Iterator<Item = &HeaderValue>,
|
||||
url: &url::Url,
|
||||
) {
|
||||
let cookies = cookie_headers.filter_map(|val| {
|
||||
std::str::from_utf8(val.as_bytes())
|
||||
.map_err(RawCookieParseError::from)
|
||||
.and_then(RawCookie::parse)
|
||||
.map(|c| c.into_owned())
|
||||
.ok()
|
||||
});
|
||||
cookie_store.store_response_cookies(cookies, url);
|
||||
}
|
||||
|
||||
fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> {
|
||||
let s = cookie_store
|
||||
.get_request_values(url)
|
||||
.map(|(name, value)| format!("{}={}", name, value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
HeaderValue::from_maybe_shared(bytes::Bytes::from(s)).ok()
|
||||
}
|
||||
|
||||
/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in
|
||||
/// async/concurrent contexts.
|
||||
#[derive(Debug)]
|
||||
pub struct CookieStoreMutex {
|
||||
pub path: PathBuf,
|
||||
// NB(bt): We've made both of these public so we can access them.
|
||||
pub store: Mutex<CookieStore>,
|
||||
pub save_task: Mutex<Option<CancellableTask>>,
|
||||
}
|
||||
|
||||
impl CookieStoreMutex {
|
||||
/// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`].
|
||||
pub fn new(path: PathBuf, cookie_store: CookieStore) -> CookieStoreMutex {
|
||||
CookieStoreMutex {
|
||||
path,
|
||||
store: Mutex::new(cookie_store),
|
||||
save_task: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load<R: std::io::BufRead>(
|
||||
path: PathBuf,
|
||||
reader: R,
|
||||
) -> cookie_store::Result<CookieStoreMutex> {
|
||||
cookie_store::serde::load(reader, |c| serde_json::from_str(c))
|
||||
.map(|store| CookieStoreMutex::new(path, store))
|
||||
}
|
||||
|
||||
fn cookies_to_str(&self) -> Result<String, serde_json::Error> {
|
||||
let mut cookies = Vec::new();
|
||||
for cookie in self
|
||||
.store
|
||||
.lock()
|
||||
.expect("poisoned cookie jar mutex")
|
||||
.iter_unexpired()
|
||||
{
|
||||
if cookie.is_persistent() {
|
||||
cookies.push(cookie.clone());
|
||||
}
|
||||
}
|
||||
serde_json::to_string(&cookies)
|
||||
}
|
||||
|
||||
pub fn request_save(&self) -> cookie_store::Result<Receiver<()>> {
|
||||
let cookie_str = self.cookies_to_str()?;
|
||||
let path = self.path.clone();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let task = tauri::async_runtime::spawn(async move {
|
||||
match tokio::fs::write(&path, &cookie_str).await {
|
||||
Ok(()) => {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("failed to save cookie jar: {_e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
self.save_task
|
||||
.lock()
|
||||
.unwrap()
|
||||
.replace(CancellableTask(task));
|
||||
Ok(rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl reqwest::cookie::CookieStore for CookieStoreMutex {
|
||||
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
|
||||
set_cookies(&mut self.store.lock().unwrap(), cookie_headers, url);
|
||||
|
||||
// try to persist cookies immediately asynchronously
|
||||
if let Err(_e) = self.request_save() {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("failed to save cookie jar: {_e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
|
||||
let store = self.store.lock().unwrap();
|
||||
cookies(&store, url)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CancellableTask(tauri::async_runtime::JoinHandle<()>);
|
||||
|
||||
impl Drop for CancellableTask {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use url::Url;
|
||||
use urlpattern::{UrlPattern, UrlPatternMatchInput};
|
||||
|
||||
#[allow(rustdoc::bare_urls)]
|
||||
#[derive(Debug)]
|
||||
pub struct Entry {
|
||||
pub url: UrlPattern,
|
||||
}
|
||||
|
||||
fn parse_url_pattern(s: &str) -> Result<UrlPattern, urlpattern::quirks::Error> {
|
||||
let mut init = urlpattern::UrlPatternInit::parse_constructor_string::<regex::Regex>(s, None)?;
|
||||
if init.search.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
|
||||
init.search.replace("*".to_string());
|
||||
}
|
||||
if init.hash.as_ref().map(|p| p.is_empty()).unwrap_or(true) {
|
||||
init.hash.replace("*".to_string());
|
||||
}
|
||||
if init
|
||||
.pathname
|
||||
.as_ref()
|
||||
.map(|p| p.is_empty() || p == "/")
|
||||
.unwrap_or(true)
|
||||
{
|
||||
init.pathname.replace("*".to_string());
|
||||
}
|
||||
UrlPattern::parse(init, Default::default())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum EntryRaw {
|
||||
Value(String),
|
||||
Object { url: String },
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Entry {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
EntryRaw::deserialize(deserializer).and_then(|raw| {
|
||||
let url = match raw {
|
||||
EntryRaw::Value(url) => url,
|
||||
EntryRaw::Object { url } => url,
|
||||
};
|
||||
Ok(Entry {
|
||||
url: parse_url_pattern(&url).map_err(|e| {
|
||||
serde::de::Error::custom(format!("`{}` is not a valid URL pattern: {e}", url))
|
||||
})?,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Scope for filesystem access.
|
||||
#[derive(Debug)]
|
||||
pub struct Scope<'a> {
|
||||
allowed: Vec<&'a Arc<Entry>>,
|
||||
denied: Vec<&'a Arc<Entry>>,
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// Creates a new scope from the scope configuration.
|
||||
pub(crate) fn new(allowed: Vec<&'a Arc<Entry>>, denied: Vec<&'a Arc<Entry>>) -> Self {
|
||||
Self { allowed, denied }
|
||||
}
|
||||
|
||||
/// Determines if the given URL is allowed on this scope.
|
||||
pub fn is_allowed(&self, url: &Url) -> bool {
|
||||
let denied = self.denied.iter().any(|entry| {
|
||||
entry
|
||||
.url
|
||||
.test(UrlPatternMatchInput::Url(url.clone()))
|
||||
.unwrap_or_default()
|
||||
});
|
||||
if denied {
|
||||
false
|
||||
} else {
|
||||
self.allowed.iter().any(|entry| {
|
||||
entry
|
||||
.url
|
||||
.test(UrlPatternMatchInput::Url(url.clone()))
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
use super::Entry;
|
||||
|
||||
impl FromStr for Entry {
|
||||
type Err = urlpattern::quirks::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let pattern = super::parse_url_pattern(s)?;
|
||||
Ok(Self { url: pattern })
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_takes_precedence() {
|
||||
let allow = Arc::new("http://localhost:8080/file.png".parse().unwrap());
|
||||
let deny = Arc::new("http://localhost:8080/*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&allow], vec![&deny]);
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080?framework=tauri".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_url() {
|
||||
// plain URL
|
||||
let entry = Arc::new("http://localhost:8080".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
assert!(scope.is_allowed(&"http://localhost:8080".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/path/to/asset.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/path/list?limit=50".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://localhost:8080".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8081".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://local:8080".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_path() {
|
||||
// URL with fixed path
|
||||
let entry = Arc::new("http://localhost:8080/file.png".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png?q=1".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file".parse().unwrap()));
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file.png/other.jpg".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_wildcard() {
|
||||
let entry = Arc::new("http://localhost:8080/*.png".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/file.png#head".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://localhost:8080/assets/file.png".parse().unwrap()));
|
||||
assert!(scope.is_allowed(
|
||||
&"http://localhost:8080/assets/file.png?width=100&height=200"
|
||||
.parse()
|
||||
.unwrap()
|
||||
));
|
||||
|
||||
assert!(!scope.is_allowed(&"http://localhost:8080/file.jpeg".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_wildcard() {
|
||||
let entry = Arc::new("http://*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else#tauri".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else?rel=tauri".parse().unwrap()));
|
||||
assert!(scope.is_allowed(
|
||||
&"http://something.else/path/to/file.mp4?start=500"
|
||||
.parse()
|
||||
.unwrap()
|
||||
));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://something.else".parse().unwrap()));
|
||||
|
||||
let entry = Arc::new("http://*/*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheme_wildcard() {
|
||||
let entry = Arc::new("*://*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"file://path".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"file://path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"https://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"https://something.else?x=1#frag".parse().unwrap()));
|
||||
|
||||
let entry = Arc::new("*://*/*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"http://something.else".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"http://something.else/path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"file://path/to/file".parse().unwrap()));
|
||||
assert!(scope.is_allowed(&"https://something.else".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_query() {
|
||||
let entry = Arc::new("https://tauri.app/path?x=*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"https://tauri.app/path?x=5".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://tauri.app/path?y=5".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_hash() {
|
||||
let entry = Arc::new("https://tauri.app/path#frame*".parse().unwrap());
|
||||
let scope = super::Scope::new(vec![&entry], Vec::new());
|
||||
|
||||
assert!(scope.is_allowed(&"https://tauri.app/path#frame".parse().unwrap()));
|
||||
|
||||
assert!(!scope.is_allowed(&"https://tauri.app/path#work".parse().unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["guest-js/*.ts"]
|
||||
}
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Get the directory of this script
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Go up to the root of the repository (assumes src/app/pages is always 3 levels deep)
|
||||
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
|
||||
|
||||
cd "${REPO_ROOT}"
|
||||
echo "${REPO_ROOT}"
|
||||
|
||||
|
||||
# Run the launch script
|
||||
./script/desktop/launch_desktop_2d.sh
|
||||
@@ -9,7 +9,7 @@ import { Toaster } from "~/components/ui/Toast";
|
||||
import { JobProvider } from "~/components/JobContext";
|
||||
import "./global.css";
|
||||
import { useRenderCounter } from "~/hooks/useRenderCounter";
|
||||
|
||||
import { FetchProxy as fetch } from "@storyteller/tauri-utils";
|
||||
function PostHogInit() {
|
||||
const apiKey = import.meta.env.VITE_POSTHOG_API_KEY;
|
||||
posthog.init(apiKey, {
|
||||
|
||||
@@ -77,6 +77,12 @@ export const Login = () => {
|
||||
|
||||
return (
|
||||
<div className="pegboard fixed flex h-full w-full flex-col items-center justify-center bg-center bg-repeat">
|
||||
<Button
|
||||
className="absolute left-4 top-4 px-3 py-2 text-sm"
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
Back to Home
|
||||
</Button>
|
||||
<div className="mb-7 flex w-10/12 max-w-2xl items-center justify-center gap-4">
|
||||
<img
|
||||
src="/brand/artcraft-logo.png"
|
||||
@@ -126,12 +132,12 @@ export const Login = () => {
|
||||
)}
|
||||
</div>
|
||||
<div className="align-items flex w-full max-w-xl rounded-b-xl bg-ui-controls px-6 py-4">
|
||||
<a
|
||||
{/* <a
|
||||
href="https://storyteller.ai/password-reset"
|
||||
className="grow text-sm !text-primary-400 transition-all duration-150 hover:!text-primary-300"
|
||||
>
|
||||
Forgot your password?
|
||||
</a>
|
||||
</a> */}
|
||||
<div className="flex justify-end gap-1 text-sm">
|
||||
<p className="opacity-75">Don't have an account?</p>
|
||||
<Link to="/signup">Sign Up</Link>
|
||||
|
||||
@@ -75,6 +75,12 @@ export const Signup = () => {
|
||||
|
||||
return (
|
||||
<div className="pegboard fixed flex h-full w-full flex-col items-center justify-center bg-center bg-repeat">
|
||||
<Button
|
||||
className="absolute left-4 top-4 px-3 py-2 text-sm"
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
Back to Home
|
||||
</Button>
|
||||
<div className="mb-7 flex w-10/12 max-w-2xl items-center justify-center gap-4">
|
||||
<img
|
||||
src="/brand/artcraft-logo.png"
|
||||
|
||||
@@ -28,11 +28,11 @@ import { getCanvasRenderBitmap } from "~/signal/canvasRenderBitmap";
|
||||
import { EncodeImageBitmapToBase64 } from "~/utilities/EncodeImageBitmapToBase64";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { PopoverItem } from "~/components/reusable/Popover";
|
||||
import { Api } from "~/KonvaApp/Api";
|
||||
|
||||
import { useJobContext } from "~/components/JobContext";
|
||||
import { IsDesktopApp } from "@storyteller/tauri-utils";
|
||||
import { GalleryItem, GalleryModal } from "@storyteller/ui-gallery-modal";
|
||||
|
||||
import { PromptsApi } from "@storyteller/api";
|
||||
interface ReferenceImage {
|
||||
id: string;
|
||||
url: string;
|
||||
@@ -215,7 +215,7 @@ export const PromptBox = () => {
|
||||
};
|
||||
|
||||
const handleTauriEnqueue = async () => {
|
||||
const api = new Api();
|
||||
const api = new PromptsApi();
|
||||
let image = getCanvasRenderBitmap();
|
||||
if (image === undefined) {
|
||||
return;
|
||||
@@ -261,7 +261,7 @@ export const PromptBox = () => {
|
||||
};
|
||||
|
||||
const handleWebEnqueue = async () => {
|
||||
const api = new Api();
|
||||
const api = new PromptsApi();
|
||||
let image = getCanvasRenderBitmap();
|
||||
if (image === undefined) {
|
||||
toast.error(
|
||||
|
||||
@@ -52,7 +52,7 @@ export const ToolbarTopLeft = () => {
|
||||
className="h-[28px] select-none"
|
||||
/>
|
||||
|
||||
<Button
|
||||
{/* <Button
|
||||
variant="secondary"
|
||||
icon={faChevronRight}
|
||||
iconClassName="text-xs"
|
||||
@@ -61,7 +61,7 @@ export const ToolbarTopLeft = () => {
|
||||
className="bg-transparent p-0 text-sm text-white/80 hover:bg-transparent hover:text-white hover:underline hover:underline-offset-2"
|
||||
>
|
||||
Go to 3D Stage Editor
|
||||
</Button>
|
||||
</Button> */}
|
||||
|
||||
{/* <TabSelector
|
||||
tabs={tabs}
|
||||
|
||||
+7
-6
@@ -1,4 +1,5 @@
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Fragment } from "react";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import {
|
||||
faChevronDown,
|
||||
@@ -65,18 +66,18 @@ export function ProfileDropdown() {
|
||||
)}
|
||||
>
|
||||
<MenuItem
|
||||
as="a"
|
||||
as="button"
|
||||
href={profileUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={twMerge(
|
||||
"flex w-full items-center gap-3 rounded-lg px-3 py-2",
|
||||
"text-md font-medium text-gray-700 hover:bg-gray-100",
|
||||
"text-md font-medium text-white hover:bg-gray-100 hover:text-gray-700",
|
||||
"transition-colors duration-150",
|
||||
)}
|
||||
>
|
||||
<FontAwesomeIcon icon={faUser} className="w-4 text-gray-700" />
|
||||
<span className="text-gray-700">My Profile</span>
|
||||
<FontAwesomeIcon icon={faUser} className="w-4" />
|
||||
My Profile
|
||||
</MenuItem>
|
||||
|
||||
{menuOptions.map((option, index) => (
|
||||
@@ -85,7 +86,7 @@ export function ProfileDropdown() {
|
||||
as="button"
|
||||
className={twMerge(
|
||||
"flex w-full items-center gap-3 rounded-lg px-3 py-2",
|
||||
"text-md font-medium text-gray-700 hover:bg-gray-100",
|
||||
"text-md font-medium text-white hover:bg-gray-100 hover:text-gray-700",
|
||||
"transition-colors duration-150",
|
||||
)}
|
||||
onClick={(e) => {
|
||||
@@ -94,7 +95,7 @@ export function ProfileDropdown() {
|
||||
option.onClick();
|
||||
}}
|
||||
>
|
||||
<FontAwesomeIcon icon={option.icon} className="w-4 text-gray-700" />
|
||||
<FontAwesomeIcon icon={option.icon} className="w-4" />
|
||||
<span>{option.label}</span>
|
||||
</MenuItem>
|
||||
))}
|
||||
|
||||
@@ -10,6 +10,11 @@ import path from 'path';
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: 5741,
|
||||
// Local development CORS for images
|
||||
headers: {
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp"
|
||||
},
|
||||
},
|
||||
|
||||
//build: {
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
import { CloseButton, Button } from "~/components";
|
||||
import { Transition } from "@headlessui/react";
|
||||
import { createPortal } from "react-dom";
|
||||
import dayjs from "dayjs";
|
||||
import { faDownToLine } from "@fortawesome/pro-solid-svg-icons";
|
||||
|
||||
interface LightboxModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
imageUrl?: string | null;
|
||||
imageAlt?: string;
|
||||
onImageError?: () => void;
|
||||
title?: string;
|
||||
createdAt?: string;
|
||||
additionalInfo?: React.ReactNode;
|
||||
downloadUrl?: string;
|
||||
}
|
||||
|
||||
export function LightboxModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
imageUrl,
|
||||
imageAlt = "",
|
||||
onImageError,
|
||||
title,
|
||||
createdAt,
|
||||
additionalInfo,
|
||||
downloadUrl,
|
||||
}: LightboxModalProps) {
|
||||
return createPortal(
|
||||
<Transition appear show={isOpen}>
|
||||
<div className="fixed inset-0 z-[100]">
|
||||
<Transition.Child
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0"
|
||||
enterTo="opacity-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
>
|
||||
<div
|
||||
className="fixed inset-0 cursor-pointer bg-black/60"
|
||||
onClick={onClose}
|
||||
/>
|
||||
</Transition.Child>
|
||||
<div
|
||||
className="fixed inset-0 flex items-center justify-center p-4"
|
||||
onClick={onClose}
|
||||
>
|
||||
<Transition.Child
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<div
|
||||
className="relative h-[90vh] w-[80vw] rounded-xl bg-[#2C2C2C]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<CloseButton
|
||||
onClick={onClose}
|
||||
className="absolute right-4 top-4 z-10"
|
||||
/>
|
||||
<div className="grid h-full grid-cols-3 gap-6">
|
||||
<div className="col-span-2 flex h-full items-center justify-center overflow-hidden rounded-l-xl bg-black/40">
|
||||
{!imageUrl ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gray-800">
|
||||
<span className="text-white/60">Image not available</span>
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={imageAlt}
|
||||
className="h-full w-full object-contain"
|
||||
onError={onImageError}
|
||||
crossOrigin="anonymous"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex h-full flex-col py-5 pe-5">
|
||||
<div className="flex-1 space-y-4">
|
||||
<div className="text-xl font-medium">
|
||||
{title || "Image Generation"}
|
||||
</div>
|
||||
{createdAt && (
|
||||
<div className="text-sm text-white/60">
|
||||
Created:{" "}
|
||||
{dayjs(createdAt).format("MMM D, YYYY HH:mm:ss")}
|
||||
</div>
|
||||
)}
|
||||
{additionalInfo}
|
||||
</div>
|
||||
{downloadUrl && (
|
||||
<div className="flex justify-end">
|
||||
<a
|
||||
href={downloadUrl}
|
||||
download
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="no-underline"
|
||||
>
|
||||
<Button
|
||||
icon={faDownToLine}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Download
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition.Child>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -58,7 +58,7 @@ export const TopBar = ({ pageName }: Props) => {
|
||||
Back to Editor
|
||||
</ButtonLink>
|
||||
)}
|
||||
<Button
|
||||
{/* <Button
|
||||
variant="secondary"
|
||||
icon={faChevronRight}
|
||||
iconClassName="text-xs"
|
||||
@@ -67,7 +67,7 @@ export const TopBar = ({ pageName }: Props) => {
|
||||
className="bg-transparent p-0 text-sm text-white/80 hover:bg-transparent hover:text-white hover:underline hover:underline-offset-2"
|
||||
>
|
||||
Go to 2D Canvas
|
||||
</Button>
|
||||
</Button> */}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-center gap-2 font-medium">
|
||||
|
||||
@@ -1,52 +1,20 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { StrictMode, useEffect } from "react";
|
||||
import { useSignals, useSignalEffect } from "@preact/signals-react/runtime";
|
||||
import { useEffect } from "react";
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import * as ReactDOM from 'react-dom/client';
|
||||
import { authentication, persistLogin } from "~/signals";
|
||||
import { PageEnigma } from './pages/PageEnigma/PageEnigma';
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { PageEnigma } from "./pages/PageEnigma/PageEnigma";
|
||||
import { createRoot } from "react-dom/client";
|
||||
//import App from './app/app';
|
||||
//import { App } from './root';
|
||||
|
||||
import {
|
||||
Links,
|
||||
Meta,
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
useLoaderData,
|
||||
} from "@remix-run/react";
|
||||
|
||||
import "./styles/normalize.css";
|
||||
import "./styles/tailwind.css";
|
||||
import "./styles/base.css";
|
||||
import "@fortawesome/fontawesome-svg-core/styles.css";
|
||||
|
||||
import { config } from "@fortawesome/fontawesome-svg-core";
|
||||
|
||||
import EnvironmentVariables from "~/Classes/EnvironmentVariables";
|
||||
import { pageHeight, pageWidth } from "~/signals";
|
||||
|
||||
import { pageHeight, pageWidth, persistLogin } from "~/signals";
|
||||
import { showWizard } from "~/pages/PageEnigma/Wizard/signals/wizard";
|
||||
import { BuildEnvironmentType, GetBuildEnvironment } from "./BuildEnvironment";
|
||||
import { posthog } from "posthog-js";
|
||||
|
||||
config.autoAddCss = false; /* eslint-disable import/first */
|
||||
|
||||
//const root = ReactDOM.createRoot(
|
||||
// document.getElementById('root') as HTMLElement
|
||||
//);
|
||||
//
|
||||
//root.render(
|
||||
// <StrictMode>
|
||||
// <BrowserRouter>
|
||||
// <App/>
|
||||
// </BrowserRouter>
|
||||
// </StrictMode>
|
||||
//);
|
||||
|
||||
//createRoot(document.getElementById("root")!).render(<PageEnigma/>);
|
||||
|
||||
// TODO(bt,2025-04-19): Make these configurable
|
||||
const ENV = {
|
||||
BASE_API: "https://api.storyteller.ai",
|
||||
@@ -65,17 +33,18 @@ const GlobalSettingsManager = ({ env }: { env: Record<string, string> }) => {
|
||||
|
||||
/// Initizations that depends on ENV vars ///
|
||||
function PostHogInit() {
|
||||
const data = EnvironmentVariables.values;
|
||||
const apiKey = data.REACT_APP_PUBLIC_POSTHOG_KEY as string;
|
||||
//posthog.init(apiKey, {
|
||||
// //HACK: This is the default host from Netlify, but need to figure out why it isn't working on prod.
|
||||
// // api_host: data.DEPLOY_PRIME_URL + "/ingest" as string,
|
||||
// api_host: "https://studio.storyteller.ai/ingest" as string,
|
||||
// ui_host: data.REACT_APP_PUBLIC_POSTHOG_UI as string,
|
||||
//});
|
||||
const apiKey = import.meta.env.VITE_POSTHOG_API_KEY;
|
||||
posthog.init(apiKey, {
|
||||
api_host: "https://us.i.posthog.com/",
|
||||
ui_host: "https://us.i.posthog.com/",
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
EnvironmentVariables.initialize(env);
|
||||
if (import.meta.env.DEV) {
|
||||
return;
|
||||
}
|
||||
PostHogInit();
|
||||
}, [env]);
|
||||
|
||||
@@ -114,8 +83,8 @@ createRoot(document.getElementById("root")!).render(
|
||||
<BrowserRouter>
|
||||
<GlobalSettingsManager env={ENV} />
|
||||
<div className="topbar-spacer" />
|
||||
<PageEnigma/>
|
||||
<PageEnigma />
|
||||
</BrowserRouter>
|
||||
</StrictMode>
|
||||
</>
|
||||
</>,
|
||||
);
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faDownToLine } from "@fortawesome/pro-solid-svg-icons";
|
||||
import { LightboxModal } from "~/components/reusable/LightboxModal";
|
||||
import { LightboxModal } from "@storyteller/ui-lightbox-modal";
|
||||
import { GetCdnOrigin } from "~/api/GetCdnOrigin";
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -7,7 +7,7 @@ import React, { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { LibraryModalApi } from "./LibraryModalApi";
|
||||
import { FilterMediaClasses } from "../../../../enums";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { LightboxModal } from "~/components/reusable/LightboxModal";
|
||||
import { LightboxModal } from "@storyteller/ui-lightbox-modal";
|
||||
import { GetCdnOrigin } from "~/api/GetCdnOrigin";
|
||||
|
||||
export interface LibraryItem {
|
||||
|
||||
@@ -623,8 +623,8 @@ export const PromptBox = () => {
|
||||
src={image.url}
|
||||
alt="Reference"
|
||||
className="h-full w-full rounded-lg object-cover"
|
||||
crossOrigin="anonymous"
|
||||
referrerPolicy="no-referrer"
|
||||
// crossOrigin="anonymous"
|
||||
// referrerPolicy="no-referrer"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleRemoveReference(image.id)}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { useEffect } from "react";
|
||||
import { useSignals } from "@preact/signals-react/runtime";
|
||||
import { LinksFunction } from "@remix-run/deno";
|
||||
import { posthog } from "posthog-js";
|
||||
import { PostHogProvider } from "posthog-js/react";
|
||||
@@ -9,13 +7,11 @@ import {
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
useLoaderData,
|
||||
} from "@remix-run/react";
|
||||
|
||||
import normalizeCss from "./styles/normalize.css?url";
|
||||
import tailwindCss from "./styles/tailwind.css?url";
|
||||
import baseCss from "./styles/base.css?url";
|
||||
import { Environment, Configs } from "./configs";
|
||||
//import { api } from "@storyteller/api";
|
||||
|
||||
// The following import prevents a Font Awesome icon server-side rendering bug,
|
||||
@@ -24,12 +20,6 @@ import "@fortawesome/fontawesome-svg-core/styles.css";
|
||||
// Prevent fontawesome from adding its CSS since we did it manually above:
|
||||
import { config } from "@fortawesome/fontawesome-svg-core";
|
||||
|
||||
import EnvironmentVariables from "~/Classes/EnvironmentVariables";
|
||||
import { pageHeight, pageWidth } from "~/signals";
|
||||
|
||||
import { showWizard } from "~/pages/PageEnigma/Wizard/signals/wizard";
|
||||
import { BuildEnvironmentType, GetBuildEnvironment } from "./BuildEnvironment";
|
||||
|
||||
config.autoAddCss = false; /* eslint-disable import/first */
|
||||
|
||||
export const links: LinksFunction = () => [
|
||||
@@ -60,57 +50,7 @@ export const links: LinksFunction = () => [
|
||||
},
|
||||
];
|
||||
|
||||
// .env part 2 add to this
|
||||
export async function loader() {
|
||||
const environmentType = GetBuildEnvironment().getBuildEnvironmentType();
|
||||
const configs = new Configs(environmentType);
|
||||
|
||||
let uploadApiVideo = "https://upload.storyteller.ai";
|
||||
|
||||
switch (environmentType) {
|
||||
case BuildEnvironmentType.Dev:
|
||||
uploadApiVideo = "http://localhost:12345";
|
||||
break;
|
||||
}
|
||||
|
||||
//console.log(">>>> API LIBRARY IMPORT TEST", api());
|
||||
|
||||
const env = {
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
BASE_API: process.env.BASE_API || configs.baseApi || "%BUILD_BASE_API%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
GOOGLE_API: process.env.GOOGLE_API || configs.googleApi || "%BUILD_GOOGLE_API%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
FUNNEL_API: process.env.FUNNEL_API || configs.funnelApi || "%BUILD_FUNNEL_API%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
CDN_API: process.env.CDN_API || configs.cdnApi || "%BUILD_CDN_API%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
GRAVATAR_API: process.env.GRAVATAR_API || configs.gravatarApi || "%BUILD_GRAVATAR_API%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
DEPLOY_PRIME_URL: process.env.DEPLOY_PRIME_URL || configs.deployPrimeUrl || "%DEPLOY_PRIME_URL%",
|
||||
REACT_APP_PUBLIC_POSTHOG_KEY:
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
process.env.REACT_APP_PUBLIC_POSTHOG_KEY ||
|
||||
"%REACT_APP_PUBLIC_POSTHOG_KEY%",
|
||||
REACT_APP_PUBLIC_POSTHOG_UI:
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
process.env.REACT_APP_PUBLIC_POSTHOG_UI ||
|
||||
"%REACT_APP_PUBLIC_POSTHOG_UI%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
CONTEXT: process.env.CONTEXT || configs.deployContext || "%CONTEXT%",
|
||||
// @ts-expect-error ProvessEnv is correct
|
||||
DEPLOY_CONTEXT: process.env.DEPLOY_CONTEXT || configs.deployContext || "%DEPLOY_CONTEXT%",
|
||||
|
||||
// .env part 3
|
||||
//UPLOAD_API_VIDEO: process.env.UPLOAD_API_VIDEO || configs.uploadApiVideo || "%UPLOAD_API_VIDEO%",
|
||||
UPLOAD_API_VIDEO: uploadApiVideo,
|
||||
} as Record<string, string | boolean>;
|
||||
return { ENV: env };
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const data = useLoaderData() as { ENV: Record<string, string> };
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -120,7 +60,6 @@ export default function App() {
|
||||
<Links />
|
||||
</head>
|
||||
<body className="overflow-hidden bg-ui-background">
|
||||
{data && <GlobalSettingsManager env={data.ENV} />}
|
||||
<div className="topbar-spacer" />
|
||||
<PostHogProvider client={posthog}>
|
||||
<Outlet />
|
||||
@@ -131,48 +70,3 @@ export default function App() {
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
const GlobalSettingsManager = ({ env }: { env: Record<string, string> }) => {
|
||||
useSignals();
|
||||
|
||||
/// Initizations that depends on ENV vars ///
|
||||
function PostHogInit() {
|
||||
const data = EnvironmentVariables.values;
|
||||
const apiKey = data.REACT_APP_PUBLIC_POSTHOG_KEY as string;
|
||||
posthog.init(apiKey, {
|
||||
//HACK: This is the default host from Netlify, but need to figure out why it isn't working on prod.
|
||||
// api_host: data.DEPLOY_PRIME_URL + "/ingest" as string,
|
||||
api_host: "https://studio.storyteller.ai/ingest" as string,
|
||||
ui_host: data.REACT_APP_PUBLIC_POSTHOG_UI as string,
|
||||
});
|
||||
}
|
||||
useEffect(() => {
|
||||
EnvironmentVariables.initialize(env);
|
||||
PostHogInit();
|
||||
}, [env]);
|
||||
|
||||
/// Initizations that run only once on 1ST mount ///
|
||||
function setPage() {
|
||||
// TODO address this issue with zooming
|
||||
pageHeight.value = window.innerHeight;
|
||||
pageWidth.value = window.innerWidth;
|
||||
}
|
||||
function initWizard() {
|
||||
if (showWizard.value) {
|
||||
return;
|
||||
}
|
||||
const wizard = localStorage.getItem("storyteller-wizard");
|
||||
showWizard.value = wizard ? "" : "initial";
|
||||
localStorage.setItem("storyteller-wizard", "shown");
|
||||
}
|
||||
useEffect(() => {
|
||||
initWizard();
|
||||
setPage();
|
||||
window.addEventListener("resize", setPage);
|
||||
return () => {
|
||||
window.removeEventListener("resize", setPage);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Get the directory of this script
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Go up to the root of the repository (assumes src/app/pages is always 3 levels deep)
|
||||
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
|
||||
|
||||
cd "${REPO_ROOT}"
|
||||
echo "${REPO_ROOT}"
|
||||
|
||||
# Run the launch script
|
||||
./script/desktop/run_desktop_3d.sh
|
||||
@@ -1,8 +1,18 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["env.d.ts", "**/*.ts", "**/*.tsx", "netlify-edge-plugin.ts"],
|
||||
"include": [
|
||||
"env.d.ts",
|
||||
"**/*.js",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
"netlify-edge-plugin.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
"lib": [
|
||||
"DOM",
|
||||
"DOM.Iterable",
|
||||
"ESNext"
|
||||
],
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"jsx": "react-jsx",
|
||||
@@ -15,12 +25,17 @@
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"paths": {
|
||||
"~/*": ["apps/editor3d/app/src/*"]
|
||||
"~/*": [
|
||||
"apps/editor3d/app/src/*"
|
||||
]
|
||||
},
|
||||
// Vite takes care of building everything, not tsc.
|
||||
"noEmit": true
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
"path": "../../libs/components/lightbox-modal"
|
||||
},
|
||||
{
|
||||
"path": "../../libs/components/input"
|
||||
},
|
||||
@@ -47,6 +62,9 @@
|
||||
},
|
||||
{
|
||||
"path": "../../libs/components/gallery-modal"
|
||||
},
|
||||
{
|
||||
"path": "../../libs/tauri-utils"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -60,6 +60,11 @@ export default defineConfig({
|
||||
},
|
||||
],
|
||||
server: {
|
||||
// Local development CORS for images
|
||||
headers: {
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Embedder-Policy": "require-corp"
|
||||
},
|
||||
proxy: {
|
||||
"/v1": "https://api.storyteller.ai",
|
||||
"/avatar": "https://www.gravatar.com",
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MyApp</title>
|
||||
<base href="/" />
|
||||
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<link rel="stylesheet" href="/src/styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"name": "@frontend/my-app",
|
||||
"version": "0.0.1",
|
||||
"private": true
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
@@ -1 +0,0 @@
|
||||
/* Your styles goes here. */
|
||||
@@ -1,16 +0,0 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
|
||||
import App from './app';
|
||||
|
||||
describe('App', () => {
|
||||
it('should render successfully', () => {
|
||||
const { baseElement } = render(<BrowserRouter><App /></BrowserRouter>);
|
||||
expect(baseElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should have a greeting as the title', () => {
|
||||
const { getAllByText } = render(<BrowserRouter><App /></BrowserRouter>);
|
||||
expect(getAllByText(new RegExp('Welcome @frontend/my-app', 'gi')).length > 0).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
// Uncomment this line to use CSS modules
|
||||
// import styles from './app.module.css';
|
||||
import NxWelcome from "./nx-welcome";
|
||||
|
||||
import { Route, Routes, Link } from 'react-router-dom';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<div>
|
||||
<NxWelcome title="@frontend/my-app"/>
|
||||
|
||||
{/* START: routes */}
|
||||
{/* These routes and navigation have been generated for you */}
|
||||
{/* Feel free to move and update them to fit your needs */}
|
||||
<br/>
|
||||
<hr/>
|
||||
<br/>
|
||||
<div role="navigation">
|
||||
<ul>
|
||||
<li><Link to="/">Home</Link></li>
|
||||
<li><Link to="/page-2">Page 2</Link></li>
|
||||
</ul>
|
||||
</div>
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<div>This is the generated root route. <Link to="/page-2">Click here for page 2.</Link></div>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/page-2"
|
||||
element={
|
||||
<div><Link to="/">Click here to go back to root page.</Link></div>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
{/* END: routes */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
|
||||
@@ -1,857 +0,0 @@
|
||||
/*
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
This is a starter component and can be deleted.
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
Delete this file and get started with your project!
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
*/
|
||||
export function NxWelcome({ title }: { title: string }) {
|
||||
return (
|
||||
<>
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
html {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
|
||||
'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif,
|
||||
'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
|
||||
'Noto Color Emoji';
|
||||
line-height: 1.5;
|
||||
tab-size: 4;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
body {
|
||||
font-family: inherit;
|
||||
line-height: inherit;
|
||||
margin: 0;
|
||||
}
|
||||
h1,
|
||||
h2,
|
||||
p,
|
||||
pre {
|
||||
margin: 0;
|
||||
}
|
||||
*,
|
||||
::before,
|
||||
::after {
|
||||
box-sizing: border-box;
|
||||
border-width: 0;
|
||||
border-style: solid;
|
||||
border-color: currentColor;
|
||||
}
|
||||
h1,
|
||||
h2 {
|
||||
font-size: inherit;
|
||||
font-weight: inherit;
|
||||
}
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
pre {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
|
||||
'Liberation Mono', 'Courier New', monospace;
|
||||
}
|
||||
svg {
|
||||
display: block;
|
||||
vertical-align: middle;
|
||||
shape-rendering: auto;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
pre {
|
||||
background-color: rgba(55, 65, 81, 1);
|
||||
border-radius: 0.25rem;
|
||||
color: rgba(229, 231, 235, 1);
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
|
||||
'Liberation Mono', 'Courier New', monospace;
|
||||
overflow: auto;
|
||||
padding: 0.5rem 0.75rem;
|
||||
}
|
||||
|
||||
.shadow {
|
||||
box-shadow: 0 0 #0000, 0 0 #0000, 0 10px 15px -3px rgba(0, 0, 0, 0.1),
|
||||
0 4px 6px -2px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
.rounded {
|
||||
border-radius: 1.5rem;
|
||||
}
|
||||
.wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
.container {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
max-width: 768px;
|
||||
padding-bottom: 3rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
color: rgba(55, 65, 81, 1);
|
||||
width: 100%;
|
||||
}
|
||||
#welcome {
|
||||
margin-top: 2.5rem;
|
||||
}
|
||||
#welcome h1 {
|
||||
font-size: 3rem;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.025em;
|
||||
line-height: 1;
|
||||
}
|
||||
#welcome span {
|
||||
display: block;
|
||||
font-size: 1.875rem;
|
||||
font-weight: 300;
|
||||
line-height: 2.25rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
#hero {
|
||||
align-items: center;
|
||||
background-color: hsla(214, 62%, 21%, 1);
|
||||
border: none;
|
||||
box-sizing: border-box;
|
||||
color: rgba(55, 65, 81, 1);
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
margin-top: 3.5rem;
|
||||
}
|
||||
#hero .text-container {
|
||||
color: rgba(255, 255, 255, 1);
|
||||
padding: 3rem 2rem;
|
||||
}
|
||||
#hero .text-container h2 {
|
||||
font-size: 1.5rem;
|
||||
line-height: 2rem;
|
||||
position: relative;
|
||||
}
|
||||
#hero .text-container h2 svg {
|
||||
color: hsla(162, 47%, 50%, 1);
|
||||
height: 2rem;
|
||||
left: -0.25rem;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
width: 2rem;
|
||||
}
|
||||
#hero .text-container h2 span {
|
||||
margin-left: 2.5rem;
|
||||
}
|
||||
#hero .text-container a {
|
||||
background-color: rgba(255, 255, 255, 1);
|
||||
border-radius: 0.75rem;
|
||||
color: rgba(55, 65, 81, 1);
|
||||
display: inline-block;
|
||||
margin-top: 1.5rem;
|
||||
padding: 1rem 2rem;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
#hero .logo-container {
|
||||
display: none;
|
||||
justify-content: center;
|
||||
padding-left: 2rem;
|
||||
padding-right: 2rem;
|
||||
}
|
||||
#hero .logo-container svg {
|
||||
color: rgba(255, 255, 255, 1);
|
||||
width: 66.666667%;
|
||||
}
|
||||
#middle-content {
|
||||
align-items: flex-start;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
margin-top: 3.5rem;
|
||||
}
|
||||
|
||||
#middle-content #middle-content-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
#learning-materials {
|
||||
padding: 2.5rem 2rem;
|
||||
}
|
||||
#learning-materials h2 {
|
||||
font-weight: 500;
|
||||
font-size: 1.25rem;
|
||||
letter-spacing: -0.025em;
|
||||
line-height: 1.75rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
.list-item-link {
|
||||
align-items: center;
|
||||
border-radius: 0.75rem;
|
||||
display: flex;
|
||||
margin-top: 1rem;
|
||||
padding: 1rem;
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 150ms;
|
||||
width: 100%;
|
||||
}
|
||||
.list-item-link svg:first-child {
|
||||
margin-right: 1rem;
|
||||
height: 1.5rem;
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 150ms;
|
||||
width: 1.5rem;
|
||||
}
|
||||
.list-item-link > span {
|
||||
flex-grow: 1;
|
||||
font-weight: 400;
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
.list-item-link > span > span {
|
||||
color: rgba(107, 114, 128, 1);
|
||||
display: block;
|
||||
flex-grow: 1;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 300;
|
||||
line-height: 1rem;
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
.list-item-link svg:last-child {
|
||||
height: 1rem;
|
||||
transition-property: all;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 150ms;
|
||||
width: 1rem;
|
||||
}
|
||||
.list-item-link:hover {
|
||||
color: rgba(255, 255, 255, 1);
|
||||
background-color: hsla(162, 55%, 33%, 1);
|
||||
}
|
||||
.list-item-link:hover > span {}
|
||||
.list-item-link:hover > span > span {
|
||||
color: rgba(243, 244, 246, 1);
|
||||
}
|
||||
.list-item-link:hover svg:last-child {
|
||||
transform: translateX(0.25rem);
|
||||
}
|
||||
#other-links {}
|
||||
.button-pill {
|
||||
padding: 1.5rem 2rem;
|
||||
margin-bottom: 2rem;
|
||||
transition-duration: 300ms;
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
align-items: center;
|
||||
display: flex;
|
||||
}
|
||||
.button-pill svg {
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 150ms;
|
||||
flex-shrink: 0;
|
||||
width: 3rem;
|
||||
}
|
||||
.button-pill > span {
|
||||
letter-spacing: -0.025em;
|
||||
font-weight: 400;
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.75rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
.button-pill span span {
|
||||
display: block;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 300;
|
||||
line-height: 1.25rem;
|
||||
}
|
||||
.button-pill:hover svg,
|
||||
.button-pill:hover {
|
||||
color: rgba(255, 255, 255, 1) !important;
|
||||
}
|
||||
#nx-console:hover {
|
||||
background-color: rgba(0, 122, 204, 1);
|
||||
}
|
||||
#nx-console svg {
|
||||
color: rgba(0, 122, 204, 1);
|
||||
}
|
||||
#nx-console-jetbrains {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
#nx-console-jetbrains:hover {
|
||||
background-color: rgba(255, 49, 140, 1);
|
||||
}
|
||||
#nx-console-jetbrains svg {
|
||||
color: rgba(255, 49, 140, 1);
|
||||
}
|
||||
#nx-repo:hover {
|
||||
background-color: rgba(24, 23, 23, 1);
|
||||
}
|
||||
#nx-repo svg {
|
||||
color: rgba(24, 23, 23, 1);
|
||||
}
|
||||
#nx-cloud {
|
||||
margin-bottom: 2rem;
|
||||
margin-top: 2rem;
|
||||
padding: 2.5rem 2rem;
|
||||
}
|
||||
#nx-cloud > div {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
}
|
||||
#nx-cloud > div svg {
|
||||
border-radius: 0.375rem;
|
||||
flex-shrink: 0;
|
||||
width: 3rem;
|
||||
}
|
||||
#nx-cloud > div h2 {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.025em;
|
||||
line-height: 1.75rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
#nx-cloud > div h2 span {
|
||||
display: block;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 300;
|
||||
line-height: 1.25rem;
|
||||
}
|
||||
#nx-cloud p {
|
||||
font-size: 1rem;
|
||||
line-height: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
#nx-cloud pre {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
#nx-cloud a {
|
||||
color: rgba(107, 114, 128, 1);
|
||||
display: block;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
margin-top: 1.5rem;
|
||||
text-align: right;
|
||||
}
|
||||
#nx-cloud a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
#commands {
|
||||
padding: 2.5rem 2rem;
|
||||
margin-top: 3.5rem;
|
||||
}
|
||||
#commands h2 {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.025em;
|
||||
line-height: 1.75rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
#commands p {
|
||||
font-size: 1rem;
|
||||
font-weight: 300;
|
||||
line-height: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
details {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
margin-top: 1rem;
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
width: 100%;
|
||||
}
|
||||
details pre > span {
|
||||
color: rgba(181, 181, 181, 1);
|
||||
display: block;
|
||||
}
|
||||
summary {
|
||||
border-radius: 0.5rem;
|
||||
display: flex;
|
||||
font-weight: 400;
|
||||
padding: 0.5rem;
|
||||
cursor: pointer;
|
||||
transition-property: background-color, border-color, color, fill, stroke,
|
||||
opacity, box-shadow, transform, filter, backdrop-filter,
|
||||
-webkit-backdrop-filter;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 150ms;
|
||||
}
|
||||
summary:hover {
|
||||
background-color: rgba(243, 244, 246, 1);
|
||||
}
|
||||
summary svg {
|
||||
height: 1.5rem;
|
||||
margin-right: 1rem;
|
||||
width: 1.5rem;
|
||||
}
|
||||
#love {
|
||||
color: rgba(107, 114, 128, 1);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.25rem;
|
||||
margin-top: 3.5rem;
|
||||
opacity: 0.6;
|
||||
text-align: center;
|
||||
}
|
||||
#love svg {
|
||||
color: rgba(252, 165, 165, 1);
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
display: inline;
|
||||
margin-top: -0.25rem;
|
||||
}
|
||||
@media screen and (min-width: 768px) {
|
||||
#hero {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
#hero .logo-container {
|
||||
display: flex;
|
||||
}
|
||||
#middle-content {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 4rem;
|
||||
}
|
||||
}
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
<div className="wrapper">
|
||||
<div className="container">
|
||||
<div id="welcome">
|
||||
<h1>
|
||||
<span> Hello there, </span>
|
||||
Welcome {title} 👋
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div id="hero" className="rounded">
|
||||
<div className="text-container">
|
||||
<h2>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"
|
||||
/>
|
||||
</svg>
|
||||
<span>You're up and running</span>
|
||||
</h2>
|
||||
<a href="#commands"> What's next? </a>
|
||||
</div>
|
||||
<div className="logo-container">
|
||||
<svg
|
||||
fill="currentColor"
|
||||
role="img"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M11.987 14.138l-3.132 4.923-5.193-8.427-.012 8.822H0V4.544h3.691l5.247 8.833.005-3.998 3.044 4.759zm.601-5.761c.024-.048 0-3.784.008-3.833h-3.65c.002.059-.005 3.776-.003 3.833h3.645zm5.634 4.134a2.061 2.061 0 0 0-1.969 1.336 1.963 1.963 0 0 1 2.343-.739c.396.161.917.422 1.33.283a2.1 2.1 0 0 0-1.704-.88zm3.39 1.061c-.375-.13-.8-.277-1.109-.681-.06-.08-.116-.17-.176-.265a2.143 2.143 0 0 0-.533-.642c-.294-.216-.68-.322-1.18-.322a2.482 2.482 0 0 0-2.294 1.536 2.325 2.325 0 0 1 4.002.388.75.75 0 0 0 .836.334c.493-.105.46.36 1.203.518v-.133c-.003-.446-.246-.55-.75-.733zm2.024 1.266a.723.723 0 0 0 .347-.638c-.01-2.957-2.41-5.487-5.37-5.487a5.364 5.364 0 0 0-4.487 2.418c-.01-.026-1.522-2.39-1.538-2.418H8.943l3.463 5.423-3.379 5.32h3.54l1.54-2.366 1.568 2.366h3.541l-3.21-5.052a.7.7 0 0 1-.084-.32 2.69 2.69 0 0 1 2.69-2.691h.001c1.488 0 1.736.89 2.057 1.308.634.826 1.9.464 1.9 1.541a.707.707 0 0 0 1.066.596zm.35.133c-.173.372-.56.338-.755.639-.176.271.114.412.114.412s.337.156.538-.311c.104-.231.14-.488.103-.74z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="middle-content">
|
||||
<div id="middle-content-container">
|
||||
<div id="learning-materials" className="rounded shadow">
|
||||
<h2>Learning materials</h2>
|
||||
<a
|
||||
href="https://nx.dev/getting-started/intro?utm_source=nx-project"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="list-item-link"
|
||||
>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"
|
||||
/>
|
||||
</svg>
|
||||
<span>
|
||||
Documentation
|
||||
<span> Everything is in there </span>
|
||||
</span>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
<a
|
||||
href="https://nx.dev/blog/?utm_source=nx-project"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="list-item-link"
|
||||
>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 8h6v4H7V8z"
|
||||
/>
|
||||
</svg>
|
||||
<span>
|
||||
Blog
|
||||
<span> Changelog, features & events </span>
|
||||
</span>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
<a
|
||||
href="https://www.youtube.com/@NxDevtools/videos?utm_source=nx-project&sub_confirmation=1"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="list-item-link"
|
||||
>
|
||||
<svg
|
||||
role="img"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>YouTube</title>
|
||||
<path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
|
||||
</svg>
|
||||
<span>
|
||||
YouTube channel
|
||||
<span> Nx Show, talks & tutorials </span>
|
||||
</span>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
<a
|
||||
href="https://nx.dev/react-tutorial/1-code-generation?utm_source=nx-project"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="list-item-link"
|
||||
>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"
|
||||
/>
|
||||
</svg>
|
||||
<span>
|
||||
Interactive tutorials
|
||||
<span> Create an app, step-by-step </span>
|
||||
</span>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
<a
|
||||
id="nx-repo"
|
||||
className="button-pill rounded shadow"
|
||||
href="https://github.com/nrwl/nx?utm_source=nx-project"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<svg
|
||||
fill="currentColor"
|
||||
role="img"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
|
||||
</svg>
|
||||
<span>
|
||||
Nx is open source
|
||||
<span> Love Nx? Give us a star! </span>
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
<div id="other-links">
|
||||
<a
|
||||
id="nx-console"
|
||||
className="button-pill rounded shadow"
|
||||
href="https://marketplace.visualstudio.com/items?itemName=nrwl.angular-console&utm_source=nx-project"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<svg
|
||||
fill="currentColor"
|
||||
role="img"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>Visual Studio Code</title>
|
||||
<path d="M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z" />
|
||||
</svg>
|
||||
<span>
|
||||
Install Nx Console for VSCode
|
||||
<span>The official VSCode extension for Nx.</span>
|
||||
</span>
|
||||
</a>
|
||||
<a
|
||||
id="nx-console-jetbrains"
|
||||
className="button-pill rounded shadow"
|
||||
href="https://plugins.jetbrains.com/plugin/21060-nx-console"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<svg
|
||||
height="48"
|
||||
width="48"
|
||||
viewBox="20 20 60 60"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="m22.5 22.5h60v60h-60z" />
|
||||
<g fill="#fff">
|
||||
<path d="m29.03 71.25h22.5v3.75h-22.5z" />
|
||||
<path d="m28.09 38 1.67-1.58a1.88 1.88 0 0 0 1.47.87c.64 0 1.06-.44 1.06-1.31v-5.98h2.58v6a3.48 3.48 0 0 1 -.87 2.6 3.56 3.56 0 0 1 -2.57.95 3.84 3.84 0 0 1 -3.34-1.55z" />
|
||||
<path d="m36 30h7.53v2.19h-5v1.44h4.49v2h-4.42v1.49h5v2.21h-7.6z" />
|
||||
<path d="m47.23 32.29h-2.8v-2.29h8.21v2.27h-2.81v7.1h-2.6z" />
|
||||
<path d="m29.13 43.08h4.42a3.53 3.53 0 0 1 2.55.83 2.09 2.09 0 0 1 .6 1.53 2.16 2.16 0 0 1 -1.44 2.09 2.27 2.27 0 0 1 1.86 2.29c0 1.61-1.31 2.59-3.55 2.59h-4.44zm5 2.89c0-.52-.42-.8-1.18-.8h-1.29v1.64h1.24c.79 0 1.25-.26 1.25-.81zm-.9 2.66h-1.57v1.73h1.62c.8 0 1.24-.31 1.24-.86 0-.5-.4-.87-1.27-.87z" />
|
||||
<path d="m38 43.08h4.1a4.19 4.19 0 0 1 3 1 2.93 2.93 0 0 1 .9 2.19 3 3 0 0 1 -1.93 2.89l2.24 3.27h-3l-1.88-2.84h-.87v2.84h-2.56zm4 4.5c.87 0 1.39-.43 1.39-1.11 0-.75-.54-1.12-1.4-1.12h-1.44v2.26z" />
|
||||
<path d="m49.59 43h2.5l4 9.44h-2.79l-.67-1.69h-3.63l-.67 1.69h-2.71zm2.27 5.73-1-2.65-1.06 2.65z" />
|
||||
<path d="m56.46 43.05h2.6v9.37h-2.6z" />
|
||||
<path d="m60.06 43.05h2.42l3.37 5v-5h2.57v9.37h-2.26l-3.53-5.14v5.14h-2.57z" />
|
||||
<path d="m68.86 51 1.45-1.73a4.84 4.84 0 0 0 3 1.13c.71 0 1.08-.24 1.08-.65 0-.4-.31-.6-1.59-.91-2-.46-3.53-1-3.53-2.93 0-1.74 1.37-3 3.62-3a5.89 5.89 0 0 1 3.86 1.25l-1.26 1.84a4.63 4.63 0 0 0 -2.62-.92c-.63 0-.94.25-.94.6 0 .42.32.61 1.63.91 2.14.46 3.44 1.16 3.44 2.91 0 1.91-1.51 3-3.79 3a6.58 6.58 0 0 1 -4.35-1.5z" />
|
||||
</g>
|
||||
</svg>
|
||||
<span>
|
||||
Install Nx Console for JetBrains
|
||||
<span>
|
||||
Available for WebStorm, Intellij IDEA Ultimate and more!
|
||||
</span>
|
||||
</span>
|
||||
</a>
|
||||
<div id="nx-cloud" className="rounded shadow">
|
||||
<div>
|
||||
<svg
|
||||
id="nx-cloud-logo"
|
||||
role="img"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
stroke="currentColor"
|
||||
fill="transparent"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeWidth="2"
|
||||
d="M23 3.75V6.5c-3.036 0-5.5 2.464-5.5 5.5s-2.464 5.5-5.5 5.5-5.5 2.464-5.5 5.5H3.75C2.232 23 1 21.768 1 20.25V3.75C1 2.232 2.232 1 3.75 1h16.5C21.768 1 23 2.232 23 3.75Z"
|
||||
/>
|
||||
<path
|
||||
strokeWidth="2"
|
||||
d="M23 6v14.1667C23 21.7307 21.7307 23 20.1667 23H6c0-3.128 2.53867-5.6667 5.6667-5.6667 3.128 0 5.6666-2.5386 5.6666-5.6666C17.3333 8.53867 19.872 6 23 6Z"
|
||||
/>
|
||||
</svg>
|
||||
<h2>
|
||||
Nx Cloud
|
||||
<span>Enable faster CI & better DX</span>
|
||||
</h2>
|
||||
</div>
|
||||
<p>
|
||||
You can activate distributed tasks executions and caching by
|
||||
running:
|
||||
</p>
|
||||
<pre>nx connect</pre>
|
||||
<a
|
||||
href="https://nx.dev/nx-cloud?utm_source=nx-project"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{' '}
|
||||
What is Nx Cloud?{' '}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="commands" className="rounded shadow">
|
||||
<h2>Next steps</h2>
|
||||
<p>Here are some things you can do with Nx:</p>
|
||||
<details>
|
||||
<summary>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
Build, test and lint your app
|
||||
</summary>
|
||||
<pre>
|
||||
<span># Build</span>
|
||||
nx build {title}
|
||||
<span># Test</span>
|
||||
nx test {title}
|
||||
<span># Lint</span>
|
||||
nx lint {title}
|
||||
<span># Run them together!</span>
|
||||
nx run-many -p {title} -t build test lint
|
||||
|
||||
</pre>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
View project details
|
||||
</summary>
|
||||
<pre>nx show project {title}</pre>
|
||||
</details>
|
||||
<details>
|
||||
<summary>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
View interactive project graph
|
||||
</summary>
|
||||
<pre>nx graph</pre>
|
||||
</details>
|
||||
<details>
|
||||
<summary>
|
||||
<svg
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
Add UI library
|
||||
</summary>
|
||||
<pre>
|
||||
<span># Generate UI lib</span>
|
||||
nx g @nx/react:lib ui
|
||||
<span># Add a component</span>
|
||||
nx g @nx/react:component ui/src/lib/button
|
||||
</pre>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<p id="love">
|
||||
Carefully crafted with
|
||||
<svg
|
||||
fill="currentColor"
|
||||
stroke="none"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
|
||||
/>
|
||||
</svg>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default NxWelcome;
|
||||
@@ -1,16 +0,0 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import * as ReactDOM from 'react-dom/client';
|
||||
import App from './app/app';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App/>
|
||||
</BrowserRouter>
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -1 +0,0 @@
|
||||
/* You can add global styles to this file, and also import other style files */
|
||||
@@ -1,40 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"tsBuildInfoFile": "dist/tsconfig.app.tsbuildinfo",
|
||||
"jsx": "react-jsx",
|
||||
"lib": [
|
||||
"dom"
|
||||
],
|
||||
"types": [
|
||||
"node",
|
||||
"@nx/react/typings/cssmodule.d.ts",
|
||||
"@nx/react/typings/image.d.ts",
|
||||
"vite/client"
|
||||
],
|
||||
"rootDir": "src"
|
||||
},
|
||||
"exclude": [
|
||||
"out-tsc",
|
||||
"dist",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/**/*.test.jsx",
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts"
|
||||
],
|
||||
"include": [
|
||||
"src/**/*.js",
|
||||
"src/**/*.jsx",
|
||||
"src/**/*.ts",
|
||||
"src/**/*.tsx"
|
||||
]
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
],
|
||||
"extends": "../../tsconfig.base.json"
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/vitest",
|
||||
"types": [
|
||||
"vitest/globals",
|
||||
"vitest/importMeta",
|
||||
"vite/client",
|
||||
"node",
|
||||
"vitest",
|
||||
"@nx/react/typings/cssmodule.d.ts",
|
||||
"@nx/react/typings/image.d.ts"
|
||||
],
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
"vitest.config.ts",
|
||||
"vitest.config.mts",
|
||||
"src/**/*.test.ts",
|
||||
"src/**/*.spec.ts",
|
||||
"src/**/*.test.tsx",
|
||||
"src/**/*.spec.tsx",
|
||||
"src/**/*.test.js",
|
||||
"src/**/*.spec.js",
|
||||
"src/**/*.test.jsx",
|
||||
"src/**/*.spec.jsx",
|
||||
"src/**/*.d.ts"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/// <reference types='vitest' />
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig(() => ({
|
||||
root: __dirname,
|
||||
cacheDir: '../../node_modules/.vite/apps/my-app',
|
||||
server:{
|
||||
port: 4200,
|
||||
host: 'localhost',
|
||||
},
|
||||
preview:{
|
||||
port: 4300,
|
||||
host: 'localhost',
|
||||
},
|
||||
plugins: [react()],
|
||||
// Uncomment this if you are using workers.
|
||||
// worker: {
|
||||
// plugins: [ nxViteTsPaths() ],
|
||||
// },
|
||||
build: {
|
||||
outDir: './dist',
|
||||
emptyOutDir: true,
|
||||
reportCompressedSize: true,
|
||||
commonjsOptions: {
|
||||
transformMixedEsModules: true,
|
||||
},
|
||||
},
|
||||
test: {
|
||||
watch: false,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
reporters: ['default'],
|
||||
coverage: {
|
||||
reportsDirectory: './test-output/vitest/coverage',
|
||||
provider: 'v8' as const,
|
||||
}
|
||||
},
|
||||
}));
|
||||
@@ -2,6 +2,173 @@ import { ApiManager, ApiResponse } from "./ApiManager.js";
|
||||
import { Prompts } from "./models/Prompts.js";
|
||||
|
||||
export class PromptsApi extends ApiManager {
|
||||
|
||||
public async enqueueImageGeneration({
|
||||
disableSystemPrompt,
|
||||
prompt,
|
||||
snapshotMediaToken,
|
||||
additionalImages,
|
||||
}: {
|
||||
disableSystemPrompt: boolean;
|
||||
prompt: string;
|
||||
snapshotMediaToken: string;
|
||||
additionalImages?: string[];
|
||||
}): Promise<ApiResponse<string>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/image_studio/prompt`;
|
||||
|
||||
const uuidIdempotencyToken = crypto.randomUUID(); // Generate a new UUID
|
||||
const body = {
|
||||
uuid_idempotency_token: uuidIdempotencyToken,
|
||||
disable_system_prompt: disableSystemPrompt,
|
||||
prompt,
|
||||
snapshot_media_token: snapshotMediaToken, // Changed from scene_media_token to snapshot_media_token
|
||||
additional_images: additionalImages,
|
||||
};
|
||||
|
||||
const postResponse = await this.post<
|
||||
{
|
||||
uuid_idempotency_token: string;
|
||||
disable_system_prompt: boolean;
|
||||
prompt: string;
|
||||
snapshot_media_token: string;
|
||||
additional_images?: string[];
|
||||
},
|
||||
{ success?: boolean; job_token?: string; BadInput?: string }
|
||||
>({
|
||||
endpoint,
|
||||
body,
|
||||
});
|
||||
|
||||
// Check if the response is successful
|
||||
const isSuccess = postResponse.success ?? false;
|
||||
// Prepare the result object
|
||||
console.log("postResponse FOR ENQUEUE IMAGE GENERATION");
|
||||
console.log(postResponse);
|
||||
|
||||
const result = {
|
||||
success: isSuccess,
|
||||
data: isSuccess ? postResponse.inference_job_token : undefined,
|
||||
errorMessage: isSuccess ? undefined : postResponse.BadInput,
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async pollJobSession(
|
||||
jobToken: string,
|
||||
thumbnailWidth: number = 256,
|
||||
): Promise<
|
||||
ApiResponse<{
|
||||
job_token: string;
|
||||
request: {
|
||||
maybe_model_title: string;
|
||||
};
|
||||
status: {
|
||||
status: string;
|
||||
progress_percentage: number;
|
||||
};
|
||||
result: {
|
||||
image_url: string;
|
||||
thumbnail_url: string;
|
||||
public_bucket_path: string;
|
||||
generated_images?: string[];
|
||||
error?: string;
|
||||
};
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/jobs/job/${jobToken}`;
|
||||
|
||||
const response = await this.get<any>({
|
||||
endpoint,
|
||||
});
|
||||
console.log("Job Polling Response:");
|
||||
console.log(response);
|
||||
|
||||
const image_url = response.state.maybe_result?.media_links?.cdn_url;
|
||||
const public_bucket_path =
|
||||
response.state.maybe_result?.maybe_public_bucket_media_path;
|
||||
|
||||
const thumbnail_url =
|
||||
response.state.maybe_result?.media_links?.maybe_thumbnail_template?.replace(
|
||||
"{WIDTH}",
|
||||
thumbnailWidth.toString(),
|
||||
);
|
||||
|
||||
const progress_percentage = response.state.status.progress_percentage;
|
||||
const status_string = response.state.status.status;
|
||||
|
||||
console.log("Image URL:", image_url);
|
||||
console.log("Thumbnail URL:", thumbnail_url);
|
||||
console.log("Progress Percentage:", progress_percentage);
|
||||
console.log("Status", status_string);
|
||||
|
||||
console.log("response FROM JOBS");
|
||||
console.log(response);
|
||||
|
||||
const success = response.success ?? false;
|
||||
const status = response.status ?? "";
|
||||
const errorMessage = response.BadInput;
|
||||
|
||||
return {
|
||||
success,
|
||||
data: {
|
||||
result: {
|
||||
image_url: image_url || "",
|
||||
thumbnail_url: thumbnail_url || "",
|
||||
public_bucket_path: public_bucket_path || "",
|
||||
error: undefined,
|
||||
},
|
||||
job_token: jobToken,
|
||||
request: {
|
||||
maybe_model_title: "Image Generation",
|
||||
},
|
||||
status: {
|
||||
status: status_string.toLowerCase(),
|
||||
progress_percentage: progress_percentage,
|
||||
},
|
||||
},
|
||||
errorMessage,
|
||||
};
|
||||
}
|
||||
|
||||
public async pollStudioSessionJobs(jobToken: string): Promise<
|
||||
ApiResponse<{
|
||||
status: string;
|
||||
result: {
|
||||
generated_images?: string[];
|
||||
error?: string;
|
||||
};
|
||||
}>
|
||||
> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/image_studio/session_jobs/${jobToken}`;
|
||||
|
||||
const response = await this.get<{
|
||||
success?: boolean;
|
||||
status?: string;
|
||||
result?: {
|
||||
generated_images?: string[];
|
||||
error?: string;
|
||||
};
|
||||
BadInput?: string;
|
||||
}>({
|
||||
endpoint,
|
||||
});
|
||||
|
||||
const success = response.success ?? false;
|
||||
const status = response.status ?? "";
|
||||
const result = response.result ?? {
|
||||
generated_images: [],
|
||||
error: undefined,
|
||||
};
|
||||
const errorMessage = response.BadInput;
|
||||
|
||||
return {
|
||||
success,
|
||||
data: { status, result },
|
||||
errorMessage,
|
||||
};
|
||||
}
|
||||
|
||||
public GetPromptsByToken({
|
||||
token,
|
||||
}: {
|
||||
@@ -22,4 +189,53 @@ export class PromptsApi extends ApiManager {
|
||||
return { success: false, errorMessage: err.message };
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public async uploadSceneSnapshot({
|
||||
screenshot,
|
||||
sceneMediaToken,
|
||||
}: {
|
||||
screenshot: File; // base64 encoded PNG
|
||||
sceneMediaToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
const endpoint = `${this.ApiTargets.BaseApi}/v1/image_studio/scene_snapshot`;
|
||||
const formData = new FormData();
|
||||
formData.append("snapshot", screenshot); // Changed from "screenshot" to "snapshot" to match API spec
|
||||
if (sceneMediaToken) {
|
||||
formData.append("scene_media_token", sceneMediaToken);
|
||||
}
|
||||
|
||||
const uuidIdempotencyToken = crypto.randomUUID(); // Generate a new UUID
|
||||
formData.append("uuid_idempotency_token", uuidIdempotencyToken); // Added uuid_idempotency_token
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const postResponse = await response.json();
|
||||
console.log(postResponse);
|
||||
let result: { success: boolean; data?: string; errorMessage?: string };
|
||||
|
||||
if (postResponse.success) {
|
||||
result = {
|
||||
success: true,
|
||||
data: postResponse.snapshot_media_token,
|
||||
errorMessage: undefined,
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
success: false,
|
||||
errorMessage: "Failed to generate snapshot.",
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "../tauri-utils"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
},
|
||||
|
||||
@@ -15,7 +15,11 @@
|
||||
"types": ["node", "vite/client"]
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"references": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "../tauri-utils/tsconfig.lib.json"
|
||||
}
|
||||
],
|
||||
"exclude": [
|
||||
"vite.config.ts",
|
||||
"vite.config.mts",
|
||||
|
||||
@@ -8,7 +8,6 @@ import { CloseButton } from "@storyteller/ui-close-button";
|
||||
import { LoadingSpinner } from "@storyteller/ui-loading-spinner";
|
||||
import React, { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import {
|
||||
GetCdnOrigin,
|
||||
FilterMediaClasses,
|
||||
GalleryModalApi,
|
||||
UsersApi,
|
||||
@@ -63,8 +62,9 @@ export const GalleryModal = React.memo(
|
||||
const [isLightboxVisible, setIsLightboxVisible] = useState(false);
|
||||
const [failedImageUrls] = useState<Set<string>>(new Set());
|
||||
const [username, setUsername] = useState<string>("");
|
||||
const cdnOrigin = GetCdnOrigin();
|
||||
|
||||
const imageUrl = lightboxImage?.fullImage || "";
|
||||
|
||||
const api = useMemo(() => new GalleryModalApi(), []);
|
||||
const usersApi = useMemo(() => new UsersApi(), []);
|
||||
|
||||
@@ -107,16 +107,6 @@ export const GalleryModal = React.memo(
|
||||
[failedImageUrls]
|
||||
);
|
||||
|
||||
const getImageUrl = useCallback(
|
||||
(path: string | undefined | null) => {
|
||||
if (!path) return null;
|
||||
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
||||
const url = `${cdnOrigin}${normalizedPath}`;
|
||||
return failedImageUrls.has(url) ? null : url;
|
||||
},
|
||||
[cdnOrigin, failedImageUrls]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const getUsername = async () => {
|
||||
const session = await usersApi.GetSession();
|
||||
@@ -139,13 +129,20 @@ export const GalleryModal = React.memo(
|
||||
user_uploads_only: activeTab === "uploads",
|
||||
});
|
||||
if (response.success && response.data) {
|
||||
// Print the JSON response for debugging
|
||||
console.log("Media files response:", response.data);
|
||||
const thumbnail_size = 250;
|
||||
const newItems = response.data.map((item: any) => ({
|
||||
id: item.token,
|
||||
label: item.maybe_title || "Image Generation",
|
||||
thumbnail: getImageUrl(item.public_bucket_path),
|
||||
fullImage: getImageUrl(item.public_bucket_path),
|
||||
thumbnail: item.media_links.maybe_thumbnail_template?.replace(
|
||||
"{WIDTH}",
|
||||
thumbnail_size.toString()
|
||||
),
|
||||
fullImage: item.media_links.cdn_url,
|
||||
createdAt: item.created_at,
|
||||
}));
|
||||
console.log("Media files response:", newItems);
|
||||
setGroupedItems(groupItemsByDate(newItems));
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -270,7 +267,8 @@ export const GalleryModal = React.memo(
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={item.thumbnail}
|
||||
//src={item.thumbnail}
|
||||
src={item.fullImage || item.thumbnail}
|
||||
alt={item.label}
|
||||
className="h-full w-full object-cover"
|
||||
onError={() =>
|
||||
|
||||
@@ -14,13 +14,21 @@ import { fetch as tauriFetch } from '@tauri-apps/plugin-http'
|
||||
/// former, we replace Fetch with the Tauri fetch. If the latter, we dispatch
|
||||
/// to the normal browser fetch.
|
||||
|
||||
export function FetchProxy(args: any) : Promise<Response> {
|
||||
export function FetchProxy(args: any, additionalArgs: any) : Promise<Response> {
|
||||
if (IsDesktopApp()) {
|
||||
// Tauri proxy fetch
|
||||
return tauriFetch(args);
|
||||
if (additionalArgs !== undefined) {
|
||||
return tauriFetch(args, additionalArgs);
|
||||
} else {
|
||||
return tauriFetch(args);
|
||||
}
|
||||
} else {
|
||||
// Browser native fetch
|
||||
return fetch(args);
|
||||
if (additionalArgs !== undefined) {
|
||||
return fetch(args, additionalArgs);
|
||||
} else {
|
||||
return fetch(args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Generated
+2
-5
@@ -2173,7 +2173,8 @@
|
||||
},
|
||||
"apps/my-app": {
|
||||
"name": "@frontend/my-app",
|
||||
"version": "0.0.1"
|
||||
"version": "0.0.1",
|
||||
"extraneous": true
|
||||
},
|
||||
"libs/api": {
|
||||
"name": "@storyteller/api",
|
||||
@@ -4961,10 +4962,6 @@
|
||||
"resolved": "libs/login",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@frontend/my-app": {
|
||||
"resolved": "apps/my-app",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@headlessui/react": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@headlessui/react/-/react-2.2.2.tgz",
|
||||
|
||||
@@ -15,7 +15,8 @@ config_path="${rust_crate_path}/tauri.artcraft_3d.no_dev.conf.toml"
|
||||
export TAURI_FRONTEND_PATH="${frontend_path}"
|
||||
export TAURI_APP_PATH="${rust_crate_path}"
|
||||
|
||||
cargo tauri dev --no-dev-server \
|
||||
|
||||
RUSTFLAGS="-Awarnings" cargo tauri dev --no-dev-server \
|
||||
--no-dev-server-wait \
|
||||
--no-watch \
|
||||
--config "${config_path}"
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
# Kill any process running on port 5741, which will block startup
|
||||
if lsof -i tcp:5173 &>/dev/null; then
|
||||
lsof -i tcp:5173 -t | xargs kill -9
|
||||
echo "Killed process running on port 5173"
|
||||
else
|
||||
echo "No process running on port 5173"
|
||||
fi
|
||||
|
||||
root_dir=$(pwd)
|
||||
frontend_path="${root_dir}/frontend"
|
||||
rust_crate_path="${root_dir}/crates/desktop/tauri-artcraft"
|
||||
|
||||
# The tauri dev server integration is super annoying: It eats ctrl-c interrupts,
|
||||
# it decoheres the and corrupts terminal output, and it's slow. This configuration
|
||||
# allows us to start without it. Simply launch `nx` and the dev server as a separate
|
||||
# process and leave tauri out of the loop
|
||||
config_path="${rust_crate_path}/tauri.artcraft_3d.no_dev.conf.toml"
|
||||
|
||||
export TAURI_FRONTEND_PATH="${frontend_path}"
|
||||
export TAURI_APP_PATH="${rust_crate_path}"
|
||||
|
||||
# Launch nx dev editor3d in the background
|
||||
(cd "$frontend_path" && npx nx dev editor3d &)
|
||||
|
||||
RUSTFLAGS="-Awarnings" cargo tauri dev --no-dev-server \
|
||||
--no-dev-server-wait \
|
||||
--no-watch \
|
||||
--config "${config_path}"
|
||||
|
||||
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
|
||||
set -euxo pipefail
|
||||
# calls these
|
||||
./script/desktop/launch_rust_only_3d_for_michael.sh
|
||||
Reference in New Issue
Block a user