ctb_formats_javascript/
lint.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from dlint: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Derived from Deno's dlint (https://github.com/denoland/deno_lint).
22// For parts derived from dlint:
23// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
24
25// See additional licensing details at end of file.
26
27//! Linter driver and source code analysis for JavaScript modules.
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace crate prelude"
33)]
34pub(crate) use ctb_utilities::*;
35
36use crate::deno_config::{get_rules_from_config, parse_config};
37use crate::project_files_resolver::resolve_file_paths_in_dir;
38use deno_ast::{MediaType, ModuleSpecifier};
39use deno_lint::linter::{LintConfig, LintFileOptions, Linter, LinterOptions};
40use deno_lint::rules::get_all_rules;
41
42pub fn lint_file(
43    file: &std::path::Path,
44    source_code: &str,
45    config_bytes: Option<&[u8]>,
46) -> Result<Vec<deno_lint::diagnostic::LintDiagnostic>> {
47    let mut jsdoc_rules = crate::jsdoc::JSDocRules::default();
48    if let Some(bytes) = config_bytes {
49        if let Ok(config) = parse_config(bytes) {
50            jsdoc_rules.require_jsdoc = config
51                .rules
52                .include
53                .iter()
54                .any(|r| r == "require-jsdoc")
55                && !config.rules.exclude.iter().any(|r| r == "require-jsdoc");
56            jsdoc_rules.require_param = config
57                .rules
58                .include
59                .iter()
60                .any(|r| r == "require-param")
61                && !config.rules.exclude.iter().any(|r| r == "require-param");
62            jsdoc_rules.require_returns = config
63                .rules
64                .include
65                .iter()
66                .any(|r| r == "require-returns")
67                && !config.rules.exclude.iter().any(|r| r == "require-returns");
68        }
69    }
70    let jsdoc_enabled = jsdoc_rules.require_jsdoc
71        || jsdoc_rules.require_param
72        || jsdoc_rules.require_returns;
73
74    let rules = if let Some(bytes) = config_bytes {
75        get_rules_from_config(bytes)?
76    } else {
77        deno_lint::rules::recommended_rules(get_all_rules())
78    };
79
80    let all_rules = get_all_rules();
81    let mut all_rule_codes = all_rules
82        .iter()
83        .map(|rule| rule.code())
84        .map(std::borrow::Cow::from)
85        .collect::<std::collections::HashSet<_>>();
86
87    all_rule_codes.insert("require-jsdoc".into());
88    all_rule_codes.insert("require-param".into());
89    all_rule_codes.insert("require-returns".into());
90
91    let external_linter = if jsdoc_enabled {
92        let cb: deno_lint::linter::ExternalLinterCb =
93            std::sync::Arc::new(move |parsed_source| {
94                let diags =
95                    crate::jsdoc::run_jsdoc_linter(&parsed_source, jsdoc_rules);
96                let mut rules = vec![];
97                if jsdoc_rules.require_jsdoc {
98                    rules.push("require-jsdoc".into());
99                }
100                if jsdoc_rules.require_param {
101                    rules.push("require-param".into());
102                }
103                if jsdoc_rules.require_returns {
104                    rules.push("require-returns".into());
105                }
106                Some(deno_lint::linter::ExternalLinterResult {
107                    diagnostics: diags,
108                    rules,
109                })
110            });
111        Some(cb)
112    } else {
113        None
114    };
115
116    let linter = Linter::new(LinterOptions {
117        rules,
118        all_rule_codes,
119        custom_ignore_file_directive: None,
120        custom_ignore_diagnostic_directive: None,
121    });
122
123    let absolute_path = if file.is_absolute() {
124        file.to_path_buf()
125    } else {
126        // Reason for fallback: if current_dir query fails, empty PathBuf serves as relative base.
127        std::env::current_dir().unwrap_or_default().join(file)
128    };
129    let specifier =
130        ModuleSpecifier::from_file_path(&absolute_path).map_err(|()| {
131            anyhow::anyhow!(
132                "Failed to convert path to specifier: {absolute_path:?}"
133            )
134        })?;
135
136    let (_, diagnostics) = linter.lint_file(LintFileOptions {
137        specifier,
138        source_code: source_code.to_string(),
139        media_type: MediaType::from_path(file),
140        config: LintConfig {
141            default_jsx_factory: Some("React.createElement".to_string()),
142            default_jsx_fragment_factory: Some("React.Fragment".to_string()),
143        },
144        external_linter,
145    })?;
146
147    Ok(diagnostics)
148}
149
150/// Lint a directory of files, returning diagnostics for each file.
151/// Reads the configuration either from the provided `config` bytes, if any, or from the `deno.json` in the directory.
152pub fn lint_directory(
153    directory: &std::path::Path,
154    config: Option<Vec<u8>>,
155) -> Result<Vec<deno_lint::diagnostic::LintDiagnostic>> {
156    let parsed_config = if let Some(bytes) = &config {
157        Some(parse_config(bytes)?)
158    } else {
159        let deno_json_path = directory.join("deno.json");
160        if deno_json_path.exists() {
161            let bytes = std::fs::read(&deno_json_path)?;
162            Some(parse_config(&bytes)?)
163        } else {
164            None
165        }
166    };
167
168    let files = if let Some(cfg) = &parsed_config {
169        resolve_file_paths_in_dir(directory, &cfg.files)?
170    } else {
171        let mut js_files = Vec::new();
172        for entry in walkdir::WalkDir::new(directory)
173            .into_iter()
174            .filter_map(std::result::Result::ok)
175            .filter(|e| e.file_type().is_file())
176        {
177            let path = entry.path();
178            if path.extension().and_then(|s| s.to_str()) == Some("js") {
179                js_files.push(path.to_path_buf());
180            }
181        }
182        js_files
183    };
184
185    let mut all_diagnostics = Vec::new();
186    for file_path in files {
187        let source_code = std::fs::read_to_string(&file_path)?;
188        let diagnostics =
189            lint_file(&file_path, &source_code, config.as_deref())?;
190        all_diagnostics.extend(diagnostics);
191    }
192
193    Ok(all_diagnostics)
194}
195
196#[cfg(test)]
197#[allow(
198    clippy::panic,
199    clippy::expect_used,
200    clippy::unwrap_used,
201    clippy::unwrap_in_result,
202    clippy::panic_in_result_fn,
203    clippy::indexing_slicing,
204    clippy::arithmetic_side_effects,
205    reason = "Standard repository test boilerplate"
206)]
207mod tests {
208    use super::*;
209    use ctb_utilities::string::{
210        pattern_match_custom_wildcard, strip_ansi_codes,
211    };
212    use deno_ast::diagnostics::Diagnostic;
213    use std::path::Path;
214
215    /// Checks if the given string matches a wildcard pattern where the wildcard
216    /// token is `"[WILDCARD]"`.
217    fn wildcard_match(pattern: &str, s: &str) -> bool {
218        pattern_match_custom_wildcard(pattern, s, "[WILDCARD]")
219    }
220
221    #[crate::ctb_test]
222    fn test_wildcard_match() {
223        assert!(wildcard_match(
224            "hello [WILDCARD] world",
225            "hello brave new world"
226        ));
227        assert!(!wildcard_match(
228            "hello [WILDCARD] world",
229            "hello brave new worlds"
230        ));
231        assert!(wildcard_match("[WILDCARD]", "anything"));
232    }
233
234    #[crate::ctb_test]
235    fn test_lint_file_valid() {
236        let code = "const a = 1;\nconsole.log(a);";
237        let file = Path::new("test.js");
238        let diagnostics = lint_file(file, code, None).unwrap();
239        assert!(diagnostics.is_empty());
240    }
241
242    #[crate::ctb_test]
243    fn test_lint_file_invalid() {
244        let code = "debugger;";
245        let file = Path::new("test.js");
246        let diagnostics = lint_file(file, code, None).unwrap();
247        assert!(!diagnostics.is_empty());
248        assert_eq!(diagnostics[0].code(), "no-debugger");
249    }
250
251    #[crate::ctb_test]
252    fn test_lint_file_with_config() {
253        let code = "debugger;";
254        let file = Path::new("test.js");
255        let config = r#"{
256      "rules": {
257        "exclude": ["no-debugger"]
258      }
259    }"#;
260        let diagnostics =
261            lint_file(file, code, Some(config.as_bytes())).unwrap();
262        assert!(diagnostics.is_empty());
263    }
264
265    #[crate::ctb_test]
266    fn test_lint_file_with_jsdoc_config() {
267        let code = "function foo(x) {}";
268        let file = Path::new("test.js");
269        let config = r#"{
270      "rules": {
271        "include": ["require-jsdoc", "require-param"]
272      }
273    }"#;
274        let diagnostics =
275            lint_file(file, code, Some(config.as_bytes())).unwrap();
276        assert_eq!(diagnostics.len(), 2);
277        let codes: std::collections::HashSet<_> =
278            diagnostics.iter().map(|d| d.code().to_string()).collect();
279        assert!(codes.contains("require-jsdoc"));
280        assert!(codes.contains("require-param"));
281    }
282
283    #[crate::ctb_test]
284    fn test_simple_ts() {
285        let ts_bytes = crate::get_js_data("fixtures/simple.ts").unwrap();
286        let ts_code = std::str::from_utf8(&ts_bytes).unwrap();
287        let out_bytes = crate::get_js_data("fixtures/simple.out").unwrap();
288        let expected_out = std::str::from_utf8(&out_bytes).unwrap();
289
290        let file = Path::new("/a/simple.ts");
291        let diagnostics = lint_file(file, ts_code, None).unwrap();
292
293        let mut actual = String::new();
294        for d in &diagnostics {
295            actual.push_str(&format!("{}\n\n", d.display()));
296        }
297        actual.push_str(&format!(
298            "Found {} problem{}\n\n",
299            diagnostics.len(),
300            if diagnostics.len() == 1 { "" } else { "s" }
301        ));
302
303        let actual_clean = strip_ansi_codes(&actual).trim_end().to_string();
304        let expected_clean =
305            expected_out.replace("\r\n", "\n").trim_end().to_string();
306
307        assert!(
308            wildcard_match(&expected_clean, &actual_clean),
309            "Expected:\n{expected_clean}\nActual:\n{actual_clean}"
310        );
311    }
312
313    #[crate::ctb_test]
314    fn test_issue1145_no_trailing_newline_ts() {
315        let ts_bytes =
316            crate::get_js_data("fixtures/issue1145_no_trailing_newline.ts")
317                .unwrap();
318        let ts_code = std::str::from_utf8(&ts_bytes).unwrap();
319        let out_bytes =
320            crate::get_js_data("fixtures/issue1145_no_trailing_newline.out")
321                .unwrap();
322        let expected_out = std::str::from_utf8(&out_bytes).unwrap();
323
324        let file = Path::new("/a/issue1145_no_trailing_newline.ts");
325        let diagnostics = lint_file(file, ts_code, None).unwrap();
326
327        let mut actual = String::new();
328        for d in &diagnostics {
329            actual.push_str(&format!("{}\n\n", d.display()));
330        }
331        actual.push_str(&format!(
332            "Found {} problem{}\n\n",
333            diagnostics.len(),
334            if diagnostics.len() == 1 { "" } else { "s" }
335        ));
336
337        let actual_clean = strip_ansi_codes(&actual).trim_end().to_string();
338        let expected_clean =
339            expected_out.replace("\r\n", "\n").trim_end().to_string();
340
341        assert!(
342            wildcard_match(&expected_clean, &actual_clean),
343            "Expected:\n{expected_clean}\nActual:\n{actual_clean}"
344        );
345    }
346}
347
348/*
349Code from dlint is used under the following license:
350======
351
352MIT License
353
354Copyright (c) 2018-2024 the Deno authors
355
356Permission is hereby granted, free of charge, to any person obtaining a copy
357of this software and associated documentation files (the "Software"), to deal
358in the Software without restriction, including without limitation the rights
359to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
360copies of the Software, and to permit persons to whom the Software is
361furnished to do so, subject to the following conditions:
362
363The above copyright notice and this permission notice shall be included in all
364copies or substantial portions of the Software.
365
366THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
367IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
368FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
369AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
370LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
371OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
372SOFTWARE.
373*/