1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-12 10:37:52 -05:00

Merge branch 'main' into repl_restart

This commit is contained in:
Bartek Iwańczuk 2022-11-26 00:52:18 +01:00
commit 43f1f303e6
No known key found for this signature in database
GPG key ID: 0C6BCDDC3B3AD750
112 changed files with 303 additions and 358 deletions

View file

@ -21,12 +21,7 @@
".git",
"cli/bench/testdata/express-router.js",
"cli/bench/testdata/npm/*",
"cli/dts/lib.d.ts",
"cli/dts/lib.dom*",
"cli/dts/lib.es*",
"cli/dts/lib.scripthost.d.ts",
"cli/dts/lib.webworker*.d.ts",
"cli/dts/typescript.d.ts",
"cli/tsc/dts/*.d.ts",
"cli/tests/testdata/fmt/badly_formatted.json",
"cli/tests/testdata/fmt/badly_formatted.md",
"cli/tests/testdata/byte_order_mark.ts",

View file

@ -762,6 +762,157 @@ impl ConfigFile {
}
}
/// Represents the "default" type library that should be used when type
/// checking the code in the module graph. Note that a user provided config
/// of `"lib"` would override this value.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum TsTypeLib {
DenoWindow,
DenoWorker,
UnstableDenoWindow,
UnstableDenoWorker,
}
impl Default for TsTypeLib {
fn default() -> Self {
Self::DenoWindow
}
}
impl Serialize for TsTypeLib {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value = match self {
Self::DenoWindow => vec!["deno.window".to_string()],
Self::DenoWorker => vec!["deno.worker".to_string()],
Self::UnstableDenoWindow => {
vec!["deno.window".to_string(), "deno.unstable".to_string()]
}
Self::UnstableDenoWorker => {
vec!["deno.worker".to_string(), "deno.unstable".to_string()]
}
};
Serialize::serialize(&value, serializer)
}
}
/// An enum that represents the base tsc configuration to return.
pub enum TsConfigType {
/// Return a configuration for bundling, using swc to emit the bundle. This is
/// independent of type checking.
Bundle,
/// Return a configuration to use tsc to type check. This
/// is independent of either bundling or emitting via swc.
Check { lib: TsTypeLib },
/// Return a configuration to use swc to emit single module files.
Emit,
}
pub struct TsConfigForEmit {
pub ts_config: TsConfig,
pub maybe_ignored_options: Option<IgnoredCompilerOptions>,
}
/// For a given configuration type and optionally a configuration file,
/// return a `TsConfig` struct and optionally any user configuration
/// options that were ignored.
pub fn get_ts_config_for_emit(
config_type: TsConfigType,
maybe_config_file: Option<&ConfigFile>,
) -> Result<TsConfigForEmit, AnyError> {
let mut ts_config = match config_type {
TsConfigType::Bundle => TsConfig::new(json!({
"checkJs": false,
"emitDecoratorMetadata": false,
"importsNotUsedAsValues": "remove",
"inlineSourceMap": false,
"inlineSources": false,
"sourceMap": false,
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
})),
TsConfigType::Check { lib } => TsConfig::new(json!({
"allowJs": true,
"allowSyntheticDefaultImports": true,
"checkJs": false,
"emitDecoratorMetadata": false,
"experimentalDecorators": true,
"incremental": true,
"jsx": "react",
"importsNotUsedAsValues": "remove",
"inlineSourceMap": true,
"inlineSources": true,
"isolatedModules": true,
"lib": lib,
"module": "esnext",
"moduleDetection": "force",
"noEmit": true,
"resolveJsonModule": true,
"sourceMap": false,
"strict": true,
"target": "esnext",
"tsBuildInfoFile": "deno:///.tsbuildinfo",
"useDefineForClassFields": true,
// TODO(@kitsonk) remove for Deno 2.0
"useUnknownInCatchVariables": false,
})),
TsConfigType::Emit => TsConfig::new(json!({
"checkJs": false,
"emitDecoratorMetadata": false,
"importsNotUsedAsValues": "remove",
"inlineSourceMap": true,
"inlineSources": true,
"sourceMap": false,
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
"resolveJsonModule": true,
})),
};
let maybe_ignored_options =
ts_config.merge_tsconfig_from_config_file(maybe_config_file)?;
Ok(TsConfigForEmit {
ts_config,
maybe_ignored_options,
})
}
impl From<TsConfig> for deno_ast::EmitOptions {
fn from(config: TsConfig) -> Self {
let options: EmitConfigOptions = serde_json::from_value(config.0).unwrap();
let imports_not_used_as_values =
match options.imports_not_used_as_values.as_str() {
"preserve" => deno_ast::ImportsNotUsedAsValues::Preserve,
"error" => deno_ast::ImportsNotUsedAsValues::Error,
_ => deno_ast::ImportsNotUsedAsValues::Remove,
};
let (transform_jsx, jsx_automatic, jsx_development) =
match options.jsx.as_str() {
"react" => (true, false, false),
"react-jsx" => (true, true, false),
"react-jsxdev" => (true, true, true),
_ => (false, false, false),
};
deno_ast::EmitOptions {
emit_metadata: options.emit_decorator_metadata,
imports_not_used_as_values,
inline_source_map: options.inline_source_map,
inline_sources: options.inline_sources,
source_map: options.source_map,
jsx_automatic,
jsx_development,
jsx_factory: options.jsx_factory,
jsx_fragment_factory: options.jsx_fragment_factory,
jsx_import_source: options.jsx_import_source,
transform_jsx,
var_decl_imports: false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -95,6 +95,15 @@ pub struct Lockfile {
}
impl Lockfile {
pub fn as_maybe_locker(
lockfile: Option<Arc<Mutex<Lockfile>>>,
) -> Option<Rc<RefCell<dyn deno_graph::source::Locker>>> {
lockfile.as_ref().map(|lf| {
Rc::new(RefCell::new(Locker(Some(lf.clone()))))
as Rc<RefCell<dyn deno_graph::source::Locker>>
})
}
pub fn discover(
flags: &Flags,
maybe_config_file: Option<&ConfigFile>,
@ -359,15 +368,6 @@ impl deno_graph::source::Locker for Locker {
}
}
pub fn as_maybe_locker(
lockfile: Option<Arc<Mutex<Lockfile>>>,
) -> Option<Rc<RefCell<dyn deno_graph::source::Locker>>> {
lockfile.as_ref().map(|lf| {
Rc::new(RefCell::new(Locker(Some(lf.clone()))))
as Rc<RefCell<dyn deno_graph::source::Locker>>
})
}
#[cfg(test)]
mod tests {
use super::*;

View file

@ -1,7 +1,8 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
pub mod config_file;
pub mod flags;
mod config_file;
mod flags;
mod lockfile;
mod flags_allow_net;
@ -10,13 +11,20 @@ pub use config_file::ConfigFile;
pub use config_file::EmitConfigOptions;
pub use config_file::FmtConfig;
pub use config_file::FmtOptionsConfig;
pub use config_file::IgnoredCompilerOptions;
pub use config_file::JsxImportSourceConfig;
pub use config_file::LintConfig;
pub use config_file::LintRulesConfig;
pub use config_file::MaybeImportsResult;
pub use config_file::ProseWrap;
pub use config_file::TestConfig;
pub use config_file::TsConfig;
pub use config_file::TsConfigForEmit;
pub use config_file::TsConfigType;
pub use config_file::TsTypeLib;
pub use flags::*;
pub use lockfile::Lockfile;
pub use lockfile::LockfileError;
use deno_ast::ModuleSpecifier;
use deno_core::anyhow::anyhow;
@ -36,16 +44,10 @@ use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use crate::args::config_file::JsxImportSourceConfig;
use crate::deno_dir::DenoDir;
use crate::emit::get_ts_config_for_emit;
use crate::emit::TsConfigType;
use crate::emit::TsConfigWithIgnoredOptions;
use crate::emit::TsTypeLib;
use crate::file_fetcher::get_root_cert_store;
use crate::file_fetcher::CacheSetting;
use crate::fs_util;
use crate::lockfile::Lockfile;
use crate::version;
/// Overrides for the options below that when set will
@ -188,8 +190,11 @@ impl CliOptions {
pub fn resolve_ts_config_for_emit(
&self,
config_type: TsConfigType,
) -> Result<TsConfigWithIgnoredOptions, AnyError> {
get_ts_config_for_emit(config_type, self.maybe_config_file.as_ref())
) -> Result<TsConfigForEmit, AnyError> {
config_file::get_ts_config_for_emit(
config_type,
self.maybe_config_file.as_ref(),
)
}
/// Resolves the storage key to use based on the current flags, config, or main module.

View file

@ -122,7 +122,7 @@ mod ts {
"esnext.intl",
];
let path_dts = cwd.join("dts");
let path_dts = cwd.join("tsc/dts");
// ensure we invalidate the build properly.
for name in libs.iter() {
println!(
@ -476,5 +476,8 @@ fn main() {
fn deno_webgpu_get_declaration() -> PathBuf {
let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
manifest_dir.join("dts").join("lib.deno_webgpu.d.ts")
manifest_dir
.join("tsc")
.join("dts")
.join("lib.deno_webgpu.d.ts")
}

29
cli/dts/README.md vendored
View file

@ -1,29 +0,0 @@
# How to upgrade TypeScript.
The files in this directory are mostly from the TypeScript repository. We
currently (unfortunately) have a rather manual process for upgrading TypeScript.
It works like this currently:
1. Checkout denoland/TypeScript repo in a separate directory.
1. Add Microsoft/TypeScript as a remote and fetch its latest tags
1. Checkout a new branch based on this tag.
1. Cherry pick the custom commit we made in a previous release to the new one.
1. This commit has a "deno.ts" file in it. Read the instructions in it.
1. Copy typescript.js into Deno repo.
1. Copy d.ts files into dts directory.
So that might look something like this:
```
git clone https://github.com/denoland/TypeScript.git
cd typescript
git remote add upstream https://github.com/Microsoft/TypeScript
git fetch upstream
git checkout v3.9.7
git checkout -b branch_v3.9.7
git cherry pick <previous-release-branch-commit-we-did>
npm install
gulp local
rsync lib/typescript.js ~/src/deno/cli/tsc/00_typescript.js
rsync --exclude=protocol.d.ts --exclude=tsserverlibrary.d.ts --exclude=typescriptServices.d.ts lib/*.d.ts ~/src/deno/cli/dts/
```

View file

@ -1,154 +1,18 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
//! The collection of APIs to be able to take `deno_graph` module graphs and
//! populate a cache, emit files, and transform a graph into the structures for
//! loading into an isolate.
use crate::args::config_file::IgnoredCompilerOptions;
use crate::args::ConfigFile;
use crate::args::EmitConfigOptions;
use crate::args::TsConfig;
use crate::cache::EmitCache;
use crate::cache::FastInsecureHasher;
use crate::cache::ParsedSourceCache;
use deno_ast::swc::bundler::Hook;
use deno_ast::swc::bundler::ModuleRecord;
use deno_ast::swc::common::Span;
use deno_core::error::AnyError;
use deno_core::serde::Serialize;
use deno_core::serde::Serializer;
use deno_core::serde_json;
use deno_core::serde_json::json;
use deno_core::ModuleSpecifier;
use deno_graph::MediaType;
use deno_graph::ModuleGraphError;
use deno_graph::ResolutionError;
use std::fmt;
use std::sync::Arc;
/// Represents the "default" type library that should be used when type
/// checking the code in the module graph. Note that a user provided config
/// of `"lib"` would override this value.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum TsTypeLib {
DenoWindow,
DenoWorker,
UnstableDenoWindow,
UnstableDenoWorker,
}
impl Default for TsTypeLib {
fn default() -> Self {
Self::DenoWindow
}
}
impl Serialize for TsTypeLib {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value = match self {
Self::DenoWindow => vec!["deno.window".to_string()],
Self::DenoWorker => vec!["deno.worker".to_string()],
Self::UnstableDenoWindow => {
vec!["deno.window".to_string(), "deno.unstable".to_string()]
}
Self::UnstableDenoWorker => {
vec!["deno.worker".to_string(), "deno.unstable".to_string()]
}
};
Serialize::serialize(&value, serializer)
}
}
/// An enum that represents the base tsc configuration to return.
pub enum TsConfigType {
/// Return a configuration for bundling, using swc to emit the bundle. This is
/// independent of type checking.
Bundle,
/// Return a configuration to use tsc to type check. This
/// is independent of either bundling or emitting via swc.
Check { lib: TsTypeLib },
/// Return a configuration to use swc to emit single module files.
Emit,
}
pub struct TsConfigWithIgnoredOptions {
pub ts_config: TsConfig,
pub maybe_ignored_options: Option<IgnoredCompilerOptions>,
}
/// For a given configuration type and optionally a configuration file,
/// return a `TsConfig` struct and optionally any user configuration
/// options that were ignored.
pub fn get_ts_config_for_emit(
config_type: TsConfigType,
maybe_config_file: Option<&ConfigFile>,
) -> Result<TsConfigWithIgnoredOptions, AnyError> {
let mut ts_config = match config_type {
TsConfigType::Bundle => TsConfig::new(json!({
"checkJs": false,
"emitDecoratorMetadata": false,
"importsNotUsedAsValues": "remove",
"inlineSourceMap": false,
"inlineSources": false,
"sourceMap": false,
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
})),
TsConfigType::Check { lib } => TsConfig::new(json!({
"allowJs": true,
"allowSyntheticDefaultImports": true,
"checkJs": false,
"emitDecoratorMetadata": false,
"experimentalDecorators": true,
"incremental": true,
"jsx": "react",
"importsNotUsedAsValues": "remove",
"inlineSourceMap": true,
"inlineSources": true,
"isolatedModules": true,
"lib": lib,
"module": "esnext",
"moduleDetection": "force",
"noEmit": true,
"resolveJsonModule": true,
"sourceMap": false,
"strict": true,
"target": "esnext",
"tsBuildInfoFile": "deno:///.tsbuildinfo",
"useDefineForClassFields": true,
// TODO(@kitsonk) remove for Deno 2.0
"useUnknownInCatchVariables": false,
})),
TsConfigType::Emit => TsConfig::new(json!({
"checkJs": false,
"emitDecoratorMetadata": false,
"importsNotUsedAsValues": "remove",
"inlineSourceMap": true,
"inlineSources": true,
"sourceMap": false,
"jsx": "react",
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
"resolveJsonModule": true,
})),
};
let maybe_ignored_options =
ts_config.merge_tsconfig_from_config_file(maybe_config_file)?;
Ok(TsConfigWithIgnoredOptions {
ts_config,
maybe_ignored_options,
})
}
/// A hashing function that takes the source code, version and optionally a
/// user provided config and generates a string hash which can be stored to
/// A hashing function that takes the source code and emit options
/// hash then generates a string hash which can be stored to
/// determine if the cached emit is valid or not.
pub fn get_source_hash(source_text: &str, emit_options_hash: u64) -> u64 {
fn get_source_hash(source_text: &str, emit_options_hash: u64) -> u64 {
FastInsecureHasher::new()
.write_str(source_text)
.write_u64(emit_options_hash)
@ -183,107 +47,3 @@ pub fn emit_parsed_source(
Ok(transpiled_source.text)
}
}
/// An adapter struct to make a deno_graph::ModuleGraphError display as expected
/// in the Deno CLI.
#[derive(Debug)]
pub struct GraphError(pub ModuleGraphError);
impl std::error::Error for GraphError {}
impl From<ModuleGraphError> for GraphError {
fn from(err: ModuleGraphError) -> Self {
Self(err)
}
}
impl fmt::Display for GraphError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
ModuleGraphError::ResolutionError(err) => {
if matches!(
err,
ResolutionError::InvalidDowngrade { .. }
| ResolutionError::InvalidLocalImport { .. }
) {
write!(f, "{}", err.to_string_with_range())
} else {
self.0.fmt(f)
}
}
_ => self.0.fmt(f),
}
}
}
/// This contains the logic for Deno to rewrite the `import.meta` when bundling.
pub struct BundleHook;
impl Hook for BundleHook {
fn get_import_meta_props(
&self,
span: Span,
module_record: &ModuleRecord,
) -> Result<Vec<deno_ast::swc::ast::KeyValueProp>, AnyError> {
use deno_ast::swc::ast;
Ok(vec![
ast::KeyValueProp {
key: ast::PropName::Ident(ast::Ident::new("url".into(), span)),
value: Box::new(ast::Expr::Lit(ast::Lit::Str(ast::Str {
span,
value: module_record.file_name.to_string().into(),
raw: None,
}))),
},
ast::KeyValueProp {
key: ast::PropName::Ident(ast::Ident::new("main".into(), span)),
value: Box::new(if module_record.is_entry {
ast::Expr::Member(ast::MemberExpr {
span,
obj: Box::new(ast::Expr::MetaProp(ast::MetaPropExpr {
span,
kind: ast::MetaPropKind::ImportMeta,
})),
prop: ast::MemberProp::Ident(ast::Ident::new("main".into(), span)),
})
} else {
ast::Expr::Lit(ast::Lit::Bool(ast::Bool { span, value: false }))
}),
},
])
}
}
impl From<TsConfig> for deno_ast::EmitOptions {
fn from(config: TsConfig) -> Self {
let options: EmitConfigOptions = serde_json::from_value(config.0).unwrap();
let imports_not_used_as_values =
match options.imports_not_used_as_values.as_str() {
"preserve" => deno_ast::ImportsNotUsedAsValues::Preserve,
"error" => deno_ast::ImportsNotUsedAsValues::Error,
_ => deno_ast::ImportsNotUsedAsValues::Remove,
};
let (transform_jsx, jsx_automatic, jsx_development) =
match options.jsx.as_str() {
"react" => (true, false, false),
"react-jsx" => (true, true, false),
"react-jsxdev" => (true, true, true),
_ => (false, false, false),
};
deno_ast::EmitOptions {
emit_metadata: options.emit_decorator_metadata,
imports_not_used_as_values,
inline_source_map: options.inline_source_map,
inline_sources: options.inline_sources,
source_map: options.source_map,
jsx_automatic,
jsx_development,
jsx_factory: options.jsx_factory,
jsx_fragment_factory: options.jsx_fragment_factory,
jsx_import_source: options.jsx_import_source,
transform_jsx,
var_decl_imports: false,
}
}
}

View file

@ -9,8 +9,6 @@
//! Diagnostics are compile-time type errors, whereas JsErrors are runtime
//! exceptions.
use crate::emit::GraphError;
use deno_ast::Diagnostic;
use deno_core::error::AnyError;
use deno_graph::ModuleGraphError;
@ -25,11 +23,7 @@ fn get_diagnostic_class(_: &Diagnostic) -> &'static str {
"SyntaxError"
}
fn get_graph_error_class(err: &GraphError) -> &'static str {
get_module_graph_error_class(&err.0)
}
pub fn get_module_graph_error_class(err: &ModuleGraphError) -> &'static str {
fn get_module_graph_error_class(err: &ModuleGraphError) -> &'static str {
match err {
ModuleGraphError::LoadingErr(_, err) => get_error_class_name(err.as_ref()),
ModuleGraphError::InvalidSource(_, _)
@ -60,7 +54,6 @@ pub fn get_error_class_name(e: &AnyError) -> &'static str {
.map(get_import_map_error_class)
})
.or_else(|| e.downcast_ref::<Diagnostic>().map(get_diagnostic_class))
.or_else(|| e.downcast_ref::<GraphError>().map(get_graph_error_class))
.or_else(|| {
e.downcast_ref::<ModuleGraphError>()
.map(get_module_graph_error_class)

View file

@ -1,7 +1,7 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::args::TsTypeLib;
use crate::colors;
use crate::emit::TsTypeLib;
use crate::errors::get_error_class_name;
use crate::npm::resolve_npm_package_reqs;
use crate::npm::NpmPackageReference;

View file

@ -13,7 +13,6 @@ use super::tsc;
use super::tsc::TsServer;
use crate::args::LintConfig;
use crate::diagnostics;
use crate::npm::NpmPackageReference;
use deno_ast::MediaType;
@ -43,7 +42,7 @@ pub type DiagnosticRecord =
pub type DiagnosticVec = Vec<DiagnosticRecord>;
type DiagnosticMap =
HashMap<ModuleSpecifier, (Option<i32>, Vec<lsp::Diagnostic>)>;
type TsDiagnosticsMap = HashMap<String, Vec<diagnostics::Diagnostic>>;
type TsDiagnosticsMap = HashMap<String, Vec<crate::tsc::Diagnostic>>;
type DiagnosticsByVersionMap = HashMap<Option<i32>, Vec<lsp::Diagnostic>>;
#[derive(Clone)]
@ -335,25 +334,25 @@ impl DiagnosticsServer {
}
}
impl<'a> From<&'a diagnostics::DiagnosticCategory> for lsp::DiagnosticSeverity {
fn from(category: &'a diagnostics::DiagnosticCategory) -> Self {
impl<'a> From<&'a crate::tsc::DiagnosticCategory> for lsp::DiagnosticSeverity {
fn from(category: &'a crate::tsc::DiagnosticCategory) -> Self {
match category {
diagnostics::DiagnosticCategory::Error => lsp::DiagnosticSeverity::ERROR,
diagnostics::DiagnosticCategory::Warning => {
crate::tsc::DiagnosticCategory::Error => lsp::DiagnosticSeverity::ERROR,
crate::tsc::DiagnosticCategory::Warning => {
lsp::DiagnosticSeverity::WARNING
}
diagnostics::DiagnosticCategory::Suggestion => {
crate::tsc::DiagnosticCategory::Suggestion => {
lsp::DiagnosticSeverity::HINT
}
diagnostics::DiagnosticCategory::Message => {
crate::tsc::DiagnosticCategory::Message => {
lsp::DiagnosticSeverity::INFORMATION
}
}
}
}
impl<'a> From<&'a diagnostics::Position> for lsp::Position {
fn from(pos: &'a diagnostics::Position) -> Self {
impl<'a> From<&'a crate::tsc::Position> for lsp::Position {
fn from(pos: &'a crate::tsc::Position) -> Self {
Self {
line: pos.line as u32,
character: pos.character as u32,
@ -361,7 +360,7 @@ impl<'a> From<&'a diagnostics::Position> for lsp::Position {
}
}
fn get_diagnostic_message(diagnostic: &diagnostics::Diagnostic) -> String {
fn get_diagnostic_message(diagnostic: &crate::tsc::Diagnostic) -> String {
if let Some(message) = diagnostic.message_text.clone() {
message
} else if let Some(message_chain) = diagnostic.message_chain.clone() {
@ -372,8 +371,8 @@ fn get_diagnostic_message(diagnostic: &diagnostics::Diagnostic) -> String {
}
fn to_lsp_range(
start: &diagnostics::Position,
end: &diagnostics::Position,
start: &crate::tsc::Position,
end: &crate::tsc::Position,
) -> lsp::Range {
lsp::Range {
start: start.into(),
@ -382,7 +381,7 @@ fn to_lsp_range(
}
fn to_lsp_related_information(
related_information: &Option<Vec<diagnostics::Diagnostic>>,
related_information: &Option<Vec<crate::tsc::Diagnostic>>,
) -> Option<Vec<lsp::DiagnosticRelatedInformation>> {
related_information.as_ref().map(|related| {
related
@ -408,7 +407,7 @@ fn to_lsp_related_information(
}
fn ts_json_to_diagnostics(
diagnostics: Vec<diagnostics::Diagnostic>,
diagnostics: Vec<crate::tsc::Diagnostic>,
) -> Vec<lsp::Diagnostic> {
diagnostics
.iter()

View file

@ -7,7 +7,6 @@ mod cdp;
mod checksum;
mod deno_dir;
mod deno_std;
mod diagnostics;
mod diff;
mod display;
mod emit;
@ -19,7 +18,6 @@ mod graph_util;
mod http_cache;
mod http_util;
mod js;
mod lockfile;
mod logger;
mod lsp;
mod module_loader;
@ -60,12 +58,12 @@ use crate::args::ReplFlags;
use crate::args::RunFlags;
use crate::args::TaskFlags;
use crate::args::TestFlags;
use crate::args::TsConfigType;
use crate::args::TypeCheckMode;
use crate::args::UninstallFlags;
use crate::args::UpgradeFlags;
use crate::args::VendorFlags;
use crate::cache::TypeCheckCache;
use crate::emit::TsConfigType;
use crate::file_fetcher::File;
use crate::file_watcher::ResolutionResult;
use crate::graph_util::graph_lock_or_exit;
@ -74,6 +72,7 @@ use crate::resolver::CliResolver;
use crate::tools::check;
use args::CliOptions;
use args::Lockfile;
use deno_ast::MediaType;
use deno_core::anyhow::bail;
use deno_core::error::generic_error;
@ -327,7 +326,7 @@ async fn create_graph_and_maybe_check(
Permissions::allow_all(),
Permissions::allow_all(),
);
let maybe_locker = lockfile::as_maybe_locker(ps.lockfile.clone());
let maybe_locker = Lockfile::as_maybe_locker(ps.lockfile.clone());
let maybe_imports = ps.options.to_maybe_imports()?;
let maybe_cli_resolver = CliResolver::maybe_new(
ps.options.to_maybe_jsx_import_source_config(),
@ -925,7 +924,7 @@ fn unwrap_or_exit<T>(result: Result<T, AnyError>) -> T {
if let Some(e) = error.downcast_ref::<JsError>() {
error_string = format_js_error(e);
} else if let Some(e) = error.downcast_ref::<lockfile::LockfileError>() {
} else if let Some(e) = error.downcast_ref::<args::LockfileError>() {
error_string = e.to_string();
error_code = 10;
}

View file

@ -1,7 +1,7 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::args::TsTypeLib;
use crate::emit::emit_parsed_source;
use crate::emit::TsTypeLib;
use crate::graph_util::ModuleEntry;
use crate::node;
use crate::proc_state::ProcState;

View file

@ -703,20 +703,25 @@ pub fn url_to_node_resolution(
npm_resolver: &dyn RequireNpmResolver,
) -> Result<NodeResolution, AnyError> {
let url_str = url.as_str().to_lowercase();
Ok(if url_str.starts_with("http") {
NodeResolution::Esm(url)
if url_str.starts_with("http") {
Ok(NodeResolution::Esm(url))
} else if url_str.ends_with(".js") || url_str.ends_with(".d.ts") {
let package_config = get_closest_package_json(&url, npm_resolver)?;
if package_config.typ == "module" {
NodeResolution::Esm(url)
Ok(NodeResolution::Esm(url))
} else {
NodeResolution::CommonJs(url)
Ok(NodeResolution::CommonJs(url))
}
} else if url_str.ends_with(".mjs") || url_str.ends_with(".d.mts") {
NodeResolution::Esm(url)
Ok(NodeResolution::Esm(url))
} else if url_str.ends_with(".ts") {
Err(generic_error(format!(
"TypeScript files are not supported in npm packages: {}",
url
)))
} else {
NodeResolution::CommonJs(url)
})
Ok(NodeResolution::CommonJs(url))
}
}
fn finalize_resolution(

View file

@ -10,7 +10,7 @@ use deno_core::parking_lot::RwLock;
use serde::Deserialize;
use serde::Serialize;
use crate::lockfile::Lockfile;
use crate::args::Lockfile;
use self::graph::GraphDependencyResolver;
use self::snapshot::NpmPackagesPartitioned;

View file

@ -13,7 +13,7 @@ use deno_core::parking_lot::Mutex;
use serde::Deserialize;
use serde::Serialize;
use crate::lockfile::Lockfile;
use crate::args::Lockfile;
use crate::npm::cache::should_sync_download;
use crate::npm::cache::NpmPackageCacheFolderId;
use crate::npm::registry::NpmPackageVersionDistInfo;

View file

@ -11,7 +11,7 @@ use deno_core::futures;
use deno_core::futures::future::BoxFuture;
use deno_core::url::Url;
use crate::lockfile::Lockfile;
use crate::args::Lockfile;
use crate::npm::cache::should_sync_download;
use crate::npm::resolution::NpmResolutionSnapshot;
use crate::npm::NpmCache;

View file

@ -15,8 +15,8 @@ use deno_core::url::Url;
use deno_runtime::deno_node::PackageJson;
use deno_runtime::deno_node::TYPES_CONDITIONS;
use crate::args::Lockfile;
use crate::fs_util;
use crate::lockfile::Lockfile;
use crate::npm::resolution::NpmResolution;
use crate::npm::resolution::NpmResolutionSnapshot;
use crate::npm::resolvers::common::cache_packages;

View file

@ -22,8 +22,8 @@ use deno_runtime::deno_node::PackageJson;
use deno_runtime::deno_node::TYPES_CONDITIONS;
use tokio::task::JoinHandle;
use crate::args::Lockfile;
use crate::fs_util;
use crate::lockfile::Lockfile;
use crate::npm::cache::mixed_case_package_name_encode;
use crate::npm::cache::should_sync_download;
use crate::npm::cache::NpmPackageCacheFolderId;

View file

@ -22,8 +22,8 @@ use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use crate::args::Lockfile;
use crate::fs_util;
use crate::lockfile::Lockfile;
use self::common::InnerNpmPackageResolver;
use self::local::LocalNpmPackageResolver;

View file

@ -3,6 +3,9 @@
use crate::args::CliOptions;
use crate::args::DenoSubcommand;
use crate::args::Flags;
use crate::args::Lockfile;
use crate::args::TsConfigType;
use crate::args::TsTypeLib;
use crate::args::TypeCheckMode;
use crate::cache;
use crate::cache::EmitCache;
@ -12,16 +15,12 @@ use crate::cache::ParsedSourceCache;
use crate::cache::TypeCheckCache;
use crate::deno_dir;
use crate::emit::emit_parsed_source;
use crate::emit::TsConfigType;
use crate::emit::TsTypeLib;
use crate::file_fetcher::FileFetcher;
use crate::graph_util::graph_lock_or_exit;
use crate::graph_util::GraphData;
use crate::graph_util::ModuleEntry;
use crate::http_cache;
use crate::http_util::HttpClient;
use crate::lockfile::as_maybe_locker;
use crate::lockfile::Lockfile;
use crate::node;
use crate::node::NodeResolution;
use crate::npm::resolve_npm_package_reqs;
@ -330,7 +329,7 @@ impl ProcState {
root_permissions.clone(),
dynamic_permissions.clone(),
);
let maybe_locker = as_maybe_locker(self.lockfile.clone());
let maybe_locker = Lockfile::as_maybe_locker(self.lockfile.clone());
let maybe_imports = self.options.to_maybe_imports()?;
let maybe_resolver =
self.maybe_resolver.as_ref().map(|r| r.as_graph_resolver());
@ -640,7 +639,7 @@ impl ProcState {
roots: Vec<(ModuleSpecifier, ModuleKind)>,
loader: &mut dyn Loader,
) -> Result<deno_graph::ModuleGraph, AnyError> {
let maybe_locker = as_maybe_locker(self.lockfile.clone());
let maybe_locker = Lockfile::as_maybe_locker(self.lockfile.clone());
let maybe_imports = self.options.to_maybe_imports()?;
let maybe_cli_resolver = CliResolver::maybe_new(

View file

@ -8,7 +8,7 @@ use deno_graph::source::DEFAULT_JSX_IMPORT_SOURCE_MODULE;
use import_map::ImportMap;
use std::sync::Arc;
use crate::args::config_file::JsxImportSourceConfig;
use crate::args::JsxImportSourceConfig;
/// A resolver that takes care of resolution, taking into account loaded
/// import map, JSX settings.

View file

@ -126,7 +126,7 @@ fn typecheck_declarations_ns() {
let output = util::deno_cmd()
.arg("test")
.arg("--doc")
.arg(util::root_path().join("cli/dts/lib.deno.ns.d.ts"))
.arg(util::root_path().join("cli/tsc/dts/lib.deno.ns.d.ts"))
.output()
.unwrap();
println!("stdout: {}", String::from_utf8(output.stdout).unwrap());
@ -140,7 +140,7 @@ fn typecheck_declarations_unstable() {
.arg("test")
.arg("--doc")
.arg("--unstable")
.arg(util::root_path().join("cli/dts/lib.deno.unstable.d.ts"))
.arg(util::root_path().join("cli/tsc/dts/lib.deno.unstable.d.ts"))
.output()
.unwrap();
println!("stdout: {}", String::from_utf8(output.stdout).unwrap());

View file

@ -314,6 +314,14 @@ itest!(types_no_types_entry {
exit_code: 0,
});
itest!(typescript_file_in_package {
args: "run npm/typescript_file_in_package/main.ts",
output: "npm/typescript_file_in_package/main.out",
envs: env_vars(),
http_server: true,
exit_code: 1,
});
#[test]
fn parallel_downloading() {
let (out, _err) = util::run_and_collect_output_with_args(

View file

@ -0,0 +1,4 @@
// this should not work because we don't support typescript files in npm packages
export function getValue(): 5 {
return 5;
}

View file

@ -0,0 +1,5 @@
{
"name": "@denotest/typescript-file",
"version": "1.0.0",
"main": "./index.ts"
}

View file

@ -0,0 +1,6 @@
Download http://localhost:4545/npm/registry/@denotest/typescript-file
Download http://localhost:4545/npm/registry/@denotest/typescript-file/1.0.0.tgz
error: Could not resolve 'npm:@denotest/typescript-file'.
Caused by:
TypeScript files are not supported in npm packages: file:///[WILDCARD]/@denotest/typescript-file/1.0.0/index.ts

View file

@ -0,0 +1,5 @@
// We don't support typescript files in npm packages because we don't
// want to encourage people distributing npm packages that aren't JavaScript.
import { getValue } from "npm:@denotest/typescript-file";
console.log(getValue());

View file

@ -15,11 +15,11 @@ use crate::args::TsConfig;
use crate::args::TypeCheckMode;
use crate::cache::FastInsecureHasher;
use crate::cache::TypeCheckCache;
use crate::diagnostics::Diagnostics;
use crate::graph_util::GraphData;
use crate::graph_util::ModuleEntry;
use crate::npm::NpmPackageResolver;
use crate::tsc;
use crate::tsc::Diagnostics;
use crate::tsc::Stats;
use crate::version;

View file

@ -2,3 +2,33 @@
This directory contains the typescript compiler and a small compiler host for
the runtime snapshot.
## How to upgrade TypeScript.
The files in this directory are mostly from the TypeScript repository. We
currently (unfortunately) have a rather manual process for upgrading TypeScript.
It works like this currently:
1. Checkout denoland/TypeScript repo in a separate directory.
1. Add Microsoft/TypeScript as a remote and fetch its latest tags
1. Checkout a new branch based on this tag.
1. Cherry pick the custom commit we made in a previous release to the new one.
1. This commit has a "deno.ts" file in it. Read the instructions in it.
1. Copy typescript.js into Deno repo.
1. Copy d.ts files into dts directory.
So that might look something like this:
```
git clone https://github.com/denoland/TypeScript.git
cd typescript
git remote add upstream https://github.com/Microsoft/TypeScript
git fetch upstream
git checkout v3.9.7
git checkout -b branch_v3.9.7
git cherry pick <previous-release-branch-commit-we-did>
npm install
gulp local
rsync lib/typescript.js ~/src/deno/cli/tsc/00_typescript.js
rsync --exclude=protocol.d.ts --exclude=tsserverlibrary.d.ts --exclude=typescriptServices.d.ts lib/*.d.ts ~/src/deno/cli/tsc/dts/
```

View file

@ -2,7 +2,7 @@
// Contains types that can be used to validate and check `99_main_compiler.js`
import * as _ts from "../dts/typescript";
import * as _ts from "./dts/typescript";
declare global {
namespace ts {

Some files were not shown because too many files have changed in this diff Show more