diff --git a/.dprintrc.json b/.dprintrc.json index dfa68783c24de0..204bbd1f6332f7 100644 --- a/.dprintrc.json +++ b/.dprintrc.json @@ -14,6 +14,7 @@ "excludes": [ ".cargo_home", "cli/dts", + "cli/tests/encoding", "cli/tsc/*typescript.js", "gh-pages", "std/**/testdata", @@ -24,8 +25,8 @@ "third_party" ], "plugins": [ - "https://plugins.dprint.dev/typescript-0.19.9.wasm", - "https://plugins.dprint.dev/json-0.4.1.wasm", - "https://plugins.dprint.dev/markdown-0.2.4.wasm" + "https://plugins.dprint.dev/typescript-0.29.0.wasm", + "https://plugins.dprint.dev/json-0.7.0.wasm", + "https://plugins.dprint.dev/markdown-0.4.0.wasm" ] } diff --git a/.gitattributes b/.gitattributes index 5abb4177686788..00d74b78499b11 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,7 +2,13 @@ * text=auto eol=lf *.png -text +/cli/tests/encoding/* -text + # Tell git which symlinks point to files, and which ones point to directories. # This is relevant for Windows only, and requires git >= 2.19.2 to work. -/core/libdeno/* symlink=dir /cli/tests/symlink_to_subdir symlink=dir + +# Tell github these are vendored files. +# Doesn't include them in the language statistics. +/cli/tsc/00_typescript.js linguist-vendored +/cli/dts/* linguist-vendored diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d77954b5f04dc..09a0b443d424e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: config: - - os: macOS-latest + - os: macos-10.15 kind: test_release - os: windows-2019 kind: test_release @@ -61,12 +61,12 @@ jobs: !startsWith(github.ref, 'refs/tags/std/') run: | mkdir -p target/release - tar --exclude=.cargo_home --exclude=".git*" --exclude=target --exclude=deno_typescript/typescript/tests --exclude=third_party/cpplint --exclude=third_party/node_modules --exclude=third_party/python_packages --exclude=third_party/prebuilt -czvf target/release/deno_src.tar.gz -C .. deno + tar --exclude=.cargo_home --exclude=".git*" --exclude=target --exclude=third_party/node_modules --exclude=third_party/python_packages --exclude=third_party/prebuilt -czvf target/release/deno_src.tar.gz -C .. deno - name: Install rust uses: hecrj/setup-rust-action@v1 with: - rust-version: 1.45.0 + rust-version: 1.45.2 - name: Install rust targets run: | @@ -233,9 +233,10 @@ jobs: run: | cd core cargo publish - cd ../deno_typescript sleep 30 + cd ../op_crates/web cargo publish - cd ../cli + sleep 30 + cd ../../cli sleep 30 cargo publish diff --git a/Cargo.lock b/Cargo.lock index 31f53cf939c7e8..d4b13b7b230d23 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16,15 +16,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee2a4ec343196209d6594e19543ae87a39f96d5534d7174822a3ad825dd6ed7e" -[[package]] -name = "ahash" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8fd72866655d1904d6b0997d0b07ba561047d070fbe29de039031c641b61217" -dependencies = [ - "const-random", -] - [[package]] name = "aho-corasick" version = "0.7.13" @@ -70,18 +61,24 @@ version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d25d88fd6b8041580a654f9d0c581a047baee2b3efee13275f2fc392fc75034" +[[package]] +name = "arrayvec" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" + [[package]] name = "ast_node" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa87dd2848313961eec40d0625ac425cd9e8bb75988382a247484b7aa3805e5d" +checksum = "fd6ee2941db3551563d29eaf5214cd3d7b2f322e0c0e3954f5ae020f860bae8c" dependencies = [ "darling", "pmutil", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", "swc_macros_common", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -91,7 +88,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9021768bcce77296b64648cc7a7460e3df99979b97ed5c925c38d1cc83778d98" dependencies = [ "brotli", - "bytes 0.5.5", + "bytes", "flate2", "futures-core", "memchr", @@ -121,15 +118,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" -[[package]] -name = "base64" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e" -dependencies = [ - "byteorder", -] - [[package]] name = "base64" version = "0.11.0" @@ -220,22 +208,9 @@ checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" [[package]] name = "bytes" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c" -dependencies = [ - "byteorder", - "iovec", -] - -[[package]] -name = "bytes" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "118cf036fbb97d0816e3c34b2d7a1e8cfc60f68fcf63d550ddbe9bd5f59c213b" -dependencies = [ - "loom", -] +checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38" [[package]] name = "cargo_gn" @@ -257,9 +232,9 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "clap" -version = "2.33.1" +version = "2.33.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdfa80d47f954d53a35a64987ca1422f495b8d6483c0fe9f7117b36c2a792129" +checksum = "10040cdf04294b565d9e0319955430099ec3813a64c952b86a41200ad714ae48" dependencies = [ "ansi_term", "atty", @@ -279,26 +254,6 @@ dependencies = [ "bitflags", ] -[[package]] -name = "const-random" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f1af9ac737b2dd2d577701e59fd09ba34822f6f2ebdb30a7647405d9e55e16a" -dependencies = [ - "const-random-macro", - "proc-macro-hack", -] - -[[package]] -name = "const-random-macro" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e4c606eb459dd29f7c57b2e0879f2b6f14ee130918c2b78ccb58a9624e6c7a" -dependencies = [ - "getrandom", - "proc-macro-hack", -] - [[package]] name = "crc32fast" version = "1.2.0" @@ -347,10 +302,10 @@ checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b" dependencies = [ "fnv", "ident_case", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", "strsim 0.9.3", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -361,45 +316,37 @@ checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72" dependencies = [ "darling_core", "quote 1.0.7", - "syn 1.0.33", -] - -[[package]] -name = "dashmap" -version = "3.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93b8a57df1b6a3f0a96df85297d506a871b31252df23f969b9837ccb5d07455c" -dependencies = [ - "ahash", - "cfg-if", - "num_cpus", + "syn 1.0.36", ] [[package]] name = "deno" -version = "1.2.0" +version = "1.3.1" dependencies = [ "atty", "base64 0.12.3", "byteorder", - "bytes 0.5.5", + "bytes", "clap", "deno_core", + "deno_doc", "deno_lint", + "deno_web", "dissimilar", "dlopen", - "futures 0.3.5", + "dprint-plugin-typescript", + "encoding_rs", + "futures", "fwdansi", "http", "idna", "indexmap", "lazy_static", "libc", - "log 0.4.8", + "log 0.4.11", "nix", "notify", "os_pipe", - "pty", "rand 0.7.3", "regex", "reqwest", @@ -410,12 +357,14 @@ dependencies = [ "serde_derive", "serde_json", "sourcemap", + "swc_common", + "swc_ecmascript", "sys-info", "tempfile", "termcolor", "test_util", "tokio", - "tokio-rustls 0.13.1", + "tokio-rustls 0.14.0", "tokio-tungstenite", "url", "utime", @@ -430,43 +379,58 @@ dependencies = [ [[package]] name = "deno_core" -version = "0.49.0" +version = "0.54.0" dependencies = [ - "derive_deref", "downcast-rs", - "futures 0.3.5", + "futures", "lazy_static", "libc", - "log 0.4.8", + "log 0.4.11", "rusty_v8", "serde_json", - "smallvec 1.4.1", + "smallvec", "tokio", "url", ] [[package]] -name = "deno_lint" -version = "0.1.16" +name = "deno_doc" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9215a4316612e7535f104a7cbc0a3ef535d7eb49c963a3c48433759d7f04bb5" +checksum = "c3ee3c1b4b40ed04881bf9c005504fc52dbb2bef879922b1c6ed31119449489d" dependencies = [ - "dprint-plugin-typescript", + "futures", "lazy_static", "regex", - "swc_atoms", - "swc_ecma_visit", + "serde", + "serde_derive", + "serde_json", + "swc_common", + "swc_ecmascript", + "termcolor", ] [[package]] -name = "derive_deref" -version = "1.1.1" +name = "deno_lint" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcdbcee2d9941369faba772587a565f4f534e42cb8d17e5295871de730163b2b" +checksum = "40d72410d84bb82ec20204e4a3ca4de3031edb89090cb6eca84fd1fc798b87d5" dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.7", - "syn 1.0.33", + "lazy_static", + "log 0.4.11", + "regex", + "serde", + "serde_json", + "swc_common", + "swc_ecmascript", +] + +[[package]] +name = "deno_web" +version = "0.4.0" +dependencies = [ + "deno_core", + "futures", ] [[package]] @@ -515,25 +479,23 @@ checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" [[package]] name = "dprint-core" -version = "0.24.0" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb13f434a98b4fc4f35ae52d5130c9bbe2a514f56c3d6529df11df91080fbd8f" +checksum = "fab44561ffc8f70d26d6c4cc81a648ecd47dd60836abecf0599253a7b9fdbf5d" dependencies = [ "serde", ] [[package]] name = "dprint-plugin-typescript" -version = "0.19.8" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c227beb41f4c0e3be999c17f9a292765c7d3cfea3186ae55325907e046ad5fc9" +checksum = "daf2fc659dd444679f15976518fe29866b493ff131f5fd49d1600211559d0201" dependencies = [ "dprint-core", "serde", - "serde_json", "swc_common", - "swc_ecma_ast", - "swc_ecma_parser", + "swc_ecmascript", ] [[package]] @@ -564,9 +526,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e57153e35187d51f08471d5840459ff29093473e7bedd004a1414985aab92f3" dependencies = [ "pmutil", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "swc_macros_common", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -623,9 +585,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "039885ad6579a86b94ad8df696cce8c530da496bf7b07b12fec8d6c4cd654bb9" dependencies = [ "pmutil", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "swc_macros_common", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -669,12 +631,6 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" -[[package]] -name = "futures" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b980f2816d6ee8673b6517b52cb0e808a180efc92e5c19d02cdda79066703ef" - [[package]] name = "futures" version = "0.3.5" @@ -715,7 +671,6 @@ dependencies = [ "futures-core", "futures-task", "futures-util", - "num_cpus", ] [[package]] @@ -731,9 +686,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0b5a30a4328ab5473878237c447333c093297bded83a4983d10f4deea240d39" dependencies = [ "proc-macro-hack", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -757,7 +712,6 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8764574ff08b701a084482c3c7031349104b07ac897393010494beaa18ce32c6" dependencies = [ - "futures 0.1.29", "futures-channel", "futures-core", "futures-io", @@ -770,7 +724,6 @@ dependencies = [ "proc-macro-hack", "proc-macro-nested", "slab", - "tokio-io", ] [[package]] @@ -792,19 +745,6 @@ dependencies = [ "byteorder", ] -[[package]] -name = "generator" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add72f17bb81521258fcc8a7a3245b1e184e916bfbe34f0ea89558f440df5c68" -dependencies = [ - "cc", - "libc", - "log 0.4.8", - "rustc_version", - "winapi 0.3.9", -] - [[package]] name = "generic-array" version = "0.12.3" @@ -831,19 +771,28 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79b7246d7e4b979c03fa093da39cfb3617a96bbeee6310af63991668d7e843ff" dependencies = [ - "bytes 0.5.5", + "bytes", "fnv", "futures-core", "futures-sink", "futures-util", "http", "indexmap", - "log 0.4.8", + "log 0.4.11", "slab", "tokio", "tokio-util", ] +[[package]] +name = "hashbrown" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34f595585f103464d8d2f6e9864682d74c1601fed5e07d62b1c9058dba8246fb" +dependencies = [ + "autocfg 1.0.0", +] + [[package]] name = "headers" version = "0.3.2" @@ -852,7 +801,7 @@ checksum = "ed18eb2459bf1a09ad2d6b1547840c3e5e62882fa09b9a6a20b1de8e3228848f" dependencies = [ "base64 0.12.3", "bitflags", - "bytes 0.5.5", + "bytes", "headers-core", "http", "mime 0.3.16", @@ -884,7 +833,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d569972648b2c512421b5f2a405ad6ac9666547189d0c5477a3f200f3e02f9" dependencies = [ - "bytes 0.5.5", + "bytes", "fnv", "itoa", ] @@ -895,7 +844,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13d5ff830006f7646652e057693569bfe0d51760c0085a071769d142a205111b" dependencies = [ - "bytes 0.5.5", + "bytes", "http", ] @@ -911,7 +860,7 @@ version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6e7655b9594024ad0ee439f3b5a7299369dc2a3f459b47c696f9ff676f9aa1f" dependencies = [ - "bytes 0.5.5", + "bytes", "futures-channel", "futures-core", "futures-util", @@ -920,7 +869,7 @@ dependencies = [ "http-body", "httparse", "itoa", - "log 0.4.8", + "log 0.4.11", "pin-project", "socket2", "time", @@ -931,17 +880,17 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac965ea399ec3a25ac7d13b8affd4b8f39325cca00858ddf5eb29b79e6b14b08" +checksum = "37743cc83e8ee85eacfce90f2f4102030d9ff0a95244098d781e9bee4a90abb6" dependencies = [ - "bytes 0.5.5", + "bytes", "futures-util", "hyper", - "log 0.4.8", - "rustls 0.17.0", + "log 0.4.11", + "rustls 0.18.0", "tokio", - "tokio-rustls 0.13.1", + "tokio-rustls 0.14.0", "webpki", ] @@ -970,11 +919,12 @@ checksum = "c3360c7b59e5ffa2653671fb74b4741a5d343c03f331c0a4aeda42b5c2b0ec7d" [[package]] name = "indexmap" -version = "1.4.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c398b2b113b55809ceb9ee3e753fcbac793f1956663f3c36549c1346015c2afe" +checksum = "86b45e59b16c76b11bf9738fd5d38879d3bd28ad292d7b313608becb17ae2df9" dependencies = [ "autocfg 1.0.0", + "hashbrown", ] [[package]] @@ -1003,7 +953,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19a8a95243d5a0398cae618ec29477c6e3cb631152be5c19481f80bc71559754" dependencies = [ - "bytes 0.5.5", + "bytes", ] [[package]] @@ -1015,6 +965,25 @@ dependencies = [ "libc", ] +[[package]] +name = "ipnet" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47be2f14c678be2fdcab04ab1171db51b2762ce6f0a8ee87c8dd4a04ed216135" + +[[package]] +name = "is-macro" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04807f3dc9e3ea39af3f8469a5297267faf94859637afb836b33f47d9b2650ee" +dependencies = [ + "Inflector", + "pmutil", + "proc-macro2 1.0.19", + "quote 1.0.7", + "syn 1.0.36", +] + [[package]] name = "itoa" version = "0.4.6" @@ -1030,6 +999,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsdoc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4e7d036004e0fd899c705945f16a1ad6c1d45e52fbdeeea054ad60e8db152c4" +dependencies = [ + "nom", + "serde", + "swc_atoms", + "swc_common", +] + [[package]] name = "kernel32-sys" version = "0.2.2" @@ -1053,20 +1034,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" [[package]] -name = "libc" -version = "0.2.72" +name = "lexical-core" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9f8082297d534141b30c8d39e9b1773713ab50fdbe4ff30f750d063b3bfd701" +checksum = "db65c6da02e61f55dae90a0ae427b2a5f6b3e8db09f58d10efab23af92592616" +dependencies = [ + "arrayvec", + "bitflags", + "cfg-if", + "ryu", + "static_assertions", +] [[package]] -name = "lock_api" -version = "0.1.5" +name = "libc" +version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c" -dependencies = [ - "owning_ref", - "scopeguard 0.3.3", -] +checksum = "a2f02823cf78b754822df5f7f268fb59822e7296276d3e069d8e8cb26a14bd10" [[package]] name = "log" @@ -1074,29 +1058,18 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b" dependencies = [ - "log 0.4.8", + "log 0.4.11", ] [[package]] name = "log" -version = "0.4.8" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b" dependencies = [ "cfg-if", ] -[[package]] -name = "loom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ecc775857611e1df29abba5c41355cdf540e7e9d4acfdf0f355eefee82330b7" -dependencies = [ - "cfg-if", - "generator", - "scoped-tls 0.1.2", -] - [[package]] name = "matches" version = "0.1.8" @@ -1173,7 +1146,7 @@ dependencies = [ "iovec", "kernel32-sys", "libc", - "log 0.4.8", + "log 0.4.11", "miow 0.2.1", "net2", "slab", @@ -1187,7 +1160,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" dependencies = [ "lazycell", - "log 0.4.8", + "log 0.4.11", "mio", "slab", ] @@ -1198,7 +1171,7 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0840c1c50fd55e521b247f949c241c9997709f23bd7f023b9762cd561e935656" dependencies = [ - "log 0.4.8", + "log 0.4.11", "mio", "miow 0.3.5", "winapi 0.3.9", @@ -1245,7 +1218,7 @@ checksum = "136eed74cadb9edd2651ffba732b19a450316b680e4f48d6c79e905799e19d01" dependencies = [ "buf_redux", "httparse", - "log 0.4.8", + "log 0.4.11", "mime 0.2.6", "mime_guess 1.8.8", "quick-error", @@ -1285,6 +1258,17 @@ dependencies = [ "void", ] +[[package]] +name = "nom" +version = "5.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb4262d26ed83a1c0a33a38fe2bb15797329c85770da05e6b828ddb782627af" +dependencies = [ + "lexical-core", + "memchr", + "version_check 0.9.2", +] + [[package]] name = "notify" version = "5.0.0-pre.3" @@ -1358,6 +1342,15 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" +[[package]] +name = "ordered-float" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3741934be594d77de1c8461ebcbbe866f585ea616a9753aa78f2bdc69f0e4579" +dependencies = [ + "num-traits", +] + [[package]] name = "os_pipe" version = "0.9.2" @@ -1377,29 +1370,6 @@ dependencies = [ "stable_deref_trait", ] -[[package]] -name = "parking_lot" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" -dependencies = [ - "libc", - "rand 0.6.5", - "rustc_version", - "smallvec 0.6.13", - "winapi 0.3.9", -] - [[package]] name = "percent-encoding" version = "2.1.0" @@ -1479,9 +1449,9 @@ version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a0ffd45cf79d88737d7cc85bfd5d2894bee1139b356e616fe85dc389c61aaf7" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -1502,9 +1472,9 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3894e5d549cccbe44afecf72922f277f603cd4bb0219c8342631ef18fffbe004" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -1521,9 +1491,9 @@ checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" [[package]] name = "proc-macro-hack" -version = "0.5.16" +version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e0456befd48169b9f13ef0f0ad46d492cf9d2dbb918bcf38e01eed4ce3ec5e4" +checksum = "99c605b9a0adc77b7211c6b1f722dcb613d68d66859a44f3d485a6da332b0598" [[package]] name = "proc-macro-nested" @@ -1542,9 +1512,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa" +checksum = "04f5f085b5d71e2188cb8271e5da0161ad52c3f227a661a3c135fdf28e258b12" dependencies = [ "unicode-xid 0.2.1", ] @@ -1580,7 +1550,7 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", ] [[package]] @@ -1784,13 +1754,13 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b82c9238b305f26f53443e3a4bc8528d64b8d0bee408ec949eb7bf5635ec680" +checksum = "12427a5577082c24419c9c417db35cfeb65962efc7675bb6b0d5f1f9d315bfe6" dependencies = [ "async-compression", "base64 0.12.3", - "bytes 0.5.5", + "bytes", "encoding_rs", "futures-core", "futures-util", @@ -1798,18 +1768,19 @@ dependencies = [ "http-body", "hyper", "hyper-rustls", + "ipnet", "js-sys", "lazy_static", - "log 0.4.8", + "log 0.4.11", "mime 0.3.16", "mime_guess 2.0.3", "percent-encoding", "pin-project-lite", - "rustls 0.17.0", + "rustls 0.18.0", "serde", "serde_urlencoded", "tokio", - "tokio-rustls 0.13.1", + "tokio-rustls 0.14.0", "url", "wasm-bindgen", "wasm-bindgen-futures", @@ -1844,12 +1815,12 @@ dependencies = [ [[package]] name = "rustls" -version = "0.16.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b25a18b1bf7387f0145e7f8324e700805aade3842dd3db2e74e4cdeb4677c09e" +checksum = "c0d4a31f5d68413404705d6982529b0e11a9aacd4839d1d6222ee3b8cb4015e1" dependencies = [ - "base64 0.10.1", - "log 0.4.8", + "base64 0.11.0", + "log 0.4.11", "ring", "sct", "webpki", @@ -1857,12 +1828,12 @@ dependencies = [ [[package]] name = "rustls" -version = "0.17.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0d4a31f5d68413404705d6982529b0e11a9aacd4839d1d6222ee3b8cb4015e1" +checksum = "cac94b333ee2aac3284c5b8a1b7fb4dd11cba88c244e3fe33cdbd047af0eb693" dependencies = [ - "base64 0.11.0", - "log 0.4.8", + "base64 0.12.3", + "log 0.4.11", "ring", "sct", "webpki", @@ -1870,9 +1841,9 @@ dependencies = [ [[package]] name = "rusty_v8" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "390f2a21e9855f0cf6113a076cabdfd880b13c055391d61474d5eebf2c1ed491" +checksum = "30925153e17b35ca37a21f4bbf5f61277348ee3110d65360d89010993ce27079" dependencies = [ "bitflags", "cargo_gn", @@ -1889,10 +1860,10 @@ checksum = "3358c21cbbc1a751892528db4e1de4b7a2b6a73f001e215aaba97d712cfa9777" dependencies = [ "cfg-if", "libc", - "log 0.4.8", + "log 0.4.11", "memchr", "nix", - "scopeguard 1.1.0", + "scopeguard", "unicode-segmentation", "unicode-width", "utf8parse", @@ -1920,24 +1891,12 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scoped-tls" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "332ffa32bf586782a3efaeb58f127980944bbc8c4d6913a86107ac2a5ab24b28" - [[package]] name = "scoped-tls" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" -[[package]] -name = "scopeguard" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27" - [[package]] name = "scopeguard" version = "1.1.0" @@ -1977,29 +1936,29 @@ checksum = "b46e1121e8180c12ff69a742aabc4f310542b6ccb69f1691689ac17fdf8618aa" [[package]] name = "serde" -version = "1.0.114" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5317f7588f0a5078ee60ef675ef96735a1442132dc645eb1d12c018620ed8cd3" +checksum = "e54c9a88f2da7238af84b5101443f0c0d0a3bbdc455e34a5c9497b1903ed55d5" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.114" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0be94b04690fbaed37cddffc5c134bf537c8e3329d53e982fe04c374978f8e" +checksum = "609feed1d0a73cc36a0182a840a9b37b4a82f0b1150369f0536a9e3f2a31dc48" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] name = "serde_json" -version = "1.0.56" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3433e879a558dde8b5e8feb2a04899cf34fdde1fafb894687e52105fc1162ac3" +checksum = "164eacbdb13512ec2745fb09d51fd5b22b0d65ed294a1dcf7285a360c80a675c" dependencies = [ "indexmap", "itoa", @@ -2061,18 +2020,9 @@ checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" [[package]] name = "smallvec" -version = "0.6.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7b0758c52e15a8b5e3691eae6cc559f08eee9406e548a4477ba4e67770a82b6" -dependencies = [ - "maybe-uninit", -] - -[[package]] -name = "smallvec" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3757cb9d89161a2f24e1cf78efa0c1fcff485d18e3f55e0aa3480824ddaa0f3f" +checksum = "fbee7696b84bbf3d89a1c2eccff0850e3047ed46bfcd2e92c29a2d074d57e252" [[package]] name = "socket2" @@ -2088,9 +2038,9 @@ dependencies = [ [[package]] name = "sourcemap" -version = "6.0.0" +version = "6.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7f42ca034bf301214458cf7f4dcbe7f680fd23d9e4c61193ed139684e2e3adc" +checksum = "6e031f2463ecbdd5f34c950f89f5c1e1032f22c0f8e3dc4bdb2e8b6658cf61eb" dependencies = [ "base64 0.11.0", "if_chain", @@ -2110,9 +2060,15 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] name = "stable_deref_trait" -version = "1.1.1" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "static_assertions" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "string_cache" @@ -2135,7 +2091,7 @@ checksum = "f24c8e5e19d22a726626f1a5e16fe15b132dcf21d10177fa5a45ce7962996b97" dependencies = [ "phf_generator 0.8.0", "phf_shared 0.8.0", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", ] @@ -2146,10 +2102,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94fdb6536756cfd35ee18b9a9972ab2a699d405cc57e0ad0532022960f30d581" dependencies = [ "pmutil", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", "swc_macros_common", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -2176,34 +2132,33 @@ dependencies = [ [[package]] name = "swc_common" -version = "0.6.2" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79e97fcbda03677da4d57519548082bd8ed30d6afcef8e18053ad829e290d252" +checksum = "458740fb57fe3f2b748819c1db0f448d920d4a64b00e802a485bd41290ef6790" dependencies = [ "ast_node", - "atty", "cfg-if", - "dashmap", "either", "from_variant", "fxhash", - "log 0.4.8", - "parking_lot", - "scoped-tls 1.0.0", + "log 0.4.11", + "once_cell", + "owning_ref", + "scoped-tls", "serde", "sourcemap", - "string_cache", - "termcolor", + "swc_visit", "unicode-width", ] [[package]] name = "swc_ecma_ast" -version = "0.23.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b0fe7f603d4ddef115f7efe72e9c0823f90d9adae5dd4d754fe1a08686b021" +checksum = "809a1fc3a64d853be83a2b7b389ccacf3c17e221393722550b0af631650e600e" dependencies = [ "enum_kind", + "is-macro", "num-bigint", "serde", "string_enum", @@ -2211,24 +2166,52 @@ dependencies = [ "swc_common", ] +[[package]] +name = "swc_ecma_codegen" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcee2cebe6f06eaf2ff1819d3c16c31cf5530ef9f6832ee37d2f8d2b5907a38b" +dependencies = [ + "bitflags", + "num-bigint", + "sourcemap", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_codegen_macros", +] + +[[package]] +name = "swc_ecma_codegen_macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04378143fd1296af71dd3aea2e096bef6fbf8aa3c25352d44d62d7f28aa9851b" +dependencies = [ + "pmutil", + "proc-macro2 1.0.19", + "quote 1.0.7", + "swc_macros_common", + "syn 1.0.36", +] + [[package]] name = "swc_ecma_parser" -version = "0.27.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00871b8900ab4c64b66c81787c95e511e46fb25b54db481a98ab1905160e1edd" +checksum = "504dbc87d7222f01ca57d3572b3b281956b3bda59b80ab3b5125c8f522f6b729" dependencies = [ "either", "enum_kind", - "log 0.4.8", + "fxhash", + "log 0.4.11", "num-bigint", - "once_cell", - "regex", "serde", - "smallvec 1.4.1", + "smallvec", "swc_atoms", "swc_common", "swc_ecma_ast", "swc_ecma_parser_macros", + "swc_ecma_visit", "unicode-xid 0.2.1", ] @@ -2239,37 +2222,81 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8798810e2c79b884cf238bcb72b4bd12375121ee91724f1ceeb54b6e38a138e7" dependencies = [ "pmutil", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", "swc_macros_common", - "syn 1.0.33", + "syn 1.0.36", +] + +[[package]] +name = "swc_ecma_transforms" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ead6107d1d3a8d6c208007cf010c4dbd4fffbd483171b1a64056458647737e" +dependencies = [ + "Inflector", + "arrayvec", + "either", + "fxhash", + "indexmap", + "is-macro", + "jsdoc", + "log 0.4.11", + "once_cell", + "ordered-float", + "regex", + "scoped-tls", + "serde", + "serde_json", + "smallvec", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "swc_ecma_utils", + "swc_ecma_visit", + "unicode-xid 0.2.1", +] + +[[package]] +name = "swc_ecma_utils" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955c573b290af6880cf465c350a9058f1302640ed67f3230b0affebf1558b7c1" +dependencies = [ + "once_cell", + "scoped-tls", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_visit", + "unicode-xid 0.2.1", ] [[package]] name = "swc_ecma_visit" -version = "0.8.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9ce020872b2c0e6b4b65edbb39f523377a67c4532cdde68efbeaa27fade1e44" +checksum = "6d15e3550f565b81fd414162f49ec9cc708d1e561f8ca2fd29b1828b328aa062" dependencies = [ "num-bigint", "swc_atoms", "swc_common", "swc_ecma_ast", - "swc_ecma_visit_macros", + "swc_visit", ] [[package]] -name = "swc_ecma_visit_macros" -version = "0.4.0" +name = "swc_ecmascript" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a32877a341800d772d95858c24344ce00f68361763eae5fa97187e6be136c4b" +checksum = "4c7e45832f8a90fa87a1244cd0d3c9c0fbac0fc55c4e2a0b810e9b7bfc0b5819" dependencies = [ - "Inflector", - "pmutil", - "proc-macro2 1.0.18", - "quote 1.0.7", - "swc_macros_common", - "syn 1.0.33", + "swc_ecma_ast", + "swc_ecma_codegen", + "swc_ecma_parser", + "swc_ecma_transforms", + "swc_ecma_visit", ] [[package]] @@ -2279,9 +2306,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18a9f27d290938370597d363df9a77ba4be8e2bc99f32f69eb5245cdeed3c512" dependencies = [ "pmutil", - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", +] + +[[package]] +name = "swc_visit" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6683cd5f6b97498e887e0d4da4c44ddafb755dfb0d950c52af99344fad23fec9" +dependencies = [ + "either", + "swc_visit_macros", +] + +[[package]] +name = "swc_visit_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1802720b0826a2ae6fac5be1305b1277cf1e83418549f465edf075d8016a1548" +dependencies = [ + "Inflector", + "pmutil", + "proc-macro2 1.0.19", + "quote 1.0.7", + "swc_macros_common", + "syn 1.0.36", ] [[package]] @@ -2297,11 +2348,11 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.33" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8d5d96e8cbb005d6959f119f773bfaebb5684296108fb32600c00cde305b2cd" +checksum = "4cdb98bcb1f9d81d07b536179c269ea15999b5d14ea958196413869445bb5250" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", "unicode-xid 0.2.1", ] @@ -2344,7 +2395,7 @@ name = "test_plugin" version = "0.0.1" dependencies = [ "deno_core", - "futures 0.3.5", + "futures", "test_util", ] @@ -2352,10 +2403,11 @@ dependencies = [ name = "test_util" version = "0.1.0" dependencies = [ - "bytes 0.5.5", - "futures 0.3.5", + "bytes", + "futures", "lazy_static", "os_pipe", + "pty", "regex", "tempfile", "tokio", @@ -2386,9 +2438,9 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd80fc12f73063ac132ac92aceea36734f04a1d93c1240c6944e23a3b8841793" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] @@ -2422,7 +2474,7 @@ version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d34ca54d84bf2b5b4d7d31e901a8464f7b60ac145a284fba25ceb801f2ddccd" dependencies = [ - "bytes 0.5.5", + "bytes", "fnv", "futures-core", "iovec", @@ -2440,48 +2492,37 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "tokio-io" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57fc868aae093479e3131e3d165c93b1c7474109d13c90ec0dda2a1bbfff0674" -dependencies = [ - "bytes 0.4.12", - "futures 0.1.29", - "log 0.4.8", -] - [[package]] name = "tokio-macros" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0c3acc6aa564495a0f2e1d59fab677cd7f81a19994cfc7f3ad0e64301560389" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", ] [[package]] name = "tokio-rustls" -version = "0.12.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3068d891551949b37681724d6b73666787cc63fa8e255c812a41d2513aff9775" +checksum = "15cb62a0d2770787abc96e99c1cd98fcf17f94959f3af63ca85bdfb203f051b4" dependencies = [ "futures-core", - "rustls 0.16.0", + "rustls 0.17.0", "tokio", "webpki", ] [[package]] name = "tokio-rustls" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15cb62a0d2770787abc96e99c1cd98fcf17f94959f3af63ca85bdfb203f051b4" +checksum = "228139ddd4fea3fa345a29233009635235833e52807af7ea6448ead03890d6a9" dependencies = [ "futures-core", - "rustls 0.17.0", + "rustls 0.18.0", "tokio", "webpki", ] @@ -2492,8 +2533,8 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8b8fe88007ebc363512449868d7da4389c9400072a3f666f212c7280082882a" dependencies = [ - "futures 0.3.5", - "log 0.4.8", + "futures", + "log 0.4.11", "pin-project", "tokio", "tungstenite", @@ -2505,10 +2546,10 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be8242891f2b6cbef26a2d7e8605133c2c554cd35b3e4948ea892d6d68436499" dependencies = [ - "bytes 0.5.5", + "bytes", "futures-core", "futures-sink", - "log 0.4.8", + "log 0.4.11", "pin-project-lite", "tokio", ] @@ -2528,6 +2569,36 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860" +[[package]] +name = "tracing" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d79ca061b032d6ce30c660fded31189ca0b9922bf483cd70759f13a2d86786c" +dependencies = [ + "cfg-if", + "log 0.4.11", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db63662723c316b43ca36d833707cc93dff82a02ba3d7e354f342682cc8b3545" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "tracing-futures" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab7bb6f14721aa00656086e9335d363c5c8747bae02ebe32ea2c7dece5689b4c" +dependencies = [ + "pin-project", + "tracing", +] + [[package]] name = "try-lock" version = "0.2.3" @@ -2542,11 +2613,11 @@ checksum = "cfea31758bf674f990918962e8e5f07071a3161bd7c4138ed23e416e1ac4264e" dependencies = [ "base64 0.11.0", "byteorder", - "bytes 0.5.5", + "bytes", "http", "httparse", "input_buffer", - "log 0.4.8", + "log 0.4.11", "rand 0.7.3", "sha-1", "url", @@ -2723,34 +2794,36 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" dependencies = [ - "log 0.4.8", + "log 0.4.11", "try-lock", ] [[package]] name = "warp" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e95175b7a927258ecbb816bdada3cc469cb68593e7940b96a60f4af366a9970" +checksum = "df341dee97c9ae29dfa5e0b0fbbbf620e0d6a36686389bedf83b3daeb8b0d0ac" dependencies = [ - "bytes 0.5.5", - "futures 0.3.5", + "bytes", + "futures", "headers", "http", "hyper", - "log 0.4.8", + "log 0.4.11", "mime 0.3.16", "mime_guess 2.0.3", "multipart", "pin-project", - "scoped-tls 1.0.0", + "scoped-tls", "serde", "serde_json", "serde_urlencoded", "tokio", - "tokio-rustls 0.12.3", + "tokio-rustls 0.13.1", "tokio-tungstenite", "tower-service", + "tracing", + "tracing-futures", "urlencoding", ] @@ -2780,10 +2853,10 @@ checksum = "3e53963b583d18a5aa3aaae4b4c1cb535218246131ba22a71f05b518098571df" dependencies = [ "bumpalo", "lazy_static", - "log 0.4.8", - "proc-macro2 1.0.18", + "log 0.4.11", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", "wasm-bindgen-shared", ] @@ -2815,9 +2888,9 @@ version = "0.2.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9adff9ee0e94b926ca81b57f57f86d5545cdcb1d259e21ec9bdd95b901754c75" dependencies = [ - "proc-macro2 1.0.18", + "proc-macro2 1.0.19", "quote 1.0.7", - "syn 1.0.33", + "syn 1.0.36", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -2859,9 +2932,9 @@ dependencies = [ [[package]] name = "which" -version = "4.0.1" +version = "4.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5fe1a9cb33fe7cf77d431070d0223e544b1e4e7f7764bad0a3e691a6678a131" +checksum = "87c14ef7e1b8b8ecfc75d5eca37949410046e66f15d185c01d70824f1f8111ef" dependencies = [ "libc", "thiserror", diff --git a/Cargo.toml b/Cargo.toml index ea0e02cf95b00e..80e6ce4e6ab90c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,14 @@ members = [ "core", "test_plugin", "test_util", + "op_crates/web", ] exclude = [ "std/hash/_wasm" ] + + +[profile.release] +codegen-units = 1 +lto = true +opt-level = 'z' # Optimize for size diff --git a/Releases.md b/Releases.md index 2113e100bd4df7..8af49252fedf08 100644 --- a/Releases.md +++ b/Releases.md @@ -6,6 +6,129 @@ https://github.com/denoland/deno/releases We also have one-line install commands at https://github.com/denoland/deno_install +### 1.3.1 / 2020.08.21 + +- fix: Allow isolated "%"s when parsing file URLs (#7108) +- fix: Blob.arrayBuffer returns Uint8Array (#7086) +- fix: CLI argument parsing with dash values (#7039) +- fix: Create Body stream from any valid bodySource (#7128) +- fix: Granular permission requests/revokes (#7074) +- fix: Handling of multiple spaces in URLSearchParams (#7068) +- core: Enable WebAssembly.instantiateStreaming (#7043) +- core: Add missing export of HeapLimits (#7047) +- upgrade: swc_ecmascript, deno_lint, dprint (#7098) + +Changes in std version 0.66.0: + +- BREAKING(std/datetime): Remove currentDayOfYear (#7059) +- feat(std/node): Add basic asserts (#7091) +- feat(std/datetime): Generalise parser, add formatter (#6619) +- fix(std/node): Misnamed assert exports (#7123) +- fix(std/encoding/toml): Stop TOML parser from detecting numbers in strings. + (#7064) +- fix(std/encoding/csv): Improve error message on ParseError (#7057) + +### 1.3.0 / 2020.08.13 + +Changes in the CLI: + +- feat: Add "--no-check" flag to deno install (#6948) +- feat: Add "--ignore" flag to deno lint (#6934) +- feat: Add "--json" flag to deno lint (#6940) +- feat: Add "--reload" flag to deno bundle (#6996) +- feat: Add "--reload" flag to deno info (#7009) +- feat: FileReader API (#6673) +- feat: Handle imports in deno doc (#6987) +- feat: Stabilize Deno.mainModule (#6993) +- feat: Support file URLs in Deno.run for executable (#6994) +- fix: console.log should see color codes when grouping occurs (#7000) +- fix: URLSearchParams.toString() behaviour is different from browsers (#7017) +- fix: Remove @ts-expect-error directives (#7024) +- fix(unstable): Add missing globals to diagnostics (#6988) +- refactor(doc): Remove detailed / summary distinction (#6818) +- core: Memory limits & callbacks (#6914) +- upgrade: TypeScript to 3.9.7 (#7036) +- upgrade: Rust crates (#7034, #7040) + +Changes in std version 0.65.0: + +- feat(std/http): Add TLS serve abilities to file_server (#6962) +- feat(std/http): Add --no-dir-listing flag to file_server (#6808) +- feat(std/node): Add util.inspect (#6833) +- fix: Make std work with isolatedModules (#7016) + +### 1.2.3 / 2020.08.08 + +Changes in the CLI: + +- fix: Never type check in deno info (#6978) +- fix: add missing globals to unstable diagnostics (#6960) +- fix: add support for non-UTF8 source files (#6789) +- fix: hash file names in gen cache (#6911) +- refactor: Encode op errors as strings instead of numbers (#6977) +- refactor: Op crate for Web APIs (#6906) +- refactor: remove repeated code in main.rs (#6954) +- upgrade to rusty_v8 0.8.1 / V8 8.6.334 (#6980) +- upgrade: deno_lint v0.1.21 (#6985) +- upgrade: swc_ecmascript (#6943) +- feat(unstable): custom http client for fetch (#6918) + +Changes in std version 0.64.0: + +- fix(std/toml): parser error with inline comments (#6942) +- fix(std/encoding/toml): Add boolean support to stringify (#6941) +- refactor: Rewrite globToRegExp() (#6963) + +### 1.2.2 / 2020.07.31 + +Changes in the CLI: + +- fix: Change release build flags to optimize for size (#6907) +- fix: Fix file URL to path conversion on Windows (#6920) +- fix: deno-types, X-TypeScript-Types precedence (#6761) +- fix: downcast from SwcDiagnosticBuffer to OpError (#6909) +- perf: Use SWC to strip types for "--no-check" flag (#6895) +- upgrade: deno_lint, dprint, swc (#6928, #6869) +- feat(unstable): add "--ignore" flag to deno fmt (#6890) + +Changes in std version 0.63.0: + +- feat(std/async): add pooledMap utility (#6898) +- fix(std/json): Add newline at the end of json files (#6885) +- fix(std/path): Percent-decode in fromFileUrl() (#6913) +- fix(std/tar): directory type bug (#6905) + +### 1.2.1 / 2020.07.23 + +Changes in the CLI: + +- fix: IPv6 hostname should be compressed (#6772) +- fix: Ignore polling errors caused by return() in watchFs (#6785) +- fix: Improve URL compatibility (#6807) +- fix: ModuleSpecifier removes relative path parts (#6762) +- fix: Share reqwest client between fetch calls (#6792) +- fix: add icon and metadata to deno.exe on Windows (#6693) +- fix: panic for runtime error in TS compiler (#6758) +- fix: providing empty source code for missing compiled files (#6760) +- refactor: Make OpDispatcher a trait (#6736, #6742) +- refactor: Remove duplicate code and allow filename overwrite for DomFile + (#6817, #6830) +- upgrade: Rust 1.45.0 (#6791) +- upgrade: rusty_v8 0.7.0 (#6801) +- upgrade: tokio 0.2.22 (#6838) + +Changes in std version 0.62.0: + +- BREAKING(std/fs): remove readFileStr and writeFileStr (#6848, #6847) +- feat(std/encoding): add ascii85 module (#6711) +- feat(std/node): add string_decoder (#6638) +- fix(std/encoding/toml): could not parse strings with apostrophes/semicolons + (#6781) +- fix(std/testing): assertThrows inheritance (#6623) +- fix(std/wasi): remove number overload from rights in path_open (#6768) +- refactor(std/datetime): improve weekOfYear (#6741) +- refactor(std/path): enrich the types in parse_format_test (#6803) + ### 1.2.0 / 2020.07.13 Changes in the CLI: diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 92fddfd9f181a3..bc42f96de87378 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -2,7 +2,7 @@ [package] name = "deno" -version = "1.2.0" +version = "1.3.1" license = "MIT" authors = ["the Deno authors"] edition = "2018" @@ -15,57 +15,62 @@ name = "deno" path = "main.rs" [build-dependencies] -deno_core = { path = "../core", version = "0.49.0" } +deno_core = { path = "../core", version = "0.54.0" } +deno_web = { path = "../op_crates/web", version = "0.4.0" } [target.'cfg(windows)'.build-dependencies] -winres = "0.1" -winapi = "0.3.8" +winres = "0.1.11" +winapi = "0.3.9" [dependencies] -deno_core = { path = "../core", version = "0.49.0" } -deno_lint = "0.1.16" +deno_core = { path = "../core", version = "0.54.0" } +deno_doc = { version = "0.1.1" } +deno_lint = { version = "0.1.24", features = ["json"] } atty = "0.2.14" -base64 = "0.12.2" -bytes = "0.5.5" +base64 = "0.12.3" +bytes = "0.5.6" byteorder = "1.3.4" -clap = "2.33.1" +clap = "2.33.2" dissimilar = "1.0.2" dlopen = "0.1.8" -futures = { version = "0.3.5", features = ["compat", "io-compat"] } +encoding_rs = "0.8.23" +dprint-plugin-typescript = "0.30.0" +futures = "0.3.5" http = "0.2.1" idna = "0.2.0" -indexmap = "1.4.0" +indexmap = "1.5.1" lazy_static = "1.4.0" -libc = "0.2.71" -log = "0.4.8" -notify = "5.0.0-pre.2" +libc = "0.2.74" +log = "0.4.11" +notify = "5.0.0-pre.3" rand = "0.7.3" regex = "1.3.9" -reqwest = { version = "0.10.6", default-features = false, features = ["rustls-tls", "stream", "gzip", "brotli"] } +reqwest = { version = "0.10.7", default-features = false, features = ["rustls-tls", "stream", "gzip", "brotli"] } ring = "0.16.15" -rustyline = { version = "6.2", default-features = false } -serde = { version = "1.0.112", features = ["derive"] } -serde_derive = "1.0.112" -serde_json = { version = "1.0.55", features = [ "preserve_order" ] } +rustyline = { version = "6.2.0", default-features = false } +serde = { version = "1.0.115", features = ["derive"] } +serde_derive = "1.0.115" +serde_json = { version = "1.0.57", features = [ "preserve_order" ] } sys-info = "0.7.0" -sourcemap = "6.0.0" +sourcemap = "6.0.1" +swc_common = { version = "=0.9.1", features = ["sourcemap"] } +swc_ecmascript = { version = "=0.5.0", features = ["codegen", "parser", "transforms", "visit"] } tempfile = "3.1.0" termcolor = "1.1.0" tokio = { version = "0.2.22", features = ["full"] } -tokio-rustls = "0.13.1" tokio-tungstenite = { version = "0.10.1", features = ["connect"] } url = "2.1.1" -utime = "0.3.0" +utime = "0.3.1" webpki = "0.21.3" webpki-roots = "0.19.0" walkdir = "2.3.1" -warp = "0.2.3" +warp = { version = "0.2.4", features = ["tls"] } semver-parser = "0.9.0" uuid = { version = "0.8.1", features = ["v4"] } [target.'cfg(windows)'.dependencies] -winapi = { version = "0.3.8", features = ["knownfolders", "objbase", "shlobj", +winapi = { version = "0.3.9", features = ["knownfolders", "objbase", "shlobj", "winbase", "winerror", "tlhelp32"] } fwdansi = "1.1.0" @@ -78,12 +83,9 @@ os_pipe = "0.9.2" tokio-tungstenite = { version = "0.10.1", features = ["connect"] } test_util = { path = "../test_util" } -[target.'cfg(unix)'.dev-dependencies] -pty = "0.2.2" - [package.metadata.winres] # This section defines the metadata that appears in the deno.exe PE header. OriginalFilename = "deno.exe" LegalCopyright = "© Deno contributors & Deno Land Inc. MIT licensed." ProductName = "Deno" -FileDescription = "A secure JavaScript/TypeScript runtime, built on V8 and Rust." +FileDescription = "A secure runtime for JavaScript and TypeScript." diff --git a/cli/build.rs b/cli/build.rs index 983857625ac8ae..df4211d8b8cd8f 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -38,6 +38,11 @@ fn create_compiler_snapshot( ) { let mut runtime_isolate = CoreIsolate::new(StartupData::None, true); let mut custom_libs: HashMap = HashMap::new(); + let web_scripts = deno_web::get_scripts(); + custom_libs.insert( + "lib.deno.web.d.ts".to_string(), + PathBuf::from(web_scripts.declaration), + ); custom_libs.insert( "lib.deno.window.d.ts".to_string(), cwd.join("dts/lib.deno.window.d.ts"), @@ -66,8 +71,17 @@ fn create_compiler_snapshot( } fn ts_version() -> String { - // TODO(ry) This should be automatically extracted from typescript.js - "3.9.2".to_string() + std::fs::read_to_string("tsc/00_typescript.js") + .unwrap() + .lines() + .find(|l| l.contains("ts.version = ")) + .expect( + "Failed to find the pattern `ts.version = ` in typescript source code", + ) + .chars() + .skip_while(|c| !char::is_numeric(*c)) + .take_while(|c| *c != '"') + .collect::() } fn main() { @@ -80,6 +94,10 @@ fn main() { // op_fetch_asset::trace_serializer(); println!("cargo:rustc-env=TS_VERSION={}", ts_version()); + println!( + "cargo:rustc-env=DENO_WEB_LIB_PATH={}", + deno_web::get_scripts().declaration + ); println!( "cargo:rustc-env=TARGET={}", @@ -93,7 +111,7 @@ fn main() { let runtime_snapshot_path = o.join("CLI_SNAPSHOT.bin"); let compiler_snapshot_path = o.join("COMPILER_SNAPSHOT.bin"); - let js_files = get_js_files("js2"); + let js_files = get_js_files_for_rt(); create_runtime_snapshot(&runtime_snapshot_path, js_files); let js_files = get_js_files("tsc"); @@ -123,3 +141,68 @@ fn get_js_files(d: &str) -> Vec { js_files.sort(); js_files } + +fn get_js_files_for_rt() -> Vec { + let web_scripts = deno_web::get_scripts(); + + let f = vec![ + "rt/00_bootstrap_namespace.js", + &web_scripts.dom_exception, + "rt/01_build.js", + "rt/01_colors.js", + "rt/01_errors.js", + &web_scripts.event, + "rt/01_internals.js", + "rt/01_version.js", + "rt/01_web_util.js", + &web_scripts.abort_signal, + "rt/02_console.js", + "rt/03_dom_iterable.js", + "rt/06_util.js", + &web_scripts.text_encoding, + "rt/10_dispatch_json.js", + "rt/10_dispatch_minimal.js", + "rt/11_crypto.js", + "rt/11_resources.js", + "rt/11_streams.js", + "rt/11_timers.js", + "rt/11_url.js", + "rt/11_workers.js", + "rt/12_io.js", + "rt/13_buffer.js", + "rt/20_blob.js", + "rt/20_headers.js", + "rt/20_streams_queuing_strategy.js", + "rt/21_dom_file.js", + "rt/21_filereader.js", + "rt/22_form_data.js", + "rt/23_multipart.js", + "rt/24_body.js", + "rt/25_request.js", + "rt/26_fetch.js", + "rt/30_files.js", + "rt/30_fs.js", + "rt/30_metrics.js", + "rt/30_net.js", + "rt/30_os.js", + "rt/40_compiler_api.js", + "rt/40_diagnostics.js", + "rt/40_error_stack.js", + "rt/40_fs_events.js", + "rt/40_net_unstable.js", + "rt/40_performance.js", + "rt/40_permissions.js", + "rt/40_plugins.js", + "rt/40_process.js", + "rt/40_read_file.js", + "rt/40_repl.js", + "rt/40_signals.js", + "rt/40_testing.js", + "rt/40_tls.js", + "rt/40_tty.js", + "rt/40_write_file.js", + "rt/90_deno_ns.js", + "rt/99_main.js", + ]; + f.iter().map(|p| p.to_string()).collect() +} diff --git a/cli/diagnostics.rs b/cli/diagnostics.rs index 00707c498033ac..41ee5ec22397cc 100644 --- a/cli/diagnostics.rs +++ b/cli/diagnostics.rs @@ -2,9 +2,6 @@ //! This module encodes TypeScript errors (diagnostics) into Rust structs and //! contains code for printing them to the console. -// TODO(ry) This module does a lot of JSON parsing manually. It should use -// serde_json. - use crate::colors; use crate::fmt_errors::format_stack; use serde::Deserialize; @@ -152,10 +149,7 @@ fn format_maybe_related_information( for rd in related_information { s.push_str("\n\n"); s.push_str(&format_stack( - match rd.category { - DiagnosticCategory::Error => true, - _ => false, - }, + matches!(rd.category, DiagnosticCategory::Error), &format_message(&rd.message_chain, &rd.message, 0), rd.source_line.as_deref(), rd.start_column, @@ -180,10 +174,7 @@ impl fmt::Display for DiagnosticItem { f, "{}", format_stack( - match self.category { - DiagnosticCategory::Error => true, - _ => false, - }, + matches!(self.category, DiagnosticCategory::Error), &format!( "{}: {}", format_category_and_code(&self.category, self.code), diff --git a/cli/disk_cache.rs b/cli/disk_cache.rs index afea71cd22b640..d6fb9866c242f1 100644 --- a/cli/disk_cache.rs +++ b/cli/disk_cache.rs @@ -1,4 +1,5 @@ use crate::fs as deno_fs; +use crate::http_cache::url_to_filename; use std::ffi::OsStr; use std::fs; use std::io; @@ -50,7 +51,7 @@ impl DiskCache { out.push(scheme); match scheme { - "http" | "https" | "wasm" => { + "wasm" => { let host = url.host_str().unwrap(); let host_port = match url.port() { // Windows doesn't support ":" in filenames, so we represent port using a @@ -64,6 +65,7 @@ impl DiskCache { out.push(path_seg); } } + "http" | "https" => out = url_to_filename(url), "file" => { let path = url.to_file_path().unwrap(); let mut path_components = path.components(); @@ -194,15 +196,15 @@ mod tests { let mut test_cases = vec![ ( "http://deno.land/std/http/file_server.ts", - "http/deno.land/std/http/file_server.ts", + "http/deno.land/d8300752800fe3f0beda9505dc1c3b5388beb1ee45afd1f1e2c9fc0866df15cf", ), ( "http://localhost:8000/std/http/file_server.ts", - "http/localhost_PORT8000/std/http/file_server.ts", + "http/localhost_PORT8000/d8300752800fe3f0beda9505dc1c3b5388beb1ee45afd1f1e2c9fc0866df15cf", ), ( "https://deno.land/std/http/file_server.ts", - "https/deno.land/std/http/file_server.ts", + "https/deno.land/d8300752800fe3f0beda9505dc1c3b5388beb1ee45afd1f1e2c9fc0866df15cf", ), ("wasm://wasm/d1c677ea", "wasm/wasm/d1c677ea"), ]; @@ -251,12 +253,12 @@ mod tests { ( "http://deno.land/std/http/file_server.ts", "js", - "http/deno.land/std/http/file_server.ts.js", + "http/deno.land/d8300752800fe3f0beda9505dc1c3b5388beb1ee45afd1f1e2c9fc0866df15cf.js", ), ( "http://deno.land/std/http/file_server.ts", "js.map", - "http/deno.land/std/http/file_server.ts.js.map", + "http/deno.land/d8300752800fe3f0beda9505dc1c3b5388beb1ee45afd1f1e2c9fc0866df15cf.js.map", ), ]; diff --git a/cli/doc/class.rs b/cli/doc/class.rs deleted file mode 100644 index d8fa29ded3ce0b..00000000000000 --- a/cli/doc/class.rs +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::colors; -use crate::doc::display::{ - display_abstract, display_accessibility, display_async, display_generator, - display_method, display_optional, display_readonly, display_static, - SliceDisplayer, -}; -use crate::swc_common::Spanned; -use crate::swc_ecma_ast; -use serde::Serialize; - -use super::function::function_to_function_def; -use super::function::FunctionDef; -use super::interface::expr_to_name; -use super::params::{ - assign_pat_to_param_def, ident_to_param_def, pat_to_param_def, - prop_name_to_string, ts_fn_param_to_param_def, -}; -use super::parser::DocParser; -use super::ts_type::{ - maybe_type_param_instantiation_to_type_defs, ts_type_ann_to_def, TsTypeDef, -}; -use super::ts_type_param::maybe_type_param_decl_to_type_param_defs; -use super::ts_type_param::TsTypeParamDef; -use super::Location; -use super::ParamDef; - -use std::fmt::{Display, Formatter, Result as FmtResult}; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ClassConstructorDef { - pub js_doc: Option, - pub accessibility: Option, - pub name: String, - pub params: Vec, - pub location: Location, -} - -impl Display for ClassConstructorDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}{}({})", - display_accessibility(self.accessibility), - colors::magenta("constructor"), - SliceDisplayer::new(&self.params, ", ", false), - ) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ClassPropertyDef { - pub js_doc: Option, - pub ts_type: Option, - pub readonly: bool, - pub accessibility: Option, - pub optional: bool, - pub is_abstract: bool, - pub is_static: bool, - pub name: String, - pub location: Location, -} - -impl Display for ClassPropertyDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}{}{}{}{}{}", - display_abstract(self.is_abstract), - display_accessibility(self.accessibility), - display_static(self.is_static), - display_readonly(self.readonly), - colors::bold(&self.name), - display_optional(self.optional), - )?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ClassIndexSignatureDef { - pub readonly: bool, - pub params: Vec, - pub ts_type: Option, -} - -impl Display for ClassIndexSignatureDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}[{}]", - display_readonly(self.readonly), - SliceDisplayer::new(&self.params, ", ", false) - )?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ClassMethodDef { - pub js_doc: Option, - pub accessibility: Option, - pub optional: bool, - pub is_abstract: bool, - pub is_static: bool, - pub name: String, - pub kind: swc_ecma_ast::MethodKind, - pub function_def: FunctionDef, - pub location: Location, -} - -impl Display for ClassMethodDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}{}{}{}{}{}{}{}({})", - display_abstract(self.is_abstract), - display_accessibility(self.accessibility), - display_static(self.is_static), - display_async(self.function_def.is_async), - display_method(self.kind), - display_generator(self.function_def.is_generator), - colors::bold(&self.name), - display_optional(self.optional), - SliceDisplayer::new(&self.function_def.params, ", ", false), - )?; - if let Some(return_type) = &self.function_def.return_type { - write!(f, ": {}", return_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ClassDef { - // TODO(bartlomieju): decorators - pub is_abstract: bool, - pub constructors: Vec, - pub properties: Vec, - pub index_signatures: Vec, - pub methods: Vec, - pub extends: Option, - pub implements: Vec, - pub type_params: Vec, - pub super_type_params: Vec, -} - -pub fn class_to_class_def( - doc_parser: &DocParser, - class: &swc_ecma_ast::Class, -) -> ClassDef { - let mut constructors = vec![]; - let mut methods = vec![]; - let mut properties = vec![]; - let mut index_signatures = vec![]; - - let extends: Option = match &class.super_class { - Some(boxed) => { - use crate::swc_ecma_ast::Expr; - let expr: &Expr = &**boxed; - match expr { - Expr::Ident(ident) => Some(ident.sym.to_string()), - _ => None, - } - } - None => None, - }; - - let implements = class - .implements - .iter() - .map(|expr| expr.into()) - .collect::>(); - - for member in &class.body { - use crate::swc_ecma_ast::ClassMember::*; - - match member { - Constructor(ctor) => { - let ctor_js_doc = doc_parser.js_doc_for_span(ctor.span()); - let constructor_name = prop_name_to_string( - &ctor.key, - Some(&doc_parser.ast_parser.source_map), - ); - - let mut params = vec![]; - - for param in &ctor.params { - use crate::swc_ecma_ast::ParamOrTsParamProp::*; - - let param_def = match param { - Param(param) => pat_to_param_def( - ¶m.pat, - Some(&doc_parser.ast_parser.source_map), - ), - TsParamProp(ts_param_prop) => { - use swc_ecma_ast::TsParamPropParam; - - match &ts_param_prop.param { - TsParamPropParam::Ident(ident) => ident_to_param_def( - ident, - Some(&doc_parser.ast_parser.source_map), - ), - TsParamPropParam::Assign(assign_pat) => { - assign_pat_to_param_def( - assign_pat, - Some(&doc_parser.ast_parser.source_map), - ) - } - } - } - }; - params.push(param_def); - } - - let constructor_def = ClassConstructorDef { - js_doc: ctor_js_doc, - accessibility: ctor.accessibility, - name: constructor_name, - params, - location: doc_parser.ast_parser.get_span_location(ctor.span).into(), - }; - constructors.push(constructor_def); - } - Method(class_method) => { - let method_js_doc = doc_parser.js_doc_for_span(class_method.span()); - let method_name = prop_name_to_string( - &class_method.key, - Some(&doc_parser.ast_parser.source_map), - ); - let fn_def = - function_to_function_def(&doc_parser, &class_method.function); - let method_def = ClassMethodDef { - js_doc: method_js_doc, - accessibility: class_method.accessibility, - optional: class_method.is_optional, - is_abstract: class_method.is_abstract, - is_static: class_method.is_static, - name: method_name, - kind: class_method.kind, - function_def: fn_def, - location: doc_parser - .ast_parser - .get_span_location(class_method.span) - .into(), - }; - methods.push(method_def); - } - ClassProp(class_prop) => { - let prop_js_doc = doc_parser.js_doc_for_span(class_prop.span()); - - let ts_type = class_prop - .type_ann - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - let prop_name = expr_to_name(&*class_prop.key); - - let prop_def = ClassPropertyDef { - js_doc: prop_js_doc, - ts_type, - readonly: class_prop.readonly, - optional: class_prop.is_optional, - is_abstract: class_prop.is_abstract, - is_static: class_prop.is_static, - accessibility: class_prop.accessibility, - name: prop_name, - location: doc_parser - .ast_parser - .get_span_location(class_prop.span) - .into(), - }; - properties.push(prop_def); - } - TsIndexSignature(ts_index_sig) => { - let mut params = vec![]; - for param in &ts_index_sig.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let ts_type = ts_index_sig - .type_ann - .as_ref() - .map(|rt| (&*rt.type_ann).into()); - - let index_sig_def = ClassIndexSignatureDef { - readonly: ts_index_sig.readonly, - params, - ts_type, - }; - index_signatures.push(index_sig_def); - } - // TODO(bartlomieju): - PrivateMethod(_) => {} - PrivateProp(_) => {} - _ => {} - } - } - - let type_params = - maybe_type_param_decl_to_type_param_defs(class.type_params.as_ref()); - - let super_type_params = maybe_type_param_instantiation_to_type_defs( - class.super_type_params.as_ref(), - ); - - ClassDef { - is_abstract: class.is_abstract, - extends, - implements, - constructors, - properties, - index_signatures, - methods, - type_params, - super_type_params, - } -} - -pub fn get_doc_for_class_decl( - doc_parser: &DocParser, - class_decl: &swc_ecma_ast::ClassDecl, -) -> (String, ClassDef) { - let class_name = class_decl.ident.sym.to_string(); - let class_def = class_to_class_def(doc_parser, &class_decl.class); - - (class_name, class_def) -} diff --git a/cli/doc/display.rs b/cli/doc/display.rs deleted file mode 100644 index 9da04363f6f10d..00000000000000 --- a/cli/doc/display.rs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::colors; -use crate::swc_ecma_ast; -use std::fmt::{Display, Formatter, Result}; - -pub(crate) struct Indent(pub i64); - -impl Display for Indent { - fn fmt(&self, f: &mut Formatter<'_>) -> Result { - for _ in 0..self.0 { - write!(f, " ")?; - } - Ok(()) - } -} - -pub(crate) struct SliceDisplayer<'a, T: Display>(&'a [T], &'a str, bool); - -impl<'a, T: Display> SliceDisplayer<'a, T> { - pub fn new( - slice: &'a [T], - separator: &'a str, - trailing: bool, - ) -> SliceDisplayer<'a, T> { - SliceDisplayer(slice, separator, trailing) - } -} - -impl Display for SliceDisplayer<'_, T> { - fn fmt(&self, f: &mut Formatter<'_>) -> Result { - if self.0.is_empty() { - return Ok(()); - } - - write!(f, "{}", self.0[0])?; - for v in &self.0[1..] { - write!(f, "{}{}", self.1, v)?; - } - - if self.2 { - write!(f, "{}", self.1)?; - } - - Ok(()) - } -} - -pub(crate) fn display_abstract(is_abstract: bool) -> impl Display { - colors::magenta(if is_abstract { "abstract " } else { "" }) -} - -pub(crate) fn display_accessibility( - accessibility: Option, -) -> impl Display { - colors::magenta( - match accessibility.unwrap_or(swc_ecma_ast::Accessibility::Public) { - swc_ecma_ast::Accessibility::Public => "", - swc_ecma_ast::Accessibility::Protected => "protected ", - swc_ecma_ast::Accessibility::Private => "private ", - }, - ) -} - -pub(crate) fn display_async(is_async: bool) -> impl Display { - colors::magenta(if is_async { "async " } else { "" }) -} - -pub(crate) fn display_generator(is_generator: bool) -> impl Display { - colors::magenta(if is_generator { "*" } else { "" }) -} - -pub(crate) fn display_method(method: swc_ecma_ast::MethodKind) -> impl Display { - colors::magenta(match method { - swc_ecma_ast::MethodKind::Getter => "get ", - swc_ecma_ast::MethodKind::Setter => "set ", - _ => "", - }) -} - -pub(crate) fn display_optional(is_optional: bool) -> impl Display { - colors::magenta(if is_optional { "?" } else { "" }) -} - -pub(crate) fn display_readonly(is_readonly: bool) -> impl Display { - colors::magenta(if is_readonly { "readonly " } else { "" }) -} - -pub(crate) fn display_static(is_static: bool) -> impl Display { - colors::magenta(if is_static { "static " } else { "" }) -} diff --git a/cli/doc/enum.rs b/cli/doc/enum.rs deleted file mode 100644 index bf561cf942a77a..00000000000000 --- a/cli/doc/enum.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::swc_ecma_ast; -use serde::Serialize; - -use super::parser::DocParser; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct EnumMemberDef { - pub name: String, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct EnumDef { - pub members: Vec, -} - -pub fn get_doc_for_ts_enum_decl( - _doc_parser: &DocParser, - enum_decl: &swc_ecma_ast::TsEnumDecl, -) -> (String, EnumDef) { - let enum_name = enum_decl.id.sym.to_string(); - let mut members = vec![]; - - for enum_member in &enum_decl.members { - use crate::swc_ecma_ast::TsEnumMemberId::*; - - let member_name = match &enum_member.id { - Ident(ident) => ident.sym.to_string(), - Str(str_) => str_.value.to_string(), - }; - - let member_def = EnumMemberDef { name: member_name }; - members.push(member_def); - } - - let enum_def = EnumDef { members }; - - (enum_name, enum_def) -} diff --git a/cli/doc/function.rs b/cli/doc/function.rs deleted file mode 100644 index ede8bdbbd26a7d..00000000000000 --- a/cli/doc/function.rs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use super::params::pat_to_param_def; -use super::parser::DocParser; -use super::ts_type::ts_type_ann_to_def; -use super::ts_type::TsTypeDef; -use super::ts_type_param::maybe_type_param_decl_to_type_param_defs; -use super::ts_type_param::TsTypeParamDef; -use super::ParamDef; -use crate::swc_ecma_ast; -use serde::Serialize; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct FunctionDef { - pub params: Vec, - pub return_type: Option, - pub is_async: bool, - pub is_generator: bool, - pub type_params: Vec, - // TODO(bartlomieju): decorators -} - -pub fn function_to_function_def( - doc_parser: &DocParser, - function: &swc_ecma_ast::Function, -) -> FunctionDef { - let mut params = vec![]; - - for param in &function.params { - let param_def = - pat_to_param_def(¶m.pat, Some(&doc_parser.ast_parser.source_map)); - params.push(param_def); - } - - let maybe_return_type = function - .return_type - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - let type_params = - maybe_type_param_decl_to_type_param_defs(function.type_params.as_ref()); - - FunctionDef { - params, - return_type: maybe_return_type, - is_async: function.is_async, - is_generator: function.is_generator, - type_params, - } -} - -pub fn get_doc_for_fn_decl( - doc_parser: &DocParser, - fn_decl: &swc_ecma_ast::FnDecl, -) -> (String, FunctionDef) { - let name = fn_decl.ident.sym.to_string(); - let fn_def = function_to_function_def(&doc_parser, &fn_decl.function); - (name, fn_def) -} diff --git a/cli/doc/interface.rs b/cli/doc/interface.rs deleted file mode 100644 index d3caa8748492bc..00000000000000 --- a/cli/doc/interface.rs +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::colors; -use crate::doc::display::{display_optional, display_readonly, SliceDisplayer}; -use crate::swc_ecma_ast; -use serde::Serialize; - -use super::params::ts_fn_param_to_param_def; -use super::parser::DocParser; -use super::ts_type::ts_type_ann_to_def; -use super::ts_type::TsTypeDef; -use super::ts_type_param::maybe_type_param_decl_to_type_param_defs; -use super::ts_type_param::TsTypeParamDef; -use super::Location; -use super::ParamDef; - -use std::fmt::{Display, Formatter, Result as FmtResult}; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct InterfaceMethodDef { - pub name: String, - pub location: Location, - pub js_doc: Option, - pub optional: bool, - pub params: Vec, - pub return_type: Option, - pub type_params: Vec, -} - -impl Display for InterfaceMethodDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}{}({})", - colors::bold(&self.name), - display_optional(self.optional), - SliceDisplayer::new(&self.params, ", ", false), - )?; - if let Some(return_type) = &self.return_type { - write!(f, ": {}", return_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct InterfacePropertyDef { - pub name: String, - pub location: Location, - pub js_doc: Option, - pub params: Vec, - pub computed: bool, - pub optional: bool, - pub ts_type: Option, - pub type_params: Vec, -} - -impl Display for InterfacePropertyDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}{}", - colors::bold(&self.name), - display_optional(self.optional), - )?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct InterfaceIndexSignatureDef { - pub readonly: bool, - pub params: Vec, - pub ts_type: Option, -} - -impl Display for InterfaceIndexSignatureDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}[{}]", - display_readonly(self.readonly), - SliceDisplayer::new(&self.params, ", ", false) - )?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct InterfaceCallSignatureDef { - pub location: Location, - pub js_doc: Option, - pub params: Vec, - pub ts_type: Option, - pub type_params: Vec, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct InterfaceDef { - pub extends: Vec, - pub methods: Vec, - pub properties: Vec, - pub call_signatures: Vec, - pub index_signatures: Vec, - pub type_params: Vec, -} - -pub fn expr_to_name(expr: &swc_ecma_ast::Expr) -> String { - use crate::swc_ecma_ast::Expr::*; - use crate::swc_ecma_ast::ExprOrSuper::*; - - match expr { - Ident(ident) => ident.sym.to_string(), - Member(member_expr) => { - let left = match &member_expr.obj { - Super(_) => "super".to_string(), - Expr(boxed_expr) => expr_to_name(&*boxed_expr), - }; - let right = expr_to_name(&*member_expr.prop); - format!("[{}.{}]", left, right) - } - _ => "".to_string(), - } -} - -pub fn get_doc_for_ts_interface_decl( - doc_parser: &DocParser, - interface_decl: &swc_ecma_ast::TsInterfaceDecl, -) -> (String, InterfaceDef) { - let interface_name = interface_decl.id.sym.to_string(); - - let mut methods = vec![]; - let mut properties = vec![]; - let mut call_signatures = vec![]; - let mut index_signatures = vec![]; - - for type_element in &interface_decl.body.body { - use crate::swc_ecma_ast::TsTypeElement::*; - - match &type_element { - TsMethodSignature(ts_method_sig) => { - let method_js_doc = doc_parser.js_doc_for_span(ts_method_sig.span); - - let mut params = vec![]; - - for param in &ts_method_sig.params { - let param_def = ts_fn_param_to_param_def( - param, - Some(&doc_parser.ast_parser.source_map), - ); - params.push(param_def); - } - - let name = expr_to_name(&*ts_method_sig.key); - - let maybe_return_type = ts_method_sig - .type_ann - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_method_sig.type_params.as_ref(), - ); - - let method_def = InterfaceMethodDef { - name, - js_doc: method_js_doc, - location: doc_parser - .ast_parser - .get_span_location(ts_method_sig.span) - .into(), - optional: ts_method_sig.optional, - params, - return_type: maybe_return_type, - type_params, - }; - methods.push(method_def); - } - TsPropertySignature(ts_prop_sig) => { - let prop_js_doc = doc_parser.js_doc_for_span(ts_prop_sig.span); - let name = expr_to_name(&*ts_prop_sig.key); - - let mut params = vec![]; - - for param in &ts_prop_sig.params { - let param_def = ts_fn_param_to_param_def( - param, - Some(&doc_parser.ast_parser.source_map), - ); - params.push(param_def); - } - - let ts_type = ts_prop_sig - .type_ann - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_prop_sig.type_params.as_ref(), - ); - - let prop_def = InterfacePropertyDef { - name, - js_doc: prop_js_doc, - location: doc_parser - .ast_parser - .get_span_location(ts_prop_sig.span) - .into(), - params, - ts_type, - computed: ts_prop_sig.computed, - optional: ts_prop_sig.optional, - type_params, - }; - properties.push(prop_def); - } - TsCallSignatureDecl(ts_call_sig) => { - let call_sig_js_doc = doc_parser.js_doc_for_span(ts_call_sig.span); - - let mut params = vec![]; - for param in &ts_call_sig.params { - let param_def = ts_fn_param_to_param_def( - param, - Some(&doc_parser.ast_parser.source_map), - ); - params.push(param_def); - } - - let ts_type = ts_call_sig - .type_ann - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_call_sig.type_params.as_ref(), - ); - - let call_sig_def = InterfaceCallSignatureDef { - js_doc: call_sig_js_doc, - location: doc_parser - .ast_parser - .get_span_location(ts_call_sig.span) - .into(), - params, - ts_type, - type_params, - }; - call_signatures.push(call_sig_def); - } - TsIndexSignature(ts_index_sig) => { - let mut params = vec![]; - for param in &ts_index_sig.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let ts_type = ts_index_sig - .type_ann - .as_ref() - .map(|rt| (&*rt.type_ann).into()); - - let index_sig_def = InterfaceIndexSignatureDef { - readonly: ts_index_sig.readonly, - params, - ts_type, - }; - index_signatures.push(index_sig_def); - } - // TODO: - TsConstructSignatureDecl(_) => {} - } - } - - let type_params = maybe_type_param_decl_to_type_param_defs( - interface_decl.type_params.as_ref(), - ); - - let extends = interface_decl - .extends - .iter() - .map(|expr| expr.into()) - .collect::>(); - - let interface_def = InterfaceDef { - extends, - methods, - properties, - call_signatures, - index_signatures, - type_params, - }; - - (interface_name, interface_def) -} diff --git a/cli/doc/mod.rs b/cli/doc/mod.rs deleted file mode 100644 index 49f8d7453edb3f..00000000000000 --- a/cli/doc/mod.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -pub mod class; -mod display; -pub mod r#enum; -pub mod function; -pub mod interface; -pub mod module; -pub mod namespace; -mod node; -pub mod params; -pub mod parser; -pub mod printer; -pub mod ts_type; -pub mod ts_type_param; -pub mod type_alias; -pub mod variable; - -pub use node::DocNode; -pub use node::DocNodeKind; -pub use node::Location; -pub use params::ParamDef; -pub use parser::DocParser; -pub use printer::DocPrinter; - -#[cfg(test)] -mod tests; - -pub fn find_nodes_by_name_recursively( - doc_nodes: Vec, - name: String, -) -> Vec { - let mut parts = name.splitn(2, '.'); - let name = parts.next(); - let leftover = parts.next(); - if name.is_none() { - return doc_nodes; - } - - let name = name.unwrap(); - let doc_nodes = find_nodes_by_name(doc_nodes, name.to_string()); - - let mut found: Vec = vec![]; - match leftover { - Some(leftover) => { - for node in doc_nodes { - let children = find_children_by_name(node, leftover.to_string()); - found.extend(children); - } - found - } - None => doc_nodes, - } -} - -fn find_nodes_by_name(doc_nodes: Vec, name: String) -> Vec { - let mut found: Vec = vec![]; - for node in doc_nodes { - if node.name == name { - found.push(node); - } - } - found -} - -fn find_children_by_name(node: DocNode, name: String) -> Vec { - match node.kind { - DocNodeKind::Namespace => { - let namespace_def = node.namespace_def.unwrap(); - find_nodes_by_name_recursively(namespace_def.elements, name) - } - // TODO(#4516) handle class, interface etc... - _ => vec![], - } -} diff --git a/cli/doc/module.rs b/cli/doc/module.rs deleted file mode 100644 index 79b1b92bee0e56..00000000000000 --- a/cli/doc/module.rs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::swc_common::Spanned; -use crate::swc_ecma_ast; - -use super::parser::DocParser; -use super::DocNode; -use super::DocNodeKind; - -pub fn get_doc_node_for_export_decl( - doc_parser: &DocParser, - export_decl: &swc_ecma_ast::ExportDecl, -) -> DocNode { - let export_span = export_decl.span(); - use crate::swc_ecma_ast::Decl; - - let js_doc = doc_parser.js_doc_for_span(export_span); - let location = doc_parser.ast_parser.get_span_location(export_span).into(); - - match &export_decl.decl { - Decl::Class(class_decl) => { - let (name, class_def) = - super::class::get_doc_for_class_decl(doc_parser, class_decl); - DocNode { - kind: DocNodeKind::Class, - name, - location, - js_doc, - class_def: Some(class_def), - function_def: None, - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - } - } - Decl::Fn(fn_decl) => { - let (name, function_def) = - super::function::get_doc_for_fn_decl(doc_parser, fn_decl); - DocNode { - kind: DocNodeKind::Function, - name, - location, - js_doc, - function_def: Some(function_def), - class_def: None, - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - } - } - Decl::Var(var_decl) => { - let (name, var_def) = super::variable::get_doc_for_var_decl(var_decl); - DocNode { - kind: DocNodeKind::Variable, - name, - location, - js_doc, - variable_def: Some(var_def), - function_def: None, - class_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - } - } - Decl::TsInterface(ts_interface_decl) => { - let (name, interface_def) = - super::interface::get_doc_for_ts_interface_decl( - doc_parser, - ts_interface_decl, - ); - DocNode { - kind: DocNodeKind::Interface, - name, - location, - js_doc, - interface_def: Some(interface_def), - variable_def: None, - function_def: None, - class_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - } - } - Decl::TsTypeAlias(ts_type_alias) => { - let (name, type_alias_def) = - super::type_alias::get_doc_for_ts_type_alias_decl( - doc_parser, - ts_type_alias, - ); - DocNode { - kind: DocNodeKind::TypeAlias, - name, - location, - js_doc, - type_alias_def: Some(type_alias_def), - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - enum_def: None, - namespace_def: None, - } - } - Decl::TsEnum(ts_enum) => { - let (name, enum_def) = - super::r#enum::get_doc_for_ts_enum_decl(doc_parser, ts_enum); - DocNode { - kind: DocNodeKind::Enum, - name, - location, - js_doc, - enum_def: Some(enum_def), - type_alias_def: None, - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - namespace_def: None, - } - } - Decl::TsModule(ts_module) => { - let (name, namespace_def) = - super::namespace::get_doc_for_ts_module(doc_parser, ts_module); - DocNode { - kind: DocNodeKind::Namespace, - name, - location, - js_doc, - namespace_def: Some(namespace_def), - enum_def: None, - type_alias_def: None, - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - } - } - } -} diff --git a/cli/doc/namespace.rs b/cli/doc/namespace.rs deleted file mode 100644 index 6cbc619e8e03cd..00000000000000 --- a/cli/doc/namespace.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::swc_ecma_ast; -use serde::Serialize; - -use super::parser::DocParser; -use super::DocNode; -use super::DocNodeKind; - -#[derive(Debug, Serialize, Clone)] -pub struct NamespaceDef { - pub elements: Vec, -} - -pub fn get_doc_for_ts_namespace_decl( - doc_parser: &DocParser, - ts_namespace_decl: &swc_ecma_ast::TsNamespaceDecl, -) -> DocNode { - let js_doc = doc_parser.js_doc_for_span(ts_namespace_decl.span); - let location = doc_parser - .ast_parser - .get_span_location(ts_namespace_decl.span) - .into(); - let namespace_name = ts_namespace_decl.id.sym.to_string(); - - use crate::swc_ecma_ast::TsNamespaceBody::*; - - let elements = match &*ts_namespace_decl.body { - TsModuleBlock(ts_module_block) => { - doc_parser.get_doc_nodes_for_module_body(ts_module_block.body.clone()) - } - TsNamespaceDecl(ts_namespace_decl) => { - vec![get_doc_for_ts_namespace_decl(doc_parser, ts_namespace_decl)] - } - }; - - let ns_def = NamespaceDef { elements }; - - DocNode { - kind: DocNodeKind::Namespace, - name: namespace_name, - location, - js_doc, - namespace_def: Some(ns_def), - function_def: None, - variable_def: None, - enum_def: None, - class_def: None, - type_alias_def: None, - interface_def: None, - } -} - -pub fn get_doc_for_ts_module( - doc_parser: &DocParser, - ts_module_decl: &swc_ecma_ast::TsModuleDecl, -) -> (String, NamespaceDef) { - use crate::swc_ecma_ast::TsModuleName; - let namespace_name = match &ts_module_decl.id { - TsModuleName::Ident(ident) => ident.sym.to_string(), - TsModuleName::Str(str_) => str_.value.to_string(), - }; - - let elements = if let Some(body) = &ts_module_decl.body { - use crate::swc_ecma_ast::TsNamespaceBody::*; - - match &body { - TsModuleBlock(ts_module_block) => { - doc_parser.get_doc_nodes_for_module_body(ts_module_block.body.clone()) - } - TsNamespaceDecl(ts_namespace_decl) => { - vec![get_doc_for_ts_namespace_decl(doc_parser, ts_namespace_decl)] - } - } - } else { - vec![] - }; - - let ns_def = NamespaceDef { elements }; - - (namespace_name, ns_def) -} diff --git a/cli/doc/node.rs b/cli/doc/node.rs deleted file mode 100644 index 690221ed001b63..00000000000000 --- a/cli/doc/node.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::swc_common; -use serde::Serialize; - -#[derive(Debug, PartialEq, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub enum DocNodeKind { - Function, - Variable, - Class, - Enum, - Interface, - TypeAlias, - Namespace, -} - -#[derive(Debug, Serialize, Clone, PartialEq)] -pub struct Location { - pub filename: String, - pub line: usize, - pub col: usize, -} - -impl Into for swc_common::Loc { - fn into(self) -> Location { - use crate::swc_common::FileName::*; - - let filename = match &self.file.name { - Real(path_buf) => path_buf.to_string_lossy().to_string(), - Custom(str_) => str_.to_string(), - _ => panic!("invalid filename"), - }; - - Location { - filename, - line: self.line, - col: self.col_display, - } - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub enum ReexportKind { - /// export * from "./path/to/module.js"; - All, - /// export * as someNamespace from "./path/to/module.js"; - Namespace(String), - /// export default from "./path/to/module.js"; - Default, - /// (identifier, optional alias) - /// export { foo } from "./path/to/module.js"; - /// export { foo as bar } from "./path/to/module.js"; - Named(String, Option), -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct Reexport { - pub kind: ReexportKind, - pub src: String, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ModuleDoc { - pub definitions: Vec, - pub reexports: Vec, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct DocNode { - pub kind: DocNodeKind, - pub name: String, - pub location: Location, - pub js_doc: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub function_def: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub variable_def: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub enum_def: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub class_def: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub type_alias_def: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub namespace_def: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub interface_def: Option, -} diff --git a/cli/doc/params.rs b/cli/doc/params.rs deleted file mode 100644 index 3e7967c816e45c..00000000000000 --- a/cli/doc/params.rs +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use super::display::{display_optional, SliceDisplayer}; -use super::ts_type::{ts_type_ann_to_def, TsTypeDef}; -use crate::swc_common::SourceMap; -use crate::swc_ecma_ast; -use crate::swc_ecma_ast::{ObjectPatProp, Pat, TsFnParam}; -use serde::Serialize; -use std::fmt::{Display, Formatter, Result as FmtResult}; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -#[serde(tag = "kind")] -pub enum ParamDef { - #[serde(rename_all = "camelCase")] - Array { - elements: Vec>, - optional: bool, - ts_type: Option, - }, - #[serde(rename_all = "camelCase")] - Assign { - left: Box, - right: String, - ts_type: Option, - }, - #[serde(rename_all = "camelCase")] - Identifier { - name: String, - optional: bool, - ts_type: Option, - }, - #[serde(rename_all = "camelCase")] - Object { - props: Vec, - optional: bool, - ts_type: Option, - }, - #[serde(rename_all = "camelCase")] - Rest { - arg: Box, - ts_type: Option, - }, -} - -impl Display for ParamDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - match self { - Self::Array { - elements, - optional, - ts_type, - } => { - write!(f, "[")?; - if !elements.is_empty() { - if let Some(v) = &elements[0] { - write!(f, "{}", v)?; - } - for maybe_v in &elements[1..] { - write!(f, ", ")?; - if let Some(v) = maybe_v { - write!(f, "{}", v)?; - } - } - } - write!(f, "]")?; - write!(f, "{}", display_optional(*optional))?; - if let Some(ts_type) = ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } - Self::Assign { left, ts_type, .. } => { - write!(f, "{}", left)?; - if let Some(ts_type) = ts_type { - write!(f, ": {}", ts_type)?; - } - // TODO(SyrupThinker) As we cannot display expressions the value is just omitted - // write!(f, " = {}", right)?; - Ok(()) - } - Self::Identifier { - name, - optional, - ts_type, - } => { - write!(f, "{}{}", name, display_optional(*optional))?; - if let Some(ts_type) = ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } - Self::Object { - props, - optional, - ts_type, - } => { - write!( - f, - "{{{}}}{}", - SliceDisplayer::new(&props, ", ", false), - display_optional(*optional) - )?; - if let Some(ts_type) = ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } - Self::Rest { arg, ts_type } => { - write!(f, "...{}", arg)?; - if let Some(ts_type) = ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } - } - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -#[serde(tag = "kind")] -pub enum ObjectPatPropDef { - Assign { key: String, value: Option }, - KeyValue { key: String, value: Box }, - Rest { arg: Box }, -} - -impl Display for ObjectPatPropDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - match self { - Self::KeyValue { key, .. } => { - // The internal identifier does not need to be exposed - write!(f, "{}", key) - } - Self::Assign { key, value } => { - if let Some(_value) = value { - // TODO(SyrupThinker) As we cannot display expressions the value is just omitted - write!(f, "{}", key) - } else { - write!(f, "{}", key) - } - } - Self::Rest { arg } => write!(f, "...{}", arg), - } - } -} - -pub fn ident_to_param_def( - ident: &swc_ecma_ast::Ident, - _source_map: Option<&SourceMap>, -) -> ParamDef { - let ts_type = ident.type_ann.as_ref().map(|rt| ts_type_ann_to_def(rt)); - - ParamDef::Identifier { - name: ident.sym.to_string(), - optional: ident.optional, - ts_type, - } -} - -fn rest_pat_to_param_def( - rest_pat: &swc_ecma_ast::RestPat, - source_map: Option<&SourceMap>, -) -> ParamDef { - let ts_type = rest_pat.type_ann.as_ref().map(|rt| ts_type_ann_to_def(rt)); - - ParamDef::Rest { - arg: Box::new(pat_to_param_def(&*rest_pat.arg, source_map)), - ts_type, - } -} - -fn object_pat_prop_to_def( - object_pat_prop: &ObjectPatProp, - source_map: Option<&SourceMap>, -) -> ObjectPatPropDef { - match object_pat_prop { - ObjectPatProp::Assign(assign) => ObjectPatPropDef::Assign { - key: assign.key.sym.to_string(), - value: assign.value.as_ref().map(|_| "".to_string()), - }, - ObjectPatProp::KeyValue(keyvalue) => ObjectPatPropDef::KeyValue { - key: prop_name_to_string(&keyvalue.key, source_map), - value: Box::new(pat_to_param_def(&*keyvalue.value, source_map)), - }, - ObjectPatProp::Rest(rest) => ObjectPatPropDef::Rest { - arg: Box::new(pat_to_param_def(&*rest.arg, source_map)), - }, - } -} - -fn object_pat_to_param_def( - object_pat: &swc_ecma_ast::ObjectPat, - source_map: Option<&SourceMap>, -) -> ParamDef { - let props = object_pat - .props - .iter() - .map(|prop| object_pat_prop_to_def(prop, source_map)) - .collect::>(); - let ts_type = object_pat - .type_ann - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - ParamDef::Object { - props, - optional: object_pat.optional, - ts_type, - } -} - -fn array_pat_to_param_def( - array_pat: &swc_ecma_ast::ArrayPat, - source_map: Option<&SourceMap>, -) -> ParamDef { - let elements = array_pat - .elems - .iter() - .map(|elem| elem.as_ref().map(|e| pat_to_param_def(e, source_map))) - .collect::>>(); - let ts_type = array_pat.type_ann.as_ref().map(|rt| ts_type_ann_to_def(rt)); - - ParamDef::Array { - elements, - optional: array_pat.optional, - ts_type, - } -} - -pub fn assign_pat_to_param_def( - assign_pat: &swc_ecma_ast::AssignPat, - source_map: Option<&SourceMap>, -) -> ParamDef { - let ts_type = assign_pat - .type_ann - .as_ref() - .map(|rt| ts_type_ann_to_def(rt)); - - ParamDef::Assign { - left: Box::new(pat_to_param_def(&*assign_pat.left, source_map)), - right: "".to_string(), - ts_type, - } -} - -pub fn pat_to_param_def( - pat: &swc_ecma_ast::Pat, - source_map: Option<&SourceMap>, -) -> ParamDef { - match pat { - Pat::Ident(ident) => ident_to_param_def(ident, source_map), - Pat::Array(array_pat) => array_pat_to_param_def(array_pat, source_map), - Pat::Rest(rest_pat) => rest_pat_to_param_def(rest_pat, source_map), - Pat::Object(object_pat) => object_pat_to_param_def(object_pat, source_map), - Pat::Assign(assign_pat) => assign_pat_to_param_def(assign_pat, source_map), - _ => unreachable!(), - } -} - -pub fn ts_fn_param_to_param_def( - ts_fn_param: &swc_ecma_ast::TsFnParam, - source_map: Option<&SourceMap>, -) -> ParamDef { - match ts_fn_param { - TsFnParam::Ident(ident) => ident_to_param_def(ident, source_map), - TsFnParam::Array(array_pat) => { - array_pat_to_param_def(array_pat, source_map) - } - TsFnParam::Rest(rest_pat) => rest_pat_to_param_def(rest_pat, source_map), - TsFnParam::Object(object_pat) => { - object_pat_to_param_def(object_pat, source_map) - } - } -} - -pub fn prop_name_to_string( - prop_name: &swc_ecma_ast::PropName, - source_map: Option<&SourceMap>, -) -> String { - use crate::swc_ecma_ast::PropName; - match prop_name { - PropName::Ident(ident) => ident.sym.to_string(), - PropName::Str(str_) => str_.value.to_string(), - PropName::Num(num) => num.value.to_string(), - PropName::Computed(comp_prop_name) => source_map - .map(|sm| sm.span_to_snippet(comp_prop_name.span).unwrap()) - .unwrap_or_else(|| "".to_string()), - } -} diff --git a/cli/doc/parser.rs b/cli/doc/parser.rs deleted file mode 100644 index 59fa2b7342a763..00000000000000 --- a/cli/doc/parser.rs +++ /dev/null @@ -1,567 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::file_fetcher::map_file_extension; -use crate::op_error::OpError; -use crate::swc_common::comments::CommentKind; -use crate::swc_common::Span; -use crate::swc_ecma_ast; -use crate::swc_ecma_ast::Decl; -use crate::swc_ecma_ast::DefaultDecl; -use crate::swc_ecma_ast::ModuleDecl; -use crate::swc_ecma_ast::Stmt; -use crate::swc_util::AstParser; -use crate::swc_util::SwcDiagnosticBuffer; - -use deno_core::ErrBox; -use deno_core::ModuleSpecifier; -use futures::Future; -use regex::Regex; -use std::collections::HashMap; -use std::path::PathBuf; -use std::pin::Pin; - -use super::namespace::NamespaceDef; -use super::node; -use super::node::ModuleDoc; -use super::DocNode; -use super::DocNodeKind; -use super::Location; - -pub trait DocFileLoader { - fn resolve( - &self, - specifier: &str, - referrer: &str, - ) -> Result { - ModuleSpecifier::resolve_import(specifier, referrer).map_err(OpError::from) - } - - fn load_source_code( - &self, - specifier: &str, - ) -> Pin>>>; -} - -pub struct DocParser { - pub ast_parser: AstParser, - pub loader: Box, - pub private: bool, -} - -impl DocParser { - pub fn new(loader: Box, private: bool) -> Self { - DocParser { - loader, - ast_parser: AstParser::new(), - private, - } - } - - fn parse_module( - &self, - file_name: &str, - source_code: &str, - ) -> Result { - let media_type = map_file_extension(&PathBuf::from(file_name)); - self.ast_parser.parse_module( - file_name, - media_type, - source_code, - |parse_result| { - let module = parse_result?; - let doc_entries = - self.get_doc_nodes_for_module_body(module.body.clone()); - let reexports = self.get_reexports_for_module_body(module.body); - let module_doc = ModuleDoc { - definitions: doc_entries, - reexports, - }; - Ok(module_doc) - }, - ) - } - - pub async fn parse(&self, file_name: &str) -> Result, ErrBox> { - let source_code = self.loader.load_source_code(file_name).await?; - - self.parse_source(file_name, source_code.as_str()) - } - - pub fn parse_source( - &self, - file_name: &str, - source_code: &str, - ) -> Result, ErrBox> { - let module_doc = self.parse_module(file_name, &source_code)?; - Ok(module_doc.definitions) - } - - async fn flatten_reexports( - &self, - reexports: &[node::Reexport], - referrer: &str, - ) -> Result, ErrBox> { - let mut by_src: HashMap> = HashMap::new(); - - let mut processed_reexports: Vec = vec![]; - - for reexport in reexports { - if by_src.get(&reexport.src).is_none() { - by_src.insert(reexport.src.to_string(), vec![]); - } - - let bucket = by_src.get_mut(&reexport.src).unwrap(); - bucket.push(reexport.clone()); - } - - for specifier in by_src.keys() { - let resolved_specifier = self.loader.resolve(specifier, referrer)?; - let doc_nodes = self.parse(&resolved_specifier.to_string()).await?; - let reexports_for_specifier = by_src.get(specifier).unwrap(); - - for reexport in reexports_for_specifier { - match &reexport.kind { - node::ReexportKind::All => { - processed_reexports.extend(doc_nodes.clone()) - } - node::ReexportKind::Namespace(ns_name) => { - let ns_def = NamespaceDef { - elements: doc_nodes.clone(), - }; - let ns_doc_node = DocNode { - kind: DocNodeKind::Namespace, - name: ns_name.to_string(), - location: Location { - filename: specifier.to_string(), - line: 1, - col: 0, - }, - js_doc: None, - namespace_def: Some(ns_def), - enum_def: None, - type_alias_def: None, - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - }; - processed_reexports.push(ns_doc_node); - } - node::ReexportKind::Named(ident, maybe_alias) => { - // Try to find reexport. - // NOTE: the reexport might actually be reexport from another - // module; for now we're skipping nested reexports. - let maybe_doc_node = - doc_nodes.iter().find(|node| &node.name == ident); - - if let Some(doc_node) = maybe_doc_node { - let doc_node = doc_node.clone(); - let doc_node = if let Some(alias) = maybe_alias { - DocNode { - name: alias.to_string(), - ..doc_node - } - } else { - doc_node - }; - - processed_reexports.push(doc_node); - } - } - node::ReexportKind::Default => { - // TODO: handle default export from child module - } - } - } - } - - Ok(processed_reexports) - } - - pub async fn parse_with_reexports( - &self, - file_name: &str, - ) -> Result, ErrBox> { - let source_code = self.loader.load_source_code(file_name).await?; - - let module_doc = self.parse_module(file_name, &source_code)?; - - let flattened_docs = if !module_doc.reexports.is_empty() { - let mut flattenned_reexports = self - .flatten_reexports(&module_doc.reexports, file_name) - .await?; - flattenned_reexports.extend(module_doc.definitions); - flattenned_reexports - } else { - module_doc.definitions - }; - - Ok(flattened_docs) - } - - pub fn get_doc_nodes_for_module_exports( - &self, - module_decl: &ModuleDecl, - ) -> Vec { - match module_decl { - ModuleDecl::ExportDecl(export_decl) => { - vec![super::module::get_doc_node_for_export_decl( - self, - export_decl, - )] - } - ModuleDecl::ExportDefaultDecl(export_default_decl) => { - let (js_doc, location) = - self.details_for_span(export_default_decl.span); - let name = "default".to_string(); - - let doc_node = match &export_default_decl.decl { - DefaultDecl::Class(class_expr) => { - let class_def = - crate::doc::class::class_to_class_def(self, &class_expr.class); - DocNode { - kind: DocNodeKind::Class, - name, - location, - js_doc, - class_def: Some(class_def), - function_def: None, - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - } - } - DefaultDecl::Fn(fn_expr) => { - let function_def = crate::doc::function::function_to_function_def( - self, - &fn_expr.function, - ); - DocNode { - kind: DocNodeKind::Function, - name, - location, - js_doc, - class_def: None, - function_def: Some(function_def), - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - } - } - DefaultDecl::TsInterfaceDecl(interface_decl) => { - let (_, interface_def) = - crate::doc::interface::get_doc_for_ts_interface_decl( - self, - interface_decl, - ); - DocNode { - kind: DocNodeKind::Interface, - name, - location, - js_doc, - class_def: None, - function_def: None, - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: Some(interface_def), - } - } - }; - - vec![doc_node] - } - ModuleDecl::ExportDefaultExpr(_export_default_expr) => vec![], - _ => vec![], - } - } - - pub fn get_doc_node_for_stmt(&self, stmt: &Stmt) -> Option { - match stmt { - Stmt::Decl(decl) => self.get_doc_node_for_decl(decl), - _ => None, - } - } - - fn details_for_span(&self, span: Span) -> (Option, Location) { - let js_doc = self.js_doc_for_span(span); - let location = self.ast_parser.get_span_location(span).into(); - (js_doc, location) - } - - pub fn get_doc_node_for_decl(&self, decl: &Decl) -> Option { - match decl { - Decl::Class(class_decl) => { - if !self.private && !class_decl.declare { - return None; - } - let (name, class_def) = - super::class::get_doc_for_class_decl(self, class_decl); - let (js_doc, location) = self.details_for_span(class_decl.class.span); - Some(DocNode { - kind: DocNodeKind::Class, - name, - location, - js_doc, - class_def: Some(class_def), - function_def: None, - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - }) - } - Decl::Fn(fn_decl) => { - if !self.private && !fn_decl.declare { - return None; - } - let (name, function_def) = - super::function::get_doc_for_fn_decl(self, fn_decl); - let (js_doc, location) = self.details_for_span(fn_decl.function.span); - Some(DocNode { - kind: DocNodeKind::Function, - name, - location, - js_doc, - function_def: Some(function_def), - class_def: None, - variable_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - }) - } - Decl::Var(var_decl) => { - if !self.private && !var_decl.declare { - return None; - } - let (name, var_def) = super::variable::get_doc_for_var_decl(var_decl); - let (js_doc, location) = self.details_for_span(var_decl.span); - Some(DocNode { - kind: DocNodeKind::Variable, - name, - location, - js_doc, - variable_def: Some(var_def), - function_def: None, - class_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - interface_def: None, - }) - } - Decl::TsInterface(ts_interface_decl) => { - if !self.private && !ts_interface_decl.declare { - return None; - } - let (name, interface_def) = - super::interface::get_doc_for_ts_interface_decl( - self, - ts_interface_decl, - ); - let (js_doc, location) = self.details_for_span(ts_interface_decl.span); - Some(DocNode { - kind: DocNodeKind::Interface, - name, - location, - js_doc, - interface_def: Some(interface_def), - variable_def: None, - function_def: None, - class_def: None, - enum_def: None, - type_alias_def: None, - namespace_def: None, - }) - } - Decl::TsTypeAlias(ts_type_alias) => { - if !self.private && !ts_type_alias.declare { - return None; - } - let (name, type_alias_def) = - super::type_alias::get_doc_for_ts_type_alias_decl( - self, - ts_type_alias, - ); - let (js_doc, location) = self.details_for_span(ts_type_alias.span); - Some(DocNode { - kind: DocNodeKind::TypeAlias, - name, - location, - js_doc, - type_alias_def: Some(type_alias_def), - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - enum_def: None, - namespace_def: None, - }) - } - Decl::TsEnum(ts_enum) => { - if !self.private && !ts_enum.declare { - return None; - } - let (name, enum_def) = - super::r#enum::get_doc_for_ts_enum_decl(self, ts_enum); - let (js_doc, location) = self.details_for_span(ts_enum.span); - Some(DocNode { - kind: DocNodeKind::Enum, - name, - location, - js_doc, - enum_def: Some(enum_def), - type_alias_def: None, - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - namespace_def: None, - }) - } - Decl::TsModule(ts_module) => { - if !self.private && !ts_module.declare { - return None; - } - let (name, namespace_def) = - super::namespace::get_doc_for_ts_module(self, ts_module); - let (js_doc, location) = self.details_for_span(ts_module.span); - Some(DocNode { - kind: DocNodeKind::Namespace, - name, - location, - js_doc, - namespace_def: Some(namespace_def), - enum_def: None, - type_alias_def: None, - interface_def: None, - variable_def: None, - function_def: None, - class_def: None, - }) - } - } - } - - pub fn get_reexports_for_module_body( - &self, - module_body: Vec, - ) -> Vec { - use swc_ecma_ast::ExportSpecifier::*; - - let mut reexports: Vec = vec![]; - - for node in module_body.iter() { - if let swc_ecma_ast::ModuleItem::ModuleDecl(module_decl) = node { - let r = match module_decl { - ModuleDecl::ExportNamed(named_export) => { - if let Some(src) = &named_export.src { - let src_str = src.value.to_string(); - named_export - .specifiers - .iter() - .map(|export_specifier| match export_specifier { - Namespace(ns_export) => node::Reexport { - kind: node::ReexportKind::Namespace( - ns_export.name.sym.to_string(), - ), - src: src_str.to_string(), - }, - Default(_) => node::Reexport { - kind: node::ReexportKind::Default, - src: src_str.to_string(), - }, - Named(named_export) => { - let ident = named_export.orig.sym.to_string(); - let maybe_alias = - named_export.exported.as_ref().map(|e| e.sym.to_string()); - let kind = node::ReexportKind::Named(ident, maybe_alias); - node::Reexport { - kind, - src: src_str.to_string(), - } - } - }) - .collect::>() - } else { - vec![] - } - } - ModuleDecl::ExportAll(export_all) => { - let reexport = node::Reexport { - kind: node::ReexportKind::All, - src: export_all.src.value.to_string(), - }; - vec![reexport] - } - _ => vec![], - }; - - reexports.extend(r); - } - } - - reexports - } - - pub fn get_doc_nodes_for_module_body( - &self, - module_body: Vec, - ) -> Vec { - let mut doc_entries: Vec = vec![]; - for node in module_body.iter() { - match node { - swc_ecma_ast::ModuleItem::ModuleDecl(module_decl) => { - doc_entries - .extend(self.get_doc_nodes_for_module_exports(module_decl)); - } - swc_ecma_ast::ModuleItem::Stmt(stmt) => { - if let Some(doc_node) = self.get_doc_node_for_stmt(stmt) { - doc_entries.push(doc_node); - } - } - } - } - doc_entries - } - - pub fn js_doc_for_span(&self, span: Span) -> Option { - let comments = self.ast_parser.get_span_comments(span); - let js_doc_comment = comments.iter().rev().find(|comment| { - comment.kind == CommentKind::Block && comment.text.starts_with('*') - })?; - - let mut margin_pat = String::from(""); - if let Some(margin) = self.ast_parser.source_map.span_to_margin(span) { - for _ in 0..margin { - margin_pat.push(' '); - } - } - - let js_doc_re = Regex::new(r#" ?\* ?"#).unwrap(); - let txt = js_doc_comment - .text - .split('\n') - .map(|line| js_doc_re.replace(line, "").to_string()) - .map(|line| { - if line.starts_with(&margin_pat) { - line[margin_pat.len()..].to_string() - } else { - line - } - }) - .collect::>() - .join("\n"); - - let txt = txt.trim_start().trim_end().to_string(); - - Some(txt) - } -} diff --git a/cli/doc/printer.rs b/cli/doc/printer.rs deleted file mode 100644 index 2e55c752a6950f..00000000000000 --- a/cli/doc/printer.rs +++ /dev/null @@ -1,474 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -// TODO(ry) This module builds up output by appending to a string. Instead it -// should either use a formatting trait -// https://doc.rust-lang.org/std/fmt/index.html#formatting-traits -// Or perhaps implement a Serializer for serde -// https://docs.serde.rs/serde/ser/trait.Serializer.html - -// TODO(ry) The methods in this module take ownership of the DocNodes, this is -// unnecessary and can result in unnecessary copying. Instead they should take -// references. - -use crate::colors; -use crate::doc; -use crate::doc::display::{ - display_abstract, display_async, display_generator, Indent, SliceDisplayer, -}; -use crate::doc::DocNodeKind; -use crate::swc_ecma_ast; -use std::fmt::{Display, Formatter, Result as FmtResult}; - -pub struct DocPrinter<'a> { - doc_nodes: &'a [doc::DocNode], - details: bool, - private: bool, -} - -impl<'a> DocPrinter<'a> { - pub fn new( - doc_nodes: &[doc::DocNode], - details: bool, - private: bool, - ) -> DocPrinter { - DocPrinter { - doc_nodes, - details, - private, - } - } - - pub fn format(&self, w: &mut Formatter<'_>) -> FmtResult { - if self.details { - self.format_details(w, self.doc_nodes, 0) - } else { - self.format_summary(w, self.doc_nodes, 0) - } - } - - fn format_summary( - &self, - w: &mut Formatter<'_>, - doc_nodes: &[doc::DocNode], - indent: i64, - ) -> FmtResult { - let mut sorted = Vec::from(doc_nodes); - sorted.sort_unstable_by(|a, b| { - let kind_cmp = self.kind_order(&a.kind).cmp(&self.kind_order(&b.kind)); - if kind_cmp == core::cmp::Ordering::Equal { - a.name.cmp(&b.name) - } else { - kind_cmp - } - }); - - for node in sorted { - self.format_signature(w, &node, indent)?; - - if let Some(js_doc) = &node.js_doc { - self.format_jsdoc(w, js_doc, indent + 1, self.details)?; - } - - writeln!(w)?; - - if DocNodeKind::Namespace == node.kind { - self.format_summary( - w, - &node.namespace_def.as_ref().unwrap().elements, - indent + 1, - )?; - - writeln!(w)?; - }; - } - - Ok(()) - } - - fn format_details( - &self, - w: &mut Formatter<'_>, - doc_nodes: &[doc::DocNode], - indent: i64, - ) -> FmtResult { - for node in doc_nodes { - write!( - w, - "{}", - colors::italic_gray(&format!( - "Defined in {}:{}:{} \n\n", - node.location.filename, node.location.line, node.location.col - )) - )?; - - self.format_signature(w, &node, indent)?; - - let js_doc = &node.js_doc; - if let Some(js_doc) = js_doc { - self.format_jsdoc(w, js_doc, indent + 1, self.details)?; - } - writeln!(w)?; - - match node.kind { - DocNodeKind::Class => self.format_class_details(w, node)?, - DocNodeKind::Enum => self.format_enum_details(w, node)?, - DocNodeKind::Interface => self.format_interface_details(w, node)?, - DocNodeKind::Namespace => self.format_namespace_details(w, node)?, - _ => {} - } - } - - Ok(()) - } - - fn kind_order(&self, kind: &doc::DocNodeKind) -> i64 { - match kind { - DocNodeKind::Function => 0, - DocNodeKind::Variable => 1, - DocNodeKind::Class => 2, - DocNodeKind::Enum => 3, - DocNodeKind::Interface => 4, - DocNodeKind::TypeAlias => 5, - DocNodeKind::Namespace => 6, - } - } - - fn format_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - match node.kind { - DocNodeKind::Function => self.format_function_signature(w, node, indent), - DocNodeKind::Variable => self.format_variable_signature(w, node, indent), - DocNodeKind::Class => self.format_class_signature(w, node, indent), - DocNodeKind::Enum => self.format_enum_signature(w, node, indent), - DocNodeKind::Interface => { - self.format_interface_signature(w, node, indent) - } - DocNodeKind::TypeAlias => { - self.format_type_alias_signature(w, node, indent) - } - DocNodeKind::Namespace => { - self.format_namespace_signature(w, node, indent) - } - } - } - - // TODO(SyrupThinker) this should use a JSDoc parser - fn format_jsdoc( - &self, - w: &mut Formatter<'_>, - jsdoc: &str, - indent: i64, - details: bool, - ) -> FmtResult { - for line in jsdoc.lines() { - // Only show the first paragraph when summarising - // This should use the @summary JSDoc tag instead - if !details && line.is_empty() { - break; - } - - writeln!(w, "{}{}", Indent(indent), colors::gray(&line))?; - } - - Ok(()) - } - - fn format_class_details( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - ) -> FmtResult { - let class_def = node.class_def.as_ref().unwrap(); - for node in &class_def.constructors { - writeln!(w, "{}{}", Indent(1), node,)?; - if let Some(js_doc) = &node.js_doc { - self.format_jsdoc(w, &js_doc, 2, self.details)?; - } - } - for node in class_def.properties.iter().filter(|node| { - self.private - || node - .accessibility - .unwrap_or(swc_ecma_ast::Accessibility::Public) - != swc_ecma_ast::Accessibility::Private - }) { - writeln!(w, "{}{}", Indent(1), node,)?; - if let Some(js_doc) = &node.js_doc { - self.format_jsdoc(w, &js_doc, 2, self.details)?; - } - } - for index_sign_def in &class_def.index_signatures { - writeln!(w, "{}{}", Indent(1), index_sign_def)?; - } - for node in class_def.methods.iter().filter(|node| { - self.private - || node - .accessibility - .unwrap_or(swc_ecma_ast::Accessibility::Public) - != swc_ecma_ast::Accessibility::Private - }) { - writeln!(w, "{}{}", Indent(1), node,)?; - if let Some(js_doc) = &node.js_doc { - self.format_jsdoc(w, js_doc, 2, self.details)?; - } - } - writeln!(w) - } - - fn format_enum_details( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - ) -> FmtResult { - let enum_def = node.enum_def.as_ref().unwrap(); - for member in &enum_def.members { - writeln!(w, "{}{}", Indent(1), colors::bold(&member.name))?; - } - writeln!(w) - } - - fn format_interface_details( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - ) -> FmtResult { - let interface_def = node.interface_def.as_ref().unwrap(); - - for property_def in &interface_def.properties { - writeln!(w, "{}{}", Indent(1), property_def)?; - if let Some(js_doc) = &property_def.js_doc { - self.format_jsdoc(w, js_doc, 2, self.details)?; - } - } - for method_def in &interface_def.methods { - writeln!(w, "{}{}", Indent(1), method_def)?; - if let Some(js_doc) = &method_def.js_doc { - self.format_jsdoc(w, js_doc, 2, self.details)?; - } - } - for index_sign_def in &interface_def.index_signatures { - writeln!(w, "{}{}", Indent(1), index_sign_def)?; - } - writeln!(w) - } - - fn format_namespace_details( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - ) -> FmtResult { - let elements = &node.namespace_def.as_ref().unwrap().elements; - for node in elements { - self.format_signature(w, &node, 1)?; - if let Some(js_doc) = &node.js_doc { - self.format_jsdoc(w, js_doc, 2, false)?; - } - } - writeln!(w) - } - - fn format_class_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - let class_def = node.class_def.as_ref().unwrap(); - write!( - w, - "{}{}{} {}", - Indent(indent), - display_abstract(class_def.is_abstract), - colors::magenta("class"), - colors::bold(&node.name), - )?; - if !class_def.type_params.is_empty() { - write!( - w, - "<{}>", - SliceDisplayer::new(&class_def.type_params, ", ", false) - )?; - } - - if let Some(extends) = &class_def.extends { - write!(w, " {} {}", colors::magenta("extends"), extends)?; - } - if !class_def.super_type_params.is_empty() { - write!( - w, - "<{}>", - SliceDisplayer::new(&class_def.super_type_params, ", ", false) - )?; - } - - if !class_def.implements.is_empty() { - write!( - w, - " {} {}", - colors::magenta("implements"), - SliceDisplayer::new(&class_def.implements, ", ", false) - )?; - } - - writeln!(w) - } - - fn format_enum_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - writeln!( - w, - "{}{} {}", - Indent(indent), - colors::magenta("enum"), - colors::bold(&node.name) - ) - } - - fn format_function_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - let function_def = node.function_def.as_ref().unwrap(); - write!( - w, - "{}{}{}{} {}", - Indent(indent), - display_async(function_def.is_async), - colors::magenta("function"), - display_generator(function_def.is_generator), - colors::bold(&node.name) - )?; - if !function_def.type_params.is_empty() { - write!( - w, - "<{}>", - SliceDisplayer::new(&function_def.type_params, ", ", false) - )?; - } - write!( - w, - "({})", - SliceDisplayer::new(&function_def.params, ", ", false) - )?; - if let Some(return_type) = &function_def.return_type { - write!(w, ": {}", return_type)?; - } - writeln!(w) - } - - fn format_interface_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - let interface_def = node.interface_def.as_ref().unwrap(); - write!( - w, - "{}{} {}", - Indent(indent), - colors::magenta("interface"), - colors::bold(&node.name) - )?; - - if !interface_def.type_params.is_empty() { - write!( - w, - "<{}>", - SliceDisplayer::new(&interface_def.type_params, ", ", false) - )?; - } - - if !interface_def.extends.is_empty() { - write!( - w, - " {} {}", - colors::magenta("extends"), - SliceDisplayer::new(&interface_def.extends, ", ", false) - )?; - } - - writeln!(w) - } - - fn format_type_alias_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - let type_alias_def = node.type_alias_def.as_ref().unwrap(); - write!( - w, - "{}{} {}", - Indent(indent), - colors::magenta("type"), - colors::bold(&node.name), - )?; - - if !type_alias_def.type_params.is_empty() { - write!( - w, - "<{}>", - SliceDisplayer::new(&type_alias_def.type_params, ", ", false) - )?; - } - - writeln!(w, " = {}", type_alias_def.ts_type) - } - - fn format_namespace_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - writeln!( - w, - "{}{} {}", - Indent(indent), - colors::magenta("namespace"), - colors::bold(&node.name) - ) - } - - fn format_variable_signature( - &self, - w: &mut Formatter<'_>, - node: &doc::DocNode, - indent: i64, - ) -> FmtResult { - let variable_def = node.variable_def.as_ref().unwrap(); - write!( - w, - "{}{} {}", - Indent(indent), - colors::magenta(match variable_def.kind { - swc_ecma_ast::VarDeclKind::Const => "const", - swc_ecma_ast::VarDeclKind::Let => "let", - swc_ecma_ast::VarDeclKind::Var => "var", - }), - colors::bold(&node.name), - )?; - if let Some(ts_type) = &variable_def.ts_type { - write!(w, ": {}", ts_type)?; - } - writeln!(w) - } -} - -impl<'a> Display for DocPrinter<'a> { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - self.format(f) - } -} diff --git a/cli/doc/tests.rs b/cli/doc/tests.rs deleted file mode 100644 index e46fff62105571..00000000000000 --- a/cli/doc/tests.rs +++ /dev/null @@ -1,2073 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use super::DocParser; -use super::DocPrinter; -use crate::colors; -use serde_json::json; - -use super::parser::DocFileLoader; -use crate::op_error::OpError; -use std::collections::HashMap; - -use futures::Future; -use futures::FutureExt; -use std::pin::Pin; - -pub struct TestLoader { - files: HashMap, -} - -impl TestLoader { - pub fn new(files_vec: Vec<(String, String)>) -> Box { - let mut files = HashMap::new(); - - for file_tuple in files_vec { - files.insert(file_tuple.0, file_tuple.1); - } - - Box::new(Self { files }) - } -} - -impl DocFileLoader for TestLoader { - fn load_source_code( - &self, - specifier: &str, - ) -> Pin>>> { - let res = match self.files.get(specifier) { - Some(source_code) => Ok(source_code.to_string()), - None => Err(OpError::other("not found".to_string())), - }; - - async move { res }.boxed_local() - } -} - -macro_rules! doc_test { - ( $name:ident, $source:expr; $block:block ) => { - doc_test!($name, $source, false, false; $block); - }; - - ( $name:ident, $source:expr, details; $block:block ) => { - doc_test!($name, $source, true, false; $block); - }; - - ( $name:ident, $source:expr, private; $block:block ) => { - doc_test!($name, $source, false, true; $block); - }; - - ( $name:ident, $source:expr, details, private; $block:block ) => { - doc_test!($name, $source, true, true; $block); - }; - - ( $name:ident, $source:expr, $details:expr, $private:expr; $block:block ) => { - #[tokio::test] - async fn $name() { - let source_code = $source; - let details = $details; - let private = $private; - - let loader = - TestLoader::new(vec![("test.ts".to_string(), source_code.to_string())]); - let entries = DocParser::new(loader, private) - .parse("test.ts") - .await - .unwrap(); - - let doc = DocPrinter::new(&entries, details, private).to_string(); - #[allow(unused_variables)] - let doc = colors::strip_ansi_codes(&doc); - - $block - } - }; -} - -macro_rules! contains_test { - ( $name:ident, $source:expr; - $( $contains:expr ),* $( ; $( $notcontains:expr ),* )? ) => { - contains_test!($name, $source, false, false; $($contains),* $(;$($notcontains),*)?); - }; - - ( $name:ident, $source:expr, details; - $( $contains:expr ),* $( ; $( $notcontains:expr ),* )? ) => { - contains_test!($name, $source, true, false; $($contains),* $(;$($notcontains),*)?); - }; - - ( $name:ident, $source:expr, private; - $( $contains:expr ),* $( ; $( $notcontains:expr ),* )? ) => { - contains_test!($name, $source, false, true; $($contains),* $(;$($notcontains),*)?); - }; - - ( $name:ident, $source:expr, details, private; - $( $contains:expr ),* $( ; $( $notcontains:expr ),* )? ) => { - contains_test!($name, $source, true, true; $($contains),* $(;$($notcontains),*)?); - }; - - ( $name:ident, $source:expr, $details:expr, $private:expr; - $( $contains:expr ),* $( ; $( $notcontains:expr ),* )? ) => { - doc_test!($name, $source, $details, $private; { - $( - assert!(doc.contains($contains)); - )* - $( - $( - assert!(!doc.contains($notcontains)); - )* - )? - }); - }; -} - -macro_rules! json_test { - ( $name:ident, $source:expr; $json:tt ) => { - json_test!($name, $source, false; $json); - }; - - ( $name:ident, $source:expr, private; $json:tt ) => { - json_test!($name, $source, true; $json); - }; - - ( $name:ident, $source:expr, $private:expr; $json:tt ) => { - doc_test!($name, $source, false, $private; { - let actual = serde_json::to_value(&entries).unwrap(); - let expected_json = json!($json); - assert_eq!(actual, expected_json); - }); - }; -} - -#[tokio::test] -async fn reexports() { - let nested_reexport_source_code = r#" -/** - * JSDoc for bar - */ -export const bar = "bar"; - -export default 42; -"#; - let reexport_source_code = r#" -import { bar } from "./nested_reexport.ts"; - -/** - * JSDoc for const - */ -export const foo = "foo"; -"#; - let test_source_code = r#" -export { default, foo as fooConst } from "./reexport.ts"; - -/** JSDoc for function */ -export function fooFn(a: number) { - return a; -} -"#; - let loader = TestLoader::new(vec![ - ("file:///test.ts".to_string(), test_source_code.to_string()), - ( - "file:///reexport.ts".to_string(), - reexport_source_code.to_string(), - ), - ( - "file:///nested_reexport.ts".to_string(), - nested_reexport_source_code.to_string(), - ), - ]); - let entries = DocParser::new(loader, false) - .parse_with_reexports("file:///test.ts") - .await - .unwrap(); - assert_eq!(entries.len(), 2); - - let expected_json = json!([ - { - "kind": "variable", - "name": "fooConst", - "location": { - "filename": "file:///reexport.ts", - "line": 7, - "col": 0 - }, - "jsDoc": "JSDoc for const", - "variableDef": { - "tsType": null, - "kind": "const" - } - }, - { - "kind": "function", - "name": "fooFn", - "location": { - "filename": "file:///test.ts", - "line": 5, - "col": 0 - }, - "jsDoc": "JSDoc for function", - "functionDef": { - "params": [ - { - "name": "a", - "kind": "identifier", - "optional": false, - "tsType": { - "keyword": "number", - "kind": "keyword", - "repr": "number", - }, - } - ], - "typeParams": [], - "returnType": null, - "isAsync": false, - "isGenerator": false - } - } - ]); - let actual = serde_json::to_value(&entries).unwrap(); - assert_eq!(actual, expected_json); - - assert!(colors::strip_ansi_codes( - DocPrinter::new(&entries, false, false).to_string().as_str() - ) - .contains("function fooFn(a: number)")); -} - -#[tokio::test] -async fn filter_nodes_by_name() { - use super::find_nodes_by_name_recursively; - let source_code = r#" -export namespace Deno { - export class Buffer {} - export function test(options: object): void; - export function test(name: string, fn: Function): void; - export function test(name: string | object, fn?: Function): void {} -} - -export namespace Deno { - export namespace Inner { - export function a(): void {} - export const b = 100; - } -} -"#; - let loader = - TestLoader::new(vec![("test.ts".to_string(), source_code.to_string())]); - let entries = DocParser::new(loader, false) - .parse("test.ts") - .await - .unwrap(); - - let found = - find_nodes_by_name_recursively(entries.clone(), "Deno".to_string()); - assert_eq!(found.len(), 2); - assert_eq!(found[0].name, "Deno".to_string()); - assert_eq!(found[1].name, "Deno".to_string()); - - let found = - find_nodes_by_name_recursively(entries.clone(), "Deno.test".to_string()); - assert_eq!(found.len(), 3); - assert_eq!(found[0].name, "test".to_string()); - assert_eq!(found[1].name, "test".to_string()); - assert_eq!(found[2].name, "test".to_string()); - - let found = - find_nodes_by_name_recursively(entries.clone(), "Deno.Inner.a".to_string()); - assert_eq!(found.len(), 1); - assert_eq!(found[0].name, "a".to_string()); - - let found = - find_nodes_by_name_recursively(entries.clone(), "Deno.test.a".to_string()); - assert_eq!(found.len(), 0); - - let found = find_nodes_by_name_recursively(entries, "a.b.c".to_string()); - assert_eq!(found.len(), 0); -} - -mod serialization { - use super::*; - - json_test!(declare_namespace, - r#" -/** Namespace JSdoc */ -declare namespace RootNs { - declare const a = "a"; - - /** Nested namespace JSDoc */ - declare namespace NestedNs { - declare enum Foo { - a = 1, - b = 2, - c = 3, - } - } -} - "#; - [{ - "kind": "namespace", - "name": "RootNs", - "location": { - "filename": "test.ts", - "line": 3, - "col": 0 - }, - "jsDoc": "Namespace JSdoc", - "namespaceDef": { - "elements": [ - { - "kind": "variable", - "name": "a", - "location": { - "filename": "test.ts", - "line": 4, - "col": 12 - }, - "jsDoc": null, - "variableDef": { - "tsType": null, - "kind": "const" - } - }, - { - "kind": "namespace", - "name": "NestedNs", - "location": { - "filename": "test.ts", - "line": 7, - "col": 4 - }, - "jsDoc": "Nested namespace JSDoc", - "namespaceDef": { - "elements": [ - { - "kind": "enum", - "name": "Foo", - "location": { - "filename": "test.ts", - "line": 8, - "col": 6 - }, - "jsDoc": null, - "enumDef": { - "members": [ - { - "name": "a" - }, - { - "name": "b" - }, - { - "name": "c" - } - ] - } - } - ] - } - } - ] - } - }]); - - json_test!(export_class, - r#" -/** Class doc */ -export class Foobar extends Fizz implements Buzz, Aldrin { - private private1?: boolean; - protected protected1: number; - public public1: boolean; - public2: number; - - /** Constructor js doc */ - constructor(name: string, private private2: number, protected protected2: number) {} - - /** Async foo method */ - async foo(): Promise { - // - } - - /** Sync bar method */ - bar?(): void { - // - } -} - "#; - [{ - "kind": "class", - "name": "Foobar", - "location": { - "filename": "test.ts", - "line": 3, - "col": 0 - }, - "jsDoc": "Class doc", - "classDef": { - "isAbstract": false, - "extends": "Fizz", - "implements": [ - { - "repr": "Buzz", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "Buzz" - } - }, - { - "repr": "Aldrin", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "Aldrin" - } - } - ], - "typeParams": [], - "superTypeParams": [], - "constructors": [ - { - "jsDoc": "Constructor js doc", - "accessibility": null, - "name": "constructor", - "params": [ - { - "name": "name", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "string", - "kind": "keyword", - "keyword": "string" - } - }, - { - "name": "private2", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - }, - { - "name": "protected2", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - } - ], - "location": { - "filename": "test.ts", - "line": 10, - "col": 4 - } - } - ], - "properties": [ - { - "jsDoc": null, - "tsType": { - "repr": "boolean", - "kind": "keyword", - "keyword": "boolean" - }, - "readonly": false, - "accessibility": "private", - "optional": true, - "isAbstract": false, - "isStatic": false, - "name": "private1", - "location": { - "filename": "test.ts", - "line": 4, - "col": 4 - } - }, - { - "jsDoc": null, - "tsType": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - }, - "readonly": false, - "accessibility": "protected", - "optional": false, - "isAbstract": false, - "isStatic": false, - "name": "protected1", - "location": { - "filename": "test.ts", - "line": 5, - "col": 4 - } - }, - { - "jsDoc": null, - "tsType": { - "repr": "boolean", - "kind": "keyword", - "keyword": "boolean" - }, - "readonly": false, - "accessibility": "public", - "optional": false, - "isAbstract": false, - "isStatic": false, - "name": "public1", - "location": { - "filename": "test.ts", - "line": 6, - "col": 4 - } - }, - { - "jsDoc": null, - "tsType": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - }, - "readonly": false, - "accessibility": null, - "optional": false, - "isAbstract": false, - "isStatic": false, - "name": "public2", - "location": { - "filename": "test.ts", - "line": 7, - "col": 4 - } - } - ], - "indexSignatures": [], - "methods": [ - { - "jsDoc": "Async foo method", - "accessibility": null, - "optional": false, - "isAbstract": false, - "isStatic": false, - "name": "foo", - "kind": "method", - "functionDef": { - "params": [], - "returnType": { - "repr": "Promise", - "kind": "typeRef", - "typeRef": { - "typeParams": [ - { - "repr": "void", - "kind": "keyword", - "keyword": "void" - } - ], - "typeName": "Promise" - } - }, - "typeParams": [], - "isAsync": true, - "isGenerator": false - }, - "location": { - "filename": "test.ts", - "line": 13, - "col": 4 - } - }, - { - "jsDoc": "Sync bar method", - "accessibility": null, - "optional": true, - "isAbstract": false, - "isStatic": false, - "name": "bar", - "kind": "method", - "functionDef": { - "params": [], - "returnType": { - "repr": "void", - "kind": "keyword", - "keyword": "void" - }, - "isAsync": false, - "isGenerator": false, - "typeParams": [] - }, - "location": { - "filename": "test.ts", - "line": 18, - "col": 4 - } - } - ] - } - }]); - - json_test!(export_const, - r#" -/** Something about fizzBuzz */ -export const fizzBuzz = "fizzBuzz"; - -export const env: { - /** get doc */ - get(key: string): string | undefined; - - /** set doc */ - set(key: string, value: string): void; -} - "#; - [ - { - "kind":"variable", - "name":"fizzBuzz", - "location":{ - "filename":"test.ts", - "line":3, - "col":0 - }, - "jsDoc":"Something about fizzBuzz", - "variableDef":{ - "tsType":null, - "kind":"const" - } - }, - { - "kind":"variable", - "name":"env", - "location":{ - "filename":"test.ts", - "line":5, - "col":0 - }, - "jsDoc":null, - "variableDef":{ - "tsType":{ - "repr":"", - "kind":"typeLiteral", - "typeLiteral":{ - "methods":[{ - "name":"get", - "params":[ - { - "name":"key", - "kind":"identifier", - "optional":false, - "tsType":{ - "repr":"string", - "kind":"keyword", - "keyword":"string" - } - } - ], - "returnType":{ - "repr":"", - "kind":"union", - "union":[ - { - "repr":"string", - "kind":"keyword", - "keyword":"string" - }, - { - "repr":"undefined", - "kind":"keyword", - "keyword":"undefined" - } - ] - }, - "typeParams":[] - }, { - "name":"set", - "params":[ - { - "name":"key", - "kind":"identifier", - "optional":false, - "tsType":{ - "repr":"string", - "kind":"keyword", - "keyword":"string" - } - }, - { - "name":"value", - "kind":"identifier", - "optional":false, - "tsType":{ - "repr":"string", - "kind":"keyword", - "keyword":"string" - } - } - ], - "returnType":{ - "repr":"void", - "kind":"keyword", - "keyword":"void" - }, - "typeParams":[] - } - ], - "properties":[], - "callSignatures":[], - "indexSignatures": [] - } - }, - "kind":"const" - } - } - ] - ); - - json_test!(export_default_class, - r#" -/** Class doc */ -export default class Foobar { - /** Constructor js doc */ - constructor(name: string, private private2: number, protected protected2: number) {} -} - "#; - [{ - "kind": "class", - "name": "default", - "location": { - "filename": "test.ts", - "line": 3, - "col": 0 - }, - "jsDoc": "Class doc", - "classDef": { - "isAbstract": false, - "extends": null, - "implements": [], - "typeParams": [], - "superTypeParams": [], - "constructors": [ - { - "jsDoc": "Constructor js doc", - "accessibility": null, - "name": "constructor", - "params": [ - { - "name": "name", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "string", - "kind": "keyword", - "keyword": "string" - } - }, - { - "name": "private2", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - }, - { - "name": "protected2", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - } - ], - "location": { - "filename": "test.ts", - "line": 5, - "col": 4 - } - } - ], - "properties": [], - "indexSignatures": [], - "methods": [] - } - }]); - - json_test!(export_default_fn, - r#" -export default function foo(a: number) { - return a; -} - "#; - [{ - "kind": "function", - "name": "default", - "location": { - "filename": "test.ts", - "line": 2, - "col": 15 - }, - "jsDoc": null, - "functionDef": { - "params": [ - { - "name": "a", - "kind": "identifier", - "optional": false, - "tsType": { - "keyword": "number", - "kind": "keyword", - "repr": "number", - }, - } - ], - "typeParams": [], - "returnType": null, - "isAsync": false, - "isGenerator": false - } - }]); - - json_test!(export_default_interface, - r#" -/** - * Interface js doc - */ -export default interface Reader { - /** Read n bytes */ - read?(buf: Uint8Array, something: unknown): Promise -} - "#; - [{ - "kind": "interface", - "name": "default", - "location": { - "filename": "test.ts", - "line": 5, - "col": 0 - }, - "jsDoc": "Interface js doc", - "interfaceDef": { - "extends": [], - "methods": [ - { - "name": "read", - "location": { - "filename": "test.ts", - "line": 7, - "col": 4 - }, - "optional": true, - "jsDoc": "Read n bytes", - "params": [ - { - "name": "buf", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "Uint8Array", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "Uint8Array" - } - } - }, - { - "name": "something", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "unknown", - "kind": "keyword", - "keyword": "unknown" - } - } - ], - "typeParams": [], - "returnType": { - "repr": "Promise", - "kind": "typeRef", - "typeRef": { - "typeParams": [ - { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - ], - "typeName": "Promise" - } - } - } - ], - "properties": [], - "callSignatures": [], - "indexSignatures": [], - "typeParams": [] - } - }]); - - json_test!(export_enum, - r#" -/** - * Some enum for good measure - */ -export enum Hello { - World = "world", - Fizz = "fizz", - Buzz = "buzz", -} - "#; - [{ - "kind": "enum", - "name": "Hello", - "location": { - "filename": "test.ts", - "line": 5, - "col": 0 - }, - "jsDoc": "Some enum for good measure", - "enumDef": { - "members": [ - { - "name": "World" - }, - { - "name": "Fizz" - }, - { - "name": "Buzz" - } - ] - } - }]); - - json_test!(export_fn, - r#"/** -* @module foo -*/ - -/** -* Hello there, this is a multiline JSdoc. -* -* It has many lines -* -* Or not that many? -*/ -export function foo(a: string, b?: number, cb: (...cbArgs: unknown[]) => void, ...args: unknown[]): void { - /** - * @todo document all the things. - */ - console.log("Hello world"); -} - "#; - [{ - "functionDef": { - "isAsync": false, - "isGenerator": false, - "typeParams": [], - "params": [ - { - "name": "a", - "kind": "identifier", - "optional": false, - "tsType": { - "keyword": "string", - "kind": "keyword", - "repr": "string", - }, - }, - { - "name": "b", - "kind": "identifier", - "optional": true, - "tsType": { - "keyword": "number", - "kind": "keyword", - "repr": "number", - }, - }, - { - "name": "cb", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "", - "kind": "fnOrConstructor", - "fnOrConstructor": { - "constructor": false, - "tsType": { - "keyword": "void", - "kind": "keyword", - "repr": "void" - }, - "typeParams": [], - "params": [{ - "arg": { - "name": "cbArgs", - "kind": "identifier", - "optional": false, - "tsType": null - }, - "kind": "rest", - "tsType": { - "repr": "", - "kind": "array", - "array": { - "repr": "unknown", - "kind": "keyword", - "keyword": "unknown" - } - }, - }] - } - }, - }, - { - "arg": { - "name": "args", - "kind": "identifier", - "optional": false, - "tsType": null - }, - "kind": "rest", - "tsType": { - "array": { - "keyword": "unknown", - "kind": "keyword", - "repr": "unknown" - }, - "kind": "array", - "repr": "" - } - } - ], - "returnType": { - "keyword": "void", - "kind": "keyword", - "repr": "void", - }, - }, - "jsDoc": "Hello there, this is a multiline JSdoc.\n\nIt has many lines\n\nOr not that many?", - "kind": "function", - "location": { - "col": 0, - "filename": "test.ts", - "line": 12, - }, - "name": "foo", - }]); - - json_test!(export_fn2, - r#" -interface AssignOpts { - a: string; - b: number; -} - -export function foo([e,,f, ...g]: number[], { c, d: asdf, i = "asdf", ...rest}, ops: AssignOpts = {}): void { - console.log("Hello world"); -} - "#; - [{ - "functionDef": { - "isAsync": false, - "isGenerator": false, - "typeParams": [], - "params": [ - { - "elements": [ - { - "name": "e", - "kind": "identifier", - "optional": false, - "tsType": null - }, - null, - { - "name": "f", - "kind": "identifier", - "optional": false, - "tsType": null - }, - { - "arg": { - "name": "g", - "kind": "identifier", - "optional": false, - "tsType": null - }, - "kind": "rest", - "tsType": null - } - ], - "kind": "array", - "optional": false, - "tsType": { - "repr": "", - "kind": "array", - "array": { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - } - }, - { - "kind": "object", - "optional": false, - "props": [ - { - "kind": "assign", - "key": "c", - "value": null - }, - { - "kind": "keyValue", - "key": "d", - "value": { - "name": "asdf", - "kind": "identifier", - "optional": false, - "tsType": null - } - }, - { - "kind": "assign", - "key": "i", - "value": "" - }, - { - "arg": { - "name": "rest", - "kind": "identifier", - "optional": false, - "tsType": null - }, - "kind": "rest" - } - ], - "tsType": null - }, - { - "kind": "assign", - "left": { - "name": "ops", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "AssignOpts", - "kind": "typeRef", - "typeRef": { - "typeName": "AssignOpts", - "typeParams": null, - } - } - }, - "right": "", - "tsType": null - } - ], - "returnType": { - "keyword": "void", - "kind": "keyword", - "repr": "void", - }, - }, - "jsDoc": null, - "kind": "function", - "location": { - "col": 0, - "filename": "test.ts", - "line": 7, - }, - "name": "foo", - }]); - - json_test!(export_interface, - r#" -interface Foo { - foo(): void; -} -interface Bar { - bar(): void; -} -/** - * Interface js doc - */ -export interface Reader extends Foo, Bar { - /** Read n bytes */ - read?(buf: Uint8Array, something: unknown): Promise -} - "#; - [{ - "kind": "interface", - "name": "Reader", - "location": { - "filename": "test.ts", - "line": 11, - "col": 0 - }, - "jsDoc": "Interface js doc", - "interfaceDef": { - "extends": [ - { - "repr": "Foo", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "Foo" - } - }, - { - "repr": "Bar", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "Bar" - } - } - ], - "methods": [ - { - "name": "read", - "location": { - "filename": "test.ts", - "line": 13, - "col": 4 - }, - "optional": true, - "jsDoc": "Read n bytes", - "params": [ - { - "name": "buf", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "Uint8Array", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "Uint8Array" - } - } - }, - { - "name": "something", - "kind": "identifier", - "optional": false, - "tsType": { - "repr": "unknown", - "kind": "keyword", - "keyword": "unknown" - } - } - ], - "typeParams": [], - "returnType": { - "repr": "Promise", - "kind": "typeRef", - "typeRef": { - "typeParams": [ - { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - ], - "typeName": "Promise" - } - } - } - ], - "properties": [], - "callSignatures": [], - "indexSignatures": [], - "typeParams": [], - } - }]); - - json_test!(export_interface2, - r#" -export interface TypedIface { - something(): T -} - "#; - [{ - "kind": "interface", - "name": "TypedIface", - "location": { - "filename": "test.ts", - "line": 2, - "col": 0 - }, - "jsDoc": null, - "interfaceDef": { - "extends": [], - "methods": [ - { - "name": "something", - "location": { - "filename": "test.ts", - "line": 3, - "col": 4 - }, - "jsDoc": null, - "optional": false, - "params": [], - "typeParams": [], - "returnType": { - "repr": "T", - "kind": "typeRef", - "typeRef": { - "typeParams": null, - "typeName": "T" - } - } - } - ], - "properties": [], - "callSignatures": [], - "indexSignatures": [], - "typeParams": [ - { "name": "T" } - ], - } - }]); - - json_test!(export_type_alias, - r#" -/** Array holding numbers */ -export type NumberArray = Array; - "#; - [{ - "kind": "typeAlias", - "name": "NumberArray", - "location": { - "filename": "test.ts", - "line": 3, - "col": 0 - }, - "jsDoc": "Array holding numbers", - "typeAliasDef": { - "typeParams": [], - "tsType": { - "repr": "Array", - "kind": "typeRef", - "typeRef": { - "typeParams": [ - { - "repr": "number", - "kind": "keyword", - "keyword": "number" - } - ], - "typeName": "Array" - } - } - } - }]); - - json_test!(export_namespace, - r#" -/** Namespace JSdoc */ -export namespace RootNs { - export const a = "a"; - - /** Nested namespace JSDoc */ - export namespace NestedNs { - export enum Foo { - a = 1, - b = 2, - c = 3, - } - } -} - "#; - [{ - "kind": "namespace", - "name": "RootNs", - "location": { - "filename": "test.ts", - "line": 3, - "col": 0 - }, - "jsDoc": "Namespace JSdoc", - "namespaceDef": { - "elements": [ - { - "kind": "variable", - "name": "a", - "location": { - "filename": "test.ts", - "line": 4, - "col": 4 - }, - "jsDoc": null, - "variableDef": { - "tsType": null, - "kind": "const" - } - }, - { - "kind": "namespace", - "name": "NestedNs", - "location": { - "filename": "test.ts", - "line": 7, - "col": 4 - }, - "jsDoc": "Nested namespace JSDoc", - "namespaceDef": { - "elements": [ - { - "kind": "enum", - "name": "Foo", - "location": { - "filename": "test.ts", - "line": 8, - "col": 6 - }, - "jsDoc": null, - "enumDef": { - "members": [ - { - "name": "a" - }, - { - "name": "b" - }, - { - "name": "c" - } - ] - } - } - ] - } - } - ] - } - }]); - - json_test!(optional_return_type, - r#" - export function foo(a: number) { - return a; - } - "#; - [{ - "kind": "function", - "name": "foo", - "location": { - "filename": "test.ts", - "line": 2, - "col": 2 - }, - "jsDoc": null, - "functionDef": { - "params": [ - { - "name": "a", - "kind": "identifier", - "optional": false, - "tsType": { - "keyword": "number", - "kind": "keyword", - "repr": "number", - }, - } - ], - "typeParams": [], - "returnType": null, - "isAsync": false, - "isGenerator": false - } - }] - ); - - json_test!(ts_lit_types, - r#" -export type boolLit = false; -export type strLit = "text"; -export type tplLit = `text`; -export type numLit = 5; - "#; - [ - { - "kind": "typeAlias", - "name": "boolLit", - "location": { - "filename": "test.ts", - "line": 2, - "col": 0 - }, - "jsDoc": null, - "typeAliasDef": { - "tsType": { - "repr": "false", - "kind": "literal", - "literal": { - "kind": "boolean", - "boolean": false - } - }, - "typeParams": [] - } - }, { - "kind": "typeAlias", - "name": "strLit", - "location": { - "filename": "test.ts", - "line": 3, - "col": 0 - }, - "jsDoc": null, - "typeAliasDef": { - "tsType": { - "repr": "text", - "kind": "literal", - "literal": { - "kind": "string", - "string": "text" - } - }, - "typeParams": [] - } - }, { - "kind": "typeAlias", - "name": "tplLit", - "location": { - "filename": "test.ts", - "line": 4, - "col": 0 - }, - "jsDoc": null, - "typeAliasDef": { - "tsType": { - "repr": "text", - "kind": "literal", - "literal": { - "kind": "string", - "string": "text" - } - }, - "typeParams": [] - } - }, { - "kind": "typeAlias", - "name": "numLit", - "location": { - "filename": "test.ts", - "line": 5, - "col": 0 - }, - "jsDoc": null, - "typeAliasDef": { - "tsType": { - "repr": "5", - "kind": "literal", - "literal": { - "kind": "number", - "number": 5.0 - } - }, - "typeParams": [] - } - } - ]); -} - -mod printer { - use super::*; - - contains_test!(abstract_class, - "export abstract class Class {}", - details; - "abstract class Class" - ); - - contains_test!(abstract_class_abstract_method, - r#" -export abstract class Class { - abstract method() {} -} - "#, - details; - "abstract method()" - ); - - contains_test!(class_async_method, - r#" -export class Class { - async amethod(v) {} -} - "#, - details; - "async amethod(v)" - ); - - contains_test!(class_constructor, - r#" -export class Class { - constructor(a, b) {} -} - "#, - details; - "constructor(a, b)" - ); - - const CLASS_SOURCE: &str = r#" -export class C { - /** a doc */ - a() {} - f: number; -} - "#; - - contains_test!(class_details, - CLASS_SOURCE, - details; - "class C", - "a()", - "f: number" - ); - - contains_test!(class_details_all_with_private, - r#" -export class Class { - private pri() {} - protected pro() {} - public pub() {} -} - "#, - details, - private; - "private pri()", - "protected pro()", - "pub()" - ); - - contains_test!(class_details_only_non_private_without_private, - r#" -export class Class { - private pri() {} - protected pro() {} - public pub() {} -} - "#, - details; - "protected pro()", - "pub()" - ); - - contains_test!(class_declaration, - "export class Class {}"; - "class Class" - ); - - contains_test!(class_extends, - "export class Class extends Object {}"; - "class Class extends Object" - ); - - contains_test!(class_extends_implements, - "export class Class extends Object implements Iterator, Iterable {}"; - "class Class extends Object implements Iterator, Iterable" - ); - - contains_test!(class_generic_extends_implements, - "export class Class extends Map implements Iterator, Iterable {}"; - "class Class extends Map implements Iterator, Iterable" - ); - - contains_test!(class_getter_and_setter, - r#" -export class Class { - get a(): void {} - set b(_v: void) {} -} - "#, - details; - "get a(): void", - "set b(_v: void)" - ); - - contains_test!(class_index_signature, - r#" -export class C { - [key: string]: number; -} - "#, - details; - "[key: string]: number" - ); - - contains_test!(class_implements, - "export class Class implements Iterator {}"; - "class Class implements Iterator" - ); - - contains_test!(class_implements2, - "export class Class implements Iterator, Iterable {}"; - "class Class implements Iterator, Iterable" - ); - - contains_test!(class_method, - r#" -export class Class { - method(v) {} -} - "#, - details; - "method(v)" - ); - - contains_test!(class_property, - r#" -export class Class { - someproperty: bool; - optproperty: bigint; -} - "#, - details; - "someproperty: bool", - "optproperty: bigint" - ); - - contains_test!(class_readonly_index_signature, - r#" -export class C { - readonly [key: string]: number; -} - "#, - details; - "readonly [key: string]: number" - ); - - contains_test!(class_static_property, - r#" -export class Class { - static property = ""; -} - "#, - details; - "static property" - ); - - contains_test!(class_summary, - CLASS_SOURCE; - "class C"; - "a()", - "f: number" - ); - - contains_test!(class_readonly_property, - r#" -export class Class { - readonly property = ""; -} - "#, - details; - "readonly property" - ); - - contains_test!(class_private_property, - r#" -export class Class { - private property = ""; -} - "#, - details, - private; - "private property" - ); - - contains_test!(const_declaration, - "export const Const = 0;"; - "const Const" - ); - - contains_test!(enum_declaration, - "export enum Enum {}"; - "enum Enum" - ); - - const EXPORT_SOURCE: &str = r#" -export function a() {} -function b() {} -export class C {} -class D {} -export interface E {} -interface F {} -export namespace G {} -namespace H {} - "#; - - contains_test!(exports_all_with_private, - EXPORT_SOURCE, - private; - "function a()", - "class C", - "interface E", - "namespace G", - "function b()", - "class D", - "interface F", - "namespace H" - ); - - contains_test!(exports_only_exports_without_private, - EXPORT_SOURCE; - "function a()", - "class C", - "interface E", - "namespace G"; - "function b()", - "class D", - "interface F", - "namespace H" - ); - - contains_test!(function_async, - "export async function a() {}"; - "async function a()" - ); - - contains_test!(function_array_deconstruction, - "export function f([a, b, ...c]) {}"; - "function f([a, b, ...c])" - ); - - contains_test!(function_async_generator, - "export async function* ag() {}"; - "async function* ag()" - ); - - contains_test!(function_declaration, - "export function fun() {}"; - "function fun()" - ); - - contains_test!(function_generator, - "export function* g() {}"; - "function* g()" - ); - - contains_test!(function_generic, - "export function add(a: T, b: T) { return a + b; }"; - "function add(a: T, b: T)" - ); - - contains_test!(function_object_deconstruction, - "export function f({ a, b, ...c }) {}"; - "function f({a, b, ...c})" - ); - - /* TODO(SyrupThinker) NYI - contains_test!(function_type_predicate, - r#" - export function isFish(pet: Fish | Bird): pet is Fish { - return (pet as Fish).swim !== undefined; - } - "#; - "pet is Fish" - ); - */ - - contains_test!(generic_instantiated_with_tuple_type, - r#" -interface Generic {} -export function f(): Generic<[string, number]> { return {}; } - "#; - "Generic<[string, number]>" - ); - - contains_test!(type_literal_declaration, - "export type T = {}"; - "{ }" - ); - - contains_test!(type_literal_index_signature, - "export type T = { [key: string]: number; }"; - "[key: string]: number" - ); - - contains_test!(type_literal_readonly_index_signature, - "export type T = { readonly [key: string]: number; }"; - "readonly [key: string]: number" - ); - - contains_test!(interface_declaration, - "export interface Interface {}"; - "interface Interface" - ); - - contains_test!(interface_extends, - "export interface Interface extends Iterator {}"; - "interface Interface extends Iterator" - ); - - contains_test!(interface_extends2, - "export interface Interface extends Iterator, Iterable {}"; - "interface Interface extends Iterator, Iterable" - ); - - contains_test!(interface_generic, - "export interface Interface {}"; - "interface Interface" - ); - - contains_test!(interface_generic_extends, - "export interface Interface extends Iterable {}"; - "interface Interface extends Iterable" - ); - - contains_test!(interface_index_signature, - r#" -export interface Interface { - [index: number]: Interface; -} - "#, - details; - "[index: number]: Interface" - ); - - contains_test!(interface_method, - r#" -export interface I { - m(a, b); - mo?(c); -} - "#, - details; - "m(a, b)", - "mo?(c)" - ); - - contains_test!(interface_property, - r#" -export interface I { - p: string; - po?: number; -} - "#, - details; - "p: string", - "po?: number" - ); - - contains_test!(interface_readonly_index_signature, - r#" -export interface Interface { - readonly [index: number]: Interface; -} - "#, - details; - "readonly [index: number]: Interface" - ); - - const JSDOC_SOURCE: &str = r#" -/** - * A is a class - * - * Nothing more - */ -export class A {} -/** - * B is an interface - * - * Should be - */ -export interface B {} -/** - * C is a function - * - * Summarised - */ -export function C() {} - "#; - - contains_test!(jsdoc_details, - JSDOC_SOURCE, - details; - "A is a class", - "B is an interface", - "C is a function", - "Nothing more", - "Should be", - "Summarised" - ); - - contains_test!(jsdoc_summary, - JSDOC_SOURCE; - "A is a class", - "B is an interface", - "C is a function"; - "Nothing more", - "Should be", - "Summarised" - ); - - contains_test!(namespace_declaration, - "export namespace Namespace {}"; - "namespace Namespace" - ); - - const NAMESPACE_SOURCE: &str = r#" -export namespace Namespace { - /** - * Doc comment 1 - * - * Details 1 - */ - export function a() {} - /** - * Doc comment 2 - * - * Details 2 - */ - export class B {} -} - "#; - - contains_test!(namespace_details, - NAMESPACE_SOURCE, - details; - "namespace Namespace", - "function a()", - "class B", - "Doc comment 1", - "Doc comment 2"; - "Details 1", - "Details 2" - ); - - contains_test!(namespace_summary, - NAMESPACE_SOURCE; - "namespace Namespace", - "function a()", - "class B", - "Doc comment 1", - "Doc comment 2"; - "Details 1", - "Details 2" - ); - - contains_test!(type_alias, - "export type A = number"; - "type A = number" - ); - - contains_test!(type_generic_alias, - "export type A = T"; - "type A = T" - ); -} diff --git a/cli/doc/ts_type.rs b/cli/doc/ts_type.rs deleted file mode 100644 index 36502ee5e4f556..00000000000000 --- a/cli/doc/ts_type.rs +++ /dev/null @@ -1,986 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use super::display::{display_readonly, SliceDisplayer}; -use super::interface::expr_to_name; -use super::params::ts_fn_param_to_param_def; -use super::ts_type_param::maybe_type_param_decl_to_type_param_defs; -use super::ts_type_param::TsTypeParamDef; -use super::ParamDef; -use crate::colors; -use crate::doc; -use crate::swc_ecma_ast; -use crate::swc_ecma_ast::{ - TsArrayType, TsConditionalType, TsExprWithTypeArgs, TsFnOrConstructorType, - TsIndexedAccessType, TsKeywordType, TsLit, TsLitType, TsOptionalType, - TsParenthesizedType, TsRestType, TsThisType, TsTupleType, TsType, TsTypeAnn, - TsTypeLit, TsTypeOperator, TsTypeParamInstantiation, TsTypeQuery, TsTypeRef, - TsUnionOrIntersectionType, -}; -use serde::Serialize; -use std::fmt::{Display, Formatter, Result as FmtResult}; - -// pub enum TsType { -// * TsKeywordType(TsKeywordType), -// * TsThisType(TsThisType), -// * TsFnOrConstructorType(TsFnOrConstructorType), -// * TsTypeRef(TsTypeRef), -// * TsTypeQuery(TsTypeQuery), -// * TsTypeLit(TsTypeLit), -// * TsArrayType(TsArrayType), -// * TsTupleType(TsTupleType), -// * TsOptionalType(TsOptionalType), -// * TsRestType(TsRestType), -// * TsUnionOrIntersectionType(TsUnionOrIntersectionType), -// * TsConditionalType(TsConditionalType), -// * TsParenthesizedType(TsParenthesizedType), -// * TsTypeOperator(TsTypeOperator), -// * TsIndexedAccessType(TsIndexedAccessType), -// * TsLitType(TsLitType), -// TsInferType(TsInferType), -// TsMappedType(TsMappedType), -// TsTypePredicate(TsTypePredicate), -// TsImportType(TsImportType), -// } - -impl Into for &TsLitType { - fn into(self) -> TsTypeDef { - let (repr, lit) = match &self.lit { - TsLit::Number(num) => ( - format!("{}", num.value), - LiteralDef { - kind: LiteralDefKind::Number, - number: Some(num.value), - string: None, - boolean: None, - }, - ), - TsLit::Str(str_) => ( - str_.value.to_string(), - LiteralDef { - kind: LiteralDefKind::String, - number: None, - string: Some(str_.value.to_string()), - boolean: None, - }, - ), - TsLit::Tpl(tpl) => { - // A template literal in a type is not allowed to have - // expressions, so there will only be one quasi. - let quasi = tpl.quasis.get(0).expect("Expected tpl to have a quasi."); - let text = quasi.raw.value.to_string(); - ( - text.clone(), - LiteralDef { - kind: LiteralDefKind::String, // semantically the same - number: None, - string: Some(text), - boolean: None, - }, - ) - } - TsLit::Bool(bool_) => ( - bool_.value.to_string(), - LiteralDef { - kind: LiteralDefKind::Boolean, - number: None, - string: None, - boolean: Some(bool_.value), - }, - ), - }; - - TsTypeDef { - repr, - kind: Some(TsTypeDefKind::Literal), - literal: Some(lit), - ..Default::default() - } - } -} - -impl Into for &TsArrayType { - fn into(self) -> TsTypeDef { - let ts_type_def: TsTypeDef = (&*self.elem_type).into(); - - TsTypeDef { - array: Some(Box::new(ts_type_def)), - kind: Some(TsTypeDefKind::Array), - ..Default::default() - } - } -} - -impl Into for &TsTupleType { - fn into(self) -> TsTypeDef { - let mut type_defs = vec![]; - - for type_box in &self.elem_types { - let ts_type: &TsType = &type_box.ty; - let def: TsTypeDef = ts_type.into(); - type_defs.push(def) - } - - TsTypeDef { - tuple: Some(type_defs), - kind: Some(TsTypeDefKind::Tuple), - ..Default::default() - } - } -} - -impl Into for &TsUnionOrIntersectionType { - fn into(self) -> TsTypeDef { - use crate::swc_ecma_ast::TsUnionOrIntersectionType::*; - - match self { - TsUnionType(union_type) => { - let mut types_union = vec![]; - - for type_box in &union_type.types { - let ts_type: &TsType = &(*type_box); - let def: TsTypeDef = ts_type.into(); - types_union.push(def); - } - - TsTypeDef { - union: Some(types_union), - kind: Some(TsTypeDefKind::Union), - ..Default::default() - } - } - TsIntersectionType(intersection_type) => { - let mut types_intersection = vec![]; - - for type_box in &intersection_type.types { - let ts_type: &TsType = &(*type_box); - let def: TsTypeDef = ts_type.into(); - types_intersection.push(def); - } - - TsTypeDef { - intersection: Some(types_intersection), - kind: Some(TsTypeDefKind::Intersection), - ..Default::default() - } - } - } - } -} - -impl Into for &TsKeywordType { - fn into(self) -> TsTypeDef { - use crate::swc_ecma_ast::TsKeywordTypeKind::*; - - let keyword_str = match self.kind { - TsAnyKeyword => "any", - TsUnknownKeyword => "unknown", - TsNumberKeyword => "number", - TsObjectKeyword => "object", - TsBooleanKeyword => "boolean", - TsBigIntKeyword => "bigint", - TsStringKeyword => "string", - TsSymbolKeyword => "symbol", - TsVoidKeyword => "void", - TsUndefinedKeyword => "undefined", - TsNullKeyword => "null", - TsNeverKeyword => "never", - }; - - TsTypeDef { - repr: keyword_str.to_string(), - kind: Some(TsTypeDefKind::Keyword), - keyword: Some(keyword_str.to_string()), - ..Default::default() - } - } -} - -impl Into for &TsTypeOperator { - fn into(self) -> TsTypeDef { - let ts_type = (&*self.type_ann).into(); - let type_operator_def = TsTypeOperatorDef { - operator: self.op.as_str().to_string(), - ts_type, - }; - - TsTypeDef { - type_operator: Some(Box::new(type_operator_def)), - kind: Some(TsTypeDefKind::TypeOperator), - ..Default::default() - } - } -} - -impl Into for &TsParenthesizedType { - fn into(self) -> TsTypeDef { - let ts_type = (&*self.type_ann).into(); - - TsTypeDef { - parenthesized: Some(Box::new(ts_type)), - kind: Some(TsTypeDefKind::Parenthesized), - ..Default::default() - } - } -} - -impl Into for &TsRestType { - fn into(self) -> TsTypeDef { - let ts_type = (&*self.type_ann).into(); - - TsTypeDef { - rest: Some(Box::new(ts_type)), - kind: Some(TsTypeDefKind::Rest), - ..Default::default() - } - } -} - -impl Into for &TsOptionalType { - fn into(self) -> TsTypeDef { - let ts_type = (&*self.type_ann).into(); - - TsTypeDef { - optional: Some(Box::new(ts_type)), - kind: Some(TsTypeDefKind::Optional), - ..Default::default() - } - } -} - -impl Into for &TsThisType { - fn into(self) -> TsTypeDef { - TsTypeDef { - repr: "this".to_string(), - this: Some(true), - kind: Some(TsTypeDefKind::This), - ..Default::default() - } - } -} - -pub fn ts_entity_name_to_name( - entity_name: &swc_ecma_ast::TsEntityName, -) -> String { - use crate::swc_ecma_ast::TsEntityName::*; - - match entity_name { - Ident(ident) => ident.sym.to_string(), - TsQualifiedName(ts_qualified_name) => { - let left = ts_entity_name_to_name(&ts_qualified_name.left); - let right = ts_qualified_name.right.sym.to_string(); - format!("{}.{}", left, right) - } - } -} - -impl Into for &TsTypeQuery { - fn into(self) -> TsTypeDef { - use crate::swc_ecma_ast::TsTypeQueryExpr::*; - - let type_name = match &self.expr_name { - TsEntityName(entity_name) => ts_entity_name_to_name(&*entity_name), - Import(import_type) => import_type.arg.value.to_string(), - }; - - TsTypeDef { - repr: type_name.to_string(), - type_query: Some(type_name), - kind: Some(TsTypeDefKind::TypeQuery), - ..Default::default() - } - } -} - -impl Into for &TsTypeRef { - fn into(self) -> TsTypeDef { - let type_name = ts_entity_name_to_name(&self.type_name); - - let type_params = if let Some(type_params_inst) = &self.type_params { - let mut ts_type_defs = vec![]; - - for type_box in &type_params_inst.params { - let ts_type: &TsType = &(*type_box); - let def: TsTypeDef = ts_type.into(); - ts_type_defs.push(def); - } - - Some(ts_type_defs) - } else { - None - }; - - TsTypeDef { - repr: type_name.clone(), - type_ref: Some(TsTypeRefDef { - type_name, - type_params, - }), - kind: Some(TsTypeDefKind::TypeRef), - ..Default::default() - } - } -} - -impl Into for &TsExprWithTypeArgs { - fn into(self) -> TsTypeDef { - let type_name = ts_entity_name_to_name(&self.expr); - - let type_params = if let Some(type_params_inst) = &self.type_args { - let mut ts_type_defs = vec![]; - - for type_box in &type_params_inst.params { - let ts_type: &TsType = &(*type_box); - let def: TsTypeDef = ts_type.into(); - ts_type_defs.push(def); - } - - Some(ts_type_defs) - } else { - None - }; - - TsTypeDef { - repr: type_name.clone(), - type_ref: Some(TsTypeRefDef { - type_name, - type_params, - }), - kind: Some(TsTypeDefKind::TypeRef), - ..Default::default() - } - } -} - -impl Into for &TsIndexedAccessType { - fn into(self) -> TsTypeDef { - let indexed_access_def = TsIndexedAccessDef { - readonly: self.readonly, - obj_type: Box::new((&*self.obj_type).into()), - index_type: Box::new((&*self.index_type).into()), - }; - - TsTypeDef { - indexed_access: Some(indexed_access_def), - kind: Some(TsTypeDefKind::IndexedAccess), - ..Default::default() - } - } -} - -impl Into for &TsTypeLit { - fn into(self) -> TsTypeDef { - let mut methods = vec![]; - let mut properties = vec![]; - let mut call_signatures = vec![]; - let mut index_signatures = vec![]; - - for type_element in &self.members { - use crate::swc_ecma_ast::TsTypeElement::*; - - match &type_element { - TsMethodSignature(ts_method_sig) => { - let mut params = vec![]; - - for param in &ts_method_sig.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let maybe_return_type = ts_method_sig - .type_ann - .as_ref() - .map(|rt| (&*rt.type_ann).into()); - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_method_sig.type_params.as_ref(), - ); - let name = expr_to_name(&*ts_method_sig.key); - let method_def = LiteralMethodDef { - name, - params, - return_type: maybe_return_type, - type_params, - }; - methods.push(method_def); - } - TsPropertySignature(ts_prop_sig) => { - let name = expr_to_name(&*ts_prop_sig.key); - - let mut params = vec![]; - - for param in &ts_prop_sig.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let ts_type = ts_prop_sig - .type_ann - .as_ref() - .map(|rt| (&*rt.type_ann).into()); - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_prop_sig.type_params.as_ref(), - ); - let prop_def = LiteralPropertyDef { - name, - params, - ts_type, - computed: ts_prop_sig.computed, - optional: ts_prop_sig.optional, - type_params, - }; - properties.push(prop_def); - } - TsCallSignatureDecl(ts_call_sig) => { - let mut params = vec![]; - for param in &ts_call_sig.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let ts_type = ts_call_sig - .type_ann - .as_ref() - .map(|rt| (&*rt.type_ann).into()); - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_call_sig.type_params.as_ref(), - ); - - let call_sig_def = LiteralCallSignatureDef { - params, - ts_type, - type_params, - }; - call_signatures.push(call_sig_def); - } - TsIndexSignature(ts_index_sig) => { - let mut params = vec![]; - for param in &ts_index_sig.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let ts_type = ts_index_sig - .type_ann - .as_ref() - .map(|rt| (&*rt.type_ann).into()); - - let index_sig_def = LiteralIndexSignatureDef { - readonly: ts_index_sig.readonly, - params, - ts_type, - }; - index_signatures.push(index_sig_def); - } - // TODO: - TsConstructSignatureDecl(_) => {} - } - } - - let type_literal = TsTypeLiteralDef { - methods, - properties, - call_signatures, - index_signatures, - }; - - TsTypeDef { - kind: Some(TsTypeDefKind::TypeLiteral), - type_literal: Some(type_literal), - ..Default::default() - } - } -} - -impl Into for &TsConditionalType { - fn into(self) -> TsTypeDef { - let conditional_type_def = TsConditionalDef { - check_type: Box::new((&*self.check_type).into()), - extends_type: Box::new((&*self.extends_type).into()), - true_type: Box::new((&*self.true_type).into()), - false_type: Box::new((&*self.false_type).into()), - }; - - TsTypeDef { - kind: Some(TsTypeDefKind::Conditional), - conditional_type: Some(conditional_type_def), - ..Default::default() - } - } -} - -impl Into for &TsFnOrConstructorType { - fn into(self) -> TsTypeDef { - use crate::swc_ecma_ast::TsFnOrConstructorType::*; - - let fn_def = match self { - TsFnType(ts_fn_type) => { - let mut params = vec![]; - - for param in &ts_fn_type.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let type_params = maybe_type_param_decl_to_type_param_defs( - ts_fn_type.type_params.as_ref(), - ); - - TsFnOrConstructorDef { - constructor: false, - ts_type: ts_type_ann_to_def(&ts_fn_type.type_ann), - params, - type_params, - } - } - TsConstructorType(ctor_type) => { - let mut params = vec![]; - - for param in &ctor_type.params { - let param_def = ts_fn_param_to_param_def(param, None); - params.push(param_def); - } - - let type_params = maybe_type_param_decl_to_type_param_defs( - ctor_type.type_params.as_ref(), - ); - TsFnOrConstructorDef { - constructor: true, - ts_type: ts_type_ann_to_def(&ctor_type.type_ann), - params, - type_params, - } - } - }; - - TsTypeDef { - kind: Some(TsTypeDefKind::FnOrConstructor), - fn_or_constructor: Some(Box::new(fn_def)), - ..Default::default() - } - } -} - -impl Into for &TsType { - fn into(self) -> TsTypeDef { - use crate::swc_ecma_ast::TsType::*; - - match self { - TsKeywordType(ref keyword_type) => keyword_type.into(), - TsLitType(ref lit_type) => lit_type.into(), - TsTypeRef(ref type_ref) => type_ref.into(), - TsUnionOrIntersectionType(union_or_inter) => union_or_inter.into(), - TsArrayType(array_type) => array_type.into(), - TsTupleType(tuple_type) => tuple_type.into(), - TsTypeOperator(type_op_type) => type_op_type.into(), - TsParenthesizedType(paren_type) => paren_type.into(), - TsRestType(rest_type) => rest_type.into(), - TsOptionalType(optional_type) => optional_type.into(), - TsTypeQuery(type_query) => type_query.into(), - TsThisType(this_type) => this_type.into(), - TsFnOrConstructorType(fn_or_con_type) => fn_or_con_type.into(), - TsConditionalType(conditional_type) => conditional_type.into(), - TsIndexedAccessType(indexed_access_type) => indexed_access_type.into(), - TsTypeLit(type_literal) => type_literal.into(), - _ => TsTypeDef { - repr: "".to_string(), - ..Default::default() - }, - } - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsTypeRefDef { - pub type_params: Option>, - pub type_name: String, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub enum LiteralDefKind { - Number, - String, - Boolean, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct LiteralDef { - pub kind: LiteralDefKind, - - #[serde(skip_serializing_if = "Option::is_none")] - pub number: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub string: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub boolean: Option, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsTypeOperatorDef { - pub operator: String, - pub ts_type: TsTypeDef, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsFnOrConstructorDef { - pub constructor: bool, - pub ts_type: TsTypeDef, - pub params: Vec, - pub type_params: Vec, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsConditionalDef { - pub check_type: Box, - pub extends_type: Box, - pub true_type: Box, - pub false_type: Box, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsIndexedAccessDef { - pub readonly: bool, - pub obj_type: Box, - pub index_type: Box, -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct LiteralMethodDef { - pub name: String, - pub params: Vec, - pub return_type: Option, - pub type_params: Vec, -} - -impl Display for LiteralMethodDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}({})", - self.name, - SliceDisplayer::new(&self.params, ", ", false) - )?; - if let Some(return_type) = &self.return_type { - write!(f, ": {}", return_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct LiteralPropertyDef { - pub name: String, - pub params: Vec, - pub computed: bool, - pub optional: bool, - pub ts_type: Option, - pub type_params: Vec, -} - -impl Display for LiteralPropertyDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!(f, "{}", self.name)?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct LiteralCallSignatureDef { - pub params: Vec, - pub ts_type: Option, - pub type_params: Vec, -} - -impl Display for LiteralCallSignatureDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!(f, "({})", SliceDisplayer::new(&self.params, ", ", false))?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct LiteralIndexSignatureDef { - pub readonly: bool, - pub params: Vec, - pub ts_type: Option, -} - -impl Display for LiteralIndexSignatureDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!( - f, - "{}[{}]", - display_readonly(self.readonly), - SliceDisplayer::new(&self.params, ", ", false) - )?; - if let Some(ts_type) = &self.ts_type { - write!(f, ": {}", ts_type)?; - } - Ok(()) - } -} - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsTypeLiteralDef { - pub methods: Vec, - pub properties: Vec, - pub call_signatures: Vec, - pub index_signatures: Vec, -} - -#[derive(Debug, PartialEq, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub enum TsTypeDefKind { - Keyword, - Literal, - TypeRef, - Union, - Intersection, - Array, - Tuple, - TypeOperator, - Parenthesized, - Rest, - Optional, - TypeQuery, - This, - FnOrConstructor, - Conditional, - IndexedAccess, - TypeLiteral, -} - -#[derive(Debug, Default, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsTypeDef { - pub repr: String, - - pub kind: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub keyword: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub literal: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub type_ref: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub union: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub intersection: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub array: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub tuple: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub type_operator: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub parenthesized: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub rest: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub optional: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub type_query: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub this: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub fn_or_constructor: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub conditional_type: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub indexed_access: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub type_literal: Option, -} - -pub fn ts_type_ann_to_def(type_ann: &TsTypeAnn) -> TsTypeDef { - use crate::swc_ecma_ast::TsType::*; - - match &*type_ann.type_ann { - TsKeywordType(keyword_type) => keyword_type.into(), - TsLitType(lit_type) => lit_type.into(), - TsTypeRef(type_ref) => type_ref.into(), - TsUnionOrIntersectionType(union_or_inter) => union_or_inter.into(), - TsArrayType(array_type) => array_type.into(), - TsTupleType(tuple_type) => tuple_type.into(), - TsTypeOperator(type_op_type) => type_op_type.into(), - TsParenthesizedType(paren_type) => paren_type.into(), - TsRestType(rest_type) => rest_type.into(), - TsOptionalType(optional_type) => optional_type.into(), - TsTypeQuery(type_query) => type_query.into(), - TsThisType(this_type) => this_type.into(), - TsFnOrConstructorType(fn_or_con_type) => fn_or_con_type.into(), - TsConditionalType(conditional_type) => conditional_type.into(), - TsIndexedAccessType(indexed_access_type) => indexed_access_type.into(), - TsTypeLit(type_literal) => type_literal.into(), - _ => TsTypeDef { - repr: "".to_string(), - ..Default::default() - }, - } -} - -impl Display for TsTypeDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - if self.kind.is_none() { - return write!(f, "{}", colors::red("")); - } - - let kind = self.kind.as_ref().unwrap(); - match kind { - TsTypeDefKind::Array => write!(f, "{}[]", &*self.array.as_ref().unwrap()), - TsTypeDefKind::Conditional => { - let conditional = self.conditional_type.as_ref().unwrap(); - write!( - f, - "{} {} {} ? {} : {}", - &*conditional.check_type, - colors::magenta("extends"), - &*conditional.extends_type, - &*conditional.true_type, - &*conditional.false_type - ) - } - TsTypeDefKind::FnOrConstructor => { - let fn_or_constructor = self.fn_or_constructor.as_ref().unwrap(); - write!( - f, - "{}({}) => {}", - colors::magenta(if fn_or_constructor.constructor { - "new " - } else { - "" - }), - SliceDisplayer::new(&fn_or_constructor.params, ", ", false), - &fn_or_constructor.ts_type, - ) - } - TsTypeDefKind::IndexedAccess => { - let indexed_access = self.indexed_access.as_ref().unwrap(); - write!( - f, - "{}[{}]", - &*indexed_access.obj_type, &*indexed_access.index_type - ) - } - TsTypeDefKind::Intersection => { - let intersection = self.intersection.as_ref().unwrap(); - write!(f, "{}", SliceDisplayer::new(&intersection, " & ", false)) - } - TsTypeDefKind::Keyword => { - write!(f, "{}", colors::cyan(self.keyword.as_ref().unwrap())) - } - TsTypeDefKind::Literal => { - let literal = self.literal.as_ref().unwrap(); - match literal.kind { - doc::ts_type::LiteralDefKind::Boolean => write!( - f, - "{}", - colors::yellow(&literal.boolean.unwrap().to_string()) - ), - doc::ts_type::LiteralDefKind::String => write!( - f, - "{}", - colors::green(&format!("\"{}\"", literal.string.as_ref().unwrap())) - ), - doc::ts_type::LiteralDefKind::Number => write!( - f, - "{}", - colors::yellow(&literal.number.unwrap().to_string()) - ), - } - } - TsTypeDefKind::Optional => { - write!(f, "{}?", &*self.optional.as_ref().unwrap()) - } - TsTypeDefKind::Parenthesized => { - write!(f, "({})", &*self.parenthesized.as_ref().unwrap()) - } - TsTypeDefKind::Rest => write!(f, "...{}", &*self.rest.as_ref().unwrap()), - TsTypeDefKind::This => write!(f, "this"), - TsTypeDefKind::Tuple => { - let tuple = self.tuple.as_ref().unwrap(); - write!(f, "[{}]", SliceDisplayer::new(&tuple, ", ", false)) - } - TsTypeDefKind::TypeLiteral => { - let type_literal = self.type_literal.as_ref().unwrap(); - write!( - f, - "{{ {}{}{}{}}}", - SliceDisplayer::new(&type_literal.call_signatures, "; ", true), - SliceDisplayer::new(&type_literal.methods, "; ", true), - SliceDisplayer::new(&type_literal.properties, "; ", true), - SliceDisplayer::new(&type_literal.index_signatures, "; ", true), - ) - } - TsTypeDefKind::TypeOperator => { - let operator = self.type_operator.as_ref().unwrap(); - write!(f, "{} {}", operator.operator, &operator.ts_type) - } - TsTypeDefKind::TypeQuery => { - write!(f, "typeof {}", self.type_query.as_ref().unwrap()) - } - TsTypeDefKind::TypeRef => { - let type_ref = self.type_ref.as_ref().unwrap(); - write!(f, "{}", colors::intense_blue(&type_ref.type_name))?; - if let Some(type_params) = &type_ref.type_params { - write!(f, "<{}>", SliceDisplayer::new(type_params, ", ", false))?; - } - Ok(()) - } - TsTypeDefKind::Union => { - let union = self.union.as_ref().unwrap(); - write!(f, "{}", SliceDisplayer::new(union, " | ", false)) - } - } - } -} - -pub fn maybe_type_param_instantiation_to_type_defs( - maybe_type_param_instantiation: Option<&TsTypeParamInstantiation>, -) -> Vec { - if let Some(type_param_instantiation) = maybe_type_param_instantiation { - type_param_instantiation - .params - .iter() - .map(|type_param| type_param.as_ref().into()) - .collect::>() - } else { - vec![] - } -} diff --git a/cli/doc/ts_type_param.rs b/cli/doc/ts_type_param.rs deleted file mode 100644 index 0483708b6f8bf6..00000000000000 --- a/cli/doc/ts_type_param.rs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use super::ts_type::TsTypeDef; -use crate::swc_ecma_ast::TsTypeParam; -use crate::swc_ecma_ast::TsTypeParamDecl; -use serde::Serialize; -use std::fmt::{Display, Formatter, Result as FmtResult}; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TsTypeParamDef { - pub name: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub constraint: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option, -} - -impl Display for TsTypeParamDef { - fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - write!(f, "{}", self.name)?; - if let Some(constraint) = &self.constraint { - write!(f, " extends {}", constraint)?; - } - if let Some(default) = &self.default { - write!(f, " = {}", default)?; - } - Ok(()) - } -} - -impl Into for &TsTypeParam { - fn into(self) -> TsTypeParamDef { - let name = self.name.sym.to_string(); - let constraint: Option = - if let Some(ts_type) = self.constraint.as_ref() { - let type_def: TsTypeDef = (&**ts_type).into(); - Some(type_def) - } else { - None - }; - let default: Option = - if let Some(ts_type) = self.default.as_ref() { - let type_def: TsTypeDef = (&**ts_type).into(); - Some(type_def) - } else { - None - }; - - TsTypeParamDef { - name, - constraint, - default, - } - } -} - -pub fn maybe_type_param_decl_to_type_param_defs( - maybe_type_param_decl: Option<&TsTypeParamDecl>, -) -> Vec { - if let Some(type_params_decl) = maybe_type_param_decl { - type_params_decl - .params - .iter() - .map(|type_param| type_param.into()) - .collect::>() - } else { - vec![] - } -} diff --git a/cli/doc/type_alias.rs b/cli/doc/type_alias.rs deleted file mode 100644 index b26395c3f1131d..00000000000000 --- a/cli/doc/type_alias.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use super::parser::DocParser; -use super::ts_type::TsTypeDef; -use super::ts_type_param::maybe_type_param_decl_to_type_param_defs; -use super::ts_type_param::TsTypeParamDef; -use crate::swc_ecma_ast; -use serde::Serialize; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct TypeAliasDef { - pub ts_type: TsTypeDef, - pub type_params: Vec, -} - -pub fn get_doc_for_ts_type_alias_decl( - _doc_parser: &DocParser, - type_alias_decl: &swc_ecma_ast::TsTypeAliasDecl, -) -> (String, TypeAliasDef) { - let alias_name = type_alias_decl.id.sym.to_string(); - let ts_type = type_alias_decl.type_ann.as_ref().into(); - let type_params = maybe_type_param_decl_to_type_param_defs( - type_alias_decl.type_params.as_ref(), - ); - let type_alias_def = TypeAliasDef { - ts_type, - type_params, - }; - - (alias_name, type_alias_def) -} diff --git a/cli/doc/variable.rs b/cli/doc/variable.rs deleted file mode 100644 index 0b9c28a4253251..00000000000000 --- a/cli/doc/variable.rs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -use crate::swc_ecma_ast; -use serde::Serialize; - -use super::ts_type::ts_type_ann_to_def; -use super::ts_type::TsTypeDef; - -#[derive(Debug, Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct VariableDef { - pub ts_type: Option, - pub kind: swc_ecma_ast::VarDeclKind, -} - -// TODO: change this function to return Vec<(String, VariableDef)> as single -// var declaration can have multiple declarators -pub fn get_doc_for_var_decl( - var_decl: &swc_ecma_ast::VarDecl, -) -> (String, VariableDef) { - assert!(!var_decl.decls.is_empty()); - let var_declarator = var_decl.decls.get(0).unwrap(); - let var_name = match &var_declarator.name { - swc_ecma_ast::Pat::Ident(ident) => ident.sym.to_string(), - _ => "".to_string(), - }; - - let maybe_ts_type = match &var_declarator.name { - swc_ecma_ast::Pat::Ident(ident) => { - ident.type_ann.as_ref().map(|rt| ts_type_ann_to_def(rt)) - } - _ => None, - }; - - let variable_def = VariableDef { - ts_type: maybe_ts_type, - kind: var_decl.kind, - }; - - (var_name, variable_def) -} diff --git a/cli/dts/README.md b/cli/dts/README.md new file mode 100644 index 00000000000000..bfa022109d4037 --- /dev/null +++ b/cli/dts/README.md @@ -0,0 +1,19 @@ +# How to upgrade TypeScript. + +The files in this directory are mostly from the TypeScript repository. We +currently (unfortunately) have a rather manual process for upgrading TypeScript. +It works like this currently: + +1. Checkout typescript repo in a seperate directory. +2. Copy typescript.js into Deno repo +3. Copy d.ts files into dts directory + +So that might look something like this: + +``` +git clone https://github.com/microsoft/TypeScript.git +cd typescript +git checkout v3.9.7 +cp lib/typescript.js ~/src/deno/cli/tsc/00_typescript.js +cp lib/*.d.ts ~/src/deno/cli/dts/ +``` diff --git a/cli/dts/lib.deno.ns.d.ts b/cli/dts/lib.deno.ns.d.ts index 96217938131e95..829b31a70befa5 100644 --- a/cli/dts/lib.deno.ns.d.ts +++ b/cli/dts/lib.deno.ns.d.ts @@ -993,9 +993,9 @@ declare namespace Deno { } /** Synchronously creates a new temporary directory in the default directory - * for temporary files (see also `Deno.dir("temp")`), unless `dir` is specified. - * Other optional options include prefixing and suffixing the directory name - * with `prefix` and `suffix` respectively. + * for temporary files, unless `dir` is specified. Other optional options + * include prefixing and suffixing the directory name with `prefix` and + * `suffix` respectively. * * The full path to the newly created directory is returned. * @@ -1013,9 +1013,9 @@ declare namespace Deno { export function makeTempDirSync(options?: MakeTempOptions): string; /** Creates a new temporary directory in the default directory for temporary - * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other - * optional options include prefixing and suffixing the directory name with - * `prefix` and `suffix` respectively. + * files, unless `dir` is specified. Other optional options include + * prefixing and suffixing the directory name with `prefix` and `suffix` + * respectively. * * This call resolves to the full path to the newly created directory. * @@ -1565,7 +1565,7 @@ declare namespace Deno { * else overwriting. * * ```ts - * await Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it + * Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it * ``` * * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`. @@ -1896,7 +1896,7 @@ declare namespace Deno { export interface RunOptions { /** Arguments to pass. Note, the first element needs to be a path to the * binary */ - cmd: string[]; + cmd: string[] | [URL, ...string[]]; cwd?: string; env?: { [key: string]: string; @@ -2025,4 +2025,7 @@ declare namespace Deno { * called when `Deno.inspect()` is called, or when the object is logged to * the console. */ export const customInspect: unique symbol; + + /** The URL of the entrypoint module entered from the command-line. */ + export const mainModule: string; } diff --git a/cli/dts/lib.deno.shared_globals.d.ts b/cli/dts/lib.deno.shared_globals.d.ts index c77f1ea0e7eecc..672f8ada41dcf9 100644 --- a/cli/dts/lib.deno.shared_globals.d.ts +++ b/cli/dts/lib.deno.shared_globals.d.ts @@ -4,6 +4,7 @@ /// /// +/// // This follows the WebIDL at: https://webassembly.github.io/spec/js-api/ // and: https://webassembly.github.io/spec/web-api/ @@ -529,12 +530,6 @@ interface DOMStringList { [index: number]: string; } -declare class DOMException extends Error { - constructor(message?: string, name?: string); - readonly name: string; - readonly message: string; -} - type BufferSource = ArrayBufferView | ArrayBuffer; type BlobPart = BufferSource | Blob | string; @@ -574,6 +569,48 @@ declare const File: { new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; }; +interface FileReaderEventMap { + "abort": ProgressEvent; + "error": ProgressEvent; + "load": ProgressEvent; + "loadend": ProgressEvent; + "loadstart": ProgressEvent; + "progress": ProgressEvent; +} + +/** Lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. */ +interface FileReader extends EventTarget { + readonly error: DOMException | null; + onabort: ((this: FileReader, ev: ProgressEvent) => any) | null; + onerror: ((this: FileReader, ev: ProgressEvent) => any) | null; + onload: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null; + onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null; + onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null; + readonly readyState: number; + readonly result: string | ArrayBuffer | null; + abort(): void; + readAsArrayBuffer(blob: Blob): void; + readAsBinaryString(blob: Blob): void; + readAsDataURL(blob: Blob): void; + readAsText(blob: Blob, encoding?: string): void; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; + addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var FileReader: { + prototype: FileReader; + new(): FileReader; + readonly DONE: number; + readonly EMPTY: number; + readonly LOADING: number; +}; + declare const isConsoleInstance: unique symbol; declare class Console { @@ -594,8 +631,7 @@ declare class Console { }>, ) => void; - /** From MDN: - * Displays an interactive tree of the descendant elements of + /** Displays an interactive tree of the descendant elements of * the specified XML/HTML element. If it is not possible to display * as an element the JavaScript Object view is shown instead. * The output is presented as a hierarchical listing of expandable @@ -603,6 +639,9 @@ declare class Console { * * Since we write to stdout, we can't display anything interactive * we just fall back to `console.dir`. + * + * > [Console.dirxml](https://developer.mozilla.org/en-US/docs/Web/API/Console/dirxml) + * > by Mozilla Contributors is licensed under CC-BY-SA 2.5. */ dirxml: ( obj: unknown, @@ -1028,46 +1067,6 @@ declare function fetch( init?: RequestInit, ): Promise; -/** Decodes a string of data which has been encoded using base-64 encoding. - * - * console.log(atob("aGVsbG8gd29ybGQ=")); // outputs 'hello world' - */ -declare function atob(s: string): string; - -/** Creates a base-64 ASCII encoded string from the input string. - * - * console.log(btoa("hello world")); // outputs "aGVsbG8gd29ybGQ=" - */ -declare function btoa(s: string): string; - -declare class TextDecoder { - /** Returns encoding's name, lowercased. */ - readonly encoding: string; - /** Returns `true` if error mode is "fatal", and `false` otherwise. */ - readonly fatal: boolean; - /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ - readonly ignoreBOM = false; - constructor( - label?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean }, - ); - /** Returns the result of running encoding's decoder. */ - decode(input?: BufferSource, options?: { stream?: false }): string; - readonly [Symbol.toStringTag]: string; -} - -declare class TextEncoder { - /** Returns "utf-8". */ - readonly encoding = "utf-8"; - /** Returns the result of running UTF-8's encoder. */ - encode(input?: string): Uint8Array; - encodeInto( - input: string, - dest: Uint8Array, - ): { read: number; written: number }; - readonly [Symbol.toStringTag]: string; -} - interface URLSearchParams { /** Appends a specified key/value pair as a new search parameter. * @@ -1277,6 +1276,12 @@ interface PostMessageOptions { transfer?: any[]; } +interface ProgressEventInit extends EventInit { + lengthComputable?: boolean; + loaded?: number; + total?: number; +} + declare class Worker extends EventTarget { onerror?: (e: ErrorEvent) => void; onmessage?: (e: MessageEvent) => void; @@ -1442,143 +1447,6 @@ declare class PerformanceMeasure extends PerformanceEntry { readonly entryType: "measure"; } -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} - -/** An event which takes place in the DOM. */ -declare class Event { - constructor(type: string, eventInitDict?: EventInit); - /** Returns true or false depending on how event was initialized. True if - * event goes through its target's ancestors in reverse tree order, and - * false otherwise. */ - readonly bubbles: boolean; - cancelBubble: boolean; - /** Returns true or false depending on how event was initialized. Its return - * value does not always carry meaning, but true can indicate that part of the - * operation during which event was dispatched, can be canceled by invoking - * the preventDefault() method. */ - readonly cancelable: boolean; - /** Returns true or false depending on how event was initialized. True if - * event invokes listeners past a ShadowRoot node that is the root of its - * target, and false otherwise. */ - readonly composed: boolean; - /** Returns the object whose event listener's callback is currently being - * invoked. */ - readonly currentTarget: EventTarget | null; - /** Returns true if preventDefault() was invoked successfully to indicate - * cancellation, and false otherwise. */ - readonly defaultPrevented: boolean; - /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, - * AT_TARGET, and BUBBLING_PHASE. */ - readonly eventPhase: number; - /** Returns true if event was dispatched by the user agent, and false - * otherwise. */ - readonly isTrusted: boolean; - /** Returns the object to which event is dispatched (its target). */ - readonly target: EventTarget | null; - /** Returns the event's timestamp as the number of milliseconds measured - * relative to the time origin. */ - readonly timeStamp: number; - /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ - readonly type: string; - /** Returns the invocation target objects of event's path (objects on which - * listeners will be invoked), except for any nodes in shadow trees of which - * the shadow root's mode is "closed" that are not reachable from event's - * currentTarget. */ - composedPath(): EventTarget[]; - /** If invoked when the cancelable attribute value is true, and while - * executing a listener for the event with passive set to false, signals to - * the operation that caused event to be dispatched that it needs to be - * canceled. */ - preventDefault(): void; - /** Invoking this method prevents event from reaching any registered event - * listeners after the current one finishes running and, when dispatched in a - * tree, also prevents event from reaching any other objects. */ - stopImmediatePropagation(): void; - /** When dispatched in a tree, invoking this method prevents event from - * reaching any objects other than the current object. */ - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; - static readonly CAPTURING_PHASE: number; - static readonly NONE: number; -} - -/** - * EventTarget is a DOM interface implemented by objects that can receive events - * and may have listeners for them. - */ -declare class EventTarget { - /** Appends an event listener for events whose type attribute value is type. - * The callback argument sets the callback that will be invoked when the event - * is dispatched. - * - * The options argument sets listener-specific options. For compatibility this - * can be a boolean, in which case the method behaves exactly as if the value - * was specified as options's capture. - * - * When set to true, options's capture prevents callback from being invoked - * when the event's eventPhase attribute value is BUBBLING_PHASE. When false - * (or not present), callback will not be invoked when event's eventPhase - * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if - * event's eventPhase attribute value is AT_TARGET. - * - * When set to true, options's passive indicates that the callback will not - * cancel the event by invoking preventDefault(). This is used to enable - * performance optimizations described in § 2.8 Observing event listeners. - * - * When set to true, options's once indicates that the callback will only be - * invoked once after which the event listener will be removed. - * - * The event listener is appended to target's event listener list and is not - * appended if it has the same type, callback, and capture. */ - addEventListener( - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions, - ): void; - /** Dispatches a synthetic event event to target and returns true if either - * event's cancelable attribute value is false or its preventDefault() method - * was not invoked, and false otherwise. */ - dispatchEvent(event: Event): boolean; - /** Removes the event listener in target's event listener list with the same - * type, callback, and options. */ - removeEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean, - ): void; - [Symbol.toStringTag]: string; -} - -interface EventListener { - (evt: Event): void | Promise; -} - -interface EventListenerObject { - handleEvent(evt: Event): void | Promise; -} - -declare type EventListenerOrEventListenerObject = - | EventListener - | EventListenerObject; - -interface AddEventListenerOptions extends EventListenerOptions { - once?: boolean; - passive?: boolean; -} - -interface EventListenerOptions { - capture?: boolean; -} - /** Events measuring progress of an underlying process, like an HTTP request * (for an XMLHttpRequest, or the loading of the underlying resource of an * ,