1use crate::host::with_host;
20use fusevm::Value;
21
22pub const METHODS: &[&str] = &[
23 "readFile",
24 "writeFile",
25 "appendFile",
26 "readdir",
27 "mkdir",
28 "rmdir",
29 "rm",
30 "unlink",
31 "stat",
32 "lstat",
33 "statfs",
34 "access",
35 "rename",
36 "copyFile",
37 "cp",
38 "chmod",
39 "chown",
40 "lchown",
41 "link",
42 "symlink",
43 "readlink",
44 "realpath",
45 "truncate",
46 "utimes",
47 "lutimes",
48 "mkdtemp",
49 "open",
50 "opendir",
51 "glob",
52];
53
54fn file_handle_module() -> Result<Value, String> {
57 thread_local! {
58 static MODULE: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
59 }
60 if let Some(m) = MODULE.with(|m| m.borrow().clone()) {
61 return Ok(m);
62 }
63 let factory = crate::eval_internal(include_str!("fs_filehandle.js"))?;
64 let (node_error, cancel) = with_host(|h| {
65 (
66 h.alloc(crate::host::JsObj::Builtin("util.@@nodeError".into())),
67 h.alloc(crate::host::JsObj::Builtin(
68 "util.@@readableStreamCancel".into(),
69 )),
70 )
71 });
72 let made = crate::host::invoke(&factory, vec![node_error, cancel], None)?;
73 MODULE.with(|m| *m.borrow_mut() = Some(made.clone()));
74 Ok(made)
75}
76
77fn call_port(name: &str, args: Vec<Value>) -> Result<Value, String> {
79 let f = crate::builtins::get_property(&file_handle_module()?, name)?;
80 crate::host::invoke(&f, args, None)
81}
82
83fn is_file_handle(v: &Value) -> Result<bool, String> {
87 let plain = with_host(|h| matches!(h.get(v), Some(crate::host::JsObj::Object(_))));
88 if !plain {
89 return Ok(false);
90 }
91 let class = crate::builtins::get_property(&file_handle_module()?, "FileHandle")?;
92 let found = crate::host::call_method(&class, "isFileHandle", vec![v.clone()])?;
93 Ok(with_host(|h| h.truthy(&found)))
94}
95
96pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
97 if method == "open" {
98 return Some(call_port("open", args.to_vec()));
99 }
100 if matches!(method, "readFile" | "writeFile" | "appendFile") {
103 match is_file_handle(args.first().unwrap_or(&Value::Undef)) {
104 Ok(true) => {
105 let port = if method == "readFile" {
106 "readFile"
107 } else {
108 "writeFile"
109 };
110 return Some(call_port(port, args.to_vec()));
111 }
112 Ok(false) => {}
113 Err(e) => return Some(Err(e)),
114 }
115 }
116 if matches!(method, "readFile" | "writeFile" | "appendFile") {
119 let opts = args.get(if method == "readFile" { 1 } else { 2 });
120 if let Some(o) = opts.filter(|o| with_host(|h| h.type_of(o)) == "object") {
121 let refusal = match call_port("signalRefusal", vec![o.clone()]) {
122 Ok(r) => r,
123 Err(e) => return Some(Err(e)),
124 };
125 if !matches!(refusal, Value::Undef) {
126 let p = with_host(|h| h.new_promise());
127 let id = with_host(|h| h.promise_id(&p).unwrap_or(0));
128 crate::host::reject_promise_val(id, refusal);
129 return Some(Ok(p));
130 }
131 }
132 }
133 let sync_name = match method {
136 "readFile" => "readFileSync",
137 "writeFile" => "writeFileSync",
138 "appendFile" => "appendFileSync",
139 "readdir" => "readdirSync",
140 "mkdir" => "mkdirSync",
141 "rmdir" => "rmdirSync",
142 "rm" => "rmSync",
143 "unlink" => "unlinkSync",
144 "stat" => "statSync",
145 "lstat" => "lstatSync",
146 "statfs" => "statfsSync",
147 "access" => "accessSync",
148 "rename" => "renameSync",
149 "copyFile" => "copyFileSync",
150 "cp" => "cpSync",
151 "chmod" => "chmodSync",
152 "chown" => "chownSync",
153 "lchown" => "lchownSync",
154 "link" => "linkSync",
155 "symlink" => "symlinkSync",
156 "readlink" => "readlinkSync",
157 "realpath" => "realpathSync",
158 "truncate" => "truncateSync",
159 "utimes" => "utimesSync",
160 "lutimes" => "lutimesSync",
161 "mkdtemp" => "mkdtempSync",
162 "opendir" => "opendirSync",
163 "glob" => "globSync",
164 _ => return None,
165 };
166 Some(Ok(settled(sync(sync_name, args))))
169}
170
171fn sync(sync_method: &str, args: &[Value]) -> Result<Value, String> {
174 super::fs::call(sync_method, args).unwrap_or_else(|| Err("Error: EIO: internal error".into()))
175}
176
177fn settled(result: Result<Value, String>) -> Value {
181 let p = with_host(|h| h.new_promise());
182 let id = with_host(|h| h.promise_id(&p).unwrap_or(0));
183 let outcome = match result {
185 Ok(v) => Ok(v),
186 Err(e) => Err(with_host(|h| crate::builtins::synth_error(h, &e))),
187 };
188 with_host(|h| {
193 h.queue_io_native(Box::new(move || {
194 match outcome {
195 Ok(v) => crate::host::resolve_promise_val(id, v),
196 Err(ev) => crate::host::reject_promise_val(id, ev),
197 }
198 Ok(())
199 }))
200 });
201 p
202}