use js_sys::{Array, Function, Object, Reflect, Uint8Array};
use std::{
io::{IoSlice, IoSliceMut},
time::{SystemTime, UNIX_EPOCH},
};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use super::api::{
Dirent, Metadata, OpenOptions, ReadStreamOptions, StatFs, TempDir, WatchFileOptions,
WatchOptions, WriteStreamOptions,
};
pub type File = u32;
pub type Dir = JsValue;
pub struct ReadStream {
value: JsValue,
iterator: JsValue,
}
pub fn create_read_stream(path: &str, options: ReadStreamOptions) -> Result<ReadStream, JsValue> {
if options.chunk_size == 0 || options.chunk_size > u32::MAX as usize {
return Err(invalid_path_error(
"stream chunk size must be between 1 and u32::MAX",
));
}
if options.end.is_some_and(|end| end < options.start) {
return Err(invalid_path_error("stream end must not be before start"));
}
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
if options.start > MAX_SAFE_INTEGER || options.end.is_some_and(|end| end >= MAX_SAFE_INTEGER) {
return Err(invalid_path_error(
"stream byte positions must be JavaScript safe integers",
));
}
let js_options = Object::new();
Reflect::set(
&js_options,
&JsValue::from_str("highWaterMark"),
&JsValue::from_f64(options.chunk_size as f64),
)?;
if options.start != 0 {
Reflect::set(
&js_options,
&JsValue::from_str("start"),
&JsValue::from_f64(options.start as f64),
)?;
}
if let Some(end) = options.end {
Reflect::set(
&js_options,
&JsValue::from_str("end"),
&JsValue::from_f64(end as f64),
)?;
}
let value = call_fs(
"createReadStream",
&[JsValue::from_str(path), js_options.into()],
)?;
let symbol = js_sys::Symbol::async_iterator();
let method = Reflect::get(&value, &symbol.into())?.dyn_into::<Function>()?;
let iterator = method.call0(&value)?;
Ok(ReadStream { value, iterator })
}
pub async fn stream_read(stream: &mut ReadStream) -> Result<Option<Vec<u8>>, JsValue> {
let next =
Reflect::get(&stream.iterator, &JsValue::from_str("next"))?.dyn_into::<Function>()?;
let promise = next
.call0(&stream.iterator)?
.dyn_into::<js_sys::Promise>()?;
let result = JsFuture::from(promise).await?;
if Reflect::get(&result, &JsValue::from_str("done"))?.as_bool() == Some(true) {
return Ok(None);
}
let value = Reflect::get(&result, &JsValue::from_str("value"))?;
if !value.is_instance_of::<Uint8Array>() {
return Err(JsValue::from_str(
"ZenFS read stream returned a non-byte chunk",
));
}
Ok(Some(Uint8Array::new(&value).to_vec()))
}
pub fn read_stream_destroy(stream: &ReadStream) -> Result<(), JsValue> {
let method =
Reflect::get(&stream.value, &JsValue::from_str("destroy"))?.dyn_into::<Function>()?;
method.call0(&stream.value)?;
Ok(())
}
pub struct WriteStream {
value: JsValue,
}
pub fn create_write_stream(
path: &str,
options: WriteStreamOptions,
) -> Result<WriteStream, JsValue> {
if options.start.is_some_and(|start| start > (1 << 53) - 1) {
return Err(invalid_path_error(
"stream byte positions must be JavaScript safe integers",
));
}
let js_options = Object::new();
if let Some(start) = options.start {
Reflect::set(
&js_options,
&JsValue::from_str("start"),
&JsValue::from_f64(start as f64),
)?;
}
let value = call_fs(
"createWriteStream",
&[JsValue::from_str(path), js_options.into()],
)?;
Ok(WriteStream { value })
}
pub async fn stream_write(stream: &mut WriteStream, bytes: &[u8]) -> Result<(), JsValue> {
let write = Reflect::get(&stream.value, &JsValue::from_str("write"))?.dyn_into::<Function>()?;
let chunk = Uint8Array::from(bytes);
let promise = js_sys::Promise::new(&mut |resolve, reject| {
let callback_reject = reject.clone();
let callback = Closure::once_into_js(move |error: JsValue| {
if error.is_null() || error.is_undefined() {
let _ = resolve.call0(&JsValue::UNDEFINED);
} else {
let _ = callback_reject.call1(&JsValue::UNDEFINED, &error);
}
});
if let Err(error) = write.call2(&stream.value, &chunk, &callback) {
let _ = reject.call1(&JsValue::UNDEFINED, &error);
}
});
JsFuture::from(promise).await?;
Ok(())
}
pub async fn stream_end(stream: &mut WriteStream) -> Result<(), JsValue> {
let end = Reflect::get(&stream.value, &JsValue::from_str("end"))?.dyn_into::<Function>()?;
let promise = js_sys::Promise::new(&mut |resolve, reject| {
let callback = Closure::once_into_js(move || {
let _ = resolve.call0(&JsValue::UNDEFINED);
});
if let Err(error) = end.call1(&stream.value, &callback) {
let _ = reject.call1(&JsValue::UNDEFINED, &error);
}
});
JsFuture::from(promise).await?;
Ok(())
}
pub fn write_stream_destroy(stream: &WriteStream) -> Result<(), JsValue> {
let method =
Reflect::get(&stream.value, &JsValue::from_str("destroy"))?.dyn_into::<Function>()?;
method.call0(&stream.value)?;
Ok(())
}
pub struct Watcher {
value: JsValue,
_callback: Closure<dyn FnMut(JsValue, JsValue)>,
}
pub fn watch(
path: &str,
options: WatchOptions,
mut listener: Box<dyn FnMut(&str, &str) + Send>,
) -> Result<Watcher, JsValue> {
let js_options = Object::new();
Reflect::set(
&js_options,
&JsValue::from_str("recursive"),
&JsValue::from_bool(options.recursive),
)?;
Reflect::set(
&js_options,
&JsValue::from_str("persistent"),
&JsValue::from_bool(options.persistent),
)?;
let callback = Closure::wrap(Box::new(move |event: JsValue, name: JsValue| {
if let (Some(event), Some(name)) = (event.as_string(), name.as_string()) {
listener(&event, &name);
}
}) as Box<dyn FnMut(JsValue, JsValue)>);
let value = call_fs(
"watch",
&[
JsValue::from_str(path),
js_options.into(),
callback.as_ref().clone(),
],
)?;
Ok(Watcher {
value,
_callback: callback,
})
}
pub fn watch_close(watcher: &Watcher) -> Result<(), JsValue> {
let close =
Reflect::get(&watcher.value, &JsValue::from_str("close"))?.dyn_into::<Function>()?;
close.call0(&watcher.value)?;
Ok(())
}
thread_local! {
static FILE_WATCHES: std::cell::RefCell<std::collections::HashMap<String, Vec<(u64, Closure<dyn FnMut(JsValue, JsValue)>)>>> = Default::default();
static NEXT_FILE_WATCH_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
}
pub fn watch_file(
path: &str,
options: WatchFileOptions,
mut listener: Box<dyn FnMut(Metadata, Metadata) + Send>,
) -> Result<u64, JsValue> {
if options.interval.is_zero() {
return Err(invalid_path_error("watch interval must be positive"));
}
let js_options = Object::new();
Reflect::set(
&js_options,
&JsValue::from_str("interval"),
&JsValue::from_f64(options.interval.as_secs_f64() * 1000.0),
)?;
Reflect::set(
&js_options,
&JsValue::from_str("persistent"),
&JsValue::from_bool(options.persistent),
)?;
let callback = Closure::wrap(Box::new(move |curr: JsValue, prev: JsValue| {
if let (Ok(curr), Ok(prev)) = (metadata_from_stats(&curr), metadata_from_stats(&prev)) {
listener(curr, prev);
}
}) as Box<dyn FnMut(JsValue, JsValue)>);
call_fs(
"watchFile",
&[
JsValue::from_str(path),
js_options.into(),
callback.as_ref().clone(),
],
)?;
let id = NEXT_FILE_WATCH_ID.with(|next| {
let id = next.get();
next.set(id.wrapping_add(1));
id
});
FILE_WATCHES.with(|watches| {
watches
.borrow_mut()
.entry(path.to_owned())
.or_default()
.push((id, callback))
});
Ok(id)
}
pub fn unwatch_file(path: &str, id: Option<u64>) -> Result<(), JsValue> {
FILE_WATCHES.with(|watches| {
let mut watches = watches.borrow_mut();
if let Some(id) = id {
if let Some(list) = watches.get_mut(path) {
if let Some(index) = list.iter().position(|(candidate, _)| *candidate == id) {
call_fs(
"unwatchFile",
&[JsValue::from_str(path), list[index].1.as_ref().clone()],
)?;
list.remove(index);
if list.is_empty() {
watches.remove(path);
}
}
}
} else {
call_fs("unwatchFile", &[JsValue::from_str(path)])?;
watches.remove(path);
}
Ok(())
})
}
pub fn invalid_path_error(message: &str) -> JsValue {
JsValue::from_str(message)
}
#[cfg(test)]
#[wasm_bindgen(module = "https://esm.sh/@zenfs/core@2.7.6?bundle&target=es2022")]
extern "C" {
#[wasm_bindgen(thread_local_v2, js_name = fs)]
static ZEN_FS: JsValue;
}
#[cfg(test)]
macro_rules! zenfs_setup_imports {
($module:literal) => {
#[wasm_bindgen(module = $module)]
extern "C" {
#[wasm_bindgen(catch, js_name = configure)]
fn zenfs_configure(configuration: &JsValue) -> Result<js_sys::Promise, JsValue>;
#[wasm_bindgen(catch, js_name = configureSync)]
fn zenfs_configure_sync(configuration: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = configureSingle)]
fn zenfs_configure_single(configuration: &JsValue) -> Result<js_sys::Promise, JsValue>;
#[wasm_bindgen(catch, js_name = configureSingleSync)]
fn zenfs_configure_single_sync(configuration: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = configureFileSystem)]
fn zenfs_configure_file_system(
filesystem: &JsValue,
configuration: &JsValue,
) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = resolveMountConfig)]
fn zenfs_resolve_mount_config(
configuration: &JsValue,
) -> Result<js_sys::Promise, JsValue>;
#[wasm_bindgen(catch, js_name = resolveMountConfigSync)]
fn zenfs_resolve_mount_config_sync(configuration: &JsValue)
-> Result<JsValue, JsValue>;
#[wasm_bindgen(catch, js_name = resolveRemoteMount)]
fn zenfs_resolve_remote_mount(
channel: &JsValue,
configuration: &JsValue,
) -> Result<js_sys::Promise, JsValue>;
#[wasm_bindgen(catch, js_name = mount)]
fn zenfs_mount(mount_point: &str, filesystem: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = umount)]
fn zenfs_umount(mount_point: &str) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = sync)]
fn zenfs_sync() -> Result<js_sys::Promise, JsValue>;
#[wasm_bindgen(catch, js_name = waitOnline)]
fn zenfs_wait_online(worker: &JsValue) -> Result<js_sys::Promise, JsValue>;
#[wasm_bindgen(catch, js_name = attachFS)]
fn zenfs_attach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = detachFS)]
fn zenfs_detach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue>;
#[wasm_bindgen(catch, js_name = globToRegex)]
fn zenfs_glob_to_regex(pattern: &str) -> Result<JsValue, JsValue>;
#[wasm_bindgen(catch, js_name = normalizePath)]
fn zenfs_normalize_path(path: &str) -> Result<String, JsValue>;
#[wasm_bindgen(thread_local_v2, js_name = mounts)]
static ZEN_MOUNTS: JsValue;
#[wasm_bindgen(thread_local_v2, js_name = promises)]
static ZEN_PROMISES: JsValue;
#[wasm_bindgen(thread_local_v2, js_name = default)]
static ZEN_DEFAULT: JsValue;
#[wasm_bindgen(thread_local_v2, js_name = vfs)]
static ZEN_VFS: JsValue;
#[wasm_bindgen(thread_local_v2, js_name = version)]
static ZEN_VERSION: JsValue;
#[wasm_bindgen(thread_local_v2, js_name = constants)]
static ZEN_CONSTANTS: JsValue;
}
};
}
#[cfg(not(test))]
#[wasm_bindgen(inline_js = r#"
function canResolveZenFs() {
try {
if (typeof import.meta.resolve === "function") {
import.meta.resolve("@zenfs/core");
return true;
}
} catch (_) {
return false;
}
try {
return [...document.querySelectorAll('script[type="importmap"]')]
.some((script) => Object.hasOwn(JSON.parse(script.textContent || "{}").imports || {}, "@zenfs/core"));
} catch (_) {
return false;
}
}
let zenfsModule = null;
const zenfsModulePromise = canResolveZenFs()
? import("@zenfs/core").then((module) => (zenfsModule = module, module)).catch(() => null)
: Promise.resolve(null);
function requireZenFs() {
if (!zenfsModule) {
throw new Error("ZenFS is not available or has not finished loading");
}
return zenfsModule;
}
export function zenfs_is_configured() {
if (!zenfsModule) return false;
const mounts = zenfsModule.mounts;
return mounts instanceof Map ? mounts.size > 0 : Object.keys(mounts || {}).length > 0;
}
export function zenfs_get_export(name) {
return zenfsModule ? zenfsModule[name] : undefined;
}
export function zenfs_call_sync(name, args) {
const fn = requireZenFs()[name];
if (typeof fn !== "function") throw new TypeError(`ZenFS export ${name} is not a function`);
return fn(...args);
}
export async function zenfs_call_async(name, args) {
let module = zenfsModule || await zenfsModulePromise;
if (!module && canResolveZenFs()) {
module = await import("@zenfs/core").then((loaded) => (zenfsModule = loaded, loaded)).catch(() => null);
}
if (!module) throw new Error("ZenFS is not available; enable the webfs feature to use its fallback");
const fn = module[name];
if (typeof fn !== "function") throw new TypeError(`ZenFS export ${name} is not a function`);
return fn(...args);
}
"#)]
extern "C" {
fn zenfs_is_configured() -> bool;
fn zenfs_get_export(name: &str) -> JsValue;
#[wasm_bindgen(catch)]
fn zenfs_call_sync(name: &str, args: &Array) -> Result<JsValue, JsValue>;
#[wasm_bindgen(catch)]
fn zenfs_call_async(name: &str, args: &Array) -> Result<js_sys::Promise, JsValue>;
}
#[cfg(not(test))]
struct ZenFsExport(&'static str);
#[cfg(not(test))]
impl ZenFsExport {
fn with<R>(&self, f: impl FnOnce(&JsValue) -> R) -> R {
let value = zenfs_get_export(self.0);
f(&value)
}
}
#[cfg(not(test))]
const ZEN_FS: ZenFsExport = ZenFsExport("fs");
#[cfg(not(test))]
const ZEN_MOUNTS: ZenFsExport = ZenFsExport("mounts");
#[cfg(not(test))]
const ZEN_PROMISES: ZenFsExport = ZenFsExport("promises");
#[cfg(not(test))]
const ZEN_DEFAULT: ZenFsExport = ZenFsExport("default");
#[cfg(not(test))]
const ZEN_VFS: ZenFsExport = ZenFsExport("vfs");
#[cfg(not(test))]
const ZEN_VERSION: ZenFsExport = ZenFsExport("version");
#[cfg(not(test))]
const ZEN_CONSTANTS: ZenFsExport = ZenFsExport("constants");
#[cfg(not(test))]
fn call_zenfs_sync(name: &str, args: &[JsValue]) -> Result<JsValue, JsValue> {
zenfs_call_sync(name, &Array::from_iter(args.iter().cloned()))
}
#[cfg(not(test))]
fn call_zenfs_async(name: &str, args: &[JsValue]) -> Result<js_sys::Promise, JsValue> {
zenfs_call_async(name, &Array::from_iter(args.iter().cloned()))
}
#[cfg(all(not(test), feature = "webfs", feature = "zenfs"))]
pub fn is_configured() -> bool {
zenfs_is_configured()
}
#[cfg(all(test, feature = "webfs", feature = "zenfs"))]
pub fn is_configured() -> bool {
true
}
#[cfg(not(test))]
fn zenfs_configure(configuration: &JsValue) -> Result<js_sys::Promise, JsValue> {
call_zenfs_async("configure", &[configuration.clone()])
}
#[cfg(not(test))]
fn zenfs_configure_sync(configuration: &JsValue) -> Result<(), JsValue> {
call_zenfs_sync("configureSync", &[configuration.clone()]).map(|_| ())
}
#[cfg(not(test))]
fn zenfs_configure_single(configuration: &JsValue) -> Result<js_sys::Promise, JsValue> {
call_zenfs_async("configureSingle", &[configuration.clone()])
}
#[cfg(not(test))]
fn zenfs_configure_single_sync(configuration: &JsValue) -> Result<(), JsValue> {
call_zenfs_sync("configureSingleSync", &[configuration.clone()]).map(|_| ())
}
#[cfg(not(test))]
fn zenfs_configure_file_system(
filesystem: &JsValue,
configuration: &JsValue,
) -> Result<(), JsValue> {
call_zenfs_sync(
"configureFileSystem",
&[filesystem.clone(), configuration.clone()],
)
.map(|_| ())
}
#[cfg(not(test))]
fn zenfs_resolve_mount_config(configuration: &JsValue) -> Result<js_sys::Promise, JsValue> {
call_zenfs_async("resolveMountConfig", &[configuration.clone()])
}
#[cfg(not(test))]
fn zenfs_resolve_mount_config_sync(configuration: &JsValue) -> Result<JsValue, JsValue> {
call_zenfs_sync("resolveMountConfigSync", &[configuration.clone()])
}
#[cfg(not(test))]
fn zenfs_resolve_remote_mount(
channel: &JsValue,
configuration: &JsValue,
) -> Result<js_sys::Promise, JsValue> {
call_zenfs_async(
"resolveRemoteMount",
&[channel.clone(), configuration.clone()],
)
}
#[cfg(not(test))]
fn zenfs_mount(mount_point: &str, filesystem: &JsValue) -> Result<(), JsValue> {
call_zenfs_sync(
"mount",
&[JsValue::from_str(mount_point), filesystem.clone()],
)
.map(|_| ())
}
#[cfg(not(test))]
fn zenfs_umount(mount_point: &str) -> Result<(), JsValue> {
call_zenfs_sync("umount", &[JsValue::from_str(mount_point)]).map(|_| ())
}
#[cfg(not(test))]
fn zenfs_sync() -> Result<js_sys::Promise, JsValue> {
call_zenfs_async("sync", &[])
}
#[cfg(not(test))]
fn zenfs_wait_online(worker: &JsValue) -> Result<js_sys::Promise, JsValue> {
call_zenfs_async("waitOnline", &[worker.clone()])
}
#[cfg(not(test))]
fn zenfs_attach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
call_zenfs_sync("attachFS", &[channel.clone(), filesystem.clone()]).map(|_| ())
}
#[cfg(not(test))]
fn zenfs_detach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
call_zenfs_sync("detachFS", &[channel.clone(), filesystem.clone()]).map(|_| ())
}
#[cfg(not(test))]
fn zenfs_glob_to_regex(pattern: &str) -> Result<JsValue, JsValue> {
call_zenfs_sync("globToRegex", &[JsValue::from_str(pattern)])
}
#[cfg(not(test))]
fn zenfs_normalize_path(path: &str) -> Result<String, JsValue> {
call_zenfs_sync("normalizePath", &[JsValue::from_str(path)])?
.as_string()
.ok_or_else(|| JsValue::from_str("ZenFS normalizePath did not return a string"))
}
#[cfg(test)]
zenfs_setup_imports!("https://esm.sh/@zenfs/core@2.7.6?bundle&target=es2022");
async fn await_zenfs_promise(promise: js_sys::Promise) -> Result<JsValue, JsValue> {
JsFuture::from(promise).await
}
#[wasm_bindgen]
pub async fn configure(configuration: &JsValue) -> Result<(), JsValue> {
await_zenfs_promise(zenfs_configure(configuration)?).await?;
Ok(())
}
#[wasm_bindgen(js_name = configureSync)]
pub fn configure_sync(configuration: &JsValue) -> Result<(), JsValue> {
zenfs_configure_sync(configuration)
}
#[wasm_bindgen(js_name = configureSingle)]
pub async fn configure_single(configuration: &JsValue) -> Result<(), JsValue> {
await_zenfs_promise(zenfs_configure_single(configuration)?).await?;
Ok(())
}
#[wasm_bindgen(js_name = configureSingleSync)]
pub fn configure_single_sync(configuration: &JsValue) -> Result<(), JsValue> {
zenfs_configure_single_sync(configuration)
}
#[wasm_bindgen(js_name = configureFileSystem)]
pub fn configure_file_system(filesystem: &JsValue, configuration: &JsValue) -> Result<(), JsValue> {
zenfs_configure_file_system(filesystem, configuration)
}
#[wasm_bindgen(js_name = resolveMountConfig)]
pub async fn resolve_mount_config(configuration: &JsValue) -> Result<JsValue, JsValue> {
await_zenfs_promise(zenfs_resolve_mount_config(configuration)?).await
}
#[wasm_bindgen(js_name = resolveMountConfigSync)]
pub fn resolve_mount_config_sync(configuration: &JsValue) -> Result<JsValue, JsValue> {
zenfs_resolve_mount_config_sync(configuration)
}
#[wasm_bindgen(js_name = resolveRemoteMount)]
pub async fn resolve_remote_mount(
channel: &JsValue,
configuration: &JsValue,
) -> Result<JsValue, JsValue> {
await_zenfs_promise(zenfs_resolve_remote_mount(channel, configuration)?).await
}
#[wasm_bindgen]
pub fn mount(mount_point: &str, filesystem: &JsValue) -> Result<(), JsValue> {
zenfs_mount(mount_point, filesystem)
}
#[wasm_bindgen]
pub fn umount(mount_point: &str) -> Result<(), JsValue> {
zenfs_umount(mount_point)
}
#[wasm_bindgen]
pub fn mounts() -> JsValue {
ZEN_MOUNTS.with(JsValue::clone)
}
#[wasm_bindgen]
pub async fn sync() -> Result<(), JsValue> {
await_zenfs_promise(zenfs_sync()?).await?;
Ok(())
}
#[wasm_bindgen(js_name = waitOnline)]
pub async fn wait_online(worker: &JsValue) -> Result<(), JsValue> {
await_zenfs_promise(zenfs_wait_online(worker)?).await?;
Ok(())
}
#[wasm_bindgen(js_name = attachFS)]
pub fn attach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
zenfs_attach_fs(channel, filesystem)
}
#[wasm_bindgen(js_name = detachFS)]
pub fn detach_fs(channel: &JsValue, filesystem: &JsValue) -> Result<(), JsValue> {
zenfs_detach_fs(channel, filesystem)
}
#[wasm_bindgen(js_name = fs)]
pub fn zenfs_fs() -> JsValue {
ZEN_FS.with(JsValue::clone)
}
#[wasm_bindgen]
pub fn promises() -> JsValue {
ZEN_PROMISES.with(JsValue::clone)
}
#[wasm_bindgen(js_name = defaultFs)]
pub fn default_fs() -> JsValue {
ZEN_DEFAULT.with(JsValue::clone)
}
#[wasm_bindgen]
pub fn vfs() -> JsValue {
ZEN_VFS.with(JsValue::clone)
}
#[wasm_bindgen]
pub fn version() -> JsValue {
ZEN_VERSION.with(JsValue::clone)
}
#[wasm_bindgen]
pub fn constants() -> JsValue {
ZEN_CONSTANTS.with(JsValue::clone)
}
fn call_fs(method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
let fs = ZEN_FS.with(JsValue::clone);
let method = Reflect::get(&fs, &JsValue::from_str(method))?;
let method = method
.dyn_into::<Function>()
.map_err(|_| JsValue::from_str("ZenFS method is not a function"))?;
let arguments = Array::from_iter(arguments.iter().cloned());
method.apply(&fs, &arguments)
}
async fn call_fs_promise(method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
let fs = ZEN_FS.with(JsValue::clone);
let promises = Reflect::get(&fs, &JsValue::from_str("promises"))?;
let method = Reflect::get(&promises, &JsValue::from_str(method))?
.dyn_into::<Function>()
.map_err(|_| JsValue::from_str("ZenFS promise method is not a function"))?;
let arguments = Array::from_iter(arguments.iter().cloned());
let promise = method
.apply(&promises, &arguments)?
.dyn_into::<js_sys::Promise>()?;
JsFuture::from(promise).await
}
async fn call_fs_callback(method_name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
let fs = ZEN_FS.with(JsValue::clone);
let method = Reflect::get(&fs, &JsValue::from_str(method_name))?
.dyn_into::<Function>()
.map_err(|_| JsValue::from_str("ZenFS callback method is not a function"))?;
let arguments = Array::from_iter(arguments.iter().cloned());
let promise = js_sys::Promise::new(&mut |resolve, reject| {
let callback_resolve = resolve.clone();
let callback_reject = reject.clone();
let callback = Closure::once_into_js(move |error: JsValue, value: JsValue| {
if error.is_null() || error.is_undefined() {
let _ = callback_resolve.call1(&JsValue::UNDEFINED, &value);
} else {
let _ = callback_reject.call1(&JsValue::UNDEFINED, &error);
}
});
arguments.push(&callback);
if let Err(error) = method.apply(&fs, &arguments) {
let _ = reject.call1(&JsValue::UNDEFINED, &error);
}
});
JsFuture::from(promise).await
}
fn mkdir_options(recursive: bool) -> Result<JsValue, JsValue> {
let options = Object::new();
Reflect::set(
&options,
&JsValue::from_str("recursive"),
&JsValue::from_bool(recursive),
)?;
Ok(options.into())
}
fn removal_options(recursive: bool, force: bool) -> Result<JsValue, JsValue> {
let options = Object::new();
Reflect::set(
&options,
&JsValue::from_str("recursive"),
&JsValue::from_bool(recursive),
)?;
Reflect::set(
&options,
&JsValue::from_str("force"),
&JsValue::from_bool(force),
)?;
Ok(options.into())
}
fn returned_string(value: JsValue, method: &str) -> Result<String, JsValue> {
value
.as_string()
.ok_or_else(|| JsValue::from_str(&format!("ZenFS {method} did not return a string")))
}
fn returned_names(value: JsValue) -> Result<Vec<String>, JsValue> {
Array::from(&value)
.iter()
.map(|value| returned_string(value, "directory listing"))
.collect()
}
fn descriptor_value(fd: &File) -> JsValue {
JsValue::from_f64(f64::from(*fd))
}
fn returned_usize(value: JsValue, operation: &str) -> Result<usize, JsValue> {
value
.as_f64()
.filter(|value| value.is_finite() && *value >= 0.0)
.map(|value| value as usize)
.ok_or_else(|| JsValue::from_str(&format!("ZenFS {operation} did not return a byte count")))
}
fn returned_descriptor(value: JsValue) -> Result<File, JsValue> {
value
.as_f64()
.filter(|fd| fd.is_finite() && *fd >= 0.0 && *fd <= f64::from(u32::MAX))
.map(|fd| fd as u32)
.ok_or_else(|| JsValue::from_str("ZenFS open did not return a file descriptor"))
}
fn open_flags(options: &OpenOptions) -> Result<&'static str, JsValue> {
if !options.read && !options.write && !options.append {
return Err(JsValue::from_str(
"at least one file access mode is required",
));
}
if options.truncate && !options.write && !options.append && !options.create_new {
return Err(JsValue::from_str("truncate requires write access"));
}
if options.create && !options.write && !options.append {
return Err(JsValue::from_str("create requires write or append access"));
}
if options.create_new && !options.write && !options.append {
return Err(JsValue::from_str(
"create_new requires write or append access",
));
}
Ok(if options.append {
match (options.read, options.create_new) {
(true, true) => "ax+",
(false, true) => "ax",
(true, false) => "a+",
(false, false) => "a",
}
} else if options.create_new {
if options.read { "wx+" } else { "wx" }
} else if options.truncate || options.create {
if options.read { "w+" } else { "w" }
} else if options.write {
"r+"
} else {
"r"
})
}
#[wasm_bindgen(js_name = appDir)]
pub fn app_dir(name: &str) -> Result<String, JsValue> {
if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\\') {
return Err(JsValue::from_str(
"application name must be a single path component",
));
}
let path = format!("/app/{name}");
let options = mkdir_options(true)?;
call_fs("mkdirSync", &[JsValue::from_str(&path), options])?;
Ok(path)
}
#[wasm_bindgen(js_name = exists)]
pub async fn exists(path: &str) -> Result<bool, JsValue> {
call_fs_promise("exists", &[JsValue::from_str(path)])
.await?
.as_bool()
.ok_or_else(|| JsValue::from_str("ZenFS exists did not return a boolean"))
}
pub fn exists_sync(path: &str) -> Result<bool, JsValue> {
call_fs("existsSync", &[JsValue::from_str(path)])?
.as_bool()
.ok_or_else(|| JsValue::from_str("ZenFS existsSync did not return a boolean"))
}
pub async fn access(path: &str, mode: u32) -> Result<(), JsValue> {
call_fs_promise(
"access",
&[JsValue::from_str(path), JsValue::from_f64(f64::from(mode))],
)
.await?;
Ok(())
}
pub fn access_sync(path: &str, mode: u32) -> Result<(), JsValue> {
call_fs(
"accessSync",
&[JsValue::from_str(path), JsValue::from_f64(f64::from(mode))],
)?;
Ok(())
}
#[wasm_bindgen(js_name = readText)]
pub fn read_text(path: &str) -> Result<String, JsValue> {
call_fs(
"readFileSync",
&[JsValue::from_str(path), JsValue::from_str("utf8")],
)?
.as_string()
.ok_or_else(|| JsValue::from_str("ZenFS did not return a UTF-8 string"))
}
#[wasm_bindgen(js_name = writeText)]
pub fn write_text(path: &str, contents: &str) -> Result<(), JsValue> {
call_fs(
"writeFileSync",
&[JsValue::from_str(path), JsValue::from_str(contents)],
)?;
Ok(())
}
#[wasm_bindgen(js_name = appendText)]
pub fn append_text(path: &str, contents: &str) -> Result<(), JsValue> {
call_fs(
"appendFileSync",
&[JsValue::from_str(path), JsValue::from_str(contents)],
)?;
Ok(())
}
pub async fn append_file(path: &str, contents: &[u8]) -> Result<(), JsValue> {
let contents = Uint8Array::from(contents);
call_fs_promise("appendFile", &[JsValue::from_str(path), contents.into()]).await?;
Ok(())
}
pub fn append_file_sync(path: &str, contents: &[u8]) -> Result<(), JsValue> {
let contents = Uint8Array::from(contents);
call_fs(
"appendFileSync",
&[JsValue::from_str(path), contents.into()],
)?;
Ok(())
}
#[wasm_bindgen(js_name = readFile)]
pub async fn read_file(path: &str) -> Result<Vec<u8>, JsValue> {
let contents = call_fs_promise("readFile", &[JsValue::from_str(path)]).await?;
Ok(Uint8Array::new(&contents).to_vec())
}
pub fn read_file_sync(path: &str) -> Result<Vec<u8>, JsValue> {
let contents = call_fs("readFileSync", &[JsValue::from_str(path)])?;
Ok(Uint8Array::new(&contents).to_vec())
}
#[wasm_bindgen(js_name = writeFile)]
pub async fn write_file(path: &str, contents: &[u8]) -> Result<(), JsValue> {
let contents = Uint8Array::from(contents);
call_fs_promise("writeFile", &[JsValue::from_str(path), contents.into()]).await?;
Ok(())
}
pub fn write_file_sync(path: &str, contents: &[u8]) -> Result<(), JsValue> {
let contents = Uint8Array::from(contents);
call_fs("writeFileSync", &[JsValue::from_str(path), contents.into()])?;
Ok(())
}
#[wasm_bindgen(js_name = copyFile)]
pub async fn copy_file(from: &str, to: &str) -> Result<(), JsValue> {
call_fs_promise(
"copyFile",
&[JsValue::from_str(from), JsValue::from_str(to)],
)
.await?;
Ok(())
}
pub fn copy_file_sync(from: &str, to: &str) -> Result<(), JsValue> {
call_fs(
"copyFileSync",
&[JsValue::from_str(from), JsValue::from_str(to)],
)?;
Ok(())
}
pub async fn cp(from: &str, to: &str) -> Result<(), JsValue> {
let options = Object::new();
Reflect::set(&options, &JsValue::from_str("recursive"), &JsValue::TRUE)?;
call_fs_promise(
"cp",
&[
JsValue::from_str(from),
JsValue::from_str(to),
options.into(),
],
)
.await?;
Ok(())
}
pub fn cp_sync(from: &str, to: &str) -> Result<(), JsValue> {
let options = Object::new();
Reflect::set(&options, &JsValue::from_str("recursive"), &JsValue::TRUE)?;
call_fs(
"cpSync",
&[
JsValue::from_str(from),
JsValue::from_str(to),
options.into(),
],
)?;
Ok(())
}
pub fn open_sync(path: &str, options: &OpenOptions) -> Result<File, JsValue> {
let flags = open_flags(options)?;
if options.append && !options.create && !options.create_new {
let exists = call_fs("existsSync", &[JsValue::from_str(path)])?
.as_bool()
.ok_or_else(|| JsValue::from_str("ZenFS existsSync did not return a boolean"))?;
if !exists {
let descriptor = call_fs(
"openSync",
&[JsValue::from_str(path), JsValue::from_str("r")],
)?;
call_fs("closeSync", &[descriptor])?;
}
}
let descriptor =
if options.create && !options.create_new && !options.truncate && !options.append {
match call_fs(
"openSync",
&[JsValue::from_str(path), JsValue::from_str("r+")],
) {
Ok(descriptor) => descriptor,
Err(error) if is_no_entry(&error) => call_fs(
"openSync",
&[JsValue::from_str(path), JsValue::from_str("w+")],
)?,
Err(error) => return Err(error),
}
} else if options.truncate && !options.create && !options.create_new && !options.append {
let descriptor = call_fs(
"openSync",
&[JsValue::from_str(path), JsValue::from_str("r+")],
)?;
let descriptor = descriptor
.as_f64()
.filter(|fd| fd.is_finite() && *fd >= 0.0 && *fd <= f64::from(u32::MAX))
.ok_or_else(|| {
JsValue::from_str("ZenFS openSync did not return a file descriptor")
})? as u32;
if let Err(error) = call_fs(
"ftruncateSync",
&[
JsValue::from_f64(f64::from(descriptor)),
JsValue::from_f64(0.0),
],
) {
let _ = call_fs("closeSync", &[JsValue::from_f64(f64::from(descriptor))]);
return Err(error);
}
return Ok(descriptor);
} else {
call_fs(
"openSync",
&[JsValue::from_str(path), JsValue::from_str(flags)],
)?
};
let descriptor = descriptor
.as_f64()
.filter(|fd| fd.is_finite() && *fd >= 0.0 && *fd <= f64::from(u32::MAX))
.ok_or_else(|| JsValue::from_str("ZenFS openSync did not return a file descriptor"))?;
let descriptor = descriptor as u32;
if options.truncate
&& options.append
&& let Err(error) = call_fs(
"ftruncateSync",
&[
JsValue::from_f64(f64::from(descriptor)),
JsValue::from_f64(0.0),
],
)
{
let _ = call_fs("closeSync", &[JsValue::from_f64(f64::from(descriptor))]);
return Err(error);
}
Ok(descriptor)
}
pub async fn open(path: &str, options: &OpenOptions) -> Result<File, JsValue> {
let flags = open_flags(options)?;
if options.append && !options.create && !options.create_new {
let exists = call_fs_promise("exists", &[JsValue::from_str(path)])
.await?
.as_bool()
.ok_or_else(|| JsValue::from_str("ZenFS exists did not return a boolean"))?;
if !exists {
let descriptor =
call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("r")])
.await?;
call_fs_callback("close", &[descriptor]).await?;
}
}
let descriptor = if options.create
&& !options.create_new
&& !options.truncate
&& !options.append
{
match call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("r+")]).await {
Ok(descriptor) => descriptor,
Err(error) if is_no_entry(&error) => {
call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("w+")])
.await?
}
Err(error) => return Err(error),
}
} else if options.truncate && !options.create && !options.create_new && !options.append {
let descriptor =
call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str("r+")]).await?;
if let Err(error) =
call_fs_callback("ftruncate", &[descriptor.clone(), JsValue::from_f64(0.0)]).await
{
let _ = call_fs_callback("close", &[descriptor]).await;
return Err(error);
}
descriptor
} else {
call_fs_callback("open", &[JsValue::from_str(path), JsValue::from_str(flags)]).await?
};
let descriptor = returned_descriptor(descriptor)?;
if options.truncate
&& options.append
&& let Err(error) = call_fs_callback(
"ftruncate",
&[
JsValue::from_f64(f64::from(descriptor)),
JsValue::from_f64(0.0),
],
)
.await
{
let _ = call_fs_callback("close", &[JsValue::from_f64(f64::from(descriptor))]).await;
return Err(error);
}
Ok(descriptor)
}
fn is_no_entry(error: &JsValue) -> bool {
Reflect::get(error, &JsValue::from_str("code"))
.ok()
.and_then(|code| code.as_string())
.as_deref()
== Some("ENOENT")
}
pub async fn open_as_blob(path: &str) -> Result<Vec<u8>, JsValue> {
let result = call_fs("openAsBlob", &[JsValue::from_str(path)])?;
let promise = result
.dyn_into::<js_sys::Promise>()
.map_err(|_| JsValue::from_str("ZenFS openAsBlob did not return a promise"))?;
let blob = JsFuture::from(promise).await?;
let array_buffer = Reflect::get(&blob, &JsValue::from_str("arrayBuffer"))?
.dyn_into::<Function>()
.map_err(|_| JsValue::from_str("ZenFS openAsBlob did not return a Blob"))?;
let array_buffer = array_buffer.call0(&blob)?.dyn_into::<js_sys::Promise>()?;
let buffer = JsFuture::from(array_buffer).await?;
Ok(Uint8Array::new(&buffer).to_vec())
}
pub fn close_sync(file: File) -> Result<(), JsValue> {
call_fs("closeSync", &[descriptor_value(&file)])?;
Ok(())
}
pub async fn close(file: &File) -> Result<(), JsValue> {
call_fs_callback("close", &[descriptor_value(file)]).await?;
Ok(())
}
pub fn read_sync(file: &mut File, buffer: &mut [u8]) -> Result<usize, JsValue> {
let target = Uint8Array::new_with_length(buffer.len() as u32);
let count = call_fs(
"readSync",
&[
descriptor_value(file),
target.clone().into(),
JsValue::from_f64(0.0),
JsValue::from_f64(buffer.len() as f64),
JsValue::NULL,
],
)?;
let count = returned_usize(count, "readSync")?;
let count = count.min(buffer.len());
target
.subarray(0, count as u32)
.copy_to(&mut buffer[..count]);
Ok(count)
}
pub async fn read(file: &mut File, buffer: &mut [u8]) -> Result<usize, JsValue> {
let target = Uint8Array::new_with_length(buffer.len() as u32);
let count = call_fs_callback(
"read",
&[
descriptor_value(file),
target.clone().into(),
JsValue::from_f64(0.0),
JsValue::from_f64(buffer.len() as f64),
JsValue::NULL,
],
)
.await?;
let count = returned_usize(count, "read")?.min(buffer.len());
target
.subarray(0, count as u32)
.copy_to(&mut buffer[..count]);
Ok(count)
}
pub fn write_sync(file: &mut File, buffer: &[u8]) -> Result<usize, JsValue> {
let contents = Uint8Array::from(buffer);
let count = call_fs(
"writeSync",
&[
descriptor_value(file),
contents.into(),
JsValue::from_f64(0.0),
JsValue::from_f64(buffer.len() as f64),
JsValue::NULL,
],
)?;
returned_usize(count, "writeSync")
}
pub async fn write(file: &mut File, buffer: &[u8]) -> Result<usize, JsValue> {
let contents = Uint8Array::from(buffer);
let count = call_fs_callback(
"write",
&[
descriptor_value(file),
contents.into(),
JsValue::from_f64(0.0),
JsValue::from_f64(buffer.len() as f64),
JsValue::NULL,
],
)
.await?;
returned_usize(count, "write")
}
pub fn readv_sync(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> Result<usize, JsValue> {
let arrays = buffers
.iter()
.map(|buffer| Uint8Array::from(&buffer[..]))
.collect::<Vec<_>>();
let js_buffers = Array::new();
for buffer in &arrays {
js_buffers.push(buffer);
}
let count = call_fs(
"readvSync",
&[descriptor_value(file), js_buffers.into(), JsValue::NULL],
)?;
let count = returned_usize(count, "readvSync")?;
let mut remaining = count;
for (target, source) in buffers.iter_mut().zip(arrays.iter()) {
let copied = remaining.min(target.len());
source
.subarray(0, copied as u32)
.copy_to(&mut target[..copied]);
remaining -= copied;
if remaining == 0 {
break;
}
}
Ok(count)
}
pub async fn readv(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> Result<usize, JsValue> {
let arrays = buffers
.iter()
.map(|buffer| Uint8Array::from(&buffer[..]))
.collect::<Vec<_>>();
let js_buffers = Array::new();
for buffer in &arrays {
js_buffers.push(buffer);
}
let count = call_fs_callback(
"readv",
&[descriptor_value(file), js_buffers.into(), JsValue::NULL],
)
.await?;
let count = returned_usize(count, "readv")?;
let mut remaining = count;
for (target, source) in buffers.iter_mut().zip(arrays.iter()) {
let copied = remaining.min(target.len());
source
.subarray(0, copied as u32)
.copy_to(&mut target[..copied]);
remaining -= copied;
if remaining == 0 {
break;
}
}
Ok(count)
}
pub fn writev_sync(file: &mut File, buffers: &[IoSlice<'_>]) -> Result<usize, JsValue> {
let js_buffers = Array::new();
for buffer in buffers {
js_buffers.push(&Uint8Array::from(&buffer[..]));
}
let count = call_fs(
"writevSync",
&[descriptor_value(file), js_buffers.into(), JsValue::NULL],
)?;
returned_usize(count, "writevSync")
}
pub async fn writev(file: &mut File, buffers: &[IoSlice<'_>]) -> Result<usize, JsValue> {
let js_buffers = Array::new();
for buffer in buffers {
js_buffers.push(&Uint8Array::from(&buffer[..]));
}
let count = call_fs_callback(
"writev",
&[descriptor_value(file), js_buffers.into(), JsValue::NULL],
)
.await?;
returned_usize(count, "writev")
}
fn stats_bool(stats: &JsValue, name: &str) -> Result<bool, JsValue> {
let member = Reflect::get(stats, &JsValue::from_str(name))?;
if let Ok(method) = member.clone().dyn_into::<Function>() {
method
.call0(stats)?
.as_bool()
.ok_or_else(|| JsValue::from_str("ZenFS stat method did not return a boolean"))
} else {
member
.as_bool()
.ok_or_else(|| JsValue::from_str("ZenFS stat property was not a boolean"))
}
}
fn metadata_from_stats(stats: &JsValue) -> Result<Metadata, JsValue> {
let len = Reflect::get(stats, &JsValue::from_str("size"))?
.as_f64()
.filter(|size| size.is_finite() && *size >= 0.0)
.map(|size| size as u64)
.ok_or_else(|| JsValue::from_str("ZenFS stat size was not a non-negative number"))?;
Ok(Metadata::from_parts(
len,
stats_bool(stats, "isFile")?,
stats_bool(stats, "isDirectory")?,
stats_bool(stats, "isSymbolicLink")?,
))
}
fn statfs_field(stats: &JsValue, field: &str) -> Result<f64, JsValue> {
let value = Reflect::get(stats, &JsValue::from_str(field))?;
value
.as_f64()
.filter(|value| value.is_finite() && *value >= 0.0)
.ok_or_else(|| {
JsValue::from_str(&format!(
"ZenFS statfs field {field} was not a non-negative number: {value:?}"
))
})
}
fn statfs_from_stats(stats: &JsValue) -> Result<StatFs, JsValue> {
Ok(StatFs {
block_size: statfs_field(stats, "bsize")? as u64,
blocks: statfs_field(stats, "blocks")?,
blocks_free: statfs_field(stats, "bfree")?,
blocks_available: statfs_field(stats, "bavail")?,
files: statfs_field(stats, "files")?,
files_free: statfs_field(stats, "ffree")?,
})
}
fn js_time(time: SystemTime) -> JsValue {
let seconds = match time.duration_since(UNIX_EPOCH) {
Ok(duration) => duration.as_secs_f64(),
Err(error) => -error.duration().as_secs_f64(),
};
JsValue::from_f64(seconds)
}
fn number(value: u32) -> JsValue {
JsValue::from_f64(f64::from(value))
}
macro_rules! path_metadata {
($async_name:ident, $sync_name:ident, $js_name:literal, $js_sync:literal, $output:ty, $convert:ident) => {
pub fn $sync_name(path: &str) -> Result<$output, JsValue> {
$convert(&call_fs($js_sync, &[JsValue::from_str(path)])?)
}
pub async fn $async_name(path: &str) -> Result<$output, JsValue> {
$convert(&call_fs_promise($js_name, &[JsValue::from_str(path)]).await?)
}
};
}
path_metadata!(
stat,
stat_sync,
"stat",
"statSync",
Metadata,
metadata_from_stats
);
path_metadata!(
lstat,
lstat_sync,
"lstat",
"lstatSync",
Metadata,
metadata_from_stats
);
path_metadata!(
statfs,
statfs_sync,
"statfs",
"statfsSync",
StatFs,
statfs_from_stats
);
macro_rules! metadata_change {
($async_name:ident, $sync_name:ident, $js_name:literal, $js_sync:literal, ($($arg:ident: $type:ty => $value:expr),*)) => {
pub fn $sync_name(path: &str, $($arg: $type),*) -> Result<(), JsValue> {
call_fs($js_sync, &[JsValue::from_str(path), $($value),*])?;
Ok(())
}
pub async fn $async_name(path: &str, $($arg: $type),*) -> Result<(), JsValue> {
call_fs_promise($js_name, &[JsValue::from_str(path), $($value),*]).await?;
Ok(())
}
};
}
metadata_change!(chmod, chmod_sync, "chmod", "chmodSync", (mode: u32 => number(mode)));
metadata_change!(lchmod, lchmod_sync, "lchmod", "lchmodSync", (mode: u32 => number(mode)));
metadata_change!(chown, chown_sync, "chown", "chownSync", (uid: u32 => number(uid), gid: u32 => number(gid)));
metadata_change!(lchown, lchown_sync, "lchown", "lchownSync", (uid: u32 => number(uid), gid: u32 => number(gid)));
metadata_change!(utimes, utimes_sync, "utimes", "utimesSync", (atime: SystemTime => js_time(atime), mtime: SystemTime => js_time(mtime)));
metadata_change!(lutimes, lutimes_sync, "lutimes", "lutimesSync", (atime: SystemTime => js_time(atime), mtime: SystemTime => js_time(mtime)));
macro_rules! descriptor_metadata_change {
($async_name:ident, $sync_name:ident, $js_name:literal, $js_sync:literal, ($($arg:ident: $type:ty => $value:expr),*)) => {
pub fn $sync_name(file: &File, $($arg: $type),*) -> Result<(), JsValue> {
call_fs($js_sync, &[descriptor_value(file), $($value),*])?;
Ok(())
}
pub async fn $async_name(file: &File, $($arg: $type),*) -> Result<(), JsValue> {
call_fs_callback($js_name, &[descriptor_value(file), $($value),*]).await?;
Ok(())
}
};
}
descriptor_metadata_change!(fchmod, fchmod_sync, "fchmod", "fchmodSync", (mode: u32 => number(mode)));
descriptor_metadata_change!(fchown, fchown_sync, "fchown", "fchownSync", (uid: u32 => number(uid), gid: u32 => number(gid)));
descriptor_metadata_change!(futimes, futimes_sync, "futimes", "futimesSync", (atime: SystemTime => js_time(atime), mtime: SystemTime => js_time(mtime)));
pub fn fstat_sync(file: &File) -> Result<Metadata, JsValue> {
let stats = call_fs("fstatSync", &[descriptor_value(file)])?;
metadata_from_stats(&stats)
}
pub async fn fstat(file: &File) -> Result<Metadata, JsValue> {
let stats = call_fs_callback("fstat", &[descriptor_value(file)]).await?;
metadata_from_stats(&stats)
}
pub fn fsync_sync(file: &File) -> Result<(), JsValue> {
call_fs("fsyncSync", &[descriptor_value(file)])?;
Ok(())
}
pub async fn fsync(file: &File) -> Result<(), JsValue> {
call_fs_callback("fsync", &[descriptor_value(file)]).await?;
Ok(())
}
pub fn fdatasync_sync(file: &File) -> Result<(), JsValue> {
call_fs("fdatasyncSync", &[descriptor_value(file)])?;
Ok(())
}
pub async fn fdatasync(file: &File) -> Result<(), JsValue> {
call_fs_callback("fdatasync", &[descriptor_value(file)]).await?;
Ok(())
}
pub fn ftruncate_sync(file: &File, size: u64) -> Result<(), JsValue> {
call_fs(
"ftruncateSync",
&[descriptor_value(file), JsValue::from_f64(size as f64)],
)?;
Ok(())
}
pub async fn ftruncate(file: &File, size: u64) -> Result<(), JsValue> {
call_fs_callback(
"ftruncate",
&[descriptor_value(file), JsValue::from_f64(size as f64)],
)
.await?;
Ok(())
}
pub fn truncate_sync(path: &str, len: u64) -> Result<(), JsValue> {
call_fs(
"truncateSync",
&[JsValue::from_str(path), JsValue::from_f64(len as f64)],
)?;
Ok(())
}
pub async fn truncate(path: &str, len: u64) -> Result<(), JsValue> {
call_fs_promise(
"truncate",
&[JsValue::from_str(path), JsValue::from_f64(len as f64)],
)
.await?;
Ok(())
}
#[wasm_bindgen(js_name = createDir)]
pub fn create_dir(path: &str) -> Result<(), JsValue> {
let options = mkdir_options(false)?;
call_fs("mkdirSync", &[JsValue::from_str(path), options])?;
Ok(())
}
#[wasm_bindgen(js_name = createDirAll)]
pub fn create_dir_all(path: &str) -> Result<(), JsValue> {
let options = mkdir_options(true)?;
call_fs("mkdirSync", &[JsValue::from_str(path), options])?;
Ok(())
}
#[wasm_bindgen(js_name = readDir)]
pub fn read_dir(path: &str) -> Result<Vec<String>, JsValue> {
readdir_sync(path)
}
pub fn mkdir_sync(path: &str, recursive: bool) -> Result<(), JsValue> {
call_fs(
"mkdirSync",
&[JsValue::from_str(path), mkdir_options(recursive)?],
)?;
Ok(())
}
pub async fn mkdir(path: &str, recursive: bool) -> Result<(), JsValue> {
call_fs_promise(
"mkdir",
&[JsValue::from_str(path), mkdir_options(recursive)?],
)
.await?;
Ok(())
}
pub fn mkdtemp_sync(prefix: &str) -> Result<String, JsValue> {
returned_string(
call_fs("mkdtempSync", &[JsValue::from_str(prefix)])?,
"mkdtempSync",
)
}
pub async fn mkdtemp(prefix: &str) -> Result<String, JsValue> {
returned_string(
call_fs_promise("mkdtemp", &[JsValue::from_str(prefix)]).await?,
"mkdtemp",
)
}
pub fn mkdtemp_disposable_sync(prefix: &str) -> Result<TempDir, JsValue> {
let value = call_fs("mkdtempDisposableSync", &[JsValue::from_str(prefix)])?;
let path = returned_string(
Reflect::get(&value, &JsValue::from_str("path"))?,
"mkdtempDisposableSync",
)?;
Ok(TempDir { path })
}
pub fn readdir_sync(path: &str) -> Result<Vec<String>, JsValue> {
returned_names(call_fs("readdirSync", &[JsValue::from_str(path)])?)
}
pub async fn readdir(path: &str) -> Result<Vec<String>, JsValue> {
returned_names(call_fs_promise("readdir", &[JsValue::from_str(path)]).await?)
}
fn dir_entry(entry: JsValue) -> Result<Option<Dirent>, JsValue> {
if entry.is_null() || entry.is_undefined() {
return Ok(None);
}
let name = returned_string(
Reflect::get(&entry, &JsValue::from_str("name"))?,
"Dirent.name",
)?;
Ok(Some(Dirent::from_parts(
name,
stats_bool(&entry, "isFile")?,
stats_bool(&entry, "isDirectory")?,
stats_bool(&entry, "isSymbolicLink")?,
)))
}
pub fn dir_read_sync(dir: &mut Dir) -> Result<Option<Dirent>, JsValue> {
let read = Reflect::get(dir, &JsValue::from_str("readSync"))?.dyn_into::<Function>()?;
dir_entry(read.call0(dir)?)
}
pub async fn dir_read(dir: &mut Dir) -> Result<Option<Dirent>, JsValue> {
let read = Reflect::get(dir, &JsValue::from_str("read"))?.dyn_into::<Function>()?;
let promise = read.call0(dir)?.dyn_into::<js_sys::Promise>()?;
dir_entry(JsFuture::from(promise).await?)
}
pub fn dir_close_sync(dir: &Dir) -> Result<(), JsValue> {
let close = Reflect::get(dir, &JsValue::from_str("closeSync"))?.dyn_into::<Function>()?;
close.call0(dir)?;
Ok(())
}
pub async fn dir_close(dir: &Dir) -> Result<(), JsValue> {
let close = Reflect::get(dir, &JsValue::from_str("close"))?.dyn_into::<Function>()?;
let promise = close.call0(dir)?.dyn_into::<js_sys::Promise>()?;
JsFuture::from(promise).await?;
Ok(())
}
pub fn open_dir_sync(path: &str) -> Result<Dir, JsValue> {
call_fs("opendirSync", &[JsValue::from_str(path)])
}
pub async fn open_dir(path: &str) -> Result<Dir, JsValue> {
call_fs_promise("opendir", &[JsValue::from_str(path)]).await
}
#[cfg(not(feature = "webfs"))]
pub fn opendir_sync(path: &str) -> Result<super::api::Dir, JsValue> {
open_dir_sync(path).map(super::api::Dir::from_inner)
}
#[cfg(not(feature = "webfs"))]
pub async fn opendir(path: &str) -> Result<super::api::Dir, JsValue> {
open_dir(path).await.map(super::api::Dir::from_inner)
}
#[cfg(all(test, feature = "webfs", feature = "zenfs"))]
pub fn opendir_sync(path: &str) -> Result<super::api::Dir, JsValue> {
let inner = crate::implementation::Dir::ZenFs(open_dir_sync(path)?);
Ok(super::api::Dir::from_inner(inner))
}
#[cfg(all(test, feature = "webfs", feature = "zenfs"))]
pub async fn opendir(path: &str) -> Result<super::api::Dir, JsValue> {
let inner = crate::implementation::Dir::ZenFs(open_dir(path).await?);
Ok(super::api::Dir::from_inner(inner))
}
pub fn rmdir_sync(path: &str) -> Result<(), JsValue> {
call_fs("rmdirSync", &[JsValue::from_str(path)])?;
Ok(())
}
pub async fn rmdir(path: &str) -> Result<(), JsValue> {
call_fs_promise("rmdir", &[JsValue::from_str(path)]).await?;
Ok(())
}
pub fn rm_sync(path: &str, recursive: bool, force: bool) -> Result<(), JsValue> {
call_fs(
"rmSync",
&[JsValue::from_str(path), removal_options(recursive, force)?],
)?;
Ok(())
}
pub async fn rm(path: &str, recursive: bool, force: bool) -> Result<(), JsValue> {
call_fs_promise(
"rm",
&[JsValue::from_str(path), removal_options(recursive, force)?],
)
.await?;
Ok(())
}
pub fn realpath_sync(path: &str) -> Result<String, JsValue> {
returned_string(
call_fs("realpathSync", &[JsValue::from_str(path)])?,
"realpathSync",
)
}
pub async fn realpath(path: &str) -> Result<String, JsValue> {
returned_string(
call_fs_promise("realpath", &[JsValue::from_str(path)]).await?,
"realpath",
)
}
pub fn glob_sync(pattern: &str) -> Result<Vec<String>, JsValue> {
returned_names(call_fs("globSync", &[JsValue::from_str(pattern)])?)
}
pub async fn glob(pattern: &str) -> Result<Vec<String>, JsValue> {
returned_names(call_fs_callback("glob", &[JsValue::from_str(pattern)]).await?)
}
pub fn glob_to_regex(pattern: &str) -> Result<String, JsValue> {
returned_string(
Reflect::get(&zenfs_glob_to_regex(pattern)?, &JsValue::from_str("source"))?,
"globToRegex",
)
}
pub fn normalize_path(path: &str) -> Result<String, JsValue> {
zenfs_normalize_path(path)
}
#[wasm_bindgen(js_name = removeFile)]
pub fn remove_file(path: &str) -> Result<(), JsValue> {
call_fs("unlinkSync", &[JsValue::from_str(path)])?;
Ok(())
}
#[wasm_bindgen(js_name = renameSync)]
pub fn rename_sync(from: &str, to: &str) -> Result<(), JsValue> {
call_fs(
"renameSync",
&[JsValue::from_str(from), JsValue::from_str(to)],
)?;
Ok(())
}
#[wasm_bindgen(js_name = rename)]
pub async fn rename(from: &str, to: &str) -> Result<(), JsValue> {
call_fs_promise("rename", &[JsValue::from_str(from), JsValue::from_str(to)]).await?;
Ok(())
}
pub fn link_sync(original: &str, link: &str) -> Result<(), JsValue> {
call_fs(
"linkSync",
&[JsValue::from_str(original), JsValue::from_str(link)],
)?;
Ok(())
}
pub async fn link(original: &str, link: &str) -> Result<(), JsValue> {
call_fs_promise(
"link",
&[JsValue::from_str(original), JsValue::from_str(link)],
)
.await?;
Ok(())
}
pub fn symlink_sync(target: &str, link: &str) -> Result<(), JsValue> {
call_fs(
"symlinkSync",
&[JsValue::from_str(target), JsValue::from_str(link)],
)?;
Ok(())
}
pub async fn symlink(target: &str, link: &str) -> Result<(), JsValue> {
call_fs_promise(
"symlink",
&[JsValue::from_str(target), JsValue::from_str(link)],
)
.await?;
Ok(())
}
pub fn readlink_sync(path: &str) -> Result<String, JsValue> {
returned_string(
call_fs("readlinkSync", &[JsValue::from_str(path)])?,
"readlinkSync",
)
}
pub async fn readlink(path: &str) -> Result<String, JsValue> {
returned_string(
call_fs_promise("readlink", &[JsValue::from_str(path)]).await?,
"readlink",
)
}
pub fn unlink_sync(path: &str) -> Result<(), JsValue> {
call_fs("unlinkSync", &[JsValue::from_str(path)])?;
Ok(())
}
pub async fn unlink(path: &str) -> Result<(), JsValue> {
call_fs_promise("unlink", &[JsValue::from_str(path)]).await?;
Ok(())
}
#[cfg(all(test, not(all(feature = "webfs", not(feature = "zenfs")))))]
mod tests {
use super::*;
use wasm_bindgen_test::wasm_bindgen_test;
fn test_path(name: &str) -> String {
create_dir_all("/app").unwrap();
format!("/app/renfs-{name}-{:x}", js_sys::Math::random().to_bits())
}
async fn wait_for_watch(milliseconds: u32) {
let promise = js_sys::Promise::new(&mut |resolve, _reject| {
let callback = Closure::once_into_js(move || {
let _ = resolve.call0(&JsValue::UNDEFINED);
});
let set_timeout = Reflect::get(&js_sys::global(), &JsValue::from_str("setTimeout"))
.unwrap()
.dyn_into::<Function>()
.unwrap();
set_timeout
.call2(
&JsValue::UNDEFINED,
&callback,
&JsValue::from_f64(f64::from(milliseconds)),
)
.unwrap();
});
JsFuture::from(promise).await.unwrap();
}
#[wasm_bindgen_test]
async fn streams_use_zenfs_read_and_write_objects() {
let root = test_path("streams");
mkdir_sync(&root, false).unwrap();
let dir = crate::Directory::new(&root).unwrap();
let mut output = dir.create_write_stream("data").unwrap();
output.write(b"abc").await.unwrap();
output.write(b"defgh").await.unwrap();
output.end().await.unwrap();
assert_eq!(dir.read_text("data").unwrap(), "abcdefgh");
let mut input = dir
.create_read_stream_with_options(
"data",
crate::ReadStreamOptions {
start: 2,
end: Some(6),
chunk_size: 2,
},
)
.unwrap();
assert_eq!(input.read().await.unwrap(), Some(b"cd".to_vec()));
assert_eq!(input.read().await.unwrap(), Some(b"ef".to_vec()));
assert_eq!(input.read().await.unwrap(), Some(b"g".to_vec()));
assert_eq!(input.read().await.unwrap(), None);
input.destroy().unwrap();
let mut replace = dir.create_write_stream("data").unwrap();
replace.write(b"!").await.unwrap();
replace.end().await.unwrap();
assert_eq!(dir.read_text("data").unwrap(), "!");
let mut positioned = dir
.create_write_stream_with_options(
"positioned",
crate::WriteStreamOptions { start: Some(2) },
)
.unwrap();
positioned.write(b"x").await.unwrap();
positioned.end().await.unwrap();
assert_eq!(dir.read_file_sync("positioned").unwrap(), b"\0\0x");
let mut abandoned = dir.create_read_stream("data").unwrap();
abandoned.destroy().unwrap();
assert!(abandoned.read().await.is_err());
let mut invalid = dir.create_write_stream("missing/child").unwrap();
assert!(invalid.write(b"bad").await.is_err());
invalid.destroy().unwrap();
rm_sync(&root, true, false).unwrap();
}
#[wasm_bindgen_test]
async fn watch_and_watch_file_notify_and_unsubscribe() {
use std::sync::{Arc, Mutex};
let root = test_path("watch");
mkdir_sync(&root, false).unwrap();
let file = format!("{root}/file");
let events = Arc::new(Mutex::new(Vec::new()));
let reported = Arc::clone(&events);
let mut watcher = crate::fs::watch(&root, move |event, name| {
reported
.lock()
.unwrap()
.push((event.to_owned(), name.to_owned()));
})
.unwrap();
write_text(&file, "a").unwrap();
wait_for_watch(50).await;
assert!(
events
.lock()
.unwrap()
.iter()
.any(|(_, name)| name == "file")
);
watcher.close().unwrap();
let first = Arc::new(Mutex::new(Vec::new()));
let second = Arc::new(Mutex::new(Vec::new()));
let options = crate::WatchFileOptions {
interval: std::time::Duration::from_millis(20),
..Default::default()
};
let reported = Arc::clone(&first);
let id = crate::fs::watch_file_with_options(&file, options, move |curr, prev| {
reported.lock().unwrap().push((curr.len(), prev.len()));
})
.unwrap();
let reported = Arc::clone(&second);
crate::fs::watch_file_with_options(&file, options, move |curr, prev| {
reported.lock().unwrap().push((curr.len(), prev.len()));
})
.unwrap();
write_text(&file, "longer").unwrap();
wait_for_watch(120).await;
assert!(first.lock().unwrap().contains(&(6, 1)));
assert!(second.lock().unwrap().contains(&(6, 1)));
crate::fs::unwatch_file_listener(&file, id).unwrap();
first.lock().unwrap().clear();
second.lock().unwrap().clear();
write_text(&file, "even longer").unwrap();
wait_for_watch(120).await;
assert!(first.lock().unwrap().is_empty());
assert!(second.lock().unwrap().contains(&(11, 6)));
crate::fs::unwatch_file(&file).unwrap();
second.lock().unwrap().clear();
write_text(&file, "gone quiet").unwrap();
wait_for_watch(70).await;
assert!(second.lock().unwrap().is_empty());
rm_sync(&root, true, false).unwrap();
}
#[wasm_bindgen_test]
fn app_dir_creates_a_directory_and_rejects_invalid_names() {
let name = format!("renfs-test-{:x}", js_sys::Math::random().to_bits());
let path = app_dir(&name).unwrap();
assert_eq!(path, format!("/app/{name}"));
assert!(exists_sync(&path).unwrap());
for invalid in ["", ".", "..", "nested/name", r"nested\name"] {
let error = app_dir(invalid).unwrap_err();
assert_eq!(
error.as_string().as_deref(),
Some("application name must be a single path component")
);
}
}
#[wasm_bindgen_test]
fn javascript_exceptions_are_returned_as_errors() {
let missing = format!("{}/missing.txt", test_path("missing"));
let error = read_text(&missing).unwrap_err();
let message = Reflect::get(&error, &JsValue::from_str("message")).unwrap();
let message = message.as_string().unwrap();
assert!(message.starts_with("ENOENT:"));
assert!(message.contains(&missing));
}
#[wasm_bindgen_test]
async fn open_as_blob_reads_a_file_snapshot() {
let path = test_path("blob");
write_file_sync(&path, b"blob contents").unwrap();
let blob = open_as_blob(&path).await.unwrap();
assert_eq!(blob, b"blob contents");
}
#[wasm_bindgen_test]
async fn promise_and_callback_filesystem_apis_are_async() {
let path = test_path("async-apis");
write_file(&path, b"async").await.unwrap();
append_file(&path, b" file").await.unwrap();
assert!(exists(&path).await.unwrap());
assert_eq!(read_file(&path).await.unwrap(), b"async file");
let mut options = OpenOptions::new();
options.read(true);
let mut file = open(&path, &options).await.unwrap();
let mut contents = [0; 10];
assert_eq!(
read(&mut file, &mut contents).await.unwrap(),
contents.len()
);
assert_eq!(&contents, b"async file");
assert_eq!(fstat(&file).await.unwrap().len(), contents.len() as u64);
close(&file).await.unwrap();
}
#[wasm_bindgen_test]
async fn directory_and_path_apis_work() {
let root = test_path("directory");
mkdir(&root, false).await.unwrap();
let nested = format!("{root}/nested");
mkdir_sync(&nested, false).unwrap();
assert_eq!(readdir_sync(&root).unwrap(), vec!["nested"]);
assert_eq!(readdir(&root).await.unwrap(), vec!["nested"]);
let mut opened = opendir_sync(&root).unwrap();
let entry = opened.read_sync().unwrap().unwrap();
assert_eq!(entry.name(), "nested");
assert!(entry.is_dir());
assert_eq!(opened.read_sync().unwrap(), None);
opened.close_sync().unwrap();
assert!(opened.read_sync().is_err());
let mut opened = opendir(&root).await.unwrap();
let entry = opened.read().await.unwrap().unwrap();
assert_eq!(entry.name(), "nested");
assert!(entry.is_dir());
assert_eq!(opened.read().await.unwrap(), None);
opened.close().await.unwrap();
assert!(opened.read().await.is_err());
assert_eq!(realpath_sync(&nested).unwrap(), nested);
assert_eq!(realpath(&nested).await.unwrap(), nested);
let expected = nested.trim_start_matches('/').to_owned();
assert!(glob_sync(&format!("{root}/*")).unwrap().contains(&expected));
assert!(
glob(&format!("{root}/*"))
.await
.unwrap()
.contains(&expected)
);
assert!(!glob_to_regex("*.txt").unwrap().is_empty());
assert_eq!(
normalize_path("/app/./nested/../file").unwrap(),
"/app/file"
);
rmdir(&nested).await.unwrap();
rm_sync(&root, true, false).unwrap();
rm(&root, true, true).await.unwrap();
}
#[wasm_bindgen_test]
async fn temporary_directory_apis_work() {
let prefix = test_path("temporary");
let first = mkdtemp_sync(&prefix).unwrap();
let second = mkdtemp(&prefix).await.unwrap();
assert_ne!(first, second);
let disposable = mkdtemp_disposable_sync(&prefix).unwrap();
let path = disposable.path().to_owned();
assert!(exists_sync(&path).unwrap());
drop(disposable);
assert!(!exists_sync(&path).unwrap());
rm_sync(&first, true, false).unwrap();
rm_sync(&second, true, false).unwrap();
}
#[wasm_bindgen_test]
async fn metadata_permissions_and_timestamps_work() {
let root = test_path("metadata");
mkdir_sync(&root, false).unwrap();
let path = format!("{root}/file");
write_file_sync(&path, b"hello").unwrap();
assert_eq!(stat_sync(&path).unwrap().len(), 5);
assert!(lstat_sync(&path).unwrap().is_file());
assert_eq!(stat(&path).await.unwrap().len(), 5);
assert!(lstat(&path).await.unwrap().is_file());
assert!(statfs_sync(&path).unwrap().block_size > 0);
assert!(statfs(&path).await.unwrap().blocks > 0.0);
let time = UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000);
chmod_sync(&path, 0o640).unwrap();
chmod(&path, 0o600).await.unwrap();
chown_sync(&path, 1, 1).unwrap();
chown(&path, 1, 1).await.unwrap();
utimes_sync(&path, time, time).unwrap();
utimes(&path, time, time).await.unwrap();
let options = OpenOptions {
read: true,
..OpenOptions::default()
};
let file = open_sync(&path, &options).unwrap();
fchmod_sync(&file, 0o644).unwrap();
fchmod(&file, 0o600).await.unwrap();
fchown_sync(&file, 1, 1).unwrap();
fchown(&file, 1, 1).await.unwrap();
futimes_sync(&file, time, time).unwrap();
futimes(&file, time, time).await.unwrap();
close_sync(file).unwrap();
let link = format!("{root}/link");
call_fs(
"symlinkSync",
&[JsValue::from_str(&path), JsValue::from_str(&link)],
)
.unwrap();
assert!(lstat_sync(&link).unwrap().is_symlink());
assert!(stat_sync(&link).unwrap().is_file());
lchown_sync(&link, 1, 1).unwrap();
lchown(&link, 1, 1).await.unwrap();
lutimes_sync(&link, time, time).unwrap();
lutimes(&link, time, time).await.unwrap();
lchmod_sync(&link, 0o777).unwrap();
lchmod(&link, 0o777).await.unwrap();
rm_sync(&root, true, false).unwrap();
}
#[wasm_bindgen_test]
async fn link_and_rename_apis_work() {
let root = test_path("links");
mkdir_sync(&root, false).unwrap();
let source = format!("{root}/source");
let hard = format!("{root}/hard");
let moved = format!("{root}/moved");
let symbolic = format!("{root}/symbolic");
write_text(&source, "value").unwrap();
link_sync(&source, &hard).unwrap();
rename(&hard, &moved).await.unwrap();
unlink_sync(&source).unwrap();
assert_eq!(read_text(&moved).unwrap(), "value");
link(&moved, &hard).await.unwrap();
rename_sync(&hard, &source).unwrap();
unlink(&source).await.unwrap();
symlink_sync(&moved, &symbolic).unwrap();
assert_eq!(readlink_sync(&symbolic).unwrap(), moved);
assert_eq!(readlink(&symbolic).await.unwrap(), moved);
unlink_sync(&symbolic).unwrap();
symlink(&moved, &symbolic).await.unwrap();
assert!(lstat_sync(&symbolic).unwrap().is_symlink());
unlink(&symbolic).await.unwrap();
unlink_sync(&moved).unwrap();
rm_sync(&root, true, false).unwrap();
}
#[wasm_bindgen_test]
async fn directory_symlink_targets_stay_relative_and_inside_root() {
let root = test_path("relative-links");
mkdir_sync(&root, false).unwrap();
let dir = crate::Directory::new(&root).unwrap();
dir.mkdir_sync("nested", false).unwrap();
dir.write_text("source", "value").unwrap();
dir.symlink_sync("../source", "nested/link").unwrap();
assert_eq!(dir.readlink_sync("nested/link").unwrap(), "../source");
assert_eq!(dir.read_text("nested/link").unwrap(), "value");
let mut opened = dir.opendir_sync("nested").unwrap();
let entry = opened.read_sync().unwrap().unwrap();
assert_eq!(entry.name(), "link");
assert!(entry.is_symlink());
opened.close_sync().unwrap();
dir.symlink("../missing", "nested/dangling").await.unwrap();
assert_eq!(dir.readlink("nested/dangling").await.unwrap(), "../missing");
assert!(dir.symlink_sync("../../outside", "nested/escape").is_err());
dir.unlink("nested/link").await.unwrap();
assert_eq!(dir.read_text("source").unwrap(), "value");
rm_sync(&root, true, false).unwrap();
}
}
#[cfg(all(test, not(all(feature = "webfs", not(feature = "zenfs")))))]
#[path = "implementation_tests.rs"]
mod shared_tests;