1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-21 04:52:26 -05:00

Merge branch 'main' into update-imagebitmap

This commit is contained in:
Hajime-san 2024-09-17 12:47:07 +09:00 committed by GitHub
commit 825515e2cb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
1399 changed files with 34564 additions and 15592 deletions

View file

@ -56,7 +56,6 @@
"tests/testdata/run/byte_order_mark.ts",
"tests/testdata/run/error_syntax_empty_trailing_line.mjs",
"tests/testdata/run/inline_js_source_map*",
"tests/testdata/test/glob/",
"tests/testdata/test/markdown_windows.md",
"tests/util/std",
"tests/wpt/runner/expectation.json",

View file

@ -649,7 +649,7 @@ const ci = {
name: "test_format.js",
if: "matrix.job == 'lint' && matrix.os == 'linux'",
run:
"deno run --unstable --allow-write --allow-read --allow-run --allow-net ./tools/format.js --check",
"deno run --allow-write --allow-read --allow-run --allow-net ./tools/format.js --check",
},
{
name: "Lint PR title",
@ -664,7 +664,7 @@ const ci = {
name: "lint.js",
if: "matrix.job == 'lint'",
run:
"deno run --unstable --allow-write --allow-read --allow-run --allow-net ./tools/lint.js",
"deno run --allow-write --allow-read --allow-run --allow-net ./tools/lint.js",
},
{
name: "jsdoc_checker.js",
@ -826,7 +826,7 @@ const ci = {
"!startsWith(github.ref, 'refs/tags/')",
].join("\n"),
run:
"target/release/deno run -A --unstable --config tests/config/deno.json ext/websocket/autobahn/fuzzingclient.js",
"target/release/deno run -A --config tests/config/deno.json ext/websocket/autobahn/fuzzingclient.js",
},
{
name: "Test (full, debug)",
@ -879,9 +879,9 @@ const ci = {
DENO_BIN: "./target/debug/deno",
},
run: [
"deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\\",
"deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\\",
" ./tests/wpt/wpt.ts setup",
"deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\\",
"deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\\",
' ./tests/wpt/wpt.ts run --quiet --binary="$DENO_BIN"',
].join("\n"),
},
@ -892,9 +892,9 @@ const ci = {
DENO_BIN: "./target/release/deno",
},
run: [
"deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\\",
"deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\\",
" ./tests/wpt/wpt.ts setup",
"deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\\",
"deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\\",
" ./tests/wpt/wpt.ts run --quiet --release \\",
' --binary="$DENO_BIN" \\',
" --json=wpt.json \\",
@ -958,8 +958,7 @@ const ci = {
"git clone --depth 1 --branch gh-pages \\",
" https://${DENOBOT_PAT}@github.com/denoland/benchmark_data.git \\",
" gh-pages",
"./target/release/deno run --allow-all --unstable \\",
" ./tools/build_benchmark_jsons.js --release",
"./target/release/deno run --allow-all ./tools/build_benchmark_jsons.js --release",
"cd gh-pages",
'git config user.email "propelml@gmail.com"',
'git config user.name "denobot"',

View file

@ -389,7 +389,7 @@ jobs:
cache-path: ./target
- name: test_format.js
if: '!(matrix.skip) && (matrix.job == ''lint'' && matrix.os == ''linux'')'
run: deno run --unstable --allow-write --allow-read --allow-run --allow-net ./tools/format.js --check
run: deno run --allow-write --allow-read --allow-run --allow-net ./tools/format.js --check
- name: Lint PR title
if: '!(matrix.skip) && (matrix.job == ''lint'' && github.event_name == ''pull_request'' && matrix.os == ''linux'')'
env:
@ -397,7 +397,7 @@ jobs:
run: deno run ./tools/verify_pr_title.js "$PR_TITLE"
- name: lint.js
if: '!(matrix.skip) && (matrix.job == ''lint'')'
run: deno run --unstable --allow-write --allow-read --allow-run --allow-net ./tools/lint.js
run: deno run --allow-write --allow-read --allow-run --allow-net ./tools/lint.js
- name: jsdoc_checker.js
if: '!(matrix.skip) && (matrix.job == ''lint'')'
run: deno run --allow-read --allow-env --allow-sys ./tools/jsdoc_checker.js
@ -494,7 +494,7 @@ jobs:
matrix.job == 'test' &&
matrix.profile == 'release' &&
!startsWith(github.ref, 'refs/tags/'))
run: target/release/deno run -A --unstable --config tests/config/deno.json ext/websocket/autobahn/fuzzingclient.js
run: target/release/deno run -A --config tests/config/deno.json ext/websocket/autobahn/fuzzingclient.js
- name: 'Test (full, debug)'
if: |-
!(matrix.skip) && (matrix.job == 'test' &&
@ -531,18 +531,18 @@ jobs:
env:
DENO_BIN: ./target/debug/deno
run: |-
deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\
deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\
./tests/wpt/wpt.ts setup
deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\
deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\
./tests/wpt/wpt.ts run --quiet --binary="$DENO_BIN"
- name: Run web platform tests (release)
if: '!(matrix.skip) && (matrix.wpt && matrix.profile == ''release'')'
env:
DENO_BIN: ./target/release/deno
run: |-
deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\
deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\
./tests/wpt/wpt.ts setup
deno run -A --unstable --lock=tools/deno.lock.json --config tests/config/deno.json\
deno run -A --lock=tools/deno.lock.json --config tests/config/deno.json\
./tests/wpt/wpt.ts run --quiet --release \
--binary="$DENO_BIN" \
--json=wpt.json \
@ -590,8 +590,7 @@ jobs:
git clone --depth 1 --branch gh-pages \
https://${DENOBOT_PAT}@github.com/denoland/benchmark_data.git \
gh-pages
./target/release/deno run --allow-all --unstable \
./tools/build_benchmark_jsons.js --release
./target/release/deno run --allow-all ./tools/build_benchmark_jsons.js --release
cd gh-pages
git config user.email "propelml@gmail.com"
git config user.name "denobot"

View file

@ -1,15 +1,22 @@
name: promote_to_rc
name: promote_to_release
on:
workflow_dispatch:
inputs:
releaseKind:
description: 'Kind of release'
type: choice
options:
- rc
- lts
required: true
commitHash:
description: Commit to promote to the Release Candidate
description: Commit to promote to release
required: true
jobs:
promote-to-rc:
name: Promote to Release Candidate
promote-to-release:
name: Promote to Release
runs-on: macOS-latest
if: github.repository == 'denoland/deno'
steps:
@ -42,14 +49,14 @@ jobs:
./tools/install_prebuilt.js rcodesign
echo $GITHUB_WORKSPACE/third_party/prebuilt/mac >> $GITHUB_PATH
- name: Promote to RC
- name: Promote to Release
env:
APPLE_CODESIGN_KEY: '${{ secrets.APPLE_CODESIGN_KEY }}'
APPLE_CODESIGN_PASSWORD: '${{ secrets.APPLE_CODESIGN_PASSWORD }}'
run: |
deno run -A ./tools/release/promote_to_rc.ts ${{github.event.inputs.commitHash}}
deno run -A ./tools/release/promote_to_release.ts ${{github.event.inputs.releaseKind}} ${{github.event.inputs.commitHash}}
- name: Upload archives to dl.deno.land
run: |
gsutil -h "Cache-Control: public, max-age=3600" cp ./*.zip gs://dl.deno.land/release/$(cat release-rc-latest.txt)/
gsutil -h "Cache-Control: no-cache" cp release-rc-latest.txt gs://dl.deno.land/release-rc-latest.txt
gsutil -h "Cache-Control: public, max-age=3600" cp ./*.zip gs://dl.deno.land/release/$(cat release-${{github.event.inputs.commitHash}}-latest.txt)/
gsutil -h "Cache-Control: no-cache" cp release-${{github.event.inputs.commitHash}}-latest.txt gs://dl.deno.land/release-${{github.event.inputs.commitHash}}-latest.txt

View file

@ -66,9 +66,9 @@ jobs:
- name: Run web platform tests
shell: bash
run: |
deno run --unstable -A --lock=tools/deno.lock.json --config=tests/config/deno.json \
deno run -A --lock=tools/deno.lock.json --config=tests/config/deno.json \
./tests/wpt/wpt.ts setup
deno run --unstable -A --lock=tools/deno.lock.json --config=tests/config/deno.json \
deno run -A --lock=tools/deno.lock.json --config=tests/config/deno.json \
./tests/wpt/wpt.ts run \ \
--binary=$(which deno) --quiet --release --no-ignore --json=wpt.json --wptreport=wptreport.json --exit-zero

38
Cargo.lock generated
View file

@ -1152,7 +1152,7 @@ dependencies = [
[[package]]
name = "deno"
version = "2.0.0-rc.1"
version = "2.0.0-rc.2"
dependencies = [
"anstream",
"async-trait",
@ -1385,9 +1385,9 @@ dependencies = [
[[package]]
name = "deno_config"
version = "0.33.2"
version = "0.34.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d90b5eacfd6ee4ec978a11739c71eaeb19a575889f8c2b473430df84078fe2"
checksum = "764368ba1424ea74f9a28d8e2e7633f57d008e73f76b12bc272f6d5903ca1e08"
dependencies = [
"anyhow",
"deno_package_json",
@ -1415,9 +1415,9 @@ dependencies = [
[[package]]
name = "deno_core"
version = "0.307.0"
version = "0.309.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "154b0902402807a043579102f949e6dd6f3a09d2d5049929fd710fc3192bf109"
checksum = "eaecc78e8903d1b5d95c7fb01a14eb342b9e63484763a304fd30a8f48861f9df"
dependencies = [
"anyhow",
"bincode",
@ -1729,9 +1729,9 @@ dependencies = [
[[package]]
name = "deno_lockfile"
version = "0.23.0"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb68a4a666c69eabd8fe505d6fdc4ed4a2d962fe1680dbfa8b0c8a2975d58ed0"
checksum = "579117d5815aa9bae0212637d6f4d5f45f9649bb2c8988dca434077545535039"
dependencies = [
"deno_semver",
"serde",
@ -1878,9 +1878,9 @@ dependencies = [
[[package]]
name = "deno_npm"
version = "0.25.0"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efb2dd7efaf478d780a6ca43e6127667d5329ed9a5ff89f42cec0dc21ee58342"
checksum = "e61b112e9bb332e8e6b0d82fcea7664423933de476e1726dd23a924a2d94f4ef"
dependencies = [
"anyhow",
"async-trait",
@ -1897,9 +1897,9 @@ dependencies = [
[[package]]
name = "deno_ops"
version = "0.183.0"
version = "0.185.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9114f9eb6419839f1ab9668f91c463238945bb974e1998629a703f72b4608daf"
checksum = "2d817c00b3f30bef495c84080b5ed327ed68d6d2636b5ed8b730d00a06221dc1"
dependencies = [
"proc-macro-rules",
"proc-macro2",
@ -4369,9 +4369,9 @@ dependencies = [
[[package]]
name = "malva"
version = "0.9.0"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e6e9f16e424a6672f6726daf965333952dece79ef3d17aac712b92b3b72d0a8"
checksum = "484beda6e5d775ed06a8ec0fce79e51d39f49d834ed2a29da3f437079321804f"
dependencies = [
"aho-corasick",
"itertools 0.13.0",
@ -5305,9 +5305,9 @@ dependencies = [
[[package]]
name = "pretty_yaml"
version = "0.4.0"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22ba50511591c8e1d84125f7e2e6d17ccb06865c484b812f5ee3af61f42a66be"
checksum = "dda9a64ee7296e82d1e0f4389383e6a7d8e6e2487d8391f7d028c131395fd376"
dependencies = [
"rowan",
"tiny_pretty",
@ -6326,9 +6326,9 @@ dependencies = [
[[package]]
name = "serde_v8"
version = "0.216.0"
version = "0.218.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1733b8192f123beedd2fc7998efeaf2a0b8bfa35c01537f50b690e786db8024c"
checksum = "134add6f9dc7a226912468f7c427a476583ab362e094f04ff3a9fa79f2df97c7"
dependencies = [
"num-bigint",
"serde",
@ -7981,9 +7981,9 @@ dependencies = [
[[package]]
name = "v8"
version = "0.105.0"
version = "0.106.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692624c4fd58ff50aa6d690c159df18e7881c13970005b9b2bff77dc425fd370"
checksum = "a381badc47c6f15acb5fe0b5b40234162349ed9d4e4fd7c83a7f5547c0fc69c5"
dependencies = [
"bindgen",
"bitflags 2.6.0",

View file

@ -45,10 +45,10 @@ repository = "https://github.com/denoland/deno"
[workspace.dependencies]
deno_ast = { version = "=0.42.0", features = ["transpiling"] }
deno_core = { version = "0.307.0" }
deno_core = { version = "0.309.0" }
deno_bench_util = { version = "0.162.0", path = "./bench_util" }
deno_lockfile = "=0.23.0"
deno_lockfile = "=0.23.1"
deno_media_type = { version = "0.1.4", features = ["module_specifier"] }
deno_permissions = { version = "0.28.0", path = "./runtime/permissions" }
deno_runtime = { version = "0.177.0", path = "./runtime" }

View file

@ -2,7 +2,7 @@
[package]
name = "deno"
version = "2.0.0-rc.1"
version = "2.0.0-rc.2"
authors.workspace = true
default-run = "deno"
edition.workspace = true
@ -65,13 +65,13 @@ winres.workspace = true
[dependencies]
deno_ast = { workspace = true, features = ["bundler", "cjs", "codegen", "proposal", "react", "sourcemap", "transforms", "typescript", "view", "visit"] }
deno_cache_dir = { workspace = true }
deno_config = { version = "=0.33.2", features = ["workspace", "sync"] }
deno_config = { version = "=0.34.2", features = ["workspace", "sync"] }
deno_core = { workspace = true, features = ["include_js_files_for_snapshotting"] }
deno_doc = { version = "0.148.0", features = ["html", "syntect"] }
deno_graph = { version = "=0.82.1" }
deno_lint = { version = "=0.65.0", features = ["docs"] }
deno_lockfile.workspace = true
deno_npm = "=0.25.0"
deno_npm = "=0.25.1"
deno_package_json.workspace = true
deno_runtime = { workspace = true, features = ["include_js_files_for_snapshotting"] }
deno_semver.workspace = true
@ -123,7 +123,7 @@ libc.workspace = true
libz-sys.workspace = true
log = { workspace = true, features = ["serde"] }
lsp-types.workspace = true
malva = "=0.9.0"
malva = "=0.10.1"
markup_fmt = "=0.12.0"
memmem.workspace = true
monch.workspace = true
@ -134,7 +134,7 @@ p256.workspace = true
pathdiff = "0.2.1"
percent-encoding.workspace = true
phf.workspace = true
pretty_yaml = "=0.4.0"
pretty_yaml = "=0.5.0"
quick-junit = "^0.3.5"
rand = { workspace = true, features = ["small_rng"] }
regex.workspace = true

View file

@ -32,7 +32,6 @@ use deno_core::normalize_path;
use deno_core::resolve_url_or_path;
use deno_core::url::Url;
use deno_graph::GraphKind;
use deno_runtime::colors;
use deno_runtime::deno_permissions::parse_sys_kind;
use deno_runtime::deno_permissions::PermissionsOptions;
use log::debug;
@ -570,6 +569,7 @@ fn parse_packages_allowed_scripts(s: &str) -> Result<String, AnyError> {
Clone, Default, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize,
)]
pub struct UnstableConfig {
// TODO(bartlomieju): remove in Deno 2.5
pub legacy_flag_enabled: bool, // --unstable
pub bare_node_builtins: bool, // --unstable-bare-node-builts
pub sloppy_imports: bool,
@ -660,107 +660,25 @@ impl PermissionFlags {
|| self.deny_write.is_some()
}
pub fn to_options(
&self,
// will be None when `deno compile` can't resolve the cwd
initial_cwd: Option<&Path>,
) -> Result<PermissionsOptions, AnyError> {
fn convert_option_str_to_path_buf(
flag: &Option<Vec<String>>,
initial_cwd: Option<&Path>,
) -> Result<Option<Vec<PathBuf>>, AnyError> {
let Some(paths) = &flag else {
return Ok(None);
};
let mut new_paths = Vec::with_capacity(paths.len());
for path in paths {
if let Some(initial_cwd) = initial_cwd {
new_paths.push(initial_cwd.join(path))
} else {
let path = PathBuf::from(path);
if path.is_absolute() {
new_paths.push(path);
} else {
bail!("Could not resolve relative permission path '{}' when current working directory could not be resolved.", path.display())
}
}
}
Ok(Some(new_paths))
}
fn resolve_allow_run(
allow_run: &[String],
) -> Result<Vec<PathBuf>, AnyError> {
let mut new_allow_run = Vec::with_capacity(allow_run.len());
for command_name in allow_run {
if command_name.is_empty() {
bail!("Empty command name not allowed in --allow-run=...")
}
let command_path_result = which::which(command_name);
match command_path_result {
Ok(command_path) => new_allow_run.push(command_path),
Err(err) => {
log::info!(
"{} Failed to resolve '{}' for allow-run: {}",
colors::gray("Info"),
command_name,
err
);
}
}
}
Ok(new_allow_run)
}
let mut deny_write =
convert_option_str_to_path_buf(&self.deny_write, initial_cwd)?;
let allow_run = self
.allow_run
.as_ref()
.and_then(|raw_allow_run| match resolve_allow_run(raw_allow_run) {
Ok(resolved_allow_run) => {
if resolved_allow_run.is_empty() && !raw_allow_run.is_empty() {
None // convert to no permissions if now empty
} else {
Some(Ok(resolved_allow_run))
}
}
Err(err) => Some(Err(err)),
})
.transpose()?;
// add the allow_run list to deno_write
if let Some(allow_run_vec) = &allow_run {
if !allow_run_vec.is_empty() {
let deno_write = deny_write.get_or_insert_with(Vec::new);
deno_write.extend(allow_run_vec.iter().cloned());
}
}
Ok(PermissionsOptions {
pub fn to_options(&self) -> PermissionsOptions {
PermissionsOptions {
allow_all: self.allow_all,
allow_env: self.allow_env.clone(),
deny_env: self.deny_env.clone(),
allow_net: self.allow_net.clone(),
deny_net: self.deny_net.clone(),
allow_ffi: convert_option_str_to_path_buf(&self.allow_ffi, initial_cwd)?,
deny_ffi: convert_option_str_to_path_buf(&self.deny_ffi, initial_cwd)?,
allow_read: convert_option_str_to_path_buf(
&self.allow_read,
initial_cwd,
)?,
deny_read: convert_option_str_to_path_buf(&self.deny_read, initial_cwd)?,
allow_run,
allow_ffi: self.allow_ffi.clone(),
deny_ffi: self.deny_ffi.clone(),
allow_read: self.allow_read.clone(),
deny_read: self.deny_read.clone(),
allow_run: self.allow_run.clone(),
deny_run: self.deny_run.clone(),
allow_sys: self.allow_sys.clone(),
deny_sys: self.deny_sys.clone(),
allow_write: convert_option_str_to_path_buf(
&self.allow_write,
initial_cwd,
)?,
deny_write,
allow_write: self.allow_write.clone(),
deny_write: self.deny_write.clone(),
prompt: !resolve_no_prompt(self),
})
}
}
}
@ -1121,6 +1039,8 @@ impl Flags {
static ENV_VARIABLES_HELP: &str = cstr!(
r#"<y>Environment variables:</>
<y>Docs:</> <c>https://docs.deno.com/go/env-vars</>
<g>DENO_AUTH_TOKENS</> A semi-colon separated list of bearer tokens and hostnames
to use when fetching remote modules from private repositories
<p(245)>(e.g. "abcde12345@deno.land;54321edcba@github.com")</>
@ -1655,7 +1575,7 @@ Evaluate the given files, run all benches declared with 'Deno.bench()' and repor
If you specify a directory instead of a file, the path is expanded to all contained files matching the glob <c>{*_,*.,}bench.{js,mjs,ts,mts,jsx,tsx}</>:
<p(245)>deno bench src/</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/bench</>"),
<y>Read more:</> <c>https://docs.deno.com/go/bench</>"),
UnstableArgsConfig::ResolutionAndRuntime,
)
.defer(|cmd| {
@ -1720,7 +1640,7 @@ Download and compile a module with all of its static dependencies and save them
Future runs of this module will trigger no downloads or compilation unless --reload is specified
<y>Read more:</> <c>https://docs.deno.com/go/cmd/cache</>"),
<y>Read more:</> <c>https://docs.deno.com/go/cache</>"),
UnstableArgsConfig::ResolutionOnly,
)
.defer(|cmd| {
@ -1753,7 +1673,7 @@ fn check_subcommand() -> Command {
Unless --reload is specified, this command will not re-download already cached dependencies
<y>Read more:</> <c>https://docs.deno.com/go/cmd/check</>"),
<y>Read more:</> <c>https://docs.deno.com/go/check</>"),
UnstableArgsConfig::ResolutionAndRuntime
)
.defer(|cmd| {
@ -1797,7 +1717,7 @@ Any flags specified which affect runtime behavior will be applied to the resulti
Cross-compiling to different target architectures is supported using the <c>--target</> flag.
On the first invocation with deno will download the proper binary and cache it in <c>$DENO_DIR</>.
<y>Read more:</> <c>https://docs.deno.com/go/cmd/compile</>
<y>Read more:</> <c>https://docs.deno.com/go/compile</>
"),
UnstableArgsConfig::ResolutionAndRuntime,
)
@ -1904,7 +1824,7 @@ Write a report using the lcov format:
Generate html reports from lcov:
<p(245)>genhtml -o html_cov cov.lcov</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/coverage</>"),
<y>Read more:</> <c>https://docs.deno.com/go/coverage</>"),
UnstableArgsConfig::None,
)
.defer(|cmd| {
@ -1997,7 +1917,7 @@ Show documentation for runtime built-ins:
<p(245)>deno doc</>
<p(245)>deno doc --filter Deno.Listener</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/doc</>"),
<y>Read more:</> <c>https://docs.deno.com/go/doc</>"),
UnstableArgsConfig::ResolutionOnly
)
.defer(|cmd| {
@ -2117,7 +2037,7 @@ To evaluate as TypeScript:
This command has implicit access to all permissions.
<y>Read more:</> <c>https://docs.deno.com/go/cmd/eval</>"
<y>Read more:</> <c>https://docs.deno.com/go/eval</>"
),
UnstableArgsConfig::ResolutionAndRuntime,
)
@ -2165,7 +2085,7 @@ Ignore formatting code by preceding it with an ignore comment:
Ignore formatting a file by adding an ignore comment at the top of the file:
<p(245)>// deno-fmt-ignore-file</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/fmt</>"),
<y>Read more:</> <c>https://docs.deno.com/go/fmt</>"),
UnstableArgsConfig::None,
)
.defer(|cmd| {
@ -2343,7 +2263,7 @@ The following information is shown:
emit: Local path of compiled source code (TypeScript only)
dependencies: Dependency tree of the source file
<y>Read more:</> <c>https://docs.deno.com/go/cmd/info</>"),
<y>Read more:</> <c>https://docs.deno.com/go/info</>"),
UnstableArgsConfig::ResolutionOnly
)
.defer(|cmd| cmd
@ -2577,7 +2497,7 @@ To ignore specific diagnostics, you can write an ignore comment on the preceding
To ignore linting on an entire file, you can add an ignore comment at the top of the file:
<p(245)>// deno-lint-ignore-file</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/lint</>
<y>Read more:</> <c>https://docs.deno.com/go/lint</>
"),
UnstableArgsConfig::ResolutionOnly,
)
@ -2700,6 +2620,13 @@ fn repl_subcommand() -> Command {
<p(245)>[default: $DENO_DIR/deno_history.txt]</>"))
)
.arg(env_file_arg())
.arg(
Arg::new("args")
.num_args(0..)
.action(ArgAction::Append)
.value_name("ARGS")
.last(true)
)
}
fn run_args(command: Command, top_level: bool) -> Command {
@ -2737,7 +2664,7 @@ Grant all permissions:
Specifying the filename '-' to read the file from stdin.
<p(245)>curl https://examples.deno.land/hello-world.ts | deno run -</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/run</>"), UnstableArgsConfig::ResolutionAndRuntime), false)
<y>Read more:</> <c>https://docs.deno.com/go/run</>"), UnstableArgsConfig::ResolutionAndRuntime), false)
}
fn serve_host_validator(host: &str) -> Result<String, String> {
@ -2761,7 +2688,7 @@ Start a server defined in server.ts:
Start a server defined in server.ts, watching for changes and running on port 5050:
<p(245)>deno serve --watch --port 5050 server.ts</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/serve</>"), UnstableArgsConfig::ResolutionAndRuntime), true, true)
<y>Read more:</> <c>https://docs.deno.com/go/serve</>"), UnstableArgsConfig::ResolutionAndRuntime), true, true)
.arg(
Arg::new("port")
.long("port")
@ -2830,7 +2757,7 @@ Directory arguments are expanded to all contained files matching the glob <c>{*_
or <c>**/__tests__/**</>:
<p(245)>deno test src/</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/test</>"),
<y>Read more:</> <c>https://docs.deno.com/go/test</>"),
UnstableArgsConfig::ResolutionAndRuntime
)
.defer(|cmd|
@ -2983,12 +2910,8 @@ The declaration file could be saved and used for typing information.",
)
}
fn upgrade_subcommand() -> Command {
command(
"upgrade",
cstr!("Upgrade deno executable to the given version.
<g>Latest</>
pub static UPGRADE_USAGE: &str = cstr!(
"<g>Latest</>
<bold>deno upgrade</>
<g>Specific version</>
@ -2999,7 +2922,15 @@ fn upgrade_subcommand() -> Command {
<g>Channel</>
<bold>deno upgrade</> <p(245)>stable</>
<bold>deno upgrade</> <p(245)>rc</>
<bold>deno upgrade</> <p(245)>canary</>
<bold>deno upgrade</> <p(245)>canary</>"
);
fn upgrade_subcommand() -> Command {
command(
"upgrade",
color_print::cformat!("Upgrade deno executable to the given version.
{}
The version is downloaded from <p(245)>https://dl.deno.land</> and is used to replace the current executable.
@ -3007,7 +2938,7 @@ If you want to not replace the current Deno executable but instead download an u
different location, use the <c>--output</> flag:
<p(245)>deno upgrade --output $HOME/my_deno</>
<y>Read more:</> <c>https://docs.deno.com/go/cmd/upgrade</>"),
<y>Read more:</> <c>https://docs.deno.com/go/upgrade</>", UPGRADE_USAGE),
UnstableArgsConfig::None,
)
.hide(cfg!(not(feature = "upgrade")))
@ -3151,7 +3082,7 @@ fn compile_args_without_check_args(app: Command) -> Command {
fn permission_args(app: Command, requires: Option<&'static str>) -> Command {
app
.after_help(cstr!(r#"<y>Permission options:</>
Docs: <c>https://docs.deno.com/go/permissions</>
<y>Docs</>: <c>https://docs.deno.com/go/permissions</>
<g>-A, --allow-all</> Allow all permissions.
<g>--no-prompt</> Always throw if required permission wasn't passed.
@ -4704,6 +4635,10 @@ fn repl_parse(
})
.transpose()?;
if let Some(args) = matches.remove_many::<String>("args") {
flags.argv.extend(args);
}
handle_repl_flags(
flags,
ReplFlags {
@ -5476,6 +5411,7 @@ fn unstable_args_parse(
matches: &mut ArgMatches,
cfg: UnstableArgsConfig,
) {
// TODO(bartlomieju): remove in Deno 2.5
if matches.get_flag("unstable") {
flags.unstable_config.legacy_flag_enabled = true;
}
@ -8765,7 +8701,7 @@ mod tests {
#[test]
fn test_with_flags() {
#[rustfmt::skip]
let r = flags_from_vec(svec!["deno", "test", "--unstable", "--no-npm", "--no-remote", "--trace-leaks", "--no-run", "--filter", "- foo", "--coverage=cov", "--clean", "--location", "https:foo", "--allow-net", "--permit-no-files", "dir1/", "dir2/", "--", "arg1", "arg2"]);
let r = flags_from_vec(svec!["deno", "test", "--no-npm", "--no-remote", "--trace-leaks", "--no-run", "--filter", "- foo", "--coverage=cov", "--clean", "--location", "https:foo", "--allow-net", "--permit-no-files", "dir1/", "dir2/", "--", "arg1", "arg2"]);
assert_eq!(
r.unwrap(),
Flags {
@ -8789,10 +8725,6 @@ mod tests {
junit_path: None,
hide_stacktraces: false,
}),
unstable_config: UnstableConfig {
legacy_flag_enabled: true,
..Default::default()
},
no_npm: true,
no_remote: true,
location: Some(Url::parse("https://foo/").unwrap()),
@ -10200,7 +10132,6 @@ mod tests {
"deno",
"bench",
"--json",
"--unstable",
"--no-npm",
"--no-remote",
"--no-run",
@ -10228,10 +10159,6 @@ mod tests {
},
watch: Default::default(),
}),
unstable_config: UnstableConfig {
legacy_flag_enabled: true,
..Default::default()
},
no_npm: true,
no_remote: true,
type_check_mode: TypeCheckMode::Local,
@ -10722,6 +10649,25 @@ mod tests {
);
}
#[test]
fn repl_user_args() {
let r = flags_from_vec(svec!["deno", "repl", "foo"]);
assert!(r.is_err());
let r = flags_from_vec(svec!["deno", "repl", "--", "foo"]);
assert_eq!(
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Repl(ReplFlags {
eval_files: None,
eval: None,
is_default_command: false,
}),
argv: svec!["foo"],
..Flags::default()
}
);
}
#[test]
fn bare_with_flag_no_file() {
let r = flags_from_vec(svec!["deno", "--no-config"]);
@ -10802,10 +10748,10 @@ mod tests {
conn_file: None,
}),
unstable_config: UnstableConfig {
legacy_flag_enabled: false,
bare_node_builtins: true,
sloppy_imports: false,
features: svec!["ffi", "worker-options"],
..Default::default()
},
..Flags::default()
}

View file

@ -3,7 +3,6 @@
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::url::Url;
use deno_runtime::deno_permissions::PermissionsContainer;
use crate::file_fetcher::FileFetcher;
@ -17,7 +16,7 @@ pub async fn resolve_import_map_value_from_specifier(
Ok(serde_json::from_str(&data_url_text)?)
} else {
let file = file_fetcher
.fetch(specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(specifier)
.await?
.into_text_decoded()?;
Ok(serde_json::from_str(&file.source)?)

View file

@ -27,7 +27,6 @@ use deno_npm::npm_rc::NpmRc;
use deno_npm::npm_rc::ResolvedNpmRc;
use deno_npm::resolution::ValidSerializedNpmResolutionSnapshot;
use deno_npm::NpmSystemInfo;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::npm::NpmPackageReqReference;
use import_map::resolve_import_map_value_from_specifier;
@ -810,6 +809,8 @@ impl CliOptions {
}
}
warn_insecure_allow_run_flags(&flags);
let maybe_lockfile = maybe_lockfile.filter(|_| !force_global_cache);
let deno_dir_provider =
Arc::new(DenoDirProvider::new(flags.cache_path.clone()));
@ -1082,7 +1083,7 @@ impl CliOptions {
let specifier = specifier.clone();
async move {
let file = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&specifier)
.await?
.into_text_decoded()?;
Ok(file.source.to_string())
@ -1501,8 +1502,8 @@ impl CliOptions {
&self.flags.permissions
}
pub fn permissions_options(&self) -> Result<PermissionsOptions, AnyError> {
self.flags.permissions.to_options(Some(&self.initial_cwd))
pub fn permissions_options(&self) -> PermissionsOptions {
self.flags.permissions.to_options()
}
pub fn reload_flag(&self) -> bool {
@ -1548,10 +1549,6 @@ impl CliOptions {
&self.flags.unsafely_ignore_certificate_errors
}
pub fn legacy_unstable_flag(&self) -> bool {
self.flags.unstable_config.legacy_flag_enabled
}
pub fn unstable_bare_node_builtins(&self) -> bool {
self.flags.unstable_config.bare_node_builtins
|| self.workspace().has_unstable("bare-node-builtins")
@ -1600,18 +1597,6 @@ impl CliOptions {
}
});
// TODO(2.0): remove this code and enable these features in `99_main.js` by default.
let future_features = [
deno_runtime::deno_ffi::UNSTABLE_FEATURE_NAME.to_string(),
deno_runtime::deno_fs::UNSTABLE_FEATURE_NAME.to_string(),
deno_runtime::deno_webgpu::UNSTABLE_FEATURE_NAME.to_string(),
];
future_features.iter().for_each(|future_feature| {
if !from_config_file.contains(future_feature) {
from_config_file.push(future_feature.to_string());
}
});
if !from_config_file.is_empty() {
// collect unstable granular flags
let mut all_valid_unstable_flags: Vec<&str> =
@ -1705,6 +1690,27 @@ impl CliOptions {
}
}
/// Warns for specific uses of `--allow-run`. This function is not
/// intended to catch every single possible insecure use of `--allow-run`,
/// but is just an attempt to discourage some common pitfalls.
fn warn_insecure_allow_run_flags(flags: &Flags) {
let permissions = &flags.permissions;
if permissions.allow_all {
return;
}
let Some(allow_run_list) = permissions.allow_run.as_ref() else {
return;
};
// discourage using --allow-run without an allow list
if allow_run_list.is_empty() {
log::warn!(
"{} --allow-run can be trivially exploited. Prefer specifying an allow list (https://docs.deno.com/runtime/fundamentals/security/#running-subprocesses)",
colors::yellow("Warning")
);
}
}
/// Resolves the path to use for a local node_modules folder.
fn resolve_node_modules_folder(
cwd: &Path,

View file

@ -1,6 +1,5 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
@ -10,18 +9,16 @@ use deno_package_json::PackageJsonDepValue;
use deno_semver::npm::NpmPackageReqReference;
use deno_semver::package::PackageReq;
use crate::util::path::is_banned_path_char;
#[derive(Debug)]
pub struct InstallNpmRemotePkg {
pub alias: String,
pub alias: Option<String>,
pub base_dir: PathBuf,
pub req: PackageReq,
}
#[derive(Debug)]
pub struct InstallNpmWorkspacePkg {
pub alias: String,
pub alias: Option<String>,
pub target_dir: PathBuf,
}
@ -43,16 +40,13 @@ impl NpmInstallDepsProvider {
let workspace_npm_pkgs = workspace.npm_packages();
for (_, folder) in workspace.config_folders() {
let mut deno_json_aliases = HashSet::new();
// deal with the deno.json first because it takes precedence during resolution
if let Some(deno_json) = &folder.deno_json {
// don't bother with externally referenced import maps as users
// should inline their import map to get this behaviour
if let Some(serde_json::Value::Object(obj)) = &deno_json.json.imports {
deno_json_aliases.reserve(obj.len());
let mut pkg_pkgs = Vec::with_capacity(obj.len());
for (alias, value) in obj {
for (_alias, value) in obj {
let serde_json::Value::String(specifier) = value else {
continue;
};
@ -60,11 +54,6 @@ impl NpmInstallDepsProvider {
else {
continue;
};
// skip any aliases with banned characters
if alias.chars().any(|c| c == '\\' || is_banned_path_char(c)) {
continue;
}
deno_json_aliases.insert(alias.to_lowercase());
let pkg_req = npm_req_ref.into_inner().req;
let workspace_pkg = workspace_npm_pkgs
.iter()
@ -72,12 +61,12 @@ impl NpmInstallDepsProvider {
if let Some(pkg) = workspace_pkg {
workspace_pkgs.push(InstallNpmWorkspacePkg {
alias: alias.to_string(),
alias: None,
target_dir: pkg.pkg_json.dir_path().to_path_buf(),
});
} else {
pkg_pkgs.push(InstallNpmRemotePkg {
alias: alias.to_string(),
alias: None,
base_dir: deno_json.dir_path(),
req: pkg_req,
});
@ -85,7 +74,7 @@ impl NpmInstallDepsProvider {
}
// sort within each package (more like npm resolution)
pkg_pkgs.sort_by(|a, b| a.alias.cmp(&b.alias));
pkg_pkgs.sort_by(|a, b| a.req.cmp(&b.req));
remote_pkgs.extend(pkg_pkgs);
}
}
@ -97,11 +86,6 @@ impl NpmInstallDepsProvider {
let Ok(dep) = dep else {
continue;
};
if deno_json_aliases.contains(&alias.to_lowercase()) {
// aliases in deno.json take precedence over package.json, so
// since this can't be resolved don't bother installing it
continue;
}
match dep {
PackageJsonDepValue::Req(pkg_req) => {
let workspace_pkg = workspace_npm_pkgs.iter().find(|pkg| {
@ -112,12 +96,12 @@ impl NpmInstallDepsProvider {
if let Some(pkg) = workspace_pkg {
workspace_pkgs.push(InstallNpmWorkspacePkg {
alias,
alias: Some(alias),
target_dir: pkg.pkg_json.dir_path().to_path_buf(),
});
} else {
pkg_pkgs.push(InstallNpmRemotePkg {
alias,
alias: Some(alias),
base_dir: pkg_json.dir_path().to_path_buf(),
req: pkg_req,
});
@ -128,7 +112,7 @@ impl NpmInstallDepsProvider {
pkg.matches_name_and_version_req(&alias, &version_req)
}) {
workspace_pkgs.push(InstallNpmWorkspacePkg {
alias,
alias: Some(alias),
target_dir: pkg.pkg_json.dir_path().to_path_buf(),
});
}

View file

@ -49,7 +49,7 @@ pub fn benchmark(
}
let port = get_port();
// deno run -A --unstable <path> <addr>
// deno run -A --unstable-net <path> <addr>
res.insert(
file_stem.to_string(),
run(
@ -57,7 +57,7 @@ pub fn benchmark(
deno_exe.as_str(),
"run",
"--allow-all",
"--unstable",
"--unstable-net",
"--enable-testing-features-do-not-use",
path,
&server_addr(port),

View file

@ -13,7 +13,6 @@ mod ts {
use deno_core::error::AnyError;
use deno_core::op2;
use deno_core::OpState;
use deno_runtime::deno_node::SUPPORTED_BUILTIN_NODE_MODULES;
use serde::Serialize;
use std::collections::HashMap;
use std::io::Write;
@ -25,7 +24,6 @@ mod ts {
struct BuildInfoResponse {
build_specifier: String,
libs: Vec<String>,
node_built_in_module_names: Vec<String>,
}
#[op2]
@ -37,14 +35,9 @@ mod ts {
.iter()
.map(|s| s.to_string())
.collect();
let node_built_in_module_names = SUPPORTED_BUILTIN_NODE_MODULES
.iter()
.map(|s| s.to_string())
.collect();
BuildInfoResponse {
build_specifier,
libs: build_libs,
node_built_in_module_names,
}
}
@ -243,6 +236,7 @@ mod ts {
"esnext.decorators",
"esnext.disposable",
"esnext.intl",
"esnext.iterator",
"esnext.object",
"esnext.promise",
"esnext.regexp",
@ -446,7 +440,7 @@ fn main() {
);
let ts_version = ts::version();
debug_assert_eq!(ts_version, "5.5.2"); // bump this assertion when it changes
debug_assert_eq!(ts_version, "5.6.2"); // bump this assertion when it changes
println!("cargo:rustc-env=TS_VERSION={}", ts_version);
println!("cargo:rerun-if-env-changed=TS_VERSION");

View file

@ -80,10 +80,6 @@ impl CodeCache {
data,
));
}
pub fn remove_code_cache(&self, specifier: &str) {
Self::ensure_ok(self.inner.remove_code_cache(specifier))
}
}
impl code_cache::CodeCache for CodeCache {
@ -162,15 +158,6 @@ impl CodeCacheInner {
self.conn.execute(sql, params)?;
Ok(())
}
pub fn remove_code_cache(&self, specifier: &str) -> Result<(), AnyError> {
let sql = "
DELETE FROM codecache
WHERE specifier=$1;";
let params = params![specifier];
self.conn.execute(sql, params)?;
Ok(())
}
}
fn serialize_code_cache_type(

8
cli/cache/mod.rs vendored
View file

@ -4,6 +4,7 @@ use crate::args::CacheSetting;
use crate::errors::get_error_class_name;
use crate::file_fetcher::FetchNoFollowOptions;
use crate::file_fetcher::FetchOptions;
use crate::file_fetcher::FetchPermissionsOption;
use crate::file_fetcher::FileFetcher;
use crate::file_fetcher::FileOrRedirect;
use crate::npm::CliNpmResolver;
@ -18,7 +19,6 @@ use deno_graph::source::CacheInfo;
use deno_graph::source::LoadFuture;
use deno_graph::source::LoadResponse;
use deno_graph::source::Loader;
use deno_runtime::deno_permissions::PermissionsContainer;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
@ -112,7 +112,7 @@ pub struct FetchCacher {
global_http_cache: Arc<GlobalHttpCache>,
npm_resolver: Arc<dyn CliNpmResolver>,
module_info_cache: Arc<ModuleInfoCache>,
permissions: PermissionsContainer,
permissions: FetchPermissionsOption,
cache_info_enabled: bool,
}
@ -123,7 +123,7 @@ impl FetchCacher {
global_http_cache: Arc<GlobalHttpCache>,
npm_resolver: Arc<dyn CliNpmResolver>,
module_info_cache: Arc<ModuleInfoCache>,
permissions: PermissionsContainer,
permissions: FetchPermissionsOption,
) -> Self {
Self {
file_fetcher,
@ -230,7 +230,7 @@ impl Loader for FetchCacher {
.fetch_no_follow_with_options(FetchNoFollowOptions {
fetch_options: FetchOptions {
specifier: &specifier,
permissions: &permissions,
permissions: permissions.as_ref(),
maybe_accept: None,
maybe_cache_setting: maybe_cache_setting.as_ref(),
},

View file

@ -65,10 +65,13 @@ use deno_core::FeatureChecker;
use deno_runtime::deno_fs;
use deno_runtime::deno_node::DenoFsNodeResolverEnv;
use deno_runtime::deno_node::NodeResolver;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::deno_tls::rustls::RootCertStore;
use deno_runtime::deno_tls::RootCertStoreProvider;
use deno_runtime::deno_web::BlobStore;
use deno_runtime::inspector_server::InspectorServer;
use deno_runtime::permissions::RuntimePermissionDescriptorParser;
use log::warn;
use node_resolver::analyze::NodeCodeTranslator;
use once_cell::sync::OnceCell;
@ -181,6 +184,7 @@ struct CliFactoryServices {
node_code_translator: Deferred<Arc<CliNodeCodeTranslator>>,
node_resolver: Deferred<Arc<NodeResolver>>,
npm_resolver: Deferred<Arc<dyn CliNpmResolver>>,
permission_desc_parser: Deferred<Arc<RuntimePermissionDescriptorParser>>,
sloppy_imports_resolver: Deferred<Option<Arc<SloppyImportsResolver>>>,
text_only_progress_bar: Deferred<ProgressBar>,
type_checker: Deferred<Arc<TypeChecker>>,
@ -708,16 +712,20 @@ impl CliFactory {
.await
}
pub fn permission_desc_parser(
&self,
) -> Result<&Arc<RuntimePermissionDescriptorParser>, AnyError> {
self.services.permission_desc_parser.get_or_try_init(|| {
let fs = self.fs().clone();
Ok(Arc::new(RuntimePermissionDescriptorParser::new(fs)))
})
}
pub fn feature_checker(&self) -> Result<&Arc<FeatureChecker>, AnyError> {
self.services.feature_checker.get_or_try_init(|| {
let cli_options = self.cli_options()?;
let mut checker = FeatureChecker::default();
checker.set_exit_cb(Box::new(crate::unstable_exit_cb));
checker.set_warn_cb(Box::new(crate::unstable_warn_cb));
if cli_options.legacy_unstable_flag() {
checker.enable_legacy_unstable();
checker.warn_on_legacy_unstable();
}
let unstable_features = cli_options.unstable_features();
for granular_flag in crate::UNSTABLE_GRANULAR_FLAGS {
if unstable_features.contains(&granular_flag.name.to_string()) {
@ -743,6 +751,17 @@ impl CliFactory {
))
}
pub fn create_permissions_container(
&self,
) -> Result<PermissionsContainer, AnyError> {
let desc_parser = self.permission_desc_parser()?.clone();
let permissions = Permissions::from_options(
desc_parser.as_ref(),
&self.cli_options()?.permissions_options(),
)?;
Ok(PermissionsContainer::new(desc_parser, permissions))
}
pub async fn create_cli_main_worker_factory(
&self,
) -> Result<CliMainWorkerFactory, AnyError> {
@ -758,11 +777,17 @@ impl CliFactory {
};
Ok(CliMainWorkerFactory::new(
StorageKeyResolver::from_options(cli_options),
cli_options.sub_command().clone(),
npm_resolver.clone(),
node_resolver.clone(),
self.blob_store().clone(),
if cli_options.code_cache_enabled() {
Some(self.code_cache()?.clone())
} else {
None
},
self.feature_checker()?.clone(),
self.fs().clone(),
maybe_file_watcher_communicator,
self.maybe_inspector_server()?.clone(),
cli_options.maybe_lockfile().cloned(),
Box::new(CliModuleLoaderFactory::new(
cli_options,
if cli_options.code_cache_enabled() {
@ -783,17 +808,12 @@ impl CliFactory {
self.parsed_source_cache().clone(),
self.resolver().await?.clone(),
)),
node_resolver.clone(),
npm_resolver.clone(),
self.permission_desc_parser()?.clone(),
self.root_cert_store_provider().clone(),
self.fs().clone(),
maybe_file_watcher_communicator,
self.maybe_inspector_server()?.clone(),
cli_options.maybe_lockfile().cloned(),
self.feature_checker()?.clone(),
if cli_options.code_cache_enabled() {
Some(self.code_cache()?.clone())
} else {
None
},
StorageKeyResolver::from_options(cli_options),
cli_options.sub_command().clone(),
self.create_cli_main_worker_options()?,
))
}
@ -856,7 +876,6 @@ impl CliFactory {
unsafely_ignore_certificate_errors: cli_options
.unsafely_ignore_certificate_errors()
.clone(),
unstable: cli_options.legacy_unstable_flag(),
create_hmr_runner,
create_coverage_collector,
node_ipc: cli_options.node_ipc_fd(),

View file

@ -161,9 +161,38 @@ fn get_validated_scheme(
}
}
#[derive(Debug, Copy, Clone)]
pub enum FetchPermissionsOptionRef<'a> {
AllowAll,
Container(&'a PermissionsContainer),
}
#[derive(Debug, Clone)]
pub enum FetchPermissionsOption {
AllowAll,
Container(PermissionsContainer),
}
impl FetchPermissionsOption {
pub fn as_ref(&self) -> FetchPermissionsOptionRef {
match self {
FetchPermissionsOption::AllowAll => FetchPermissionsOptionRef::AllowAll,
FetchPermissionsOption::Container(container) => {
FetchPermissionsOptionRef::Container(container)
}
}
}
}
impl From<PermissionsContainer> for FetchPermissionsOption {
fn from(value: PermissionsContainer) -> Self {
Self::Container(value)
}
}
pub struct FetchOptions<'a> {
pub specifier: &'a ModuleSpecifier,
pub permissions: &'a PermissionsContainer,
pub permissions: FetchPermissionsOptionRef<'a>,
pub maybe_accept: Option<&'a str>,
pub maybe_cache_setting: Option<&'a CacheSetting>,
}
@ -515,11 +544,33 @@ impl FileFetcher {
}
}
#[inline(always)]
pub async fn fetch_bypass_permissions(
&self,
specifier: &ModuleSpecifier,
) -> Result<File, AnyError> {
self
.fetch_inner(specifier, FetchPermissionsOptionRef::AllowAll)
.await
}
/// Fetch a source file and asynchronously return it.
#[allow(dead_code)] // todo(25469): undo when merging
#[inline(always)]
pub async fn fetch(
&self,
specifier: &ModuleSpecifier,
permissions: &PermissionsContainer,
) -> Result<File, AnyError> {
self
.fetch_inner(specifier, FetchPermissionsOptionRef::Container(permissions))
.await
}
async fn fetch_inner(
&self,
specifier: &ModuleSpecifier,
permissions: FetchPermissionsOptionRef<'_>,
) -> Result<File, AnyError> {
self
.fetch_with_options(FetchOptions {
@ -583,7 +634,14 @@ impl FileFetcher {
specifier
);
let scheme = get_validated_scheme(specifier)?;
options.permissions.check_specifier(specifier)?;
match options.permissions {
FetchPermissionsOptionRef::AllowAll => {
// allow
}
FetchPermissionsOptionRef::Container(permissions) => {
permissions.check_specifier(specifier)?;
}
}
if let Some(file) = self.memory_files.get(specifier) {
Ok(FileOrRedirect::File(file))
} else if scheme == "file" {
@ -684,9 +742,7 @@ mod tests {
async fn test_fetch(specifier: &ModuleSpecifier) -> (File, FileFetcher) {
let (file_fetcher, _) = setup(CacheSetting::ReloadAll, None);
let result = file_fetcher
.fetch(specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(specifier).await;
assert!(result.is_ok());
(result.unwrap(), file_fetcher)
}
@ -700,7 +756,7 @@ mod tests {
.fetch_with_options_and_max_redirect(
FetchOptions {
specifier,
permissions: &PermissionsContainer::allow_all(),
permissions: FetchPermissionsOptionRef::AllowAll,
maybe_accept: None,
maybe_cache_setting: Some(&file_fetcher.cache_setting),
},
@ -796,9 +852,7 @@ mod tests {
};
file_fetcher.insert_memory_files(file.clone());
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let result_file = result.unwrap();
assert_eq!(result_file, file);
@ -809,9 +863,7 @@ mod tests {
let (file_fetcher, _) = setup(CacheSetting::Use, None);
let specifier = resolve_url("data:application/typescript;base64,ZXhwb3J0IGNvbnN0IGEgPSAiYSI7CgpleHBvcnQgZW51bSBBIHsKICBBLAogIEIsCiAgQywKfQo=").unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(
@ -840,9 +892,7 @@ mod tests {
None,
);
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(
@ -862,9 +912,7 @@ mod tests {
let specifier =
ModuleSpecifier::parse("http://localhost:4545/subdir/mod2.ts").unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(
@ -882,9 +930,7 @@ mod tests {
.set(&specifier, headers.clone(), file.source.as_bytes())
.unwrap();
let result = file_fetcher_01
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher_01.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(
@ -908,9 +954,7 @@ mod tests {
.set(&specifier, headers.clone(), file.source.as_bytes())
.unwrap();
let result = file_fetcher_02
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher_02.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(
@ -933,9 +977,7 @@ mod tests {
Default::default(),
None,
);
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(
@ -966,9 +1008,7 @@ mod tests {
None,
);
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let cache_key =
file_fetcher.http_cache.cache_item_key(&specifier).unwrap();
@ -1002,9 +1042,7 @@ mod tests {
Default::default(),
None,
);
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let cache_key =
@ -1041,9 +1079,7 @@ mod tests {
resolve_url("http://localhost:4545/subdir/redirects/redirect1.js")
.unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
assert_eq!(file.specifier, redirected_specifier);
@ -1082,9 +1118,7 @@ mod tests {
resolve_url("http://localhost:4545/subdir/redirects/redirect1.js")
.unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
assert_eq!(file.specifier, redirected_02_specifier);
@ -1142,9 +1176,7 @@ mod tests {
None,
);
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let cache_key = file_fetcher
@ -1182,7 +1214,7 @@ mod tests {
None,
);
let result = file_fetcher
.fetch(&redirected_specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&redirected_specifier)
.await;
assert!(result.is_ok());
@ -1223,7 +1255,7 @@ mod tests {
.fetch_with_options_and_max_redirect(
FetchOptions {
specifier: &specifier,
permissions: &PermissionsContainer::allow_all(),
permissions: FetchPermissionsOptionRef::AllowAll,
maybe_accept: None,
maybe_cache_setting: Some(&file_fetcher.cache_setting),
},
@ -1236,7 +1268,7 @@ mod tests {
.fetch_with_options_and_max_redirect(
FetchOptions {
specifier: &specifier,
permissions: &PermissionsContainer::allow_all(),
permissions: FetchPermissionsOptionRef::AllowAll,
maybe_accept: None,
maybe_cache_setting: Some(&file_fetcher.cache_setting),
},
@ -1264,9 +1296,7 @@ mod tests {
resolve_url("http://localhost:4550/subdir/redirects/redirect1.js")
.unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
assert_eq!(file.specifier, redirected_specifier);
@ -1310,9 +1340,7 @@ mod tests {
let specifier =
resolve_url("http://localhost:4545/run/002_hello.ts").unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(get_custom_error_class(&err), Some("NoRemote"));
@ -1343,22 +1371,16 @@ mod tests {
let specifier =
resolve_url("http://localhost:4545/run/002_hello.ts").unwrap();
let result = file_fetcher_01
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher_01.fetch_bypass_permissions(&specifier).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.to_string(), "Specifier not found in cache: \"http://localhost:4545/run/002_hello.ts\", --cached-only is specified.");
assert_eq!(get_custom_error_class(&err), Some("NotCached"));
let result = file_fetcher_02
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher_02.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let result = file_fetcher_01
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher_01.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
}
@ -1368,17 +1390,13 @@ mod tests {
let fixture_path = temp_dir.path().join("mod.ts");
let specifier = ModuleSpecifier::from_file_path(&fixture_path).unwrap();
fs::write(fixture_path.clone(), r#"console.log("hello deno");"#).unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(&*file.source, r#"console.log("hello deno");"#);
fs::write(fixture_path, r#"console.log("goodbye deno");"#).unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap().into_text_decoded().unwrap();
assert_eq!(&*file.source, r#"console.log("goodbye deno");"#);
@ -1392,18 +1410,14 @@ mod tests {
setup(CacheSetting::RespectHeaders, Some(temp_dir.clone()));
let specifier =
ModuleSpecifier::parse("http://localhost:4545/dynamic").unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
let first = file.source;
let (file_fetcher, _) =
setup(CacheSetting::RespectHeaders, Some(temp_dir.clone()));
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
let second = file.source;
@ -1419,18 +1433,14 @@ mod tests {
setup(CacheSetting::RespectHeaders, Some(temp_dir.clone()));
let specifier =
ModuleSpecifier::parse("http://localhost:4545/dynamic_cache").unwrap();
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
let first = file.source;
let (file_fetcher, _) =
setup(CacheSetting::RespectHeaders, Some(temp_dir.clone()));
let result = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await;
let result = file_fetcher.fetch_bypass_permissions(&specifier).await;
assert!(result.is_ok());
let file = result.unwrap();
let second = file.source;

View file

@ -9,9 +9,9 @@ use deno_core::error::AnyError;
use deno_core::parking_lot::RwLock;
use deno_graph::ModuleGraph;
use deno_runtime::colors;
use deno_runtime::deno_permissions::PermissionsContainer;
use crate::args::CliOptions;
use crate::file_fetcher::FetchPermissionsOption;
use crate::module_loader::ModuleLoadPreparer;
use crate::util::fs::collect_specifiers;
use crate::util::path::is_script_ext;
@ -75,7 +75,7 @@ impl MainModuleGraphContainer {
specifiers,
false,
self.cli_options.ts_type_lib_window(),
PermissionsContainer::allow_all(),
FetchPermissionsOption::AllowAll,
)
.await?;
graph_permit.commit();

View file

@ -11,6 +11,7 @@ use crate::cache::ModuleInfoCache;
use crate::cache::ParsedSourceCache;
use crate::colors;
use crate::errors::get_error_class_name;
use crate::file_fetcher::FetchPermissionsOption;
use crate::file_fetcher::FileFetcher;
use crate::npm::CliNpmResolver;
use crate::resolver::CliGraphResolver;
@ -41,7 +42,6 @@ use deno_graph::ResolutionError;
use deno_graph::SpecifierError;
use deno_runtime::deno_fs::FileSystem;
use deno_runtime::deno_node;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::jsr::JsrDepPackageReq;
use deno_semver::package::PackageNv;
use deno_semver::Version;
@ -670,12 +670,12 @@ impl ModuleGraphBuilder {
/// Creates the default loader used for creating a graph.
pub fn create_graph_loader(&self) -> cache::FetchCacher {
self.create_fetch_cacher(PermissionsContainer::allow_all())
self.create_fetch_cacher(FetchPermissionsOption::AllowAll)
}
pub fn create_fetch_cacher(
&self,
permissions: PermissionsContainer,
permissions: FetchPermissionsOption,
) -> cache::FetchCacher {
cache::FetchCacher::new(
self.file_fetcher.clone(),

View file

@ -6,7 +6,6 @@ use dashmap::DashMap;
use deno_core::serde_json;
use deno_graph::packages::JsrPackageInfo;
use deno_graph::packages::JsrPackageVersionInfo;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::package::PackageNv;
use deno_semver::package::PackageReq;
use std::sync::Arc;
@ -68,10 +67,7 @@ impl JsrFetchResolver {
let file_fetcher = self.file_fetcher.clone();
// spawn due to the lsp's `Send` requirement
let file = deno_core::unsync::spawn(async move {
file_fetcher
.fetch(&meta_url, &PermissionsContainer::allow_all())
.await
.ok()
file_fetcher.fetch_bypass_permissions(&meta_url).await.ok()
})
.await
.ok()??;
@ -96,10 +92,7 @@ impl JsrFetchResolver {
let file_fetcher = self.file_fetcher.clone();
// spawn due to the lsp's `Send` requirement
let file = deno_core::unsync::spawn(async move {
file_fetcher
.fetch(&meta_url, &PermissionsContainer::allow_all())
.await
.ok()
file_fetcher.fetch_bypass_permissions(&meta_url).await.ok()
})
.await
.ok()??;

View file

@ -37,12 +37,13 @@ use deno_lint::linter::LintConfig as DenoLintConfig;
use deno_npm::npm_rc::ResolvedNpmRc;
use deno_package_json::PackageJsonCache;
use deno_runtime::deno_node::PackageJson;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::fs_util::specifier_to_file_path;
use indexmap::IndexSet;
use lsp_types::ClientCapabilities;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::ops::Deref;
use std::ops::DerefMut;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
@ -70,6 +71,54 @@ fn is_true() -> bool {
true
}
/// Wrapper that defaults if it fails to deserialize. Good for individual
/// settings.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct SafeValue<T> {
inner: T,
}
impl<'de, T: Default + for<'de2> Deserialize<'de2>> Deserialize<'de>
for SafeValue<T>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Self {
inner: Deserialize::deserialize(deserializer).unwrap_or_default(),
})
}
}
impl<T: Serialize> Serialize for SafeValue<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.inner.serialize(serializer)
}
}
impl<T> Deref for SafeValue<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for SafeValue<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.inner
}
}
impl<T> SafeValue<T> {
pub fn as_deref(&self) -> &T {
&self.inner
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodeLensSettings {
@ -538,7 +587,7 @@ pub struct WorkspaceSettings {
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
#[serde(default)]
pub unstable: bool,
pub unstable: SafeValue<Vec<String>>,
#[serde(default)]
pub javascript: LanguageWorkspaceSettings,
@ -568,7 +617,7 @@ impl Default for WorkspaceSettings {
testing: Default::default(),
tls_certificate: None,
unsafely_ignore_certificate_errors: None,
unstable: false,
unstable: Default::default(),
javascript: Default::default(),
typescript: Default::default(),
}
@ -1459,17 +1508,16 @@ impl ConfigData {
ConfigWatchedFileType::ImportMap,
);
// spawn due to the lsp's `Send` requirement
let fetch_result = deno_core::unsync::spawn({
let file_fetcher = file_fetcher.cloned().unwrap();
let import_map_url = import_map_url.clone();
async move {
file_fetcher
.fetch(&import_map_url, &PermissionsContainer::allow_all())
.await
}
})
.await
.unwrap();
let fetch_result =
deno_core::unsync::spawn({
let file_fetcher = file_fetcher.cloned().unwrap();
let import_map_url = import_map_url.clone();
async move {
file_fetcher.fetch_bypass_permissions(&import_map_url).await
}
})
.await
.unwrap();
let value_result = fetch_result.and_then(|f| {
serde_json::from_slice::<Value>(&f.source).map_err(|e| e.into())
@ -1508,7 +1556,7 @@ impl ConfigData {
let file_fetcher = file_fetcher.clone().unwrap();
async move {
let file = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&specifier)
.await?
.into_text_decoded()?;
Ok(file.source.to_string())
@ -2141,7 +2189,7 @@ mod tests {
},
tls_certificate: None,
unsafely_ignore_certificate_errors: None,
unstable: false,
unstable: Default::default(),
javascript: LanguageWorkspaceSettings {
inlay_hints: InlayHintsSettings {
parameter_names: InlayHintsParamNamesOptions {

View file

@ -12,6 +12,7 @@ use super::language_server::StateSnapshot;
use super::performance::Performance;
use super::tsc;
use super::tsc::TsServer;
use super::urls::uri_parse_unencoded;
use super::urls::url_to_uri;
use super::urls::LspUrlMap;
@ -53,11 +54,9 @@ use deno_semver::package::PackageReq;
use import_map::ImportMap;
use import_map::ImportMapError;
use log::error;
use lsp_types::Uri;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use std::thread;
@ -738,7 +737,7 @@ fn to_lsp_related_information(
if let (Some(file_name), Some(start), Some(end)) =
(&ri.file_name, &ri.start, &ri.end)
{
let uri = Uri::from_str(file_name).unwrap();
let uri = uri_parse_unencoded(file_name).unwrap();
Some(lsp::DiagnosticRelatedInformation {
location: lsp::Location {
uri,

View file

@ -14,7 +14,6 @@ use deno_graph::packages::JsrPackageInfo;
use deno_graph::packages::JsrPackageInfoVersion;
use deno_graph::packages::JsrPackageVersionInfo;
use deno_graph::ModuleSpecifier;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::jsr::JsrPackageReqReference;
use deno_semver::package::PackageNv;
use deno_semver::package::PackageReq;
@ -311,7 +310,7 @@ impl PackageSearchApi for CliJsrSearchApi {
// spawn due to the lsp's `Send` requirement
let file = deno_core::unsync::spawn(async move {
file_fetcher
.fetch(&search_url, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&search_url)
.await?
.into_text_decoded()
})

View file

@ -3859,7 +3859,11 @@ impl Inner {
</details>
"#,
serde_json::to_string_pretty(&workspace_settings).unwrap(),
serde_json::to_string_pretty(&workspace_settings)
.inspect_err(|e| {
dbg!(e);
})
.unwrap(),
documents_specifiers.len(),
documents_specifiers
.into_iter()

View file

@ -4,7 +4,6 @@ use dashmap::DashMap;
use deno_core::anyhow::anyhow;
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::package::PackageNv;
use deno_semver::Version;
use serde::Deserialize;
@ -55,7 +54,7 @@ impl PackageSearchApi for CliNpmSearchApi {
let file_fetcher = self.file_fetcher.clone();
let file = deno_core::unsync::spawn(async move {
file_fetcher
.fetch(&search_url, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&search_url)
.await?
.into_text_decoded()
})

View file

@ -16,6 +16,7 @@ use crate::args::CacheSetting;
use crate::cache::GlobalHttpCache;
use crate::cache::HttpCache;
use crate::file_fetcher::FetchOptions;
use crate::file_fetcher::FetchPermissionsOptionRef;
use crate::file_fetcher::FileFetcher;
use crate::http_util::HttpClientProvider;
@ -30,7 +31,6 @@ use deno_core::url::Position;
use deno_core::url::Url;
use deno_core::ModuleSpecifier;
use deno_graph::Dependency;
use deno_runtime::deno_permissions::PermissionsContainer;
use log::error;
use once_cell::sync::Lazy;
use std::borrow::Cow;
@ -481,7 +481,7 @@ impl ModuleRegistry {
file_fetcher
.fetch_with_options(FetchOptions {
specifier: &specifier,
permissions: &PermissionsContainer::allow_all(),
permissions: FetchPermissionsOptionRef::AllowAll,
maybe_accept: Some("application/vnd.deno.reg.v2+json, application/vnd.deno.reg.v1+json;q=0.9, application/json;q=0.8"),
maybe_cache_setting: None,
})
@ -584,7 +584,7 @@ impl ModuleRegistry {
let file = deno_core::unsync::spawn({
async move {
file_fetcher
.fetch(&endpoint, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&endpoint)
.await
.ok()?
.into_text_decoded()
@ -983,7 +983,7 @@ impl ModuleRegistry {
// spawn due to the lsp's `Send` requirement
let file = deno_core::unsync::spawn(async move {
file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&specifier)
.await
.ok()?
.into_text_decoded()
@ -1049,7 +1049,7 @@ impl ModuleRegistry {
let specifier = specifier.clone();
async move {
file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&specifier)
.await
.map_err(|err| {
error!(
@ -1095,7 +1095,7 @@ impl ModuleRegistry {
let specifier = specifier.clone();
async move {
file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.fetch_bypass_permissions(&specifier)
.await
.map_err(|err| {
error!(

View file

@ -1,7 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use std::collections::HashMap;
use std::str::FromStr;
use deno_ast::LineAndColumnIndex;
use deno_ast::ModuleSpecifier;
@ -42,6 +41,7 @@ use super::config::LanguageWorkspaceSettings;
use super::config::ObjectLiteralMethodSnippets;
use super::config::TestingSettings;
use super::config::WorkspaceSettings;
use super::urls::uri_parse_unencoded;
use super::urls::url_to_uri;
#[derive(Debug)]
@ -263,7 +263,8 @@ impl ReplLanguageServer {
}
fn get_document_uri(&self) -> Uri {
Uri::from_str(self.cwd_uri.join("$deno$repl.ts").unwrap().as_str()).unwrap()
uri_parse_unencoded(self.cwd_uri.join("$deno$repl.ts").unwrap().as_str())
.unwrap()
}
}
@ -311,7 +312,7 @@ pub fn get_repl_workspace_settings() -> WorkspaceSettings {
document_preload_limit: 0, // don't pre-load any modules as it's expensive and not useful for the repl
tls_certificate: None,
unsafely_ignore_certificate_errors: None,
unstable: false,
unstable: Default::default(),
suggest: DenoCompletionSettings {
imports: ImportCompletionSettings {
auto_discover: false,

View file

@ -12,6 +12,7 @@ use crate::lsp::client::Client;
use crate::lsp::client::TestingNotification;
use crate::lsp::config;
use crate::lsp::logging::lsp_log;
use crate::lsp::urls::uri_parse_unencoded;
use crate::lsp::urls::uri_to_url;
use crate::lsp::urls::url_to_uri;
use crate::tools::test;
@ -30,13 +31,13 @@ use deno_core::unsync::spawn;
use deno_core::unsync::spawn_blocking;
use deno_core::ModuleSpecifier;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::tokio_util::create_and_run_current_thread;
use indexmap::IndexMap;
use lsp_types::Uri;
use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::HashSet;
use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
@ -219,15 +220,19 @@ impl TestRun {
) -> Result<(), AnyError> {
let args = self.get_args();
lsp_log!("Executing test run with arguments: {}", args.join(" "));
let flags =
Arc::new(flags_from_vec(args.into_iter().map(From::from).collect())?);
let flags = Arc::new(flags_from_vec(
args.into_iter().map(|s| From::from(s.as_ref())).collect(),
)?);
let factory = CliFactory::from_flags(flags);
let cli_options = factory.cli_options()?;
// Various test files should not share the same permissions in terms of
// `PermissionsContainer` - otherwise granting/revoking permissions in one
// file would have impact on other files, which is undesirable.
let permissions =
Permissions::from_options(&cli_options.permissions_options()?)?;
let permission_desc_parser = factory.permission_desc_parser()?.clone();
let permissions = Permissions::from_options(
permission_desc_parser.as_ref(),
&cli_options.permissions_options(),
)?;
let main_graph_container = factory.main_module_graph_container().await?;
test::check_specifiers(
factory.file_fetcher()?,
@ -275,7 +280,10 @@ impl TestRun {
let join_handles = queue.into_iter().map(move |specifier| {
let specifier = specifier.clone();
let worker_factory = worker_factory.clone();
let permissions = permissions.clone();
let permissions_container = PermissionsContainer::new(
permission_desc_parser.clone(),
permissions.clone(),
);
let worker_sender = test_event_sender_factory.worker();
let fail_fast_tracker = fail_fast_tracker.clone();
let lsp_filter = self.filters.get(&specifier);
@ -304,7 +312,7 @@ impl TestRun {
// channel.
create_and_run_current_thread(test::test_specifier(
worker_factory,
permissions,
permissions_container,
specifier,
worker_sender,
fail_fast_tracker,
@ -452,37 +460,42 @@ impl TestRun {
Ok(())
}
fn get_args(&self) -> Vec<&str> {
let mut args = vec!["deno", "test"];
fn get_args(&self) -> Vec<Cow<str>> {
let mut args = vec![Cow::Borrowed("deno"), Cow::Borrowed("test")];
args.extend(
self
.workspace_settings
.testing
.args
.iter()
.map(|s| s.as_str()),
.map(|s| Cow::Borrowed(s.as_str())),
);
args.push("--trace-leaks");
if self.workspace_settings.unstable && !args.contains(&"--unstable") {
args.push("--unstable");
args.push(Cow::Borrowed("--trace-leaks"));
for unstable_feature in self.workspace_settings.unstable.as_deref() {
let flag = format!("--unstable-{unstable_feature}");
if !args.contains(&Cow::Borrowed(&flag)) {
args.push(Cow::Owned(flag));
}
}
if let Some(config) = &self.workspace_settings.config {
if !args.contains(&"--config") && !args.contains(&"-c") {
args.push("--config");
args.push(config.as_str());
if !args.contains(&Cow::Borrowed("--config"))
&& !args.contains(&Cow::Borrowed("-c"))
{
args.push(Cow::Borrowed("--config"));
args.push(Cow::Borrowed(config.as_str()));
}
}
if let Some(import_map) = &self.workspace_settings.import_map {
if !args.contains(&"--import-map") {
args.push("--import-map");
args.push(import_map.as_str());
if !args.contains(&Cow::Borrowed("--import-map")) {
args.push(Cow::Borrowed("--import-map"));
args.push(Cow::Borrowed(import_map.as_str()));
}
}
if self.kind == lsp_custom::TestRunKind::Debug
&& !args.contains(&"--inspect")
&& !args.contains(&"--inspect-brk")
&& !args.contains(&Cow::Borrowed("--inspect"))
&& !args.contains(&Cow::Borrowed("--inspect-brk"))
{
args.push("--inspect");
args.push(Cow::Borrowed("--inspect"));
}
args
}
@ -529,7 +542,7 @@ impl LspTestDescription {
&self,
tests: &IndexMap<usize, LspTestDescription>,
) -> lsp_custom::TestIdentifier {
let uri = Uri::from_str(&self.location().file_name).unwrap();
let uri = uri_parse_unencoded(&self.location().file_name).unwrap();
let static_id = self.static_id();
let mut root_desc = self;
while let Some(parent_id) = root_desc.parent_id() {

View file

@ -5475,7 +5475,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"noEmit": true,
"lib": [],
}),
@ -5521,7 +5520,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"jsx": "react",
"lib": ["esnext", "dom", "deno.ns"],
"noEmit": true,
@ -5547,7 +5545,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -5578,7 +5575,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -5624,7 +5620,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -5655,7 +5650,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -5722,7 +5716,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -5800,7 +5793,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, cache) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -5942,7 +5934,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -6093,7 +6084,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -6202,7 +6192,6 @@ mod tests {
let (temp_dir, ts_server, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),
@ -6273,7 +6262,6 @@ mod tests {
let (temp_dir, _, snapshot, _) = setup(
json!({
"target": "esnext",
"module": "esnext",
"lib": ["deno.ns", "deno.window"],
"noEmit": true,
}),

View file

@ -55,6 +55,25 @@ const COMPONENT: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
.add(b'+')
.add(b',');
/// Characters that may be left unencoded in a `Url` path but not valid in a
/// `Uri` path.
const URL_TO_URI_PATH: &percent_encoding::AsciiSet =
&percent_encoding::CONTROLS
.add(b'[')
.add(b']')
.add(b'^')
.add(b'|');
/// Characters that may be left unencoded in a `Url` query but not valid in a
/// `Uri` query.
const URL_TO_URI_QUERY: &percent_encoding::AsciiSet =
&URL_TO_URI_PATH.add(b'\\').add(b'`').add(b'{').add(b'}');
/// Characters that may be left unencoded in a `Url` fragment but not valid in
/// a `Uri` fragment.
const URL_TO_URI_FRAGMENT: &percent_encoding::AsciiSet =
&URL_TO_URI_PATH.add(b'#').add(b'\\').add(b'{').add(b'}');
fn hash_data_specifier(specifier: &ModuleSpecifier) -> String {
let mut file_name_str = specifier.path().to_string();
if let Some(query) = specifier.query() {
@ -122,8 +141,33 @@ impl LspUrlMapInner {
}
}
pub fn uri_parse_unencoded(s: &str) -> Result<Uri, AnyError> {
url_to_uri(&Url::parse(s)?)
}
pub fn url_to_uri(url: &Url) -> Result<Uri, AnyError> {
Ok(Uri::from_str(url.as_str()).inspect_err(|err| {
let components = deno_core::url::quirks::internal_components(url);
let mut input = String::with_capacity(url.as_str().len());
input.push_str(&url.as_str()[..components.path_start as usize]);
input.push_str(
&percent_encoding::utf8_percent_encode(url.path(), URL_TO_URI_PATH)
.to_string(),
);
if let Some(query) = url.query() {
input.push('?');
input.push_str(
&percent_encoding::utf8_percent_encode(query, URL_TO_URI_QUERY)
.to_string(),
);
}
if let Some(fragment) = url.fragment() {
input.push('#');
input.push_str(
&percent_encoding::utf8_percent_encode(fragment, URL_TO_URI_FRAGMENT)
.to_string(),
);
}
Ok(Uri::from_str(&input).inspect_err(|err| {
lsp_warn!("Could not convert URL \"{url}\" to URI: {err}")
})?)
}
@ -189,7 +233,7 @@ impl LspUrlMap {
} else {
to_deno_uri(specifier)
};
let uri = Uri::from_str(&uri_str)?;
let uri = uri_parse_unencoded(&uri_str)?;
inner.put(specifier.clone(), uri.clone());
uri
};

View file

@ -337,17 +337,54 @@ fn exit_with_message(message: &str, code: i32) -> ! {
std::process::exit(code);
}
fn get_suggestions_for_commonjs_error(e: &JsError) -> Vec<FixSuggestion> {
if e.name.as_deref() == Some("ReferenceError") {
if let Some(msg) = &e.message {
if msg.contains("module is not defined")
|| msg.contains("exports is not defined")
{
return vec![
FixSuggestion::info("Deno does not support CommonJS modules without `.cjs` extension."),
FixSuggestion::hint("Rewrite this module to ESM or change the file extension to `.cjs`."),
];
}
fn get_suggestions_for_terminal_errors(e: &JsError) -> Vec<FixSuggestion> {
if let Some(msg) = &e.message {
if msg.contains("module is not defined")
|| msg.contains("exports is not defined")
{
return vec![
FixSuggestion::info(
"Deno does not support CommonJS modules without `.cjs` extension.",
),
FixSuggestion::hint(
"Rewrite this module to ESM or change the file extension to `.cjs`.",
),
];
} else if msg.contains("openKv is not a function") {
return vec![
FixSuggestion::info("Deno.openKv() is an unstable API."),
FixSuggestion::hint(
"Run again with `--unstable-kv` flag to enable this API.",
),
];
} else if msg.contains("cron is not a function") {
return vec![
FixSuggestion::info("Deno.cron() is an unstable API."),
FixSuggestion::hint(
"Run again with `--unstable-cron` flag to enable this API.",
),
];
} else if msg.contains("WebSocketStream is not defined") {
return vec![
FixSuggestion::info("new WebSocketStream() is an unstable API."),
FixSuggestion::hint(
"Run again with `--unstable-net` flag to enable this API.",
),
];
} else if msg.contains("Temporal is not defined") {
return vec![
FixSuggestion::info("Temporal is an unstable API."),
FixSuggestion::hint(
"Run again with `--unstable-temporal` flag to enable this API.",
),
];
} else if msg.contains("BroadcastChannel is not defined") {
return vec![
FixSuggestion::info("BroadcastChannel is an unstable API."),
FixSuggestion::hint(
"Run again with `--unstable-broadcast-channel` flag to enable this API.",
),
];
}
}
@ -359,7 +396,7 @@ fn exit_for_error(error: AnyError) -> ! {
let mut error_code = 1;
if let Some(e) = error.downcast_ref::<JsError>() {
let suggestions = get_suggestions_for_commonjs_error(e);
let suggestions = get_suggestions_for_terminal_errors(e);
error_string = format_js_error_with_suggestions(e, suggestions);
} else if let Some(SnapshotFromLockfileError::IntegrityCheckFailed(e)) =
error.downcast_ref::<SnapshotFromLockfileError>()
@ -380,18 +417,6 @@ pub(crate) fn unstable_exit_cb(feature: &str, api_name: &str) {
std::process::exit(70);
}
// TODO(bartlomieju): remove when `--unstable` flag is removed.
#[allow(clippy::print_stderr)]
pub(crate) fn unstable_warn_cb(feature: &str, api_name: &str) {
eprintln!(
"⚠️ {}",
colors::yellow(format!(
"The `{}` API was used with `--unstable` flag. The `--unstable` flag is deprecated and will be removed in Deno 2.0. Use granular `--unstable-{}` instead.\nLearn more at: https://docs.deno.com/runtime/manual/tools/unstable_flags",
api_name, feature
))
);
}
pub fn main() {
setup_panic_hook();
@ -434,25 +459,14 @@ fn resolve_flags_and_init(
Err(err) => exit_for_error(AnyError::from(err)),
};
// TODO(bartlomieju): remove when `--unstable` flag is removed.
// TODO(bartlomieju): remove in Deno v2.5 and hard error then.
if flags.unstable_config.legacy_flag_enabled {
#[allow(clippy::print_stderr)]
if matches!(flags.subcommand, DenoSubcommand::Check(_)) {
// can't use log crate because that's not setup yet
eprintln!(
"⚠️ {}",
colors::yellow(
"The `--unstable` flag is not needed for `deno check` anymore."
)
);
} else {
eprintln!(
"⚠️ {}",
colors::yellow(
"The `--unstable` flag is deprecated and will be removed in Deno 2.0. Use granular `--unstable-*` flags instead.\nLearn more at: https://docs.deno.com/runtime/manual/tools/unstable_flags"
)
);
}
log::warn!(
"⚠️ {}",
colors::yellow(
"The `--unstable` flag has been removed in Deno 2.0. Use granular `--unstable-*` flags instead.\nLearn more at: https://docs.deno.com/runtime/manual/tools/unstable_flags"
)
);
}
let default_v8_flags = match flags.subcommand {
@ -469,7 +483,7 @@ fn resolve_flags_and_init(
};
init_v8_flags(&default_v8_flags, &flags.v8_flags, get_v8_flags_from_env());
// TODO(bartlomieju): remove last argument in Deno 2.
// TODO(bartlomieju): remove last argument once Deploy no longer needs it
deno_core::JsRuntime::init_platform(
None, /* import assertions enabled */ false,
);

View file

@ -2,7 +2,6 @@
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashSet;
use std::path::PathBuf;
use std::pin::Pin;
use std::rc::Rc;
@ -44,7 +43,6 @@ use deno_core::error::generic_error;
use deno_core::error::AnyError;
use deno_core::futures::future::FutureExt;
use deno_core::futures::Future;
use deno_core::parking_lot::Mutex;
use deno_core::resolve_url;
use deno_core::ModuleCodeString;
use deno_core::ModuleLoader;
@ -106,7 +104,7 @@ impl ModuleLoadPreparer {
roots: &[ModuleSpecifier],
is_dynamic: bool,
lib: TsTypeLib,
permissions: PermissionsContainer,
permissions: crate::file_fetcher::FetchPermissionsOption,
) -> Result<(), AnyError> {
log::debug!("Preparing module load.");
let _pb_clear_guard = self.progress_bar.clear_guard();
@ -244,7 +242,6 @@ impl CliModuleLoaderFactory {
emitter: self.shared.emitter.clone(),
parsed_source_cache: self.shared.parsed_source_cache.clone(),
shared: self.shared.clone(),
prevent_v8_code_cache: Default::default(),
})));
ModuleLoaderAndSourceMapGetter {
module_loader: loader,
@ -296,10 +293,6 @@ struct CliModuleLoaderInner<TGraphContainer: ModuleGraphContainer> {
emitter: Arc<Emitter>,
parsed_source_cache: Arc<ParsedSourceCache>,
graph_container: TGraphContainer,
// NOTE(bartlomieju): this is temporary, for deprecated import assertions.
// Should be removed in Deno 2.
// Modules stored here should not be V8 code-cached.
prevent_v8_code_cache: Arc<Mutex<HashSet<String>>>,
}
impl<TGraphContainer: ModuleGraphContainer>
@ -769,7 +762,7 @@ impl<TGraphContainer: ModuleGraphContainer> ModuleLoader
&[specifier],
is_dynamic,
lib,
root_permissions,
root_permissions.into(),
)
.await?;
update_permit.commit();
@ -785,14 +778,6 @@ impl<TGraphContainer: ModuleGraphContainer> ModuleLoader
code_cache: &[u8],
) -> Pin<Box<dyn Future<Output = ()>>> {
if let Some(cache) = self.0.shared.code_cache.as_ref() {
if self
.0
.prevent_v8_code_cache
.lock()
.contains(specifier.as_str())
{
return std::future::ready(()).boxed_local();
}
// This log line is also used by tests.
log::debug!(
"Updating V8 code cache for ES module: {specifier}, [{source_hash:?}]"
@ -807,19 +792,6 @@ impl<TGraphContainer: ModuleGraphContainer> ModuleLoader
std::future::ready(()).boxed_local()
}
fn purge_and_prevent_code_cache(&self, specifier: &str) {
if let Some(cache) = self.0.shared.code_cache.as_ref() {
// This log line is also used by tests.
log::debug!("Remove V8 code cache for ES module: {specifier}");
cache.remove_code_cache(specifier);
self
.0
.prevent_v8_code_cache
.lock()
.insert(specifier.to_string());
}
}
fn get_source_map(&self, file_name: &str) -> Option<Vec<u8>> {
let specifier = resolve_url(file_name).ok()?;
match specifier.scheme() {

View file

@ -280,7 +280,7 @@ impl NodeRequireResolver for ByonmCliNpmResolver {
.components()
.any(|c| c.as_os_str().to_ascii_lowercase() == "node_modules")
{
permissions.check_read(path)?;
_ = permissions.check_read_path(path)?;
}
Ok(())
}

View file

@ -318,7 +318,7 @@ fn get_npm_pending_resolver(
// WARNING: When bumping this version, check if anything needs to be
// updated in the `setNodeOnlyGlobalNames` call in 99_main_compiler.js
types_node_version_req: Some(
VersionReq::parse_from_npm("18.0.0 - 18.16.19").unwrap(),
VersionReq::parse_from_npm("22.0.0 - 22.5.4").unwrap(),
),
},
)

View file

@ -127,7 +127,8 @@ impl RegistryReadPermissionChecker {
}
}
permissions.check_read(path)
_ = permissions.check_read_path(path)?;
Ok(())
}
}

