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(all(feature = "wasm_bindgen", target_arch = "wasm32"))]
74mod wasm;
75
76/// Resolve browserslist queries.
77///
78/// This is a low-level API.
79/// If you want to load queries from configuration file and
80/// resolve them automatically,
81/// use the higher-level API [`execute`] instead.
82///
83/// ```
84/// use browserslist::{Distrib, Opts, resolve};
85///
86/// let distribs = resolve(&["ie <= 6"], &Opts::default()).unwrap();
87/// assert_eq!(distribs[0].name(), "ie");
88/// assert_eq!(distribs[0].version(), "6");
89/// assert_eq!(distribs[1].name(), "ie");
90/// assert_eq!(distribs[1].version(), "5.5");
91/// ```
92pub fn resolve<S>(queries: &[S], opts: &Opts) -> Result<Vec<Distrib>, Error>
93where
94 S: AsRef<str>,
95{
96 match queries.len() {
97 1 => _resolve(queries[0].as_ref(), opts),
98 _ => {
99 // Pre-calculate capacity to avoid reallocations
100 let total_len: usize = queries.iter().map(|q| q.as_ref().len() + 1).sum();
101 let mut s = String::with_capacity(total_len);
102 for (i, q) in queries.iter().enumerate() {
103 if i > 0 {
104 s.push(',');
105 }
106 s.push_str(q.as_ref());
107 }
108 _resolve(&s, opts)
109 }
110 }
111}
112
113// reduce generic monomorphization
114fn _resolve(query: &str, opts: &Opts) -> Result<Vec<Distrib>, Error> {
115 let queries = parse_browserslist_query(query)?;
116 let mut distribs = vec![];
117 for (i, current) in queries.1.into_iter().enumerate() {
118 if i == 0 && current.negated {
119 return handle_first_negated_error(current.raw.to_string());
120 }
121
122 let dist = queries::query(current.atom, opts)?;
123 apply_query_operation(&mut distribs, dist, current.negated, current.is_and);
124 }
125
126 sort_and_dedup_distribs(&mut distribs);
127 Ok(distribs)
128}
129
130// Separate function to reduce _resolve size and improve inlining decisions
131fn apply_query_operation(
132 distribs: &mut Vec<Distrib>,
133 dist: Vec<Distrib>,
134 negated: bool,
135 is_and: bool,
136) {
137 if negated {
138 distribs.retain(|d| !dist.contains(d));
139 } else if is_and {
140 distribs.retain(|d| dist.contains(d));
141 } else {
142 distribs.extend(dist);
143 }
144}
145
146// Optimized sorting that parses versions only once
147fn sort_and_dedup_distribs(distribs: &mut Vec<Distrib>) {
148 if distribs.is_empty() {
149 return;
150 }
151
152 // Use sort_by_cached_key to parse each version only once
153 distribs.sort_by_cached_key(|d| {
154 let version = d.version().parse::<semver::Version>().unwrap_or_default();
155 (d.name().to_string(), std::cmp::Reverse(version))
156 });
157
158 // Dedup in place
159 distribs.dedup();
160}
161
162// Cold path for error handling
163#[cold]
164fn handle_first_negated_error(raw: String) -> Result<Vec<Distrib>, Error> {
165 Err(Error::NotAtFirst(raw))
166}
167
168#[cfg(not(target_arch = "wasm32"))]
169/// Load queries from configuration with environment information,
170/// then resolve those queries.
171///
172/// If you want to resolve custom queries (not from configuration file),
173/// use the lower-level API [`resolve`] instead.
174///
175/// ```
176/// use browserslist::{Opts, execute};
177///
178/// // when no config found, it use `defaults` query
179/// assert!(!execute(&Opts::default()).unwrap().is_empty());
180/// ```
181pub fn execute(opts: &Opts) -> Result<Vec<Distrib>, Error> {
182 resolve(&config::load(opts)?, opts)
183}