use sqlite_wasm_rs as ffi;
use sqlite_wasm_vfs::sahpool::{OpfsSAHPoolCfg, install as sahpool_install};
#[derive(Debug, Clone)]
pub struct OpfsOptions {
pub vfs_name: String,
pub directory: String,
pub initial_capacity: u32,
pub clear_on_init: bool,
pub set_as_default: bool,
}
impl Default for OpfsOptions {
fn default() -> Self {
Self {
vfs_name: "opfs-sahpool".into(),
directory: ".opfs-sahpool".into(),
initial_capacity: 6,
clear_on_init: false,
set_as_default: true,
}
}
}
#[derive(Debug)]
pub enum OpfsInstallError {
NotSupported,
Vfs(String),
}
impl std::fmt::Display for OpfsInstallError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotSupported => {
write!(f, "OPFS install requires a Dedicated Worker context")
}
Self::Vfs(message) => write!(f, "OPFS VFS install failed: {message}"),
}
}
}
impl std::error::Error for OpfsInstallError {}
pub async fn install_opfs_vfs(options: &OpfsOptions) -> Result<(), OpfsInstallError> {
let cfg = OpfsSAHPoolCfg {
vfs_name: options.vfs_name.clone(),
directory: options.directory.clone(),
clear_on_init: options.clear_on_init,
initial_capacity: options.initial_capacity,
};
sahpool_install::<ffi::WasmOsCallback>(&cfg, options.set_as_default)
.await
.map(|_| ())
.map_err(|error| {
let text = format!("{error:?}");
if text.contains("NotSupported") {
OpfsInstallError::NotSupported
} else {
OpfsInstallError::Vfs(text)
}
})
}