View file

@ -642,13 +642,16 @@ async fn sync_resolution_with_fs(
} else {
continue; // skip, package not found
};
let alias_clashes = remote.req.name != remote.alias
&& newest_packages_by_name.contains_key(&remote.alias);
let Some(remote_alias) = &remote.alias else {
continue;
};
let alias_clashes = remote.req.name != *remote_alias
&& newest_packages_by_name.contains_key(remote_alias);
let install_in_child = {
// we'll install in the child if the alias is taken by another package, or
// if there's already a package with the same name but different version
// linked into the root
match found_names.entry(&remote.alias) {
match found_names.entry(remote_alias) {
Entry::Occupied(nv) => {
alias_clashes
|| remote.req.name != nv.get().name // alias to a different package (in case of duplicate aliases)
@ -679,7 +682,7 @@ async fn sync_resolution_with_fs(
existing_child_node_modules_dirs.insert(dest_node_modules.clone());
}
let mut dest_path = dest_node_modules;
dest_path.push(&remote.alias);
dest_path.push(remote_alias);
symlink_package_dir(&local_registry_package_path, &dest_path)?;
} else {
@ -689,7 +692,7 @@ async fn sync_resolution_with_fs(
{
symlink_package_dir(
&local_registry_package_path,
&join_package_name(root_node_modules_dir_path, &remote.alias),
&join_package_name(root_node_modules_dir_path, remote_alias),
)?;
}
}
@ -774,9 +777,12 @@ async fn sync_resolution_with_fs(
// install correctly for a workspace (potentially in sub directories),
// but this is good enough for a first pass
for workspace in npm_install_deps_provider.workspace_pkgs() {
let Some(workspace_alias) = &workspace.alias else {
continue;
};
symlink_package_dir(
&workspace.target_dir,
&root_node_modules_dir_path.join(&workspace.alias),
&root_node_modules_dir_path.join(workspace_alias),
)?;
}
}

View file

@ -15,7 +15,6 @@ use deno_core::serde_json;
use deno_npm::registry::NpmPackageInfo;
use deno_runtime::deno_node::NodeRequireResolver;
use deno_runtime::deno_node::NpmProcessStateProvider;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_semver::package::PackageNv;
use deno_semver::package::PackageReq;
use node_resolver::NpmResolver;
@ -152,10 +151,7 @@ impl NpmFetchResolver {
let file_fetcher = self.file_fetcher.clone();
// spawn due to the lsp's `Send` requirement
let file = deno_core::unsync::spawn(async move {
file_fetcher
.fetch(&info_url, &PermissionsContainer::allow_all())
.await
.ok()
file_fetcher.fetch_bypass_permissions(&info_url).await.ok()
})
.await
.ok()??;

View file

@ -2,6 +2,7 @@
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time;
use deno_core::error::generic_error;
@ -13,6 +14,7 @@ use deno_core::ModuleSpecifier;
use deno_core::OpState;
use deno_runtime::deno_permissions::create_child_permissions;
use deno_runtime::deno_permissions::ChildPermissionsArg;
use deno_runtime::deno_permissions::PermissionDescriptorParser;
use deno_runtime::deno_permissions::PermissionsContainer;
use tokio::sync::mpsc::UnboundedSender;
use uuid::Uuid;
@ -59,11 +61,18 @@ pub fn op_pledge_test_permissions(
#[serde] args: ChildPermissionsArg,
) -> Result<Uuid, AnyError> {
let token = Uuid::new_v4();
let permission_desc_parser = state
.borrow::<Arc<dyn PermissionDescriptorParser>>()
.clone();
let parent_permissions = state.borrow_mut::<PermissionsContainer>();
let worker_permissions = {
let mut parent_permissions = parent_permissions.0.lock();
let perms = create_child_permissions(&mut parent_permissions, args)?;
PermissionsContainer::new(perms)
let mut parent_permissions = parent_permissions.inner.lock();
let perms = create_child_permissions(
permission_desc_parser.as_ref(),
&mut parent_permissions,
args,
)?;
PermissionsContainer::new(permission_desc_parser, perms)
};
let parent_permissions = parent_permissions.clone();
@ -74,7 +83,7 @@ pub fn op_pledge_test_permissions(
state.put::<PermissionsHolder>(PermissionsHolder(token, parent_permissions));
// NOTE: This call overrides current permission set for the worker
state.put(worker_permissions.0.clone());
state.put(worker_permissions.inner.clone());
state.put::<PermissionsContainer>(worker_permissions);
Ok(token)
@ -91,7 +100,7 @@ pub fn op_restore_test_permissions(
}
let permissions = permissions_holder.1;
state.put(permissions.0.clone());
state.put(permissions.inner.clone());
state.put::<PermissionsContainer>(permissions);
Ok(())
} else {

View file

@ -18,9 +18,11 @@ use deno_core::ModuleSpecifier;
use deno_core::OpState;
use deno_runtime::deno_permissions::create_child_permissions;
use deno_runtime::deno_permissions::ChildPermissionsArg;
use deno_runtime::deno_permissions::PermissionDescriptorParser;
use deno_runtime::deno_permissions::PermissionsContainer;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use uuid::Uuid;
deno_core::extension!(deno_test,
@ -54,11 +56,18 @@ pub fn op_pledge_test_permissions(
#[serde] args: ChildPermissionsArg,
) -> Result<Uuid, AnyError> {
let token = Uuid::new_v4();
let permission_desc_parser = state
.borrow::<Arc<dyn PermissionDescriptorParser>>()
.clone();
let parent_permissions = state.borrow_mut::<PermissionsContainer>();
let worker_permissions = {
let mut parent_permissions = parent_permissions.0.lock();
let perms = create_child_permissions(&mut parent_permissions, args)?;
PermissionsContainer::new(perms)
let mut parent_permissions = parent_permissions.inner.lock();
let perms = create_child_permissions(
permission_desc_parser.as_ref(),
&mut parent_permissions,
args,
)?;
PermissionsContainer::new(permission_desc_parser, perms)
};
let parent_permissions = parent_permissions.clone();
@ -68,7 +77,7 @@ pub fn op_pledge_test_permissions(
state.put::<PermissionsHolder>(PermissionsHolder(token, parent_permissions));
// NOTE: This call overrides current permission set for the worker
state.put(worker_permissions.0.clone());
state.put(worker_permissions.inner.clone());
state.put::<PermissionsContainer>(worker_permissions);
Ok(token)
@ -85,7 +94,7 @@ pub fn op_restore_test_permissions(
}
let permissions = permissions_holder.1;
state.put(permissions.0.clone());
state.put(permissions.inner.clone());
state.put::<PermissionsContainer>(permissions);
Ok(())
} else {

View file

@ -707,7 +707,14 @@ impl Resolver for CliGraphResolver {
.resolve_if_for_npm_pkg(raw_specifier, referrer, to_node_mode(mode))
.map_err(ResolveError::Other)?;
if let Some(res) = maybe_resolution {
return Ok(res.into_url());
match res {
NodeResolution::Esm(url) | NodeResolution::CommonJs(url) => {
return Ok(url)
}
NodeResolution::BuiltIn(_) => {
// don't resolve bare specifiers for built-in modules via node resolution
}
}
}
}

View file

@ -279,25 +279,6 @@
"type": "string"
}
},
"files": {
"type": "object",
"properties": {
"include": {
"type": "array",
"description": "List of files, directories or globs that will be linted.",
"items": {
"type": "string"
}
},
"exclude": {
"type": "array",
"description": "List of files, directories or globs that will not be linted.",
"items": {
"type": "string"
}
}
}
},
"rules": {
"type": "object",
"properties": {
@ -355,25 +336,6 @@
"type": "string"
}
},
"files": {
"type": "object",
"properties": {
"include": {
"type": "array",
"description": "List of files, directories or globs that will be formatted.",
"items": {
"type": "string"
}
},
"exclude": {
"type": "array",
"description": "List of files, directories or globs that will not be formatted.",
"items": {
"type": "string"
}
}
}
},
"useTabs": {
"description": "Whether to use tabs (true) or spaces (false) for indentation.",
"type": "boolean",
@ -477,25 +439,6 @@
"items": {
"type": "string"
}
},
"files": {
"type": "object",
"properties": {
"include": {
"type": "array",
"description": "List of files, directories or globs that will be searched for tests.",
"items": {
"type": "string"
}
},
"exclude": {
"type": "array",
"description": "List of files, directories or globs that will not be searched for tests.",
"items": {
"type": "string"
}
}
}
}
}
},
@ -536,25 +479,6 @@
"items": {
"type": "string"
}
},
"files": {
"type": "object",
"properties": {
"include": {
"type": "array",
"description": "List of files, directories or globs that will be searched for benchmarks.",
"items": {
"type": "string"
}
},
"exclude": {
"type": "array",
"description": "List of files, directories or globs that will not be searched for benchmarks.",
"items": {
"type": "string"
}
}
}
}
}
},

View file

@ -624,7 +624,7 @@ impl<'a> DenoCompileBinaryWriter<'a> {
},
node_modules,
unstable_config: UnstableConfig {
legacy_flag_enabled: cli_options.legacy_unstable_flag(),
legacy_flag_enabled: false,
bare_node_builtins: cli_options.unstable_bare_node_builtins(),
sloppy_imports: cli_options.unstable_sloppy_imports(),
features: cli_options.unstable_features(),

View file

@ -32,6 +32,8 @@ use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::deno_tls::rustls::RootCertStore;
use deno_runtime::deno_tls::RootCertStoreProvider;
use deno_runtime::deno_web::BlobStore;
use deno_runtime::permissions::RuntimePermissionDescriptorParser;
use deno_runtime::WorkerExecutionMode;
use deno_runtime::WorkerLogLevel;
use deno_semver::npm::NpmPackageReqReference;
@ -449,7 +451,6 @@ pub async fn run(
let current_exe_path = std::env::current_exe().unwrap();
let current_exe_name =
current_exe_path.file_name().unwrap().to_string_lossy();
let maybe_cwd = std::env::current_dir().ok();
let deno_dir_provider = Arc::new(DenoDirProvider::new(None));
let root_cert_store_provider = Arc::new(StandaloneRootCertStoreProvider {
ca_stores: metadata.ca_stores,
@ -660,8 +661,7 @@ pub async fn run(
};
let permissions = {
let mut permissions =
metadata.permissions.to_options(maybe_cwd.as_deref())?;
let mut permissions = metadata.permissions.to_options();
// if running with an npm vfs, grant read access to it
if let Some(vfs_root) = maybe_vfs_root {
match &mut permissions.allow_read {
@ -669,25 +669,24 @@ pub async fn run(
// do nothing, already granted
}
Some(vec) => {
vec.push(vfs_root);
vec.push(vfs_root.to_string_lossy().to_string());
}
None => {
permissions.allow_read = Some(vec![vfs_root]);
permissions.allow_read =
Some(vec![vfs_root.to_string_lossy().to_string()]);
}
}
}
PermissionsContainer::new(Permissions::from_options(&permissions)?)
let desc_parser =
Arc::new(RuntimePermissionDescriptorParser::new(fs.clone()));
let permissions =
Permissions::from_options(desc_parser.as_ref(), &permissions)?;
PermissionsContainer::new(desc_parser, permissions)
};
let feature_checker = Arc::new({
let mut checker = FeatureChecker::default();
checker.set_exit_cb(Box::new(crate::unstable_exit_cb));
// TODO(bartlomieju): enable, once we deprecate `--unstable` in favor
// of granular --unstable-* flags.
// feature_checker.set_warn_cb(Box::new(crate::unstable_warn_cb));
if metadata.unstable_config.legacy_flag_enabled {
checker.enable_legacy_unstable();
}
for feature in metadata.unstable_config.features {
// `metadata` is valid for the whole lifetime of the program, so we
// can leak the string here.
@ -695,21 +694,24 @@ pub async fn run(
}
checker
});
let permission_desc_parser =
Arc::new(RuntimePermissionDescriptorParser::new(fs.clone()));
let worker_factory = CliMainWorkerFactory::new(
StorageKeyResolver::empty(),
crate::args::DenoSubcommand::Run(Default::default()),
npm_resolver,
node_resolver,
Default::default(),
Box::new(module_loader_factory),
root_cert_store_provider,
Arc::new(BlobStore::default()),
// Code cache is not supported for standalone binary yet.
None,
feature_checker,
fs,
None,
None,
None,
feature_checker,
// Code cache is not supported for standalone binary yet.
None,
Box::new(module_loader_factory),
node_resolver,
npm_resolver,
permission_desc_parser,
root_cert_store_provider,
StorageKeyResolver::empty(),
crate::args::DenoSubcommand::Run(Default::default()),
CliMainWorkerOptions {
argv: metadata.argv,
log_level: WorkerLogLevel::Info,
@ -733,7 +735,6 @@ pub async fn run(
seed: metadata.seed,
unsafely_ignore_certificate_errors: metadata
.unsafely_ignore_certificate_errors,
unstable: metadata.unstable_config.legacy_flag_enabled,
create_hmr_runner: None,
create_coverage_collector: None,
node_ipc: None,
@ -744,7 +745,7 @@ pub async fn run(
// Initialize v8 once from the main thread.
v8_set_flags(construct_v8_flags(&[], &metadata.v8_flags, vec![]));
// TODO(bartlomieju): remove last argument in Deno 2.
// TODO(bartlomieju): remove last argument once Deploy no longer needs it
deno_core::JsRuntime::init_platform(None, true);
let mut worker = worker_factory

View file

@ -30,6 +30,7 @@ use deno_core::ModuleSpecifier;
use deno_core::PollEventLoopOptions;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::permissions::RuntimePermissionDescriptorParser;
use deno_runtime::tokio_util::create_and_run_current_thread;
use deno_runtime::WorkerExecutionMode;
use indexmap::IndexMap;
@ -144,14 +145,14 @@ fn create_reporter(
/// Run a single specifier as an executable bench module.
async fn bench_specifier(
worker_factory: Arc<CliMainWorkerFactory>,
permissions: Permissions,
permissions_container: PermissionsContainer,
specifier: ModuleSpecifier,
sender: UnboundedSender<BenchEvent>,
filter: TestFilter,
) -> Result<(), AnyError> {
match bench_specifier_inner(
worker_factory,
permissions,
permissions_container,
specifier.clone(),
&sender,
filter,
@ -176,7 +177,7 @@ async fn bench_specifier(
/// Run a single specifier as an executable bench module.
async fn bench_specifier_inner(
worker_factory: Arc<CliMainWorkerFactory>,
permissions: Permissions,
permissions_container: PermissionsContainer,
specifier: ModuleSpecifier,
sender: &UnboundedSender<BenchEvent>,
filter: TestFilter,
@ -185,7 +186,7 @@ async fn bench_specifier_inner(
.create_custom_worker(
WorkerExecutionMode::Bench,
specifier.clone(),
PermissionsContainer::new(permissions),
permissions_container,
vec![ops::bench::deno_bench::init_ops(sender.clone())],
Default::default(),
)
@ -264,6 +265,7 @@ async fn bench_specifier_inner(
async fn bench_specifiers(
worker_factory: Arc<CliMainWorkerFactory>,
permissions: &Permissions,
permissions_desc_parser: &Arc<RuntimePermissionDescriptorParser>,
specifiers: Vec<ModuleSpecifier>,
options: BenchSpecifierOptions,
) -> Result<(), AnyError> {
@ -273,13 +275,16 @@ async fn bench_specifiers(
let join_handles = specifiers.into_iter().map(move |specifier| {
let worker_factory = worker_factory.clone();
let permissions = permissions.clone();
let permissions_container = PermissionsContainer::new(
permissions_desc_parser.clone(),
permissions.clone(),
);
let sender = sender.clone();
let options = option_for_handles.clone();
spawn_blocking(move || {
let future = bench_specifier(
worker_factory,
permissions,
permissions_container,
specifier,
sender,
options.filter,
@ -410,8 +415,11 @@ pub async fn run_benchmarks(
// Various bench files should not share the same permissions in terms of
// `PermissionsContainer` - otherwise granting/revoking permissions in one
// file would have impact on other files, which is undesirable.
let permissions =
Permissions::from_options(&cli_options.permissions_options()?)?;
let permission_desc_parser = factory.permission_desc_parser()?.clone();
let permissions = Permissions::from_options(
permission_desc_parser.as_ref(),
&cli_options.permissions_options(),
)?;
let members_with_bench_options =
cli_options.resolve_bench_options_for_members(&bench_flags)?;
@ -446,6 +454,7 @@ pub async fn run_benchmarks(
bench_specifiers(
worker_factory,
&permissions,
&permission_desc_parser,
specifiers,
BenchSpecifierOptions {
filter: TestFilter::from_flag(&workspace_bench_options.filter),
@ -519,8 +528,11 @@ pub async fn run_benchmarks_with_watch(
// Various bench files should not share the same permissions in terms of
// `PermissionsContainer` - otherwise granting/revoking permissions in one
// file would have impact on other files, which is undesirable.
let permissions =
Permissions::from_options(&cli_options.permissions_options()?)?;
let permission_desc_parser = factory.permission_desc_parser()?.clone();
let permissions = Permissions::from_options(
permission_desc_parser.as_ref(),
&cli_options.permissions_options(),
)?;
let graph = module_graph_creator
.create_graph(graph_kind, collected_bench_modules.clone())
@ -568,6 +580,7 @@ pub async fn run_benchmarks_with_watch(
bench_specifiers(
worker_factory,
&permissions,
&permission_desc_parser,
specifiers,
BenchSpecifierOptions {
filter: TestFilter::from_flag(&workspace_bench_options.filter),

View file

@ -84,7 +84,9 @@ impl TypeChecker {
graph: ModuleGraph,
options: CheckOptions,
) -> Result<Arc<ModuleGraph>, AnyError> {
let (graph, diagnostics) = self.check_diagnostics(graph, options).await?;
let (graph, mut diagnostics) =
self.check_diagnostics(graph, options).await?;
diagnostics.emit_warnings();
if diagnostics.is_empty() {
Ok(graph)
} else {

View file

@ -907,6 +907,7 @@ fn get_resolved_malva_config(
};
let language_options = LanguageOptions {
align_comments: true,
hex_case: HexCase::Lower,
hex_color_length: None,
quotes: if let Some(true) = options.single_quote {
@ -1011,7 +1012,6 @@ fn get_resolved_yaml_config(
let layout_options = LayoutOptions {
print_width: options.line_width.unwrap_or(80) as usize,
use_tabs: options.use_tabs.unwrap_or_default(),
indent_width: options.indent_width.unwrap_or(2) as usize,
line_break: LineBreak::Lf,
};
@ -1028,6 +1028,9 @@ fn get_resolved_yaml_config(
brace_spacing: true,
bracket_spacing: false,
dash_spacing: DashSpacing::OneSpace,
prefer_single_line: false,
flow_sequence_prefer_single_line: None,
flow_map_prefer_single_line: None,
trim_trailing_whitespaces: true,
trim_trailing_zero: false,
ignore_comment_directive: "deno-fmt-ignore".into(),

View file

@ -490,10 +490,6 @@ async fn resolve_shim_data(
TypeCheckMode::Local => executable_args.push("--check".to_string()),
}
if flags.unstable_config.legacy_flag_enabled {
executable_args.push("--unstable".to_string());
}
for feature in &flags.unstable_config.features {
executable_args.push(format!("--unstable-{}", feature));
}
@ -822,13 +818,7 @@ mod tests {
create_install_shim(
&HttpClientProvider::new(None, None),
&Flags {
unstable_config: UnstableConfig {
legacy_flag_enabled: true,
..Default::default()
},
..Flags::default()
},
&Flags::default(),
InstallFlagsGlobal {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
@ -850,12 +840,11 @@ mod tests {
let content = fs::read_to_string(file_path).unwrap();
if cfg!(windows) {
assert!(content.contains(
r#""run" "--unstable" "--no-config" "http://localhost:4545/echo_server.ts""#
r#""run" "--no-config" "http://localhost:4545/echo_server.ts""#
));
} else {
assert!(content.contains(
r#"run --unstable --no-config 'http://localhost:4545/echo_server.ts'"#
));
assert!(content
.contains(r#"run --no-config 'http://localhost:4545/echo_server.ts'"#));
}
}
@ -886,13 +875,7 @@ mod tests {
async fn install_unstable_legacy() {
let shim_data = resolve_shim_data(
&HttpClientProvider::new(None, None),
&Flags {
unstable_config: UnstableConfig {
legacy_flag_enabled: true,
..Default::default()
},
..Default::default()
},
&Default::default(),
&InstallFlagsGlobal {
module_url: "http://localhost:4545/echo_server.ts".to_string(),
args: vec![],
@ -907,12 +890,7 @@ mod tests {
assert_eq!(shim_data.name, "echo_server");
assert_eq!(
shim_data.args,
vec![
"run",
"--unstable",
"--no-config",
"http://localhost:4545/echo_server.ts",
]
vec!["run", "--no-config", "http://localhost:4545/echo_server.ts",]
);
}

View file

@ -25,7 +25,6 @@ use deno_core::serde_json::json;
use deno_core::url::Url;
use deno_runtime::deno_io::Stdio;
use deno_runtime::deno_io::StdioPipe;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::WorkerExecutionMode;
use deno_terminal::colors;
@ -65,7 +64,8 @@ pub async fn kernel(
resolve_url_or_path("./$deno$jupyter.ts", cli_options.initial_cwd())
.unwrap();
// TODO(bartlomieju): should we run with all permissions?
let permissions = PermissionsContainer::new(Permissions::allow_all());
let permissions =
PermissionsContainer::allow_all(factory.permission_desc_parser()?.clone());
let npm_resolver = factory.npm_resolver().await?.clone();
let resolver = factory.resolver().await?.clone();
let worker_factory = factory.create_cli_main_worker_factory().await?;

View file

@ -106,7 +106,7 @@ pub async fn cache_top_level_deps(
&roots,
false,
deno_config::deno_json::TsTypeLib::DenoWorker,
deno_runtime::deno_permissions::PermissionsContainer::allow_all(),
crate::file_fetcher::FetchPermissionsOption::AllowAll,
)
.await?;
}

View file

@ -16,8 +16,6 @@ use deno_core::error::AnyError;
use deno_core::futures::StreamExt;
use deno_core::serde_json;
use deno_core::unsync::spawn_blocking;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::WorkerExecutionMode;
use rustyline::error::ReadlineError;
@ -151,9 +149,7 @@ async fn read_eval_file(
let specifier =
deno_core::resolve_url_or_path(eval_file, cli_options.initial_cwd())?;
let file = file_fetcher
.fetch(&specifier, &PermissionsContainer::allow_all())
.await?;
let file = file_fetcher.fetch_bypass_permissions(&specifier).await?;
Ok(file.into_text_decoded()?.source)
}
@ -166,9 +162,7 @@ pub async fn run(
let factory = CliFactory::from_flags(flags);
let cli_options = factory.cli_options()?;
let main_module = cli_options.resolve_main_module()?;
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let npm_resolver = factory.npm_resolver().await?.clone();
let resolver = factory.resolver().await?.clone();
let file_fetcher = factory.file_fetcher()?;

View file

@ -5,8 +5,6 @@ use std::sync::Arc;
use deno_config::deno_json::NodeModulesDirMode;
use deno_core::error::AnyError;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::WorkerExecutionMode;
use crate::args::EvalFlags;
@ -62,9 +60,7 @@ pub async fn run_script(
maybe_npm_install(&factory).await?;
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let worker_factory = factory.create_cli_main_worker_factory().await?;
let mut worker = worker_factory
.create_main_worker(mode, main_module, permissions)
@ -83,9 +79,7 @@ pub async fn run_from_stdin(flags: Arc<Flags>) -> Result<i32, AnyError> {
let file_fetcher = factory.file_fetcher()?;
let worker_factory = factory.create_cli_main_worker_factory().await?;
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let mut source = Vec::new();
std::io::stdin().read_to_end(&mut source)?;
// Save a fake file into file fetcher cache
@ -131,9 +125,7 @@ async fn run_with_watch(
let _ = watcher_communicator.watch_paths(cli_options.watch_paths());
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let mut worker = factory
.create_cli_main_worker_factory()
.await?
@ -181,9 +173,7 @@ pub async fn eval_command(
source: source_code.into_bytes().into(),
});
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let worker_factory = factory.create_cli_main_worker_factory().await?;
let mut worker = worker_factory
.create_main_worker(WorkerExecutionMode::Eval, main_module, permissions)

View file

@ -5,7 +5,6 @@ use std::sync::Arc;
use deno_core::error::AnyError;
use deno_core::futures::TryFutureExt;
use deno_core::ModuleSpecifier;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use super::run::check_permission_before_script;
@ -45,9 +44,7 @@ pub async fn serve(
maybe_npm_install(&factory).await?;
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let worker_factory = factory.create_cli_main_worker_factory().await?;
do_serve(
@ -175,9 +172,7 @@ async fn serve_with_watch(
let _ = watcher_communicator.watch_paths(cli_options.watch_paths());
let permissions = PermissionsContainer::new(Permissions::from_options(
&cli_options.permissions_options()?,
)?);
let permissions = factory.create_permissions_container()?;
let worker_factory = factory.create_cli_main_worker_factory().await?;
do_serve(worker_factory, main_module, permissions, worker_count, hmr)

View file

@ -75,7 +75,7 @@ See https://docs.deno.com/go/config"#
&cli_options.start_dir,
&tasks_config,
)?;
return Ok(1);
return Ok(0);
}
};

View file

@ -318,10 +318,10 @@ pub const OP_DETAILS: phf::Map<&'static str, [&'static str; 2]> = phf_map! {
"op_fs_chown_async" => ["change the owner of a file", "awaiting the result of a `Deno.chown` call"],
"op_fs_copy_file_async" => ["copy a file", "awaiting the result of a `Deno.copyFile` call"],
"op_fs_events_poll" => ["get the next file system event", "breaking out of a for await loop looping over `Deno.FsEvents`"],
"op_fs_fdatasync_async" => ["flush pending data operations for a file to disk", "awaiting the result of a `Deno.fdatasync` or `Deno.FsFile.syncData` call"],
"op_fs_file_sync_data_async" => ["flush pending data operations for a file to disk", "awaiting the result of a `Deno.FsFile.prototype.syncData` call"],
"op_fs_file_stat_async" => ["get file metadata", "awaiting the result of a `Deno.FsFile.prototype.stat` call"],
"op_fs_flock_async" => ["lock a file", "awaiting the result of a `Deno.FsFile.lock` call"],
"op_fs_fsync_async" => ["flush pending data operations for a file to disk", "awaiting the result of a `Deno.fsync` or `Deno.FsFile.sync` call"],
"op_fs_file_sync_async" => ["flush pending data operations for a file to disk", "awaiting the result of a `Deno.FsFile.sync` call"],
"op_fs_file_truncate_async" => ["truncate a file", "awaiting the result of a `Deno.FsFile.prototype.truncate` call"],
"op_fs_funlock_async" => ["unlock a file", "awaiting the result of a `Deno.FsFile.unlock` call"],
"op_fs_link_async" => ["create a hard link", "awaiting the result of a `Deno.link` call"],

View file

@ -56,6 +56,7 @@ use deno_runtime::deno_io::StdioPipe;
use deno_runtime::deno_permissions::Permissions;
use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::fmt_errors::format_js_error;
use deno_runtime::permissions::RuntimePermissionDescriptorParser;
use deno_runtime::tokio_util::create_and_run_current_thread;
use deno_runtime::worker::MainWorker;
use deno_runtime::WorkerExecutionMode;
@ -595,7 +596,7 @@ fn get_test_reporter(options: &TestSpecifiersOptions) -> Box<dyn TestReporter> {
async fn configure_main_worker(
worker_factory: Arc<CliMainWorkerFactory>,
specifier: &Url,
permissions: Permissions,
permissions_container: PermissionsContainer,
worker_sender: TestEventWorkerSender,
options: &TestSpecifierOptions,
) -> Result<(Option<Box<dyn CoverageCollector>>, MainWorker), anyhow::Error> {
@ -603,7 +604,7 @@ async fn configure_main_worker(
.create_custom_worker(
WorkerExecutionMode::Test,
specifier.clone(),
PermissionsContainer::new(permissions),
permissions_container,
vec![ops::testing::deno_test::init_ops(worker_sender.sender)],
Stdio {
stdin: StdioPipe::inherit(),
@ -646,7 +647,7 @@ async fn configure_main_worker(
/// both.
pub async fn test_specifier(
worker_factory: Arc<CliMainWorkerFactory>,
permissions: Permissions,
permissions_container: PermissionsContainer,
specifier: ModuleSpecifier,
worker_sender: TestEventWorkerSender,
fail_fast_tracker: FailFastTracker,
@ -658,7 +659,7 @@ pub async fn test_specifier(
let (coverage_collector, mut worker) = configure_main_worker(
worker_factory,
&specifier,
permissions,
permissions_container,
worker_sender,
&options,
)
@ -1327,9 +1328,8 @@ async fn fetch_inline_files(
) -> Result<Vec<File>, AnyError> {
let mut files = Vec::new();
for specifier in specifiers {
let fetch_permissions = PermissionsContainer::allow_all();
let file = file_fetcher
.fetch(&specifier, &fetch_permissions)
.fetch_bypass_permissions(&specifier)
.await?
.into_text_decoded()?;
@ -1407,6 +1407,7 @@ static HAS_TEST_RUN_SIGINT_HANDLER: AtomicBool = AtomicBool::new(false);
async fn test_specifiers(
worker_factory: Arc<CliMainWorkerFactory>,
permissions: &Permissions,
permission_desc_parser: &Arc<RuntimePermissionDescriptorParser>,
specifiers: Vec<ModuleSpecifier>,
options: TestSpecifiersOptions,
) -> Result<(), AnyError> {
@ -1434,14 +1435,17 @@ async fn test_specifiers(
let join_handles = specifiers.into_iter().map(move |specifier| {
let worker_factory = worker_factory.clone();
let permissions = permissions.clone();
let permissions_container = PermissionsContainer::new(
permission_desc_parser.clone(),
permissions.clone(),
);
let worker_sender = test_event_sender_factory.worker();
let fail_fast_tracker = fail_fast_tracker.clone();
let specifier_options = options.specifier.clone();
spawn_blocking(move || {
create_and_run_current_thread(test_specifier(
worker_factory,
permissions,
permissions_container,
specifier,
worker_sender,
fail_fast_tracker,
@ -1739,9 +1743,7 @@ async fn fetch_specifiers_with_test_mode(
.collect::<Vec<_>>();
for (specifier, mode) in &mut specifiers_with_mode {
let file = file_fetcher
.fetch(specifier, &PermissionsContainer::allow_all())
.await?;
let file = file_fetcher.fetch_bypass_permissions(specifier).await?;
let (media_type, _) = file.resolve_media_type_and_charset();
if matches!(media_type, MediaType::Unknown | MediaType::Dts) {
@ -1764,8 +1766,11 @@ pub async fn run_tests(
// Various test files should not share the same permissions in terms of
// `PermissionsContainer` - otherwise granting/revoking permissions in one
// file would have impact on other files, which is undesirable.
let permissions =
Permissions::from_options(&cli_options.permissions_options()?)?;
let permission_desc_parser = factory.permission_desc_parser()?;
let permissions = Permissions::from_options(
permission_desc_parser.as_ref(),
&cli_options.permissions_options(),
)?;
let log_level = cli_options.log_level();
let members_with_test_options =
@ -1802,6 +1807,7 @@ pub async fn run_tests(
test_specifiers(
worker_factory,
&permissions,
permission_desc_parser,
specifiers_with_mode
.into_iter()
.filter_map(|(s, m)| match m {
@ -1914,8 +1920,11 @@ pub async fn run_tests_with_watch(
.flatten()
.collect::<Vec<_>>();
let permissions =
Permissions::from_options(&cli_options.permissions_options()?)?;
let permission_desc_parser = factory.permission_desc_parser()?;
let permissions = Permissions::from_options(
permission_desc_parser.as_ref(),
&cli_options.permissions_options(),
)?;
let graph = module_graph_creator
.create_graph(graph_kind, test_modules)
.await?;
@ -1969,6 +1978,7 @@ pub async fn run_tests_with_watch(
test_specifiers(
worker_factory,
&permissions,
permission_desc_parser,
specifiers_with_mode
.into_iter()
.filter_map(|(s, m)| match m {

View file

@ -4,6 +4,7 @@
use crate::args::Flags;
use crate::args::UpgradeFlags;
use crate::args::UPGRADE_USAGE;
use crate::colors;
use crate::factory::CliFactory;
use crate::http_util::HttpClient;
@ -15,7 +16,6 @@ use crate::util::progress_bar::ProgressBarStyle;
use crate::version;
use async_trait::async_trait;
use color_print::cstr;
use deno_core::anyhow::bail;
use deno_core::anyhow::Context;
use deno_core::error::AnyError;
@ -36,9 +36,7 @@ use std::time::Duration;
const RELEASE_URL: &str = "https://github.com/denoland/deno/releases";
const CANARY_URL: &str = "https://dl.deno.land/canary";
const RC_URL: &str = "https://dl.deno.land/release";
static EXAMPLE_USAGE: &str = cstr!("Example usage:\n <p(245)>deno upgrade | deno upgrade 1.46 | deno upgrade canary</>");
const DL_RELEASE_URL: &str = "https://dl.deno.land/release";
pub static ARCHIVE_NAME: Lazy<String> =
Lazy::new(|| format!("deno-{}.zip", env!("TARGET")));
@ -385,8 +383,15 @@ pub fn check_for_upgrades(
colors::italic_gray("Run `deno upgrade rc` to install it.")
);
}
// TODO(bartlomieju)
ReleaseChannel::Lts => unreachable!(),
ReleaseChannel::Lts => {
log::info!(
"{} {} → {} {}",
colors::green("A new LTS release of Deno is available:"),
colors::cyan(version::DENO_VERSION_INFO.deno),
colors::cyan(&upgrade_version),
colors::italic_gray("Run `deno upgrade lts` to install it.")
);
}
}
update_checker.store_prompted();
@ -424,7 +429,7 @@ async fn check_for_upgrades_for_lsp_with_provider(
}
match release_channel {
ReleaseChannel::Stable | ReleaseChannel::Rc => {
ReleaseChannel::Stable | ReleaseChannel::Rc | ReleaseChannel::Lts => {
if let Ok(current) = Version::parse_standard(&current_version) {
if let Ok(latest) =
Version::parse_standard(&latest_version.version_or_hash)
@ -444,9 +449,6 @@ async fn check_for_upgrades_for_lsp_with_provider(
latest_version: latest_version.version_or_hash,
is_canary: true,
})),
// TODO(bartlomieju)
ReleaseChannel::Lts => unreachable!(),
}
}
@ -625,6 +627,7 @@ impl RequestedVersion {
};
let mut maybe_passed_version = upgrade_flags.version.clone();
// TODO(bartlomieju): prefer flags first? This whole logic could be cleaned up...
if let Some(val) = &upgrade_flags.version_or_hash_or_channel {
if let Ok(channel) = ReleaseChannel::deserialize(&val.to_lowercase()) {
// TODO(bartlomieju): print error if any other flags passed?
@ -651,18 +654,19 @@ impl RequestedVersion {
let (channel, passed_version) = if is_canary {
if !re_hash.is_match(&passed_version) {
bail!(
"Invalid commit hash passed ({})\n\n{}",
"Invalid commit hash passed ({})\n\nPass a semver, or a full 40 character git commit hash, or a release channel name.\n\nUsage:\n{}",
colors::gray(passed_version),
EXAMPLE_USAGE
UPGRADE_USAGE
);
}
(ReleaseChannel::Canary, passed_version)
} else {
let Ok(semver) = Version::parse_standard(&passed_version) else {
bail!(
"Invalid version passed ({})\n\n{}",
"Invalid version passed ({})\n\nPass a semver, or a full 40 character git commit hash, or a release channel name.\n\nUsage:\n{}",
colors::gray(passed_version),
EXAMPLE_USAGE
UPGRADE_USAGE
);
};
@ -690,65 +694,26 @@ fn select_specific_version_for_upgrade(
version: String,
force: bool,
) -> Result<Option<AvailableVersion>, AnyError> {
match release_channel {
ReleaseChannel::Stable => {
let current_is_passed = if version::DENO_VERSION_INFO.release_channel
!= ReleaseChannel::Canary
{
version::DENO_VERSION_INFO.deno == version
} else {
false
};
if !force && current_is_passed {
log::info!(
"Version {} is already installed",
version::DENO_VERSION_INFO.deno
);
return Ok(None);
}
Ok(Some(AvailableVersion {
version_or_hash: version,
release_channel,
}))
let current_is_passed = match release_channel {
ReleaseChannel::Stable | ReleaseChannel::Rc | ReleaseChannel::Lts => {
version::DENO_VERSION_INFO.release_channel == release_channel
&& version::DENO_VERSION_INFO.deno == version
}
ReleaseChannel::Canary => {
let current_is_passed = version::DENO_VERSION_INFO.git_hash == version;
if !force && current_is_passed {
log::info!(
"Version {} is already installed",
version::DENO_VERSION_INFO.deno
);
return Ok(None);
}
ReleaseChannel::Canary => version::DENO_VERSION_INFO.git_hash == version,
};
Ok(Some(AvailableVersion {
version_or_hash: version,
release_channel,
}))
}
ReleaseChannel::Rc => {
let current_is_passed = version::DENO_VERSION_INFO.release_channel
== ReleaseChannel::Rc
&& version::DENO_VERSION_INFO.deno == version;
if !force && current_is_passed {
log::info!(
"Version {} is already installed",
version::DENO_VERSION_INFO.deno
);
return Ok(None);
}
Ok(Some(AvailableVersion {
version_or_hash: version,
release_channel,
}))
}
// TODO(bartlomieju)
ReleaseChannel::Lts => unreachable!(),
if !force && current_is_passed {
log::info!(
"Version {} is already installed",
version::DENO_VERSION_INFO.deno
);
return Ok(None);
}
Ok(Some(AvailableVersion {
version_or_hash: version,
release_channel,
}))
}
async fn find_latest_version_to_upgrade(
@ -762,52 +727,28 @@ async fn find_latest_version_to_upgrade(
);
let client = http_client_provider.get_or_create()?;
let latest_version_found =
fetch_latest_version(&client, release_channel, UpgradeCheckKind::Execution)
.await?;
let latest_version_found = match fetch_latest_version(
&client,
release_channel,
UpgradeCheckKind::Execution,
)
.await
{
Ok(v) => v,
Err(err) => {
if err.to_string().contains("Not found") {
bail!(
"No {} release available at the moment.",
release_channel.name()
);
} else {
return Err(err);
}
}
};
let (maybe_newer_latest_version, current_version) = match release_channel {
ReleaseChannel::Stable => {
let current_version = version::DENO_VERSION_INFO.deno;
// If the current binary is not a stable channel, we can skip
// computation if we're on a newer release - we're not.
if version::DENO_VERSION_INFO.release_channel != ReleaseChannel::Stable {
(Some(latest_version_found), current_version)
} else {
let current = Version::parse_standard(current_version).unwrap();
let latest =
Version::parse_standard(&latest_version_found.version_or_hash)
.unwrap();
let current_is_most_recent = current >= latest;
if !force && current_is_most_recent {
(None, current_version)
} else {
(Some(latest_version_found), current_version)
}
}
}
ReleaseChannel::Rc => {
let current_version = version::DENO_VERSION_INFO.deno;
// If the current binary is not an rc channel, we can skip
// computation if we're on a newer release - we're not.
if version::DENO_VERSION_INFO.release_channel != ReleaseChannel::Rc {
(Some(latest_version_found), current_version)
} else {
let current = Version::parse_standard(current_version).unwrap();
let latest =
Version::parse_standard(&latest_version_found.version_or_hash)
.unwrap();
let current_is_most_recent = current >= latest;
if !force && current_is_most_recent {
(None, current_version)
} else {
(Some(latest_version_found), current_version)
}
}
}
ReleaseChannel::Canary => {
let current_version = version::DENO_VERSION_INFO.git_hash;
let current_is_most_recent =
@ -819,8 +760,26 @@ async fn find_latest_version_to_upgrade(
(Some(latest_version_found), current_version)
}
}
// TODO(bartlomieju)
ReleaseChannel::Lts => unreachable!(),
ReleaseChannel::Stable | ReleaseChannel::Lts | ReleaseChannel::Rc => {
let current_version = version::DENO_VERSION_INFO.deno;
// If the current binary is not the same channel, we can skip
// computation if we're on a newer release - we're not.
if version::DENO_VERSION_INFO.release_channel != release_channel {
(Some(latest_version_found), current_version)
} else {
let current = Version::parse_standard(current_version)?;
let latest =
Version::parse_standard(&latest_version_found.version_or_hash)?;
let current_is_most_recent = current >= latest;
if !force && current_is_most_recent {
(None, current_version)
} else {
(Some(latest_version_found), current_version)
}
}
}
};
log::info!("");
@ -900,7 +859,7 @@ fn get_latest_version_url(
Cow::Owned(format!("canary-{target_tuple}-latest.txt"))
}
ReleaseChannel::Rc => Cow::Borrowed("release-rc-latest.txt"),
_ => unreachable!(),
ReleaseChannel::Lts => Cow::Borrowed("release-lts-latest.txt"),
};
let query_param = match check_kind {
UpgradeCheckKind::Execution => "",
@ -927,12 +886,14 @@ fn get_download_url(
format!("{}/download/v{}/{}", RELEASE_URL, version, *ARCHIVE_NAME)
}
ReleaseChannel::Rc => {
format!("{}/v{}/{}", RC_URL, version, *ARCHIVE_NAME)
format!("{}/v{}/{}", DL_RELEASE_URL, version, *ARCHIVE_NAME)
}
ReleaseChannel::Canary => {
format!("{}/{}/{}", CANARY_URL, version, *ARCHIVE_NAME)
}
ReleaseChannel::Lts => unreachable!(),
ReleaseChannel::Lts => {
format!("{}/v{}/{}", DL_RELEASE_URL, version, *ARCHIVE_NAME)
}
};
Url::parse(&download_url).with_context(|| {
@ -1123,6 +1084,8 @@ mod test {
use std::cell::RefCell;
use std::rc::Rc;
use test_util::assert_contains;
use super::*;
#[test]
@ -1221,6 +1184,27 @@ mod test {
"5c69b4861b52ab406e73b9cd85c254f0505cb20f".to_string()
)
);
upgrade_flags.version_or_hash_or_channel =
Some("5c69b4861b52a".to_string());
let err = RequestedVersion::from_upgrade_flags(upgrade_flags.clone())
.unwrap_err()
.to_string();
assert_contains!(err, "Invalid version passed");
assert_contains!(
err,
"Pass a semver, or a full 40 character git commit hash, or a release channel name."
);
upgrade_flags.version_or_hash_or_channel = Some("11.asd.1324".to_string());
let err = RequestedVersion::from_upgrade_flags(upgrade_flags.clone())
.unwrap_err()
.to_string();
assert_contains!(err, "Invalid version passed");
assert_contains!(
err,
"Pass a semver, or a full 40 character git commit hash, or a release channel name."
);
}
#[test]
@ -1628,6 +1612,46 @@ mod test {
),
"https://dl.deno.land/release-rc-latest.txt?lsp"
);
assert_eq!(
get_latest_version_url(
ReleaseChannel::Lts,
"x86_64-pc-windows-msvc",
UpgradeCheckKind::Lsp
),
"https://dl.deno.land/release-lts-latest.txt?lsp"
);
assert_eq!(
get_latest_version_url(
ReleaseChannel::Lts,
"aarch64-apple-darwin",
UpgradeCheckKind::Execution
),
"https://dl.deno.land/release-lts-latest.txt"
);
assert_eq!(
get_latest_version_url(
ReleaseChannel::Lts,
"aarch64-apple-darwin",
UpgradeCheckKind::Lsp
),
"https://dl.deno.land/release-lts-latest.txt?lsp"
);
assert_eq!(
get_latest_version_url(
ReleaseChannel::Lts,
"x86_64-pc-windows-msvc",
UpgradeCheckKind::Execution
),
"https://dl.deno.land/release-lts-latest.txt"
);
assert_eq!(
get_latest_version_url(
ReleaseChannel::Lts,
"x86_64-pc-windows-msvc",
UpgradeCheckKind::Lsp
),
"https://dl.deno.land/release-lts-latest.txt?lsp"
);
}
#[test]

8153
cli/tsc/00_typescript.js vendored

File diff suppressed because it is too large Load diff

View file

@ -32,24 +32,15 @@ delete Object.prototype.__proto__;
/** @type {ReadonlySet<string>} */
const unstableDenoProps = new Set([
"AtomicOperation",
"CreateHttpClientOptions",
"DatagramConn",
"HttpClient",
"Kv",
"KvListIterator",
"KvU64",
"UnsafeCallback",
"UnsafePointer",
"UnsafePointerView",
"UnsafeFnPointer",
"UnixConnectOptions",
"UnixListenOptions",
"createHttpClient",
"dlopen",
"listen",
"listenDatagram",
"openKv",
"umask",
]);
const unstableMsgSuggestion =
"If not, try changing the 'lib' compiler option to include 'deno.unstable' " +
@ -126,27 +117,6 @@ delete Object.prototype.__proto__;
}
}
class SpecifierIsCjsCache {
/** @type {Set<string>} */
#cache = new Set();
/** @param {[string, ts.Extension]} param */
maybeAdd([specifier, ext]) {
if (ext === ".cjs" || ext === ".d.cts" || ext === ".cts") {
this.#cache.add(specifier);
}
}
add(specifier) {
this.#cache.add(specifier);
}
/** @param specifier {string} */
has(specifier) {
return this.#cache.has(specifier);
}
}
// In the case of the LSP, this will only ever contain the assets.
/** @type {Map<string, ts.SourceFile>} */
const sourceFileCache = new Map();
@ -163,7 +133,8 @@ delete Object.prototype.__proto__;
/** @type {Map<string, boolean>} */
const isNodeSourceFileCache = new Map();
const isCjsCache = new SpecifierIsCjsCache();
/** @type {Map<string, boolean>} */
const isCjsCache = new Map();
// Maps asset specifiers to the first scope that the asset was loaded into.
/** @type {Map<string, string | null>} */
@ -244,7 +215,7 @@ delete Object.prototype.__proto__;
scriptSnapshot,
{
...getCreateSourceFileOptions(sourceFileOptions),
impliedNodeFormat: isCjsCache.has(fileName)
impliedNodeFormat: (isCjsCache.get(fileName) ?? false)
? ts.ModuleKind.CommonJS
: ts.ModuleKind.ESNext,
// in the lsp we want to be able to show documentation
@ -491,6 +462,8 @@ delete Object.prototype.__proto__;
// TS2792: Cannot find module. Did you mean to set the 'moduleResolution'
// option to 'node', or to add aliases to the 'paths' option?
2792,
// TS2307: Cannot find module '{0}' or its corresponding type declarations.
2307,
// TS5009: Cannot find the common subdirectory path for the input files.
5009,
// TS5055: Cannot write file
@ -645,18 +618,13 @@ delete Object.prototype.__proto__;
if (!fileInfo) {
return undefined;
}
let { data, scriptKind, version, isCjs } = fileInfo;
const { data, scriptKind, version, isCjs } = fileInfo;
assert(
data != null,
`"data" is unexpectedly null for "${specifier}".`,
);
// use the cache for non-lsp
if (isCjs == null) {
isCjs = isCjsCache.has(specifier);
} else if (isCjs) {
isCjsCache.add(specifier);
}
isCjsCache.set(specifier, isCjs);
sourceFile = ts.createSourceFile(
specifier,
@ -731,11 +699,10 @@ delete Object.prototype.__proto__;
/** @type {[string, ts.Extension] | undefined} */
const resolved = ops.op_resolve(
containingFilePath,
isCjsCache.has(containingFilePath),
isCjsCache.get(containingFilePath) ?? false,
[fileReference.fileName],
)?.[0];
if (resolved) {
isCjsCache.maybeAdd(resolved);
return {
primary: true,
resolvedFileName: resolved[0],
@ -765,13 +732,12 @@ delete Object.prototype.__proto__;
/** @type {Array<[string, ts.Extension] | undefined>} */
const resolved = ops.op_resolve(
base,
isCjsCache.has(base),
isCjsCache.get(base) ?? false,
specifiers,
);
if (resolved) {
const result = resolved.map((item) => {
if (item) {
isCjsCache.maybeAdd(item);
const [resolvedFileName, extension] = item;
return {
resolvedFileName,
@ -850,9 +816,7 @@ delete Object.prototype.__proto__;
if (!fileInfo) {
return undefined;
}
if (fileInfo.isCjs) {
isCjsCache.add(specifier);
}
isCjsCache.set(specifier, fileInfo.isCjs);
sourceTextCache.set(specifier, fileInfo.data);
scriptVersionCache.set(specifier, fileInfo.version);
sourceText = fileInfo.data;
@ -980,6 +944,8 @@ delete Object.prototype.__proto__;
Object.assign(options, {
allowNonTsExtensions: true,
allowImportingTsExtensions: true,
module: ts.ModuleKind.NodeNext,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
});
if (errors.length > 0 && logDebug) {
debug(ts.formatDiagnostics(errors, host));
@ -1059,7 +1025,7 @@ delete Object.prototype.__proto__;
: ts.sortAndDeduplicateDiagnostics(
checkFiles.map((s) => program.getSemanticDiagnostics(s)).flat(),
)),
].filter((diagnostic) => !IGNORED_DIAGNOSTICS.includes(diagnostic.code));
].filter(filterMapDiagnostic);
// emit the tsbuildinfo file
// @ts-ignore: emitBuildInfo is not exposed (https://github.com/microsoft/TypeScript/issues/49871)
@ -1074,6 +1040,27 @@ delete Object.prototype.__proto__;
debug("<<< exec stop");
}
/** @param {ts.Diagnostic} diagnostic */
function filterMapDiagnostic(diagnostic) {
if (IGNORED_DIAGNOSTICS.includes(diagnostic.code)) {
return false;
}
// make the diagnostic for using an `export =` in an es module a warning
if (diagnostic.code === 1203) {
diagnostic.category = ts.DiagnosticCategory.Warning;
if (typeof diagnostic.messageText === "string") {
const message =
" This will start erroring in a future version of Deno 2 " +
"in order to align with TypeScript.";
// seems typescript shares objects, so check if it's already been set
if (!diagnostic.messageText.endsWith(message)) {
diagnostic.messageText += message;
}
}
}
return true;
}
/**
* @param {any} e
* @returns {e is (OperationCanceledError | ts.OperationCanceledException)}
@ -1145,7 +1132,8 @@ delete Object.prototype.__proto__;
"experimentalDecorators": false,
"isolatedModules": true,
"lib": ["deno.ns", "deno.window", "deno.unstable"],
"module": "esnext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"moduleDetection": "force",
"noEmit": true,
"resolveJsonModule": true,
@ -1287,7 +1275,7 @@ delete Object.prototype.__proto__;
...ls.getSemanticDiagnostics(specifier),
...ls.getSuggestionDiagnostics(specifier),
...ls.getSyntacticDiagnostics(specifier),
].filter(({ code }) => !IGNORED_DIAGNOSTICS.includes(code)));
].filter(filterMapDiagnostic));
}
return respond(id, diagnosticMap);
} catch (e) {
@ -1333,48 +1321,38 @@ delete Object.prototype.__proto__;
// A build time only op that provides some setup information that is used to
// ensure the snapshot is setup properly.
/** @type {{ buildSpecifier: string; libs: string[]; nodeBuiltInModuleNames: string[] }} */
const { buildSpecifier, libs, nodeBuiltInModuleNames } = ops.op_build_info();
ts.deno.setNodeBuiltInModuleNames(nodeBuiltInModuleNames);
const { buildSpecifier, libs } = ops.op_build_info();
// list of globals that should be kept in Node's globalThis
ts.deno.setNodeOnlyGlobalNames([
// when bumping the @types/node version we should check if
// anything needs to be updated here
"NodeRequire",
"RequireResolve",
"RequireResolve",
"process",
"console",
"__filename",
"__dirname",
"require",
"module",
"__filename",
"Buffer",
"BufferConstructor",
"BufferEncoding",
"clearImmediate",
"clearInterval",
"clearTimeout",
"console",
"Console",
"ErrorConstructor",
"exports",
"gc",
"BufferEncoding",
"BufferConstructor",
"WithImplicitCoercion",
"Buffer",
"Console",
"ImportMeta",
"setTimeout",
"setInterval",
"setImmediate",
"Global",
"AbortController",
"AbortSignal",
"Blob",
"BroadcastChannel",
"MessageChannel",
"MessagePort",
"Event",
"EventTarget",
"performance",
"TextDecoder",
"TextEncoder",
"URL",
"URLSearchParams",
"ImportMeta",
"localStorage",
"module",
"NodeModule",
"NodeRequire",
"process",
"queueMicrotask",
"RequestInit",
"require",
"ResponseInit",
"sessionStorage",
"setImmediate",
"setInterval",
"setTimeout",
]);
for (const lib of libs) {

64
cli/tsc/_analyze_types_node.ts Executable file
View file

@ -0,0 +1,64 @@
#!/usr/bin/env -S deno run --allow-env --allow-read --allow-write=.
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import {
ModuleDeclarationKind,
Node,
Project,
ts,
} from "jsr:@ts-morph/ts-morph@23";
import { Path } from "jsr:@david/path@0.2";
const dir = new Path(import.meta.dirname!);
const typesNodeDir = dir.join("../../../DefinitelyTyped/types/node");
const project = new Project({
tsConfigFilePath: typesNodeDir.join("tsconfig.json").toString(),
});
const names = new Set<string>();
const ignoredNames = new Set<string>([
"Array",
"BigInt64Array",
"BigUint64Array",
"Float32Array",
"Float64Array",
"Int16Array",
"Int32Array",
"Int8Array",
"NodeJS",
"ReadonlyArray",
"RelativeIndexable",
"RequireResolve",
"String",
"SymbolConstructor",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"WithImplicitCoercion",
]);
for (const file of project.getSourceFiles()) {
for (
const mod of file.getDescendantsOfKind(ts.SyntaxKind.ModuleDeclaration)
) {
if (mod.getDeclarationKind() !== ModuleDeclarationKind.Global) continue;
for (const statement of mod.getStatements()) {
if (Node.isVariableStatement(statement)) {
for (const decl of statement.getDeclarations()) {
if (ignoredNames.has(decl.getName())) continue;
names.add(decl.getName());
}
} else if (Node.hasName(statement)) {
if (ignoredNames.has(statement.getName())) continue;
names.add(statement.getName());
}
}
}
}
// deno-lint-ignore no-console
console.log(
"Globals: ",
Array.from(names).sort(),
);

View file

@ -280,6 +280,17 @@ impl Diagnostics {
Diagnostics(diagnostics)
}
pub fn emit_warnings(&mut self) {
self.0.retain(|d| {
if d.category == DiagnosticCategory::Warning {
log::warn!("{}\n", d);
false
} else {
true
}
});
}
/// Return a set of diagnostics where only the values where the predicate
/// returns `true` are included.
pub fn filter<P>(self, predicate: P) -> Self

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -20,14 +20,22 @@ and limitations under the License.
/// Window Async Iterable APIs
/////////////////////////////
interface FileSystemDirectoryHandleAsyncIterator<T> extends AsyncIteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<T>;
}
interface FileSystemDirectoryHandle {
[Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;
entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
keys(): AsyncIterableIterator<string>;
values(): AsyncIterableIterator<FileSystemHandle>;
[Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>;
entries(): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>;
keys(): FileSystemDirectoryHandleAsyncIterator<string>;
values(): FileSystemDirectoryHandleAsyncIterator<FileSystemHandle>;
}
interface ReadableStreamAsyncIterator<T> extends AsyncIteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): ReadableStreamAsyncIterator<T>;
}
interface ReadableStream<R = any> {
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
values(options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
}

1228
cli/tsc/dts/lib.dom.d.ts vendored

File diff suppressed because it is too large Load diff

View file

@ -41,36 +41,36 @@ interface BaseAudioContext {
}
interface CSSKeyframesRule {
[Symbol.iterator](): IterableIterator<CSSKeyframeRule>;
[Symbol.iterator](): ArrayIterator<CSSKeyframeRule>;
}
interface CSSNumericArray {
[Symbol.iterator](): IterableIterator<CSSNumericValue>;
entries(): IterableIterator<[number, CSSNumericValue]>;
keys(): IterableIterator<number>;
values(): IterableIterator<CSSNumericValue>;
[Symbol.iterator](): ArrayIterator<CSSNumericValue>;
entries(): ArrayIterator<[number, CSSNumericValue]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSNumericValue>;
}
interface CSSRuleList {
[Symbol.iterator](): IterableIterator<CSSRule>;
[Symbol.iterator](): ArrayIterator<CSSRule>;
}
interface CSSStyleDeclaration {
[Symbol.iterator](): IterableIterator<string>;
[Symbol.iterator](): ArrayIterator<string>;
}
interface CSSTransformValue {
[Symbol.iterator](): IterableIterator<CSSTransformComponent>;
entries(): IterableIterator<[number, CSSTransformComponent]>;
keys(): IterableIterator<number>;
values(): IterableIterator<CSSTransformComponent>;
[Symbol.iterator](): ArrayIterator<CSSTransformComponent>;
entries(): ArrayIterator<[number, CSSTransformComponent]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSTransformComponent>;
}
interface CSSUnparsedValue {
[Symbol.iterator](): IterableIterator<CSSUnparsedSegment>;
entries(): IterableIterator<[number, CSSUnparsedSegment]>;
keys(): IterableIterator<number>;
values(): IterableIterator<CSSUnparsedSegment>;
[Symbol.iterator](): ArrayIterator<CSSUnparsedSegment>;
entries(): ArrayIterator<[number, CSSUnparsedSegment]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSUnparsedSegment>;
}
interface Cache {
@ -92,72 +92,80 @@ interface CustomStateSet extends Set<string> {
}
interface DOMRectList {
[Symbol.iterator](): IterableIterator<DOMRect>;
[Symbol.iterator](): ArrayIterator<DOMRect>;
}
interface DOMStringList {
[Symbol.iterator](): IterableIterator<string>;
[Symbol.iterator](): ArrayIterator<string>;
}
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
entries(): IterableIterator<[number, string]>;
keys(): IterableIterator<number>;
values(): IterableIterator<string>;
[Symbol.iterator](): ArrayIterator<string>;
entries(): ArrayIterator<[number, string]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<string>;
}
interface DataTransferItemList {
[Symbol.iterator](): IterableIterator<DataTransferItem>;
[Symbol.iterator](): ArrayIterator<DataTransferItem>;
}
interface EventCounts extends ReadonlyMap<string, number> {
}
interface FileList {
[Symbol.iterator](): IterableIterator<File>;
[Symbol.iterator](): ArrayIterator<File>;
}
interface FontFaceSet extends Set<FontFace> {
}
interface FormDataIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): FormDataIterator<T>;
}
interface FormData {
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
[Symbol.iterator](): FormDataIterator<[string, FormDataEntryValue]>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): IterableIterator<[string, FormDataEntryValue]>;
entries(): FormDataIterator<[string, FormDataEntryValue]>;
/** Returns a list of keys in the list. */
keys(): IterableIterator<string>;
keys(): FormDataIterator<string>;
/** Returns a list of values in the list. */
values(): IterableIterator<FormDataEntryValue>;
values(): FormDataIterator<FormDataEntryValue>;
}
interface HTMLAllCollection {
[Symbol.iterator](): IterableIterator<Element>;
[Symbol.iterator](): ArrayIterator<Element>;
}
interface HTMLCollectionBase {
[Symbol.iterator](): IterableIterator<Element>;
[Symbol.iterator](): ArrayIterator<Element>;
}
interface HTMLCollectionOf<T extends Element> {
[Symbol.iterator](): IterableIterator<T>;
[Symbol.iterator](): ArrayIterator<T>;
}
interface HTMLFormElement {
[Symbol.iterator](): IterableIterator<Element>;
[Symbol.iterator](): ArrayIterator<Element>;
}
interface HTMLSelectElement {
[Symbol.iterator](): IterableIterator<HTMLOptionElement>;
[Symbol.iterator](): ArrayIterator<HTMLOptionElement>;
}
interface HeadersIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): HeadersIterator<T>;
}
interface Headers {
[Symbol.iterator](): IterableIterator<[string, string]>;
[Symbol.iterator](): HeadersIterator<[string, string]>;
/** Returns an iterator allowing to go through all key/value pairs contained in this object. */
entries(): IterableIterator<[string, string]>;
entries(): HeadersIterator<[string, string]>;
/** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */
keys(): IterableIterator<string>;
keys(): HeadersIterator<string>;
/** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */
values(): IterableIterator<string>;
values(): HeadersIterator<string>;
}
interface Highlight extends Set<AbstractRange> {
@ -197,32 +205,32 @@ interface MIDIOutput {
interface MIDIOutputMap extends ReadonlyMap<string, MIDIOutput> {
}
interface MediaKeyStatusMapIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): MediaKeyStatusMapIterator<T>;
}
interface MediaKeyStatusMap {
[Symbol.iterator](): IterableIterator<[BufferSource, MediaKeyStatus]>;
entries(): IterableIterator<[BufferSource, MediaKeyStatus]>;
keys(): IterableIterator<BufferSource>;
values(): IterableIterator<MediaKeyStatus>;
[Symbol.iterator](): MediaKeyStatusMapIterator<[BufferSource, MediaKeyStatus]>;
entries(): MediaKeyStatusMapIterator<[BufferSource, MediaKeyStatus]>;
keys(): MediaKeyStatusMapIterator<BufferSource>;
values(): MediaKeyStatusMapIterator<MediaKeyStatus>;
}
interface MediaList {
[Symbol.iterator](): IterableIterator<string>;
[Symbol.iterator](): ArrayIterator<string>;
}
interface MessageEvent<T = any> {
/**
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/initMessageEvent)
*/
/** @deprecated */
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
}
interface MimeTypeArray {
[Symbol.iterator](): IterableIterator<MimeType>;
[Symbol.iterator](): ArrayIterator<MimeType>;
}
interface NamedNodeMap {
[Symbol.iterator](): IterableIterator<Attr>;
[Symbol.iterator](): ArrayIterator<Attr>;
}
interface Navigator {
@ -237,82 +245,86 @@ interface Navigator {
}
interface NodeList {
[Symbol.iterator](): IterableIterator<Node>;
[Symbol.iterator](): ArrayIterator<Node>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): IterableIterator<[number, Node]>;
entries(): ArrayIterator<[number, Node]>;
/** Returns an list of keys in the list. */
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/** Returns an list of values in the list. */
values(): IterableIterator<Node>;
values(): ArrayIterator<Node>;
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>;
[Symbol.iterator](): ArrayIterator<TNode>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): IterableIterator<[number, TNode]>;
entries(): ArrayIterator<[number, TNode]>;
/** Returns an list of keys in the list. */
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/** Returns an list of values in the list. */
values(): IterableIterator<TNode>;
values(): ArrayIterator<TNode>;
}
interface Plugin {
[Symbol.iterator](): IterableIterator<MimeType>;
[Symbol.iterator](): ArrayIterator<MimeType>;
}
interface PluginArray {
[Symbol.iterator](): IterableIterator<Plugin>;
[Symbol.iterator](): ArrayIterator<Plugin>;
}
interface RTCRtpTransceiver {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCRtpTransceiver/setCodecPreferences) */
setCodecPreferences(codecs: Iterable<RTCRtpCodecCapability>): void;
setCodecPreferences(codecs: Iterable<RTCRtpCodec>): void;
}
interface RTCStatsReport extends ReadonlyMap<string, any> {
}
interface SVGLengthList {
[Symbol.iterator](): IterableIterator<SVGLength>;
[Symbol.iterator](): ArrayIterator<SVGLength>;
}
interface SVGNumberList {
[Symbol.iterator](): IterableIterator<SVGNumber>;
[Symbol.iterator](): ArrayIterator<SVGNumber>;
}
interface SVGPointList {
[Symbol.iterator](): IterableIterator<DOMPoint>;
[Symbol.iterator](): ArrayIterator<DOMPoint>;
}
interface SVGStringList {
[Symbol.iterator](): IterableIterator<string>;
[Symbol.iterator](): ArrayIterator<string>;
}
interface SVGTransformList {
[Symbol.iterator](): IterableIterator<SVGTransform>;
[Symbol.iterator](): ArrayIterator<SVGTransform>;
}
interface SourceBufferList {
[Symbol.iterator](): IterableIterator<SourceBuffer>;
[Symbol.iterator](): ArrayIterator<SourceBuffer>;
}
interface SpeechRecognitionResult {
[Symbol.iterator](): IterableIterator<SpeechRecognitionAlternative>;
[Symbol.iterator](): ArrayIterator<SpeechRecognitionAlternative>;
}
interface SpeechRecognitionResultList {
[Symbol.iterator](): IterableIterator<SpeechRecognitionResult>;
[Symbol.iterator](): ArrayIterator<SpeechRecognitionResult>;
}
interface StylePropertyMapReadOnlyIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): StylePropertyMapReadOnlyIterator<T>;
}
interface StylePropertyMapReadOnly {
[Symbol.iterator](): IterableIterator<[string, Iterable<CSSStyleValue>]>;
entries(): IterableIterator<[string, Iterable<CSSStyleValue>]>;
keys(): IterableIterator<string>;
values(): IterableIterator<Iterable<CSSStyleValue>>;
[Symbol.iterator](): StylePropertyMapReadOnlyIterator<[string, Iterable<CSSStyleValue>]>;
entries(): StylePropertyMapReadOnlyIterator<[string, Iterable<CSSStyleValue>]>;
keys(): StylePropertyMapReadOnlyIterator<string>;
values(): StylePropertyMapReadOnlyIterator<Iterable<CSSStyleValue>>;
}
interface StyleSheetList {
[Symbol.iterator](): IterableIterator<CSSStyleSheet>;
[Symbol.iterator](): ArrayIterator<CSSStyleSheet>;
}
interface SubtleCrypto {
@ -331,25 +343,29 @@ interface SubtleCrypto {
}
interface TextTrackCueList {
[Symbol.iterator](): IterableIterator<TextTrackCue>;
[Symbol.iterator](): ArrayIterator<TextTrackCue>;
}
interface TextTrackList {
[Symbol.iterator](): IterableIterator<TextTrack>;
[Symbol.iterator](): ArrayIterator<TextTrack>;
}
interface TouchList {
[Symbol.iterator](): IterableIterator<Touch>;
[Symbol.iterator](): ArrayIterator<Touch>;
}
interface URLSearchParamsIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): URLSearchParamsIterator<T>;
}
interface URLSearchParams {
[Symbol.iterator](): IterableIterator<[string, string]>;
[Symbol.iterator](): URLSearchParamsIterator<[string, string]>;
/** Returns an array of key, value pairs for every entry in the search params. */
entries(): IterableIterator<[string, string]>;
entries(): URLSearchParamsIterator<[string, string]>;
/** Returns a list of keys in the search params. */
keys(): IterableIterator<string>;
keys(): URLSearchParamsIterator<string>;
/** Returns a list of values in the search params. */
values(): IterableIterator<string>;
values(): URLSearchParamsIterator<string>;
}
interface WEBGL_draw_buffers {

View file

@ -18,9 +18,9 @@ and limitations under the License.
/// <reference lib="es2015.iterable" />
interface Generator<T = unknown, TReturn = any, TNext = unknown> extends Iterator<T, TReturn, TNext> {
interface Generator<T = unknown, TReturn = any, TNext = any> extends IteratorObject<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
next(...[value]: [] | [TNext]): IteratorResult<T, TReturn>;
return(value: TReturn): IteratorResult<T, TReturn>;
throw(e: any): IteratorResult<T, TReturn>;
[Symbol.iterator](): Generator<T, TReturn, TNext>;

View file

@ -38,39 +38,59 @@ interface IteratorReturnResult<TReturn> {
type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
interface Iterator<T, TReturn = any, TNext = undefined> {
interface Iterator<T, TReturn = any, TNext = any> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
next(...[value]: [] | [TNext]): IteratorResult<T, TReturn>;
return?(value?: TReturn): IteratorResult<T, TReturn>;
throw?(e?: any): IteratorResult<T, TReturn>;
}
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
interface Iterable<T, TReturn = any, TNext = any> {
[Symbol.iterator](): Iterator<T, TReturn, TNext>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
/**
* Describes a user-defined {@link Iterator} that is also iterable.
*/
interface IterableIterator<T, TReturn = any, TNext = any> extends Iterator<T, TReturn, TNext> {
[Symbol.iterator](): IterableIterator<T, TReturn, TNext>;
}
/**
* Describes an {@link Iterator} produced by the runtime that inherits from the intrinsic `Iterator.prototype`.
*/
interface IteratorObject<T, TReturn = unknown, TNext = unknown> extends Iterator<T, TReturn, TNext> {
[Symbol.iterator](): IteratorObject<T, TReturn, TNext>;
}
/**
* Defines the `TReturn` type used for built-in iterators produced by `Array`, `Map`, `Set`, and others.
* This is `undefined` when `strictBuiltInIteratorReturn` is `true`; otherwise, this is `any`.
*/
type BuiltinIteratorReturn = intrinsic;
interface ArrayIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): ArrayIterator<T>;
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
[Symbol.iterator](): ArrayIterator<T>;
/**
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
entries(): ArrayIterator<[number, T]>;
/**
* Returns an iterable of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an iterable of values in the array
*/
values(): IterableIterator<T>;
values(): ArrayIterator<T>;
}
interface ArrayConstructor {
@ -91,67 +111,71 @@ interface ArrayConstructor {
interface ReadonlyArray<T> {
/** Iterator of values in the array. */
[Symbol.iterator](): IterableIterator<T>;
[Symbol.iterator](): ArrayIterator<T>;
/**
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
entries(): ArrayIterator<[number, T]>;
/**
* Returns an iterable of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an iterable of values in the array
*/
values(): IterableIterator<T>;
values(): ArrayIterator<T>;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
[Symbol.iterator](): ArrayIterator<any>;
}
interface MapIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): MapIterator<T>;
}
interface Map<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): IterableIterator<[K, V]>;
[Symbol.iterator](): MapIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): IterableIterator<[K, V]>;
entries(): MapIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): IterableIterator<K>;
keys(): MapIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): IterableIterator<V>;
values(): MapIterator<V>;
}
interface ReadonlyMap<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): IterableIterator<[K, V]>;
[Symbol.iterator](): MapIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): IterableIterator<[K, V]>;
entries(): MapIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): IterableIterator<K>;
keys(): MapIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): IterableIterator<V>;
values(): MapIterator<V>;
}
interface MapConstructor {
@ -165,42 +189,46 @@ interface WeakMapConstructor {
new <K extends WeakKey, V>(iterable: Iterable<readonly [K, V]>): WeakMap<K, V>;
}
interface SetIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): SetIterator<T>;
}
interface Set<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): IterableIterator<T>;
[Symbol.iterator](): SetIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
entries(): SetIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set.
*/
keys(): IterableIterator<T>;
keys(): SetIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
values(): SetIterator<T>;
}
interface ReadonlySet<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): IterableIterator<T>;
[Symbol.iterator](): SetIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
entries(): SetIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set.
*/
keys(): IterableIterator<T>;
keys(): SetIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
values(): SetIterator<T>;
}
interface SetConstructor {
@ -233,25 +261,29 @@ interface PromiseConstructor {
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
}
interface StringIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): StringIterator<T>;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
[Symbol.iterator](): StringIterator<string>;
}
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Int8ArrayConstructor {
@ -267,19 +299,19 @@ interface Int8ArrayConstructor {
}
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Uint8ArrayConstructor {
@ -295,21 +327,21 @@ interface Uint8ArrayConstructor {
}
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Uint8ClampedArrayConstructor {
@ -325,21 +357,21 @@ interface Uint8ClampedArrayConstructor {
}
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Int16ArrayConstructor {
@ -355,19 +387,19 @@ interface Int16ArrayConstructor {
}
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Uint16ArrayConstructor {
@ -383,19 +415,19 @@ interface Uint16ArrayConstructor {
}
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Int32ArrayConstructor {
@ -411,19 +443,19 @@ interface Int32ArrayConstructor {
}
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Uint32ArrayConstructor {
@ -439,19 +471,19 @@ interface Uint32ArrayConstructor {
}
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Float32ArrayConstructor {
@ -467,19 +499,19 @@ interface Float32ArrayConstructor {
}
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
values(): ArrayIterator<number>;
}
interface Float64ArrayConstructor {

View file

@ -18,25 +18,25 @@ and limitations under the License.
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
* Returns an array of values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T; } | ArrayLike<T>): T[];
/**
* Returns an array of values of the enumerable properties of an object
* Returns an array of values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values(o: {}): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* Returns an array of key/values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T; } | ArrayLike<T>): [string, T][];
/**
* Returns an array of key/values of the enumerable properties of an object
* Returns an array of key/values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries(o: {}): [string, any][];

View file

@ -18,9 +18,9 @@ and limitations under the License.
/// <reference lib="es2018.asynciterable" />
interface AsyncGenerator<T = unknown, TReturn = any, TNext = unknown> extends AsyncIterator<T, TReturn, TNext> {
interface AsyncGenerator<T = unknown, TReturn = any, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
next(...[value]: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return(value: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw(e: any): Promise<IteratorResult<T, TReturn>>;
[Symbol.asyncIterator](): AsyncGenerator<T, TReturn, TNext>;

View file

@ -27,17 +27,27 @@ interface SymbolConstructor {
readonly asyncIterator: unique symbol;
}
interface AsyncIterator<T, TReturn = any, TNext = undefined> {
interface AsyncIterator<T, TReturn = any, TNext = any> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
next(...[value]: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return?(value?: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw?(e?: any): Promise<IteratorResult<T, TReturn>>;
}
interface AsyncIterable<T> {
[Symbol.asyncIterator](): AsyncIterator<T>;
interface AsyncIterable<T, TReturn = any, TNext = any> {
[Symbol.asyncIterator](): AsyncIterator<T, TReturn, TNext>;
}
interface AsyncIterableIterator<T> extends AsyncIterator<T> {
[Symbol.asyncIterator](): AsyncIterableIterator<T>;
/**
* Describes a user-defined {@link AsyncIterator} that is also async iterable.
*/
interface AsyncIterableIterator<T, TReturn = any, TNext = any> extends AsyncIterator<T, TReturn, TNext> {
[Symbol.asyncIterator](): AsyncIterableIterator<T, TReturn, TNext>;
}
/**
* Describes an {@link AsyncIterator} produced by the runtime that inherits from the intrinsic `AsyncIterator.prototype`.
*/
interface AsyncIteratorObject<T, TReturn = unknown, TNext = unknown> extends AsyncIterator<T, TReturn, TNext> {
[Symbol.asyncIterator](): AsyncIteratorObject<T, TReturn, TNext>;
}

View file

@ -171,7 +171,7 @@ interface BigInt64Array {
copyWithin(target: number, start: number, end?: number): this;
/** Yields index, value pairs for every entry in the array. */
entries(): IterableIterator<[number, bigint]>;
entries(): ArrayIterator<[number, bigint]>;
/**
* Determines whether all the members of an array satisfy the specified test.
@ -256,7 +256,7 @@ interface BigInt64Array {
join(separator?: string): string;
/** Yields each index in the array. */
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
@ -378,9 +378,9 @@ interface BigInt64Array {
valueOf(): BigInt64Array;
/** Yields each value in the array. */
values(): IterableIterator<bigint>;
values(): ArrayIterator<bigint>;
[Symbol.iterator](): IterableIterator<bigint>;
[Symbol.iterator](): ArrayIterator<bigint>;
readonly [Symbol.toStringTag]: "BigInt64Array";
@ -443,7 +443,7 @@ interface BigUint64Array {
copyWithin(target: number, start: number, end?: number): this;
/** Yields index, value pairs for every entry in the array. */
entries(): IterableIterator<[number, bigint]>;
entries(): ArrayIterator<[number, bigint]>;
/**
* Determines whether all the members of an array satisfy the specified test.
@ -528,7 +528,7 @@ interface BigUint64Array {
join(separator?: string): string;
/** Yields each index in the array. */
keys(): IterableIterator<number>;
keys(): ArrayIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
@ -650,9 +650,9 @@ interface BigUint64Array {
valueOf(): BigUint64Array;
/** Yields each value in the array. */
values(): IterableIterator<bigint>;
values(): ArrayIterator<bigint>;
[Symbol.iterator](): IterableIterator<bigint>;
[Symbol.iterator](): ArrayIterator<bigint>;
readonly [Symbol.toStringTag]: "BigUint64Array";

View file

@ -16,7 +16,7 @@ and limitations under the License.
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
/// <reference lib="es2020.symbol.wellknown" />
interface String {
/**
@ -24,7 +24,7 @@ interface String {
* containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
matchAll(regexp: RegExp): IterableIterator<RegExpExecArray>;
matchAll(regexp: RegExp): RegExpStringIterator<RegExpExecArray>;
/** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */
toLocaleLowerCase(locales?: Intl.LocalesArgument): string;

View file

@ -27,11 +27,15 @@ interface SymbolConstructor {
readonly matchAll: unique symbol;
}
interface RegExpStringIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): RegExpStringIterator<T>;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an iterable of matches
* containing the results of that search.
* @param string A string to search within.
*/
[Symbol.matchAll](str: string): IterableIterator<RegExpMatchArray>;
[Symbol.matchAll](str: string): RegExpStringIterator<RegExpMatchArray>;
}

View file

@ -46,6 +46,10 @@ declare namespace Intl {
granularity: "grapheme" | "word" | "sentence";
}
interface SegmentIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): SegmentIterator<T>;
}
interface Segments {
/**
* Returns an object describing the segment in the original string that includes the code unit at a specified index.
@ -55,7 +59,7 @@ declare namespace Intl {
containing(codeUnitIndex?: number): SegmentData;
/** Returns an iterator to iterate over the segments. */
[Symbol.iterator](): IterableIterator<SegmentData>;
[Symbol.iterator](): SegmentIterator<SegmentData>;
}
interface SegmentData {

View file

@ -203,7 +203,7 @@ interface Int8Array {
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint8Array;
toReversed(): Int8Array;
/**
* Copies and sorts the array.
@ -211,11 +211,11 @@ interface Int8Array {
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint8Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
* const myNums = Int8Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint8Array;
toSorted(compareFn?: (a: number, b: number) => number): Int8Array;
/**
* Copies the array and inserts the given number at the provided index.
@ -224,7 +224,7 @@ interface Int8Array {
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint8Array;
with(index: number, value: number): Int8Array;
}
interface Uint8Array {

View file

@ -26,3 +26,4 @@ and limitations under the License.
/// <reference lib="esnext.array" />
/// <reference lib="esnext.regexp" />
/// <reference lib="esnext.string" />
/// <reference lib="esnext.iterator" />

View file

@ -17,6 +17,8 @@ and limitations under the License.
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.iterable" />
/// <reference lib="es2018.asynciterable" />
interface SymbolConstructor {
/**
@ -183,3 +185,9 @@ interface AsyncDisposableStackConstructor {
readonly prototype: AsyncDisposableStack;
}
declare var AsyncDisposableStack: AsyncDisposableStackConstructor;
interface IteratorObject<T, TReturn, TNext> extends Disposable {
}
interface AsyncIteratorObject<T, TReturn, TNext> extends AsyncDisposable {
}

148
cli/tsc/dts/lib.esnext.iterator.d.ts vendored Normal file
View file

@ -0,0 +1,148 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
// NOTE: This is specified as what is essentially an unreachable module. All actual global declarations can be found
// in the `declare global` section, below. This is necessary as there is currently no way to declare an `abstract`
// member without declaring a `class`, but declaring `class Iterator<T>` globally would conflict with TypeScript's
// general purpose `Iterator<T>` interface.
export {};
// Abstract type that allows us to mark `next` as `abstract`
declare abstract class Iterator<T, TResult = undefined, TNext = unknown> { // eslint-disable-line @typescript-eslint/no-unsafe-declaration-merging
abstract next(value?: TNext): IteratorResult<T, TResult>;
}
// Merge all members of `IteratorObject<T>` into `Iterator<T>`
interface Iterator<T, TResult, TNext> extends globalThis.IteratorObject<T, TResult, TNext> {}
// Capture the `Iterator` constructor in a type we can use in the `extends` clause of `IteratorConstructor`.
type IteratorObjectConstructor = typeof Iterator;
declare global {
// Global `IteratorObject<T, TReturn, TNext>` interface that can be augmented by polyfills
interface IteratorObject<T, TReturn, TNext> {
/**
* Returns this iterator.
*/
[Symbol.iterator](): IteratorObject<T, TReturn, TNext>;
/**
* Creates an iterator whose values are the result of applying the callback to the values from this iterator.
* @param callbackfn A function that accepts up to two arguments to be used to transform values from the underlying iterator.
*/
map<U>(callbackfn: (value: T, index: number) => U): IteratorObject<U, undefined, unknown>;
/**
* Creates an iterator whose values are those from this iterator for which the provided predicate returns true.
* @param predicate A function that accepts up to two arguments to be used to test values from the underlying iterator.
*/
filter<S extends T>(predicate: (value: T, index: number) => value is S): IteratorObject<S, undefined, unknown>;
/**
* Creates an iterator whose values are those from this iterator for which the provided predicate returns true.
* @param predicate A function that accepts up to two arguments to be used to test values from the underlying iterator.
*/
filter(predicate: (value: T, index: number) => unknown): IteratorObject<T, undefined, unknown>;
/**
* Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached.
* @param limit The maximum number of values to yield.
*/
take(limit: number): IteratorObject<T, undefined, unknown>;
/**
* Creates an iterator whose values are the values from this iterator after skipping the provided count.
* @param count The number of values to drop.
*/
drop(count: number): IteratorObject<T, undefined, unknown>;
/**
* Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables.
* @param callback A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result.
*/
flatMap<U>(callback: (value: T, index: number) => Iterator<U, unknown, undefined> | Iterable<U, unknown, undefined>): IteratorObject<U, undefined, unknown>;
/**
* Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator.
*/
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T;
/**
* Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U;
/**
* Creates a new array from the values yielded by this iterator.
*/
toArray(): T[];
/**
* Performs the specified action for each element in the iterator.
* @param callbackfn A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator.
*/
forEach(callbackfn: (value: T, index: number) => void): void;
/**
* Determines whether the specified callback function returns true for any element of this iterator.
* @param predicate A function that accepts up to two arguments. The some method calls
* the predicate function for each element in this iterator until the predicate returns a value
* true, or until the end of the iterator.
*/
some(predicate: (value: T, index: number) => unknown): boolean;
/**
* Determines whether all the members of this iterator satisfy the specified test.
* @param predicate A function that accepts up to two arguments. The every method calls
* the predicate function for each element in this iterator until the predicate returns
* false, or until the end of this iterator.
*/
every(predicate: (value: T, index: number) => unknown): boolean;
/**
* Returns the value of the first element in this iterator where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of this iterator, in
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
*/
find<S extends T>(predicate: (value: T, index: number) => value is S): S | undefined;
find(predicate: (value: T, index: number) => unknown): T | undefined;
readonly [Symbol.toStringTag]: string;
}
// Global `IteratorConstructor` interface that can be augmented by polyfills
interface IteratorConstructor extends IteratorObjectConstructor {
/**
* Creates a native iterator from an iterator or iterable object.
* Returns its input if the input already inherits from the built-in Iterator class.
* @param value An iterator or iterable object to convert a native iterator.
*/
from<T>(value: Iterator<T, unknown, undefined> | Iterable<T, unknown, undefined>): IteratorObject<T, undefined, unknown>;
}
var Iterator: IteratorConstructor;
}

View file

@ -20,14 +20,22 @@ and limitations under the License.
/// Worker Async Iterable APIs
/////////////////////////////
interface FileSystemDirectoryHandleAsyncIterator<T> extends AsyncIteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<T>;
}
interface FileSystemDirectoryHandle {
[Symbol.asyncIterator](): AsyncIterableIterator<[string, FileSystemHandle]>;
entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
keys(): AsyncIterableIterator<string>;
values(): AsyncIterableIterator<FileSystemHandle>;
[Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>;
entries(): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>;
keys(): FileSystemDirectoryHandleAsyncIterator<string>;
values(): FileSystemDirectoryHandleAsyncIterator<FileSystemHandle>;
}
interface ReadableStreamAsyncIterator<T> extends AsyncIteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): ReadableStreamAsyncIterator<T>;
}
interface ReadableStream<R = any> {
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
values(options?: ReadableStreamIteratorOptions): AsyncIterableIterator<R>;
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
}

View file

@ -340,10 +340,6 @@ interface ImageEncodeOptions {
type?: string;
}
interface ImportMeta {
url: string;
}
interface JsonWebKey {
alg?: string;
crv?: string;
@ -414,6 +410,10 @@ interface MediaEncodingConfiguration extends MediaConfiguration {
type: MediaEncodingType;
}
interface MediaStreamTrackProcessorInit {
maxBufferSize?: number;
}
interface MessageEventInit<T = any> extends EventInit {
data?: T;
lastEventId?: string;
@ -717,16 +717,11 @@ interface TextEncoderEncodeIntoResult {
written: number;
}
interface TransformerCancelCallback {
(reason: any): void | PromiseLike<void>;
}
interface Transformer<I = any, O = any> {
flush?: TransformerFlushCallback<O>;
readableType?: undefined;
start?: TransformerStartCallback<O>;
transform?: TransformerTransformCallback<I, O>;
cancel?: TransformerCancelCallback;
writableType?: undefined;
}
@ -1676,6 +1671,8 @@ interface CanvasShadowStyles {
}
interface CanvasState {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/isContextLost) */
isContextLost(): boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/reset) */
reset(): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/restore) */
@ -1812,8 +1809,6 @@ declare var CloseEvent: {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */
interface CompressionStream extends GenericTransformStream {
readonly readable: ReadableStream<Uint8Array>;
readonly writable: WritableStream<BufferSource>;
}
declare var CompressionStream: {
@ -2011,9 +2006,7 @@ interface DOMMatrix extends DOMMatrixReadOnly {
rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;
rotateFromVectorSelf(x?: number, y?: number): DOMMatrix;
rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/scale3dSelf) */
scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix/scaleSelf) */
scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
skewXSelf(sx?: number): DOMMatrix;
skewYSelf(sy?: number): DOMMatrix;
@ -2030,88 +2023,48 @@ declare var DOMMatrix: {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly) */
interface DOMMatrixReadOnly {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/a) */
readonly a: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/b) */
readonly b: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/c) */
readonly c: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/d) */
readonly d: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/e) */
readonly e: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/f) */
readonly f: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/is2D) */
readonly is2D: boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/isIdentity) */
readonly isIdentity: boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m11) */
readonly m11: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m12) */
readonly m12: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m13) */
readonly m13: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m14) */
readonly m14: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m21) */
readonly m21: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m22) */
readonly m22: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m23) */
readonly m23: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m24) */
readonly m24: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m31) */
readonly m31: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m32) */
readonly m32: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m33) */
readonly m33: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m34) */
readonly m34: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m41) */
readonly m41: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m42) */
readonly m42: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m43) */
readonly m43: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/m44) */
readonly m44: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/flipX) */
flipX(): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/flipY) */
flipY(): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/inverse) */
inverse(): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/multiply) */
multiply(other?: DOMMatrixInit): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/rotate) */
rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/rotateAxisAngle) */
rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/rotateFromVector) */
rotateFromVector(x?: number, y?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/scale) */
scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/scale3d) */
scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;
/**
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/scaleNonUniform)
*/
/** @deprecated */
scaleNonUniform(scaleX?: number, scaleY?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/skewX) */
skewX(sx?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/skewY) */
skewY(sy?: number): DOMMatrix;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/toFloat32Array) */
toFloat32Array(): Float32Array;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/toFloat64Array) */
toFloat64Array(): Float64Array;
toJSON(): any;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/transformPoint) */
transformPoint(point?: DOMPointInit): DOMPoint;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/translate) */
translate(tx?: number, ty?: number, tz?: number): DOMMatrix;
@ -2154,7 +2107,6 @@ interface DOMPointReadOnly {
readonly y: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/z) */
readonly z: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/matrixTransform) */
matrixTransform(matrix?: DOMMatrixInit): DOMPoint;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMPointReadOnly/toJSON) */
toJSON(): any;
@ -2169,15 +2121,10 @@ declare var DOMPointReadOnly: {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad) */
interface DOMQuad {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p1) */
readonly p1: DOMPoint;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p2) */
readonly p2: DOMPoint;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p3) */
readonly p3: DOMPoint;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/p4) */
readonly p4: DOMPoint;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMQuad/getBounds) */
getBounds(): DOMRect;
toJSON(): any;
}
@ -2200,6 +2147,7 @@ interface DOMRect extends DOMRectReadOnly {
declare var DOMRect: {
prototype: DOMRect;
new(x?: number, y?: number, width?: number, height?: number): DOMRect;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMRect/fromRect_static) */
fromRect(other?: DOMRectInit): DOMRect;
};
@ -2265,8 +2213,6 @@ declare var DOMStringList: {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */
interface DecompressionStream extends GenericTransformStream {
readonly readable: ReadableStream<Uint8Array>;
readonly writable: WritableStream<BufferSource>;
}
declare var DecompressionStream: {
@ -2427,15 +2373,10 @@ declare var EncodedVideoChunk: {
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)
*/
interface ErrorEvent extends Event {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */
readonly colno: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */
readonly error: any;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */
readonly filename: string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */
readonly lineno: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */
readonly message: string;
}
@ -3091,7 +3032,9 @@ declare var FormData: {
};
interface GenericTransformStream {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream/readable) */
readonly readable: ReadableStream;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream/writable) */
readonly writable: WritableStream;
}
@ -3750,7 +3693,7 @@ interface IDBTransaction extends EventTarget {
/**
* Returns a list of the names of object stores in the transaction's scope. For an upgrade transaction this is all object stores in the database.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/objectStoreNames)
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/ObjectStoreNames)
*/
readonly objectStoreNames: DOMStringList;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/abort_event) */
@ -3877,6 +3820,11 @@ declare var ImageData: {
new(data: Uint8ClampedArray, sw: number, sh?: number, settings?: ImageDataSettings): ImageData;
};
interface ImportMeta {
url: string;
resolve(specifier: string): string;
}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/KHR_parallel_shader_compile) */
interface KHR_parallel_shader_compile {
readonly COMPLETION_STATUS_KHR: 0x91B1;
@ -3930,6 +3878,26 @@ declare var MediaCapabilities: {
new(): MediaCapabilities;
};
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaSourceHandle) */
interface MediaSourceHandle {
}
declare var MediaSourceHandle: {
prototype: MediaSourceHandle;
new(): MediaSourceHandle;
};
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaStreamTrackProcessor) */
interface MediaStreamTrackProcessor {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaStreamTrackProcessor/readable) */
readonly readable: ReadableStream;
}
declare var MediaStreamTrackProcessor: {
prototype: MediaStreamTrackProcessor;
new(init: MediaStreamTrackProcessorInit): MediaStreamTrackProcessor;
};
/**
* This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties.
*
@ -3991,11 +3959,7 @@ interface MessageEvent<T = any> extends Event {
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)
*/
readonly source: MessageEventSource | null;
/**
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/initMessageEvent)
*/
/** @deprecated */
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: MessagePort[]): void;
}
@ -4327,7 +4291,9 @@ interface OffscreenCanvas extends EventTarget {
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvas/height)
*/
height: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvas/contextlost_event) */
oncontextlost: ((this: OffscreenCanvas, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvas/contextrestored_event) */
oncontextrestored: ((this: OffscreenCanvas, ev: Event) => any) | null;
/**
* These attributes return the dimensions of the OffscreenCanvas object's bitmap.
@ -4379,8 +4345,6 @@ declare var OffscreenCanvas: {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvasRenderingContext2D) */
interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform {
readonly canvas: OffscreenCanvas;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvasRenderingContext2D/commit) */
commit(): void;
}
declare var OffscreenCanvasRenderingContext2D: {
@ -4885,24 +4849,19 @@ declare var ReadableStream: {
new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream<Uint8Array>;
new<R = any>(underlyingSource: UnderlyingDefaultSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
new<R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
from<R>(asyncIterable: AsyncIterable<R> | Iterable<R | PromiseLike<R>>): ReadableStream<R>;
};
interface ReadableStreamBYOBReaderReadOptions {
min?: number;
}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */
interface ReadableStreamBYOBReader extends ReadableStreamGenericReader {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */
read<T extends ArrayBufferView>(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise<ReadableStreamReadResult<T>>;
read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */
releaseLock(): void;
}
declare var ReadableStreamBYOBReader: {
prototype: ReadableStreamBYOBReader;
new(stream: ReadableStream<Uint8Array>): ReadableStreamBYOBReader;
new(stream: ReadableStream): ReadableStreamBYOBReader;
};
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */
@ -4975,6 +4934,7 @@ declare var Report: {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReportBody) */
interface ReportBody {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReportBody/toJSON) */
toJSON(): any;
}
@ -5034,11 +4994,7 @@ interface Request extends Body {
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)
*/
readonly integrity: string;
/**
* Returns a boolean indicating whether or not request can outlive the global in which it was created.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)
*/
/** Returns a boolean indicating whether or not request can outlive the global in which it was created. */
readonly keepalive: boolean;
/**
* Returns request's HTTP method, which is "GET" by default.
@ -5802,6 +5758,7 @@ interface VideoDecoderEventMap {
interface VideoDecoder extends EventTarget {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoDecoder/decodeQueueSize) */
readonly decodeQueueSize: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoDecoder/dequeue_event) */
ondequeue: ((this: VideoDecoder, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoDecoder/state) */
readonly state: CodecState;
@ -5824,6 +5781,7 @@ interface VideoDecoder extends EventTarget {
declare var VideoDecoder: {
prototype: VideoDecoder;
new(init: VideoDecoderInit): VideoDecoder;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoDecoder/isConfigSupported_static) */
isConfigSupported(config: VideoDecoderConfig): Promise<VideoDecoderSupport>;
};
@ -5839,6 +5797,7 @@ interface VideoEncoderEventMap {
interface VideoEncoder extends EventTarget {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/encodeQueueSize) */
readonly encodeQueueSize: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/dequeue_event) */
ondequeue: ((this: VideoEncoder, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/state) */
readonly state: CodecState;
@ -5848,6 +5807,7 @@ interface VideoEncoder extends EventTarget {
configure(config: VideoEncoderConfig): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/encode) */
encode(frame: VideoFrame, options?: VideoEncoderEncodeOptions): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/flush) */
flush(): Promise<void>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/reset) */
reset(): void;
@ -5860,6 +5820,7 @@ interface VideoEncoder extends EventTarget {
declare var VideoEncoder: {
prototype: VideoEncoder;
new(init: VideoEncoderInit): VideoEncoder;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoEncoder/isConfigSupported_static) */
isConfigSupported(config: VideoEncoderConfig): Promise<VideoEncoderSupport>;
};
@ -5891,6 +5852,7 @@ interface VideoFrame {
clone(): VideoFrame;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoFrame/close) */
close(): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/VideoFrame/copyTo) */
copyTo(destination: AllowSharedBufferSource, options?: VideoFrameCopyToOptions): Promise<PlaneLayout[]>;
}
@ -6668,7 +6630,7 @@ interface WebGL2RenderingContextBase {
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: number): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clientWaitSync) */
clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64): GLenum;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/compressedTexImage3D) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/compressedTexImage2D) */
compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr): void;
compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: number, srcLengthOverride?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/compressedTexSubImage3D) */
@ -7549,6 +7511,7 @@ declare var WebGLRenderingContext: {
};
interface WebGLRenderingContextBase {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/drawingBufferColorSpace) */
drawingBufferColorSpace: PredefinedColorSpace;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/drawingBufferHeight) */
readonly drawingBufferHeight: GLsizei;
@ -8258,7 +8221,7 @@ declare var WebGLVertexArrayObject: {
new(): WebGLVertexArrayObject;
};
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLVertexArrayObjectOES) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLVertexArrayObject) */
interface WebGLVertexArrayObjectOES {
}
@ -8469,24 +8432,24 @@ interface WindowOrWorkerGlobalScope {
/**
* Available only in secure contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/caches)
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/caches)
*/
readonly caches: CacheStorage;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/crossOriginIsolated) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/crossOriginIsolated) */
readonly crossOriginIsolated: boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/crypto_property) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/crypto) */
readonly crypto: Crypto;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/indexedDB) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/indexedDB) */
readonly indexedDB: IDBFactory;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/isSecureContext) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/isSecureContext) */
readonly isSecureContext: boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/origin) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/origin) */
readonly origin: string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/performance_property) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/performance) */
readonly performance: Performance;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */
atob(data: string): string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */
btoa(data: string): string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */
clearInterval(id: number | undefined): void;
@ -8583,7 +8546,9 @@ interface WorkerGlobalScope extends EventTarget, FontFaceSource, WindowOrWorkerG
onoffline: ((this: WorkerGlobalScope, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerGlobalScope/online_event) */
ononline: ((this: WorkerGlobalScope, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerGlobalScope/rejectionhandled_event) */
onrejectionhandled: ((this: WorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerGlobalScope/unhandledrejection_event) */
onunhandledrejection: ((this: WorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
/**
* Returns workerGlobal.
@ -8641,7 +8606,7 @@ declare var WorkerLocation: {
};
/**
* A subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling globalThis.self.navigator.
* A subset of the Navigator interface allowed to be accessed from a Worker. Such an object is initialized for each worker and is available via the WorkerGlobalScope.navigator property obtained by calling window.self.navigator.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerNavigator)
*/
@ -8917,7 +8882,7 @@ interface Console {
clear(): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */
count(label?: string): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countreset_static) */
countReset(label?: string): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */
debug(...data: any[]): void;
@ -8929,9 +8894,9 @@ interface Console {
error(...data: any[]): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */
group(...data: any[]): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupcollapsed_static) */
groupCollapsed(...data: any[]): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupend_static) */
groupEnd(): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */
info(...data: any[]): void;
@ -8941,9 +8906,9 @@ interface Console {
table(tabularData?: any, properties?: string[]): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */
time(label?: string): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeend_static) */
timeEnd(label?: string): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timelog_static) */
timeLog(label?: string, ...data: any[]): void;
timeStamp(label?: string): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */
@ -8966,9 +8931,7 @@ declare namespace WebAssembly {
/** [MDN Reference](https://developer.mozilla.org/docs/WebAssembly/JavaScript_interface/Global) */
interface Global<T extends ValueType = ValueType> {
/** [MDN Reference](https://developer.mozilla.org/docs/WebAssembly/JavaScript_interface/Global/value) */
value: ValueTypeMap[T];
/** [MDN Reference](https://developer.mozilla.org/docs/WebAssembly/JavaScript_interface/Global/valueOf) */
valueOf(): ValueTypeMap[T];
}
@ -9246,7 +9209,9 @@ declare var onlanguagechange: ((this: DedicatedWorkerGlobalScope, ev: Event) =>
declare var onoffline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerGlobalScope/online_event) */
declare var ononline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerGlobalScope/rejectionhandled_event) */
declare var onrejectionhandled: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WorkerGlobalScope/unhandledrejection_event) */
declare var onunhandledrejection: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
/**
* Returns workerGlobal.
@ -9271,24 +9236,24 @@ declare var fonts: FontFaceSet;
/**
* Available only in secure contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/caches)
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/caches)
*/
declare var caches: CacheStorage;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/crossOriginIsolated) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/crossOriginIsolated) */
declare var crossOriginIsolated: boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/crypto_property) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/crypto) */
declare var crypto: Crypto;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/indexedDB) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/indexedDB) */
declare var indexedDB: IDBFactory;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/isSecureContext) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/isSecureContext) */
declare var isSecureContext: boolean;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/origin) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/origin) */
declare var origin: string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/performance_property) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/performance) */
declare var performance: Performance;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/atob) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */
declare function atob(data: string): string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/btoa) */
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */
declare function btoa(data: string): string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/clearInterval) */
declare function clearInterval(id: number | undefined): void;
@ -9365,7 +9330,7 @@ type ReportList = Report[];
type RequestInfo = Request | string;
type TexImageSource = ImageBitmap | ImageData | OffscreenCanvas | VideoFrame;
type TimerHandler = string | Function;
type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | ReadableStream | WritableStream | TransformStream | VideoFrame | ArrayBuffer;
type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | MediaSourceHandle | ReadableStream | WritableStream | TransformStream | VideoFrame | ArrayBuffer;
type Uint32List = Uint32Array | GLuint[];
type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string;
type AlphaOption = "discard" | "keep";

