browserslist/lib.rs
1//! **oxc-browserslist** is a Rust-based implementation of [Browserslist](https://github.com/browserslist/browserslist).
2//!
3//! ## Introduction
4//!
5//! This library bundles Can I Use data, Electron versions list and Node.js releases list,
6//! so it won't and doesn't need to access any data files.
7//!
8//! Except several non-widely/non-frequently used features,
9//! this library works as same as the JavaScript-based
10//! implementation [Browserslist](https://github.com/browserslist/browserslist).
11//!
12//! ## Usage
13//!
14//! It provides a simple API for querying which accepts a sequence of strings and options [`Opts`],
15//! then returns the result.
16//!
17//! ```
18//! use browserslist::{Distrib, Opts, resolve, Error};
19//!
20//! let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
21//! assert_eq!(distribs[0].name(), "ie");
22//! assert_eq!(distribs[0].version(), "6");
23//! assert_eq!(distribs[1].name(), "ie");
24//! assert_eq!(distribs[1].version(), "5.5");
25//!
26//! assert_eq!(
27//! resolve(&["yuru 1.0"], &Opts::default()),
28//! Err(Error::BrowserNotFound(String::from("yuru")))
29//! );
30//! ```
31//!
32//! The result isn't a list of strings, instead, it's a tuple struct called [`Distrib`].
33//! If you need to retrieve something like JavaScript-based implementation of
34//! [Browserslist](https://github.com/browserslist/browserslist),
35//! you can convert them to strings:
36//!
37//! ```
38//! use browserslist::{Distrib, Opts, resolve, Error};
39//!
40//! let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
41//! assert_eq!(
42//! distribs.into_iter().map(|d| d.to_string()).collect::<Vec<_>>(),
43//! vec![String::from("ie 6"), String::from("ie 5.5")]
44//! );
45//! ```
46//!
47//! ## WebAssembly
48//!
49//! This crate can be compiled as WebAssembly, without configuring any features manually.
50//!
51//! Please note that browser and Deno can run WebAssembly,
52//! but those environments aren't Node.js,
53//! so you will receive an error when querying `current node` in those environments.
54
55pub use error::Error;
56pub use opts::Opts;
57use parser::parse_browserslist_query;
58pub use queries::Distrib;
59pub use semver::Version;
60#[cfg(all(feature = "wasm_bindgen", target_arch = "wasm32"))]
61pub use wasm::browserslist;
62
63#[cfg(not(target_arch = "wasm32"))]
64mod config;
65mod data;
66mod date;
67mod error;
68mod generated;
69mod opts;
70mod parser;
71mod queries;
72mod semver;
73#[cfg(test)]
74mod test;
75#[cfg(all(feature = "wasm_bindgen", target_arch = "wasm32"))]
76mod wasm;
77
78/// Resolve browserslist queries.
79///
80/// This is a low-level API.
81/// If you want to load queries from configuration file and
82/// resolve them automatically,
83/// use the higher-level API [`execute`] instead.
84///
85/// ```
86/// use browserslist::{Distrib, Opts, resolve};
87///
88/// let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
89/// assert_eq!(distribs[0].name(), "ie");
90/// assert_eq!(distribs[0].version(), "6");
91/// assert_eq!(distribs[1].name(), "ie");
92/// assert_eq!(distribs[1].version(), "5.5");
93/// ```
94pub fn resolve<S>(queries: &[S], opts: &Opts) -> Result<Vec<Distrib>, Error>
95where
96 S: AsRef<str>,
97{
98 match queries.len() {
99 1 => _resolve(queries[0].as_ref(), opts),
100 _ => {
101 // Pre-calculate capacity to avoid reallocations
102 let total_len: usize = queries.iter().map(|q| q.as_ref().len() + 1).sum();
103 let mut s = String::with_capacity(total_len);
104 for (i, q) in queries.iter().enumerate() {
105 if i > 0 {
106 s.push(',');
107 }
108 s.push_str(q.as_ref());
109 }
110 _resolve(&s, opts)
111 }
112 }
113}
114
115// reduce generic monomorphization
116fn _resolve(query: &str, opts: &Opts) -> Result<Vec<Distrib>, Error> {
117 let queries = parse_browserslist_query(query)?;
118 let mut distribs = vec![];
119 for (i, current) in queries.1.into_iter().enumerate() {
120 if i == 0 && current.negated {
121 return handle_first_negated_error(current.raw.to_string());
122 }
123
124 let dist = queries::query(current.atom, opts)?;
125 apply_query_operation(&mut distribs, dist, current.negated, current.is_and);
126 }
127
128 sort_and_dedup_distribs(&mut distribs);
129 Ok(distribs)
130}
131
132// Separate function to reduce _resolve size and improve inlining decisions
133fn apply_query_operation(
134 distribs: &mut Vec<Distrib>,
135 dist: Vec<Distrib>,
136 negated: bool,
137 is_and: bool,
138) {
139 if negated {
140 distribs.retain(|d| !dist.contains(d));
141 } else if is_and {
142 distribs.retain(|d| dist.contains(d));
143 } else {
144 distribs.extend(dist);
145 }
146}
147
148// Optimized sorting that parses versions only once
149fn sort_and_dedup_distribs(distribs: &mut Vec<Distrib>) {
150 if distribs.is_empty() {
151 return;
152 }
153
154 // Use sort_by_cached_key to parse each version only once
155 distribs.sort_by_cached_key(|d| {
156 let version = d.version().parse::<semver::Version>().unwrap_or_default();
157 (d.name().to_string(), std::cmp::Reverse(version))
158 });
159
160 // Dedup in place
161 distribs.dedup();
162}
163
164// Cold path for error handling
165#[cold]
166fn handle_first_negated_error(raw: String) -> Result<Vec<Distrib>, Error> {
167 Err(Error::NotAtFirst(raw))
168}
169
170#[cfg(not(target_arch = "wasm32"))]
171/// Load queries from configuration with environment information,
172/// then resolve those queries.
173///
174/// If you want to resolve custom queries (not from configuration file),
175/// use the lower-level API [`resolve`] instead.
176///
177/// ```
178/// use browserslist::{Opts, execute};
179///
180/// // when no config found, it use `defaults` query
181/// assert!(!execute(&Opts::default()).unwrap().is_empty());
182/// ```
183pub fn execute(opts: &Opts) -> Result<Vec<Distrib>, Error> {
184 resolve(&config::load(opts)?, opts)
185}