2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2020-12-07 05:46:39 -05:00
|
|
|
|
2022-02-04 02:14:57 -05:00
|
|
|
use super::diagnostics::DenoDiagnostic;
|
2023-07-11 17:10:43 -04:00
|
|
|
use super::diagnostics::DiagnosticSource;
|
2024-10-01 17:55:02 -04:00
|
|
|
use super::documents::Document;
|
2022-01-19 17:10:14 -05:00
|
|
|
use super::documents::Documents;
|
2021-02-06 07:39:01 -05:00
|
|
|
use super::language_server;
|
2024-04-26 16:39:33 -04:00
|
|
|
use super::resolver::LspResolver;
|
2021-02-04 13:53:02 -05:00
|
|
|
use super::tsc;
|
2024-08-23 20:21:21 -04:00
|
|
|
use super::urls::url_to_uri;
|
2021-02-04 13:53:02 -05:00
|
|
|
|
2024-02-20 21:45:00 -05:00
|
|
|
use crate::args::jsr_url;
|
2024-11-12 08:15:32 -05:00
|
|
|
use crate::lsp::logging::lsp_warn;
|
2024-10-01 17:55:02 -04:00
|
|
|
use crate::lsp::search::PackageSearchApi;
|
2024-07-25 09:07:59 -04:00
|
|
|
use crate::tools::lint::CliLinter;
|
2024-11-06 01:26:46 -05:00
|
|
|
use crate::util::path::relative_specifier;
|
2024-10-01 17:55:02 -04:00
|
|
|
use deno_config::workspace::MappedResolution;
|
2024-11-06 01:26:46 -05:00
|
|
|
use deno_graph::source::ResolutionMode;
|
2024-07-25 09:07:59 -04:00
|
|
|
use deno_lint::diagnostic::LintDiagnosticRange;
|
2020-12-07 05:46:39 -05:00
|
|
|
|
2022-05-20 16:40:55 -04:00
|
|
|
use deno_ast::SourceRange;
|
|
|
|
use deno_ast::SourceRangedForSpanned;
|
2021-09-07 10:39:32 -04:00
|
|
|
use deno_ast::SourceTextInfo;
|
2021-02-04 13:53:02 -05:00
|
|
|
use deno_core::error::custom_error;
|
2020-12-07 05:46:39 -05:00
|
|
|
use deno_core::error::AnyError;
|
2021-01-31 22:30:41 -05:00
|
|
|
use deno_core::serde::Deserialize;
|
2024-03-21 17:18:59 -04:00
|
|
|
use deno_core::serde::Serialize;
|
2023-07-01 21:07:57 -04:00
|
|
|
use deno_core::serde_json;
|
2021-02-05 15:10:53 -05:00
|
|
|
use deno_core::serde_json::json;
|
2020-12-07 05:46:39 -05:00
|
|
|
use deno_core::ModuleSpecifier;
|
2024-09-28 07:55:01 -04:00
|
|
|
use deno_path_util::url_to_file_path;
|
2023-07-01 21:07:57 -04:00
|
|
|
use deno_runtime::deno_node::PathClean;
|
2024-02-20 21:45:00 -05:00
|
|
|
use deno_semver::jsr::JsrPackageNvReference;
|
|
|
|
use deno_semver::jsr::JsrPackageReqReference;
|
2024-01-21 17:19:10 -05:00
|
|
|
use deno_semver::npm::NpmPackageReqReference;
|
2024-02-20 21:45:00 -05:00
|
|
|
use deno_semver::package::PackageNv;
|
|
|
|
use deno_semver::package::PackageNvReference;
|
2023-08-21 05:53:52 -04:00
|
|
|
use deno_semver::package::PackageReq;
|
2024-02-20 21:45:00 -05:00
|
|
|
use deno_semver::package::PackageReqReference;
|
|
|
|
use deno_semver::Version;
|
2023-07-03 14:09:24 -04:00
|
|
|
use import_map::ImportMap;
|
2021-12-18 16:14:42 -05:00
|
|
|
use once_cell::sync::Lazy;
|
2021-05-29 07:21:11 -04:00
|
|
|
use regex::Regex;
|
2024-10-25 16:52:50 -04:00
|
|
|
use std::borrow::Cow;
|
2021-02-04 13:53:02 -05:00
|
|
|
use std::cmp::Ordering;
|
2020-12-07 05:46:39 -05:00
|
|
|
use std::collections::HashMap;
|
2024-01-21 17:19:10 -05:00
|
|
|
use std::collections::HashSet;
|
2023-07-01 21:07:57 -04:00
|
|
|
use std::path::Path;
|
2024-10-08 07:48:29 -04:00
|
|
|
use text_lines::LineAndColumnIndex;
|
2022-04-03 00:17:30 -04:00
|
|
|
use tower_lsp::lsp_types as lsp;
|
|
|
|
use tower_lsp::lsp_types::Position;
|
|
|
|
use tower_lsp::lsp_types::Range;
|
2020-12-07 05:46:39 -05:00
|
|
|
|
2021-12-18 16:14:42 -05:00
|
|
|
/// Diagnostic error codes which actually are the same, and so when grouping
|
|
|
|
/// fixes we treat them the same.
|
|
|
|
static FIX_ALL_ERROR_CODES: Lazy<HashMap<&'static str, &'static str>> =
|
2023-01-16 15:27:41 -05:00
|
|
|
Lazy::new(|| ([("2339", "2339"), ("2345", "2339")]).into_iter().collect());
|
2021-02-04 13:53:02 -05:00
|
|
|
|
2021-12-18 16:14:42 -05:00
|
|
|
/// Fixes which help determine if there is a preferred fix when there are
|
|
|
|
/// multiple fixes available.
|
|
|
|
static PREFERRED_FIXES: Lazy<HashMap<&'static str, (u32, bool)>> =
|
|
|
|
Lazy::new(|| {
|
2022-09-26 15:52:16 -04:00
|
|
|
([
|
2021-12-18 16:14:42 -05:00
|
|
|
("annotateWithTypeFromJSDoc", (1, false)),
|
|
|
|
("constructorForDerivedNeedSuperCall", (1, false)),
|
|
|
|
("extendsInterfaceBecomesImplements", (1, false)),
|
|
|
|
("awaitInSyncFunction", (1, false)),
|
|
|
|
("classIncorrectlyImplementsInterface", (3, false)),
|
|
|
|
("classDoesntImplementInheritedAbstractMember", (3, false)),
|
|
|
|
("unreachableCode", (1, false)),
|
|
|
|
("unusedIdentifier", (1, false)),
|
|
|
|
("forgottenThisPropertyAccess", (1, false)),
|
|
|
|
("spelling", (2, false)),
|
|
|
|
("addMissingAwait", (1, false)),
|
|
|
|
("fixImport", (0, true)),
|
|
|
|
])
|
2023-01-16 15:27:41 -05:00
|
|
|
.into_iter()
|
2022-09-26 15:52:16 -04:00
|
|
|
.collect()
|
2021-12-18 16:14:42 -05:00
|
|
|
});
|
|
|
|
|
2024-07-23 14:39:14 -04:00
|
|
|
static IMPORT_SPECIFIER_RE: Lazy<Regex> = lazy_regex::lazy_regex!(
|
|
|
|
r#"\sfrom\s+["']([^"']*)["']|import\s*\(\s*["']([^"']*)["']\s*\)"#
|
|
|
|
);
|
2021-05-29 07:21:11 -04:00
|
|
|
|
2024-06-12 17:22:57 -04:00
|
|
|
const SUPPORTED_EXTENSIONS: &[&str] = &[
|
|
|
|
".ts", ".tsx", ".js", ".jsx", ".mjs", ".mts", ".cjs", ".cts", ".d.ts",
|
|
|
|
".d.mts", ".d.cts",
|
|
|
|
];
|
2021-05-29 07:21:11 -04:00
|
|
|
|
2024-03-21 17:18:59 -04:00
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
|
|
pub struct DataQuickFixChange {
|
|
|
|
pub range: Range,
|
|
|
|
pub new_text: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A quick fix that's stored in the diagnostic's data field.
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
|
|
pub struct DataQuickFix {
|
|
|
|
pub description: String,
|
|
|
|
pub changes: Vec<DataQuickFixChange>,
|
|
|
|
}
|
|
|
|
|
2020-12-07 05:46:39 -05:00
|
|
|
/// Category of self-generated diagnostic messages (those not coming from)
|
|
|
|
/// TypeScript.
|
2021-05-25 18:15:09 -04:00
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
2020-12-07 05:46:39 -05:00
|
|
|
pub enum Category {
|
|
|
|
/// A lint diagnostic, where the first element is the message.
|
|
|
|
Lint {
|
|
|
|
message: String,
|
|
|
|
code: String,
|
|
|
|
hint: Option<String>,
|
2024-03-21 17:18:59 -04:00
|
|
|
quick_fixes: Vec<DataQuickFix>,
|
2020-12-07 05:46:39 -05:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A structure to hold a reference to a diagnostic message.
|
2021-05-25 18:15:09 -04:00
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
2020-12-07 05:46:39 -05:00
|
|
|
pub struct Reference {
|
|
|
|
category: Category,
|
|
|
|
range: Range,
|
|
|
|
}
|
|
|
|
|
2021-05-11 10:43:00 -04:00
|
|
|
impl Reference {
|
|
|
|
pub fn to_diagnostic(&self) -> lsp::Diagnostic {
|
|
|
|
match &self.category {
|
2021-05-25 18:15:09 -04:00
|
|
|
Category::Lint {
|
|
|
|
message,
|
|
|
|
code,
|
|
|
|
hint,
|
2024-03-21 17:18:59 -04:00
|
|
|
quick_fixes,
|
2021-05-25 18:15:09 -04:00
|
|
|
} => lsp::Diagnostic {
|
2021-05-11 10:43:00 -04:00
|
|
|
range: self.range,
|
2021-11-24 20:10:12 -05:00
|
|
|
severity: Some(lsp::DiagnosticSeverity::WARNING),
|
2021-05-11 10:43:00 -04:00
|
|
|
code: Some(lsp::NumberOrString::String(code.to_string())),
|
|
|
|
code_description: None,
|
2023-07-11 17:10:43 -04:00
|
|
|
source: Some(DiagnosticSource::Lint.as_lsp_source().to_string()),
|
2021-05-25 18:15:09 -04:00
|
|
|
message: {
|
|
|
|
let mut msg = message.to_string();
|
|
|
|
if let Some(hint) = hint {
|
|
|
|
msg.push('\n');
|
|
|
|
msg.push_str(hint);
|
|
|
|
}
|
|
|
|
msg
|
|
|
|
},
|
2021-05-11 10:43:00 -04:00
|
|
|
related_information: None,
|
|
|
|
tags: None, // we should tag unused code
|
2024-03-21 17:18:59 -04:00
|
|
|
data: if quick_fixes.is_empty() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
serde_json::to_value(quick_fixes).ok()
|
|
|
|
},
|
2021-05-11 10:43:00 -04:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-25 09:07:59 -04:00
|
|
|
fn as_lsp_range_from_lint_diagnostic(
|
|
|
|
diagnostic_range: &LintDiagnosticRange,
|
|
|
|
) -> Range {
|
|
|
|
as_lsp_range(diagnostic_range.range, &diagnostic_range.text_info)
|
2024-03-21 17:18:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn as_lsp_range(
|
|
|
|
source_range: SourceRange,
|
|
|
|
text_info: &SourceTextInfo,
|
|
|
|
) -> Range {
|
|
|
|
let start_lc = text_info.line_and_column_index(source_range.start);
|
|
|
|
let end_lc = text_info.line_and_column_index(source_range.end);
|
2020-12-07 05:46:39 -05:00
|
|
|
Range {
|
|
|
|
start: Position {
|
2024-02-08 20:40:26 -05:00
|
|
|
line: start_lc.line_index as u32,
|
|
|
|
character: start_lc.column_index as u32,
|
2020-12-07 05:46:39 -05:00
|
|
|
},
|
|
|
|
end: Position {
|
2024-02-08 20:40:26 -05:00
|
|
|
line: end_lc.line_index as u32,
|
|
|
|
character: end_lc.column_index as u32,
|
2020-12-07 05:46:39 -05:00
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_lint_references(
|
2021-09-07 10:39:32 -04:00
|
|
|
parsed_source: &deno_ast::ParsedSource,
|
2024-07-25 09:07:59 -04:00
|
|
|
linter: &CliLinter,
|
2020-12-07 05:46:39 -05:00
|
|
|
) -> Result<Vec<Reference>, AnyError> {
|
2024-07-25 09:07:59 -04:00
|
|
|
let lint_diagnostics = linter.lint_with_ast(parsed_source);
|
2020-12-07 05:46:39 -05:00
|
|
|
|
|
|
|
Ok(
|
|
|
|
lint_diagnostics
|
|
|
|
.into_iter()
|
2024-07-25 09:07:59 -04:00
|
|
|
.filter_map(|d| {
|
|
|
|
let range = d.range.as_ref()?;
|
|
|
|
Some(Reference {
|
|
|
|
range: as_lsp_range_from_lint_diagnostic(range),
|
|
|
|
category: Category::Lint {
|
|
|
|
message: d.details.message,
|
|
|
|
code: d.details.code.to_string(),
|
|
|
|
hint: d.details.hint,
|
|
|
|
quick_fixes: d
|
|
|
|
.details
|
|
|
|
.fixes
|
|
|
|
.into_iter()
|
|
|
|
.map(|f| DataQuickFix {
|
|
|
|
description: f.description.to_string(),
|
|
|
|
changes: f
|
|
|
|
.changes
|
|
|
|
.into_iter()
|
|
|
|
.map(|change| DataQuickFixChange {
|
|
|
|
range: as_lsp_range(change.range, &range.text_info),
|
|
|
|
new_text: change.new_text.to_string(),
|
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
},
|
|
|
|
})
|
2020-12-07 05:46:39 -05:00
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-02-04 13:53:02 -05:00
|
|
|
fn code_as_string(code: &Option<lsp::NumberOrString>) -> String {
|
|
|
|
match code {
|
|
|
|
Some(lsp::NumberOrString::String(str)) => str.clone(),
|
|
|
|
Some(lsp::NumberOrString::Number(num)) => num.to_string(),
|
|
|
|
_ => "".to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-01 21:07:57 -04:00
|
|
|
/// Rewrites imports in quick fixes and code changes to be Deno specific.
|
|
|
|
pub struct TsResponseImportMapper<'a> {
|
|
|
|
documents: &'a Documents,
|
2024-04-02 18:02:50 -04:00
|
|
|
maybe_import_map: Option<&'a ImportMap>,
|
2024-04-26 16:39:33 -04:00
|
|
|
resolver: &'a LspResolver,
|
2024-11-06 01:26:46 -05:00
|
|
|
tsc_specifier_map: &'a tsc::TscSpecifierMap,
|
2024-10-07 13:20:45 -04:00
|
|
|
file_referrer: ModuleSpecifier,
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> TsResponseImportMapper<'a> {
|
|
|
|
pub fn new(
|
|
|
|
documents: &'a Documents,
|
2024-04-02 18:02:50 -04:00
|
|
|
maybe_import_map: Option<&'a ImportMap>,
|
2024-04-26 16:39:33 -04:00
|
|
|
resolver: &'a LspResolver,
|
2024-11-06 01:26:46 -05:00
|
|
|
tsc_specifier_map: &'a tsc::TscSpecifierMap,
|
2024-10-07 13:20:45 -04:00
|
|
|
file_referrer: &ModuleSpecifier,
|
2023-07-01 21:07:57 -04:00
|
|
|
) -> Self {
|
|
|
|
Self {
|
|
|
|
documents,
|
2023-07-03 14:09:24 -04:00
|
|
|
maybe_import_map,
|
2024-04-26 16:39:33 -04:00
|
|
|
resolver,
|
2024-11-06 01:26:46 -05:00
|
|
|
tsc_specifier_map,
|
2024-10-07 13:20:45 -04:00
|
|
|
file_referrer: file_referrer.clone(),
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-03 14:09:24 -04:00
|
|
|
pub fn check_specifier(
|
|
|
|
&self,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
referrer: &ModuleSpecifier,
|
|
|
|
) -> Option<String> {
|
|
|
|
fn concat_npm_specifier(
|
|
|
|
prefix: &str,
|
2023-08-21 05:53:52 -04:00
|
|
|
pkg_req: &PackageReq,
|
2023-07-03 14:09:24 -04:00
|
|
|
sub_path: Option<&str>,
|
|
|
|
) -> String {
|
|
|
|
let result = format!("{}{}", prefix, pkg_req);
|
|
|
|
match sub_path {
|
|
|
|
Some(path) => format!("{}/{}", result, path),
|
|
|
|
None => result,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-20 21:45:00 -05:00
|
|
|
if let Some(jsr_path) = specifier.as_str().strip_prefix(jsr_url().as_str())
|
|
|
|
{
|
|
|
|
let mut segments = jsr_path.split('/');
|
|
|
|
let name = if jsr_path.starts_with('@') {
|
|
|
|
format!("{}/{}", segments.next()?, segments.next()?)
|
|
|
|
} else {
|
|
|
|
segments.next()?.to_string()
|
|
|
|
};
|
|
|
|
let version = Version::parse_standard(segments.next()?).ok()?;
|
|
|
|
let nv = PackageNv { name, version };
|
|
|
|
let path = segments.collect::<Vec<_>>().join("/");
|
2024-05-23 12:31:56 -04:00
|
|
|
let export = self.resolver.jsr_lookup_export_for_path(
|
|
|
|
&nv,
|
|
|
|
&path,
|
2024-10-07 13:20:45 -04:00
|
|
|
Some(&self.file_referrer),
|
2024-05-23 12:31:56 -04:00
|
|
|
)?;
|
2024-02-20 21:45:00 -05:00
|
|
|
let sub_path = (export != ".").then_some(export);
|
|
|
|
let mut req = None;
|
|
|
|
req = req.or_else(|| {
|
2024-04-02 18:02:50 -04:00
|
|
|
let import_map = self.maybe_import_map?;
|
2024-02-20 21:45:00 -05:00
|
|
|
for entry in import_map.entries_for_referrer(referrer) {
|
|
|
|
let Some(value) = entry.raw_value else {
|
|
|
|
continue;
|
|
|
|
};
|
|
|
|
let Ok(req_ref) = JsrPackageReqReference::from_str(value) else {
|
|
|
|
continue;
|
|
|
|
};
|
|
|
|
let req = req_ref.req();
|
|
|
|
if req.name == nv.name
|
|
|
|
&& req.version_req.tag().is_none()
|
|
|
|
&& req.version_req.matches(&nv.version)
|
|
|
|
{
|
|
|
|
return Some(req.clone());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
});
|
2024-05-23 12:31:56 -04:00
|
|
|
req = req.or_else(|| {
|
|
|
|
self
|
|
|
|
.resolver
|
2024-10-07 13:20:45 -04:00
|
|
|
.jsr_lookup_req_for_nv(&nv, Some(&self.file_referrer))
|
2024-05-23 12:31:56 -04:00
|
|
|
});
|
2024-02-20 21:45:00 -05:00
|
|
|
let spec_str = if let Some(req) = req {
|
|
|
|
let req_ref = PackageReqReference { req, sub_path };
|
|
|
|
JsrPackageReqReference::new(req_ref).to_string()
|
|
|
|
} else {
|
|
|
|
let nv_ref = PackageNvReference { nv, sub_path };
|
|
|
|
JsrPackageNvReference::new(nv_ref).to_string()
|
|
|
|
};
|
|
|
|
let specifier = ModuleSpecifier::parse(&spec_str).ok()?;
|
2024-04-02 18:02:50 -04:00
|
|
|
if let Some(import_map) = self.maybe_import_map {
|
2024-02-20 21:45:00 -05:00
|
|
|
if let Some(result) = import_map.lookup(&specifier, referrer) {
|
|
|
|
return Some(result);
|
|
|
|
}
|
2024-08-14 17:38:18 -04:00
|
|
|
if let Some(req_ref_str) = specifier.as_str().strip_prefix("jsr:") {
|
|
|
|
if !req_ref_str.starts_with('/') {
|
|
|
|
let specifier_str = format!("jsr:/{req_ref_str}");
|
|
|
|
if let Ok(specifier) = ModuleSpecifier::parse(&specifier_str) {
|
|
|
|
if let Some(result) = import_map.lookup(&specifier, referrer) {
|
|
|
|
return Some(result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-02-20 21:45:00 -05:00
|
|
|
}
|
|
|
|
return Some(spec_str);
|
|
|
|
}
|
|
|
|
|
2024-05-23 12:31:56 -04:00
|
|
|
if let Some(npm_resolver) = self
|
|
|
|
.resolver
|
2024-10-07 13:20:45 -04:00
|
|
|
.maybe_managed_npm_resolver(Some(&self.file_referrer))
|
2024-05-23 12:31:56 -04:00
|
|
|
{
|
2024-11-01 12:27:00 -04:00
|
|
|
let in_npm_pkg = self
|
|
|
|
.resolver
|
|
|
|
.maybe_node_resolver(Some(&self.file_referrer))
|
|
|
|
.map(|n| n.in_npm_package(specifier))
|
|
|
|
.unwrap_or(false);
|
|
|
|
if in_npm_pkg {
|
2023-09-29 09:26:25 -04:00
|
|
|
if let Ok(Some(pkg_id)) =
|
|
|
|
npm_resolver.resolve_pkg_id_from_specifier(specifier)
|
|
|
|
{
|
2023-09-30 12:06:38 -04:00
|
|
|
let pkg_reqs = npm_resolver.resolve_pkg_reqs_from_pkg_id(&pkg_id);
|
2023-09-29 09:26:25 -04:00
|
|
|
// check if any pkg reqs match what is found in an import map
|
|
|
|
if !pkg_reqs.is_empty() {
|
|
|
|
let sub_path = self.resolve_package_path(specifier);
|
2024-04-02 18:02:50 -04:00
|
|
|
if let Some(import_map) = self.maybe_import_map {
|
2024-01-21 17:19:10 -05:00
|
|
|
let pkg_reqs = pkg_reqs.iter().collect::<HashSet<_>>();
|
|
|
|
let mut matches = Vec::new();
|
|
|
|
for entry in import_map.entries_for_referrer(referrer) {
|
|
|
|
if let Some(value) = entry.raw_value {
|
|
|
|
if let Ok(package_ref) =
|
|
|
|
NpmPackageReqReference::from_str(value)
|
2023-09-29 09:26:25 -04:00
|
|
|
{
|
2024-01-21 17:19:10 -05:00
|
|
|
if pkg_reqs.contains(package_ref.req()) {
|
|
|
|
let sub_path = sub_path.as_deref().unwrap_or("");
|
|
|
|
let value_sub_path = package_ref.sub_path().unwrap_or("");
|
|
|
|
if let Some(key_sub_path) =
|
|
|
|
sub_path.strip_prefix(value_sub_path)
|
|
|
|
{
|
|
|
|
matches
|
|
|
|
.push(format!("{}{}", entry.raw_key, key_sub_path));
|
|
|
|
}
|
|
|
|
}
|
2023-09-29 09:26:25 -04:00
|
|
|
}
|
2023-07-03 14:09:24 -04:00
|
|
|
}
|
|
|
|
}
|
2024-01-21 17:19:10 -05:00
|
|
|
// select the shortest match
|
|
|
|
matches.sort_by_key(|a| a.len());
|
|
|
|
if let Some(matched) = matches.first() {
|
|
|
|
return Some(matched.to_string());
|
|
|
|
}
|
2023-07-03 14:09:24 -04:00
|
|
|
}
|
|
|
|
|
2023-09-29 09:26:25 -04:00
|
|
|
// if not found in the import map, return the first pkg req
|
|
|
|
if let Some(pkg_req) = pkg_reqs.first() {
|
|
|
|
return Some(concat_npm_specifier(
|
|
|
|
"npm:",
|
|
|
|
pkg_req,
|
|
|
|
sub_path.as_deref(),
|
|
|
|
));
|
|
|
|
}
|
2023-07-03 14:09:24 -04:00
|
|
|
}
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
|
|
|
}
|
2024-11-06 01:26:46 -05:00
|
|
|
} else if let Some(dep_name) = self
|
|
|
|
.resolver
|
|
|
|
.file_url_to_package_json_dep(specifier, Some(&self.file_referrer))
|
|
|
|
{
|
|
|
|
return Some(dep_name);
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
2023-07-03 14:09:24 -04:00
|
|
|
|
|
|
|
// check if the import map has this specifier
|
2024-04-02 18:02:50 -04:00
|
|
|
if let Some(import_map) = self.maybe_import_map {
|
2023-07-03 14:09:24 -04:00
|
|
|
if let Some(result) = import_map.lookup(specifier, referrer) {
|
|
|
|
return Some(result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-01 21:07:57 -04:00
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve_package_path(
|
|
|
|
&self,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
) -> Option<String> {
|
2024-04-26 16:39:33 -04:00
|
|
|
let package_json = self
|
|
|
|
.resolver
|
|
|
|
.get_closest_package_json(specifier)
|
2023-11-04 12:41:51 -04:00
|
|
|
.ok()
|
2023-07-17 14:00:44 -04:00
|
|
|
.flatten()?;
|
2023-11-04 12:41:51 -04:00
|
|
|
let root_folder = package_json.path.parent()?;
|
2023-07-01 21:07:57 -04:00
|
|
|
|
2024-09-28 07:55:01 -04:00
|
|
|
let specifier_path = url_to_file_path(specifier).ok()?;
|
2023-07-01 21:07:57 -04:00
|
|
|
let mut search_paths = vec![specifier_path.clone()];
|
|
|
|
// TypeScript will provide a .js extension for quick fixes, so do
|
|
|
|
// a search for the .d.ts file instead
|
|
|
|
if specifier_path.extension().and_then(|e| e.to_str()) == Some("js") {
|
|
|
|
search_paths.insert(0, specifier_path.with_extension("d.ts"));
|
2024-01-21 17:19:10 -05:00
|
|
|
} else if let Some(file_name) =
|
|
|
|
specifier_path.file_name().and_then(|f| f.to_str())
|
|
|
|
{
|
|
|
|
// In some other cases, typescript will provide the .d.ts extension, but the
|
|
|
|
// export might not have a .d.ts defined. In that case, look for the corresponding
|
|
|
|
// JavaScript file after not being able to find the .d.ts file.
|
|
|
|
if let Some(file_stem) = file_name.strip_suffix(".d.ts") {
|
|
|
|
search_paths
|
|
|
|
.push(specifier_path.with_file_name(format!("{}.js", file_stem)));
|
|
|
|
} else if let Some(file_stem) = file_name.strip_suffix(".d.cts") {
|
|
|
|
search_paths
|
|
|
|
.push(specifier_path.with_file_name(format!("{}.cjs", file_stem)));
|
|
|
|
} else if let Some(file_stem) = file_name.strip_suffix(".d.mts") {
|
|
|
|
search_paths
|
|
|
|
.push(specifier_path.with_file_name(format!("{}.mjs", file_stem)));
|
|
|
|
}
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
for search_path in search_paths {
|
|
|
|
if let Some(exports) = &package_json.exports {
|
|
|
|
if let Some(result) = try_reverse_map_package_json_exports(
|
2023-11-04 12:41:51 -04:00
|
|
|
root_folder,
|
2023-07-01 21:07:57 -04:00
|
|
|
&search_path,
|
|
|
|
exports,
|
|
|
|
) {
|
|
|
|
return Some(result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Iterate over the supported extensions, concatenating the extension on the
|
|
|
|
/// specifier, returning the first specifier that is resolve-able, otherwise
|
|
|
|
/// None if none match.
|
2023-07-03 14:09:24 -04:00
|
|
|
pub fn check_unresolved_specifier(
|
2023-07-01 21:07:57 -04:00
|
|
|
&self,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &ModuleSpecifier,
|
|
|
|
) -> Option<String> {
|
2024-11-06 01:26:46 -05:00
|
|
|
let specifier_stem = specifier.strip_suffix(".js").unwrap_or(specifier);
|
|
|
|
let specifiers = std::iter::once(Cow::Borrowed(specifier)).chain(
|
|
|
|
SUPPORTED_EXTENSIONS
|
|
|
|
.iter()
|
|
|
|
.map(|ext| Cow::Owned(format!("{specifier_stem}{ext}"))),
|
|
|
|
);
|
|
|
|
for specifier in specifiers {
|
|
|
|
if let Some(specifier) = self
|
|
|
|
.resolver
|
|
|
|
.as_graph_resolver(Some(&self.file_referrer))
|
|
|
|
.resolve(
|
|
|
|
&specifier,
|
|
|
|
&deno_graph::Range {
|
|
|
|
specifier: referrer.clone(),
|
|
|
|
start: deno_graph::Position::zeroed(),
|
|
|
|
end: deno_graph::Position::zeroed(),
|
|
|
|
},
|
|
|
|
ResolutionMode::Types,
|
|
|
|
)
|
|
|
|
.ok()
|
|
|
|
.and_then(|s| self.tsc_specifier_map.normalize(s.as_str()).ok())
|
|
|
|
.filter(|s| self.documents.exists(s, Some(&self.file_referrer)))
|
2023-07-01 21:07:57 -04:00
|
|
|
{
|
2024-11-06 01:26:46 -05:00
|
|
|
if let Some(specifier) = self
|
|
|
|
.check_specifier(&specifier, referrer)
|
|
|
|
.or_else(|| relative_specifier(referrer, &specifier))
|
|
|
|
.filter(|s| !s.contains("/node_modules/"))
|
|
|
|
{
|
|
|
|
return Some(specifier);
|
|
|
|
}
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
2024-10-07 13:20:45 -04:00
|
|
|
|
|
|
|
pub fn is_valid_import(
|
|
|
|
&self,
|
|
|
|
specifier_text: &str,
|
|
|
|
referrer: &ModuleSpecifier,
|
|
|
|
) -> bool {
|
|
|
|
self
|
|
|
|
.resolver
|
|
|
|
.as_graph_resolver(Some(&self.file_referrer))
|
|
|
|
.resolve(
|
|
|
|
specifier_text,
|
|
|
|
&deno_graph::Range {
|
|
|
|
specifier: referrer.clone(),
|
|
|
|
start: deno_graph::Position::zeroed(),
|
|
|
|
end: deno_graph::Position::zeroed(),
|
|
|
|
},
|
|
|
|
deno_graph::source::ResolutionMode::Types,
|
|
|
|
)
|
|
|
|
.is_ok()
|
|
|
|
}
|
2023-07-01 21:07:57 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
fn try_reverse_map_package_json_exports(
|
|
|
|
root_path: &Path,
|
|
|
|
target_path: &Path,
|
|
|
|
exports: &serde_json::Map<String, serde_json::Value>,
|
2021-05-29 07:21:11 -04:00
|
|
|
) -> Option<String> {
|
2023-07-01 21:07:57 -04:00
|
|
|
use deno_core::serde_json::Value;
|
|
|
|
|
|
|
|
fn try_reverse_map_package_json_exports_inner(
|
|
|
|
root_path: &Path,
|
|
|
|
target_path: &Path,
|
|
|
|
exports: &serde_json::Map<String, Value>,
|
|
|
|
) -> Option<String> {
|
|
|
|
for (key, value) in exports {
|
|
|
|
match value {
|
|
|
|
Value::String(str) => {
|
|
|
|
if root_path.join(str).clean() == target_path {
|
|
|
|
return Some(if let Some(suffix) = key.strip_prefix("./") {
|
|
|
|
suffix.to_string()
|
|
|
|
} else {
|
|
|
|
String::new() // condition (ex. "types"), ignore
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Value::Object(obj) => {
|
|
|
|
if let Some(result) = try_reverse_map_package_json_exports_inner(
|
|
|
|
root_path,
|
|
|
|
target_path,
|
|
|
|
obj,
|
|
|
|
) {
|
|
|
|
return Some(if let Some(suffix) = key.strip_prefix("./") {
|
|
|
|
if result.is_empty() {
|
|
|
|
suffix.to_string()
|
|
|
|
} else {
|
|
|
|
format!("{}/{}", suffix, result)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
result // condition (ex. "types"), ignore
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
2021-05-29 07:21:11 -04:00
|
|
|
}
|
2023-07-01 21:07:57 -04:00
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
let result = try_reverse_map_package_json_exports_inner(
|
|
|
|
root_path,
|
|
|
|
target_path,
|
|
|
|
exports,
|
|
|
|
)?;
|
|
|
|
if result.is_empty() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(result)
|
2021-05-29 07:21:11 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// For a set of tsc changes, can them for any that contain something that looks
|
|
|
|
/// like an import and rewrite the import specifier to include the extension
|
2022-03-23 09:54:22 -04:00
|
|
|
pub fn fix_ts_import_changes(
|
2021-05-29 07:21:11 -04:00
|
|
|
referrer: &ModuleSpecifier,
|
|
|
|
changes: &[tsc::FileTextChanges],
|
2024-11-06 01:26:46 -05:00
|
|
|
language_server: &language_server::Inner,
|
2021-05-29 07:21:11 -04:00
|
|
|
) -> Result<Vec<tsc::FileTextChanges>, AnyError> {
|
2024-11-06 01:26:46 -05:00
|
|
|
let import_mapper = language_server.get_ts_response_import_mapper(referrer);
|
2021-05-29 07:21:11 -04:00
|
|
|
let mut r = Vec::new();
|
|
|
|
for change in changes {
|
|
|
|
let mut text_changes = Vec::new();
|
|
|
|
for text_change in &change.text_changes {
|
2022-12-29 15:07:09 -05:00
|
|
|
let lines = text_change.new_text.split('\n');
|
|
|
|
|
|
|
|
let new_lines: Vec<String> = lines
|
|
|
|
.map(|line| {
|
|
|
|
// This assumes that there's only one import per line.
|
|
|
|
if let Some(captures) = IMPORT_SPECIFIER_RE.captures(line) {
|
2024-07-23 14:39:14 -04:00
|
|
|
let specifier =
|
|
|
|
captures.iter().skip(1).find_map(|s| s).unwrap().as_str();
|
2022-12-29 15:07:09 -05:00
|
|
|
if let Some(new_specifier) =
|
2023-07-03 14:09:24 -04:00
|
|
|
import_mapper.check_unresolved_specifier(specifier, referrer)
|
2022-12-29 15:07:09 -05:00
|
|
|
{
|
|
|
|
line.replace(specifier, &new_specifier)
|
|
|
|
} else {
|
|
|
|
line.to_string()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
line.to_string()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
text_changes.push(tsc::TextChange {
|
|
|
|
span: text_change.span.clone(),
|
|
|
|
new_text: new_lines.join("\n").to_string(),
|
|
|
|
});
|
2021-05-29 07:21:11 -04:00
|
|
|
}
|
|
|
|
r.push(tsc::FileTextChanges {
|
|
|
|
file_name: change.file_name.clone(),
|
|
|
|
text_changes,
|
|
|
|
is_new_file: change.is_new_file,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
Ok(r)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Fix tsc import code actions so that the module specifier is correct for
|
|
|
|
/// resolution by Deno (includes the extension).
|
2024-10-25 16:52:50 -04:00
|
|
|
fn fix_ts_import_action<'a>(
|
2021-05-29 07:21:11 -04:00
|
|
|
referrer: &ModuleSpecifier,
|
2024-10-25 16:52:50 -04:00
|
|
|
action: &'a tsc::CodeFixAction,
|
2024-11-06 01:26:46 -05:00
|
|
|
language_server: &language_server::Inner,
|
2024-10-25 16:52:50 -04:00
|
|
|
) -> Option<Cow<'a, tsc::CodeFixAction>> {
|
|
|
|
if !matches!(
|
2024-05-21 16:15:16 -04:00
|
|
|
action.fix_name.as_str(),
|
|
|
|
"import" | "fixMissingFunctionDeclaration"
|
|
|
|
) {
|
2024-10-25 16:52:50 -04:00
|
|
|
return Some(Cow::Borrowed(action));
|
|
|
|
}
|
|
|
|
let specifier = (|| {
|
|
|
|
let text_change = action.changes.first()?.text_changes.first()?;
|
|
|
|
let captures = IMPORT_SPECIFIER_RE.captures(&text_change.new_text)?;
|
|
|
|
Some(captures.get(1)?.as_str())
|
|
|
|
})();
|
|
|
|
let Some(specifier) = specifier else {
|
|
|
|
return Some(Cow::Borrowed(action));
|
|
|
|
};
|
2024-11-06 01:26:46 -05:00
|
|
|
let import_mapper = language_server.get_ts_response_import_mapper(referrer);
|
2024-10-25 16:52:50 -04:00
|
|
|
if let Some(new_specifier) =
|
|
|
|
import_mapper.check_unresolved_specifier(specifier, referrer)
|
|
|
|
{
|
|
|
|
let description = action.description.replace(specifier, &new_specifier);
|
|
|
|
let changes = action
|
2021-05-29 07:21:11 -04:00
|
|
|
.changes
|
2024-10-25 16:52:50 -04:00
|
|
|
.iter()
|
|
|
|
.map(|c| {
|
|
|
|
let text_changes = c
|
|
|
|
.text_changes
|
2021-05-29 07:21:11 -04:00
|
|
|
.iter()
|
2024-10-25 16:52:50 -04:00
|
|
|
.map(|tc| tsc::TextChange {
|
|
|
|
span: tc.span.clone(),
|
|
|
|
new_text: tc.new_text.replace(specifier, &new_specifier),
|
2021-05-29 07:21:11 -04:00
|
|
|
})
|
|
|
|
.collect();
|
2024-10-25 16:52:50 -04:00
|
|
|
tsc::FileTextChanges {
|
|
|
|
file_name: c.file_name.clone(),
|
|
|
|
text_changes,
|
|
|
|
is_new_file: c.is_new_file,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect();
|
2021-05-29 07:21:11 -04:00
|
|
|
|
2024-10-25 16:52:50 -04:00
|
|
|
Some(Cow::Owned(tsc::CodeFixAction {
|
|
|
|
description,
|
|
|
|
changes,
|
|
|
|
commands: None,
|
|
|
|
fix_name: action.fix_name.clone(),
|
|
|
|
fix_id: None,
|
|
|
|
fix_all_description: None,
|
|
|
|
}))
|
|
|
|
} else if !import_mapper.is_valid_import(specifier, referrer) {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(Cow::Borrowed(action))
|
2021-05-29 07:21:11 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-04 13:53:02 -05:00
|
|
|
/// Determines if two TypeScript diagnostic codes are effectively equivalent.
|
|
|
|
fn is_equivalent_code(
|
|
|
|
a: &Option<lsp::NumberOrString>,
|
|
|
|
b: &Option<lsp::NumberOrString>,
|
|
|
|
) -> bool {
|
|
|
|
let a_code = code_as_string(a);
|
|
|
|
let b_code = code_as_string(b);
|
|
|
|
FIX_ALL_ERROR_CODES.get(a_code.as_str())
|
|
|
|
== FIX_ALL_ERROR_CODES.get(b_code.as_str())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return a boolean flag to indicate if the specified action is the preferred
|
|
|
|
/// action for a given set of actions.
|
|
|
|
fn is_preferred(
|
|
|
|
action: &tsc::CodeFixAction,
|
2021-02-11 23:17:48 -05:00
|
|
|
actions: &[CodeActionKind],
|
2021-02-04 13:53:02 -05:00
|
|
|
fix_priority: u32,
|
|
|
|
only_one: bool,
|
|
|
|
) -> bool {
|
2021-02-11 23:17:48 -05:00
|
|
|
actions.iter().all(|i| {
|
|
|
|
if let CodeActionKind::Tsc(_, a) = i {
|
|
|
|
if action == a {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
if a.fix_id.is_some() {
|
|
|
|
return true;
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
2021-02-11 23:17:48 -05:00
|
|
|
if let Some((other_fix_priority, _)) =
|
|
|
|
PREFERRED_FIXES.get(a.fix_name.as_str())
|
|
|
|
{
|
|
|
|
match other_fix_priority.cmp(&fix_priority) {
|
|
|
|
Ordering::Less => return true,
|
|
|
|
Ordering::Greater => return false,
|
|
|
|
Ordering::Equal => (),
|
|
|
|
}
|
|
|
|
if only_one && action.fix_name == a.fix_name {
|
|
|
|
return false;
|
|
|
|
}
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
2021-02-11 23:17:48 -05:00
|
|
|
true
|
2024-03-26 23:10:23 -04:00
|
|
|
} else if let CodeActionKind::Deno(_) = i {
|
|
|
|
// This is to make sure 'Remove import' isn't preferred over 'Cache
|
|
|
|
// dependencies'.
|
|
|
|
return false;
|
2021-02-11 23:17:48 -05:00
|
|
|
} else {
|
|
|
|
true
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convert changes returned from a TypeScript quick fix action into edits
|
|
|
|
/// for an LSP CodeAction.
|
2022-04-25 11:23:24 -04:00
|
|
|
pub fn ts_changes_to_edit(
|
2021-02-04 13:53:02 -05:00
|
|
|
changes: &[tsc::FileTextChanges],
|
2022-01-19 11:38:40 -05:00
|
|
|
language_server: &language_server::Inner,
|
2021-02-06 07:39:01 -05:00
|
|
|
) -> Result<Option<lsp::WorkspaceEdit>, AnyError> {
|
2021-02-04 13:53:02 -05:00
|
|
|
let mut text_document_edits = Vec::new();
|
|
|
|
for change in changes {
|
2024-11-12 08:15:32 -05:00
|
|
|
let edit = match change.to_text_document_edit(language_server) {
|
|
|
|
Ok(e) => e,
|
|
|
|
Err(err) => {
|
|
|
|
lsp_warn!("Couldn't covert text document edit: {:#}", err);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
text_document_edits.push(edit);
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
|
|
|
Ok(Some(lsp::WorkspaceEdit {
|
|
|
|
changes: None,
|
|
|
|
document_changes: Some(lsp::DocumentChanges::Edits(text_document_edits)),
|
|
|
|
change_annotations: None,
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
2024-11-06 01:26:46 -05:00
|
|
|
#[derive(Debug, Deserialize, Serialize)]
|
2021-02-05 15:10:53 -05:00
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct CodeActionData {
|
|
|
|
pub specifier: ModuleSpecifier,
|
|
|
|
pub fix_id: String,
|
|
|
|
}
|
|
|
|
|
2021-02-11 23:17:48 -05:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
enum CodeActionKind {
|
|
|
|
Deno(lsp::CodeAction),
|
2021-06-21 02:43:35 -04:00
|
|
|
DenoLint(lsp::CodeAction),
|
2021-02-11 23:17:48 -05:00
|
|
|
Tsc(lsp::CodeAction, tsc::CodeFixAction),
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Hash, PartialEq, Eq)]
|
|
|
|
enum FixAllKind {
|
|
|
|
Tsc(String),
|
|
|
|
}
|
|
|
|
|
2021-02-04 13:53:02 -05:00
|
|
|
#[derive(Debug, Default)]
|
|
|
|
pub struct CodeActionCollection {
|
2021-02-11 23:17:48 -05:00
|
|
|
actions: Vec<CodeActionKind>,
|
|
|
|
fix_all_actions: HashMap<FixAllKind, CodeActionKind>,
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl CodeActionCollection {
|
2022-03-23 09:54:22 -04:00
|
|
|
pub fn add_deno_fix_action(
|
2021-02-11 23:17:48 -05:00
|
|
|
&mut self,
|
2021-12-15 22:53:17 -05:00
|
|
|
specifier: &ModuleSpecifier,
|
2021-02-11 23:17:48 -05:00
|
|
|
diagnostic: &lsp::Diagnostic,
|
|
|
|
) -> Result<(), AnyError> {
|
2022-02-04 02:14:57 -05:00
|
|
|
let code_action = DenoDiagnostic::get_code_action(specifier, diagnostic)?;
|
|
|
|
self.actions.push(CodeActionKind::Deno(code_action));
|
2021-02-11 23:17:48 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-03-21 17:18:59 -04:00
|
|
|
pub fn add_deno_lint_actions(
|
|
|
|
&mut self,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
diagnostic: &lsp::Diagnostic,
|
2024-06-05 11:04:16 -04:00
|
|
|
maybe_text_info: Option<&SourceTextInfo>,
|
|
|
|
maybe_parsed_source: Option<&deno_ast::ParsedSource>,
|
2024-03-21 17:18:59 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
if let Some(data_quick_fixes) = diagnostic
|
|
|
|
.data
|
|
|
|
.as_ref()
|
|
|
|
.and_then(|d| serde_json::from_value::<Vec<DataQuickFix>>(d.clone()).ok())
|
|
|
|
{
|
2024-08-28 00:15:48 -04:00
|
|
|
let uri = url_to_uri(specifier)?;
|
2024-03-21 17:18:59 -04:00
|
|
|
for quick_fix in data_quick_fixes {
|
|
|
|
let mut changes = HashMap::new();
|
|
|
|
changes.insert(
|
2024-08-23 20:21:21 -04:00
|
|
|
uri.clone(),
|
2024-03-21 17:18:59 -04:00
|
|
|
quick_fix
|
|
|
|
.changes
|
|
|
|
.into_iter()
|
|
|
|
.map(|change| lsp::TextEdit {
|
|
|
|
new_text: change.new_text.clone(),
|
|
|
|
range: change.range,
|
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
);
|
|
|
|
let code_action = lsp::CodeAction {
|
|
|
|
title: quick_fix.description.to_string(),
|
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(vec![diagnostic.clone()]),
|
|
|
|
command: None,
|
|
|
|
is_preferred: None,
|
|
|
|
disabled: None,
|
|
|
|
data: None,
|
|
|
|
edit: Some(lsp::WorkspaceEdit {
|
|
|
|
changes: Some(changes),
|
|
|
|
change_annotations: None,
|
|
|
|
document_changes: None,
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
self.actions.push(CodeActionKind::DenoLint(code_action));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
self.add_deno_lint_ignore_action(
|
|
|
|
specifier,
|
|
|
|
diagnostic,
|
|
|
|
maybe_text_info,
|
|
|
|
maybe_parsed_source,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn add_deno_lint_ignore_action(
|
2021-06-21 02:43:35 -04:00
|
|
|
&mut self,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
diagnostic: &lsp::Diagnostic,
|
2024-06-05 11:04:16 -04:00
|
|
|
maybe_text_info: Option<&SourceTextInfo>,
|
|
|
|
maybe_parsed_source: Option<&deno_ast::ParsedSource>,
|
2021-06-21 02:43:35 -04:00
|
|
|
) -> Result<(), AnyError> {
|
2024-08-28 00:15:48 -04:00
|
|
|
let uri = url_to_uri(specifier)?;
|
2021-06-21 02:43:35 -04:00
|
|
|
let code = diagnostic
|
|
|
|
.code
|
|
|
|
.as_ref()
|
|
|
|
.map(|v| match v {
|
|
|
|
lsp::NumberOrString::String(v) => v.to_owned(),
|
|
|
|
_ => "".to_string(),
|
|
|
|
})
|
|
|
|
.unwrap();
|
|
|
|
|
2021-10-28 19:56:01 -04:00
|
|
|
let line_content = maybe_text_info.map(|ti| {
|
|
|
|
ti.line_text(diagnostic.range.start.line as usize)
|
2021-09-07 10:39:32 -04:00
|
|
|
.to_string()
|
|
|
|
});
|
2021-06-21 02:43:35 -04:00
|
|
|
|
|
|
|
let mut changes = HashMap::new();
|
|
|
|
changes.insert(
|
2024-08-23 20:21:21 -04:00
|
|
|
uri.clone(),
|
2021-06-21 02:43:35 -04:00
|
|
|
vec![lsp::TextEdit {
|
|
|
|
new_text: prepend_whitespace(
|
2023-01-27 10:43:16 -05:00
|
|
|
format!("// deno-lint-ignore {code}\n"),
|
2021-06-21 02:43:35 -04:00
|
|
|
line_content,
|
|
|
|
),
|
|
|
|
range: lsp::Range {
|
|
|
|
start: lsp::Position {
|
|
|
|
line: diagnostic.range.start.line,
|
|
|
|
character: 0,
|
|
|
|
},
|
|
|
|
end: lsp::Position {
|
|
|
|
line: diagnostic.range.start.line,
|
|
|
|
character: 0,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}],
|
|
|
|
);
|
|
|
|
let ignore_error_action = lsp::CodeAction {
|
2023-01-27 10:43:16 -05:00
|
|
|
title: format!("Disable {code} for this line"),
|
2021-06-21 02:43:35 -04:00
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(vec![diagnostic.clone()]),
|
|
|
|
command: None,
|
|
|
|
is_preferred: None,
|
|
|
|
disabled: None,
|
|
|
|
data: None,
|
|
|
|
edit: Some(lsp::WorkspaceEdit {
|
|
|
|
changes: Some(changes),
|
|
|
|
change_annotations: None,
|
|
|
|
document_changes: None,
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
self
|
|
|
|
.actions
|
|
|
|
.push(CodeActionKind::DenoLint(ignore_error_action));
|
|
|
|
|
2021-09-14 08:16:51 -04:00
|
|
|
// Disable a lint error for the entire file.
|
2024-06-05 11:04:16 -04:00
|
|
|
let maybe_ignore_comment = maybe_parsed_source.and_then(|ps| {
|
2021-09-14 08:16:51 -04:00
|
|
|
// Note: we can use ps.get_leading_comments() but it doesn't
|
|
|
|
// work when shebang is present at the top of the file.
|
|
|
|
ps.comments().get_vec().iter().find_map(|c| {
|
|
|
|
let comment_text = c.text.trim();
|
|
|
|
comment_text.split_whitespace().next().and_then(|prefix| {
|
|
|
|
if prefix == "deno-lint-ignore-file" {
|
|
|
|
Some(c.clone())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
2023-01-27 10:43:16 -05:00
|
|
|
let mut new_text = format!("// deno-lint-ignore-file {code}\n");
|
2021-09-14 08:16:51 -04:00
|
|
|
let mut range = lsp::Range {
|
|
|
|
start: lsp::Position {
|
|
|
|
line: 0,
|
|
|
|
character: 0,
|
|
|
|
},
|
|
|
|
end: lsp::Position {
|
|
|
|
line: 0,
|
|
|
|
character: 0,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
// If ignore file comment already exists, append the lint code
|
|
|
|
// to the existing comment.
|
|
|
|
if let Some(ignore_comment) = maybe_ignore_comment {
|
2023-01-27 10:43:16 -05:00
|
|
|
new_text = format!(" {code}");
|
2021-09-14 08:16:51 -04:00
|
|
|
// Get the end position of the comment.
|
2024-06-05 11:04:16 -04:00
|
|
|
let line = maybe_text_info
|
2021-09-14 08:16:51 -04:00
|
|
|
.unwrap()
|
2022-05-20 16:40:55 -04:00
|
|
|
.line_and_column_index(ignore_comment.end());
|
2021-09-14 08:16:51 -04:00
|
|
|
let position = lsp::Position {
|
|
|
|
line: line.line_index as u32,
|
|
|
|
character: line.column_index as u32,
|
|
|
|
};
|
|
|
|
// Set the edit range to the end of the comment.
|
|
|
|
range.start = position;
|
|
|
|
range.end = position;
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut changes = HashMap::new();
|
2024-08-23 20:21:21 -04:00
|
|
|
changes.insert(uri.clone(), vec![lsp::TextEdit { new_text, range }]);
|
2021-09-14 08:16:51 -04:00
|
|
|
let ignore_file_action = lsp::CodeAction {
|
2023-01-27 10:43:16 -05:00
|
|
|
title: format!("Disable {code} for the entire file"),
|
2021-09-14 08:16:51 -04:00
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(vec![diagnostic.clone()]),
|
|
|
|
command: None,
|
|
|
|
is_preferred: None,
|
|
|
|
disabled: None,
|
|
|
|
data: None,
|
|
|
|
edit: Some(lsp::WorkspaceEdit {
|
|
|
|
changes: Some(changes),
|
|
|
|
change_annotations: None,
|
|
|
|
document_changes: None,
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
self
|
|
|
|
.actions
|
|
|
|
.push(CodeActionKind::DenoLint(ignore_file_action));
|
|
|
|
|
2021-06-21 02:43:35 -04:00
|
|
|
let mut changes = HashMap::new();
|
|
|
|
changes.insert(
|
2024-08-23 20:21:21 -04:00
|
|
|
uri,
|
2021-06-21 02:43:35 -04:00
|
|
|
vec![lsp::TextEdit {
|
|
|
|
new_text: "// deno-lint-ignore-file\n".to_string(),
|
|
|
|
range: lsp::Range {
|
|
|
|
start: lsp::Position {
|
|
|
|
line: 0,
|
|
|
|
character: 0,
|
|
|
|
},
|
|
|
|
end: lsp::Position {
|
|
|
|
line: 0,
|
|
|
|
character: 0,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}],
|
|
|
|
);
|
|
|
|
let ignore_file_action = lsp::CodeAction {
|
|
|
|
title: "Ignore lint errors for the entire file".to_string(),
|
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(vec![diagnostic.clone()]),
|
|
|
|
command: None,
|
|
|
|
is_preferred: None,
|
|
|
|
disabled: None,
|
|
|
|
data: None,
|
|
|
|
edit: Some(lsp::WorkspaceEdit {
|
|
|
|
changes: Some(changes),
|
|
|
|
change_annotations: None,
|
|
|
|
document_changes: None,
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
self
|
|
|
|
.actions
|
|
|
|
.push(CodeActionKind::DenoLint(ignore_file_action));
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-02-04 13:53:02 -05:00
|
|
|
/// Add a TypeScript code fix action to the code actions collection.
|
2022-04-25 11:23:24 -04:00
|
|
|
pub fn add_ts_fix_action(
|
2021-02-04 13:53:02 -05:00
|
|
|
&mut self,
|
2021-05-29 07:21:11 -04:00
|
|
|
specifier: &ModuleSpecifier,
|
2021-02-04 13:53:02 -05:00
|
|
|
action: &tsc::CodeFixAction,
|
|
|
|
diagnostic: &lsp::Diagnostic,
|
2022-01-19 11:38:40 -05:00
|
|
|
language_server: &language_server::Inner,
|
2021-02-06 07:39:01 -05:00
|
|
|
) -> Result<(), AnyError> {
|
2021-02-04 13:53:02 -05:00
|
|
|
if action.commands.is_some() {
|
|
|
|
// In theory, tsc can return actions that require "commands" to be applied
|
|
|
|
// back into TypeScript. Currently there is only one command, `install
|
|
|
|
// package` but Deno doesn't support that. The problem is that the
|
|
|
|
// `.applyCodeActionCommand()` returns a promise, and with the current way
|
|
|
|
// we wrap tsc, we can't handle the asynchronous response, so it is
|
|
|
|
// actually easier to return errors if we ever encounter one of these,
|
|
|
|
// which we really wouldn't expect from the Deno lsp.
|
|
|
|
return Err(custom_error(
|
|
|
|
"UnsupportedFix",
|
|
|
|
"The action returned from TypeScript is unsupported.",
|
|
|
|
));
|
|
|
|
}
|
2024-11-06 01:26:46 -05:00
|
|
|
let Some(action) = fix_ts_import_action(specifier, action, language_server)
|
|
|
|
else {
|
2024-10-07 13:20:45 -04:00
|
|
|
return Ok(());
|
|
|
|
};
|
2022-04-25 11:23:24 -04:00
|
|
|
let edit = ts_changes_to_edit(&action.changes, language_server)?;
|
2021-02-04 13:53:02 -05:00
|
|
|
let code_action = lsp::CodeAction {
|
|
|
|
title: action.description.clone(),
|
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(vec![diagnostic.clone()]),
|
|
|
|
edit,
|
|
|
|
command: None,
|
|
|
|
is_preferred: None,
|
|
|
|
disabled: None,
|
|
|
|
data: None,
|
|
|
|
};
|
2021-02-11 23:17:48 -05:00
|
|
|
self.actions.retain(|i| match i {
|
|
|
|
CodeActionKind::Tsc(c, a) => {
|
|
|
|
!(action.fix_name == a.fix_name && code_action.edit == c.edit)
|
|
|
|
}
|
|
|
|
_ => true,
|
2021-02-04 13:53:02 -05:00
|
|
|
});
|
2021-02-11 23:17:48 -05:00
|
|
|
self
|
|
|
|
.actions
|
2024-10-25 16:52:50 -04:00
|
|
|
.push(CodeActionKind::Tsc(code_action, action.as_ref().clone()));
|
2021-02-04 13:53:02 -05:00
|
|
|
|
|
|
|
if let Some(fix_id) = &action.fix_id {
|
2021-02-11 23:17:48 -05:00
|
|
|
if let Some(CodeActionKind::Tsc(existing_fix_all, existing_action)) =
|
|
|
|
self.fix_all_actions.get(&FixAllKind::Tsc(fix_id.clone()))
|
2021-02-04 13:53:02 -05:00
|
|
|
{
|
2021-02-11 23:17:48 -05:00
|
|
|
self.actions.retain(|i| match i {
|
|
|
|
CodeActionKind::Tsc(c, _) => c != existing_fix_all,
|
|
|
|
_ => true,
|
|
|
|
});
|
|
|
|
self.actions.push(CodeActionKind::Tsc(
|
|
|
|
existing_fix_all.clone(),
|
|
|
|
existing_action.clone(),
|
|
|
|
));
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add a TypeScript action to the actions as a "fix all" action, where it
|
|
|
|
/// will fix all occurrences of the diagnostic in the file.
|
2021-02-05 15:10:53 -05:00
|
|
|
pub fn add_ts_fix_all_action(
|
2021-02-04 13:53:02 -05:00
|
|
|
&mut self,
|
|
|
|
action: &tsc::CodeFixAction,
|
2021-02-05 15:10:53 -05:00
|
|
|
specifier: &ModuleSpecifier,
|
2021-02-04 13:53:02 -05:00
|
|
|
diagnostic: &lsp::Diagnostic,
|
2021-02-05 15:10:53 -05:00
|
|
|
) {
|
2024-11-06 01:26:46 -05:00
|
|
|
let data = action.fix_id.as_ref().map(|fix_id| {
|
|
|
|
json!(CodeActionData {
|
|
|
|
specifier: specifier.clone(),
|
|
|
|
fix_id: fix_id.clone(),
|
|
|
|
})
|
|
|
|
});
|
2021-02-04 13:53:02 -05:00
|
|
|
let title = if let Some(description) = &action.fix_all_description {
|
|
|
|
description.clone()
|
|
|
|
} else {
|
|
|
|
format!("{} (Fix all in file)", action.description)
|
|
|
|
};
|
|
|
|
|
|
|
|
let code_action = lsp::CodeAction {
|
|
|
|
title,
|
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(vec![diagnostic.clone()]),
|
2021-02-05 15:10:53 -05:00
|
|
|
edit: None,
|
2021-02-04 13:53:02 -05:00
|
|
|
command: None,
|
|
|
|
is_preferred: None,
|
|
|
|
disabled: None,
|
2021-02-05 15:10:53 -05:00
|
|
|
data,
|
2021-02-04 13:53:02 -05:00
|
|
|
};
|
2021-02-11 23:17:48 -05:00
|
|
|
if let Some(CodeActionKind::Tsc(existing, _)) = self
|
|
|
|
.fix_all_actions
|
|
|
|
.get(&FixAllKind::Tsc(action.fix_id.clone().unwrap()))
|
2021-02-04 13:53:02 -05:00
|
|
|
{
|
2021-02-11 23:17:48 -05:00
|
|
|
self.actions.retain(|i| match i {
|
|
|
|
CodeActionKind::Tsc(c, _) => c != existing,
|
|
|
|
_ => true,
|
|
|
|
});
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
2021-02-11 23:17:48 -05:00
|
|
|
self
|
|
|
|
.actions
|
|
|
|
.push(CodeActionKind::Tsc(code_action.clone(), action.clone()));
|
2021-02-04 13:53:02 -05:00
|
|
|
self.fix_all_actions.insert(
|
2021-02-11 23:17:48 -05:00
|
|
|
FixAllKind::Tsc(action.fix_id.clone().unwrap()),
|
|
|
|
CodeActionKind::Tsc(code_action, action.clone()),
|
2021-02-04 13:53:02 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Move out the code actions and return them as a `CodeActionResponse`.
|
|
|
|
pub fn get_response(self) -> lsp::CodeActionResponse {
|
2024-03-26 23:10:23 -04:00
|
|
|
// Prefer Deno fixes first, then TSC fixes, then Deno lint fixes.
|
|
|
|
let (deno, rest): (Vec<_>, Vec<_>) = self
|
2023-09-18 12:39:28 -04:00
|
|
|
.actions
|
|
|
|
.into_iter()
|
|
|
|
.partition(|a| matches!(a, CodeActionKind::Deno(_)));
|
2024-03-26 23:10:23 -04:00
|
|
|
let (tsc, deno_lint): (Vec<_>, Vec<_>) = rest
|
|
|
|
.into_iter()
|
|
|
|
.partition(|a| matches!(a, CodeActionKind::Tsc(..)));
|
2023-09-17 14:05:19 -04:00
|
|
|
|
2024-03-26 23:10:23 -04:00
|
|
|
deno
|
2021-02-04 13:53:02 -05:00
|
|
|
.into_iter()
|
2024-03-26 23:10:23 -04:00
|
|
|
.chain(tsc)
|
2023-09-18 12:39:28 -04:00
|
|
|
.chain(deno_lint)
|
|
|
|
.map(|k| match k {
|
2021-02-11 23:17:48 -05:00
|
|
|
CodeActionKind::Deno(c) => lsp::CodeActionOrCommand::CodeAction(c),
|
2021-06-21 02:43:35 -04:00
|
|
|
CodeActionKind::DenoLint(c) => lsp::CodeActionOrCommand::CodeAction(c),
|
2023-09-18 12:39:28 -04:00
|
|
|
CodeActionKind::Tsc(c, _) => lsp::CodeActionOrCommand::CodeAction(c),
|
2021-02-11 23:17:48 -05:00
|
|
|
})
|
2021-02-04 13:53:02 -05:00
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Determine if a action can be converted into a "fix all" action.
|
|
|
|
pub fn is_fix_all_action(
|
|
|
|
&self,
|
|
|
|
action: &tsc::CodeFixAction,
|
|
|
|
diagnostic: &lsp::Diagnostic,
|
2021-02-06 07:39:01 -05:00
|
|
|
file_diagnostics: &[lsp::Diagnostic],
|
2021-02-04 13:53:02 -05:00
|
|
|
) -> bool {
|
|
|
|
// If the action does not have a fix id (indicating it can be "bundled up")
|
|
|
|
// or if the collection already contains a "bundled" action return false
|
|
|
|
if action.fix_id.is_none()
|
|
|
|
|| self
|
|
|
|
.fix_all_actions
|
2021-02-11 23:17:48 -05:00
|
|
|
.contains_key(&FixAllKind::Tsc(action.fix_id.clone().unwrap()))
|
2021-02-04 13:53:02 -05:00
|
|
|
{
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
// else iterate over the diagnostic in the file and see if there are any
|
|
|
|
// other diagnostics that could be bundled together in a "fix all" code
|
|
|
|
// action
|
|
|
|
file_diagnostics.iter().any(|d| {
|
2021-02-06 07:39:01 -05:00
|
|
|
if d == diagnostic || d.code.is_none() || diagnostic.code.is_none() {
|
2021-02-04 13:53:02 -05:00
|
|
|
false
|
|
|
|
} else {
|
|
|
|
d.code == diagnostic.code
|
|
|
|
|| is_equivalent_code(&d.code, &diagnostic.code)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the `.is_preferred` flag on code actions, this should be only executed
|
|
|
|
/// when all actions are added to the collection.
|
|
|
|
pub fn set_preferred_fixes(&mut self) {
|
|
|
|
let actions = self.actions.clone();
|
2021-02-11 23:17:48 -05:00
|
|
|
for entry in self.actions.iter_mut() {
|
|
|
|
if let CodeActionKind::Tsc(code_action, action) = entry {
|
|
|
|
if action.fix_id.is_some() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if let Some((fix_priority, only_one)) =
|
|
|
|
PREFERRED_FIXES.get(action.fix_name.as_str())
|
|
|
|
{
|
|
|
|
code_action.is_preferred =
|
|
|
|
Some(is_preferred(action, &actions, *fix_priority, *only_one));
|
|
|
|
}
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-09-24 18:33:52 -04:00
|
|
|
|
|
|
|
pub fn add_cache_all_action(
|
|
|
|
&mut self,
|
|
|
|
specifier: &ModuleSpecifier,
|
|
|
|
diagnostics: Vec<lsp::Diagnostic>,
|
|
|
|
) {
|
|
|
|
self.actions.push(CodeActionKind::Deno(lsp::CodeAction {
|
|
|
|
title: "Cache all dependencies of this module.".to_string(),
|
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: Some(diagnostics),
|
|
|
|
command: Some(lsp::Command {
|
|
|
|
title: "".to_string(),
|
|
|
|
command: "deno.cache".to_string(),
|
|
|
|
arguments: Some(vec![json!([]), json!(&specifier)]),
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
}));
|
|
|
|
}
|
2024-10-01 17:55:02 -04:00
|
|
|
|
|
|
|
pub async fn add_source_actions(
|
|
|
|
&mut self,
|
|
|
|
document: &Document,
|
|
|
|
range: &lsp::Range,
|
|
|
|
language_server: &language_server::Inner,
|
|
|
|
) {
|
2024-10-08 07:48:29 -04:00
|
|
|
fn import_start_from_specifier(
|
|
|
|
document: &Document,
|
|
|
|
import: &deno_graph::Import,
|
|
|
|
) -> Option<LineAndColumnIndex> {
|
|
|
|
// find the top level statement that contains the specifier
|
|
|
|
let parsed_source = document.maybe_parsed_source()?.as_ref().ok()?;
|
|
|
|
let text_info = parsed_source.text_info_lazy();
|
|
|
|
let specifier_range = SourceRange::new(
|
|
|
|
text_info.loc_to_source_pos(LineAndColumnIndex {
|
|
|
|
line_index: import.specifier_range.start.line,
|
|
|
|
column_index: import.specifier_range.start.character,
|
|
|
|
}),
|
|
|
|
text_info.loc_to_source_pos(LineAndColumnIndex {
|
|
|
|
line_index: import.specifier_range.end.line,
|
|
|
|
column_index: import.specifier_range.end.character,
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
2024-11-01 12:27:00 -04:00
|
|
|
parsed_source
|
|
|
|
.program_ref()
|
|
|
|
.body()
|
|
|
|
.find(|i| i.range().contains(&specifier_range))
|
|
|
|
.map(|i| text_info.line_and_column_index(i.range().start))
|
2024-10-08 07:48:29 -04:00
|
|
|
}
|
|
|
|
|
2024-10-01 17:55:02 -04:00
|
|
|
async fn deno_types_for_npm_action(
|
|
|
|
document: &Document,
|
|
|
|
range: &lsp::Range,
|
|
|
|
language_server: &language_server::Inner,
|
|
|
|
) -> Option<lsp::CodeAction> {
|
|
|
|
let (dep_key, dependency, _) =
|
|
|
|
document.get_maybe_dependency(&range.end)?;
|
|
|
|
if dependency.maybe_deno_types_specifier.is_some() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
if dependency.maybe_code.maybe_specifier().is_none()
|
|
|
|
&& dependency.maybe_type.maybe_specifier().is_none()
|
|
|
|
{
|
|
|
|
// We're using byonm and the package is not cached.
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let position = deno_graph::Position::new(
|
|
|
|
range.end.line as usize,
|
|
|
|
range.end.character as usize,
|
|
|
|
);
|
2024-10-08 07:48:29 -04:00
|
|
|
let import_start = dependency.imports.iter().find_map(|i| {
|
2024-10-01 17:55:02 -04:00
|
|
|
if json!(i.kind) != json!("es") && json!(i.kind) != json!("tsType") {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
if !i.specifier_range.includes(&position) {
|
|
|
|
return None;
|
|
|
|
}
|
2024-10-08 07:48:29 -04:00
|
|
|
|
|
|
|
import_start_from_specifier(document, i)
|
2024-10-01 17:55:02 -04:00
|
|
|
})?;
|
|
|
|
let referrer = document.specifier();
|
|
|
|
let file_referrer = document.file_referrer();
|
|
|
|
let config_data = language_server
|
|
|
|
.config
|
|
|
|
.tree
|
|
|
|
.data_for_specifier(file_referrer?)?;
|
|
|
|
let workspace_resolver = config_data.resolver.clone();
|
|
|
|
let npm_ref = if let Ok(resolution) =
|
|
|
|
workspace_resolver.resolve(&dep_key, document.specifier())
|
|
|
|
{
|
|
|
|
let specifier = match resolution {
|
|
|
|
MappedResolution::Normal { specifier, .. }
|
|
|
|
| MappedResolution::ImportMap { specifier, .. } => specifier,
|
|
|
|
_ => {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
NpmPackageReqReference::from_specifier(&specifier).ok()?
|
|
|
|
} else {
|
|
|
|
// Only resolve bare package.json deps for byonm.
|
|
|
|
if !config_data.byonm {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
if !language_server
|
|
|
|
.resolver
|
|
|
|
.is_bare_package_json_dep(&dep_key, referrer)
|
|
|
|
{
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
NpmPackageReqReference::from_str(&format!("npm:{}", &dep_key)).ok()?
|
|
|
|
};
|
|
|
|
let package_name = &npm_ref.req().name;
|
|
|
|
if package_name.starts_with("@types/") {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let managed_npm_resolver = language_server
|
|
|
|
.resolver
|
|
|
|
.maybe_managed_npm_resolver(file_referrer);
|
|
|
|
if let Some(npm_resolver) = managed_npm_resolver {
|
|
|
|
if !npm_resolver.is_pkg_req_folder_cached(npm_ref.req()) {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if language_server
|
|
|
|
.resolver
|
|
|
|
.npm_to_file_url(&npm_ref, document.specifier(), file_referrer)
|
|
|
|
.is_some()
|
|
|
|
{
|
|
|
|
// The package import has types.
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let types_package_name = format!("@types/{package_name}");
|
|
|
|
let types_package_version = language_server
|
|
|
|
.npm_search_api
|
|
|
|
.versions(&types_package_name)
|
|
|
|
.await
|
|
|
|
.ok()
|
|
|
|
.and_then(|versions| versions.first().cloned())?;
|
|
|
|
let types_specifier_text =
|
|
|
|
if let Some(npm_resolver) = managed_npm_resolver {
|
|
|
|
let mut specifier_text = if let Some(req) =
|
|
|
|
npm_resolver.top_package_req_for_name(&types_package_name)
|
|
|
|
{
|
|
|
|
format!("npm:{req}")
|
|
|
|
} else {
|
|
|
|
format!("npm:{}@^{}", &types_package_name, types_package_version)
|
|
|
|
};
|
|
|
|
let specifier = ModuleSpecifier::parse(&specifier_text).ok()?;
|
|
|
|
if let Some(file_referrer) = file_referrer {
|
|
|
|
if let Some(text) = language_server
|
|
|
|
.get_ts_response_import_mapper(file_referrer)
|
|
|
|
.check_specifier(&specifier, referrer)
|
|
|
|
{
|
|
|
|
specifier_text = text;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
specifier_text
|
|
|
|
} else {
|
|
|
|
types_package_name.clone()
|
|
|
|
};
|
|
|
|
let uri = language_server
|
|
|
|
.url_map
|
|
|
|
.specifier_to_uri(referrer, file_referrer)
|
|
|
|
.ok()?;
|
|
|
|
let position = lsp::Position {
|
2024-10-08 07:48:29 -04:00
|
|
|
line: import_start.line_index as u32,
|
|
|
|
character: import_start.column_index as u32,
|
2024-10-01 17:55:02 -04:00
|
|
|
};
|
|
|
|
let new_text = format!(
|
|
|
|
"{}// @deno-types=\"{}\"\n",
|
|
|
|
if position.character == 0 { "" } else { "\n" },
|
|
|
|
&types_specifier_text
|
|
|
|
);
|
|
|
|
let text_edit = lsp::TextEdit {
|
|
|
|
range: lsp::Range {
|
|
|
|
start: position,
|
|
|
|
end: position,
|
|
|
|
},
|
|
|
|
new_text,
|
|
|
|
};
|
|
|
|
Some(lsp::CodeAction {
|
|
|
|
title: format!(
|
|
|
|
"Add @deno-types directive for \"{}\"",
|
|
|
|
&types_specifier_text
|
|
|
|
),
|
|
|
|
kind: Some(lsp::CodeActionKind::QUICKFIX),
|
|
|
|
diagnostics: None,
|
|
|
|
edit: Some(lsp::WorkspaceEdit {
|
|
|
|
changes: Some([(uri, vec![text_edit])].into_iter().collect()),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if let Some(action) =
|
|
|
|
deno_types_for_npm_action(document, range, language_server).await
|
|
|
|
{
|
|
|
|
self.actions.push(CodeActionKind::Deno(action));
|
|
|
|
}
|
|
|
|
}
|
2021-02-04 13:53:02 -05:00
|
|
|
}
|
|
|
|
|
2021-06-21 02:43:35 -04:00
|
|
|
/// Prepend the whitespace characters found at the start of line_content to content.
|
|
|
|
fn prepend_whitespace(content: String, line_content: Option<String>) -> String {
|
|
|
|
if let Some(line) = line_content {
|
2024-04-15 19:07:32 -04:00
|
|
|
let whitespace_end = line
|
|
|
|
.char_indices()
|
|
|
|
.find_map(|(i, c)| (!c.is_whitespace()).then_some(i))
|
|
|
|
.unwrap_or(0);
|
|
|
|
let whitespace = &line[0..whitespace_end];
|
2021-06-21 02:43:35 -04:00
|
|
|
format!("{}{}", &whitespace, content)
|
|
|
|
} else {
|
|
|
|
content
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-20 16:40:55 -04:00
|
|
|
pub fn source_range_to_lsp_range(
|
|
|
|
range: &SourceRange,
|
|
|
|
source_text_info: &SourceTextInfo,
|
|
|
|
) -> lsp::Range {
|
|
|
|
let start = source_text_info.line_and_column_index(range.start);
|
|
|
|
let end = source_text_info.line_and_column_index(range.end);
|
|
|
|
lsp::Range {
|
|
|
|
start: lsp::Position {
|
|
|
|
line: start.line_index as u32,
|
|
|
|
character: start.column_index as u32,
|
|
|
|
},
|
|
|
|
end: lsp::Position {
|
|
|
|
line: end.line_index as u32,
|
|
|
|
character: end.column_index as u32,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-07 05:46:39 -05:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-07-01 21:07:57 -04:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
2020-12-07 05:46:39 -05:00
|
|
|
use super::*;
|
|
|
|
|
2021-05-25 18:15:09 -04:00
|
|
|
#[test]
|
|
|
|
fn test_reference_to_diagnostic() {
|
|
|
|
let range = Range {
|
|
|
|
start: Position {
|
|
|
|
line: 1,
|
|
|
|
character: 1,
|
|
|
|
},
|
|
|
|
end: Position {
|
|
|
|
line: 2,
|
|
|
|
character: 2,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
let test_cases = [
|
|
|
|
(
|
|
|
|
Reference {
|
|
|
|
category: Category::Lint {
|
|
|
|
message: "message1".to_string(),
|
|
|
|
code: "code1".to_string(),
|
|
|
|
hint: None,
|
2024-03-21 17:18:59 -04:00
|
|
|
quick_fixes: Vec::new(),
|
2021-05-25 18:15:09 -04:00
|
|
|
},
|
|
|
|
range,
|
|
|
|
},
|
|
|
|
lsp::Diagnostic {
|
|
|
|
range,
|
2021-11-24 20:10:12 -05:00
|
|
|
severity: Some(lsp::DiagnosticSeverity::WARNING),
|
2021-05-25 18:15:09 -04:00
|
|
|
code: Some(lsp::NumberOrString::String("code1".to_string())),
|
|
|
|
source: Some("deno-lint".to_string()),
|
|
|
|
message: "message1".to_string(),
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
),
|
|
|
|
(
|
|
|
|
Reference {
|
|
|
|
category: Category::Lint {
|
|
|
|
message: "message2".to_string(),
|
|
|
|
code: "code2".to_string(),
|
|
|
|
hint: Some("hint2".to_string()),
|
2024-03-21 17:18:59 -04:00
|
|
|
quick_fixes: Vec::new(),
|
2021-05-25 18:15:09 -04:00
|
|
|
},
|
|
|
|
range,
|
|
|
|
},
|
|
|
|
lsp::Diagnostic {
|
|
|
|
range,
|
2021-11-24 20:10:12 -05:00
|
|
|
severity: Some(lsp::DiagnosticSeverity::WARNING),
|
2021-05-25 18:15:09 -04:00
|
|
|
code: Some(lsp::NumberOrString::String("code2".to_string())),
|
|
|
|
source: Some("deno-lint".to_string()),
|
|
|
|
message: "message2\nhint2".to_string(),
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
),
|
|
|
|
];
|
|
|
|
|
|
|
|
for (input, expected) in test_cases.iter() {
|
|
|
|
let actual = input.to_diagnostic();
|
|
|
|
assert_eq!(&actual, expected);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-01 21:07:57 -04:00
|
|
|
#[test]
|
|
|
|
fn test_try_reverse_map_package_json_exports() {
|
|
|
|
let exports = json!({
|
|
|
|
".": {
|
|
|
|
"types": "./src/index.d.ts",
|
|
|
|
"browser": "./dist/module.js",
|
|
|
|
},
|
|
|
|
"./hooks": {
|
|
|
|
"types": "./hooks/index.d.ts",
|
|
|
|
"browser": "./dist/devtools.module.js",
|
|
|
|
},
|
|
|
|
"./utils": {
|
|
|
|
"types": {
|
|
|
|
"./sub_utils": "./utils_sub_utils.d.ts"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
let exports = exports.as_object().unwrap();
|
|
|
|
assert_eq!(
|
|
|
|
try_reverse_map_package_json_exports(
|
|
|
|
&PathBuf::from("/project/"),
|
|
|
|
&PathBuf::from("/project/hooks/index.d.ts"),
|
|
|
|
exports,
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
"hooks"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
try_reverse_map_package_json_exports(
|
|
|
|
&PathBuf::from("/project/"),
|
|
|
|
&PathBuf::from("/project/dist/devtools.module.js"),
|
|
|
|
exports,
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
"hooks"
|
|
|
|
);
|
|
|
|
assert!(try_reverse_map_package_json_exports(
|
|
|
|
&PathBuf::from("/project/"),
|
|
|
|
&PathBuf::from("/project/src/index.d.ts"),
|
|
|
|
exports,
|
|
|
|
)
|
|
|
|
.is_none());
|
|
|
|
assert_eq!(
|
|
|
|
try_reverse_map_package_json_exports(
|
|
|
|
&PathBuf::from("/project/"),
|
|
|
|
&PathBuf::from("/project/utils_sub_utils.d.ts"),
|
|
|
|
exports,
|
|
|
|
)
|
|
|
|
.unwrap(),
|
|
|
|
"utils/sub_utils"
|
|
|
|
);
|
|
|
|
}
|
2024-04-15 19:07:32 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_prepend_whitespace() {
|
|
|
|
// Regression test for https://github.com/denoland/deno/issues/23361.
|
|
|
|
assert_eq!(
|
|
|
|
&prepend_whitespace("foo".to_string(), Some("\u{a0}bar".to_string())),
|
|
|
|
"\u{a0}foo"
|
|
|
|
);
|
|
|
|
}
|
2020-12-07 05:46:39 -05:00
|
|
|
}
|