diff --git a/plugins/app/src/api-iife.js b/plugins/app/src/api-iife.js new file mode 100644 index 00000000..6ec8c2d7 --- /dev/null +++ b/plugins/app/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_APP__=function(e){"use strict";var n=Object.defineProperty,t=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},r=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),i=(e,n,r,i)=>(t(e,n,"write to private field"),i?i.call(e,r):n.set(e,r),r);function a(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${t}`;return Object.defineProperty(window,r,{value:t=>(n&&Reflect.deleteProperty(window,r),e?.(t)),writable:!1,configurable:!0}),t}((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})({},{Channel:()=>s,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>_,invoke:()=>u,transformCallback:()=>a});var o,s=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,o,(()=>{})),this.id=a((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,n,t){let r=new s;return r.onmessage=t,u(`plugin:${e}|register_listener`,{event:n,handler:r}).then((()=>new l(e,n,r.id)))}async function u(e,n={}){return new Promise(((t,r)=>{let i=a((e=>{t(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...n})}))}function _(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}return e.getName=async function(){return u("plugin:app|name")},e.getTauriVersion=async function(){return u("plugin:app|tauri_version")},e.getVersion=async function(){return u("plugin:app|version")},e.hide=async function(){return u("plugin:app|hide")},e.show=async function(){return u("plugin:app|show")},e}({});Object.defineProperty(window.__TAURI__,"app",{value:__TAURI_APP__})} diff --git a/plugins/app/src/lib.rs b/plugins/app/src/lib.rs index 790ed9d2..a8783728 100644 --- a/plugins/app/src/lib.rs +++ b/plugins/app/src/lib.rs @@ -7,6 +7,7 @@ mod commands; pub fn init() -> TauriPlugin { Builder::new("app") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ commands::version, commands::name, diff --git a/plugins/authenticator/src/api-iife.js b/plugins/authenticator/src/api-iife.js new file mode 100644 index 00000000..7dbd08cc --- /dev/null +++ b/plugins/authenticator/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_AUTHENTICATOR__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},i=(e,t,i)=>(n(e,t,"read from private field"),i?i.call(e):t.get(e)),r=(e,t,i,r)=>(n(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i);function a(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],i=`_${n}`;return Object.defineProperty(window,i,{value:n=>(t&&Reflect.deleteProperty(window,i),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var i in n)t(e,i,{get:n[i],enumerable:!0})})({},{Channel:()=>l,PluginListener:()=>s,addPluginListener:()=>c,convertFileSrc:()=>h,invoke:()=>u,transformCallback:()=>a});var o,l=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=a((e=>{i(this,o).call(this,e)}))}set onmessage(e){r(this,o,e)}get onmessage(){return i(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var s=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let i=new l;return i.onmessage=n,u(`plugin:${e}|register_listener`,{event:t,handler:i}).then((()=>new s(e,t,i.id)))}async function u(e,t={}){return new Promise(((n,i)=>{let r=a((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{i(e),Reflect.deleteProperty(window,`_${r}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:r,error:o,...t})}))}function h(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.Authenticator=class{async init(){return await u("plugin:authenticator|init_auth")}async register(e,t){return await u("plugin:authenticator|register",{timeout:1e4,challenge:e,application:t})}async verifyRegistration(e,t,n,i){return await u("plugin:authenticator|verify_registration",{challenge:e,application:t,registerData:n,clientData:i})}async sign(e,t,n){return await u("plugin:authenticator|sign",{timeout:1e4,challenge:e,application:t,keyHandle:n})}async verifySignature(e,t,n,i,r,a){return await u("plugin:authenticator|verify_signature",{challenge:e,application:t,signData:n,clientData:i,keyHandle:r,pubkey:a})}},e}({});Object.defineProperty(window.__TAURI__,"authenticator",{value:__TAURI_AUTHENTICATOR__})} diff --git a/plugins/authenticator/src/lib.rs b/plugins/authenticator/src/lib.rs index e1b488e0..55c6ac9d 100644 --- a/plugins/authenticator/src/lib.rs +++ b/plugins/authenticator/src/lib.rs @@ -67,6 +67,7 @@ fn verify_signature( pub fn init() -> TauriPlugin { PluginBuilder::new("authenticator") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ init_auth, register, diff --git a/plugins/autostart/src/api-iife.js b/plugins/autostart/src/api-iife.js new file mode 100644 index 00000000..d9e37f09 --- /dev/null +++ b/plugins/autostart/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_AUTOSTART__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),i=(e,t,r,i)=>(n(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);function a(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>o,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>d,invoke:()=>u,transformCallback:()=>a});var s,o=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,s,(()=>{})),this.id=a((e=>{r(this,s).call(this,e)}))}set onmessage(e){i(this,s,e)}get onmessage(){return r(this,s)}toJSON(){return`__CHANNEL__:${this.id}`}};s=new WeakMap;var l=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new o;return r.onmessage=n,u(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new l(e,t,r.id)))}async function u(e,t={}){return new Promise(((n,r)=>{let i=a((e=>{n(e),Reflect.deleteProperty(window,`_${s}`)}),!0),s=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:s,...t})}))}function d(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.disable=async function(){await u("plugin:autostart|disable")},e.enable=async function(){await u("plugin:autostart|enable")},e.isEnabled=async function(){return await u("plugin:autostart|is_enabled")},e}({});Object.defineProperty(window.__TAURI__,"autostart",{value:__TAURI_AUTOSTART__})} diff --git a/plugins/autostart/src/lib.rs b/plugins/autostart/src/lib.rs index cfdd5ccc..6134db32 100644 --- a/plugins/autostart/src/lib.rs +++ b/plugins/autostart/src/lib.rs @@ -99,6 +99,7 @@ pub fn init( args: Option>, ) -> TauriPlugin { Builder::new("autostart") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![enable, disable, is_enabled]) .setup(move |app, _api| { let mut builder = AutoLaunchBuilder::new(); diff --git a/plugins/cli/src/api-iife.js b/plugins/cli/src/api-iife.js new file mode 100644 index 00000000..caa2eff6 --- /dev/null +++ b/plugins/cli/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_CLI__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),i=(e,t,r,i)=>(n(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);function a(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>s,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>d,invoke:()=>_,transformCallback:()=>a});var o,s=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=a((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return _(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new s;return r.onmessage=n,_(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new l(e,t,r.id)))}async function _(e,t={}){return new Promise(((n,r)=>{let i=a((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...t})}))}function d(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.getMatches=async function(){return await _("plugin:cli|cli_matches")},e}({});Object.defineProperty(window.__TAURI__,"cli",{value:__TAURI_CLI__})} diff --git a/plugins/cli/src/lib.rs b/plugins/cli/src/lib.rs index 25795c01..ed5713d5 100644 --- a/plugins/cli/src/lib.rs +++ b/plugins/cli/src/lib.rs @@ -36,6 +36,7 @@ fn cli_matches(_app: AppHandle, cli: State<'_, Cli>) -> Result pub fn init() -> TauriPlugin { Builder::new("cli") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![cli_matches]) .setup(|app, api| { app.manage(Cli(api)); diff --git a/plugins/clipboard/src/api-iife.js b/plugins/clipboard/src/api-iife.js new file mode 100644 index 00000000..ab0565fb --- /dev/null +++ b/plugins/clipboard/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_CLIPBOARD__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),i=(e,t,r,i)=>(n(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);function a(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>l,PluginListener:()=>s,addPluginListener:()=>c,convertFileSrc:()=>_,invoke:()=>d,transformCallback:()=>a});var o,l=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=a((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var s=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new l;return r.onmessage=n,d(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new s(e,t,r.id)))}async function d(e,t={}){return new Promise(((n,r)=>{let i=a((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...t})}))}function _(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.readText=async function(){return(await d("plugin:clipboard|read")).options},e.writeText=async function(e,t){return d("plugin:clipboard|write",{data:{kind:"PlainText",options:{label:null==t?void 0:t.label,text:e}}})},e}({});Object.defineProperty(window.__TAURI__,"clipboard",{value:__TAURI_CLIPBOARD__})} diff --git a/plugins/clipboard/src/lib.rs b/plugins/clipboard/src/lib.rs index a655d93e..7fc05348 100644 --- a/plugins/clipboard/src/lib.rs +++ b/plugins/clipboard/src/lib.rs @@ -39,6 +39,7 @@ impl> crate::ClipboardExt for T { /// Initializes the plugin. pub fn init() -> TauriPlugin { Builder::new("clipboard") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![commands::write, commands::read]) .setup(|app, api| { #[cfg(mobile)] diff --git a/plugins/dialog/src/api-iife.js b/plugins/dialog/src/api-iife.js new file mode 100644 index 00000000..55c25540 --- /dev/null +++ b/plugins/dialog/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_DIALOG__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},i=(e,t,i)=>(n(e,t,"read from private field"),i?i.call(e):t.get(e)),o=(e,t,i,o)=>(n(e,t,"write to private field"),o?o.call(e,i):t.set(e,i),i);function l(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],i=`_${n}`;return Object.defineProperty(window,i,{value:n=>(t&&Reflect.deleteProperty(window,i),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var i in n)t(e,i,{get:n[i],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>s,addPluginListener:()=>u,convertFileSrc:()=>c,invoke:()=>d,transformCallback:()=>l});var r,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,r,(()=>{})),this.id=l((e=>{i(this,r).call(this,e)}))}set onmessage(e){o(this,r,e)}get onmessage(){return i(this,r)}toJSON(){return`__CHANNEL__:${this.id}`}};r=new WeakMap;var s=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function u(e,t,n){let i=new a;return i.onmessage=n,d(`plugin:${e}|register_listener`,{event:t,handler:i}).then((()=>new s(e,t,i.id)))}async function d(e,t={}){return new Promise(((n,i)=>{let o=l((e=>{n(e),Reflect.deleteProperty(window,`_${r}`)}),!0),r=l((e=>{i(e),Reflect.deleteProperty(window,`_${o}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:o,error:r,...t})}))}function c(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.ask=async function(e,t){var n,i,o,l,r;const a="string"==typeof t?{title:t}:t;return d("plugin:dialog|ask",{message:e.toString(),title:null===(n=null==a?void 0:a.title)||void 0===n?void 0:n.toString(),type_:null==a?void 0:a.type,okButtonLabel:null!==(o=null===(i=null==a?void 0:a.okLabel)||void 0===i?void 0:i.toString())&&void 0!==o?o:"Yes",cancelButtonLabel:null!==(r=null===(l=null==a?void 0:a.cancelLabel)||void 0===l?void 0:l.toString())&&void 0!==r?r:"No"})},e.confirm=async function(e,t){var n,i,o,l,r;const a="string"==typeof t?{title:t}:t;return d("plugin:dialog|confirm",{message:e.toString(),title:null===(n=null==a?void 0:a.title)||void 0===n?void 0:n.toString(),type_:null==a?void 0:a.type,okButtonLabel:null!==(o=null===(i=null==a?void 0:a.okLabel)||void 0===i?void 0:i.toString())&&void 0!==o?o:"Ok",cancelButtonLabel:null!==(r=null===(l=null==a?void 0:a.cancelLabel)||void 0===l?void 0:l.toString())&&void 0!==r?r:"Cancel"})},e.message=async function(e,t){var n,i;const o="string"==typeof t?{title:t}:t;return d("plugin:dialog|message",{message:e.toString(),title:null===(n=null==o?void 0:o.title)||void 0===n?void 0:n.toString(),type_:null==o?void 0:o.type,okButtonLabel:null===(i=null==o?void 0:o.okLabel)||void 0===i?void 0:i.toString()})},e.open=async function(e={}){return"object"==typeof e&&Object.freeze(e),d("plugin:dialog|open",{options:e})},e.save=async function(e={}){return"object"==typeof e&&Object.freeze(e),d("plugin:dialog|save",{options:e})},e}({});Object.defineProperty(window.__TAURI__,"dialog",{value:__TAURI_DIALOG__})} diff --git a/plugins/dialog/src/lib.rs b/plugins/dialog/src/lib.rs index 2c07b591..8353b71c 100644 --- a/plugins/dialog/src/lib.rs +++ b/plugins/dialog/src/lib.rs @@ -75,7 +75,13 @@ pub fn init() -> TauriPlugin { // Dialogs are implemented natively on Android #[cfg(not(target_os = "android"))] { - builder = builder.js_init_script(include_str!("init.js").to_string()); + let mut init_script = include_str!("init.js").to_string(); + init_script.push_str(include_str!("api-iife.js")); + builder = builder.js_init_script(init_script); + } + #[cfg(target_os = "android")] + { + builder = builder.js_init_script(include_str!("api-iife.js").to_string()); } builder diff --git a/plugins/fs/src/api-iife.js b/plugins/fs/src/api-iife.js new file mode 100644 index 00000000..4d076522 --- /dev/null +++ b/plugins/fs/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_FS__=function(e){"use strict";var t=Object.defineProperty,n=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},r=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},i=(e,t,n)=>(r(e,t,"read from private field"),n?n.call(e):t.get(e));function o(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}n({},{Channel:()=>c,PluginListener:()=>s,addPluginListener:()=>u,convertFileSrc:()=>l,invoke:()=>p,transformCallback:()=>o});var a,c=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,a,(()=>{})),this.id=o((e=>{i(this,a).call(this,e)}))}set onmessage(e){((e,t,n,i)=>{r(e,t,"write to private field"),i?i.call(e,n):t.set(e,n)})(this,a,e)}get onmessage(){return i(this,a)}toJSON(){return`__CHANNEL__:${this.id}`}};a=new WeakMap;var s=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return p(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function u(e,t,n){let r=new c;return r.onmessage=n,p(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new s(e,t,r.id)))}async function p(e,t={}){return new Promise(((n,r)=>{let i=o((e=>{n(e),Reflect.deleteProperty(window,`_${a}`)}),!0),a=o((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:a,...t})}))}function l(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}function d(){return navigator.appVersion.includes("Win")}n({},{BaseDirectory:()=>f,appCacheDir:()=>v,appConfigDir:()=>h,appDataDir:()=>g,appLocalDataDir:()=>_,appLogDir:()=>O,audioDir:()=>w,basename:()=>W,cacheDir:()=>m,configDir:()=>D,dataDir:()=>A,delimiter:()=>B,desktopDir:()=>b,dirname:()=>H,documentDir:()=>C,downloadDir:()=>R,executableDir:()=>P,extname:()=>V,fontDir:()=>T,homeDir:()=>j,isAbsolute:()=>J,join:()=>S,localDataDir:()=>F,normalize:()=>N,pictureDir:()=>x,publicDir:()=>L,resolve:()=>M,resolveResource:()=>U,resourceDir:()=>I,runtimeDir:()=>$,sep:()=>z,templateDir:()=>k,videoDir:()=>E});var y,f=((y=f||{})[y.Audio=1]="Audio",y[y.Cache=2]="Cache",y[y.Config=3]="Config",y[y.Data=4]="Data",y[y.LocalData=5]="LocalData",y[y.Document=6]="Document",y[y.Download=7]="Download",y[y.Picture=8]="Picture",y[y.Public=9]="Public",y[y.Video=10]="Video",y[y.Resource=11]="Resource",y[y.Temp=12]="Temp",y[y.AppConfig=13]="AppConfig",y[y.AppData=14]="AppData",y[y.AppLocalData=15]="AppLocalData",y[y.AppCache=16]="AppCache",y[y.AppLog=17]="AppLog",y[y.Desktop=18]="Desktop",y[y.Executable=19]="Executable",y[y.Font=20]="Font",y[y.Home=21]="Home",y[y.Runtime=22]="Runtime",y[y.Template=23]="Template",y);async function h(){return p("plugin:path|resolve_directory",{directory:13})}async function g(){return p("plugin:path|resolve_directory",{directory:14})}async function _(){return p("plugin:path|resolve_directory",{directory:15})}async function v(){return p("plugin:path|resolve_directory",{directory:16})}async function w(){return p("plugin:path|resolve_directory",{directory:1})}async function m(){return p("plugin:path|resolve_directory",{directory:2})}async function D(){return p("plugin:path|resolve_directory",{directory:3})}async function A(){return p("plugin:path|resolve_directory",{directory:4})}async function b(){return p("plugin:path|resolve_directory",{directory:18})}async function C(){return p("plugin:path|resolve_directory",{directory:6})}async function R(){return p("plugin:path|resolve_directory",{directory:7})}async function P(){return p("plugin:path|resolve_directory",{directory:19})}async function T(){return p("plugin:path|resolve_directory",{directory:20})}async function j(){return p("plugin:path|resolve_directory",{directory:21})}async function F(){return p("plugin:path|resolve_directory",{directory:5})}async function x(){return p("plugin:path|resolve_directory",{directory:8})}async function L(){return p("plugin:path|resolve_directory",{directory:9})}async function I(){return p("plugin:path|resolve_directory",{directory:11})}async function U(e){return p("plugin:path|resolve_directory",{directory:11,path:e})}async function $(){return p("plugin:path|resolve_directory",{directory:22})}async function k(){return p("plugin:path|resolve_directory",{directory:23})}async function E(){return p("plugin:path|resolve_directory",{directory:10})}async function O(){return p("plugin:path|resolve_directory",{directory:17})}var z=d()?"\\":"/",B=d()?";":":";async function M(...e){return p("plugin:path|resolve",{paths:e})}async function N(e){return p("plugin:path|normalize",{path:e})}async function S(...e){return p("plugin:path|join",{paths:e})}async function H(e){return p("plugin:path|dirname",{path:e})}async function V(e){return p("plugin:path|extname",{path:e})}async function W(e,t){return p("plugin:path|basename",{path:e,ext:t})}async function J(e){return p("plugin:path|isAbsolute",{path:e})}async function K(e,t,n){"object"==typeof n&&Object.freeze(n),"object"==typeof e&&Object.freeze(e);const r={path:"",contents:""};let i=n;return"string"==typeof e?r.path=e:(r.path=e.path,r.contents=e.contents),"string"==typeof t?r.contents=null!=t?t:"":i=t,await p("plugin:fs|write_file",{path:r.path,contents:Array.from((new TextEncoder).encode(r.contents)),options:i})}return e.BaseDirectory=f,e.Dir=f,e.copyFile=async function(e,t,n={}){return await p("plugin:fs|copy_file",{source:e,destination:t,options:n})},e.createDir=async function(e,t={}){return await p("plugin:fs|create_dir",{path:e,options:t})},e.exists=async function(e){return await p("plugin:fs|exists",{path:e})},e.metadata=async function(e){return await p("plugin:fs|metadata",{path:e}).then((e=>{const{accessedAtMs:t,createdAtMs:n,modifiedAtMs:r,...i}=e;return{accessedAt:new Date(t),createdAt:new Date(n),modifiedAt:new Date(r),...i}}))},e.readBinaryFile=async function(e,t={}){const n=await p("plugin:fs|read_file",{path:e,options:t});return Uint8Array.from(n)},e.readDir=async function(e,t={}){return await p("plugin:fs|read_dir",{path:e,options:t})},e.readTextFile=async function(e,t={}){return await p("plugin:fs|read_text_file",{path:e,options:t})},e.removeDir=async function(e,t={}){return await p("plugin:fs|remove_dir",{path:e,options:t})},e.removeFile=async function(e,t={}){return await p("plugin:fs|remove_file",{path:e,options:t})},e.renameFile=async function(e,t,n={}){return await p("plugin:fs|rename_file",{oldPath:e,newPath:t,options:n})},e.writeBinaryFile=async function(e,t,n){"object"==typeof n&&Object.freeze(n),"object"==typeof e&&Object.freeze(e);const r={path:"",contents:[]};let i=n;return"string"==typeof e?r.path=e:(r.path=e.path,r.contents=e.contents),t&&"dir"in t?i=t:"string"==typeof e&&(r.contents=null!=t?t:[]),await p("plugin:fs|write_binary_file",{path:r.path,contents:Array.from(r.contents instanceof ArrayBuffer?new Uint8Array(r.contents):r.contents),options:i})},e.writeFile=K,e.writeTextFile=K,e}({});Object.defineProperty(window.__TAURI__,"fs",{value:__TAURI_FS__})} diff --git a/plugins/fs/src/lib.rs b/plugins/fs/src/lib.rs index 023d04e6..9156661f 100644 --- a/plugins/fs/src/lib.rs +++ b/plugins/fs/src/lib.rs @@ -38,6 +38,7 @@ impl> FsExt for T { pub fn init() -> TauriPlugin> { PluginBuilder::>::new("fs") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ commands::read_file, commands::read_text_file, diff --git a/plugins/global-shortcut/src/api-iife.js b/plugins/global-shortcut/src/api-iife.js new file mode 100644 index 00000000..773ddb20 --- /dev/null +++ b/plugins/global-shortcut/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_GLOBALSHORTCUT__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),i=(e,t,r,i)=>(n(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);function a(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>s,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>h,invoke:()=>u,transformCallback:()=>a});var o,s=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=a((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new s;return r.onmessage=n,u(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new l(e,t,r.id)))}async function u(e,t={}){return new Promise(((n,r)=>{let i=a((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...t})}))}function h(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.isRegistered=async function(e){return await u("plugin:globalShortcut|is_registered",{shortcut:e})},e.register=async function(e,t){return await u("plugin:globalShortcut|register",{shortcut:e,handler:a(t)})},e.registerAll=async function(e,t){return await u("plugin:globalShortcut|register_all",{shortcuts:e,handler:a(t)})},e.unregister=async function(e){return await u("plugin:globalShortcut|unregister",{shortcut:e})},e.unregisterAll=async function(){return await u("plugin:globalShortcut|unregister_all")},e}({});Object.defineProperty(window.__TAURI__,"globalShortcut",{value:__TAURI_GLOBALSHORTCUT__})} diff --git a/plugins/global-shortcut/src/lib.rs b/plugins/global-shortcut/src/lib.rs index 4266de21..6e8dd668 100644 --- a/plugins/global-shortcut/src/lib.rs +++ b/plugins/global-shortcut/src/lib.rs @@ -279,6 +279,7 @@ impl Builder { pub fn build(self) -> TauriPlugin { let handler = self.handler; PluginBuilder::new("globalShortcut") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ register, register_all, diff --git a/plugins/http/src/api-iife.js b/plugins/http/src/api-iife.js new file mode 100644 index 00000000..31c7ad9e --- /dev/null +++ b/plugins/http/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_HTTP__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),s=(e,t,r,s)=>(n(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);function i(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>c,addPluginListener:()=>u,convertFileSrc:()=>h,invoke:()=>d,transformCallback:()=>i});var o,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=i((e=>{r(this,o).call(this,e)}))}set onmessage(e){s(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l,c=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function u(e,t,n){let r=new a;return r.onmessage=n,d(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new c(e,t,r.id)))}async function d(e,t={}){return new Promise(((n,r)=>{let s=i((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=i((e=>{r(e),Reflect.deleteProperty(window,`_${s}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:s,error:o,...t})}))}function h(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}e.ResponseType=void 0,(l=e.ResponseType||(e.ResponseType={}))[l.JSON=1]="JSON",l[l.Text=2]="Text",l[l.Binary=3]="Binary";class p{constructor(e,t){this.type=e,this.payload=t}static form(e){const t={},n=(e,n)=>{if(null!==n){let r;r="string"==typeof n?n:n instanceof Uint8Array||Array.isArray(n)?Array.from(n):n instanceof File?{file:n.name,mime:n.type,fileName:n.name}:"string"==typeof n.file?{file:n.file,mime:n.mime,fileName:n.fileName}:{file:Array.from(n.file),mime:n.mime,fileName:n.fileName},t[String(e)]=r}};if(e instanceof FormData)for(const[t,r]of e)n(t,r);else for(const[t,r]of Object.entries(e))n(t,r);return new p("Form",t)}static json(e){return new p("Json",e)}static text(e){return new p("Text",e)}static bytes(e){return new p("Bytes",Array.from(e instanceof ArrayBuffer?new Uint8Array(e):e))}}class f{constructor(e){this.url=e.url,this.status=e.status,this.ok=this.status>=200&&this.status<300,this.headers=e.headers,this.rawHeaders=e.rawHeaders,this.data=e.data}}class y{constructor(e){this.id=e}async drop(){return d("plugin:http|drop_client",{client:this.id})}async request(t){const n=!t.responseType||t.responseType===e.ResponseType.JSON;return n&&(t.responseType=e.ResponseType.Text),d("plugin:http|request",{clientId:this.id,options:t}).then((e=>{const t=new f(e);if(n){try{t.data=JSON.parse(t.data)}catch(e){if(t.ok&&""===t.data)t.data={};else if(t.ok)throw Error(`Failed to parse response \`${t.data}\` as JSON: ${e};\n try setting the \`responseType\` option to \`ResponseType.Text\` or \`ResponseType.Binary\` if the API does not return a JSON response.`)}return t}return t}))}async get(e,t){return this.request({method:"GET",url:e,...t})}async post(e,t,n){return this.request({method:"POST",url:e,body:t,...n})}async put(e,t,n){return this.request({method:"PUT",url:e,body:t,...n})}async patch(e,t){return this.request({method:"PATCH",url:e,...t})}async delete(e,t){return this.request({method:"DELETE",url:e,...t})}}async function m(e){return d("plugin:http|create_client",{options:e}).then((e=>new y(e)))}let _=null;return e.Body=p,e.Client=y,e.Response=f,e.fetch=async function(e,t){var n;return null===_&&(_=await m()),_.request({url:e,method:null!==(n=null==t?void 0:t.method)&&void 0!==n?n:"GET",...t})},e.getClient=m,e}({});Object.defineProperty(window.__TAURI__,"http",{value:__TAURI_HTTP__})} diff --git a/plugins/http/src/lib.rs b/plugins/http/src/lib.rs index 348d26a2..641056b4 100644 --- a/plugins/http/src/lib.rs +++ b/plugins/http/src/lib.rs @@ -37,6 +37,7 @@ impl> HttpExt for T { pub fn init() -> TauriPlugin> { Builder::>::new("http") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ commands::create_client, commands::drop_client, diff --git a/plugins/log/src/api-iife.js b/plugins/log/src/api-iife.js new file mode 100644 index 00000000..42589bb5 --- /dev/null +++ b/plugins/log/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_LOG__=function(e){"use strict";var n=Object.defineProperty,t=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},r=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},a=(e,n,t)=>(r(e,n,"read from private field"),t?t.call(e):n.get(e)),i=(e,n,t,a)=>(r(e,n,"write to private field"),a?a.call(e,t):n.set(e,t),t);function o(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${t}`;return Object.defineProperty(window,r,{value:t=>(n&&Reflect.deleteProperty(window,r),e?.(t)),writable:!1,configurable:!0}),t}t({},{Channel:()=>c,PluginListener:()=>s,addPluginListener:()=>u,convertFileSrc:()=>_,invoke:()=>d,transformCallback:()=>o});var l,c=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,l,(()=>{})),this.id=o((e=>{a(this,l).call(this,e)}))}set onmessage(e){i(this,l,e)}get onmessage(){return a(this,l)}toJSON(){return`__CHANNEL__:${this.id}`}};l=new WeakMap;var s=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function u(e,n,t){let r=new c;return r.onmessage=t,d(`plugin:${e}|register_listener`,{event:n,handler:r}).then((()=>new s(e,n,r.id)))}async function d(e,n={}){return new Promise(((t,r)=>{let a=o((e=>{t(e),Reflect.deleteProperty(window,`_${i}`)}),!0),i=o((e=>{r(e),Reflect.deleteProperty(window,`_${a}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:a,error:i,...n})}))}function _(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}async function f(e,n){await d("plugin:event|unlisten",{event:e,eventId:n})}async function w(e,n,t){return d("plugin:event|listen",{event:e,windowLabel:n,handler:o(t)}).then((n=>async()=>f(e,n)))}t({},{TauriEvent:()=>h,emit:()=>p,listen:()=>E,once:()=>y});var v,g,h=((v=h||{}).WINDOW_RESIZED="tauri://resize",v.WINDOW_MOVED="tauri://move",v.WINDOW_CLOSE_REQUESTED="tauri://close-requested",v.WINDOW_CREATED="tauri://window-created",v.WINDOW_DESTROYED="tauri://destroyed",v.WINDOW_FOCUS="tauri://focus",v.WINDOW_BLUR="tauri://blur",v.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",v.WINDOW_THEME_CHANGED="tauri://theme-changed",v.WINDOW_FILE_DROP="tauri://file-drop",v.WINDOW_FILE_DROP_HOVER="tauri://file-drop-hover",v.WINDOW_FILE_DROP_CANCELLED="tauri://file-drop-cancelled",v.MENU="tauri://menu",v);async function E(e,n){return w(e,null,n)}async function y(e,n){return async function(e,n,t){return w(e,n,(n=>{t(n),f(e,n.id).catch((()=>{}))}))}(e,null,n)}async function p(e,n){return async function(e,n,t){await d("plugin:event|emit",{event:e,windowLabel:n,payload:t})}(e,void 0,n)}async function I(e,n,t){var r,a;const i=null===(r=(new Error).stack)||void 0===r?void 0:r.split("\n").map((e=>e.split("@"))),o=null==i?void 0:i.filter((([e,n])=>e.length>0&&"[native code]"!==n)),{file:l,line:c,...s}=null!=t?t:{};let u=null===(a=null==o?void 0:o[0])||void 0===a?void 0:a.filter((e=>e.length>0)).join("@");"Error"===u&&(u="webview::unknown"),await d("plugin:log|log",{level:e,message:n,location:u,file:l,line:c,keyValues:s})}return function(e){e[e.Trace=1]="Trace",e[e.Debug=2]="Debug",e[e.Info=3]="Info",e[e.Warn=4]="Warn",e[e.Error=5]="Error"}(g||(g={})),e.attachConsole=async function(){return await E("log://log",(e=>{const n=e.payload,t=n.message.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"");switch(n.level){case g.Trace:console.log(t);break;case g.Debug:console.debug(t);break;case g.Info:console.info(t);break;case g.Warn:console.warn(t);break;case g.Error:console.error(t);break;default:throw new Error(`unknown log level ${n.level}`)}}))},e.debug=async function(e,n){await I(g.Debug,e,n)},e.error=async function(e,n){await I(g.Error,e,n)},e.info=async function(e,n){await I(g.Info,e,n)},e.trace=async function(e,n){await I(g.Trace,e,n)},e.warn=async function(e,n){await I(g.Warn,e,n)},e}({});Object.defineProperty(window.__TAURI__,"log",{value:__TAURI_LOG__})} diff --git a/plugins/log/src/lib.rs b/plugins/log/src/lib.rs index cbb6dd29..3ad07f6f 100644 --- a/plugins/log/src/lib.rs +++ b/plugins/log/src/lib.rs @@ -320,6 +320,7 @@ impl Builder { pub fn build(mut self) -> TauriPlugin { plugin::Builder::new("log") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![log]) .setup(move |app_handle, _api| { let app_name = &app_handle.package_info().name; diff --git a/plugins/notification/src/api-iife.js b/plugins/notification/src/api-iife.js new file mode 100644 index 00000000..4ef6d877 --- /dev/null +++ b/plugins/notification/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_NOTIFICATION__=function(n){"use strict";var e=Object.defineProperty,i=(n,e,i)=>{if(!e.has(n))throw TypeError("Cannot "+i)},t=(n,e,t)=>(i(n,e,"read from private field"),t?t.call(n):e.get(n)),o=(n,e,t,o)=>(i(n,e,"write to private field"),o?o.call(n,t):e.set(n,t),t);function r(n,e=!1){let i=window.crypto.getRandomValues(new Uint32Array(1))[0],t=`_${i}`;return Object.defineProperty(window,t,{value:i=>(e&&Reflect.deleteProperty(window,t),n?.(i)),writable:!1,configurable:!0}),i}((n,i)=>{for(var t in i)e(n,t,{get:i[t],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>f,addPluginListener:()=>d,convertFileSrc:()=>p,invoke:()=>_,transformCallback:()=>r});var c,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((n,e,i)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,i)})(this,c,(()=>{})),this.id=r((n=>{t(this,c).call(this,n)}))}set onmessage(n){o(this,c,n)}get onmessage(){return t(this,c)}toJSON(){return`__CHANNEL__:${this.id}`}};c=new WeakMap;var s,l,u,f=class{constructor(n,e,i){this.plugin=n,this.event=e,this.channelId=i}async unregister(){return _(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function d(n,e,i){let t=new a;return t.onmessage=i,_(`plugin:${n}|register_listener`,{event:e,handler:t}).then((()=>new f(n,e,t.id)))}async function _(n,e={}){return new Promise(((i,t)=>{let o=r((n=>{i(n),Reflect.deleteProperty(window,`_${c}`)}),!0),c=r((n=>{t(n),Reflect.deleteProperty(window,`_${o}`)}),!0);window.__TAURI_IPC__({cmd:n,callback:o,error:c,...e})}))}function p(n,e="asset"){let i=encodeURIComponent(n);return navigator.userAgent.includes("Windows")?`https://${e}.localhost/${i}`:`${e}://localhost/${i}`}return function(n){n.Year="Year",n.Month="Month",n.TwoWeeks="TwoWeeks",n.Week="Week",n.Day="Day",n.Hour="Hour",n.Minute="Minute",n.Second="Second"}(s||(s={})),n.Importance=void 0,(l=n.Importance||(n.Importance={}))[l.None=0]="None",l[l.Min=1]="Min",l[l.Low=2]="Low",l[l.Default=3]="Default",l[l.High=4]="High",n.Visibility=void 0,(u=n.Visibility||(n.Visibility={}))[u.Secret=-1]="Secret",u[u.Private=0]="Private",u[u.Public=1]="Public",n.active=async function(){return _("plugin:notification|get_active")},n.cancel=async function(n){return _("plugin:notification|cancel",{notifications:n})},n.cancelAll=async function(){return _("plugin:notification|cancel")},n.channels=async function(){return _("plugin:notification|getActive")},n.createChannel=async function(n){return _("plugin:notification|create_channel",{...n})},n.isPermissionGranted=async function(){return"default"!==window.Notification.permission?Promise.resolve("granted"===window.Notification.permission):_("plugin:notification|is_permission_granted")},n.onAction=async function(n){return d("notification","actionPerformed",n)},n.onNotificationReceived=async function(n){return d("notification","notification",n)},n.pending=async function(){return _("plugin:notification|get_pending")},n.registerActionTypes=async function(n){return _("plugin:notification|register_action_types",{types:n})},n.removeActive=async function(n){return _("plugin:notification|remove_active",{notifications:n})},n.removeAllActive=async function(){return _("plugin:notification|remove_active")},n.removeChannel=async function(n){return _("plugin:notification|delete_channel",{id:n})},n.requestPermission=async function(){return window.Notification.requestPermission()},n.sendNotification=function(n){"string"==typeof n?new window.Notification(n):new window.Notification(n.title,n)},n}({});Object.defineProperty(window.__TAURI__,"notification",{value:__TAURI_NOTIFICATION__})} diff --git a/plugins/notification/src/lib.rs b/plugins/notification/src/lib.rs index 6e566fe2..03f6db09 100644 --- a/plugins/notification/src/lib.rs +++ b/plugins/notification/src/lib.rs @@ -212,13 +212,15 @@ impl> crate::NotificationExt for T { /// Initializes the plugin. pub fn init() -> TauriPlugin { + let mut init_script = include_str!("init.js").to_string(); + init_script.push_str(include_str!("api-iife.js")); Builder::new("notification") .invoke_handler(tauri::generate_handler![ commands::notify, commands::request_permission, commands::is_permission_granted ]) - .js_init_script(include_str!("init.js").into()) + .js_init_script(init_script) .setup(|app, api| { #[cfg(mobile)] let notification = mobile::init(app, api)?; diff --git a/plugins/os/src/api-iife.js b/plugins/os/src/api-iife.js new file mode 100644 index 00000000..6f95511b --- /dev/null +++ b/plugins/os/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_OS__=function(e){"use strict";var n=Object.defineProperty,t=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},r=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),i=(e,n,r,i)=>(t(e,n,"write to private field"),i?i.call(e,r):n.set(e,r),r);function o(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${t}`;return Object.defineProperty(window,r,{value:t=>(n&&Reflect.deleteProperty(window,r),e?.(t)),writable:!1,configurable:!0}),t}((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>d,invoke:()=>u,transformCallback:()=>o});var s,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,s,(()=>{})),this.id=o((e=>{r(this,s).call(this,e)}))}set onmessage(e){i(this,s,e)}get onmessage(){return r(this,s)}toJSON(){return`__CHANNEL__:${this.id}`}};s=new WeakMap;var l=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return u(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,n,t){let r=new a;return r.onmessage=t,u(`plugin:${e}|register_listener`,{event:n,handler:r}).then((()=>new l(e,n,r.id)))}async function u(e,n={}){return new Promise(((t,r)=>{let i=o((e=>{t(e),Reflect.deleteProperty(window,`_${s}`)}),!0),s=o((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:s,...n})}))}function d(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}const _=navigator.appVersion.includes("Win")?"\r\n":"\n";return e.EOL=_,e.arch=async function(){return u("plugin:os|arch")},e.platform=async function(){return u("plugin:os|platform")},e.tempdir=async function(){return u("plugin:os|tempdir")},e.type=async function(){return u("plugin:os|kind")},e.version=async function(){return u("plugin:os|version")},e}({});Object.defineProperty(window.__TAURI__,"os",{value:__TAURI_OS__})} diff --git a/plugins/os/src/lib.rs b/plugins/os/src/lib.rs index 13436d2f..8cca746d 100644 --- a/plugins/os/src/lib.rs +++ b/plugins/os/src/lib.rs @@ -66,6 +66,7 @@ pub fn tempdir() -> PathBuf { pub fn init() -> TauriPlugin { Builder::new("os") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ commands::platform, commands::version, diff --git a/plugins/positioner/src/api-iife.js b/plugins/positioner/src/api-iife.js new file mode 100644 index 00000000..9bb1eda3 --- /dev/null +++ b/plugins/positioner/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_POSITIONER__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),o=(e,t,r,o)=>(n(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);function i(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>s,PluginListener:()=>c,addPluginListener:()=>h,convertFileSrc:()=>d,invoke:()=>_,transformCallback:()=>i});var a,s=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,a,(()=>{})),this.id=i((e=>{r(this,a).call(this,e)}))}set onmessage(e){o(this,a,e)}get onmessage(){return r(this,a)}toJSON(){return`__CHANNEL__:${this.id}`}};a=new WeakMap;var l,c=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return _(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function h(e,t,n){let r=new s;return r.onmessage=n,_(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new c(e,t,r.id)))}async function _(e,t={}){return new Promise(((n,r)=>{let o=i((e=>{n(e),Reflect.deleteProperty(window,`_${a}`)}),!0),a=i((e=>{r(e),Reflect.deleteProperty(window,`_${o}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:o,error:a,...t})}))}function d(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.Position=void 0,(l=e.Position||(e.Position={}))[l.TopLeft=0]="TopLeft",l[l.TopRight=1]="TopRight",l[l.BottomLeft=2]="BottomLeft",l[l.BottomRight=3]="BottomRight",l[l.TopCenter=4]="TopCenter",l[l.BottomCenter=5]="BottomCenter",l[l.LeftCenter=6]="LeftCenter",l[l.RightCenter=7]="RightCenter",l[l.Center=8]="Center",l[l.TrayLeft=9]="TrayLeft",l[l.TrayBottomLeft=10]="TrayBottomLeft",l[l.TrayRight=11]="TrayRight",l[l.TrayBottomRight=12]="TrayBottomRight",l[l.TrayCenter=13]="TrayCenter",l[l.TrayBottomCenter=14]="TrayBottomCenter",e.moveWindow=async function(e){await _("plugin:positioner|move_window",{position:e})},e}({});Object.defineProperty(window.__TAURI__,"positioner",{value:__TAURI_POSITIONER__})} diff --git a/plugins/positioner/src/lib.rs b/plugins/positioner/src/lib.rs index 34492a34..3c924434 100644 --- a/plugins/positioner/src/lib.rs +++ b/plugins/positioner/src/lib.rs @@ -60,8 +60,9 @@ async fn move_window(window: tauri::Window, position: Position) - /// The Tauri plugin that exposes [`WindowExt::move_window`] to the webview. pub fn init() -> TauriPlugin { - let plugin = - plugin::Builder::new("positioner").invoke_handler(tauri::generate_handler![move_window]); + let plugin = plugin::Builder::new("positioner") + .js_init_script(include_str!("api-iife.js").to_string()) + .invoke_handler(tauri::generate_handler![move_window]); #[cfg(feature = "system-tray")] let plugin = plugin.setup(|app_handle, _api| { diff --git a/plugins/process/src/api-iife.js b/plugins/process/src/api-iife.js new file mode 100644 index 00000000..2495162b --- /dev/null +++ b/plugins/process/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_PROCESS__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),i=(e,t,r,i)=>(n(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);function s(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>u,invoke:()=>_,transformCallback:()=>s});var o,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=s((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return _(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new a;return r.onmessage=n,_(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new l(e,t,r.id)))}async function _(e,t={}){return new Promise(((n,r)=>{let i=s((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=s((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...t})}))}function u(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}return e.exit=async function(e=0){return _("plugin:process|exit",{code:e})},e.relaunch=async function(){return _("plugin:process|restart")},e}({});Object.defineProperty(window.__TAURI__,"process",{value:__TAURI_PROCESS__})} diff --git a/plugins/process/src/lib.rs b/plugins/process/src/lib.rs index e38a4edc..15035689 100644 --- a/plugins/process/src/lib.rs +++ b/plugins/process/src/lib.rs @@ -7,6 +7,7 @@ mod commands; pub fn init() -> TauriPlugin { Builder::new("process") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![commands::exit, commands::restart]) .build() } diff --git a/plugins/shell/src/api-iife.js b/plugins/shell/src/api-iife.js new file mode 100644 index 00000000..97cd46ca --- /dev/null +++ b/plugins/shell/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_SHELL__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),s=(e,t,r,s)=>(n(e,t,"write to private field"),s?s.call(e,r):t.set(e,r),r);function i(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>u,invoke:()=>h,transformCallback:()=>i});var o,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=i((e=>{r(this,o).call(this,e)}))}set onmessage(e){s(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return h(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new a;return r.onmessage=n,h(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new l(e,t,r.id)))}async function h(e,t={}){return new Promise(((n,r)=>{let s=i((e=>{n(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=i((e=>{r(e),Reflect.deleteProperty(window,`_${s}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:s,error:o,...t})}))}function u(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}class d{constructor(){this.eventListeners=Object.create(null)}addListener(e,t){return this.on(e,t)}removeListener(e,t){return this.off(e,t)}on(e,t){return e in this.eventListeners?this.eventListeners[e].push(t):this.eventListeners[e]=[t],this}once(e,t){const n=r=>{this.removeListener(e,n),t(r)};return this.addListener(e,n)}off(e,t){return e in this.eventListeners&&(this.eventListeners[e]=this.eventListeners[e].filter((e=>e!==t))),this}removeAllListeners(e){return e?delete this.eventListeners[e]:this.eventListeners=Object.create(null),this}emit(e,t){if(e in this.eventListeners){const n=this.eventListeners[e];for(const e of n)e(t);return!0}return!1}listenerCount(e){return e in this.eventListeners?this.eventListeners[e].length:0}prependListener(e,t){return e in this.eventListeners?this.eventListeners[e].unshift(t):this.eventListeners[e]=[t],this}prependOnceListener(e,t){const n=r=>{this.removeListener(e,n),t(r)};return this.prependListener(e,n)}}class p{constructor(e){this.pid=e}async write(e){return h("plugin:shell|stdin_write",{pid:this.pid,buffer:"string"==typeof e?e:Array.from(e)})}async kill(){return h("plugin:shell|kill",{cmd:"killChild",pid:this.pid})}}class v extends d{constructor(e,t=[],n){super(),this.stdout=new d,this.stderr=new d,this.program=e,this.args="string"==typeof t?[t]:t,this.options=null!=n?n:{}}static create(e,t=[],n){return new v(e,t,n)}static sidecar(e,t=[],n){const r=new v(e,t,n);return r.options.sidecar=!0,r}async spawn(){return async function(e,t,n=[],r){return"object"==typeof n&&Object.freeze(n),h("plugin:shell|execute",{program:t,args:n,options:r,onEventFn:i(e)})}((e=>{switch(e.event){case"Error":this.emit("error",e.payload);break;case"Terminated":this.emit("close",e.payload);break;case"Stdout":this.stdout.emit("data",e.payload);break;case"Stderr":this.stderr.emit("data",e.payload)}}),this.program,this.args,this.options).then((e=>new p(e)))}async execute(){return new Promise(((e,t)=>{this.on("error",t);const n=[],r=[];this.stdout.on("data",(e=>{n.push(e)})),this.stderr.on("data",(e=>{r.push(e)})),this.on("close",(t=>{e({code:t.code,signal:t.signal,stdout:this.collectOutput(n),stderr:this.collectOutput(r)})})),this.spawn().catch(t)}))}collectOutput(e){return"raw"===this.options.encoding?e.reduce(((e,t)=>new Uint8Array([...e,...t,10])),new Uint8Array):e.join("\n")}}return e.Child=p,e.Command=v,e.EventEmitter=d,e.open=async function(e,t){return h("plugin:shell|open",{path:e,with:t})},e}({});Object.defineProperty(window.__TAURI__,"shell",{value:__TAURI_SHELL__})} diff --git a/plugins/shell/src/lib.rs b/plugins/shell/src/lib.rs index 5453b15b..484ee899 100644 --- a/plugins/shell/src/lib.rs +++ b/plugins/shell/src/lib.rs @@ -63,8 +63,11 @@ impl> ShellExt for T { } pub fn init() -> TauriPlugin> { + let mut init_script = include_str!("init.js").to_string(); + init_script.push_str(include_str!("api-iife.js")); + Builder::>::new("shell") - .js_init_script(include_str!("init.js").to_string()) + .js_init_script(init_script) .invoke_handler(tauri::generate_handler![ commands::execute, commands::stdin_write, diff --git a/plugins/sql/src/api-iife.js b/plugins/sql/src/api-iife.js new file mode 100644 index 00000000..7e084712 --- /dev/null +++ b/plugins/sql/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_SQL__=function(){"use strict";var e=Object.defineProperty,t=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},n=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),r=(e,n,r,s)=>(t(e,n,"write to private field"),s?s.call(e,r):n.set(e,r),r);function s(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>l,addPluginListener:()=>o,convertFileSrc:()=>u,invoke:()=>c,transformCallback:()=>s});var i,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,i,(()=>{})),this.id=s((e=>{n(this,i).call(this,e)}))}set onmessage(e){r(this,i,e)}get onmessage(){return n(this,i)}toJSON(){return`__CHANNEL__:${this.id}`}};i=new WeakMap;var l=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return c(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function o(e,t,n){let r=new a;return r.onmessage=n,c(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new l(e,t,r.id)))}async function c(e,t={}){return new Promise(((n,r)=>{let i=s((e=>{n(e),Reflect.deleteProperty(window,`_${a}`)}),!0),a=s((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:a,...t})}))}function u(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}class d{constructor(e){this.path=e}static async load(e){const t=await c("plugin:sql|load",{db:e});return new d(t)}static get(e){return new d(e)}async execute(e,t){const[n,r]=await c("plugin:sql|execute",{db:this.path,query:e,values:null!=t?t:[]});return{lastInsertId:r,rowsAffected:n}}async select(e,t){return await c("plugin:sql|select",{db:this.path,query:e,values:null!=t?t:[]})}async close(e){return await c("plugin:sql|close",{db:e})}}return d}();Object.defineProperty(window.__TAURI__,"sql",{value:__TAURI_SQL__})} diff --git a/plugins/sql/src/plugin.rs b/plugins/sql/src/plugin.rs index 6d682bda..6da68ef7 100644 --- a/plugins/sql/src/plugin.rs +++ b/plugins/sql/src/plugin.rs @@ -280,6 +280,7 @@ impl Builder { pub fn build(mut self) -> TauriPlugin> { PluginBuilder::>::new("sql") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![load, execute, select, close]) .setup(|app, api| { let config = api.config().clone().unwrap_or_default(); diff --git a/plugins/store/src/api-iife.js b/plugins/store/src/api-iife.js new file mode 100644 index 00000000..ecdc7c1a --- /dev/null +++ b/plugins/store/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_STORE__=function(e){"use strict";var t=Object.defineProperty,n=(e,n)=>{for(var a in n)t(e,a,{get:n[a],enumerable:!0})},a=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,n)=>(a(e,t,"read from private field"),n?n.call(e):t.get(e)),i=(e,t,n,r)=>(a(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);function s(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],a=`_${n}`;return Object.defineProperty(window,a,{value:n=>(t&&Reflect.deleteProperty(window,a),e?.(n)),writable:!1,configurable:!0}),n}n({},{Channel:()=>l,PluginListener:()=>u,addPluginListener:()=>c,convertFileSrc:()=>p,invoke:()=>h,transformCallback:()=>s});var o,l=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,o,(()=>{})),this.id=s((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var u=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return h(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let a=new l;return a.onmessage=n,h(`plugin:${e}|register_listener`,{event:t,handler:a}).then((()=>new u(e,t,a.id)))}async function h(e,t={}){return new Promise(((n,a)=>{let r=s((e=>{n(e),Reflect.deleteProperty(window,`_${i}`)}),!0),i=s((e=>{a(e),Reflect.deleteProperty(window,`_${r}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:r,error:i,...t})}))}function p(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}async function d(e,t){await h("plugin:event|unlisten",{event:e,eventId:t})}async function _(e,t,n){return h("plugin:event|listen",{event:e,windowLabel:t,handler:s(n)}).then((t=>async()=>d(e,t)))}n({},{TauriEvent:()=>w,emit:()=>f,listen:()=>g,once:()=>v});var y,w=((y=w||{}).WINDOW_RESIZED="tauri://resize",y.WINDOW_MOVED="tauri://move",y.WINDOW_CLOSE_REQUESTED="tauri://close-requested",y.WINDOW_CREATED="tauri://window-created",y.WINDOW_DESTROYED="tauri://destroyed",y.WINDOW_FOCUS="tauri://focus",y.WINDOW_BLUR="tauri://blur",y.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",y.WINDOW_THEME_CHANGED="tauri://theme-changed",y.WINDOW_FILE_DROP="tauri://file-drop",y.WINDOW_FILE_DROP_HOVER="tauri://file-drop-hover",y.WINDOW_FILE_DROP_CANCELLED="tauri://file-drop-cancelled",y.MENU="tauri://menu",y);async function g(e,t){return _(e,null,t)}async function v(e,t){return async function(e,t,n){return _(e,t,(t=>{n(t),d(e,t.id).catch((()=>{}))}))}(e,null,t)}async function f(e,t){return async function(e,t,n){await h("plugin:event|emit",{event:e,windowLabel:t,payload:n})}(e,void 0,t)}return e.Store=class{constructor(e){this.path=e}async set(e,t){return await h("plugin:store|set",{path:this.path,key:e,value:t})}async get(e){return await h("plugin:store|get",{path:this.path,key:e})}async has(e){return await h("plugin:store|has",{path:this.path,key:e})}async delete(e){return await h("plugin:store|delete",{path:this.path,key:e})}async clear(){return await h("plugin:store|clear",{path:this.path})}async reset(){return await h("plugin:store|reset",{path:this.path})}async keys(){return await h("plugin:store|keys",{path:this.path})}async values(){return await h("plugin:store|values",{path:this.path})}async entries(){return await h("plugin:store|entries",{path:this.path})}async length(){return await h("plugin:store|length",{path:this.path})}async load(){return await h("plugin:store|load",{path:this.path})}async save(){return await h("plugin:store|save",{path:this.path})}async onKeyChange(e,t){return await g("store://change",(n=>{n.payload.path===this.path&&n.payload.key===e&&t(n.payload.value)}))}async onChange(e){return await g("store://change",(t=>{t.payload.path===this.path&&e(t.payload.key,t.payload.value)}))}},e}({});Object.defineProperty(window.__TAURI__,"store",{value:__TAURI_STORE__})} diff --git a/plugins/store/src/lib.rs b/plugins/store/src/lib.rs index 7c7918f4..18f6ac9c 100644 --- a/plugins/store/src/lib.rs +++ b/plugins/store/src/lib.rs @@ -278,6 +278,7 @@ impl Builder { /// ``` pub fn build(mut self) -> TauriPlugin { plugin::Builder::new("store") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ set, get, has, delete, clear, reset, keys, values, length, entries, load, save ]) diff --git a/plugins/stronghold/src/api-iife.js b/plugins/stronghold/src/api-iife.js new file mode 100644 index 00000000..c8dc34b3 --- /dev/null +++ b/plugins/stronghold/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_STRONGHOLD__=function(t){"use strict";var e=Object.defineProperty,r=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},n=(t,e,n)=>(r(t,e,"read from private field"),n?n.call(t):e.get(t)),a=(t,e,n,a)=>(r(t,e,"write to private field"),a?a.call(t,n):e.set(t,n),n);function s(t,e=!1){let r=window.crypto.getRandomValues(new Uint32Array(1))[0],n=`_${r}`;return Object.defineProperty(window,n,{value:r=>(e&&Reflect.deleteProperty(window,n),t?.(r)),writable:!1,configurable:!0}),r}((t,r)=>{for(var n in r)e(t,n,{get:r[n],enumerable:!0})})({},{Channel:()=>o,PluginListener:()=>c,addPluginListener:()=>h,convertFileSrc:()=>u,invoke:()=>l,transformCallback:()=>s});var i,o=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)})(this,i,(()=>{})),this.id=s((t=>{n(this,i).call(this,t)}))}set onmessage(t){a(this,i,t)}get onmessage(){return n(this,i)}toJSON(){return`__CHANNEL__:${this.id}`}};i=new WeakMap;var c=class{constructor(t,e,r){this.plugin=t,this.event=e,this.channelId=r}async unregister(){return l(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function h(t,e,r){let n=new o;return n.onmessage=r,l(`plugin:${t}|register_listener`,{event:e,handler:n}).then((()=>new c(t,e,n.id)))}async function l(t,e={}){return new Promise(((r,n)=>{let a=s((t=>{r(t),Reflect.deleteProperty(window,`_${i}`)}),!0),i=s((t=>{n(t),Reflect.deleteProperty(window,`_${a}`)}),!0);window.__TAURI_IPC__({cmd:t,callback:a,error:i,...e})}))}function u(t,e="asset"){let r=encodeURIComponent(t);return navigator.userAgent.includes("Windows")?`https://${e}.localhost/${r}`:`${e}://localhost/${r}`}function p(t){return"string"==typeof t?t:Array.from(t instanceof ArrayBuffer?new Uint8Array(t):t)}class d{constructor(t,e){this.type=t,this.payload=e}static generic(t,e){return new d("Generic",{vault:p(t),record:p(e)})}static counter(t,e){return new d("Counter",{vault:p(t),counter:e})}}class g{constructor(t){this.procedureArgs=t}async generateSLIP10Seed(t,e){return await l("plugin:stronghold|execute_procedure",{...this.procedureArgs,procedure:{type:"SLIP10Generate",payload:{output:t,sizeBytes:e}}}).then((t=>Uint8Array.from(t)))}async deriveSLIP10(t,e,r,n){return await l("plugin:stronghold|execute_procedure",{...this.procedureArgs,procedure:{type:"SLIP10Derive",payload:{chain:t,input:{type:e,payload:r},output:n}}}).then((t=>Uint8Array.from(t)))}async recoverBIP39(t,e,r){return await l("plugin:stronghold|execute_procedure",{...this.procedureArgs,procedure:{type:"BIP39Recover",payload:{mnemonic:t,passphrase:r,output:e}}}).then((t=>Uint8Array.from(t)))}async generateBIP39(t,e){return await l("plugin:stronghold|execute_procedure",{...this.procedureArgs,procedure:{type:"BIP39Generate",payload:{output:t,passphrase:e}}}).then((t=>Uint8Array.from(t)))}async getEd25519PublicKey(t){return await l("plugin:stronghold|execute_procedure",{...this.procedureArgs,procedure:{type:"PublicKey",payload:{type:"Ed25519",privateKey:t}}}).then((t=>Uint8Array.from(t)))}async signEd25519(t,e){return await l("plugin:stronghold|execute_procedure",{...this.procedureArgs,procedure:{type:"Ed25519Sign",payload:{privateKey:t,msg:e}}}).then((t=>Uint8Array.from(t)))}}class y{constructor(t,e){this.path=t,this.name=p(e)}getVault(t){return new w(this.path,this.name,p(t))}getStore(){return new _(this.path,this.name)}}class _{constructor(t,e){this.path=t,this.client=e}async get(t){return await l("plugin:stronghold|get_store_record",{snapshotPath:this.path,client:this.client,key:p(t)}).then((t=>Uint8Array.from(t)))}async insert(t,e,r){return await l("plugin:stronghold|save_store_record",{snapshotPath:this.path,client:this.client,key:p(t),value:e,lifetime:r})}async remove(t){return await l("plugin:stronghold|remove_store_record",{snapshotPath:this.path,client:this.client,key:p(t)}).then((t=>null!=t?Uint8Array.from(t):null))}}class w extends g{constructor(t,e,r){super({snapshotPath:t,client:e,vault:r}),this.path=t,this.client=p(e),this.name=p(r)}async insert(t,e){return await l("plugin:stronghold|save_secret",{snapshotPath:this.path,client:this.client,vault:this.name,recordPath:p(t),secret:e})}async remove(t){return await l("plugin:stronghold|remove_secret",{snapshotPath:this.path,client:this.client,vault:this.name,location:t})}}return t.Client=y,t.Location=d,t.Store=_,t.Stronghold=class{constructor(t,e){this.path=t,this.reload(e)}async reload(t){return await l("plugin:stronghold|initialize",{snapshotPath:this.path,password:t})}async unload(){return await l("plugin:stronghold|destroy",{snapshotPath:this.path})}async loadClient(t){return await l("plugin:stronghold|load_client",{snapshotPath:this.path,client:p(t)}).then((()=>new y(this.path,t)))}async createClient(t){return await l("plugin:stronghold|create_client",{snapshotPath:this.path,client:p(t)}).then((()=>new y(this.path,t)))}async save(){return await l("plugin:stronghold|save",{snapshotPath:this.path})}},t.Vault=w,t}({});Object.defineProperty(window.__TAURI__,"stronghold",{value:__TAURI_STRONGHOLD__})} diff --git a/plugins/stronghold/src/lib.rs b/plugins/stronghold/src/lib.rs index b35f61bd..459dd3fb 100644 --- a/plugins/stronghold/src/lib.rs +++ b/plugins/stronghold/src/lib.rs @@ -409,6 +409,7 @@ impl Builder { let password_hash_function = self.password_hash_function; PluginBuilder::new("stronghold") + .js_init_script(include_str!("api-iife.js").to_string()) .setup(move |app, _api| { app.manage(StrongholdCollection::default()); app.manage(PasswordHashFunction(password_hash_function)); diff --git a/plugins/updater/src/api-iife.js b/plugins/updater/src/api-iife.js new file mode 100644 index 00000000..98b55689 --- /dev/null +++ b/plugins/updater/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_UPDATER__=function(e){"use strict";var n=Object.defineProperty,t=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},r=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),i=(e,n,r,i)=>(t(e,n,"write to private field"),i?i.call(e,r):n.set(e,r),r);function a(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${t}`;return Object.defineProperty(window,r,{value:t=>(n&&Reflect.deleteProperty(window,r),e?.(t)),writable:!1,configurable:!0}),t}((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})({},{Channel:()=>s,PluginListener:()=>l,addPluginListener:()=>c,convertFileSrc:()=>u,invoke:()=>d,transformCallback:()=>a});var o,s=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,o,(()=>{})),this.id=a((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var l=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,n,t){let r=new s;return r.onmessage=t,d(`plugin:${e}|register_listener`,{event:n,handler:r}).then((()=>new l(e,n,r.id)))}async function d(e,n={}){return new Promise(((t,r)=>{let i=a((e=>{t(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...n})}))}function u(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}class _{constructor(e){this.response=e}async downloadAndInstall(e){const n=new s;return null!=e&&(n.onmessage=e),d("plugin:updater|download_and_install",{onEvent:n})}}return e.Update=_,e.check=async function(e){return d("plugin:updater|check",{...e}).then((e=>new _(e)))},e}({});Object.defineProperty(window.__TAURI__,"updater",{value:__TAURI_UPDATER__})} diff --git a/plugins/updater/src/lib.rs b/plugins/updater/src/lib.rs index 7d4818b3..67fa962b 100644 --- a/plugins/updater/src/lib.rs +++ b/plugins/updater/src/lib.rs @@ -78,6 +78,7 @@ impl Builder { let target = self.target; let installer_args = self.installer_args; PluginBuilder::::new("updater") + .js_init_script(include_str!("api-iife.js").to_string()) .setup(move |app, api| { let mut config = api.config().clone(); if let Some(installer_args) = installer_args { diff --git a/plugins/upload/src/api-iife.js b/plugins/upload/src/api-iife.js new file mode 100644 index 00000000..b42588ae --- /dev/null +++ b/plugins/upload/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_UPLOAD__=function(e){"use strict";var n=Object.defineProperty,t=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},r=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),o=(e,n,r,o)=>(t(e,n,"write to private field"),o?o.call(e,r):n.set(e,r),r);function a(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${t}`;return Object.defineProperty(window,r,{value:t=>(n&&Reflect.deleteProperty(window,r),e?.(t)),writable:!1,configurable:!0}),t}((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})({},{Channel:()=>l,PluginListener:()=>s,addPluginListener:()=>d,convertFileSrc:()=>u,invoke:()=>c,transformCallback:()=>a});var i,l=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,i,(()=>{})),this.id=a((e=>{r(this,i).call(this,e)}))}set onmessage(e){o(this,i,e)}get onmessage(){return r(this,i)}toJSON(){return`__CHANNEL__:${this.id}`}};i=new WeakMap;var s=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return c(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function d(e,n,t){let r=new l;return r.onmessage=t,c(`plugin:${e}|register_listener`,{event:n,handler:r}).then((()=>new s(e,n,r.id)))}async function c(e,n={}){return new Promise(((t,r)=>{let o=a((e=>{t(e),Reflect.deleteProperty(window,`_${i}`)}),!0),i=a((e=>{r(e),Reflect.deleteProperty(window,`_${o}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:o,error:i,...n})}))}function u(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}async function _(e,n,t,r){const o=new Uint32Array(1);window.crypto.getRandomValues(o);const a=o[0],i=new l;null!=t&&(i.onmessage=t),await c("plugin:upload|upload",{id:a,url:e,filePath:n,headers:null!=r?r:{},onProgress:i})}return e.default=_,e.download=async function(e,n,t,r){const o=new Uint32Array(1);window.crypto.getRandomValues(o);const a=o[0],i=new l;null!=t&&(i.onmessage=t),await c("plugin:upload|download",{id:a,url:e,filePath:n,headers:null!=r?r:{},onProgress:i})},e.upload=_,Object.defineProperty(e,"__esModule",{value:!0}),e}({});Object.defineProperty(window.__TAURI__,"upload",{value:__TAURI_UPLOAD__})} diff --git a/plugins/upload/src/lib.rs b/plugins/upload/src/lib.rs index 714fd1ca..31469863 100644 --- a/plugins/upload/src/lib.rs +++ b/plugins/upload/src/lib.rs @@ -115,6 +115,7 @@ fn file_to_body(channel: Channel, file: File) -> reqwest::Body { pub fn init() -> TauriPlugin { PluginBuilder::new("upload") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![download, upload]) .build() } diff --git a/plugins/websocket/src/api-iife.js b/plugins/websocket/src/api-iife.js new file mode 100644 index 00000000..e337e34b --- /dev/null +++ b/plugins/websocket/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_WEBSOCKET__=function(){"use strict";var e=Object.defineProperty,t=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},n=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),r=(e,n,r,i)=>(t(e,n,"write to private field"),i?i.call(e,r):n.set(e,r),r);function i(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})({},{Channel:()=>a,PluginListener:()=>o,addPluginListener:()=>c,convertFileSrc:()=>d,invoke:()=>l,transformCallback:()=>i});var s,a=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,s,(()=>{})),this.id=i((e=>{n(this,s).call(this,e)}))}set onmessage(e){r(this,s,e)}get onmessage(){return n(this,s)}toJSON(){return`__CHANNEL__:${this.id}`}};s=new WeakMap;var o=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return l(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,t,n){let r=new a;return r.onmessage=n,l(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new o(e,t,r.id)))}async function l(e,t={}){return new Promise(((n,r)=>{let s=i((e=>{n(e),Reflect.deleteProperty(window,`_${a}`)}),!0),a=i((e=>{r(e),Reflect.deleteProperty(window,`_${s}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:s,error:a,...t})}))}function d(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}class u{constructor(e,t){this.id=e,this.listeners=t}static async connect(e,t){const n=[];return await l("plugin:websocket|connect",{url:e,callbackFunction:i((e=>{n.forEach((t=>t(e)))})),options:t}).then((e=>new u(e,n)))}addListener(e){this.listeners.push(e)}async send(e){let t;if("string"==typeof e)t={type:"Text",data:e};else if("object"==typeof e&&"type"in e)t=e;else{if(!Array.isArray(e))throw new Error("invalid `message` type, expected a `{ type: string, data: any }` object, a string or a numeric array");t={type:"Binary",data:e}}return await l("plugin:websocket|send",{id:this.id,message:t})}async disconnect(){return await this.send({type:"Close",data:{code:1e3,reason:"Disconnected by client"}})}}return u}();Object.defineProperty(window.__TAURI__,"websocket",{value:__TAURI_WEBSOCKET__})} diff --git a/plugins/websocket/src/lib.rs b/plugins/websocket/src/lib.rs index b61f2537..7ffeec86 100644 --- a/plugins/websocket/src/lib.rs +++ b/plugins/websocket/src/lib.rs @@ -161,6 +161,7 @@ async fn send( pub fn init() -> TauriPlugin { PluginBuilder::new("websocket") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![connect, send]) .setup(|app, _api| { app.manage(ConnectionManager::default()); diff --git a/plugins/window-state/src/api-iife.js b/plugins/window-state/src/api-iife.js new file mode 100644 index 00000000..d623e9df --- /dev/null +++ b/plugins/window-state/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_WINDOWSTATE__=function(e){"use strict";var t=Object.defineProperty,n=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},r=(e,t,r)=>(n(e,t,"read from private field"),r?r.call(e):t.get(e)),i=(e,t,r,i)=>(n(e,t,"write to private field"),i?i.call(e,r):t.set(e,r),r);function a(e,t=!1){let n=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${n}`;return Object.defineProperty(window,r,{value:n=>(t&&Reflect.deleteProperty(window,r),e?.(n)),writable:!1,configurable:!0}),n}((e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})})({},{Channel:()=>o,PluginListener:()=>c,addPluginListener:()=>_,convertFileSrc:()=>w,invoke:()=>d,transformCallback:()=>a});var s,o=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)})(this,s,(()=>{})),this.id=a((e=>{r(this,s).call(this,e)}))}set onmessage(e){i(this,s,e)}get onmessage(){return r(this,s)}toJSON(){return`__CHANNEL__:${this.id}`}};s=new WeakMap;var l,c=class{constructor(e,t,n){this.plugin=e,this.event=t,this.channelId=n}async unregister(){return d(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function _(e,t,n){let r=new o;return r.onmessage=n,d(`plugin:${e}|register_listener`,{event:t,handler:r}).then((()=>new c(e,t,r.id)))}async function d(e,t={}){return new Promise(((n,r)=>{let i=a((e=>{n(e),Reflect.deleteProperty(window,`_${s}`)}),!0),s=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:s,...t})}))}function w(e,t="asset"){let n=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${t}.localhost/${n}`:`${t}://localhost/${n}`}async function u(e,t){d("plugin:window-state|restore_state",{label:e,flags:t})}return e.StateFlags=void 0,(l=e.StateFlags||(e.StateFlags={}))[l.SIZE=1]="SIZE",l[l.POSITION=2]="POSITION",l[l.MAXIMIZED=4]="MAXIMIZED",l[l.VISIBLE=8]="VISIBLE",l[l.DECORATIONS=16]="DECORATIONS",l[l.FULLSCREEN=32]="FULLSCREEN",l[l.ALL=63]="ALL",e.restoreState=u,e.restoreStateCurrent=async function(e){u(window.__TAURI_METADATA__.__currentWindow.label,e)},e.saveWindowState=async function(e){d("plugin:window-state|save_window_state",{flags:e})},e}({});Object.defineProperty(window.__TAURI__,"windowState",{value:__TAURI_WINDOWSTATE__})} diff --git a/plugins/window-state/src/lib.rs b/plugins/window-state/src/lib.rs index 9fdb6d54..58ac4f18 100644 --- a/plugins/window-state/src/lib.rs +++ b/plugins/window-state/src/lib.rs @@ -282,6 +282,7 @@ impl Builder { pub fn build(self) -> TauriPlugin { let flags = self.state_flags; PluginBuilder::new("window-state") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![ cmd::save_window_state, cmd::restore_state diff --git a/plugins/window/src/api-iife.js b/plugins/window/src/api-iife.js new file mode 100644 index 00000000..4ef4fbcb --- /dev/null +++ b/plugins/window/src/api-iife.js @@ -0,0 +1 @@ +if("__TAURI__"in window){var __TAURI_WINDOW__=function(e){"use strict";var n=Object.defineProperty,t=(e,t)=>{for(var i in t)n(e,i,{get:t[i],enumerable:!0})},i=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},l=(e,n,t)=>(i(e,n,"read from private field"),t?t.call(e):n.get(e)),a=(e,n,t,l)=>(i(e,n,"write to private field"),l?l.call(e,t):n.set(e,t),t);function s(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],i=`_${t}`;return Object.defineProperty(window,i,{value:t=>(n&&Reflect.deleteProperty(window,i),e?.(t)),writable:!1,configurable:!0}),t}t({},{Channel:()=>o,PluginListener:()=>u,addPluginListener:()=>c,convertFileSrc:()=>w,invoke:()=>h,transformCallback:()=>s});var r,o=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,r,(()=>{})),this.id=s((e=>{l(this,r).call(this,e)}))}set onmessage(e){a(this,r,e)}get onmessage(){return l(this,r)}toJSON(){return`__CHANNEL__:${this.id}`}};r=new WeakMap;var u=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return h(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function c(e,n,t){let i=new o;return i.onmessage=t,h(`plugin:${e}|register_listener`,{event:n,handler:i}).then((()=>new u(e,n,i.id)))}async function h(e,n={}){return new Promise(((t,i)=>{let l=s((e=>{t(e),Reflect.deleteProperty(window,`_${a}`)}),!0),a=s((e=>{i(e),Reflect.deleteProperty(window,`_${l}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:l,error:a,...n})}))}function w(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}async function d(e,n){await h("plugin:event|unlisten",{event:e,eventId:n})}async function p(e,n,t){return h("plugin:event|listen",{event:e,windowLabel:n,handler:s(t)}).then((n=>async()=>d(e,n)))}t({},{TauriEvent:()=>b,emit:()=>m,listen:()=>g,once:()=>v});var y,_,b=((y=b||{}).WINDOW_RESIZED="tauri://resize",y.WINDOW_MOVED="tauri://move",y.WINDOW_CLOSE_REQUESTED="tauri://close-requested",y.WINDOW_CREATED="tauri://window-created",y.WINDOW_DESTROYED="tauri://destroyed",y.WINDOW_FOCUS="tauri://focus",y.WINDOW_BLUR="tauri://blur",y.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",y.WINDOW_THEME_CHANGED="tauri://theme-changed",y.WINDOW_FILE_DROP="tauri://file-drop",y.WINDOW_FILE_DROP_HOVER="tauri://file-drop-hover",y.WINDOW_FILE_DROP_CANCELLED="tauri://file-drop-cancelled",y.MENU="tauri://menu",y);async function g(e,n){return p(e,null,n)}async function v(e,n){return async function(e,n,t){return p(e,n,(n=>{t(n),d(e,n.id).catch((()=>{}))}))}(e,null,n)}async function m(e,n){return async function(e,n,t){await h("plugin:event|emit",{event:e,windowLabel:n,payload:t})}(e,void 0,n)}async function f(e,n){await h("plugin:event|unlisten",{event:e,eventId:n})}async function E(e,n,t){return h("plugin:event|listen",{event:e,windowLabel:n,handler:s(t)}).then((n=>async()=>f(e,n)))}class W{constructor(e,n){this.type="Logical",this.width=e,this.height=n}}class D{constructor(e,n){this.type="Physical",this.width=e,this.height=n}toLogical(e){return new W(this.width/e,this.height/e)}}class I{constructor(e,n){this.type="Logical",this.x=e,this.y=n}}class A{constructor(e,n){this.type="Physical",this.x=e,this.y=n}toLogical(e){return new I(this.x/e,this.y/e)}}function O(){return window.__TAURI_METADATA__.__windows.map((e=>new C(e.label,{skip:!0})))}e.UserAttentionType=void 0,(_=e.UserAttentionType||(e.UserAttentionType={}))[_.Critical=1]="Critical",_[_.Informational=2]="Informational";const P=["tauri://created","tauri://error"];class T{constructor(e){this.label=e,this.listeners=Object.create(null)}async listen(e,n){return this._handleTauriEvent(e,n)?Promise.resolve((()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)})):E(e,this.label,n)}async once(e,n){return this._handleTauriEvent(e,n)?Promise.resolve((()=>{const t=this.listeners[e];t.splice(t.indexOf(n),1)})):async function(e,n,t){return E(e,n,(n=>{t(n),f(e,n.id).catch((()=>{}))}))}(e,this.label,n)}async emit(e,n){if(P.includes(e)){for(const t of this.listeners[e]||[])t({event:e,id:-1,windowLabel:this.label,payload:n});return Promise.resolve()}return async function(e,n,t){await h("plugin:event|emit",{event:e,windowLabel:n,payload:t})}(e,this.label,n)}_handleTauriEvent(e,n){return!!P.includes(e)&&(e in this.listeners?this.listeners[e].push(n):this.listeners[e]=[n],!0)}}class L extends T{async scaleFactor(){return h("plugin:window|scale_factor",{label:this.label})}async innerPosition(){return h("plugin:window|inner_position",{label:this.label}).then((({x:e,y:n})=>new A(e,n)))}async outerPosition(){return h("plugin:window|outer_position",{label:this.label}).then((({x:e,y:n})=>new A(e,n)))}async innerSize(){return h("plugin:window|inner_size",{label:this.label}).then((({width:e,height:n})=>new D(e,n)))}async outerSize(){return h("plugin:window|outer_size",{label:this.label}).then((({width:e,height:n})=>new D(e,n)))}async isFullscreen(){return h("plugin:window|is_fullscreen",{label:this.label})}async isMinimized(){return h("plugin:window|is_minimized",{label:this.label})}async isMaximized(){return h("plugin:window|is_maximized",{label:this.label})}async isDecorated(){return h("plugin:window|is_decorated",{label:this.label})}async isResizable(){return h("plugin:window|is_resizable",{label:this.label})}async isVisible(){return h("plugin:window|is_visible",{label:this.label})}async title(){return h("plugin:window|title",{label:this.label})}async theme(){return h("plugin:window|theme",{label:this.label})}async center(){return h("plugin:window|center",{label:this.label})}async requestUserAttention(n){let t=null;return n&&(t=n===e.UserAttentionType.Critical?{type:"Critical"}:{type:"Informational"}),h("plugin:window|request_user_attention",{label:this.label,value:t})}async setResizable(e){return h("plugin:window|set_resizable",{label:this.label,value:e})}async setTitle(e){return h("plugin:window|set_title",{label:this.label,value:e})}async maximize(){return h("plugin:window|maximize",{label:this.label})}async unmaximize(){return h("plugin:window|unmaximize",{label:this.label})}async toggleMaximize(){return h("plugin:window|toggle_maximize",{label:this.label})}async minimize(){return h("plugin:window|minimize",{label:this.label})}async unminimize(){return h("plugin:window|unminimize",{label:this.label})}async show(){return h("plugin:window|show",{label:this.label})}async hide(){return h("plugin:window|hide",{label:this.label})}async close(){return h("plugin:window|close",{label:this.label})}async setDecorations(e){return h("plugin:window|set_decorations",{label:this.label,value:e})}async setShadow(e){return h("plugin:window|set_shadow",{label:this.label,value:e})}async setAlwaysOnTop(e){return h("plugin:window|set_always_on_top",{label:this.label,value:e})}async setContentProtected(e){return h("plugin:window|set_content_protected",{label:this.label,value:e})}async setSize(e){if(!e||"Logical"!==e.type&&"Physical"!==e.type)throw new Error("the `size` argument must be either a LogicalSize or a PhysicalSize instance");return h("plugin:window|set_size",{label:this.label,value:{type:e.type,data:{width:e.width,height:e.height}}})}async setMinSize(e){if(e&&"Logical"!==e.type&&"Physical"!==e.type)throw new Error("the `size` argument must be either a LogicalSize or a PhysicalSize instance");return h("plugin:window|set_min_size",{label:this.label,value:e?{type:e.type,data:{width:e.width,height:e.height}}:null})}async setMaxSize(e){if(e&&"Logical"!==e.type&&"Physical"!==e.type)throw new Error("the `size` argument must be either a LogicalSize or a PhysicalSize instance");return h("plugin:window|set_max_size",{label:this.label,value:e?{type:e.type,data:{width:e.width,height:e.height}}:null})}async setPosition(e){if(!e||"Logical"!==e.type&&"Physical"!==e.type)throw new Error("the `position` argument must be either a LogicalPosition or a PhysicalPosition instance");return h("plugin:window|set_position",{label:this.label,value:{type:e.type,data:{x:e.x,y:e.y}}})}async setFullscreen(e){return h("plugin:window|set_fullscreen",{label:this.label,value:e})}async setFocus(){return h("plugin:window|set_focus",{label:this.label})}async setIcon(e){return h("plugin:window|set_icon",{label:this.label,value:"string"==typeof e?e:Array.from(e)})}async setSkipTaskbar(e){return h("plugin:window|set_skip_taskbar",{label:this.label,value:e})}async setCursorGrab(e){return h("plugin:window|set_cursor_grab",{label:this.label,value:e})}async setCursorVisible(e){return h("plugin:window|set_cursor_visible",{label:this.label,value:e})}async setCursorIcon(e){return h("plugin:window|set_cursor_icon",{label:this.label,value:e})}async setCursorPosition(e){if(!e||"Logical"!==e.type&&"Physical"!==e.type)throw new Error("the `position` argument must be either a LogicalPosition or a PhysicalPosition instance");return h("plugin:window|set_cursor_position",{label:this.label,value:{type:e.type,data:{x:e.x,y:e.y}}})}async setIgnoreCursorEvents(e){return h("plugin:window|set_ignore_cursor_events",{label:this.label,value:e})}async startDragging(){return h("plugin:window|start_dragging",{label:this.label})}async onResized(e){return this.listen(b.WINDOW_RESIZED,(n=>{n.payload=S(n.payload),e(n)}))}async onMoved(e){return this.listen(b.WINDOW_MOVED,(n=>{n.payload=N(n.payload),e(n)}))}async onCloseRequested(e){return this.listen(b.WINDOW_CLOSE_REQUESTED,(n=>{const t=new z(n);Promise.resolve(e(t)).then((()=>{if(!t.isPreventDefault())return this.close()}))}))}async onFocusChanged(e){const n=await this.listen(b.WINDOW_FOCUS,(n=>{e({...n,payload:!0})})),t=await this.listen(b.WINDOW_BLUR,(n=>{e({...n,payload:!1})}));return()=>{n(),t()}}async onScaleChanged(e){return this.listen(b.WINDOW_SCALE_FACTOR_CHANGED,e)}async onMenuClicked(e){return this.listen(b.MENU,e)}async onFileDropEvent(e){const n=await this.listen(b.WINDOW_FILE_DROP,(n=>{e({...n,payload:{type:"drop",paths:n.payload}})})),t=await this.listen(b.WINDOW_FILE_DROP_HOVER,(n=>{e({...n,payload:{type:"hover",paths:n.payload}})})),i=await this.listen(b.WINDOW_FILE_DROP_CANCELLED,(n=>{e({...n,payload:{type:"cancel"}})}));return()=>{n(),t(),i()}}async onThemeChanged(e){return this.listen(b.WINDOW_THEME_CHANGED,e)}}class z{constructor(e){this._preventDefault=!1,this.event=e.event,this.windowLabel=e.windowLabel,this.id=e.id}preventDefault(){this._preventDefault=!0}isPreventDefault(){return this._preventDefault}}class C extends L{constructor(e,n={}){super(e),(null==n?void 0:n.skip)||h("plugin:window|create",{options:{...n,label:e}}).then((async()=>this.emit("tauri://created"))).catch((async e=>this.emit("tauri://error",e)))}static getByLabel(e){return O().some((n=>n.label===e))?new C(e,{skip:!0}):null}}function R(e){return null===e?null:{name:e.name,scaleFactor:e.scaleFactor,position:N(e.position),size:S(e.size)}}function N(e){return new A(e.x,e.y)}function S(e){return new D(e.width,e.height)}return e.appWindow=void 0,"__TAURI_METADATA__"in window?e.appWindow=new C(window.__TAURI_METADATA__.__currentWindow.label,{skip:!0}):(console.warn('Could not find "window.__TAURI_METADATA__". The "appWindow" value will reference the "main" window label.\nNote that this is not an issue if running this frontend on a browser instead of a Tauri window.'),e.appWindow=new C("main",{skip:!0})),e.CloseRequestedEvent=z,e.LogicalPosition=I,e.LogicalSize=W,e.PhysicalPosition=A,e.PhysicalSize=D,e.WebviewWindow=C,e.WebviewWindowHandle=T,e.WindowManager=L,e.availableMonitors=async function(){return h("plugin:window|available_monitors").then((e=>e.map(R)))},e.currentMonitor=async function(){return h("plugin:window|current_monitor").then(R)},e.getAll=O,e.getCurrent=function(){return new C(window.__TAURI_METADATA__.__currentWindow.label,{skip:!0})},e.primaryMonitor=async function(){return h("plugin:window|primary_monitor").then(R)},e}({});Object.defineProperty(window.__TAURI__,"window",{value:__TAURI_WINDOW__})} diff --git a/plugins/window/src/lib.rs b/plugins/window/src/lib.rs index 0f4c2dda..4703517c 100644 --- a/plugins/window/src/lib.rs +++ b/plugins/window/src/lib.rs @@ -7,18 +7,20 @@ use tauri::{ mod desktop_commands; pub fn init() -> TauriPlugin { - let mut init_js = String::new(); + let mut init_script = String::new(); // window.print works on Linux/Windows; need to use the API on macOS #[cfg(any(target_os = "macos", target_os = "ios"))] { - init_js.push_str(include_str!("./scripts/print.js")); + init_script.push_str(include_str!("./scripts/print.js")); } - init_js.push_str(include_str!("./scripts/drag.js")); + init_script.push_str(include_str!("./scripts/drag.js")); #[cfg(any(debug_assertions, feature = "devtools"))] - init_js.push_str(include_str!("./scripts/toggle-devtools.js")); + init_script.push_str(include_str!("./scripts/toggle-devtools.js")); + + init_script.push_str(include_str!("api-iife.js")); Builder::new("window") - .js_init_script(init_js) + .js_init_script(init_script) .invoke_handler(|invoke| { #[cfg(desktop)] { diff --git a/shared/rollup.config.mjs b/shared/rollup.config.mjs index 9595b929..7e2bb91b 100644 --- a/shared/rollup.config.mjs +++ b/shared/rollup.config.mjs @@ -2,7 +2,7 @@ import { builtinModules } from "module"; import typescript from "@rollup/plugin-typescript"; import resolve from "@rollup/plugin-node-resolve"; -// import terser from "@rollup/plugin-terser"; +import terser from "@rollup/plugin-terser"; /** * Create a base rollup config @@ -11,6 +11,8 @@ import resolve from "@rollup/plugin-node-resolve"; * @returns {import('rollup').RollupOptions} */ export function createConfig({ input = "index.ts", pkg, external = [] }) { + const pluginJsName = pkg.name.replace("@tauri-apps/plugin-", "").replace(/-./g, x => x[1].toUpperCase()) + const iifeVarName = `__TAURI_${pluginJsName.toUpperCase()}__` return [ { input, @@ -47,5 +49,24 @@ export function createConfig({ input = "index.ts", pkg, external = [] }) { typescript({ sourceMap: true }), ], }, + { + input, + output: { + file: "src/api-iife.js", + format: "iife", + name: iifeVarName, + // IIFE is in the format `var ${iifeVarName} = (() => {})()` + // we check if __TAURI__ exists and inject the API object + banner: "if ('__TAURI__' in window) {", + // the last `}` closes the if in the banner + footer: `Object.defineProperty(window.__TAURI__, '${pluginJsName}', { value: ${iifeVarName} }) }`, + }, + // and var is not guaranteed to assign to the global `window` object so we make sure to assign it + plugins: [ + resolve(), + terser(), + typescript({ declaration: false }), + ], + }, ]; } diff --git a/shared/template/src/lib.rs b/shared/template/src/lib.rs index 77861b7f..3e0f7618 100644 --- a/shared/template/src/lib.rs +++ b/shared/template/src/lib.rs @@ -39,6 +39,7 @@ impl> crate::{{ plugin_name_pascal_case }}Ext for T /// Initializes the plugin. pub fn init() -> TauriPlugin { Builder::new("{{ plugin_name }}") + .js_init_script(include_str!("api-iife.js").to_string()) .invoke_handler(tauri::generate_handler![commands::execute]) .setup(|app, api| { #[cfg(mobile)]