View file

@ -26,24 +26,24 @@ interface AbortSignal {
}
interface CSSNumericArray {
[Symbol.iterator](): IterableIterator<CSSNumericValue>;
entries(): IterableIterator<[number, CSSNumericValue]>;
keys(): IterableIterator<number>;
values(): IterableIterator<CSSNumericValue>;
[Symbol.iterator](): ArrayIterator<CSSNumericValue>;
entries(): ArrayIterator<[number, CSSNumericValue]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSNumericValue>;
}
interface CSSTransformValue {
[Symbol.iterator](): IterableIterator<CSSTransformComponent>;
entries(): IterableIterator<[number, CSSTransformComponent]>;
keys(): IterableIterator<number>;
values(): IterableIterator<CSSTransformComponent>;
[Symbol.iterator](): ArrayIterator<CSSTransformComponent>;
entries(): ArrayIterator<[number, CSSTransformComponent]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSTransformComponent>;
}
interface CSSUnparsedValue {
[Symbol.iterator](): IterableIterator<CSSUnparsedSegment>;
entries(): IterableIterator<[number, CSSUnparsedSegment]>;
keys(): IterableIterator<number>;
values(): IterableIterator<CSSUnparsedSegment>;
[Symbol.iterator](): ArrayIterator<CSSUnparsedSegment>;
entries(): ArrayIterator<[number, CSSUnparsedSegment]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSUnparsedSegment>;
}
interface Cache {
@ -62,34 +62,42 @@ interface CanvasPathDrawingStyles {
}
interface DOMStringList {
[Symbol.iterator](): IterableIterator<string>;
[Symbol.iterator](): ArrayIterator<string>;
}
interface FileList {
[Symbol.iterator](): IterableIterator<File>;
[Symbol.iterator](): ArrayIterator<File>;
}
interface FontFaceSet extends Set<FontFace> {
}
interface FormDataIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): FormDataIterator<T>;
}
interface FormData {
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
[Symbol.iterator](): FormDataIterator<[string, FormDataEntryValue]>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): IterableIterator<[string, FormDataEntryValue]>;
entries(): FormDataIterator<[string, FormDataEntryValue]>;
/** Returns a list of keys in the list. */
keys(): IterableIterator<string>;
keys(): FormDataIterator<string>;
/** Returns a list of values in the list. */
values(): IterableIterator<FormDataEntryValue>;
values(): FormDataIterator<FormDataEntryValue>;
}
interface HeadersIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): HeadersIterator<T>;
}
interface Headers {
[Symbol.iterator](): IterableIterator<[string, string]>;
[Symbol.iterator](): HeadersIterator<[string, string]>;
/** Returns an iterator allowing to go through all key/value pairs contained in this object. */
entries(): IterableIterator<[string, string]>;
entries(): HeadersIterator<[string, string]>;
/** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */
keys(): IterableIterator<string>;
keys(): HeadersIterator<string>;
/** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */
values(): IterableIterator<string>;
values(): HeadersIterator<string>;
}
interface IDBDatabase {
@ -113,19 +121,19 @@ interface IDBObjectStore {
}
interface MessageEvent<T = any> {
/**
* @deprecated
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/initMessageEvent)
*/
/** @deprecated */
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
}
interface StylePropertyMapReadOnlyIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): StylePropertyMapReadOnlyIterator<T>;
}
interface StylePropertyMapReadOnly {
[Symbol.iterator](): IterableIterator<[string, Iterable<CSSStyleValue>]>;
entries(): IterableIterator<[string, Iterable<CSSStyleValue>]>;
keys(): IterableIterator<string>;
values(): IterableIterator<Iterable<CSSStyleValue>>;
[Symbol.iterator](): StylePropertyMapReadOnlyIterator<[string, Iterable<CSSStyleValue>]>;
entries(): StylePropertyMapReadOnlyIterator<[string, Iterable<CSSStyleValue>]>;
keys(): StylePropertyMapReadOnlyIterator<string>;
values(): StylePropertyMapReadOnlyIterator<Iterable<CSSStyleValue>>;
}
interface SubtleCrypto {
@ -143,14 +151,18 @@ interface SubtleCrypto {
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
}
interface URLSearchParamsIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): URLSearchParamsIterator<T>;
}
interface URLSearchParams {
[Symbol.iterator](): IterableIterator<[string, string]>;
[Symbol.iterator](): URLSearchParamsIterator<[string, string]>;
/** Returns an array of key, value pairs for every entry in the search params. */
entries(): IterableIterator<[string, string]>;
entries(): URLSearchParamsIterator<[string, string]>;
/** Returns a list of keys in the search params. */
keys(): IterableIterator<string>;
keys(): URLSearchParamsIterator<string>;
/** Returns a list of values in the search params. */
values(): IterableIterator<string>;
values(): URLSearchParamsIterator<string>;
}
interface WEBGL_draw_buffers {

View file

@ -214,6 +214,22 @@ declare namespace ts {
* The time spent creating or updating the auto-import program, in milliseconds.
*/
createAutoImportProviderProgramDurationMs?: number;
/**
* The time spent computing diagnostics, in milliseconds.
*/
diagnosticsDuration?: FileDiagnosticPerformanceData[];
}
/**
* Time spent computing each kind of diagnostics, in milliseconds.
*/
export type DiagnosticPerformanceData = {
[Kind in DiagnosticEventKind]?: number;
};
export interface FileDiagnosticPerformanceData extends DiagnosticPerformanceData {
/**
* The file for which the performance data is reported.
*/
file: string;
}
/**
* Arguments for FileRequest messages.
@ -584,23 +600,7 @@ declare namespace ts {
}
export interface ApplyCodeActionCommandResponse extends Response {
}
export interface FileRangeRequestArgs extends FileRequestArgs {
/**
* The line number for the request (1-based).
*/
startLine: number;
/**
* The character offset (on the line) for the request (1-based).
*/
startOffset: number;
/**
* The line number for the request (1-based).
*/
endLine: number;
/**
* The character offset (on the line) for the request (1-based).
*/
endOffset: number;
export interface FileRangeRequestArgs extends FileRequestArgs, FileRange {
}
/**
* Instances of this interface specify errorcodes on a specific location in a sourcefile.
@ -1866,7 +1866,7 @@ declare namespace ts {
* List of file names for which to compute compiler errors.
* The files will be checked in list order.
*/
files: string[];
files: (string | FileRangesRequestArgs)[];
/**
* Delay in milliseconds to wait before starting to compute
* errors for the files in the file list
@ -1887,6 +1887,27 @@ declare namespace ts {
command: CommandTypes.Geterr;
arguments: GeterrRequestArgs;
}
export interface FileRange {
/**
* The line number for the request (1-based).
*/
startLine: number;
/**
* The character offset (on the line) for the request (1-based).
*/
startOffset: number;
/**
* The line number for the request (1-based).
*/
endLine: number;
/**
* The character offset (on the line) for the request (1-based).
*/
endOffset: number;
}
export interface FileRangesRequestArgs extends Pick<FileRequestArgs, "file"> {
ranges: FileRange[];
}
export type RequestCompletedEventName = "requestCompleted";
/**
* Event that is sent when server have finished processing request with specified id.
@ -1897,6 +1918,7 @@ declare namespace ts {
}
export interface RequestCompletedEventBody {
request_seq: number;
performanceData?: PerformanceData;
}
/**
* Item of diagnostic information found in a DiagnosticEvent message.
@ -1969,8 +1991,12 @@ declare namespace ts {
* An array of diagnostic information items.
*/
diagnostics: Diagnostic[];
/**
* Spans where the region diagnostic was requested, if this is a region semantic diagnostic event.
*/
spans?: TextSpan[];
}
export type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag";
export type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag" | "regionSemanticDiag";
/**
* Event message for DiagnosticEventKind event types.
* These events provide syntactic and semantic errors for a file.
@ -2510,6 +2536,7 @@ declare namespace ts {
private readonly knownCachesSet;
private readonly projectWatchers;
private safeList;
private pendingRunRequests;
private installRunCount;
private inFlightRequestCount;
abstract readonly typesRegistry: Map<string, MapLike<string>>;
@ -2636,6 +2663,7 @@ declare namespace ts {
interface ServerHost extends System {
watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher;
watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher;
preferNonRecursiveWatch?: boolean;
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
clearTimeout(timeoutId: any): void;
setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;
@ -2644,6 +2672,18 @@ declare namespace ts {
trace?(s: string): void;
require?(initialPath: string, moduleName: string): ModuleImportResult;
}
interface InstallPackageOptionsWithProject extends InstallPackageOptions {
projectName: string;
projectRootPath: Path;
}
interface ITypingsInstaller {
isKnownTypesPackageName(name: string): boolean;
installPackage(options: InstallPackageOptionsWithProject): Promise<ApplyCodeActionCommandResult>;
enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string> | undefined): void;
attach(projectService: ProjectService): void;
onProjectClosed(p: Project): void;
readonly globalTypingsCacheLocation: string | undefined;
}
function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string>, cachePath?: string): DiscoverTypings;
function toNormalizedPath(fileName: string): NormalizedPath;
function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path;
@ -2702,6 +2742,7 @@ declare namespace ts {
readonly containingProjects: Project[];
private formatSettings;
private preferences;
private realpath;
constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: number);
isScriptOpen(): boolean;
open(newText: string | undefined): void;
@ -2735,19 +2776,6 @@ declare namespace ts {
positionToLineOffset(position: number): protocol.Location;
isJavaScript(): boolean;
}
interface InstallPackageOptionsWithProject extends InstallPackageOptions {
projectName: string;
projectRootPath: Path;
}
interface ITypingsInstaller {
isKnownTypesPackageName(name: string): boolean;
installPackage(options: InstallPackageOptionsWithProject): Promise<ApplyCodeActionCommandResult>;
enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray<string> | undefined): void;
attach(projectService: ProjectService): void;
onProjectClosed(p: Project): void;
readonly globalTypingsCacheLocation: string | undefined;
}
const nullTypingsInstaller: ITypingsInstaller;
function allRootFilesAreJsOrDts(project: Project): boolean;
function allFilesAreJsOrDts(project: Project): boolean;
enum ProjectKind {
@ -2789,33 +2817,31 @@ declare namespace ts {
private externalFiles;
private missingFilesMap;
private generatedFilesMap;
private hasAddedorRemovedFiles;
private hasAddedOrRemovedSymlinks;
protected languageService: LanguageService;
languageServiceEnabled: boolean;
readonly trace?: (s: string) => void;
readonly realpath?: (path: string) => string;
private builderState;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
private lastReportedFileNames;
/**
* Last version that was reported.
*/
private lastReportedVersion;
protected projectErrors: Diagnostic[] | undefined;
protected isInitialLoadPending: () => boolean;
private typingsCache;
private typingWatchers;
private readonly cancellationToken;
isNonTsProject(): boolean;
isJsOnlyProject(): boolean;
static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined;
private exportMapCache;
private changedFilesForExportMapCache;
private moduleSpecifierCache;
private symlinks;
readonly jsDocParsingMode: JSDocParsingMode | undefined;
isKnownTypesPackageName(name: string): boolean;
installPackage(options: InstallPackageOptions): Promise<ApplyCodeActionCommandResult>;
private get typingsCache();
getCompilationSettings(): ts.CompilerOptions;
getCompilerOptions(): ts.CompilerOptions;
getNewLine(): string;
@ -2882,6 +2908,8 @@ declare namespace ts {
* @returns: true if set of files in the project stays the same and false - otherwise.
*/
updateGraph(): boolean;
private closeWatchingTypingLocations;
private onTypingInstallerWatchInvoke;
protected removeExistingTypings(include: string[]): string[];
private updateGraphWorker;
private detachScriptInfoFromProject;
@ -2893,6 +2921,7 @@ declare namespace ts {
getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined;
getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined;
filesToString(writeProjectFileNames: boolean): string;
private filesToStringWorker;
setCompilerOptions(compilerOptions: CompilerOptions): void;
setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void;
getTypeAcquisition(): ts.TypeAcquisition;
@ -2901,6 +2930,8 @@ declare namespace ts {
protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void;
/** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */
refreshDiagnostics(): void;
private isDefaultProjectForOpenFiles;
private getCompilerOptionsForNoDtsResolutionProject;
}
/**
* If a file is opened and no tsconfig (or jsconfig) is found,
@ -2920,6 +2951,7 @@ declare namespace ts {
}
class AutoImportProviderProject extends Project {
private hostProject;
private static readonly maxDependencies;
private rootFileNames;
updateGraph(): boolean;
hasRoots(): boolean;
@ -2936,6 +2968,8 @@ declare namespace ts {
class ConfiguredProject extends Project {
readonly canonicalConfigFilePath: NormalizedPath;
private projectReferences;
private compilerHost?;
private releaseParsedConfig;
/**
* If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
* @returns: true if set of files in the project stays the same and false - otherwise.
@ -3126,6 +3160,7 @@ declare namespace ts {
configFileName?: NormalizedPath;
configFileErrors?: readonly Diagnostic[];
}
const nullTypingsInstaller: ITypingsInstaller;
interface ProjectServiceOptions {
host: ServerHost;
logger: Logger;
@ -3151,16 +3186,8 @@ declare namespace ts {
}
class ProjectService {
private readonly nodeModulesWatchers;
/**
* Contains all the deleted script info's version information so that
* it does not reset when creating script info again
* (and could have potentially collided with version where contents mismatch)
*/
private readonly filenameToScriptInfoVersion;
private readonly allJsFilesForOpenFileTelemetry;
/**
* maps external project file name to list of config files that were the part of this project
*/
private readonly externalProjectToConfiguredProjectMap;
/**
* external projects (configuration and list of root files is not controlled by tsserver)
@ -3178,13 +3205,8 @@ declare namespace ts {
* Open files: with value being project root path, and key being Path of the file that is open
*/
readonly openFiles: Map<Path, NormalizedPath | undefined>;
/** Config files looked up and cached config files for open script info */
private readonly configFileForOpenFiles;
/** Set of open script infos that are root of inferred project */
private rootOfInferredProjects;
/**
* Map of open files that are opened without complete path but have projectRoot as current directory
*/
private readonly openFilesWithNonRootedDiskPath;
private compilerOptionsForInferredProjects;
private compilerOptionsForInferredProjectsPerProjectRoot;
@ -3192,18 +3214,11 @@ declare namespace ts {
private watchOptionsForInferredProjectsPerProjectRoot;
private typeAcquisitionForInferredProjects;
private typeAcquisitionForInferredProjectsPerProjectRoot;
/**
* Project size for configured or external projects
*/
private readonly projectToSizeMap;
private readonly hostConfiguration;
private safelist;
private readonly legacySafelist;
private pendingProjectUpdates;
/**
* All the open script info that needs recalculation of the default project,
* this also caches config file info before config file change was detected to use it in case projects are not updated yet
*/
private pendingOpenFileProjectUpdates?;
readonly currentDirectory: NormalizedPath;
readonly toCanonicalFileName: (f: string) => string;
@ -3221,8 +3236,11 @@ declare namespace ts {
readonly allowLocalPluginLoads: boolean;
readonly typesMapLocation: string | undefined;
readonly serverMode: LanguageServiceMode;
/** Tracks projects that we have already sent telemetry for. */
private readonly seenProjects;
private readonly sharedExtendedConfigFileWatchers;
private readonly extendedConfigCache;
private packageJsonFilesMap;
private incompleteCompletionsCache;
private performanceEventHandler?;
private pendingPluginEnablements?;
private currentPluginEnablementPromise?;
@ -3236,20 +3254,9 @@ declare namespace ts {
setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.InferredProjectCompilerOptions, projectRootPath?: string): void;
findProject(projectName: string): Project | undefined;
getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined;
/**
* If there is default project calculation pending for this file,
* then it completes that calculation so that correct default project is used for the project
*/
private tryGetDefaultProjectForEnsuringConfiguredProjectForFile;
private doEnsureDefaultProjectForFile;
getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined;
/**
* Ensures the project structures are upto date
* This means,
* - we go through all the projects and update them if they are dirty
* - if updates reflect some change in structure or there was pending request to ensure projects for open files
* ensure that each open script info has project
*/
private ensureProjectStructuresUptoDate;
getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings;
getPreferences(file: NormalizedPath): protocol.UserPreferences;
@ -3260,37 +3267,30 @@ declare namespace ts {
private delayUpdateSourceInfoProjects;
private delayUpdateProjectsOfScriptInfoPath;
private handleDeletedFile;
private watchWildcardDirectory;
private onWildCardDirectoryWatcherInvoke;
private delayUpdateProjectsFromParsedConfigOnConfigFileChange;
private onConfigFileChanged;
private removeProject;
private assignOrphanScriptInfosToInferredProject;
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
private closeOpenFile;
private deleteScriptInfo;
private configFileExists;
/**
* This function tries to search for a tsconfig.json for the given file.
* This is different from the method the compiler uses because
* the compiler can assume it will always start searching in the
* current directory (the directory in which tsc was invoked).
* The server must start searching from the directory containing
* the newly opened file.
*/
private createConfigFileWatcherForParsedConfig;
private forEachConfigFileLocation;
/** Get cached configFileName for scriptInfo or ancestor of open script info */
private getConfigFileNameForFileFromCache;
/** Caches the configFilename for script info or ancestor of open script info */
private setConfigFileNameForFileInCache;
private printProjects;
private getConfiguredProjectByCanonicalConfigFilePath;
private findExternalProjectByProjectName;
/** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */
private getFilenameForExceededTotalSizeLimitForNonTsFiles;
private createExternalProject;
private addFilesToNonInferredProject;
private loadConfiguredProject;
private updateNonInferredProjectFiles;
private updateRootAndOptionsOfNonInferredProject;
private reloadFileNamesOfParsedConfig;
private clearSemanticCache;
private getOrCreateInferredProjectForProjectRootPathIfEnabled;
private getOrCreateSingleInferredProjectIfEnabled;
private getOrCreateSingleInferredWithoutProjectRoot;
@ -3316,23 +3316,15 @@ declare namespace ts {
private addSourceInfoToSourceMap;
private addMissingSourceMapFile;
setHostConfiguration(args: protocol.ConfigureRequestArguments): void;
private getWatchOptionsFromProjectWatchOptions;
closeLog(): void;
private sendSourceFileChange;
/**
* This function rebuilds the project for every file opened by the client
* This does not reload contents of open files from disk. But we could do that if needed
*/
reloadProjects(): void;
/**
* Remove the root of inferred project if script info is part of another project
*/
private removeRootOfInferredProjectIfNowPartOfOtherProject;
/**
* This function is to update the project structure for every inferred project.
* It is called on the premise that all the configured projects are
* up to date.
* This will go through open files and assign them to inferred project if open file is not part of any other project
* After that all the inferred project graphs are updated
*/
private ensureProjectForOpenFiles;
/**
* Open file whose contents is managed by the client
@ -3343,20 +3335,12 @@ declare namespace ts {
private findExternalProjectContainingOpenScriptInfo;
private getOrCreateOpenScriptInfo;
private assignProjectToOpenedScriptInfo;
/**
* Finds the default configured project for given info
* For any tsconfig found, it looks into that project, if not then all its references,
* The search happens for all tsconfigs till projectRootPath
*/
private tryFindDefaultConfiguredProjectForOpenScriptInfo;
/**
* Finds the default configured project, if found, it creates the solution projects (does not load them right away)
* with Find: finds the projects even if the project is deferredClosed
*/
private tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo;
private ensureProjectChildren;
private cleanupConfiguredProjects;
private cleanupProjectsAndScriptInfos;
private tryInvokeWildCardDirectories;
openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult;
private removeOrphanScriptInfos;
private telemetryOnOpenFile;
@ -3368,7 +3352,6 @@ declare namespace ts {
private collectChanges;
closeExternalProject(uncheckedFileName: string): void;
openExternalProjects(projects: protocol.ExternalProject[]): void;
/** Makes a filename safe to insert in a RegExp */
private static readonly filenameEscapeRegexp;
private static escapeFilenameForRegex;
resetSafeList(): void;
@ -3376,9 +3359,12 @@ declare namespace ts {
private applySafeListWorker;
openExternalProject(proj: protocol.ExternalProject): void;
hasDeferredExtension(): boolean;
private endEnablePlugin;
private enableRequestedPluginsAsync;
private enableRequestedPluginsWorker;
configurePlugin(args: protocol.ConfigurePluginRequestArguments): void;
private watchPackageJsonFile;
private onPackageJsonChange;
}
function formatMessage<T extends protocol.Message>(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string;
interface ServerCancellationToken extends HostCancellationToken {
@ -3386,10 +3372,6 @@ declare namespace ts {
resetRequest(requestId: number): void;
}
const nullCancellationToken: ServerCancellationToken;
interface PendingErrorCheck {
fileName: NormalizedPath;
project: Project;
}
/** @deprecated use ts.server.protocol.CommandTypes */
type CommandNames = protocol.CommandTypes;
/** @deprecated use ts.server.protocol.CommandTypes */
@ -3449,6 +3431,7 @@ declare namespace ts {
constructor(opts: SessionOptions);
private sendRequestCompletedEvent;
private addPerformanceData;
private addDiagnosticsPerformanceData;
private performanceEventHandler;
private defaultEventHandler;
private projectsUpdatedInBackgroundEvent;
@ -3460,8 +3443,8 @@ declare namespace ts {
private semanticCheck;
private syntacticCheck;
private suggestionCheck;
private regionSemanticCheck;
private sendDiagnosticsEvent;
/** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */
private updateErrorCheck;
private cleanProjects;
private cleanup;
@ -3508,10 +3491,6 @@ declare namespace ts {
private toSpanGroups;
private getReferences;
private getFileReferences;
/**
* @param fileName is the name of the file to be opened
* @param fileContent is a version of the file content that is known to be more up to date than the one on disk
*/
private openClientFile;
private getPosition;
private getPositionInFile;
@ -3610,19 +3589,12 @@ declare namespace ts {
}
namespace deno {
function setIsNodeSourceFileCallback(callback: IsNodeSourceFileCallback): void;
function setNodeBuiltInModuleNames(names: readonly string[]): void;
function setNodeOnlyGlobalNames(names: readonly string[]): void;
function createDenoForkContext({ mergeSymbol, globals, nodeGlobals, ambientModuleSymbolRegex }: {
function createDenoForkContext({ mergeSymbol, globals, nodeGlobals }: {
mergeSymbol(target: ts.Symbol, source: ts.Symbol, unidirectional?: boolean): ts.Symbol;
globals: ts.SymbolTable;
nodeGlobals: ts.SymbolTable;
ambientModuleSymbolRegex: RegExp;
}): {
hasNodeSourceFile: (node: ts.Node | undefined) => boolean;
getGlobalsForName: (id: ts.__String) => ts.SymbolTable;
mergeGlobalSymbolTable: (node: ts.Node, source: ts.SymbolTable, unidirectional?: boolean) => void;
combinedGlobals: ts.SymbolTable;
};
}): DenoForkContext;
function tryParseNpmPackageReference(text: string): {
name: string;
versionReq: string | undefined;
@ -3634,6 +3606,12 @@ declare namespace ts {
subPath: string | undefined;
};
type IsNodeSourceFileCallback = (sourceFile: ts.SourceFile) => boolean;
interface DenoForkContext {
hasNodeSourceFile: (node: ts.Node | undefined) => boolean;
getGlobalsForName: (id: ts.__String) => ts.SymbolTable;
mergeGlobalSymbolTable: (node: ts.Node, source: ts.SymbolTable, unidirectional?: boolean) => void;
combinedGlobals: ts.SymbolTable;
}
interface NpmPackageReference {
name: string;
versionReq: string;
@ -3648,7 +3626,7 @@ declare namespace ts {
readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[];
}
}
const versionMajorMinor = "5.5";
const versionMajorMinor = "5.6";
/** The version of the TypeScript compiler release */
const version: string;
/**
@ -4478,7 +4456,7 @@ declare namespace ts {
readonly right: Identifier;
}
type EntityName = Identifier | QualifiedName;
type PropertyName = Identifier | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier;
type PropertyName = Identifier | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier | BigIntLiteral;
type MemberName = Identifier | PrivateIdentifier;
type DeclarationName = PropertyName | JsxAttributeName | StringLiteralLike | ElementAccessExpression | BindingPattern | EntityNameExpression;
interface Declaration extends Node {
@ -4829,7 +4807,7 @@ declare namespace ts {
readonly kind: SyntaxKind.StringLiteral;
}
type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral;
type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName;
type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName | BigIntLiteral;
interface TemplateLiteralTypeNode extends TypeNode {
kind: SyntaxKind.TemplateLiteralType;
readonly head: TemplateHead;
@ -5549,7 +5527,7 @@ declare namespace ts {
interface NamespaceExport extends NamedDeclaration {
readonly kind: SyntaxKind.NamespaceExport;
readonly parent: ExportDeclaration;
readonly name: Identifier;
readonly name: ModuleExportName;
}
interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.NamespaceExportDeclaration;
@ -5581,7 +5559,7 @@ declare namespace ts {
interface ImportSpecifier extends NamedDeclaration {
readonly kind: SyntaxKind.ImportSpecifier;
readonly parent: NamedImports;
readonly propertyName?: Identifier;
readonly propertyName?: ModuleExportName;
readonly name: Identifier;
readonly isTypeOnly: boolean;
}
@ -5589,9 +5567,10 @@ declare namespace ts {
readonly kind: SyntaxKind.ExportSpecifier;
readonly parent: NamedExports;
readonly isTypeOnly: boolean;
readonly propertyName?: Identifier;
readonly name: Identifier;
readonly propertyName?: ModuleExportName;
readonly name: ModuleExportName;
}
type ModuleExportName = Identifier | StringLiteral;
type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier;
type TypeOnlyCompatibleAliasDeclaration = ImportClause | ImportEqualsDeclaration | NamespaceImport | ImportOrExportSpecifier | ExportDeclaration | NamespaceExport;
type TypeOnlyImportDeclaration =
@ -6046,19 +6025,67 @@ declare namespace ts {
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
isSourceFileDefaultLibrary(file: SourceFile): boolean;
/**
* Calculates the final resolution mode for a given module reference node. This is the resolution mode explicitly provided via import
* attributes, if present, or the syntax the usage would have if emitted to JavaScript. In `--module node16` or `nodenext`, this may
* depend on the file's `impliedNodeFormat`. In `--module preserve`, it depends only on the input syntax of the reference. In other
* `module` modes, when overriding import attributes are not provided, this function returns `undefined`, as the result would have no
* impact on module resolution, emit, or type checking.
* Calculates the final resolution mode for a given module reference node. This function only returns a result when module resolution
* settings allow differing resolution between ESM imports and CJS requires, or when a mode is explicitly provided via import attributes,
* which cause an `import` or `require` condition to be used during resolution regardless of module resolution settings. In absence of
* overriding attributes, and in modes that support differing resolution, the result indicates the syntax the usage would emit to JavaScript.
* Some examples:
*
* ```ts
* // tsc foo.mts --module nodenext
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `impliedNodeFormat` set by .mts file extension
*
* // tsc foo.cts --module nodenext
* import {} from "mod";
* // Result: CommonJS - the import emits as CJS due to `impliedNodeFormat` set by .cts file extension
*
* // tsc foo.ts --module preserve --moduleResolution bundler
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `--module preserve` and `--moduleResolution bundler`
* // supports conditional imports/exports
*
* // tsc foo.ts --module preserve --moduleResolution node10
* import {} from "mod";
* // Result: undefined - the import emits as ESM due to `--module preserve`, but `--moduleResolution node10`
* // does not support conditional imports/exports
*
* // tsc foo.ts --module commonjs --moduleResolution node10
* import type {} from "mod" with { "resolution-mode": "import" };
* // Result: ESNext - conditional imports/exports always supported with "resolution-mode" attribute
* ```
*/
getModeForUsageLocation(file: SourceFile, usage: StringLiteralLike): ResolutionMode;
/**
* Calculates the final resolution mode for an import at some index within a file's `imports` list. This is the resolution mode
* explicitly provided via import attributes, if present, or the syntax the usage would have if emitted to JavaScript. In
* `--module node16` or `nodenext`, this may depend on the file's `impliedNodeFormat`. In `--module preserve`, it depends only on the
* input syntax of the reference. In other `module` modes, when overriding import attributes are not provided, this function returns
* `undefined`, as the result would have no impact on module resolution, emit, or type checking.
* Calculates the final resolution mode for an import at some index within a file's `imports` list. This function only returns a result
* when module resolution settings allow differing resolution between ESM imports and CJS requires, or when a mode is explicitly provided
* via import attributes, which cause an `import` or `require` condition to be used during resolution regardless of module resolution
* settings. In absence of overriding attributes, and in modes that support differing resolution, the result indicates the syntax the
* usage would emit to JavaScript. Some examples:
*
* ```ts
* // tsc foo.mts --module nodenext
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `impliedNodeFormat` set by .mts file extension
*
* // tsc foo.cts --module nodenext
* import {} from "mod";
* // Result: CommonJS - the import emits as CJS due to `impliedNodeFormat` set by .cts file extension
*
* // tsc foo.ts --module preserve --moduleResolution bundler
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `--module preserve` and `--moduleResolution bundler`
* // supports conditional imports/exports
*
* // tsc foo.ts --module preserve --moduleResolution node10
* import {} from "mod";
* // Result: undefined - the import emits as ESM due to `--module preserve`, but `--moduleResolution node10`
* // does not support conditional imports/exports
*
* // tsc foo.ts --module commonjs --moduleResolution node10
* import type {} from "mod" with { "resolution-mode": "import" };
* // Result: ESNext - conditional imports/exports always supported with "resolution-mode" attribute
* ```
*/
getModeForResolutionAtIndex(file: SourceFile, index: number): ResolutionMode;
getProjectReferences(): readonly ProjectReference[] | undefined;
@ -6125,6 +6152,27 @@ declare namespace ts {
getBaseTypes(type: InterfaceType): BaseType[];
getBaseTypeOfLiteralType(type: Type): Type;
getWidenedType(type: Type): Type;
/**
* Gets the "awaited type" of a type.
*
* If an expression has a Promise-like type, the "awaited type" of the expression is
* derived from the type of the first argument of the fulfillment callback for that
* Promise's `then` method. If the "awaited type" is itself a Promise-like, it is
* recursively unwrapped in the same manner until a non-promise type is found.
*
* If an expression does not have a Promise-like type, its "awaited type" is the type
* of the expression.
*
* If the resulting "awaited type" is a generic object type, then it is wrapped in
* an `Awaited<T>`.
*
* In the event the "awaited type" circularly references itself, or is a non-Promise
* object-type with a callable `then()` method, an "awaited type" cannot be determined
* and the value `undefined` will be returned.
*
* This is used to reflect the runtime behavior of the `await` keyword.
*/
getAwaitedType(type: Type): Type | undefined;
getReturnTypeOfSignature(signature: Signature): Type;
getNullableType(type: Type, flags: TypeFlags): Type;
getNonNullableType(type: Type): Type;
@ -6217,6 +6265,7 @@ declare namespace ts {
getNumberType(): Type;
getNumberLiteralType(value: number): NumberLiteralType;
getBigIntType(): Type;
getBigIntLiteralType(value: PseudoBigInt): BigIntLiteralType;
getBooleanType(): Type;
getFalseType(): Type;
getTrueType(): Type;
@ -6686,7 +6735,11 @@ declare namespace ts {
minLength: number;
/** Number of initial required or optional elements */
fixedLength: number;
/** True if tuple has any rest or variadic elements */
/**
* True if tuple has any rest or variadic elements
*
* @deprecated Use `.combinedFlags & ElementFlags.Variable` instead
*/
hasRestElement: boolean;
combinedFlags: ElementFlags;
readonly: boolean;
@ -7010,6 +7063,7 @@ declare namespace ts {
strictBindCallApply?: boolean;
strictNullChecks?: boolean;
strictPropertyInitialization?: boolean;
strictBuiltinIteratorReturn?: boolean;
stripInternal?: boolean;
/** @deprecated */
suppressExcessPropertyErrors?: boolean;
@ -7018,6 +7072,7 @@ declare namespace ts {
target?: ScriptTarget;
traceResolution?: boolean;
useUnknownInCatchVariables?: boolean;
noUncheckedSideEffectImports?: boolean;
resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
@ -7344,9 +7399,10 @@ declare namespace ts {
TypeAssertions = 2,
NonNullAssertions = 4,
PartiallyEmittedExpressions = 8,
ExpressionsWithTypeArguments = 16,
Assertions = 6,
All = 15,
ExcludeJSDocTypeAssertion = 16,
All = 31,
ExcludeJSDocTypeAssertion = -2147483648,
}
type ImmediatelyInvokedFunctionExpression = CallExpression & {
readonly expression: FunctionExpression;
@ -7645,20 +7701,20 @@ declare namespace ts {
updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute;
createNamespaceImport(name: Identifier): NamespaceImport;
updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport;
createNamespaceExport(name: Identifier): NamespaceExport;
updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport;
createNamespaceExport(name: ModuleExportName): NamespaceExport;
updateNamespaceExport(node: NamespaceExport, name: ModuleExportName): NamespaceExport;
createNamedImports(elements: readonly ImportSpecifier[]): NamedImports;
updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports;
createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
createImportSpecifier(isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier;
updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: Identifier): ImportSpecifier;
createExportAssignment(modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment;
updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, expression: Expression): ExportAssignment;
createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, attributes?: ImportAttributes): ExportDeclaration;
updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, attributes: ImportAttributes | undefined): ExportDeclaration;
createNamedExports(elements: readonly ExportSpecifier[]): NamedExports;
updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports;
createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier;
updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier;
createExportSpecifier(isTypeOnly: boolean, propertyName: string | ModuleExportName | undefined, name: string | ModuleExportName): ExportSpecifier;
updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: ModuleExportName | undefined, name: ModuleExportName): ExportSpecifier;
createExternalModuleReference(expression: Expression): ExternalModuleReference;
updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference;
createJSDocAllType(): JSDocAllType;
@ -8238,6 +8294,7 @@ declare namespace ts {
readonly interactiveInlayHints?: boolean;
readonly allowRenameOfImportPath?: boolean;
readonly autoImportFileExcludePatterns?: string[];
readonly autoImportSpecifierExcludeRegexes?: string[];
readonly preferTypeOnlyAutoImports?: boolean;
/**
* Indicates whether imports should be organized in a case-insensitive manner.
@ -8976,6 +9033,7 @@ declare namespace ts {
function isExportDeclaration(node: Node): node is ExportDeclaration;
function isNamedExports(node: Node): node is NamedExports;
function isExportSpecifier(node: Node): node is ExportSpecifier;
function isModuleExportName(node: Node): node is ModuleExportName;
function isMissingDeclaration(node: Node): node is MissingDeclaration;
function isNotEmittedStatement(node: Node): node is NotEmittedStatement;
function isExternalModuleReference(node: Node): node is ExternalModuleReference;
@ -9411,24 +9469,43 @@ declare namespace ts {
function getModeForResolutionAtIndex(file: SourceFile, index: number, compilerOptions: CompilerOptions): ResolutionMode;
/**
* Use `program.getModeForUsageLocation`, which retrieves the correct `compilerOptions`, instead of this function whenever possible.
* Calculates the final resolution mode for a given module reference node. This is the resolution mode explicitly provided via import
* attributes, if present, or the syntax the usage would have if emitted to JavaScript. In `--module node16` or `nodenext`, this may
* depend on the file's `impliedNodeFormat`. In `--module preserve`, it depends only on the input syntax of the reference. In other
* `module` modes, when overriding import attributes are not provided, this function returns `undefined`, as the result would have no
* impact on module resolution, emit, or type checking.
* Calculates the final resolution mode for a given module reference node. This function only returns a result when module resolution
* settings allow differing resolution between ESM imports and CJS requires, or when a mode is explicitly provided via import attributes,
* which cause an `import` or `require` condition to be used during resolution regardless of module resolution settings. In absence of
* overriding attributes, and in modes that support differing resolution, the result indicates the syntax the usage would emit to JavaScript.
* Some examples:
*
* ```ts
* // tsc foo.mts --module nodenext
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `impliedNodeFormat` set by .mts file extension
*
* // tsc foo.cts --module nodenext
* import {} from "mod";
* // Result: CommonJS - the import emits as CJS due to `impliedNodeFormat` set by .cts file extension
*
* // tsc foo.ts --module preserve --moduleResolution bundler
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `--module preserve` and `--moduleResolution bundler`
* // supports conditional imports/exports
*
* // tsc foo.ts --module preserve --moduleResolution node10
* import {} from "mod";
* // Result: undefined - the import emits as ESM due to `--module preserve`, but `--moduleResolution node10`
* // does not support conditional imports/exports
*
* // tsc foo.ts --module commonjs --moduleResolution node10
* import type {} from "mod" with { "resolution-mode": "import" };
* // Result: ESNext - conditional imports/exports always supported with "resolution-mode" attribute
* ```
*
* @param file The file the import or import-like reference is contained within
* @param usage The module reference string
* @param compilerOptions The compiler options for the program that owns the file. If the file belongs to a referenced project, the compiler options
* should be the options of the referenced project, not the referencing project.
* @returns The final resolution mode of the import
*/
function getModeForUsageLocation(
file: {
impliedNodeFormat?: ResolutionMode;
},
usage: StringLiteralLike,
compilerOptions: CompilerOptions,
): ModuleKind.CommonJS | ModuleKind.ESNext | undefined;
function getModeForUsageLocation(file: SourceFile, usage: StringLiteralLike, compilerOptions: CompilerOptions): ResolutionMode;
function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): readonly Diagnostic[];
/**
* A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the
@ -9654,6 +9731,7 @@ declare namespace ts {
setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
/** If provided, will be used to reset existing delayed compilation */
clearTimeout?(timeoutId: any): void;
preferNonRecursiveWatch?: boolean;
}
interface ProgramHost<T extends BuilderProgram> {
/**
@ -9776,6 +9854,7 @@ declare namespace ts {
dry?: boolean;
force?: boolean;
verbose?: boolean;
stopBuildOnErrors?: boolean;
incremental?: boolean;
assumeChangesOnlyAffectDirectDependencies?: boolean;
declaration?: boolean;
@ -10743,6 +10822,10 @@ declare namespace ts {
*/
isIncomplete?: true;
entries: CompletionEntry[];
/**
* Default commit characters for the completion entries.
*/
defaultCommitCharacters?: string[];
}
interface CompletionEntryDataAutoImport {
/**
@ -10849,6 +10932,10 @@ declare namespace ts {
* is an auto-import.
*/
data?: CompletionEntryData;
/**
* If this completion entry is selected, typing a commit character will cause the entry to be accepted.
*/
commitCharacters?: string[];
}
interface CompletionEntryLabelDetails {
/**

View file

@ -468,6 +468,7 @@ struct LoadResponse {
data: String,
version: Option<String>,
script_kind: i32,
is_cjs: bool,
}
#[op2]
@ -483,6 +484,29 @@ fn op_load_inner(
state: &mut OpState,
load_specifier: &str,
) -> Result<Option<LoadResponse>, AnyError> {
fn load_from_node_modules(
specifier: &ModuleSpecifier,
node_resolver: Option<&NodeResolver>,
media_type: &mut MediaType,
is_cjs: &mut bool,
) -> Result<String, AnyError> {
*media_type = MediaType::from_specifier(specifier);
*is_cjs = node_resolver
.map(|node_resolver| {
match node_resolver.url_to_node_resolution(specifier.clone()) {
Ok(NodeResolution::CommonJs(_)) => true,
Ok(NodeResolution::Esm(_))
| Ok(NodeResolution::BuiltIn(_))
| Err(_) => false,
}
})
.unwrap_or(false);
let file_path = specifier.to_file_path().unwrap();
let code = std::fs::read_to_string(&file_path)
.with_context(|| format!("Unable to load {}", file_path.display()))?;
Ok(code)
}
let state = state.borrow_mut::<State>();
let specifier = normalize_specifier(load_specifier, &state.current_dir)
@ -491,6 +515,7 @@ fn op_load_inner(
let mut hash: Option<String> = None;
let mut media_type = MediaType::Unknown;
let graph = &state.graph;
let mut is_cjs = false;
let data = if load_specifier == "internal:///.tsbuildinfo" {
state.maybe_tsbuildinfo.as_deref().map(Cow::Borrowed)
@ -522,6 +547,7 @@ fn op_load_inner(
data: "".to_string(),
version: Some("1".to_string()),
script_kind: as_ts_script_kind(*media_type),
is_cjs: false,
}))
}
_ => None,
@ -546,26 +572,25 @@ fn op_load_inner(
// means it's Deno code importing an npm module
let specifier =
node::resolve_specifier_into_node_modules(&module.specifier);
media_type = MediaType::from_specifier(&specifier);
let file_path = specifier.to_file_path().unwrap();
let code =
std::fs::read_to_string(&file_path).with_context(|| {
format!("Unable to load {}", file_path.display())
})?;
Some(Cow::Owned(code))
Some(Cow::Owned(load_from_node_modules(
&specifier,
state.maybe_npm.as_ref().map(|n| n.node_resolver.as_ref()),
&mut media_type,
&mut is_cjs,
)?))
}
}
} else if state
} else if let Some(npm) = state
.maybe_npm
.as_ref()
.map(|npm| npm.node_resolver.in_npm_package(specifier))
.unwrap_or(false)
.filter(|npm| npm.node_resolver.in_npm_package(specifier))
{
media_type = MediaType::from_specifier(specifier);
let file_path = specifier.to_file_path().unwrap();
let code = std::fs::read_to_string(&file_path)
.with_context(|| format!("Unable to load {}", file_path.display()))?;
Some(Cow::Owned(code))
Some(Cow::Owned(load_from_node_modules(
specifier,
Some(npm.node_resolver.as_ref()),
&mut media_type,
&mut is_cjs,
)?))
} else {
None
};
@ -579,6 +604,7 @@ fn op_load_inner(
data: data.into_owned(),
version: hash,
script_kind: as_ts_script_kind(media_type),
is_cjs,
}))
}
@ -601,7 +627,7 @@ fn op_resolve(
#[string] base: String,
is_base_cjs: bool,
#[serde] specifiers: Vec<String>,
) -> Result<Vec<(String, String)>, AnyError> {
) -> Result<Vec<(String, &'static str)>, AnyError> {
op_resolve_inner(
state,
ResolveArgs {
@ -616,9 +642,9 @@ fn op_resolve(
fn op_resolve_inner(
state: &mut OpState,
args: ResolveArgs,
) -> Result<Vec<(String, String)>, AnyError> {
) -> Result<Vec<(String, &'static str)>, AnyError> {
let state = state.borrow_mut::<State>();
let mut resolved: Vec<(String, String)> =
let mut resolved: Vec<(String, &'static str)> =
Vec::with_capacity(args.specifiers.len());
let referrer_kind = if args.is_base_cjs {
NodeModuleKind::Cjs
@ -640,16 +666,14 @@ fn op_resolve_inner(
if specifier.starts_with("node:") {
resolved.push((
MISSING_DEPENDENCY_SPECIFIER.to_string(),
MediaType::Dts.to_string(),
MediaType::Dts.as_ts_extension(),
));
continue;
}
if specifier.starts_with("asset:///") {
let media_type = MediaType::from_str(&specifier)
.as_ts_extension()
.to_string();
resolved.push((specifier, media_type));
let ext = MediaType::from_str(&specifier).as_ts_extension();
resolved.push((specifier, ext));
continue;
}
@ -694,11 +718,11 @@ fn op_resolve_inner(
}
}
};
(specifier_str, media_type.as_ts_extension().into())
(specifier_str, media_type.as_ts_extension())
}
None => (
MISSING_DEPENDENCY_SPECIFIER.to_string(),
".d.ts".to_string(),
MediaType::Dts.as_ts_extension(),
),
};
log::debug!("Resolved {} to {:?}", specifier, result);
@ -853,14 +877,15 @@ fn resolve_non_graph_specifier_types(
#[op2(fast)]
fn op_is_node_file(state: &mut OpState, #[string] path: &str) -> bool {
let state = state.borrow::<State>();
match ModuleSpecifier::parse(path) {
Ok(specifier) => state
.maybe_npm
.as_ref()
.map(|n| n.node_resolver.in_npm_package(&specifier))
.unwrap_or(false),
Err(_) => false,
}
ModuleSpecifier::parse(path)
.ok()
.and_then(|specifier| {
state
.maybe_npm
.as_ref()
.map(|n| n.node_resolver.in_npm_package(&specifier))
})
.unwrap_or(false)
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
@ -1071,7 +1096,6 @@ mod tests {
"jsxFactory": "React.createElement",
"jsxFragmentFactory": "React.Fragment",
"lib": ["deno.window"],
"module": "esnext",
"noEmit": true,
"outDir": "internal:///",
"strict": true,
@ -1168,6 +1192,7 @@ mod tests {
"data": "console.log(\"hello deno\");\n",
"version": "7821807483407828376",
"scriptKind": 3,
"isCjs": false,
})
);
}
@ -1206,6 +1231,7 @@ mod tests {
"data": "some content",
"version": null,
"scriptKind": 0,
"isCjs": false,
})
);
}
@ -1235,10 +1261,7 @@ mod tests {
},
)
.expect("should have invoked op");
assert_eq!(
actual,
vec![("https://deno.land/x/b.ts".into(), ".ts".into())]
);
assert_eq!(actual, vec![("https://deno.land/x/b.ts".into(), ".ts")]);
}
#[tokio::test]
@ -1258,10 +1281,7 @@ mod tests {
},
)
.expect("should have not errored");
assert_eq!(
actual,
vec![(MISSING_DEPENDENCY_SPECIFIER.into(), ".d.ts".into())]
);
assert_eq!(actual, vec![(MISSING_DEPENDENCY_SPECIFIER.into(), ".d.ts")]);
}
#[tokio::test]

View file

@ -30,6 +30,7 @@ use deno_runtime::deno_web::BlobStore;
use deno_runtime::fmt_errors::format_js_error;
use deno_runtime::inspector_server::InspectorServer;
use deno_runtime::ops::worker_host::CreateWebWorkerCb;
use deno_runtime::permissions::RuntimePermissionDescriptorParser;
use deno_runtime::web_worker::WebWorker;
use deno_runtime::web_worker::WebWorkerOptions;
use deno_runtime::worker::MainWorker;
@ -112,7 +113,6 @@ pub struct CliMainWorkerOptions {
pub origin_data_folder_path: Option<PathBuf>,
pub seed: Option<u64>,
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
pub unstable: bool,
pub skip_op_registration: bool,
pub create_hmr_runner: Option<CreateHmrRunnerCb>,
pub create_coverage_collector: Option<CreateCoverageCollectorCb>,
@ -122,23 +122,24 @@ pub struct CliMainWorkerOptions {
}
struct SharedWorkerState {
options: CliMainWorkerOptions,
subcommand: DenoSubcommand,
storage_key_resolver: StorageKeyResolver,
npm_resolver: Arc<dyn CliNpmResolver>,
node_resolver: Arc<NodeResolver>,
blob_store: Arc<BlobStore>,
broadcast_channel: InMemoryBroadcastChannel,
shared_array_buffer_store: SharedArrayBufferStore,
code_cache: Option<Arc<dyn code_cache::CodeCache>>,
compiled_wasm_module_store: CompiledWasmModuleStore,
module_loader_factory: Box<dyn ModuleLoaderFactory>,
root_cert_store_provider: Arc<dyn RootCertStoreProvider>,
feature_checker: Arc<FeatureChecker>,
fs: Arc<dyn deno_fs::FileSystem>,
maybe_file_watcher_communicator: Option<Arc<WatcherCommunicator>>,
maybe_inspector_server: Option<Arc<InspectorServer>>,
maybe_lockfile: Option<Arc<CliLockfile>>,
feature_checker: Arc<FeatureChecker>,
code_cache: Option<Arc<dyn code_cache::CodeCache>>,
module_loader_factory: Box<dyn ModuleLoaderFactory>,
node_resolver: Arc<NodeResolver>,
npm_resolver: Arc<dyn CliNpmResolver>,
permission_desc_parser: Arc<RuntimePermissionDescriptorParser>,
root_cert_store_provider: Arc<dyn RootCertStoreProvider>,
shared_array_buffer_store: SharedArrayBufferStore,
storage_key_resolver: StorageKeyResolver,
options: CliMainWorkerOptions,
subcommand: DenoSubcommand,
}
impl SharedWorkerState {
@ -419,40 +420,42 @@ pub struct CliMainWorkerFactory {
impl CliMainWorkerFactory {
#[allow(clippy::too_many_arguments)]
pub fn new(
storage_key_resolver: StorageKeyResolver,
subcommand: DenoSubcommand,
npm_resolver: Arc<dyn CliNpmResolver>,
node_resolver: Arc<NodeResolver>,
blob_store: Arc<BlobStore>,
module_loader_factory: Box<dyn ModuleLoaderFactory>,
root_cert_store_provider: Arc<dyn RootCertStoreProvider>,
code_cache: Option<Arc<dyn code_cache::CodeCache>>,
feature_checker: Arc<FeatureChecker>,
fs: Arc<dyn deno_fs::FileSystem>,
maybe_file_watcher_communicator: Option<Arc<WatcherCommunicator>>,
maybe_inspector_server: Option<Arc<InspectorServer>>,
maybe_lockfile: Option<Arc<CliLockfile>>,
feature_checker: Arc<FeatureChecker>,
code_cache: Option<Arc<dyn code_cache::CodeCache>>,
module_loader_factory: Box<dyn ModuleLoaderFactory>,
node_resolver: Arc<NodeResolver>,
npm_resolver: Arc<dyn CliNpmResolver>,
permission_parser: Arc<RuntimePermissionDescriptorParser>,
root_cert_store_provider: Arc<dyn RootCertStoreProvider>,
storage_key_resolver: StorageKeyResolver,
subcommand: DenoSubcommand,
options: CliMainWorkerOptions,
) -> Self {
Self {
shared: Arc::new(SharedWorkerState {
options,
subcommand,
storage_key_resolver,
npm_resolver,
node_resolver,
blob_store,
broadcast_channel: Default::default(),
shared_array_buffer_store: Default::default(),
code_cache,
compiled_wasm_module_store: Default::default(),
module_loader_factory,
root_cert_store_provider,
feature_checker,
fs,
maybe_file_watcher_communicator,
maybe_inspector_server,
maybe_lockfile,
feature_checker,
code_cache,
module_loader_factory,
node_resolver,
npm_resolver,
permission_desc_parser: permission_parser,
root_cert_store_provider,
shared_array_buffer_store: Default::default(),
storage_key_resolver,
options,
subcommand,
}),
}
}
@ -526,9 +529,13 @@ impl CliMainWorkerFactory {
(main_module, false)
};
let ModuleLoaderAndSourceMapGetter { module_loader } = shared
.module_loader_factory
.create_for_main(PermissionsContainer::allow_all(), permissions.clone());
let ModuleLoaderAndSourceMapGetter { module_loader } =
shared.module_loader_factory.create_for_main(
PermissionsContainer::allow_all(
self.shared.permission_desc_parser.clone(),
),
permissions.clone(),
);
let maybe_inspector_server = shared.maybe_inspector_server.clone();
let create_web_worker_cb =
@ -580,7 +587,6 @@ impl CliMainWorkerFactory {
is_stdout_tty: deno_terminal::is_stdout_tty(),
is_stderr_tty: deno_terminal::is_stderr_tty(),
color_level: colors::get_color_level(),
unstable: shared.options.unstable,
unstable_features,
user_agent: version::DENO_VERSION_INFO.user_agent.to_string(),
inspect: shared.options.is_inspecting,
@ -621,6 +627,7 @@ impl CliMainWorkerFactory {
),
stdio,
feature_checker,
permission_desc_parser: shared.permission_desc_parser.clone(),
skip_op_registration: shared.options.skip_op_registration,
v8_code_cache: shared.code_cache.clone(),
};
@ -775,7 +782,6 @@ fn create_web_worker_callback(
color_level: colors::get_color_level(),
is_stdout_tty: deno_terminal::is_stdout_tty(),
is_stderr_tty: deno_terminal::is_stderr_tty(),
unstable: shared.options.unstable,
unstable_features,
user_agent: version::DENO_VERSION_INFO.user_agent.to_string(),
inspect: shared.options.is_inspecting,
@ -812,6 +818,7 @@ fn create_web_worker_callback(
stdio: stdio.clone(),
cache_storage_dir,
feature_checker,
permission_desc_parser: shared.permission_desc_parser.clone(),
strace_ops: shared.options.strace_ops.clone(),
close_on_idle: args.close_on_idle,
maybe_worker_metadata: args.maybe_worker_metadata,
@ -833,13 +840,16 @@ fn create_web_worker_callback(
mod tests {
use super::*;
use deno_core::resolve_path;
use deno_fs::RealFs;
use deno_runtime::deno_permissions::Permissions;
fn create_test_worker() -> MainWorker {
let main_module =
resolve_path("./hello.js", &std::env::current_dir().unwrap()).unwrap();
let permissions =
PermissionsContainer::new(Permissions::none_without_prompt());
let permissions = PermissionsContainer::new(
Arc::new(RuntimePermissionDescriptorParser::new(Arc::new(RealFs))),
Permissions::none_without_prompt(),
);
let options = WorkerOptions {
startup_snapshot: crate::js::deno_isolate_init(),

View file

@ -50,12 +50,9 @@ pub fn op_broadcast_subscribe<BC>(
where
BC: BroadcastChannel + 'static,
{
// TODO(bartlomieju): replace with `state.feature_checker.check_or_exit`
// once we phase out `check_or_exit_with_legacy_fallback`
state.feature_checker.check_or_exit_with_legacy_fallback(
UNSTABLE_FEATURE_NAME,
"BroadcastChannel",
);
state
.feature_checker
.check_or_exit(UNSTABLE_FEATURE_NAME, "BroadcastChannel");
let bc = state.borrow::<BC>();
let resource = bc.subscribe()?;
Ok(state.resource_table.add(resource))

View file

@ -844,14 +844,6 @@ function formatRaw(ctx, value, recurseTimes, typedArray, proxyDetails) {
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.Duration.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.TimeZone.prototype,
value,
) ||
ObjectPrototypeIsPrototypeOf(
globalThis.Temporal.Calendar.prototype,
value,
)
)
) {
@ -1295,6 +1287,7 @@ function getKeys(value, showHidden) {
ArrayPrototypePushApply(keys, ArrayPrototypeFilter(symbols, filter));
}
}
keys = ArrayPrototypeFilter(keys, (key) => key !== "cause");
return keys;
}

View file

@ -62,11 +62,9 @@ where
{
let cron_handler = {
let state = state.borrow();
// TODO(bartlomieju): replace with `state.feature_checker.check_or_exit`
// once we phase out `check_or_exit_with_legacy_fallback`
state
.feature_checker
.check_or_exit_with_legacy_fallback(UNSTABLE_FEATURE_NAME, "Deno.cron");
.check_or_exit(UNSTABLE_FEATURE_NAME, "Deno.cron");
state.borrow::<Rc<C>>().clone()
};

View file

@ -299,10 +299,15 @@ impl Drop for ResourceToBodyAdapter {
pub trait FetchPermissions {
fn check_net_url(
&mut self,
_url: &Url,
url: &Url,
api_name: &str,
) -> Result<(), AnyError>;
fn check_read(&mut self, _p: &Path, api_name: &str) -> Result<(), AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_read<'a>(
&mut self,
p: &'a Path,
api_name: &str,
) -> Result<Cow<'a, Path>, AnyError>;
}
impl FetchPermissions for deno_permissions::PermissionsContainer {
@ -316,12 +321,16 @@ impl FetchPermissions for deno_permissions::PermissionsContainer {
}
#[inline(always)]
fn check_read(
fn check_read<'a>(
&mut self,
path: &Path,
path: &'a Path,
api_name: &str,
) -> Result<(), AnyError> {
deno_permissions::PermissionsContainer::check_read(self, path, api_name)
) -> Result<Cow<'a, Path>, AnyError> {
deno_permissions::PermissionsContainer::check_read_path(
self,
path,
Some(api_name),
)
}
}
@ -359,7 +368,11 @@ where
type_error("NetworkError when attempting to fetch resource")
})?;
let permissions = state.borrow_mut::<FP>();
permissions.check_read(&path, "fetch()")?;
let path = permissions.check_read(&path, "fetch()")?;
let url = match path {
Cow::Owned(path) => Url::from_file_path(path).unwrap(),
Cow::Borrowed(_) => url,
};
if method != Method::GET {
return Err(type_error(format!(

View file

@ -1,7 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use crate::callback::PtrSymbol;
use crate::check_unstable;
use crate::dlfcn::DynamicLibraryResource;
use crate::ir::*;
use crate::symbol::NativeType;
@ -285,11 +284,10 @@ pub fn op_ffi_call_ptr_nonblocking<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(&state.borrow(), "Deno.UnsafeFnPointer#call");
{
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
};
let symbol = PtrSymbol::new(pointer, &def)?;
@ -383,11 +381,10 @@ pub fn op_ffi_call_ptr<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(&state.borrow(), "Deno.UnsafeFnPointer#call");
{
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
};
let symbol = PtrSymbol::new(pointer, &def)?;

View file

@ -1,6 +1,5 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use crate::check_unstable;
use crate::symbol::NativeType;
use crate::FfiPermissions;
use crate::ForeignFunction;
@ -557,9 +556,8 @@ pub fn op_ffi_unsafe_callback_create<FP, 'scope>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafeCallback");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
let thread_id: u32 = LOCAL_THREAD_ID.with(|s| {
let value = *s.borrow();

View file

@ -1,6 +1,5 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use crate::check_unstable;
use crate::ir::out_buffer_as_ptr;
use crate::symbol::NativeType;
use crate::symbol::Symbol;
@ -20,7 +19,6 @@ use serde_value::ValueDeserializer;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::c_void;
use std::path::PathBuf;
use std::rc::Rc;
pub struct DynamicLibraryResource {
@ -122,16 +120,13 @@ pub fn op_ffi_load<'scope, FP>(
where
FP: FfiPermissions + 'static,
{
let path = args.path;
check_unstable(state, "Deno.dlopen");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(Some(&PathBuf::from(&path)))?;
let path = permissions.check_partial_with_path(&args.path)?;
let lib = Library::open(&path).map_err(|e| {
dlopen2::Error::OpeningLibraryError(std::io::Error::new(
std::io::ErrorKind::Other,
format_error(e, path),
format_error(e, &path),
))
})?;
let mut resource = DynamicLibraryResource {
@ -292,7 +287,10 @@ fn sync_fn_impl<'s>(
// `path` is only used on Windows.
#[allow(unused_variables)]
pub(crate) fn format_error(e: dlopen2::Error, path: String) -> String {
pub(crate) fn format_error(
e: dlopen2::Error,
path: &std::path::Path,
) -> String {
match e {
#[cfg(target_os = "windows")]
// This calls FormatMessageW with library path
@ -302,7 +300,6 @@ pub(crate) fn format_error(e: dlopen2::Error, path: String) -> String {
//
// https://github.com/denoland/deno/issues/11632
dlopen2::Error::OpeningLibraryError(e) => {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::shared::minwindef::DWORD;
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
@ -326,7 +323,8 @@ pub(crate) fn format_error(e: dlopen2::Error, path: String) -> String {
let mut buf = vec![0; 500];
let path = OsStr::new(&path)
let path = path
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect::<Vec<_>>();
@ -386,7 +384,7 @@ mod tests {
std::io::Error::from_raw_os_error(0x000000C1),
);
assert_eq!(
format_error(err, "foo.dll".to_string()),
format_error(err, &std::path::PathBuf::from("foo.dll")),
"foo.dll is not a valid Win32 application.\r\n".to_string(),
);
}

View file

@ -1,12 +1,11 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use deno_core::error::AnyError;
use deno_core::OpState;
use std::mem::size_of;
use std::os::raw::c_char;
use std::os::raw::c_short;
use std::path::Path;
use std::path::PathBuf;
mod call;
mod callback;
@ -41,22 +40,29 @@ const _: () = {
pub const UNSTABLE_FEATURE_NAME: &str = "ffi";
fn check_unstable(state: &OpState, api_name: &str) {
// TODO(bartlomieju): replace with `state.feature_checker.check_or_exit`
// once we phase out `check_or_exit_with_legacy_fallback`
state
.feature_checker
.check_or_exit_with_legacy_fallback(UNSTABLE_FEATURE_NAME, api_name)
}
pub trait FfiPermissions {
fn check_partial(&mut self, path: Option<&Path>) -> Result<(), AnyError>;
fn check_partial_no_path(&mut self) -> Result<(), AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_partial_with_path(
&mut self,
path: &str,
) -> Result<PathBuf, AnyError>;
}
impl FfiPermissions for deno_permissions::PermissionsContainer {
#[inline(always)]
fn check_partial(&mut self, path: Option<&Path>) -> Result<(), AnyError> {
deno_permissions::PermissionsContainer::check_ffi_partial(self, path)
fn check_partial_no_path(&mut self) -> Result<(), AnyError> {
deno_permissions::PermissionsContainer::check_ffi_partial_no_path(self)
}
#[inline(always)]
fn check_partial_with_path(
&mut self,
path: &str,
) -> Result<PathBuf, AnyError> {
deno_permissions::PermissionsContainer::check_ffi_partial_with_path(
self, path,
)
}
}

View file

@ -1,6 +1,5 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use crate::check_unstable;
use crate::FfiPermissions;
use deno_core::error::range_error;
use deno_core::error::type_error;
@ -21,9 +20,8 @@ pub fn op_ffi_ptr_create<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointer#create");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
Ok(ptr_number as *mut c_void)
}
@ -37,9 +35,8 @@ pub fn op_ffi_ptr_equals<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointer#equals");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
Ok(a == b)
}
@ -52,9 +49,8 @@ pub fn op_ffi_ptr_of<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointer#of");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
Ok(buf as *mut c_void)
}
@ -67,9 +63,8 @@ pub fn op_ffi_ptr_of_exact<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointer#of");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
let Some(buf) = buf.get_backing_store() else {
return Ok(0 as _);
@ -89,9 +84,8 @@ pub fn op_ffi_ptr_offset<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointer#offset");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid pointer to offset, pointer is null"));
@ -120,9 +114,8 @@ pub fn op_ffi_ptr_value<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointer#value");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
Ok(ptr as usize)
}
@ -138,10 +131,8 @@ pub fn op_ffi_get_buf<FP, 'scope>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getArrayBuffer");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid ArrayBuffer pointer, pointer is null"));
@ -172,10 +163,8 @@ pub fn op_ffi_buf_copy_into<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#copyInto");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if src.is_null() {
Err(type_error("Invalid ArrayBuffer pointer, pointer is null"))
@ -205,10 +194,8 @@ pub fn op_ffi_cstr_read<FP, 'scope>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getCString");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid CString pointer, pointer is null"));
@ -233,10 +220,8 @@ pub fn op_ffi_read_bool<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getBool");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid bool pointer, pointer is null"));
@ -255,10 +240,8 @@ pub fn op_ffi_read_u8<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getUint8");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid u8 pointer, pointer is null"));
@ -279,10 +262,8 @@ pub fn op_ffi_read_i8<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getInt8");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid i8 pointer, pointer is null"));
@ -303,10 +284,8 @@ pub fn op_ffi_read_u16<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getUint16");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid u16 pointer, pointer is null"));
@ -327,10 +306,8 @@ pub fn op_ffi_read_i16<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getInt16");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid i16 pointer, pointer is null"));
@ -351,10 +328,8 @@ pub fn op_ffi_read_u32<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getUint32");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid u32 pointer, pointer is null"));
@ -373,10 +348,8 @@ pub fn op_ffi_read_i32<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getInt32");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid i32 pointer, pointer is null"));
@ -398,10 +371,8 @@ pub fn op_ffi_read_u64<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getBigUint64");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid u64 pointer, pointer is null"));
@ -426,10 +397,8 @@ pub fn op_ffi_read_i64<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getBigInt64");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid i64 pointer, pointer is null"));
@ -451,10 +420,8 @@ pub fn op_ffi_read_f32<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getFloat32");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid f32 pointer, pointer is null"));
@ -473,10 +440,8 @@ pub fn op_ffi_read_f64<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getFloat64");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid f64 pointer, pointer is null"));
@ -495,10 +460,8 @@ pub fn op_ffi_read_ptr<FP>(
where
FP: FfiPermissions + 'static,
{
check_unstable(state, "Deno.UnsafePointerView#getPointer");
let permissions = state.borrow_mut::<FP>();
permissions.check_partial(None)?;
permissions.check_partial_no_path()?;
if ptr.is_null() {
return Err(type_error("Invalid pointer pointer, pointer is null"));

View file

@ -1,6 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { core, internals, primordials } from "ext:core/mod.js";
import { core, primordials } from "ext:core/mod.js";
const {
isDate,
internalRidSymbol,
@ -15,15 +15,15 @@ import {
op_fs_copy_file_async,
op_fs_copy_file_sync,
op_fs_cwd,
op_fs_fdatasync_async,
op_fs_fdatasync_sync,
op_fs_file_stat_async,
op_fs_file_stat_sync,
op_fs_file_sync_async,
op_fs_file_sync_data_async,
op_fs_file_sync_data_sync,
op_fs_file_sync_sync,
op_fs_file_truncate_async,
op_fs_flock_async,
op_fs_flock_sync,
op_fs_fsync_async,
op_fs_fsync_sync,
op_fs_ftruncate_sync,
op_fs_funlock_async,
op_fs_funlock_sync,
@ -517,22 +517,6 @@ async function symlink(
);
}
function fdatasyncSync(rid) {
op_fs_fdatasync_sync(rid);
}
async function fdatasync(rid) {
await op_fs_fdatasync_async(rid);
}
function fsyncSync(rid) {
op_fs_fsync_sync(rid);
}
async function fsync(rid) {
await op_fs_fsync_async(rid);
}
function openSync(
path,
options,
@ -597,15 +581,6 @@ class FsFile {
}
}
get rid() {
internals.warnOnDeprecatedApi(
"Deno.FsFile.rid",
new Error().stack,
"Use `Deno.FsFile` methods directly instead.",
);
return this.#rid;
}
write(p) {
return write(this.#rid, p);
}
@ -648,11 +623,11 @@ class FsFile {
}
async syncData() {
await op_fs_fdatasync_async(this.#rid);
await op_fs_file_sync_data_async(this.#rid);
}
syncDataSync() {
op_fs_fdatasync_sync(this.#rid);
op_fs_file_sync_data_sync(this.#rid);
}
close() {
@ -674,11 +649,11 @@ class FsFile {
}
async sync() {
await op_fs_fsync_async(this.#rid);
await op_fs_file_sync_async(this.#rid);
}
syncSync() {
op_fs_fsync_sync(this.#rid);
op_fs_file_sync_sync(this.#rid);
}
async utime(atime, mtime) {
@ -914,11 +889,7 @@ export {
create,
createSync,
cwd,
fdatasync,
fdatasyncSync,
FsFile,
fsync,
fsyncSync,
link,
linkSync,
lstat,

View file

@ -21,10 +21,10 @@ pub use crate::sync::MaybeSync;
use crate::ops::*;
use deno_core::error::AnyError;
use deno_core::OpState;
use deno_io::fs::FsError;
use std::borrow::Cow;
use std::path::Path;
use std::path::PathBuf;
pub trait FsPermissions {
fn check_open<'a>(
@ -35,8 +35,18 @@ pub trait FsPermissions {
path: &'a Path,
api_name: &str,
) -> Result<std::borrow::Cow<'a, Path>, FsError>;
fn check_read(&mut self, path: &Path, api_name: &str)
-> Result<(), AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_read(
&mut self,
path: &str,
api_name: &str,
) -> Result<PathBuf, AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_read_path<'a>(
&mut self,
path: &'a Path,
api_name: &str,
) -> Result<Cow<'a, Path>, AnyError>;
fn check_read_all(&mut self, api_name: &str) -> Result<(), AnyError>;
fn check_read_blind(
&mut self,
@ -44,16 +54,24 @@ pub trait FsPermissions {
display: &str,
api_name: &str,
) -> Result<(), AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_write(
&mut self,
path: &Path,
path: &str,
api_name: &str,
) -> Result<(), AnyError>;
) -> Result<PathBuf, AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_write_path<'a>(
&mut self,
path: &'a Path,
api_name: &str,
) -> Result<Cow<'a, Path>, AnyError>;
#[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"]
fn check_write_partial(
&mut self,
path: &Path,
path: &str,
api_name: &str,
) -> Result<(), AnyError>;
) -> Result<PathBuf, AnyError>;
fn check_write_all(&mut self, api_name: &str) -> Result<(), AnyError>;
fn check_write_blind(
&mut self,
@ -91,31 +109,50 @@ impl FsPermissions for deno_permissions::PermissionsContainer {
if resolved {
self
.check_special_file(path, api_name)
.map_err(FsError::PermissionDenied)?;
.map_err(FsError::NotCapable)?;
return Ok(Cow::Borrowed(path));
}
// If somehow read or write aren't specified, use read
let read = read || !write;
let mut path: Cow<'a, Path> = Cow::Borrowed(path);
if read {
FsPermissions::check_read(self, path, api_name)
.map_err(|_| FsError::PermissionDenied("read"))?;
let resolved_path = FsPermissions::check_read_path(self, &path, api_name)
.map_err(|_| FsError::NotCapable("read"))?;
if let Cow::Owned(resolved_path) = resolved_path {
path = Cow::Owned(resolved_path);
}
}
if write {
FsPermissions::check_write(self, path, api_name)
.map_err(|_| FsError::PermissionDenied("write"))?;
let resolved_path =
FsPermissions::check_write_path(self, &path, api_name)
.map_err(|_| FsError::NotCapable("write"))?;
if let Cow::Owned(resolved_path) = resolved_path {
path = Cow::Owned(resolved_path);
}
}
Ok(Cow::Borrowed(path))
Ok(path)
}
fn check_read(
&mut self,
path: &Path,
path: &str,
api_name: &str,
) -> Result<(), AnyError> {
) -> Result<PathBuf, AnyError> {
deno_permissions::PermissionsContainer::check_read(self, path, api_name)
}
fn check_read_path<'a>(
&mut self,
path: &'a Path,
api_name: &str,
) -> Result<Cow<'a, Path>, AnyError> {
deno_permissions::PermissionsContainer::check_read_path(
self,
path,
Some(api_name),
)
}
fn check_read_blind(
&mut self,
path: &Path,
@ -129,17 +166,27 @@ impl FsPermissions for deno_permissions::PermissionsContainer {
fn check_write(
&mut self,
path: &Path,
path: &str,
api_name: &str,
) -> Result<(), AnyError> {
) -> Result<PathBuf, AnyError> {
deno_permissions::PermissionsContainer::check_write(self, path, api_name)
}
fn check_write_path<'a>(
&mut self,
path: &'a Path,
api_name: &str,
) -> Result<Cow<'a, Path>, AnyError> {
deno_permissions::PermissionsContainer::check_write_path(
self, path, api_name,
)
}
fn check_write_partial(
&mut self,
path: &Path,
path: &str,
api_name: &str,
) -> Result<(), AnyError> {
) -> Result<PathBuf, AnyError> {
deno_permissions::PermissionsContainer::check_write_partial(
self, path, api_name,
)
@ -167,15 +214,6 @@ impl FsPermissions for deno_permissions::PermissionsContainer {
pub const UNSTABLE_FEATURE_NAME: &str = "fs";
/// Helper for checking unstable features. Used for sync ops.
fn check_unstable(state: &OpState, api_name: &str) {
// TODO(bartlomieju): replace with `state.feature_checker.check_or_exit`
// once we phase out `check_or_exit_with_legacy_fallback`
state
.feature_checker
.check_or_exit_with_legacy_fallback(UNSTABLE_FEATURE_NAME, api_name);
}
deno_core::extension!(deno_fs,
deps = [ deno_web ],
parameters = [P: FsPermissions],
@ -229,10 +267,10 @@ deno_core::extension!(deno_fs,
op_fs_seek_sync,
op_fs_seek_async,
op_fs_fdatasync_sync,
op_fs_fdatasync_async,
op_fs_fsync_sync,
op_fs_fsync_async,
op_fs_file_sync_data_sync,
op_fs_file_sync_data_async,
op_fs_file_sync_sync,
op_fs_file_sync_async,
op_fs_file_stat_sync,
op_fs_file_stat_async,
op_fs_flock_async,

View file

@ -5,6 +5,7 @@ use std::io;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
use std::path::StripPrefixError;
use std::rc::Rc;
use deno_core::anyhow::bail;
@ -26,7 +27,6 @@ use rand::thread_rng;
use rand::Rng;
use serde::Serialize;
use crate::check_unstable;
use crate::interface::AccessCheckFn;
use crate::interface::FileSystemRc;
use crate::interface::FsDirEntry;
@ -60,7 +60,7 @@ fn map_permission_error(
path: &Path,
) -> AnyError {
match error {
FsError::PermissionDenied(err) => {
FsError::NotCapable(err) => {
let path = format!("{path:?}");
let (path, truncated) = if path.len() > 1024 {
(&path[0..1024], "...(truncated)")
@ -74,7 +74,7 @@ fn map_permission_error(
format!(
"Requires {err} access to {path}{truncated}, run again with the --allow-{err} flag")
};
custom_error("PermissionDenied", msg)
custom_error("NotCapable", msg)
}
err => Err::<(), _>(err)
.context_path(operation, path)
@ -106,8 +106,9 @@ pub fn op_fs_chdir<P>(
where
P: FsPermissions + 'static,
{
let d = PathBuf::from(&directory);
state.borrow_mut::<P>().check_read(&d, "Deno.chdir()")?;
let d = state
.borrow_mut::<P>()
.check_read(directory, "Deno.chdir()")?;
state
.borrow::<FileSystemRc>()
.chdir(&d)
@ -121,7 +122,6 @@ pub fn op_fs_umask(
) -> Result<u32, AnyError>
where
{
check_unstable(state, "Deno.umask");
state.borrow::<FileSystemRc>().umask(mask).context("umask")
}
@ -190,11 +190,9 @@ pub fn op_fs_mkdir_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let mode = mode.unwrap_or(0o777) & 0o777;
state
let path = state
.borrow_mut::<P>()
.check_write(&path, "Deno.mkdirSync()")?;
@ -215,14 +213,12 @@ pub async fn op_fs_mkdir_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let mode = mode.unwrap_or(0o777) & 0o777;
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state.borrow_mut::<P>().check_write(&path, "Deno.mkdir()")?;
state.borrow::<FileSystemRc>().clone()
let path = state.borrow_mut::<P>().check_write(&path, "Deno.mkdir()")?;
(state.borrow::<FileSystemRc>().clone(), path)
};
fs.mkdir_async(path.clone(), recursive, mode)
@ -241,8 +237,7 @@ pub fn op_fs_chmod_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_write(&path, "Deno.chmodSync()")?;
let fs = state.borrow::<FileSystemRc>();
@ -259,11 +254,10 @@ pub async fn op_fs_chmod_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state.borrow_mut::<P>().check_write(&path, "Deno.chmod()")?;
state.borrow::<FileSystemRc>().clone()
let path = state.borrow_mut::<P>().check_write(&path, "Deno.chmod()")?;
(state.borrow::<FileSystemRc>().clone(), path)
};
fs.chmod_async(path.clone(), mode)
.await
@ -281,8 +275,7 @@ pub fn op_fs_chown_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_write(&path, "Deno.chownSync()")?;
let fs = state.borrow::<FileSystemRc>();
@ -301,11 +294,10 @@ pub async fn op_fs_chown_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state.borrow_mut::<P>().check_write(&path, "Deno.chown()")?;
state.borrow::<FileSystemRc>().clone()
let path = state.borrow_mut::<P>().check_write(&path, "Deno.chown()")?;
(state.borrow::<FileSystemRc>().clone(), path)
};
fs.chown_async(path.clone(), uid, gid)
.await
@ -322,11 +314,9 @@ pub fn op_fs_remove_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_write(&path, "Deno.removeSync()")?;
.check_write(path, "Deno.removeSync()")?;
let fs = state.borrow::<FileSystemRc>();
fs.remove_sync(&path, recursive)
@ -344,21 +334,19 @@ pub async fn op_fs_remove_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
if recursive {
let path = if recursive {
state
.borrow_mut::<P>()
.check_write(&path, "Deno.remove()")?;
.check_write(&path, "Deno.remove()")?
} else {
state
.borrow_mut::<P>()
.check_write_partial(&path, "Deno.remove()")?;
}
.check_write_partial(&path, "Deno.remove()")?
};
state.borrow::<FileSystemRc>().clone()
(state.borrow::<FileSystemRc>().clone(), path)
};
fs.remove_async(path.clone(), recursive)
@ -377,12 +365,9 @@ pub fn op_fs_copy_file_sync<P>(
where
P: FsPermissions + 'static,
{
let from = PathBuf::from(from);
let to = PathBuf::from(to);
let permissions = state.borrow_mut::<P>();
permissions.check_read(&from, "Deno.copyFileSync()")?;
permissions.check_write(&to, "Deno.copyFileSync()")?;
let from = permissions.check_read(from, "Deno.copyFileSync()")?;
let to = permissions.check_write(to, "Deno.copyFileSync()")?;
let fs = state.borrow::<FileSystemRc>();
fs.copy_file_sync(&from, &to)
@ -400,15 +385,12 @@ pub async fn op_fs_copy_file_async<P>(
where
P: FsPermissions + 'static,
{
let from = PathBuf::from(from);
let to = PathBuf::from(to);
let fs = {
let (fs, from, to) = {
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&from, "Deno.copyFile()")?;
permissions.check_write(&to, "Deno.copyFile()")?;
state.borrow::<FileSystemRc>().clone()
let from = permissions.check_read(&from, "Deno.copyFile()")?;
let to = permissions.check_write(&to, "Deno.copyFile()")?;
(state.borrow::<FileSystemRc>().clone(), from, to)
};
fs.copy_file_async(from.clone(), to.clone())
@ -427,8 +409,7 @@ pub fn op_fs_stat_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_read(&path, "Deno.statSync()")?;
let fs = state.borrow::<FileSystemRc>();
@ -447,12 +428,11 @@ pub async fn op_fs_stat_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&path, "Deno.stat()")?;
state.borrow::<FileSystemRc>().clone()
let path = permissions.check_read(&path, "Deno.stat()")?;
(state.borrow::<FileSystemRc>().clone(), path)
};
let stat = fs
.stat_async(path.clone())
@ -470,8 +450,7 @@ pub fn op_fs_lstat_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_read(&path, "Deno.lstatSync()")?;
let fs = state.borrow::<FileSystemRc>();
@ -490,12 +469,11 @@ pub async fn op_fs_lstat_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&path, "Deno.lstat()")?;
state.borrow::<FileSystemRc>().clone()
let path = permissions.check_read(&path, "Deno.lstat()")?;
(state.borrow::<FileSystemRc>().clone(), path)
};
let stat = fs
.lstat_async(path.clone())
@ -513,11 +491,9 @@ pub fn op_fs_realpath_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = state.borrow::<FileSystemRc>().clone();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&path, "Deno.realPathSync()")?;
let path = permissions.check_read(&path, "Deno.realPathSync()")?;
if path.is_relative() {
permissions.check_read_blind(&fs.cwd()?, "CWD", "Deno.realPathSync()")?;
}
@ -538,18 +514,16 @@ pub async fn op_fs_realpath_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs;
{
let (fs, path) = {
let mut state = state.borrow_mut();
fs = state.borrow::<FileSystemRc>().clone();
let fs = state.borrow::<FileSystemRc>().clone();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&path, "Deno.realPath()")?;
let path = permissions.check_read(&path, "Deno.realPath()")?;
if path.is_relative() {
permissions.check_read_blind(&fs.cwd()?, "CWD", "Deno.realPath()")?;
}
}
(fs, path)
};
let resolved_path = fs
.realpath_async(path.clone())
.await
@ -568,9 +542,7 @@ pub fn op_fs_read_dir_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_read(&path, "Deno.readDirSync()")?;
@ -589,14 +561,12 @@ pub async fn op_fs_read_dir_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state
let path = state
.borrow_mut::<P>()
.check_read(&path, "Deno.readDir()")?;
state.borrow::<FileSystemRc>().clone()
(state.borrow::<FileSystemRc>().clone(), path)
};
let entries = fs
@ -616,13 +586,10 @@ pub fn op_fs_rename_sync<P>(
where
P: FsPermissions + 'static,
{
let oldpath = PathBuf::from(oldpath);
let newpath = PathBuf::from(newpath);
let permissions = state.borrow_mut::<P>();
permissions.check_read(&oldpath, "Deno.renameSync()")?;
permissions.check_write(&oldpath, "Deno.renameSync()")?;
permissions.check_write(&newpath, "Deno.renameSync()")?;
let _ = permissions.check_read(&oldpath, "Deno.renameSync()")?;
let oldpath = permissions.check_write(&oldpath, "Deno.renameSync()")?;
let newpath = permissions.check_write(&newpath, "Deno.renameSync()")?;
let fs = state.borrow::<FileSystemRc>();
fs.rename_sync(&oldpath, &newpath)
@ -640,16 +607,13 @@ pub async fn op_fs_rename_async<P>(
where
P: FsPermissions + 'static,
{
let oldpath = PathBuf::from(oldpath);
let newpath = PathBuf::from(newpath);
let fs = {
let (fs, oldpath, newpath) = {
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&oldpath, "Deno.rename()")?;
permissions.check_write(&oldpath, "Deno.rename()")?;
permissions.check_write(&newpath, "Deno.rename()")?;
state.borrow::<FileSystemRc>().clone()
_ = permissions.check_read(&oldpath, "Deno.rename()")?;
let oldpath = permissions.check_write(&oldpath, "Deno.rename()")?;
let newpath = permissions.check_write(&newpath, "Deno.rename()")?;
(state.borrow::<FileSystemRc>().clone(), oldpath, newpath)
};
fs.rename_async(oldpath.clone(), newpath.clone())
@ -668,14 +632,11 @@ pub fn op_fs_link_sync<P>(
where
P: FsPermissions + 'static,
{
let oldpath = PathBuf::from(oldpath);
let newpath = PathBuf::from(newpath);
let permissions = state.borrow_mut::<P>();
permissions.check_read(&oldpath, "Deno.linkSync()")?;
permissions.check_write(&oldpath, "Deno.linkSync()")?;
permissions.check_read(&newpath, "Deno.linkSync()")?;
permissions.check_write(&newpath, "Deno.linkSync()")?;
_ = permissions.check_read(oldpath, "Deno.linkSync()")?;
let oldpath = permissions.check_write(oldpath, "Deno.linkSync()")?;
_ = permissions.check_read(newpath, "Deno.linkSync()")?;
let newpath = permissions.check_write(newpath, "Deno.linkSync()")?;
let fs = state.borrow::<FileSystemRc>();
fs.link_sync(&oldpath, &newpath)
@ -693,17 +654,14 @@ pub async fn op_fs_link_async<P>(
where
P: FsPermissions + 'static,
{
let oldpath = PathBuf::from(&oldpath);
let newpath = PathBuf::from(&newpath);
let fs = {
let (fs, oldpath, newpath) = {
let mut state = state.borrow_mut();
let permissions = state.borrow_mut::<P>();
permissions.check_read(&oldpath, "Deno.link()")?;
permissions.check_write(&oldpath, "Deno.link()")?;
permissions.check_read(&newpath, "Deno.link()")?;
permissions.check_write(&newpath, "Deno.link()")?;
state.borrow::<FileSystemRc>().clone()
_ = permissions.check_read(&oldpath, "Deno.link()")?;
let oldpath = permissions.check_write(&oldpath, "Deno.link()")?;
_ = permissions.check_read(&newpath, "Deno.link()")?;
let newpath = permissions.check_write(&newpath, "Deno.link()")?;
(state.borrow::<FileSystemRc>().clone(), oldpath, newpath)
};
fs.link_async(oldpath.clone(), newpath.clone())
@ -774,9 +732,7 @@ pub fn op_fs_read_link_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_read(&path, "Deno.readLink()")?;
@ -796,14 +752,12 @@ pub async fn op_fs_read_link_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state
let path = state
.borrow_mut::<P>()
.check_read(&path, "Deno.readLink()")?;
state.borrow::<FileSystemRc>().clone()
(state.borrow::<FileSystemRc>().clone(), path)
};
let target = fs
@ -823,11 +777,9 @@ pub fn op_fs_truncate_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state
let path = state
.borrow_mut::<P>()
.check_write(&path, "Deno.truncateSync()")?;
.check_write(path, "Deno.truncateSync()")?;
let fs = state.borrow::<FileSystemRc>();
fs.truncate_sync(&path, len)
@ -845,14 +797,12 @@ pub async fn op_fs_truncate_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state
let path = state
.borrow_mut::<P>()
.check_write(&path, "Deno.truncate()")?;
state.borrow::<FileSystemRc>().clone()
(state.borrow::<FileSystemRc>().clone(), path)
};
fs.truncate_async(path.clone(), len)
@ -874,9 +824,7 @@ pub fn op_fs_utime_sync<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
state.borrow_mut::<P>().check_write(&path, "Deno.utime()")?;
let path = state.borrow_mut::<P>().check_write(path, "Deno.utime()")?;
let fs = state.borrow::<FileSystemRc>();
fs.utime_sync(&path, atime_secs, atime_nanos, mtime_secs, mtime_nanos)
@ -897,12 +845,10 @@ pub async fn op_fs_utime_async<P>(
where
P: FsPermissions + 'static,
{
let path = PathBuf::from(path);
let fs = {
let (fs, path) = {
let mut state = state.borrow_mut();
state.borrow_mut::<P>().check_write(&path, "Deno.utime()")?;
state.borrow::<FileSystemRc>().clone()
let path = state.borrow_mut::<P>().check_write(&path, "Deno.utime()")?;
(state.borrow::<FileSystemRc>().clone(), path)
};
fs.utime_async(
@ -922,15 +868,18 @@ where
#[string]
pub fn op_fs_make_temp_dir_sync<P>(
state: &mut OpState,
#[string] dir: Option<String>,
#[string] dir_arg: Option<String>,
#[string] prefix: Option<String>,
#[string] suffix: Option<String>,
) -> Result<String, AnyError>
where
P: FsPermissions + 'static,
{
let (dir, fs) =
make_temp_check_sync::<P>(state, dir, "Deno.makeTempDirSync()")?;
let (dir, fs) = make_temp_check_sync::<P>(
state,
dir_arg.as_deref(),
"Deno.makeTempDirSync()",
)?;
let mut rng = thread_rng();
@ -938,7 +887,11 @@ where
for _ in 0..MAX_TRIES {
let path = tmp_name(&mut rng, &dir, prefix.as_deref(), suffix.as_deref())?;
match fs.mkdir_sync(&path, false, 0o700) {
Ok(_) => return path_into_string(path.into_os_string()),
Ok(_) => {
// PERMISSIONS: ensure the absolute path is not leaked
let path = strip_dir_prefix(&dir, dir_arg.as_deref(), path)?;
return path_into_string(path.into_os_string());
}
Err(FsError::Io(ref e)) if e.kind() == io::ErrorKind::AlreadyExists => {
continue;
}
@ -957,14 +910,18 @@ where
#[string]
pub async fn op_fs_make_temp_dir_async<P>(
state: Rc<RefCell<OpState>>,
#[string] dir: Option<String>,
#[string] dir_arg: Option<String>,
#[string] prefix: Option<String>,
#[string] suffix: Option<String>,
) -> Result<String, AnyError>
where
P: FsPermissions + 'static,
{
let (dir, fs) = make_temp_check_async::<P>(state, dir, "Deno.makeTempDir()")?;
let (dir, fs) = make_temp_check_async::<P>(
state,
dir_arg.as_deref(),
"Deno.makeTempDir()",
)?;
let mut rng = thread_rng();
@ -972,7 +929,11 @@ where
for _ in 0..MAX_TRIES {
let path = tmp_name(&mut rng, &dir, prefix.as_deref(), suffix.as_deref())?;
match fs.clone().mkdir_async(path.clone(), false, 0o700).await {
Ok(_) => return path_into_string(path.into_os_string()),
Ok(_) => {
// PERMISSIONS: ensure the absolute path is not leaked
let path = strip_dir_prefix(&dir, dir_arg.as_deref(), path)?;
return path_into_string(path.into_os_string());
}
Err(FsError::Io(ref e)) if e.kind() == io::ErrorKind::AlreadyExists => {
continue;
}
@ -991,15 +952,18 @@ where
#[string]
pub fn op_fs_make_temp_file_sync<P>(
state: &mut OpState,
#[string] dir: Option<String>,
#[string] dir_arg: Option<String>,
#[string] prefix: Option<String>,
#[string] suffix: Option<String>,
) -> Result<String, AnyError>
where
P: FsPermissions + 'static,
{
let (dir, fs) =
make_temp_check_sync::<P>(state, dir, "Deno.makeTempFileSync()")?;
let (dir, fs) = make_temp_check_sync::<P>(
state,
dir_arg.as_deref(),
"Deno.makeTempFileSync()",
)?;
let open_opts = OpenOptions {
write: true,
@ -1013,7 +977,11 @@ where
for _ in 0..MAX_TRIES {
let path = tmp_name(&mut rng, &dir, prefix.as_deref(), suffix.as_deref())?;
match fs.open_sync(&path, open_opts, None) {
Ok(_) => return path_into_string(path.into_os_string()),
Ok(_) => {
// PERMISSIONS: ensure the absolute path is not leaked
let path = strip_dir_prefix(&dir, dir_arg.as_deref(), path)?;
return path_into_string(path.into_os_string());
}
Err(FsError::Io(ref e)) if e.kind() == io::ErrorKind::AlreadyExists => {
continue;
}
@ -1032,15 +1000,18 @@ where
#[string]
pub async fn op_fs_make_temp_file_async<P>(
state: Rc<RefCell<OpState>>,
#[string] dir: Option<String>,
#[string] dir_arg: Option<String>,
#[string] prefix: Option<String>,
#[string] suffix: Option<String>,
) -> Result<String, AnyError>
where
P: FsPermissions + 'static,
{
let (dir, fs) =
make_temp_check_async::<P>(state, dir, "Deno.makeTempFile()")?;
let (dir, fs) = make_temp_check_async::<P>(
state,
dir_arg.as_deref(),
"Deno.makeTempFile()",
)?;
let open_opts = OpenOptions {
write: true,
@ -1055,7 +1026,11 @@ where
for _ in 0..MAX_TRIES {
let path = tmp_name(&mut rng, &dir, prefix.as_deref(), suffix.as_deref())?;
match fs.clone().open_async(path.clone(), open_opts, None).await {
Ok(_) => return path_into_string(path.into_os_string()),
Ok(_) => {
// PERMISSIONS: ensure the absolute path is not leaked
let path = strip_dir_prefix(&dir, dir_arg.as_deref(), path)?;
return path_into_string(path.into_os_string());
}
Err(FsError::Io(ref e)) if e.kind() == io::ErrorKind::AlreadyExists => {
continue;
}
@ -1069,9 +1044,26 @@ where
.context("tmpfile")
}
fn strip_dir_prefix(
resolved_dir: &Path,
dir_arg: Option<&str>,
result_path: PathBuf,
) -> Result<PathBuf, StripPrefixError> {
if resolved_dir.is_absolute() {
match &dir_arg {
Some(dir_arg) => {
Ok(Path::new(dir_arg).join(result_path.strip_prefix(resolved_dir)?))
}
None => Ok(result_path),
}
} else {
Ok(result_path)
}
}
fn make_temp_check_sync<P>(
state: &mut OpState,
dir: Option<String>,
dir: Option<&str>,
api_name: &str,
) -> Result<(PathBuf, FileSystemRc), AnyError>
where
@ -1079,11 +1071,7 @@ where
{
let fs = state.borrow::<FileSystemRc>().clone();
let dir = match dir {
Some(dir) => {
let dir = PathBuf::from(dir);
state.borrow_mut::<P>().check_write(&dir, api_name)?;
dir
}
Some(dir) => state.borrow_mut::<P>().check_write(dir, api_name)?,
None => {
let dir = fs.tmp_dir().context("tmpdir")?;
state
@ -1097,7 +1085,7 @@ where
fn make_temp_check_async<P>(
state: Rc<RefCell<OpState>>,
dir: Option<String>,
dir: Option<&str>,
api_name: &str,
) -> Result<(PathBuf, FileSystemRc), AnyError>
where
@ -1106,11 +1094,7 @@ where
let mut state = state.borrow_mut();
let fs = state.borrow::<FileSystemRc>().clone();
let dir = match dir {
Some(dir) => {
let dir = PathBuf::from(dir);
state.borrow_mut::<P>().check_write(&dir, api_name)?;
dir
}
Some(dir) => state.borrow_mut::<P>().check_write(dir, api_name)?,
None => {
let dir = fs.tmp_dir().context("tmpdir")?;
state
@ -1430,7 +1414,7 @@ pub async fn op_fs_seek_async(
}
#[op2(fast)]
pub fn op_fs_fdatasync_sync(
pub fn op_fs_file_sync_data_sync(
state: &mut OpState,
#[smi] rid: ResourceId,
) -> Result<(), AnyError> {
@ -1440,7 +1424,7 @@ pub fn op_fs_fdatasync_sync(
}
#[op2(async)]
pub async fn op_fs_fdatasync_async(
pub async fn op_fs_file_sync_data_async(
state: Rc<RefCell<OpState>>,
#[smi] rid: ResourceId,
) -> Result<(), AnyError> {
@ -1450,7 +1434,7 @@ pub async fn op_fs_fdatasync_async(
}
#[op2(fast)]
pub fn op_fs_fsync_sync(
pub fn op_fs_file_sync_sync(
state: &mut OpState,
#[smi] rid: ResourceId,
) -> Result<(), AnyError> {
@ -1460,7 +1444,7 @@ pub fn op_fs_fsync_sync(
}
#[op2(async)]
pub async fn op_fs_fsync_async(
pub async fn op_fs_file_sync_async(
state: Rc<RefCell<OpState>>,
#[smi] rid: ResourceId,
) -> Result<(), AnyError> {

View file

@ -1069,8 +1069,10 @@ fn open_with_access_check(
};
(*access_check)(false, &path, &options)?;
// On Linux, /proc may contain magic links that we don't want to resolve
let needs_canonicalization = !is_windows_device_path
&& (!cfg!(target_os = "linux") || path.starts_with("/proc"));
let is_linux_special_path = cfg!(target_os = "linux")
&& (path.starts_with("/proc") || path.starts_with("/dev"));
let needs_canonicalization =
!is_windows_device_path && !is_linux_special_path;
let path = if needs_canonicalization {
match path.canonicalize() {
Ok(path) => path,

View file

@ -646,7 +646,7 @@ function serve(arg1, arg2) {
options.onListen(listener.addr);
} else {
// deno-lint-ignore no-console
console.log(`Listening on ${path}`);
console.error(`Listening on ${path}`);
}
});
}
@ -695,7 +695,7 @@ function serve(arg1, arg2) {
const host = formatHostName(addr.hostname);
// deno-lint-ignore no-console
console.log(`Listening on ${scheme}${host}:${addr.port}/`);
console.error(`Listening on ${scheme}${host}:${addr.port}/`);
}
};
@ -871,7 +871,7 @@ function registerDeclarativeServer(exports) {
const host = formatHostName(hostname);
// deno-lint-ignore no-console
console.debug(
console.error(
`%cdeno serve%c: Listening on %chttp://${host}:${port}/%c${nThreads}`,
"color: green",
"color: inherit",
@ -880,8 +880,8 @@ function registerDeclarativeServer(exports) {
);
}
},
handler: (req) => {
return exports.fetch(req);
handler: (req, connInfo) => {
return exports.fetch(req, connInfo);
},
});
};

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