Переглянути джерело

refactor(core): remove `app` module (#6895)

Lucas Fernandes Nogueira 2 роки тому
батько
коміт
3245d14b9e

+ 6 - 0
.changes/move-app.md

@@ -0,0 +1,6 @@
+---
+"api": patch
+"tauri": patch
+---
+
+Moved the `app` feature to its own plugin in the plugins-workspace repository.

Різницю між файлами не показано, бо вона завелика
+ 0 - 0
core/tauri/scripts/bundle.global.js


+ 0 - 8
core/tauri/src/endpoints.rs

@@ -12,7 +12,6 @@ use serde_json::Value as JsonValue;
 
 use std::sync::Arc;
 
-mod app;
 mod event;
 #[cfg(os_any)]
 mod operating_system;
@@ -54,7 +53,6 @@ impl<T: Serialize> From<T> for InvokeResponse {
 #[derive(Deserialize)]
 #[serde(tag = "module", content = "message")]
 enum Module {
-  App(app::Cmd),
   #[cfg(process_any)]
   Process(process::Cmd),
   #[cfg(os_any)]
@@ -77,12 +75,6 @@ impl Module {
       package_info,
     };
     match self {
-      Self::App(cmd) => resolver.respond_async(async move {
-        cmd
-          .run(context)
-          .and_then(|r| r.json)
-          .map_err(InvokeError::from_anyhow)
-      }),
       #[cfg(process_any)]
       Self::Process(cmd) => resolver.respond_async(async move {
         cmd

+ 0 - 58
core/tauri/src/endpoints/app.rs

@@ -1,58 +0,0 @@
-// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-License-Identifier: MIT
-
-use super::InvokeContext;
-use crate::Runtime;
-use serde::Deserialize;
-use tauri_macros::{command_enum, module_command_handler, CommandModule};
-
-/// The API descriptor.
-#[command_enum]
-#[derive(Deserialize, CommandModule)]
-#[serde(tag = "cmd", rename_all = "camelCase")]
-#[allow(clippy::enum_variant_names)]
-pub enum Cmd {
-  /// Get Application Version
-  GetAppVersion,
-  /// Get Application Name
-  GetAppName,
-  /// Get Tauri Version
-  GetTauriVersion,
-  /// Shows the application on macOS.
-  #[cmd(app_show, "app > show")]
-  Show,
-  /// Hides the application on macOS.
-  #[cmd(app_hide, "app > hide")]
-  Hide,
-}
-
-impl Cmd {
-  fn get_app_version<R: Runtime>(context: InvokeContext<R>) -> super::Result<String> {
-    Ok(context.package_info.version.to_string())
-  }
-
-  fn get_app_name<R: Runtime>(context: InvokeContext<R>) -> super::Result<String> {
-    Ok(context.package_info.name)
-  }
-
-  fn get_tauri_version<R: Runtime>(_context: InvokeContext<R>) -> super::Result<&'static str> {
-    Ok(env!("CARGO_PKG_VERSION"))
-  }
-
-  #[module_command_handler(app_show)]
-  #[allow(unused_variables)]
-  fn show<R: Runtime>(context: InvokeContext<R>) -> super::Result<()> {
-    #[cfg(target_os = "macos")]
-    context.window.app_handle.show()?;
-    Ok(())
-  }
-
-  #[module_command_handler(app_hide)]
-  #[allow(unused_variables)]
-  fn hide<R: Runtime>(context: InvokeContext<R>) -> super::Result<()> {
-    #[cfg(target_os = "macos")]
-    context.window.app_handle.hide()?;
-    Ok(())
-  }
-}

+ 3 - 0
core/tauri/src/lib.rs

@@ -303,6 +303,9 @@ pub use {
   scope::*,
 };
 
+/// The Tauri version.
+pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+
 #[cfg(target_os = "ios")]
 #[doc(hidden)]
 pub fn log_stdout() {

+ 2 - 2
core/tauri/src/path/mod.rs

@@ -15,7 +15,7 @@ use crate::{
 use serde::{de::Error as DeError, Deserialize, Deserializer};
 use serde_repr::{Deserialize_repr, Serialize_repr};
 
-#[cfg(path_all)]
+#[cfg(any(path_all, test))]
 mod commands;
 mod error;
 pub use error::*;
@@ -340,7 +340,7 @@ pub(crate) fn init<R: Runtime>() -> TauriPlugin<R> {
   #[allow(unused_mut)]
   let mut builder = Builder::new("path");
 
-  #[cfg(path_all)]
+  #[cfg(any(path_all, test))]
   {
     builder = builder.invoke_handler(crate::generate_handler![
       commands::resolve_directory,

+ 37 - 43
core/tauri/src/scope/ipc.rs

@@ -170,6 +170,8 @@ impl Scope {
 
 #[cfg(test)]
 mod tests {
+  use serde::Serialize;
+
   use super::RemoteDomainAccessScope;
   use crate::{api::ipc::CallbackFn, test::MockRuntime, App, InvokePayload, Manager, Window};
 
@@ -186,10 +188,10 @@ mod tests {
     (app, window)
   }
 
-  fn assert_ipc_response(
+  fn assert_ipc_response<R: Serialize>(
     window: &Window<MockRuntime>,
     payload: InvokePayload,
-    expected: Result<&str, &str>,
+    expected: Result<R, &str>,
   ) {
     let callback = payload.callback;
     let error = payload.error;
@@ -208,8 +210,8 @@ mod tests {
       }
     };
     let (expected_response, fn_name) = match expected {
-      Ok(payload) => (payload, callback),
-      Err(payload) => (payload, error),
+      Ok(payload) => (serde_json::to_value(payload).unwrap(), callback),
+      Err(payload) => (serde_json::to_value(payload).unwrap(), error),
     };
     let expected = format!(
       "window[\"_{}\"]({})",
@@ -224,21 +226,19 @@ mod tests {
     assert!(evaluated_script.contains(&expected));
   }
 
-  fn app_version_payload() -> InvokePayload {
+  fn path_is_absolute_payload() -> InvokePayload {
     let callback = CallbackFn(0);
     let error = CallbackFn(1);
 
     let mut payload = serde_json::Map::new();
-    let mut msg = serde_json::Map::new();
-    msg.insert(
-      "cmd".into(),
-      serde_json::Value::String("getAppVersion".into()),
+    payload.insert(
+      "path".into(),
+      serde_json::Value::String(std::env::current_dir().unwrap().display().to_string()),
     );
-    payload.insert("message".into(), serde_json::Value::Object(msg));
 
     InvokePayload {
-      cmd: "".into(),
-      tauri_module: Some("App".into()),
+      cmd: "plugin:path|is_absolute".into(),
+      tauri_module: None,
       callback,
       error,
       inner: serde_json::Value::Object(payload),
@@ -262,12 +262,13 @@ mod tests {
   fn scope_not_defined() {
     let (_app, window) = test_context(vec![RemoteDomainAccessScope::new("app.tauri.app")
       .add_window("other")
+      .add_plugin("path")
       .enable_tauri_api()]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
-      app_version_payload(),
+      path_is_absolute_payload(),
       Err(&crate::window::ipc_scope_not_found_error_message(
         "main",
         "https://tauri.app/",
@@ -279,12 +280,13 @@ mod tests {
   fn scope_not_defined_for_window() {
     let (_app, window) = test_context(vec![RemoteDomainAccessScope::new("tauri.app")
       .add_window("second")
+      .add_plugin("path")
       .enable_tauri_api()]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
-      app_version_payload(),
+      path_is_absolute_payload(),
       Err(&crate::window::ipc_scope_window_error_message("main")),
     );
   }
@@ -293,12 +295,13 @@ mod tests {
   fn scope_not_defined_for_url() {
     let (_app, window) = test_context(vec![RemoteDomainAccessScope::new("github.com")
       .add_window("main")
+      .add_plugin("path")
       .enable_tauri_api()]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
-      app_version_payload(),
+      path_is_absolute_payload(),
       Err(&crate::window::ipc_scope_domain_error_message(
         "https://tauri.app/",
       )),
@@ -307,43 +310,37 @@ mod tests {
 
   #[test]
   fn subdomain_is_not_allowed() {
-    let (app, mut window) = test_context(vec![
+    let (_app, mut window) = test_context(vec![
       RemoteDomainAccessScope::new("tauri.app")
         .add_window("main")
+        .add_plugin("path")
         .enable_tauri_api(),
       RemoteDomainAccessScope::new("sub.tauri.app")
         .add_window("main")
+        .add_plugin("path")
         .enable_tauri_api(),
     ]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
-      &window,
-      app_version_payload(),
-      Ok(app.package_info().version.to_string().as_str()),
-    );
+    assert_ipc_response(&window, path_is_absolute_payload(), Ok(true));
 
     window.navigate("https://blog.tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
-      app_version_payload(),
+      path_is_absolute_payload(),
       Err(&crate::window::ipc_scope_domain_error_message(
         "https://blog.tauri.app/",
       )),
     );
 
     window.navigate("https://sub.tauri.app".parse().unwrap());
-    assert_ipc_response(
-      &window,
-      app_version_payload(),
-      Ok(app.package_info().version.to_string().as_str()),
-    );
+    assert_ipc_response(&window, path_is_absolute_payload(), Ok(true));
 
     window.window.label = "test".into();
     window.navigate("https://dev.tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
-      app_version_payload(),
+      path_is_absolute_payload(),
       Err(&crate::window::ipc_scope_not_found_error_message(
         "test",
         "https://dev.tauri.app/",
@@ -353,16 +350,13 @@ mod tests {
 
   #[test]
   fn subpath_is_allowed() {
-    let (app, window) = test_context(vec![RemoteDomainAccessScope::new("tauri.app")
+    let (_app, window) = test_context(vec![RemoteDomainAccessScope::new("tauri.app")
       .add_window("main")
+      .add_plugin("path")
       .enable_tauri_api()]);
 
     window.navigate("https://tauri.app/inner/path".parse().unwrap());
-    assert_ipc_response(
-      &window,
-      app_version_payload(),
-      Ok(app.package_info().version.to_string().as_str()),
-    );
+    assert_ipc_response(&window, path_is_absolute_payload(), Ok(true));
   }
 
   #[test]
@@ -372,9 +366,9 @@ mod tests {
     ]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
-      app_version_payload(),
+      path_is_absolute_payload(),
       Err(crate::window::IPC_SCOPE_DOES_NOT_ALLOW),
     );
   }
@@ -386,7 +380,7 @@ mod tests {
       .add_plugin(PLUGIN_NAME)]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
       plugin_test_payload(),
       Err(&format!("plugin {PLUGIN_NAME} not found")),
@@ -400,7 +394,7 @@ mod tests {
     ]);
 
     window.navigate("https://tauri.app".parse().unwrap());
-    assert_ipc_response(
+    assert_ipc_response::<()>(
       &window,
       plugin_test_payload(),
       Err(crate::window::IPC_SCOPE_DOES_NOT_ALLOW),

+ 0 - 33
examples/api/src/views/App.svelte

@@ -1,33 +0,0 @@
-<script>
-  import { show, hide } from '@tauri-apps/api/app'
-
-  export let onMessage
-
-  function showApp() {
-    hideApp()
-      .then(() => {
-        setTimeout(() => {
-          show()
-            .then(() => onMessage('Shown app'))
-            .catch(onMessage)
-        }, 2000)
-      })
-      .catch(onMessage)
-  }
-
-  function hideApp() {
-    return hide()
-      .then(() => onMessage('Hide app'))
-      .catch(onMessage)
-  }
-</script>
-
-<div>
-  <button
-    class="btn"
-    id="show"
-    title="Hides and shows the app after 2 seconds"
-    on:click={showApp}>Show</button
-  >
-  <button class="btn" id="hide" on:click={hideApp}>Hide</button>
-</div>

+ 0 - 6
examples/api/src/views/Welcome.svelte

@@ -1,5 +1,4 @@
 <script>
-  import { getName, getVersion, getTauriVersion } from '@tauri-apps/api/app'
   import { relaunch, exit } from '@tauri-apps/api/process'
 
   let version = '0.0.0'
@@ -35,11 +34,6 @@
 
 <br />
 <br />
-<pre>
-App name: <code>{appName}</code>
-App version: <code>{version}</code>
-Tauri version: <code>{tauriVersion}</code>
-</pre>
 <br />
 <div class="flex flex-wrap gap-1 shadow-">
   <button class="btn" on:click={closeApp}>Close application</button>

Різницю між файлами не показано, бо вона завелика
+ 0 - 0
tooling/api/docs/js-api.json


+ 0 - 129
tooling/api/src/app.ts

@@ -1,129 +0,0 @@
-// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-License-Identifier: MIT
-
-/**
- * Get application metadata.
- *
- * This package is also accessible with `window.__TAURI__.app` when [`build.withGlobalTauri`](https://tauri.app/v1/api/config/#buildconfig.withglobaltauri) in `tauri.conf.json` is set to `true`.
- *
- * The APIs must be added to [`tauri.allowlist.app`](https://tauri.app/v1/api/config/#allowlistconfig.app) in `tauri.conf.json`:
- * ```json
- * {
- *   "tauri": {
- *     "allowlist": {
- *       "app": {
- *         "all": true, // enable all app APIs
- *         "show": true,
- *         "hide": true
- *       }
- *     }
- *   }
- * }
- * ```
- * It is recommended to allowlist only the APIs you use for optimal bundle size and security.
- *
- * @module
- */
-
-import { invokeTauriCommand } from './helpers/tauri'
-
-/**
- * Gets the application version.
- * @example
- * ```typescript
- * import { getVersion } from '@tauri-apps/api/app';
- * const appVersion = await getVersion();
- * ```
- *
- * @since 1.0.0
- */
-async function getVersion(): Promise<string> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    message: {
-      cmd: 'getAppVersion'
-    }
-  })
-}
-
-/**
- * Gets the application name.
- * @example
- * ```typescript
- * import { getName } from '@tauri-apps/api/app';
- * const appName = await getName();
- * ```
- *
- * @since 1.0.0
- */
-async function getName(): Promise<string> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    message: {
-      cmd: 'getAppName'
-    }
-  })
-}
-
-/**
- * Gets the Tauri version.
- *
- * @example
- * ```typescript
- * import { getTauriVersion } from '@tauri-apps/api/app';
- * const tauriVersion = await getTauriVersion();
- * ```
- *
- * @since 1.0.0
- */
-async function getTauriVersion(): Promise<string> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    message: {
-      cmd: 'getTauriVersion'
-    }
-  })
-}
-
-/**
- * Shows the application on macOS. This function does not automatically focus any specific app window.
- *
- * @example
- * ```typescript
- * import { show } from '@tauri-apps/api/app';
- * await show();
- * ```
- *
- * @since 1.2.0
- */
-async function show(): Promise<void> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    message: {
-      cmd: 'show'
-    }
-  })
-}
-
-/**
- * Hides the application on macOS.
- *
- * @example
- * ```typescript
- * import { hide } from '@tauri-apps/api/app';
- * await hide();
- * ```
- *
- * @since 1.2.0
- */
-async function hide(): Promise<void> {
-  return invokeTauriCommand({
-    __tauriModule: 'App',
-    message: {
-      cmd: 'hide'
-    }
-  })
-}
-
-export { getName, getVersion, getTauriVersion, show, hide }

+ 1 - 2
tooling/api/src/index.ts

@@ -13,7 +13,6 @@
  * @module
  */
 
-import * as app from './app'
 import * as event from './event'
 import * as path from './path'
 import * as process from './process'
@@ -25,4 +24,4 @@ import * as os from './os'
 /** @ignore */
 const invoke = tauri.invoke
 
-export { invoke, app, event, path, process, tauri, updater, window, os }
+export { invoke, event, path, process, tauri, updater, window, os }

Деякі файли не було показано, через те що забагато файлів було змінено