-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathlib.rs
More file actions
282 lines (259 loc) · 10.8 KB
/
lib.rs
File metadata and controls
282 lines (259 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
//! NAPI binding layer for vite-plus CLI
//!
//! This module provides the bridge between JavaScript tool resolvers and the Rust core.
//! It uses NAPI-RS to create native Node.js bindings that allow JavaScript functions
//! to be called from Rust code.
//!
//! ## Architecture
//!
//! The binding follows a callback pattern:
//! 1. JavaScript passes resolver functions to Rust through `CliOptions`
//! 2. These functions are wrapped in `ThreadsafeFunction` for safe cross-runtime calls
//! 3. When Rust needs a tool, it calls the corresponding JavaScript function
//! 4. JavaScript resolves the tool path and returns it to Rust
//! 5. Rust executes the tool with the resolved path
use std::{collections::HashMap, sync::Arc};
use clap::Parser as _;
use napi::{anyhow, bindgen_prelude::*, threadsafe_function::ThreadsafeFunction};
use napi_derive::napi;
use vite_error::Error;
use vite_path::current_dir;
use vite_task::{Args, CliOptions as ViteTaskCliOptions, Commands, ResolveCommandResult};
/// Module initialization - sets up tracing for debugging
#[napi_derive::module_init]
pub fn init() {
vite_task::init_tracing();
}
/// Configuration options passed from JavaScript to Rust.
///
/// Each field (except `cwd`) is a JavaScript function wrapped in a `ThreadsafeFunction`.
/// These functions are called by Rust to resolve tool binary paths when needed.
///
/// The `ThreadsafeFunction` wrapper ensures the JavaScript functions can be
/// safely called from Rust's async runtime without blocking or race conditions.
#[napi(object, object_to_js = false)]
pub struct CliOptions {
/// Resolver function for the lint tool (oxlint)
pub lint: Arc<ThreadsafeFunction<(), Promise<JsCommandResolvedResult>>>,
/// Resolver function for the fmt tool (oxfmt)
pub fmt: Arc<ThreadsafeFunction<(), Promise<JsCommandResolvedResult>>>,
/// Resolver function for the vite tool (used for build/dev)
pub vite: Arc<ThreadsafeFunction<(), Promise<JsCommandResolvedResult>>>,
/// Resolver function for the test tool (vitest)
pub test: Arc<ThreadsafeFunction<(), Promise<JsCommandResolvedResult>>>,
/// Resolver function for the lib tool (tsdown)
pub lib: Arc<ThreadsafeFunction<(), Promise<JsCommandResolvedResult>>>,
/// Resolver function for the doc tool (vitepress)
pub doc: Arc<ThreadsafeFunction<(), Promise<JsCommandResolvedResult>>>,
/// Optional working directory override
pub cwd: Option<String>,
/// Read the vite.config.ts in the Node.js side and return the `lint` and `fmt` config JSON string back to the Rust side
pub resolve_universal_vite_config: Arc<ThreadsafeFunction<String, Promise<String>>>,
}
/// Result returned by JavaScript resolver functions.
///
/// This structure contains the information needed to execute a tool:
/// - `bin_path`: The absolute path to the tool's binary/script
/// - `envs`: Environment variables to set when executing the tool
#[napi(object, object_to_js = false)]
pub struct JsCommandResolvedResult {
/// Absolute path to the tool's executable or script
pub bin_path: String,
/// Environment variables to set when running the tool
pub envs: HashMap<String, String>,
}
/// Convert JavaScript result to Rust's expected format
impl From<JsCommandResolvedResult> for ResolveCommandResult {
fn from(value: JsCommandResolvedResult) -> Self {
ResolveCommandResult { bin_path: value.bin_path, envs: value.envs }
}
}
static BUILTIN_COMMANDS: &[&str] = &["lint", "fmt", "build", "test", "doc", "lib"];
/// Main entry point for the CLI, called from JavaScript.
///
/// This function:
/// 1. Parses command-line arguments
/// 2. Sets up the working directory
/// 3. Creates Rust-callable wrappers for JavaScript resolver functions
/// 4. Passes control to the Rust core (`vite_task::main`)
///
/// ## JavaScript-to-Rust Bridge
///
/// The resolver functions are wrapped to:
/// - Call the JavaScript function asynchronously
/// - Handle errors and convert them to Rust error types
/// - Convert the JavaScript result to Rust's expected format
///
/// ## Error Handling
///
/// Errors from JavaScript resolvers are converted to specific error types
/// (e.g., `LintFailed`, `ViteError`) to provide better error messages.
#[napi]
pub async fn run(options: CliOptions) -> Result<i32> {
let args = parse_args();
// Use provided cwd or current directory
let mut cwd = current_dir()?;
if let Some(options_cwd) = options.cwd {
cwd.push(options_cwd);
};
// Extract resolver functions from options
let lint = options.lint;
let fmt = options.fmt;
let vite = options.vite;
let test = options.test;
let lib = options.lib;
let doc = options.doc;
let resolve_universal_vite_config = options.resolve_universal_vite_config;
// Call the Rust core with wrapped resolver functions
let result = vite_task::main(
cwd,
args,
Some(ViteTaskCliOptions {
// Wrap the lint resolver to be callable from Rust
lint: || async {
// Call the JavaScript function and await both the promise and the result
let resolved = lint
.call_async(Ok(())) // Call with no arguments
.await // Wait for the call to complete
.map_err(js_error_to_lint_error)? // Convert call errors
.await // Wait for the promise to resolve
.map_err(js_error_to_lint_error)?; // Convert promise errors
Ok(resolved.into()) // Convert to Rust type
},
// Wrap the fmt resolver to be callable from Rust
fmt: || async {
let resolved = fmt
.call_async(Ok(()))
.await
.map_err(js_error_to_fmt_error)?
.await
.map_err(js_error_to_fmt_error)?;
Ok(resolved.into())
},
// Wrap the vite resolver to be callable from Rust
vite: || async {
let resolved = vite
.call_async(Ok(()))
.await
.map_err(js_error_to_vite_error)?
.await
.map_err(js_error_to_vite_error)?;
Ok(resolved.into())
},
// Wrap the test resolver to be callable from Rust
test: || async {
let resolved = test
.call_async(Ok(()))
.await
.map_err(js_error_to_test_error)?
.await
.map_err(js_error_to_test_error)?;
Ok(resolved.into())
},
// Wrap the lib resolver to be callable from Rust
lib: || async {
let resolved = lib
.call_async(Ok(()))
.await
.map_err(js_error_to_lib_error)?
.await
.map_err(js_error_to_lib_error)?;
Ok(resolved.into())
},
// Wrap the doc resolver to be callable from Rust
doc: || async {
let resolved = doc
.call_async(Ok(()))
.await
.map_err(js_error_to_doc_error)?
.await
.map_err(js_error_to_doc_error)?;
Ok(resolved.into())
},
resolve_universal_vite_config: |cwd: String| async {
let resolved = resolve_universal_vite_config
.call_async(Ok(cwd))
.await
.map_err(js_error_to_resolve_universal_vite_config_error)?
.await
.map_err(js_error_to_resolve_universal_vite_config_error)?;
Ok(resolved)
},
}),
)
.await;
match result {
Ok(exit_status) => Ok(exit_status.code().unwrap_or(1)),
Err(e) => {
match e {
// Standard exit code for Ctrl+C
Error::UserCancelled => Ok(130),
_ => {
// Convert Rust errors to NAPI errors for JavaScript
tracing::error!("Rust error: {:?}", e);
Err(anyhow::Error::from(e).into())
}
}
}
}
}
/// Convert JavaScript errors to Rust lint errors
fn js_error_to_lint_error(err: napi::Error) -> Error {
Error::LintFailed { status: err.status.to_string().into(), reason: err.to_string().into() }
}
/// Convert JavaScript errors to Rust fmt errors
fn js_error_to_fmt_error(err: napi::Error) -> Error {
Error::FmtFailed { status: err.status.to_string().into(), reason: err.to_string().into() }
}
/// Convert JavaScript errors to Rust vite errors
fn js_error_to_vite_error(err: napi::Error) -> Error {
Error::ViteError { status: err.status.to_string().into(), reason: err.to_string().into() }
}
/// Convert JavaScript errors to Rust test errors
fn js_error_to_test_error(err: napi::Error) -> Error {
Error::TestFailed { status: err.status.to_string().into(), reason: err.to_string().into() }
}
/// Convert JavaScript errors to Rust lib errors
fn js_error_to_lib_error(err: napi::Error) -> Error {
Error::LibFailed { status: err.status.to_string().into(), reason: err.to_string().into() }
}
/// Convert JavaScript errors to Rust doc errors
fn js_error_to_doc_error(err: napi::Error) -> Error {
Error::DocFailed { status: err.status.to_string().into(), reason: err.to_string().into() }
}
/// Convert JavaScript errors to Rust resolve universal vite config errors
fn js_error_to_resolve_universal_vite_config_error(err: napi::Error) -> Error {
Error::ResolveUniversalViteConfigFailed {
status: err.status.to_string().into(),
reason: err.to_string().into(),
}
}
fn parse_args() -> Args {
// ArgsOs [node, vite-plus, ...]
let mut raw_args = std::env::args_os().skip(2);
if let Some(first) = raw_args.next()
&& let Some(first) = first.to_str()
&& BUILTIN_COMMANDS.contains(&first)
{
let forwarded_args = raw_args
.map(|a| a.into_string().unwrap_or_else(|os_str| os_str.to_string_lossy().into_owned()))
.collect();
return Args {
task: None,
task_args: vec![],
commands: match first {
"lint" => Commands::Lint { args: forwarded_args },
"fmt" => Commands::Fmt { args: forwarded_args },
"build" => Commands::Build { args: forwarded_args },
"test" => Commands::Test { args: forwarded_args },
"doc" => Commands::Doc { args: forwarded_args },
"lib" => Commands::Lib { args: forwarded_args },
_ => unreachable!(),
},
debug: false,
no_debug: true,
};
}
// Parse CLI arguments (skip first arg which is the node binary)
Args::parse_from(std::env::args_os().skip(1))
}