diff --git a/.changes/fs-readable-stream.md b/.changes/fs-readable-stream.md new file mode 100644 index 0000000000..cb9e7367b6 --- /dev/null +++ b/.changes/fs-readable-stream.md @@ -0,0 +1,7 @@ +--- +"fs": "patch" +"fs-js": "patch" +--- + +Add support for using `ReadableStream` with `writeFile` API. + diff --git a/Cargo.lock b/Cargo.lock index 2522f63da4..0c5a87b52e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6855,7 +6855,9 @@ dependencies = [ "serde_repr", "tauri", "tauri-plugin", + "tauri-utils", "thiserror", + "toml 0.8.2", "url", "uuid", ] diff --git a/plugins/fs/Cargo.toml b/plugins/fs/Cargo.toml index cd4e771682..9c2fdd9a2a 100644 --- a/plugins/fs/Cargo.toml +++ b/plugins/fs/Cargo.toml @@ -24,6 +24,8 @@ ios = { level = "partial", notes = "Access is restricted to Application folder b tauri-plugin = { workspace = true, features = ["build"] } schemars = { workspace = true } serde = { workspace = true } +toml = "0.8" +tauri-utils = { workspace = true, features = ["build"] } [dependencies] serde = { workspace = true } diff --git a/plugins/fs/api-iife.js b/plugins/fs/api-iife.js index e863d7a93e..0274154ec6 100644 --- a/plugins/fs/api-iife.js +++ b/plugins/fs/api-iife.js @@ -1 +1 @@ -if("__TAURI__"in window){var __TAURI_PLUGIN_FS__=function(t){"use strict";function e(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function n(t,e,n,i,o){if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var i,o,r,a,s,c;"function"==typeof SuppressedError&&SuppressedError;class f{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,i.set(this,(()=>{})),o.set(this,0),r.set(this,{}),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((({message:t,id:a})=>{if(a===e(this,o,"f")){n(this,o,a+1),e(this,i,"f").call(this,t);const s=Object.keys(e(this,r,"f"));if(s.length>0){let t=a+1;for(const n of s.sort()){if(parseInt(n)!==t)break;{const o=e(this,r,"f")[n];delete e(this,r,"f")[n],e(this,i,"f").call(this,o),t+=1}}n(this,o,t)}}else e(this,r,"f")[a.toString()]=t}))}set onmessage(t){n(this,i,t)}get onmessage(){return e(this,i,"f")}toJSON(){return`__CHANNEL__:${this.id}`}}async function l(t,e={},n){return window.__TAURI_INTERNALS__.invoke(t,e,n)}i=new WeakMap,o=new WeakMap,r=new WeakMap;class u{get rid(){return e(this,a,"f")}constructor(t){a.set(this,void 0),n(this,a,t)}async close(){return l("plugin:resources|close",{rid:this.rid})}}function p(t){return{isFile:t.isFile,isDirectory:t.isDirectory,isSymlink:t.isSymlink,size:t.size,mtime:null!==t.mtime?new Date(t.mtime):null,atime:null!==t.atime?new Date(t.atime):null,birthtime:null!==t.birthtime?new Date(t.birthtime):null,readonly:t.readonly,fileAttributes:t.fileAttributes,dev:t.dev,ino:t.ino,mode:t.mode,nlink:t.nlink,uid:t.uid,gid:t.gid,rdev:t.rdev,blksize:t.blksize,blocks:t.blocks}}a=new WeakMap,t.BaseDirectory=void 0,(s=t.BaseDirectory||(t.BaseDirectory={}))[s.Audio=1]="Audio",s[s.Cache=2]="Cache",s[s.Config=3]="Config",s[s.Data=4]="Data",s[s.LocalData=5]="LocalData",s[s.Document=6]="Document",s[s.Download=7]="Download",s[s.Picture=8]="Picture",s[s.Public=9]="Public",s[s.Video=10]="Video",s[s.Resource=11]="Resource",s[s.Temp=12]="Temp",s[s.AppConfig=13]="AppConfig",s[s.AppData=14]="AppData",s[s.AppLocalData=15]="AppLocalData",s[s.AppCache=16]="AppCache",s[s.AppLog=17]="AppLog",s[s.Desktop=18]="Desktop",s[s.Executable=19]="Executable",s[s.Font=20]="Font",s[s.Home=21]="Home",s[s.Runtime=22]="Runtime",s[s.Template=23]="Template",t.SeekMode=void 0,(c=t.SeekMode||(t.SeekMode={}))[c.Start=0]="Start",c[c.Current=1]="Current",c[c.End=2]="End";class w extends u{async read(t){if(0===t.byteLength)return 0;const e=await l("plugin:fs|read",{rid:this.rid,len:t.byteLength}),n=function(t){const e=new Uint8ClampedArray(t),n=e.byteLength;let i=0;for(let t=0;tt instanceof URL?t.toString():t)),options:i,onEvent:r});return()=>{h(a)}},t.watchImmediate=async function(t,e,n){const i={recursive:!1,...n,delayMs:null},o=Array.isArray(t)?t:[t];for(const t of o)if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const r=new f;r.onmessage=e;const a=await l("plugin:fs|watch",{paths:o.map((t=>t instanceof URL?t.toString():t)),options:i,onEvent:r});return()=>{h(a)}},t.writeFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");await l("plugin:fs|write_file",e,{headers:{path:encodeURIComponent(t instanceof URL?t.toString():t),options:JSON.stringify(n)}})},t.writeTextFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const i=new TextEncoder;await l("plugin:fs|write_text_file",i.encode(e),{headers:{path:t instanceof URL?t.toString():t,options:JSON.stringify(n)}})},t}({});Object.defineProperty(window.__TAURI__,"fs",{value:__TAURI_PLUGIN_FS__})} +if("__TAURI__"in window){var __TAURI_PLUGIN_FS__=function(t){"use strict";function e(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function n(t,e,n,i,o){if("function"==typeof e?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var i,o,r,a,s,c;"function"==typeof SuppressedError&&SuppressedError;class f{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,i.set(this,(()=>{})),o.set(this,0),r.set(this,{}),this.id=function(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}((({message:t,id:a})=>{if(a===e(this,o,"f")){n(this,o,a+1),e(this,i,"f").call(this,t);const s=Object.keys(e(this,r,"f"));if(s.length>0){let t=a+1;for(const n of s.sort()){if(parseInt(n)!==t)break;{const o=e(this,r,"f")[n];delete e(this,r,"f")[n],e(this,i,"f").call(this,o),t+=1}}n(this,o,t)}}else e(this,r,"f")[a.toString()]=t}))}set onmessage(t){n(this,i,t)}get onmessage(){return e(this,i,"f")}toJSON(){return`__CHANNEL__:${this.id}`}}async function l(t,e={},n){return window.__TAURI_INTERNALS__.invoke(t,e,n)}i=new WeakMap,o=new WeakMap,r=new WeakMap;class u{get rid(){return e(this,a,"f")}constructor(t){a.set(this,void 0),n(this,a,t)}async close(){return l("plugin:resources|close",{rid:this.rid})}}function p(t){return{isFile:t.isFile,isDirectory:t.isDirectory,isSymlink:t.isSymlink,size:t.size,mtime:null!==t.mtime?new Date(t.mtime):null,atime:null!==t.atime?new Date(t.atime):null,birthtime:null!==t.birthtime?new Date(t.birthtime):null,readonly:t.readonly,fileAttributes:t.fileAttributes,dev:t.dev,ino:t.ino,mode:t.mode,nlink:t.nlink,uid:t.uid,gid:t.gid,rdev:t.rdev,blksize:t.blksize,blocks:t.blocks}}a=new WeakMap,t.BaseDirectory=void 0,(s=t.BaseDirectory||(t.BaseDirectory={}))[s.Audio=1]="Audio",s[s.Cache=2]="Cache",s[s.Config=3]="Config",s[s.Data=4]="Data",s[s.LocalData=5]="LocalData",s[s.Document=6]="Document",s[s.Download=7]="Download",s[s.Picture=8]="Picture",s[s.Public=9]="Public",s[s.Video=10]="Video",s[s.Resource=11]="Resource",s[s.Temp=12]="Temp",s[s.AppConfig=13]="AppConfig",s[s.AppData=14]="AppData",s[s.AppLocalData=15]="AppLocalData",s[s.AppCache=16]="AppCache",s[s.AppLog=17]="AppLog",s[s.Desktop=18]="Desktop",s[s.Executable=19]="Executable",s[s.Font=20]="Font",s[s.Home=21]="Home",s[s.Runtime=22]="Runtime",s[s.Template=23]="Template",t.SeekMode=void 0,(c=t.SeekMode||(t.SeekMode={}))[c.Start=0]="Start",c[c.Current=1]="Current",c[c.End=2]="End";class w extends u{async read(t){if(0===t.byteLength)return 0;const e=await l("plugin:fs|read",{rid:this.rid,len:t.byteLength}),n=function(t){const e=new Uint8ClampedArray(t),n=e.byteLength;let i=0;for(let t=0;tt instanceof URL?t.toString():t)),options:i,onEvent:r});return()=>{d(a)}},t.watchImmediate=async function(t,e,n){const i={recursive:!1,...n,delayMs:null},o=Array.isArray(t)?t:[t];for(const t of o)if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const r=new f;r.onmessage=e;const a=await l("plugin:fs|watch",{paths:o.map((t=>t instanceof URL?t.toString():t)),options:i,onEvent:r});return()=>{d(a)}},t.writeFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");if(e instanceof ReadableStream){const i=await h(t,n);for await(const t of e)await i.write(t);i.close()}else await l("plugin:fs|write_file",e,{headers:{path:encodeURIComponent(t instanceof URL?t.toString():t),options:JSON.stringify(n)}})},t.writeTextFile=async function(t,e,n){if(t instanceof URL&&"file:"!==t.protocol)throw new TypeError("Must be a file URL.");const i=new TextEncoder;await l("plugin:fs|write_text_file",i.encode(e),{headers:{path:t instanceof URL?t.toString():t,options:JSON.stringify(n)}})},t}({});Object.defineProperty(window.__TAURI__,"fs",{value:__TAURI_PLUGIN_FS__})} diff --git a/plugins/fs/build.rs b/plugins/fs/build.rs index cb9d00dafc..cdb21629e1 100644 --- a/plugins/fs/build.rs +++ b/plugins/fs/build.rs @@ -7,6 +7,8 @@ use std::{ path::{Path, PathBuf}, }; +use tauri_utils::acl::manifest::PermissionFile; + #[path = "src/scope.rs"] #[allow(dead_code)] mod scope; @@ -62,31 +64,31 @@ const BASE_DIR_VARS: &[&str] = &[ "APPCACHE", "APPLOG", ]; -const COMMANDS: &[&str] = &[ - "mkdir", - "create", - "copy_file", - "remove", - "rename", - "truncate", - "ftruncate", - "write", - "write_file", - "write_text_file", - "read_dir", - "read_file", - "read", - "open", - "read_text_file", - "read_text_file_lines", - "read_text_file_lines_next", - "seek", - "stat", - "lstat", - "fstat", - "exists", - "watch", - "unwatch", +const COMMANDS: &[(&str, &[&str])] = &[ + ("mkdir", &[]), + ("create", &[]), + ("copy_file", &[]), + ("remove", &[]), + ("rename", &[]), + ("truncate", &[]), + ("ftruncate", &[]), + ("write", &[]), + ("write_file", &["open", "write"]), + ("write_text_file", &[]), + ("read_dir", &[]), + ("read_file", &[]), + ("read", &[]), + ("open", &[]), + ("read_text_file", &[]), + ("read_text_file_lines", &["read_text_file_lines_next"]), + ("read_text_file_lines_next", &[]), + ("seek", &[]), + ("stat", &[]), + ("lstat", &[]), + ("fstat", &[]), + ("exists", &[]), + ("watch", &[]), + ("unwatch", &[]), ]; fn main() { @@ -192,9 +194,42 @@ permissions = [ } } - tauri_plugin::Builder::new(COMMANDS) + tauri_plugin::Builder::new(&COMMANDS.iter().map(|c| c.0).collect::>()) .global_api_script_path("./api-iife.js") .global_scope_schema(schemars::schema_for!(FsScopeEntry)) .android_path("android") .build(); + + // workaround to include nested permissions as `tauri_plugin` doesn't support it + let permissions_dir = autogenerated.join("commands"); + for (command, nested_commands) in COMMANDS { + if nested_commands.is_empty() { + continue; + } + + let permission_path = permissions_dir.join(format!("{command}.toml")); + + let content = std::fs::read_to_string(&permission_path) + .expect(&format!("failed to read {command}.toml")); + + let mut permission_file = toml::from_str::(&content) + .expect(&format!("failed to deserialize {command}.toml")); + + for p in permission_file.permission.iter_mut() { + p.commands + .allow + .extend(nested_commands.iter().map(|s| s.to_string())); + } + + let out = toml::to_string_pretty(&permission_file) + .expect(&format!("failed to serialize {command}.toml")); + let out = format!( + r#"# Automatically generated - DO NOT EDIT! + +"$schema" = "../../schemas/schema.json" + +{out}"# + ); + std::fs::write(permission_path, out).expect(&format!("failed to write {command}.toml")); + } } diff --git a/plugins/fs/guest-js/index.ts b/plugins/fs/guest-js/index.ts index 57e7518d5c..e8619f1844 100644 --- a/plugins/fs/guest-js/index.ts +++ b/plugins/fs/guest-js/index.ts @@ -416,11 +416,11 @@ class FileHandle extends Resource { } /** - * Writes `p.byteLength` bytes from `p` to the underlying data stream. It - * resolves to the number of bytes written from `p` (`0` <= `n` <= - * `p.byteLength`) or reject with the error encountered that caused the + * Writes `data.byteLength` bytes from `data` to the underlying data stream. It + * resolves to the number of bytes written from `data` (`0` <= `n` <= + * `data.byteLength`) or reject with the error encountered that caused the * write to stop early. `write()` must reject with a non-null error if - * would resolve to `n` < `p.byteLength`. `write()` must not modify the + * would resolve to `n` < `data.byteLength`. `write()` must not modify the * slice data, even temporarily. * * @example @@ -1033,19 +1033,27 @@ interface WriteFileOptions { */ async function writeFile( path: string | URL, - data: Uint8Array, + data: Uint8Array | ReadableStream, options?: WriteFileOptions ): Promise { if (path instanceof URL && path.protocol !== 'file:') { throw new TypeError('Must be a file URL.') } - await invoke('plugin:fs|write_file', data, { - headers: { - path: encodeURIComponent(path instanceof URL ? path.toString() : path), - options: JSON.stringify(options) + if (data instanceof ReadableStream) { + const file = await open(path, options) + for await (const chunk of data) { + await file.write(chunk) } - }) + file.close() + } else { + await invoke('plugin:fs|write_file', data, { + headers: { + path: encodeURIComponent(path instanceof URL ? path.toString() : path), + options: JSON.stringify(options) + } + }) + } } /** diff --git a/plugins/fs/permissions/autogenerated/commands/read_text_file_lines.toml b/plugins/fs/permissions/autogenerated/commands/read_text_file_lines.toml index 1ba629cbf4..86f3581843 100644 --- a/plugins/fs/permissions/autogenerated/commands/read_text_file_lines.toml +++ b/plugins/fs/permissions/autogenerated/commands/read_text_file_lines.toml @@ -5,9 +5,18 @@ [[permission]] identifier = "allow-read-text-file-lines" description = "Enables the read_text_file_lines command without any pre-configured scope." -commands.allow = ["read_text_file_lines"] + +[permission.commands] +allow = [ + "read_text_file_lines", + "read_text_file_lines_next", +] +deny = [] [[permission]] identifier = "deny-read-text-file-lines" description = "Denies the read_text_file_lines command without any pre-configured scope." -commands.deny = ["read_text_file_lines"] + +[permission.commands] +allow = ["read_text_file_lines_next"] +deny = ["read_text_file_lines"] diff --git a/plugins/fs/permissions/autogenerated/commands/write_file.toml b/plugins/fs/permissions/autogenerated/commands/write_file.toml index cb0450fc54..258eeb9771 100644 --- a/plugins/fs/permissions/autogenerated/commands/write_file.toml +++ b/plugins/fs/permissions/autogenerated/commands/write_file.toml @@ -5,9 +5,22 @@ [[permission]] identifier = "allow-write-file" description = "Enables the write_file command without any pre-configured scope." -commands.allow = ["write_file"] + +[permission.commands] +allow = [ + "write_file", + "open", + "write", +] +deny = [] [[permission]] identifier = "deny-write-file" description = "Denies the write_file command without any pre-configured scope." -commands.deny = ["write_file"] + +[permission.commands] +allow = [ + "open", + "write", +] +deny = ["write_file"]