├── tests ├── hello.txt ├── wasm.ts.out ├── if_main.ts.out ├── unbuffered_stdout.ts.out ├── 001_hello.js.out ├── 002_hello.ts.out ├── error_007_any.ts ├── exit_error42.ts.out ├── https_import.ts.out ├── 003_relative_import.ts.out ├── 005_more_imports.ts.out ├── 012_async.ts.out ├── 013_dynamic_import.ts.out ├── 017_import_redirect.ts.out ├── 023_no_ext_with_mime.out ├── 004_set_timeout.ts.out ├── 010_set_interval.ts.out ├── 014_duplicate_import.ts.out ├── 016_double_await.ts.out ├── 001_hello.js ├── 002_hello.ts ├── 006_url_imports.ts.out ├── 023_no_ext_with_mime ├── 023_no_ext_with_mime.mime ├── 024_import_no_ext_with_mime.ts.out ├── circular1.js.out ├── exec_path.ts ├── is_tty.ts ├── subdir │ ├── mod4.js │ ├── no_ext │ ├── mod3.js │ ├── form_urlencoded.txt │ ├── mismatch_ext.ts │ ├── mt_javascript.js │ ├── mt_video_vdn.t2.ts │ ├── unknown_ext.deno │ ├── mt_video_mp2t.t3.ts │ ├── mod2.ts │ ├── mt_text_ecmascript.j3.js │ ├── mt_text_javascript.j1.js │ ├── mt_text_typescript.t1.ts │ ├── mt_application_ecmascript.j2.js │ ├── mt_application_x_javascript.j4.js │ ├── mt_application_x_typescript.t4.ts │ ├── auto_print_hello.ts │ ├── print_hello.ts │ ├── config.json │ ├── subdir2 │ │ └── mod2.ts │ └── mod1.ts ├── badly_formatted_fixed.js ├── error_007_any.ts.out ├── types.test ├── unbuffered_stderr.ts.out ├── error_006_import_ext_failure.ts ├── error_009_missing_js_module.js ├── wasm.test ├── 020_json_modules.ts.out ├── 024_import_no_ext_with_mime.ts ├── badly_formatted.js ├── circular1.js ├── circular2.js ├── esm_imports_b.js ├── 018_async_catch.ts.out ├── 019_media_types.ts.out ├── error_004_missing_module.ts ├── if_main.test ├── 001_hello.test ├── 002_hello.test ├── 012_async.test ├── circular1.test ├── exit_error42.ts ├── import_meta2.ts ├── no_color.js ├── error_syntax.js ├── https_import.test ├── import_meta.test ├── 003_relative_import.ts ├── 004_set_timeout.test ├── 006_url_imports.test ├── 018_async_catch.test ├── 019_media_types.test ├── 020_json_modules.ts ├── esm_imports_a.js ├── unbuffered_stderr.ts ├── unbuffered_stdout.ts ├── 005_more_imports.test ├── 010_set_interval.test ├── 020_json_modules.test ├── unbuffered_stdout.test ├── 003_relative_import.test ├── 017_import_redirect.test ├── error_010_nonexistent_arg.out ├── exit_error42.test ├── import_meta.ts ├── import_meta.ts.out ├── 013_dynamic_import.disabled ├── 016_double_await.test ├── error_005_missing_dynamic_import.ts ├── 014_duplicate_import.disabled ├── 023_no_ext_with_mime.test ├── error_001.test ├── error_002.test ├── error_003_typescript.ts ├── error_009_missing_js_module.js.out ├── async_error.test ├── error_001.ts ├── error_002.ts ├── error_003_typescript.test ├── error_syntax.test ├── unbuffered_stderr.test ├── 006_url_imports.ts ├── error_007_any.test ├── error_008_checkjs.test ├── error_010_nonexistent_arg.test ├── 024_import_no_ext_with_mime.test ├── 010_set_interval.ts ├── error_009_missing_js_module.test ├── error_004_missing_module.test ├── error_syntax.js.out ├── async_error.ts ├── error_006_import_ext_failure.test ├── error_005_missing_dynamic_import.test ├── error_001.ts.out ├── error_008_checkjs.js.out ├── error_002.ts.out ├── 004_set_timeout.ts ├── 022_info_flag.test ├── error_008_checkjs.js ├── if_main.ts ├── 005_more_imports.ts ├── 012_async.ts ├── async_error.ts.out ├── cat.ts ├── 017_import_redirect.ts ├── 014_duplicate_import.ts ├── echo_server.ts ├── 016_double_await.ts ├── https_import.ts ├── 013_dynamic_import.ts ├── types.out ├── 018_async_catch.ts ├── error_003_typescript.ts.out ├── fetch_deps.ts ├── wasm.ts ├── error_005_missing_dynamic_import.ts.out ├── 022_info_flag.out ├── error_006_import_ext_failure.ts.out ├── error_004_missing_module.ts.out ├── http_bench.ts ├── 019_media_types.ts └── README.md ├── core ├── libdeno.rs ├── Cargo.toml ├── BUILD.gn └── shared.rs ├── testing ├── website ├── rustdoc ├── typedoc ├── welcome.ts ├── favicon.ico ├── images │ ├── deno_logo.png │ ├── deno_logo_2.gif │ └── schematic_v0.2.png ├── style.css ├── manual.html └── style_guide.html ├── tools ├── clang ├── memory ├── ts_library_builder │ ├── testdata │ │ ├── moduleF.ts │ │ ├── lib.extra.d.ts │ │ ├── api.ts │ │ ├── moduleD.ts │ │ ├── moduleE.ts │ │ ├── moduleB.ts │ │ ├── moduleA.ts │ │ ├── moduleC.ts │ │ └── globals.ts │ ├── tsconfig.json │ └── main.ts ├── build_test.py ├── node_http.js ├── testdata │ ├── wrk1.txt │ ├── unit_test_output2.txt │ └── strace_summary.out ├── write_gn_args.py ├── test_format.py ├── node_tcp.js ├── upload_website.py ├── sync_third_party.py ├── node_tcp_promise.js ├── is_tty_test.py ├── run_node.py ├── permission_prompt_test.ts ├── build.py ├── prefetch_test.py ├── docs.py ├── lint.py ├── fmt_test.py ├── prebuilt.py ├── hyper_hello.rs ├── deno_dir_test.py ├── benchmark_test.py ├── throughput_benchmark.py ├── format.py ├── sha256sum.py ├── setup_test.py └── unit_tests.py ├── Docs.md ├── .prettierrc.json ├── prebuilt ├── mac │ ├── hyperfine.sha1 │ └── sccache.sha1 ├── .gitignore ├── linux64 │ ├── hyperfine.sha1 │ └── sccache.sha1 └── win │ ├── hyperfine.exe.sha1 │ └── sccache.exe.sha1 ├── .prettierignore ├── .github └── PULL_REQUEST_TEMPLATE.md ├── js ├── mock_builtin.js ├── types.ts ├── performance_test.ts ├── location_test.ts ├── version_test.ts ├── plugins.d.ts ├── platform_test.ts ├── window.ts ├── platform.ts ├── version.ts ├── custom_event_test.ts ├── globals_test.ts ├── dom_file.ts ├── os_test.ts ├── format_error.ts ├── performance.ts ├── resources.ts ├── blob_test.ts ├── chmod.ts ├── errors.ts ├── truncate.ts ├── metrics.ts ├── location.ts ├── dir.ts ├── resources_test.ts ├── libdeno.ts ├── read_link.ts ├── rename.ts ├── metrics_test.ts ├── read_dir.ts ├── remove.ts ├── copy_file.ts ├── dir_test.ts ├── read_file.ts ├── unit_tests.ts ├── symlink.ts ├── event_target.ts ├── mkdir.ts ├── read_file_test.ts ├── rename_test.ts ├── text_encoding_test.ts ├── main.ts ├── custom_event.ts ├── flatbuffers.ts ├── mkdir_test.ts ├── workers.ts ├── event_target_test.ts ├── deno.ts ├── read_link_test.ts ├── symlink_test.ts ├── event_test.ts ├── read_dir_test.ts ├── truncate_test.ts ├── mixins │ └── dom_iterable_test.ts ├── write_file.ts ├── stat.ts └── make_temp_dir_test.ts ├── .rustfmt.toml ├── .gitignore ├── .gitattributes ├── .editorconfig ├── libdeno ├── test.h ├── file_util.h ├── exceptions.h ├── test.cc ├── snapshot_creator.cc ├── file_util_test.cc ├── deno.gni └── file_util.cc ├── .gitmodules ├── src ├── version.rs ├── snapshot.rs ├── msg.rs ├── tokio_write.rs └── ansi.rs ├── tsconfig.json ├── package.json ├── LICENSE ├── README.md ├── Cargo.toml ├── gclient_config.py ├── tslint.json └── .gn /tests/hello.txt: -------------------------------------------------------------------------------- 1 | Hello world! -------------------------------------------------------------------------------- /tests/wasm.ts.out: -------------------------------------------------------------------------------- 1 | 42 2 | -------------------------------------------------------------------------------- /core/libdeno.rs: -------------------------------------------------------------------------------- 1 | ../src/libdeno.rs -------------------------------------------------------------------------------- /testing: -------------------------------------------------------------------------------- 1 | third_party/v8/testing -------------------------------------------------------------------------------- /tests/if_main.ts.out: -------------------------------------------------------------------------------- 1 | main 2 | -------------------------------------------------------------------------------- /tests/unbuffered_stdout.ts.out: -------------------------------------------------------------------------------- 1 | a -------------------------------------------------------------------------------- /website/rustdoc: -------------------------------------------------------------------------------- 1 | ../target/doc/ -------------------------------------------------------------------------------- /website/typedoc: -------------------------------------------------------------------------------- 1 | ../target/typedoc/ -------------------------------------------------------------------------------- /tests/001_hello.js.out: -------------------------------------------------------------------------------- 1 | Hello World 2 | -------------------------------------------------------------------------------- /tests/002_hello.ts.out: -------------------------------------------------------------------------------- 1 | Hello World 2 | -------------------------------------------------------------------------------- /tests/error_007_any.ts: -------------------------------------------------------------------------------- 1 | throw {}; 2 | -------------------------------------------------------------------------------- /tests/exit_error42.ts.out: -------------------------------------------------------------------------------- 1 | before 2 | -------------------------------------------------------------------------------- /tests/https_import.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | -------------------------------------------------------------------------------- /tests/003_relative_import.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | -------------------------------------------------------------------------------- /tests/005_more_imports.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | -------------------------------------------------------------------------------- /tests/012_async.ts.out: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | -------------------------------------------------------------------------------- /tests/013_dynamic_import.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | -------------------------------------------------------------------------------- /tests/017_import_redirect.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | -------------------------------------------------------------------------------- /tests/023_no_ext_with_mime.out: -------------------------------------------------------------------------------- 1 | HELLO 2 | -------------------------------------------------------------------------------- /tools/clang: -------------------------------------------------------------------------------- 1 | ../third_party/v8/tools/clang -------------------------------------------------------------------------------- /tools/memory: -------------------------------------------------------------------------------- 1 | ../third_party/v8/tools/memory/ -------------------------------------------------------------------------------- /tests/004_set_timeout.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | World 3 | -------------------------------------------------------------------------------- /tests/010_set_interval.ts.out: -------------------------------------------------------------------------------- 1 | test 2 | test 3 | -------------------------------------------------------------------------------- /tests/014_duplicate_import.ts.out: -------------------------------------------------------------------------------- 1 | hello! 2 | -------------------------------------------------------------------------------- /tests/016_double_await.ts.out: -------------------------------------------------------------------------------- 1 | true 2 | false 3 | -------------------------------------------------------------------------------- /Docs.md: -------------------------------------------------------------------------------- 1 | Moved to https://deno.land/manual.html 2 | -------------------------------------------------------------------------------- /tests/001_hello.js: -------------------------------------------------------------------------------- 1 | console.log("Hello World"); 2 | -------------------------------------------------------------------------------- /tests/002_hello.ts: -------------------------------------------------------------------------------- 1 | console.log("Hello World"); 2 | -------------------------------------------------------------------------------- /tests/006_url_imports.ts.out: -------------------------------------------------------------------------------- 1 | Hello 2 | success 3 | -------------------------------------------------------------------------------- /tests/023_no_ext_with_mime: -------------------------------------------------------------------------------- 1 | console.log("HELLO"); 2 | -------------------------------------------------------------------------------- /tests/023_no_ext_with_mime.mime: -------------------------------------------------------------------------------- 1 | application/javascript -------------------------------------------------------------------------------- /tests/024_import_no_ext_with_mime.ts.out: -------------------------------------------------------------------------------- 1 | HELLO 2 | -------------------------------------------------------------------------------- /tests/circular1.js.out: -------------------------------------------------------------------------------- 1 | circular2 2 | circular1 3 | -------------------------------------------------------------------------------- /tests/exec_path.ts: -------------------------------------------------------------------------------- 1 | console.log(Deno.execPath); 2 | -------------------------------------------------------------------------------- /tests/is_tty.ts: -------------------------------------------------------------------------------- 1 | console.log(Deno.isTTY().stdin); 2 | -------------------------------------------------------------------------------- /tests/subdir/mod4.js: -------------------------------------------------------------------------------- 1 | export const isMod4 = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/no_ext: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "proseWrap": "always" 3 | } 4 | -------------------------------------------------------------------------------- /tests/subdir/mod3.js: -------------------------------------------------------------------------------- 1 | export const isTSFile = false; 2 | -------------------------------------------------------------------------------- /website/welcome.ts: -------------------------------------------------------------------------------- 1 | console.log("Welcome to Deno 🦕"); 2 | -------------------------------------------------------------------------------- /tests/badly_formatted_fixed.js: -------------------------------------------------------------------------------- 1 | console.log("Hello World"); 2 | -------------------------------------------------------------------------------- /tests/error_007_any.ts.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]Uncaught # 2 | -------------------------------------------------------------------------------- /tests/subdir/form_urlencoded.txt: -------------------------------------------------------------------------------- 1 | field_1=Hi&field_2=%3CDeno%3E -------------------------------------------------------------------------------- /tests/subdir/mismatch_ext.ts: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_javascript.js: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_video_vdn.t2.ts: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/unknown_ext.deno: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/types.test: -------------------------------------------------------------------------------- 1 | args: --types 2 | output: tests/types.out 3 | -------------------------------------------------------------------------------- /tests/unbuffered_stderr.ts.out: -------------------------------------------------------------------------------- 1 | Compiling [WILDCARD].ts 2 | x -------------------------------------------------------------------------------- /prebuilt/mac/hyperfine.sha1: -------------------------------------------------------------------------------- 1 | fe12887d9fcce693fa333992cb46c6ab7ada181e -------------------------------------------------------------------------------- /prebuilt/mac/sccache.sha1: -------------------------------------------------------------------------------- 1 | 573863cf8284cfeffdbf3983d38c1b87663be724 -------------------------------------------------------------------------------- /tests/error_006_import_ext_failure.ts: -------------------------------------------------------------------------------- 1 | import "./non-existent"; 2 | -------------------------------------------------------------------------------- /tests/error_009_missing_js_module.js: -------------------------------------------------------------------------------- 1 | import "./bad-module.js"; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_video_mp2t.t3.ts: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/wasm.test: -------------------------------------------------------------------------------- 1 | args: tests/wasm.ts 2 | output: tests/wasm.ts.out -------------------------------------------------------------------------------- /prebuilt/.gitignore: -------------------------------------------------------------------------------- 1 | *.a 2 | *.lib 3 | *.exe 4 | sccache 5 | hyperfine 6 | -------------------------------------------------------------------------------- /prebuilt/linux64/hyperfine.sha1: -------------------------------------------------------------------------------- 1 | c01e9c3d9169065911a1c74e935e0fdf15094e36 -------------------------------------------------------------------------------- /prebuilt/win/hyperfine.exe.sha1: -------------------------------------------------------------------------------- 1 | ad87698076d05b3d7d2cdf0705302ccf9444e3f2 -------------------------------------------------------------------------------- /prebuilt/win/sccache.exe.sha1: -------------------------------------------------------------------------------- 1 | 780e971f6651a1cd142bf2f6a8403068fb62d2f8 -------------------------------------------------------------------------------- /tests/020_json_modules.ts.out: -------------------------------------------------------------------------------- 1 | {"foo":{"bar":true,"baz":["qat",1]}} 2 | -------------------------------------------------------------------------------- /tests/024_import_no_ext_with_mime.ts: -------------------------------------------------------------------------------- 1 | import "./023_no_ext_with_mime"; 2 | -------------------------------------------------------------------------------- /tests/badly_formatted.js: -------------------------------------------------------------------------------- 1 | 2 | console.log( 3 | "Hello World" 4 | ) 5 | -------------------------------------------------------------------------------- /tests/subdir/mod2.ts: -------------------------------------------------------------------------------- 1 | export { printHello } from "./print_hello.ts"; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_text_ecmascript.j3.js: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_text_javascript.j1.js: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_text_typescript.t1.ts: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/circular1.js: -------------------------------------------------------------------------------- 1 | import "circular2.js"; 2 | console.log("circular1"); 3 | -------------------------------------------------------------------------------- /tests/circular2.js: -------------------------------------------------------------------------------- 1 | import "circular1.js"; 2 | console.log("circular2"); 3 | -------------------------------------------------------------------------------- /tests/esm_imports_b.js: -------------------------------------------------------------------------------- 1 | export function retb() { 2 | return "b"; 3 | } 4 | -------------------------------------------------------------------------------- /tests/subdir/mt_application_ecmascript.j2.js: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_application_x_javascript.j4.js: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tests/subdir/mt_application_x_typescript.t4.ts: -------------------------------------------------------------------------------- 1 | export const loaded = true; 2 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/moduleF.ts: -------------------------------------------------------------------------------- 1 | export const key = "value"; 2 | -------------------------------------------------------------------------------- /prebuilt/linux64/sccache.sha1: -------------------------------------------------------------------------------- 1 | eb8a16722a8019259244022b9c2e0412aeafefdd 2 | 3 | -------------------------------------------------------------------------------- /tests/018_async_catch.ts.out: -------------------------------------------------------------------------------- 1 | before await fn() 2 | catch 3 | after try-catch 4 | -------------------------------------------------------------------------------- /tests/019_media_types.ts.out: -------------------------------------------------------------------------------- 1 | success true true true true true true true true 2 | -------------------------------------------------------------------------------- /tests/error_004_missing_module.ts: -------------------------------------------------------------------------------- 1 | import * as badModule from "bad-module.ts"; 2 | -------------------------------------------------------------------------------- /tests/subdir/auto_print_hello.ts: -------------------------------------------------------------------------------- 1 | console.log("hello!"); 2 | export default {}; 3 | -------------------------------------------------------------------------------- /website/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fd/deno/master/website/favicon.ico -------------------------------------------------------------------------------- /tests/if_main.test: -------------------------------------------------------------------------------- 1 | args: tests/if_main.ts --reload 2 | output: tests/if_main.ts.out 3 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | js/flatbuffers.js 2 | tests/error_syntax.js 3 | tests/badly_formatted.js 4 | -------------------------------------------------------------------------------- /tests/001_hello.test: -------------------------------------------------------------------------------- 1 | args: tests/001_hello.js --reload 2 | output: tests/001_hello.js.out 3 | -------------------------------------------------------------------------------- /tests/002_hello.test: -------------------------------------------------------------------------------- 1 | args: tests/002_hello.ts --reload 2 | output: tests/002_hello.ts.out 3 | -------------------------------------------------------------------------------- /tests/012_async.test: -------------------------------------------------------------------------------- 1 | args: tests/012_async.ts --reload 2 | output: tests/012_async.ts.out 3 | -------------------------------------------------------------------------------- /tests/circular1.test: -------------------------------------------------------------------------------- 1 | args: tests/circular1.js --reload 2 | output: tests/circular1.js.out 3 | -------------------------------------------------------------------------------- /tests/exit_error42.ts: -------------------------------------------------------------------------------- 1 | console.log("before"); 2 | Deno.exit(42); 3 | console.log("after"); 4 | -------------------------------------------------------------------------------- /tests/import_meta2.ts: -------------------------------------------------------------------------------- 1 | console.log("import_meta2", import.meta.url, import.meta.main); 2 | -------------------------------------------------------------------------------- /tests/no_color.js: -------------------------------------------------------------------------------- 1 | import { noColor } from "deno"; 2 | console.log("noColor", noColor); 3 | -------------------------------------------------------------------------------- /tests/error_syntax.js: -------------------------------------------------------------------------------- 1 | 2 | // prettier-ignore 3 | (the following is a syntax error ^^ ! ) 4 | -------------------------------------------------------------------------------- /tests/https_import.test: -------------------------------------------------------------------------------- 1 | args: tests/https_import.ts --reload 2 | output: tests/https_import.ts.out 3 | -------------------------------------------------------------------------------- /tests/import_meta.test: -------------------------------------------------------------------------------- 1 | args: tests/import_meta.ts --reload 2 | output: tests/import_meta.ts.out 3 | -------------------------------------------------------------------------------- /tests/subdir/print_hello.ts: -------------------------------------------------------------------------------- 1 | export function printHello(): void { 2 | console.log("Hello"); 3 | } 4 | -------------------------------------------------------------------------------- /website/images/deno_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fd/deno/master/website/images/deno_logo.png -------------------------------------------------------------------------------- /tests/subdir/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": { 3 | "bar": true, 4 | "baz": ["qat", 1] 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /website/images/deno_logo_2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fd/deno/master/website/images/deno_logo_2.gif -------------------------------------------------------------------------------- /tests/003_relative_import.ts: -------------------------------------------------------------------------------- 1 | import { printHello } from "./subdir/print_hello.ts"; 2 | 3 | printHello(); 4 | -------------------------------------------------------------------------------- /tests/004_set_timeout.test: -------------------------------------------------------------------------------- 1 | args: tests/004_set_timeout.ts --reload 2 | output: tests/004_set_timeout.ts.out 3 | -------------------------------------------------------------------------------- /tests/006_url_imports.test: -------------------------------------------------------------------------------- 1 | args: tests/006_url_imports.ts --reload 2 | output: tests/006_url_imports.ts.out 3 | -------------------------------------------------------------------------------- /tests/018_async_catch.test: -------------------------------------------------------------------------------- 1 | args: tests/018_async_catch.ts --reload 2 | output: tests/018_async_catch.ts.out 3 | -------------------------------------------------------------------------------- /tests/019_media_types.test: -------------------------------------------------------------------------------- 1 | args: tests/019_media_types.ts --reload 2 | output: tests/019_media_types.ts.out 3 | -------------------------------------------------------------------------------- /tests/020_json_modules.ts: -------------------------------------------------------------------------------- 1 | import config from "./subdir/config.json"; 2 | console.log(JSON.stringify(config)); 3 | -------------------------------------------------------------------------------- /tests/esm_imports_a.js: -------------------------------------------------------------------------------- 1 | import { retb } from "./esm_imports_b.js"; 2 | 3 | if (retb() != "b") throw Error(); 4 | -------------------------------------------------------------------------------- /tests/unbuffered_stderr.ts: -------------------------------------------------------------------------------- 1 | const { stderr } = Deno; 2 | 3 | stderr.write(new TextEncoder().encode("x")); 4 | -------------------------------------------------------------------------------- /tests/unbuffered_stdout.ts: -------------------------------------------------------------------------------- 1 | const { stdout } = Deno; 2 | 3 | stdout.write(new TextEncoder().encode("a")); 4 | -------------------------------------------------------------------------------- /website/images/schematic_v0.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fd/deno/master/website/images/schematic_v0.2.png -------------------------------------------------------------------------------- /tests/005_more_imports.test: -------------------------------------------------------------------------------- 1 | args: tests/005_more_imports.ts --reload 2 | output: tests/005_more_imports.ts.out 3 | -------------------------------------------------------------------------------- /tests/010_set_interval.test: -------------------------------------------------------------------------------- 1 | args: tests/010_set_interval.ts --reload 2 | output: tests/010_set_interval.ts.out 3 | -------------------------------------------------------------------------------- /tests/020_json_modules.test: -------------------------------------------------------------------------------- 1 | args: tests/020_json_modules.ts --reload 2 | output: tests/020_json_modules.ts.out 3 | -------------------------------------------------------------------------------- /tests/unbuffered_stdout.test: -------------------------------------------------------------------------------- 1 | args: tests/unbuffered_stdout.ts --reload 2 | output: tests/unbuffered_stdout.ts.out 3 | -------------------------------------------------------------------------------- /tests/003_relative_import.test: -------------------------------------------------------------------------------- 1 | args: tests/003_relative_import.ts --reload 2 | output: tests/003_relative_import.ts.out 3 | -------------------------------------------------------------------------------- /tests/017_import_redirect.test: -------------------------------------------------------------------------------- 1 | args: tests/017_import_redirect.ts --reload 2 | output: tests/017_import_redirect.ts.out 3 | -------------------------------------------------------------------------------- /tests/error_010_nonexistent_arg.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]Cannot resolve module "file:[WILDCARD]not-a-valid-filename.ts" from "." 2 | -------------------------------------------------------------------------------- /tests/exit_error42.test: -------------------------------------------------------------------------------- 1 | exit_code: 42 2 | args: tests/exit_error42.ts --reload 3 | output: tests/exit_error42.ts.out 4 | -------------------------------------------------------------------------------- /tests/import_meta.ts: -------------------------------------------------------------------------------- 1 | console.log("import_meta", import.meta.url, import.meta.main); 2 | 3 | import "import_meta2.ts"; 4 | -------------------------------------------------------------------------------- /tests/import_meta.ts.out: -------------------------------------------------------------------------------- 1 | import_meta2 [WILDCARD]import_meta2.ts false 2 | import_meta [WILDCARD]import_meta.ts true 3 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | -------------------------------------------------------------------------------- /js/mock_builtin.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | export default undefined; 3 | -------------------------------------------------------------------------------- /tests/013_dynamic_import.disabled: -------------------------------------------------------------------------------- 1 | args: tests/013_dynamic_import.ts --reload 2 | output: tests/013_dynamic_import.ts.out 3 | -------------------------------------------------------------------------------- /tests/016_double_await.test: -------------------------------------------------------------------------------- 1 | args: tests/016_double_await.ts --allow-read --reload 2 | output: tests/016_double_await.ts.out 3 | -------------------------------------------------------------------------------- /tests/error_005_missing_dynamic_import.ts: -------------------------------------------------------------------------------- 1 | (async () => { 2 | const badModule = await import("bad-module.ts"); 3 | })(); 4 | -------------------------------------------------------------------------------- /tests/014_duplicate_import.disabled: -------------------------------------------------------------------------------- 1 | args: tests/014_duplicate_import.ts --reload 2 | output: tests/014_duplicate_import.ts.out 3 | -------------------------------------------------------------------------------- /tests/023_no_ext_with_mime.test: -------------------------------------------------------------------------------- 1 | args: tests/023_no_ext_with_mime --reload --recompile 2 | output: tests/023_no_ext_with_mime.out 3 | -------------------------------------------------------------------------------- /tests/error_001.test: -------------------------------------------------------------------------------- 1 | args: tests/error_001.ts --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_001.ts.out 5 | -------------------------------------------------------------------------------- /tests/error_002.test: -------------------------------------------------------------------------------- 1 | args: tests/error_002.ts --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_002.ts.out 5 | -------------------------------------------------------------------------------- /tests/error_003_typescript.ts: -------------------------------------------------------------------------------- 1 | // console.log intentionally misspelled to trigger TypeScript error 2 | consol.log("hello world!"); 3 | -------------------------------------------------------------------------------- /tests/error_009_missing_js_module.js.out: -------------------------------------------------------------------------------- 1 | Cannot resolve module "./bad-module.js" from "[WILDCARD]error_009_missing_js_module.js" 2 | -------------------------------------------------------------------------------- /tests/async_error.test: -------------------------------------------------------------------------------- 1 | exit_code: 1 2 | args: tests/async_error.ts --reload 3 | check_stderr: true 4 | output: tests/async_error.ts.out 5 | -------------------------------------------------------------------------------- /tests/error_001.ts: -------------------------------------------------------------------------------- 1 | function foo() { 2 | throw Error("bad"); 3 | } 4 | 5 | function bar() { 6 | foo(); 7 | } 8 | 9 | bar(); 10 | -------------------------------------------------------------------------------- /tests/error_002.ts: -------------------------------------------------------------------------------- 1 | import { throwsError } from "./subdir/mod1.ts"; 2 | 3 | function foo() { 4 | throwsError(); 5 | } 6 | 7 | foo(); 8 | -------------------------------------------------------------------------------- /tests/error_003_typescript.test: -------------------------------------------------------------------------------- 1 | args: tests/error_003_typescript.ts --reload 2 | exit_code: 1 3 | output: tests/error_003_typescript.ts.out 4 | -------------------------------------------------------------------------------- /tests/error_syntax.test: -------------------------------------------------------------------------------- 1 | args: tests/error_syntax.js --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_syntax.js.out 5 | -------------------------------------------------------------------------------- /tests/unbuffered_stderr.test: -------------------------------------------------------------------------------- 1 | args: tests/unbuffered_stderr.ts --reload 2 | check_stderr: true 3 | output: tests/unbuffered_stderr.ts.out 4 | -------------------------------------------------------------------------------- /tests/006_url_imports.ts: -------------------------------------------------------------------------------- 1 | import { printHello } from "http://localhost:4545/tests/subdir/mod2.ts"; 2 | printHello(); 3 | console.log("success"); 4 | -------------------------------------------------------------------------------- /tests/error_007_any.test: -------------------------------------------------------------------------------- 1 | args: tests/error_007_any.ts --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_007_any.ts.out 5 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/lib.extra.d.ts: -------------------------------------------------------------------------------- 1 | // comment 2 | 3 | declare namespace Qat { 4 | class Foo { 5 | bar: string; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tests/error_008_checkjs.test: -------------------------------------------------------------------------------- 1 | args: tests/error_008_checkjs.js --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_008_checkjs.js.out 5 | -------------------------------------------------------------------------------- /tests/error_010_nonexistent_arg.test: -------------------------------------------------------------------------------- 1 | args: not-a-valid-filename.ts 2 | output: tests/error_010_nonexistent_arg.out 3 | exit_code: 1 4 | check_stderr: true 5 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | max_width = 80 3 | tab_spaces = 2 4 | format_macro_bodies = true 5 | -------------------------------------------------------------------------------- /js/types.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | export type TypedArray = Uint8Array | Float32Array | Int32Array; 3 | -------------------------------------------------------------------------------- /tests/024_import_no_ext_with_mime.test: -------------------------------------------------------------------------------- 1 | args: tests/024_import_no_ext_with_mime.ts --reload --recompile 2 | output: tests/024_import_no_ext_with_mime.ts.out 3 | -------------------------------------------------------------------------------- /tests/010_set_interval.ts: -------------------------------------------------------------------------------- 1 | const id = setInterval(() => { 2 | console.log("test"); 3 | }, 200); 4 | 5 | setTimeout(() => { 6 | clearInterval(id); 7 | }, 500); 8 | -------------------------------------------------------------------------------- /tests/error_009_missing_js_module.test: -------------------------------------------------------------------------------- 1 | args: tests/error_009_missing_js_module.js 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_009_missing_js_module.js.out -------------------------------------------------------------------------------- /tests/error_004_missing_module.test: -------------------------------------------------------------------------------- 1 | args: tests/error_004_missing_module.ts --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_004_missing_module.ts.out 5 | -------------------------------------------------------------------------------- /tests/error_syntax.js.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]tests/error_syntax.js:3:5 2 | (the following is a syntax error ^^ ! ) 3 | ^^^^^^^^^ 4 | Uncaught SyntaxError: Unexpected identifier 5 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/api.ts: -------------------------------------------------------------------------------- 1 | export { foo, bar } from "./moduleA"; 2 | export { Foo } from "./moduleB"; 3 | /** jsdoc for arr */ 4 | export const arr: string[] = []; 5 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/moduleD.ts: -------------------------------------------------------------------------------- 1 | import * as moduleF from "./moduleF"; 2 | 3 | export function reprocess(value: typeof moduleF.key) { 4 | console.log(value); 5 | } 6 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/moduleE.ts: -------------------------------------------------------------------------------- 1 | import * as moduleF from "./moduleF"; 2 | 3 | export function process(value: typeof moduleF.key) { 4 | console.log(value); 5 | } 6 | -------------------------------------------------------------------------------- /tests/async_error.ts: -------------------------------------------------------------------------------- 1 | console.log("hello"); 2 | const foo = async () => { 3 | console.log("before error"); 4 | throw Error("error"); 5 | }; 6 | 7 | foo(); 8 | console.log("world"); 9 | -------------------------------------------------------------------------------- /tests/error_006_import_ext_failure.test: -------------------------------------------------------------------------------- 1 | args: tests/error_006_import_ext_failure.ts --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_006_import_ext_failure.ts.out 5 | -------------------------------------------------------------------------------- /tests/error_005_missing_dynamic_import.test: -------------------------------------------------------------------------------- 1 | args: tests/error_005_missing_dynamic_import.ts --reload 2 | check_stderr: true 3 | exit_code: 1 4 | output: tests/error_005_missing_dynamic_import.ts.out 5 | -------------------------------------------------------------------------------- /tests/error_001.ts.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]Error: bad 2 | at foo (file://[WILDCARD]tests/error_001.ts:2:9) 3 | at bar (file://[WILDCARD]tests/error_001.ts:6:3) 4 | at file://[WILDCARD]tests/error_001.ts:9:1 5 | -------------------------------------------------------------------------------- /tools/ts_library_builder/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "strict": true, 5 | "target": "esnext" 6 | }, 7 | "files": ["./build_library.ts"] 8 | } 9 | -------------------------------------------------------------------------------- /tests/error_008_checkjs.js.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]tests/error_008_checkjs.js:2:0 2 | consol.log("hello world!"); 3 | ^ 4 | Uncaught ReferenceError: consol is not defined 5 | at [WILDCARD]tests/error_008_checkjs.js:2:1 6 | -------------------------------------------------------------------------------- /tests/subdir/subdir2/mod2.ts: -------------------------------------------------------------------------------- 1 | import { printHello } from "../print_hello.ts"; 2 | 3 | export function returnsFoo(): string { 4 | return "Foo"; 5 | } 6 | 7 | export function printHello2(): void { 8 | printHello(); 9 | } 10 | -------------------------------------------------------------------------------- /tests/error_002.ts.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]Error: exception from mod1 2 | at throwsError (file://[WILDCARD]/tests/subdir/mod1.ts:16:9) 3 | at foo (file://[WILDCARD]/tests/error_002.ts:4:3) 4 | at file://[WILDCARD]/tests/error_002.ts:7:1 5 | -------------------------------------------------------------------------------- /tests/004_set_timeout.ts: -------------------------------------------------------------------------------- 1 | setTimeout(() => { 2 | console.log("World"); 3 | }, 10); 4 | 5 | console.log("Hello"); 6 | 7 | const id = setTimeout(() => { 8 | console.log("Not printed"); 9 | }, 10000); 10 | 11 | clearTimeout(id); 12 | -------------------------------------------------------------------------------- /tests/022_info_flag.test: -------------------------------------------------------------------------------- 1 | # The output assumes 003_relative_import.ts has already been run earlier 2 | # and its output is cached to $DENO_DIR. 3 | args: --info http://127.0.0.1:4545/tests/019_media_types.ts 4 | output: tests/022_info_flag.out 5 | -------------------------------------------------------------------------------- /tests/error_008_checkjs.js: -------------------------------------------------------------------------------- 1 | // console.log intentionally misspelled to trigger a type error 2 | consol.log("hello world!"); 3 | 4 | // the following error should be ignored and not output to the console 5 | // @ts-ignore 6 | const foo = new Foo(); 7 | -------------------------------------------------------------------------------- /tools/build_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import sys 4 | from build import main as build 5 | from test import main as test 6 | 7 | build(sys.argv) 8 | test(sys.argv) 9 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/moduleB.ts: -------------------------------------------------------------------------------- 1 | /** jsdoc about Foo */ 2 | export class Foo { 3 | private _foo = "foo"; 4 | /** jsdoc about Foo.log() */ 5 | log() { 6 | console.log(this._foo); 7 | return this._foo; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tests/if_main.ts: -------------------------------------------------------------------------------- 1 | if (window.location.toString() == import.meta.url) { 2 | console.log("main"); 3 | } else { 4 | console.log("import.meta.url", import.meta.url); 5 | console.log("window.location", window.location.toString()); 6 | throw Error("not main"); 7 | } 8 | -------------------------------------------------------------------------------- /tests/005_more_imports.ts: -------------------------------------------------------------------------------- 1 | import { returnsHi, returnsFoo2, printHello3 } from "./subdir/mod1.ts"; 2 | 3 | printHello3(); 4 | 5 | if (returnsHi() !== "Hi") { 6 | throw Error("Unexpected"); 7 | } 8 | 9 | if (returnsFoo2() !== "Foo") { 10 | throw Error("Unexpected"); 11 | } 12 | -------------------------------------------------------------------------------- /tests/012_async.ts: -------------------------------------------------------------------------------- 1 | // Check that we can use the async keyword. 2 | async function main() { 3 | await new Promise((resolve, reject) => { 4 | console.log("2"); 5 | setTimeout(resolve, 100); 6 | }); 7 | console.log("3"); 8 | } 9 | 10 | console.log("1"); 11 | main(); 12 | -------------------------------------------------------------------------------- /tests/async_error.ts.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]hello 2 | before error 3 | world 4 | [WILDCARD]tests/async_error.ts:4:10 5 | throw Error("error"); 6 | ^ 7 | Uncaught Error: error 8 | at foo ([WILDCARD]tests/async_error.ts:4:9) 9 | at [WILDCARD]tests/async_error.ts:7:1 10 | -------------------------------------------------------------------------------- /tests/cat.ts: -------------------------------------------------------------------------------- 1 | const { stdout, open, copy, args } = Deno; 2 | 3 | async function main() { 4 | for (let i = 1; i < args.length; i++) { 5 | const filename = args[i]; 6 | const file = await open(filename); 7 | await copy(stdout, file); 8 | } 9 | } 10 | 11 | main(); 12 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/moduleA.ts: -------------------------------------------------------------------------------- 1 | /** jsdoc for foo */ 2 | export function foo(a: string, b: string) { 3 | console.log(a, b); 4 | } 5 | 6 | // no jsdoc for bar 7 | export async function bar(promise: Promise): Promise { 8 | return promise.then(() => {}); 9 | } 10 | -------------------------------------------------------------------------------- /tests/017_import_redirect.ts: -------------------------------------------------------------------------------- 1 | // http -> https redirect would happen: 2 | // tslint:disable-next-line:max-line-length 3 | import { printHello } from "http://gist.githubusercontent.com/ry/f12b2aa3409e6b52645bc346a9e22929/raw/79318f239f51d764384a8bded8d7c6a833610dde/print_hello.ts"; 4 | 5 | printHello(); 6 | -------------------------------------------------------------------------------- /tests/014_duplicate_import.ts: -------------------------------------------------------------------------------- 1 | // with all the imports of the same module, the module should only be 2 | // instantiated once 3 | import "./subdir/auto_print_hello.ts"; 4 | 5 | import "./subdir/auto_print_hello.ts"; 6 | 7 | (async () => { 8 | await import("./subdir/auto_print_hello.ts"); 9 | })(); 10 | -------------------------------------------------------------------------------- /tests/echo_server.ts: -------------------------------------------------------------------------------- 1 | const { args, listen, copy } = Deno; 2 | const addr = args[1] || "127.0.0.1:4544"; 3 | const listener = listen("tcp", addr); 4 | console.log("listening on", addr); 5 | listener.accept().then(async conn => { 6 | await copy(conn, conn); 7 | conn.close(); 8 | listener.close(); 9 | }); 10 | -------------------------------------------------------------------------------- /tools/node_http.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | const http = require("http"); 3 | const port = process.argv[2] || "4544"; 4 | console.log("port", port); 5 | http 6 | .Server((req, res) => { 7 | res.end("Hello World\n"); 8 | }) 9 | .listen(port); 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # build 2 | *.swp 3 | /out/ 4 | /target/ 5 | *.pyc 6 | gclient_config.py_entries 7 | yarn.lock 8 | # npm deps 9 | node_modules 10 | # editor files 11 | .idea 12 | .vscode 13 | # export dir for gh-pages 14 | /gh-pages 15 | # temp benchmark data 16 | /website/data.json 17 | /website/recent.json 18 | /js/gen 19 | -------------------------------------------------------------------------------- /tests/016_double_await.ts: -------------------------------------------------------------------------------- 1 | // This is to test if Deno would die at 2nd await 2 | // See https://github.com/denoland/deno/issues/919 3 | (async () => { 4 | const currDirInfo = await Deno.stat("."); 5 | const parentDirInfo = await Deno.stat(".."); 6 | console.log(currDirInfo.isDirectory()); 7 | console.log(parentDirInfo.isFile()); 8 | })(); 9 | -------------------------------------------------------------------------------- /js/performance_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert } from "./test_util.ts"; 3 | 4 | test(function now() { 5 | const start = performance.now(); 6 | setTimeout(() => { 7 | const end = performance.now(); 8 | assert(end - start >= 10); 9 | }, 10); 10 | }); 11 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Use Unix line endings in all text files. 2 | * text=auto eol=lf 3 | 4 | # Tell git which symlinks point to files, and which ones point to directories. 5 | # This is revelevant for Windows only, and requires git >= 2.19.2 to work. 6 | /* symlink=dir 7 | /website/* symlink=dir 8 | /tools/clang symlink=dir 9 | /tools/memory symlink=dir 10 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | indent_style = space 7 | indent_size = 2 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | 11 | [*.out] # make editor neutral to .out files 12 | insert_final_newline = false 13 | trim_trailing_whitespace = false 14 | 15 | [*.py] 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /libdeno/test.h: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #ifndef TEST_H_ 3 | #define TEST_H_ 4 | 5 | #include "deno.h" 6 | #include "testing/gtest/include/gtest/gtest.h" 7 | 8 | extern deno_buf snapshot; // Loaded in libdeno/test.cc 9 | const deno_buf empty = {nullptr, 0, nullptr, 0, 0}; 10 | 11 | #endif // TEST_H_ 12 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "third_party"] 2 | path = third_party 3 | url = https://github.com/denoland/deno_third_party.git 4 | [submodule "build"] 5 | path = build 6 | url = https://github.com/denoland/chromium_build.git 7 | [submodule "js/deps/https/deno.land/x/std"] 8 | path = js/deps/https/deno.land/x/std 9 | url = https://github.com/denoland/deno_std.git 10 | -------------------------------------------------------------------------------- /tests/https_import.ts: -------------------------------------------------------------------------------- 1 | // TODO Use https://localhost:4555/ but we need more infrastructure to 2 | // support verifying self-signed certificates. 3 | // tslint:disable-next-line:max-line-length 4 | import { printHello } from "https://gist.githubusercontent.com/ry/f12b2aa3409e6b52645bc346a9e22929/raw/79318f239f51d764384a8bded8d7c6a833610dde/print_hello.ts"; 5 | 6 | printHello(); 7 | -------------------------------------------------------------------------------- /tests/013_dynamic_import.ts: -------------------------------------------------------------------------------- 1 | (async () => { 2 | const { 3 | returnsHi, 4 | returnsFoo2, 5 | printHello3 6 | } = await import("./subdir/mod1.ts"); 7 | 8 | printHello3(); 9 | 10 | if (returnsHi() !== "Hi") { 11 | throw Error("Unexpected"); 12 | } 13 | 14 | if (returnsFoo2() !== "Foo") { 15 | throw Error("Unexpected"); 16 | } 17 | })(); 18 | -------------------------------------------------------------------------------- /js/location_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert } from "./test_util.ts"; 3 | 4 | test(function locationBasic() { 5 | // location example: file:///Users/rld/src/deno/js/unit_tests.ts 6 | console.log("location", window.location.toString()); 7 | assert(window.location.toString().endsWith("unit_tests.ts")); 8 | }); 9 | -------------------------------------------------------------------------------- /tests/types.out: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | /// 4 | /// 5 | 6 | declare namespace Deno { 7 | [WILDCARD] 8 | } 9 | [WILDCARD] 10 | declare interface Window { 11 | [WILDCARD] 12 | Deno: typeof Deno; 13 | } 14 | 15 | declare const window: Window; 16 | [WILDCARD] 17 | -------------------------------------------------------------------------------- /js/version_test.ts: -------------------------------------------------------------------------------- 1 | import { test, assert } from "./test_util.ts"; 2 | 3 | test(function version() { 4 | const pattern = /^\d+\.\d+\.\d+$/; 5 | assert(pattern.test(Deno.version.deno)); 6 | assert(pattern.test(Deno.version.v8)); 7 | assert(pattern.test(Deno.version.typescript)); 8 | }); 9 | 10 | test(function versionGnArgs() { 11 | assert(Deno.version.gnArgs.length > 100); 12 | }); 13 | -------------------------------------------------------------------------------- /src/version.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | use crate::libdeno; 3 | 4 | use std::ffi::CStr; 5 | 6 | pub const DENO: &str = env!("CARGO_PKG_VERSION"); 7 | 8 | pub fn v8() -> &'static str { 9 | let version = unsafe { libdeno::deno_v8_version() }; 10 | let c_str = unsafe { CStr::from_ptr(version) }; 11 | c_str.to_str().unwrap() 12 | } 13 | -------------------------------------------------------------------------------- /tests/018_async_catch.ts: -------------------------------------------------------------------------------- 1 | async function fn() { 2 | throw new Error("message"); 3 | } 4 | async function call() { 5 | try { 6 | console.log("before await fn()"); 7 | await fn(); 8 | console.log("after await fn()"); 9 | } catch (error) { 10 | console.log("catch"); 11 | } 12 | console.log("after try-catch"); 13 | } 14 | call().catch(() => console.log("outer catch")); 15 | -------------------------------------------------------------------------------- /tests/error_003_typescript.ts.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]tests/error_003_typescript.ts[WILDCARD] - error TS2552: Cannot find name 'consol'. Did you mean 'console'? 2 | 3 | [WILDCARD] consol.log("hello world!"); 4 | [WILDCARD]~~~~~~ 5 | 6 | $asset$/lib.deno_runtime.d.ts[WILDCARD] 7 | [WILDCARD]declare const console: consoleTypes.Console; 8 | [WILDCARD]~~~~~~~ 9 | [WILDCARD]'console' is declared here. 10 | 11 | -------------------------------------------------------------------------------- /js/plugins.d.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | // This allows TypeScript to resolve any modules that end with `!string` 4 | // as there is a rollup plugin that will take any mids ending with `!string` 5 | // and return them as a string to rollup for inlining 6 | declare module "*!string" { 7 | const value: string; 8 | export default value; 9 | } 10 | -------------------------------------------------------------------------------- /tests/subdir/mod1.ts: -------------------------------------------------------------------------------- 1 | import { returnsFoo, printHello2 } from "./subdir2/mod2.ts"; 2 | 3 | export function returnsHi(): string { 4 | return "Hi"; 5 | } 6 | 7 | export function returnsFoo2(): string { 8 | return returnsFoo(); 9 | } 10 | 11 | export function printHello3(): void { 12 | printHello2(); 13 | } 14 | 15 | export function throwsError(): void { 16 | throw Error("exception from mod1"); 17 | } 18 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/moduleC.ts: -------------------------------------------------------------------------------- 1 | /** jsdoc for Bar */ 2 | export class Bar { 3 | private _bar: string; 4 | /** jsdoc for Bar.log() */ 5 | log() { 6 | console.log(this._bar); 7 | return this.log; 8 | } 9 | } 10 | 11 | /** 12 | * jsdoc for qat 13 | * @param a jsdoc for qat(a) 14 | * @param b jsdoc for qat(b) 15 | */ 16 | export function qat(a: string, b: string) { 17 | return a + b; 18 | } 19 | -------------------------------------------------------------------------------- /tools/testdata/wrk1.txt: -------------------------------------------------------------------------------- 1 | Running 10s test @ http://127.0.0.1:4500/ 2 | 2 threads and 10 connections 3 | Thread Stats Avg Stdev Max +/- Stdev 4 | Latency 5.08ms 1.37ms 34.96ms 96.63% 5 | Req/Sec 0.92k 51.83 1.00k 78.50% 6 | 18381 requests in 10.00s, 0.89MB read 7 | Socket errors: connect 0, read 18381, write 0, timeout 0 8 | Requests/sec: 1837.86 9 | Transfer/sec: 91.53KB 10 | -------------------------------------------------------------------------------- /js/platform_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert } from "./test_util.ts"; 3 | 4 | test(function platformTransform() { 5 | // deno.platform is injected by rollup at compile time. Here 6 | // we check it has been properly transformed. 7 | const { arch, os } = Deno.platform; 8 | assert(arch === "x64"); 9 | assert(os === "mac" || os === "win" || os === "linux"); 10 | }); 11 | -------------------------------------------------------------------------------- /libdeno/file_util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #ifndef FILE_UTIL_H_ 3 | #define FILE_UTIL_H_ 4 | 5 | #include 6 | 7 | namespace deno { 8 | bool ReadFileToString(const char* fn, std::string* contents); 9 | std::string Basename(std::string const& filename); 10 | std::string Dirname(std::string const& filename); 11 | bool ExePath(std::string* path); 12 | } // namespace deno 13 | 14 | #endif // FILE_UTIL_H_ 15 | -------------------------------------------------------------------------------- /tools/ts_library_builder/testdata/globals.ts: -------------------------------------------------------------------------------- 1 | import * as moduleC from "./moduleC"; 2 | import * as moduleD from "./moduleD"; 3 | import * as moduleE from "./moduleE"; 4 | 5 | // tslint:disable-next-line:no-any 6 | const foobarbaz: any = {}; 7 | foobarbaz.bar = new moduleC.Bar(); 8 | foobarbaz.qat = moduleC.qat; 9 | foobarbaz.process = moduleE.process; 10 | foobarbaz.reprocess = moduleD.reprocess; 11 | foobarbaz.Bar = moduleC.Bar; 12 | export type Bar = moduleC.Bar; 13 | -------------------------------------------------------------------------------- /js/window.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | // (0, eval) is indirect eval. 4 | // See the links below for details: 5 | // - https://stackoverflow.com/a/14120023 6 | // - https://tc39.github.io/ecma262/#sec-performeval (spec) 7 | export const window = (0, eval)("this"); 8 | // TODO: The above should be replaced with globalThis 9 | // when the globalThis proposal goes to stage 4 10 | // See https://github.com/tc39/proposal-global 11 | -------------------------------------------------------------------------------- /tools/write_gn_args.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import os 3 | import sys 4 | import third_party 5 | from util import run_output, build_path 6 | 7 | out_filename = sys.argv[1] 8 | 9 | args_list = run_output([ 10 | third_party.gn_path, "args", 11 | build_path(), "--list", "--short", "--overrides-only" 12 | ], 13 | env=third_party.google_env()) 14 | 15 | with open(out_filename, "w") as f: 16 | f.write(args_list) 17 | -------------------------------------------------------------------------------- /js/platform.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | // Do not add unsupported platforms. 4 | export interface Platform { 5 | /** The operating system CPU architecture. */ 6 | arch: "x64"; 7 | 8 | /** The operating system platform. */ 9 | os: "mac" | "win" | "linux"; 10 | } 11 | 12 | // 'platform' is injected by rollup.config.js at compile time. 13 | export const platform: Platform = { 14 | // tslint:disable:no-any 15 | arch: "" as any, 16 | os: "" as any 17 | // tslint:disable:any 18 | }; 19 | -------------------------------------------------------------------------------- /tools/test_format.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # This program fails if ./tools/format.py changes any files. 3 | 4 | import sys 5 | import util 6 | import sys 7 | import subprocess 8 | 9 | 10 | def main(): 11 | util.run([sys.executable, "tools/format.py"]) 12 | output = util.run_output( 13 | ["git", "status", "-uno", "--porcelain", "--ignore-submodules"]) 14 | if len(output) > 0: 15 | print "Run tools/format.py " 16 | print output 17 | sys.exit(1) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /tools/node_tcp.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | // Note: this is a keep-alive server. 3 | const { Server } = require("net"); 4 | const port = process.argv[2] || "4544"; 5 | console.log("port", port); 6 | 7 | const response = Buffer.from( 8 | "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" 9 | ); 10 | 11 | Server(socket => { 12 | socket.on("data", _ => { 13 | socket.write(response); 14 | }); 15 | socket.on("error", _ => { 16 | socket.destroy(); 17 | }); 18 | }).listen(port); 19 | -------------------------------------------------------------------------------- /tools/upload_website.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import os 4 | import tempfile 5 | from util import run, root_path 6 | 7 | # Probably run tools/docs.py first. 8 | # AWS CLI must be installed separately. 9 | 10 | os.chdir(os.path.join(root_path, "website")) 11 | 12 | # Invalidate the cache. 13 | run([ 14 | "aws", "cloudfront", "create-invalidation", "--distribution-id", 15 | "E2HNK8Z3X3JDVG", "--paths", "/*" 16 | ]) 17 | 18 | run(["aws", "s3", "sync", ".", "s3://deno.land/"]) 19 | -------------------------------------------------------------------------------- /core/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | [package] 4 | name = "deno_core" 5 | version = "0.0.1" 6 | edition = "2018" 7 | 8 | [lib] 9 | path = "lib.rs" 10 | 11 | [[bin]] 12 | name = "deno_core_http_bench" 13 | path = "http_bench.rs" 14 | required-features = ["bin-dependencies"] 15 | 16 | [features] 17 | bin-dependencies = ["tokio"] 18 | 19 | [dependencies] 20 | futures = "0.1.25" 21 | lazy_static = "1.3.0" 22 | libc = "0.2.49" 23 | log = "0.4.6" 24 | serde_json = "1.0.38" 25 | tokio = { version = "0.1.15", optional = true } 26 | -------------------------------------------------------------------------------- /tests/fetch_deps.ts: -------------------------------------------------------------------------------- 1 | // Run ./tools/http_server.py too in order for this test to run. 2 | import { assert } from "../js/deps/https/deno.land/x/std/testing/mod.ts"; 3 | 4 | // TODO Top level await https://github.com/denoland/deno/issues/471 5 | async function main() { 6 | const response = await fetch("http://localhost:4545/package.json"); 7 | const json = await response.json(); 8 | const deps = Object.keys(json.devDependencies); 9 | console.log("Deno JS Deps"); 10 | console.log(deps.map(d => `* ${d}`).join("\n")); 11 | assert(deps.includes("typescript")); 12 | } 13 | 14 | main(); 15 | -------------------------------------------------------------------------------- /tools/sync_third_party.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | # Run this script if you are changing Deno's dependencies. 4 | # To update the deno_third_party git repo after running this, try the following: 5 | # cd third_party 6 | # find . -type f | grep -v "\.git" | \ 7 | # xargs -I% git add -f --no-warn-embedded-repo "%" 8 | 9 | import third_party 10 | import util 11 | 12 | util.enable_ansi_colors() 13 | 14 | third_party.fix_symlinks() 15 | 16 | third_party.run_yarn() 17 | third_party.run_cargo() 18 | third_party.run_pip() 19 | third_party.run_gclient_sync() 20 | -------------------------------------------------------------------------------- /tests/wasm.ts: -------------------------------------------------------------------------------- 1 | // prettier-ignore 2 | const wasmCode = new Uint8Array([ 3 | 0, 97, 115, 109, 1, 0, 0, 0, 1, 133, 128, 128, 128, 0, 1, 96, 0, 1, 127, 4 | 3, 130, 128, 128, 128, 0, 1, 0, 4, 132, 128, 128, 128, 0, 1, 112, 0, 0, 5 | 5, 131, 128, 128, 128, 0, 1, 0, 1, 6, 129, 128, 128, 128, 0, 0, 7, 145, 6 | 128, 128, 128, 0, 2, 6, 109, 101, 109, 111, 114, 121, 2, 0, 4, 109, 97, 7 | 105, 110, 0, 0, 10, 138, 128, 128, 128, 0, 1, 132, 128, 128, 128, 0, 0, 8 | 65, 42, 11 9 | ]); 10 | 11 | const wasmModule = new WebAssembly.Module(wasmCode); 12 | 13 | const wasmInstance = new WebAssembly.Instance(wasmModule); 14 | 15 | console.log(wasmInstance.exports.main().toString()); 16 | -------------------------------------------------------------------------------- /js/version.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | interface Version { 3 | deno: string; 4 | v8: string; 5 | typescript: string; 6 | gnArgs: string; 7 | } 8 | 9 | export const version: Version = { 10 | deno: "", 11 | v8: "", 12 | typescript: "TS_VERSION", // This string will be replaced by rollup 13 | gnArgs: `GN_ARGS` // This string will be replaced by rollup 14 | }; 15 | 16 | /** 17 | * Sets the deno and v8 versions and freezes the version object. 18 | * @internal 19 | */ 20 | export function setVersions(denoVersion: string, v8Version: string): void { 21 | version.deno = denoVersion; 22 | version.v8 = v8Version; 23 | 24 | Object.freeze(version); 25 | } 26 | -------------------------------------------------------------------------------- /tools/node_tcp_promise.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | // Note: this is a keep-alive server. 3 | const { Server } = require("net"); 4 | const port = process.argv[2] || "4544"; 5 | console.log("port", port); 6 | 7 | const response = Buffer.from( 8 | "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" 9 | ); 10 | 11 | async function write(socket, buffer) { 12 | let p = new Promise((resolve, reject) => { 13 | socket.write(buffer, resolve); 14 | }); 15 | return p; 16 | } 17 | 18 | Server(async socket => { 19 | socket.on("error", _ => { 20 | socket.destroy(); 21 | }); 22 | for await (const data of socket) { 23 | write(socket, response); 24 | } 25 | }).listen(port); 26 | -------------------------------------------------------------------------------- /tools/is_tty_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import os 4 | import pty 5 | import select 6 | import subprocess 7 | from util import build_path, executable_suffix 8 | from sys import stdin 9 | from permission_prompt_test import tty_capture 10 | 11 | IS_TTY_TEST_TS = "tests/is_tty.ts" 12 | 13 | 14 | def is_tty_test(deno_exe): 15 | cmd = [deno_exe, IS_TTY_TEST_TS] 16 | code, stdout, _ = tty_capture(cmd, b'') 17 | assert code == 0 18 | assert str(stdin.isatty()).lower() in stdout 19 | 20 | 21 | def main(): 22 | deno_exe = os.path.join(build_path(), "deno" + executable_suffix) 23 | is_tty_test(deno_exe) 24 | 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /js/custom_event_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 the Deno authors. All rights reserved. MIT license. 2 | import { test, assertEqual } from "./test_util.ts"; 3 | 4 | test(function customEventInitializedWithDetail() { 5 | const type = "touchstart"; 6 | const detail = { message: "hello" }; 7 | const customEventDict = new CustomEventInit({ 8 | bubbles: true, 9 | cancelable: true, 10 | detail 11 | }); 12 | const event = new CustomEvent(type, customEventDict); 13 | 14 | assertEqual(event.bubbles, true); 15 | assertEqual(event.cancelable, true); 16 | assertEqual(event.currentTarget, null); 17 | assertEqual(event.detail, detail); 18 | assertEqual(event.isTrusted, false); 19 | assertEqual(event.target, null); 20 | assertEqual(event.type, type); 21 | }); 22 | -------------------------------------------------------------------------------- /tests/error_005_missing_dynamic_import.ts.out: -------------------------------------------------------------------------------- 1 | [WILDCARD]NotFound: Cannot resolve module "bad-module.ts" from "[WILDCARD]/tests/error_005_missing_dynamic_import.ts" 2 | at DenoError ([WILDCARD]/js/errors.ts:[WILDCARD]) 3 | at maybeError ([WILDCARD]/js/errors.ts:[WILDCARD]) 4 | at maybeThrowError ([WILDCARD]/js/errors.ts:[WILDCARD]) 5 | at sendSync ([WILDCARD]/js/dispatch.ts:[WILDCARD]) 6 | at fetchModuleMetaData ([WILDCARD]/js/os.ts:[WILDCARD]) 7 | at _resolveModule ([WILDCARD]/js/compiler.ts:[WILDCARD]) 8 | at resolveModuleNames ([WILDCARD]/js/compiler.ts:[WILDCARD]) 9 | at compilerHost.resolveModuleNames ([WILDCARD]) 10 | at resolveModuleNamesWorker ([WILDCARD]) 11 | at resolveModuleNamesReusingOldState ([WILDCARD]typescript.js:[WILDCARD]) 12 | -------------------------------------------------------------------------------- /tests/022_info_flag.out: -------------------------------------------------------------------------------- 1 | local: [WILDCARD]deps/http/127.0.0.1_PORT4545/tests/019_media_types.ts 2 | type: TypeScript 3 | compiled: [WILDCARD].js 4 | map: [WILDCARD].js.map 5 | deps: 6 | http://127.0.0.1:4545/tests/019_media_types.ts 7 | ├── http://localhost:4545/tests/subdir/mt_text_typescript.t1.ts 8 | ├── http://localhost:4545/tests/subdir/mt_video_vdn.t2.ts 9 | ├── http://localhost:4545/tests/subdir/mt_video_mp2t.t3.ts 10 | ├── http://localhost:4545/tests/subdir/mt_application_x_typescript.t4.ts 11 | ├── http://localhost:4545/tests/subdir/mt_text_javascript.j1.js 12 | ├── http://localhost:4545/tests/subdir/mt_application_ecmascript.j2.js 13 | ├── http://localhost:4545/tests/subdir/mt_text_ecmascript.j3.js 14 | └── http://localhost:4545/tests/subdir/mt_application_x_javascript.j4.js 15 | -------------------------------------------------------------------------------- /tools/run_node.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | """ 4 | gn can only run python scripts. This launches a subprocess Node process. 5 | The working dir of this program is out/Debug/ (AKA root_build_dir) 6 | Before running node, we symlink js/node_modules to out/Debug/node_modules. 7 | """ 8 | import subprocess 9 | import sys 10 | import os 11 | from util import remove_and_symlink, root_path, run 12 | 13 | tools_path = os.path.join(root_path, "tools") 14 | third_party_path = os.path.join(root_path, "third_party") 15 | target_abs = os.path.join(third_party_path, "node_modules") 16 | target_rel = os.path.relpath(target_abs) 17 | 18 | remove_and_symlink(target_rel, "node_modules", True) 19 | run(["node"] + sys.argv[1:], quiet=True) 20 | -------------------------------------------------------------------------------- /tests/error_006_import_ext_failure.ts.out: -------------------------------------------------------------------------------- 1 | Compiling [WILDCARD]tests/error_006_import_ext_failure.ts 2 | Uncaught NotFound: Cannot resolve module "./non-existent" from "[WILDCARD]/tests/error_006_import_ext_failure.ts" 3 | at DenoError ([WILDCARD]/js/errors.ts:[WILDCARD]) 4 | at maybeError ([WILDCARD]/js/errors.ts:[WILDCARD]) 5 | at maybeThrowError ([WILDCARD]/js/errors.ts:[WILDCARD]) 6 | at sendSync ([WILDCARD]/js/dispatch.ts:[WILDCARD]) 7 | at fetchModuleMetaData ([WILDCARD]/js/os.ts:[WILDCARD]) 8 | at _resolveModule ([WILDCARD]/js/compiler.ts:[WILDCARD]) 9 | at resolveModuleNames ([WILDCARD]/js/compiler.ts:[WILDCARD]) 10 | at compilerHost.resolveModuleNames ([WILDCARD]) 11 | at resolveModuleNamesWorker ([WILDCARD]) 12 | at resolveModuleNamesReusingOldState ([WILDCARD]typescript.js:[WILDCARD]) 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "allowUnreachableCode": false, 5 | "baseUrl": ".", 6 | "checkJs": true, 7 | "module": "esnext", 8 | "moduleResolution": "node", 9 | "noImplicitReturns": true, 10 | "noFallthroughCasesInSwitch": true, 11 | "noLib": true, 12 | "noUnusedLocals": true, 13 | "paths": { 14 | "*": ["*", "target/debug/*", "target/release/*"] 15 | }, 16 | "preserveConstEnums": true, 17 | "pretty": true, 18 | "removeComments": true, 19 | "resolveJsonModule": true, 20 | "sourceMap": true, 21 | "strict": true, 22 | "target": "esnext", 23 | "types": [] 24 | }, 25 | "files": [ 26 | "node_modules/typescript/lib/lib.esnext.d.ts", 27 | "js/lib.web_assembly.d.ts", 28 | "js/main.ts", 29 | "js/compiler.ts" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /tests/error_004_missing_module.ts.out: -------------------------------------------------------------------------------- 1 | Compiling [WILDCARD]tests/error_004_missing_module.ts 2 | Uncaught NotFound: Cannot resolve module "bad-module.ts" from "[WILDCARD]/tests/error_004_missing_module.ts" 3 | at DenoError ([WILDCARD]/js/errors.ts:[WILDCARD]) 4 | at maybeError ([WILDCARD]/js/errors.ts:[WILDCARD]) 5 | at maybeThrowError ([WILDCARD]/js/errors.ts:[WILDCARD]) 6 | at sendSync ([WILDCARD]/js/dispatch.ts:[WILDCARD]) 7 | at fetchModuleMetaData ([WILDCARD]/js/os.ts:[WILDCARD]) 8 | at _resolveModule ([WILDCARD]/js/compiler.ts:[WILDCARD]) 9 | at resolveModuleNames ([WILDCARD]/js/compiler.ts:[WILDCARD]) 10 | at compilerHost.resolveModuleNames ([WILDCARD]typescript.js:[WILDCARD]) 11 | at resolveModuleNamesWorker ([WILDCARD]typescript.js:[WILDCARD]) 12 | at resolveModuleNamesReusingOldState ([WILDCARD]typescript.js:[WILDCARD]) 13 | -------------------------------------------------------------------------------- /libdeno/exceptions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #ifndef EXCEPTIONS_H_ 3 | #define EXCEPTIONS_H_ 4 | 5 | #include 6 | #include "third_party/v8/include/v8.h" 7 | 8 | namespace deno { 9 | 10 | v8::Local EncodeExceptionAsObject(v8::Local context, 11 | v8::Local exception); 12 | 13 | std::string EncodeExceptionAsJSON(v8::Local context, 14 | v8::Local exception); 15 | 16 | void HandleException(v8::Local context, 17 | v8::Local exception); 18 | 19 | void HandleExceptionMessage(v8::Local context, 20 | v8::Local message); 21 | } // namespace deno 22 | 23 | #endif // EXCEPTIONS_H_ 24 | -------------------------------------------------------------------------------- /tools/permission_prompt_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | const { args, listen, env, exit, makeTempDirSync, readFile, run } = Deno; 3 | 4 | const name = args[1]; 5 | const test = { 6 | needsRead: () => { 7 | readFile("package.json"); 8 | }, 9 | needsWrite: () => { 10 | makeTempDirSync(); 11 | }, 12 | needsEnv: () => { 13 | env().home; 14 | }, 15 | needsNet: () => { 16 | listen("tcp", "127.0.0.1:4540"); 17 | }, 18 | needsRun: async () => { 19 | const process = run({ 20 | args: [ 21 | "python", 22 | "-c", 23 | "import sys; sys.stdout.write('hello'); sys.stdout.flush()" 24 | ] 25 | }); 26 | await process.status(); 27 | } 28 | }[name]; 29 | 30 | if (!test) { 31 | console.log("Unknown test:", name); 32 | exit(1); 33 | } 34 | 35 | test(); 36 | -------------------------------------------------------------------------------- /core/BUILD.gn: -------------------------------------------------------------------------------- 1 | import("//build_extra/rust/rust.gni") 2 | 3 | # deno_core does not depend on flatbuffers nor tokio. 4 | main_extern = [ 5 | "$rust_build:futures", 6 | "$rust_build:libc", 7 | "$rust_build:serde_json", 8 | "$rust_build:log", 9 | ] 10 | 11 | rust_crate("deno_core") { 12 | source_root = "lib.rs" 13 | extern = main_extern 14 | deps = [ 15 | "../libdeno:libdeno_static_lib", 16 | ] 17 | } 18 | 19 | rust_test("deno_core_test") { 20 | source_root = "lib.rs" 21 | extern = main_extern 22 | deps = [ 23 | "../libdeno:libdeno_static_lib", 24 | ] 25 | } 26 | 27 | rust_executable("deno_core_http_bench") { 28 | source_root = "http_bench.rs" 29 | extern = [ 30 | "$rust_build:futures", 31 | "$rust_build:lazy_static", 32 | "$rust_build:libc", 33 | "$rust_build:log", 34 | "$rust_build:tokio", 35 | ":deno_core" 36 | ] 37 | } 38 | -------------------------------------------------------------------------------- /tools/build.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | from __future__ import print_function 4 | import os 5 | import sys 6 | import third_party 7 | from util import build_path, enable_ansi_colors, run 8 | 9 | 10 | def main(argv): 11 | enable_ansi_colors() 12 | 13 | third_party.fix_symlinks() 14 | 15 | ninja_args = argv[1:] 16 | if not "-C" in ninja_args: 17 | if not os.path.isdir(build_path()): 18 | print("Build directory '%s' does not exist." % build_path(), 19 | "Run tools/setup.py") 20 | sys.exit(1) 21 | ninja_args = ["-C", build_path()] + ninja_args 22 | 23 | run([third_party.ninja_path] + ninja_args, 24 | env=third_party.google_env(), 25 | quiet=True) 26 | 27 | 28 | if __name__ == '__main__': 29 | sys.exit(main(sys.argv)) 30 | -------------------------------------------------------------------------------- /js/globals_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert } from "./test_util.ts"; 3 | 4 | test(function globalThisExists() { 5 | assert(globalThis != null); 6 | }); 7 | 8 | test(function windowExists() { 9 | assert(window != null); 10 | }); 11 | 12 | test(function windowWindowExists() { 13 | assert(window.window === window); 14 | }); 15 | 16 | test(function globalThisEqualsWindow() { 17 | assert(globalThis === window); 18 | }); 19 | 20 | test(function DenoNamespaceExists() { 21 | assert(Deno != null); 22 | }); 23 | 24 | test(function DenoNamespaceEqualsWindowDeno() { 25 | assert(Deno === window.Deno); 26 | }); 27 | 28 | test(function DenoNamespaceIsFrozen() { 29 | assert(Object.isFrozen(Deno)); 30 | }); 31 | 32 | test(function webAssemblyExists() { 33 | assert(typeof WebAssembly.compile === "function"); 34 | }); 35 | -------------------------------------------------------------------------------- /js/dom_file.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as domTypes from "./dom_types"; 3 | import * as blob from "./blob"; 4 | 5 | // TODO Rename this to DomFileImpl 6 | export class DenoFile extends blob.DenoBlob implements domTypes.DomFile { 7 | lastModified: number; 8 | name: string; 9 | 10 | constructor( 11 | fileBits: domTypes.BlobPart[], 12 | fileName: string, 13 | options?: domTypes.FilePropertyBag 14 | ) { 15 | options = options || {}; 16 | super(fileBits, options); 17 | 18 | // 4.1.2.1 Replace any "/" character (U+002F SOLIDUS) 19 | // with a ":" (U + 003A COLON) 20 | this.name = String(fileName).replace(/\u002F/g, "\u003A"); 21 | // 4.1.3.3 If lastModified is not provided, set lastModified to the current 22 | // date and time represented in number of milliseconds since the Unix Epoch. 23 | this.lastModified = options.lastModified || Date.now(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /js/os_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ env: true }, function envSuccess() { 5 | const env = Deno.env(); 6 | assert(env !== null); 7 | env.test_var = "Hello World"; 8 | const newEnv = Deno.env(); 9 | assertEqual(env.test_var, newEnv.test_var); 10 | }); 11 | 12 | test(function envFailure() { 13 | let caughtError = false; 14 | try { 15 | const env = Deno.env(); 16 | } catch (err) { 17 | caughtError = true; 18 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 19 | assertEqual(err.name, "PermissionDenied"); 20 | } 21 | 22 | assert(caughtError); 23 | }); 24 | 25 | test(function osPid() { 26 | console.log("pid", Deno.pid); 27 | assert(Deno.pid > 0); 28 | }); 29 | 30 | // See complete tests in tools/is_tty_test.py 31 | test(function osIsTTYSmoke() { 32 | console.log(Deno.isTTY()); 33 | }); 34 | -------------------------------------------------------------------------------- /tools/prefetch_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import os 4 | import sys 5 | from util import mkdtemp, tests_path, run_output, green_ok 6 | import shutil 7 | 8 | 9 | def prefetch_test(deno_exe): 10 | sys.stdout.write("prefetch_test...") 11 | sys.stdout.flush() 12 | 13 | deno_dir = mkdtemp() 14 | try: 15 | t = os.path.join(tests_path, "006_url_imports.ts") 16 | output = run_output([deno_exe, "--prefetch", t], 17 | merge_env={"DENO_DIR": deno_dir}) 18 | assert output == "" 19 | # Check that we actually did the prefetch. 20 | os.path.exists( 21 | os.path.join(deno_dir, 22 | "deps/http/localhost_PORT4545/tests/subdir/mod2.ts")) 23 | finally: 24 | shutil.rmtree(deno_dir) 25 | 26 | print green_ok() 27 | 28 | 29 | if __name__ == "__main__": 30 | prefetch_test(sys.argv[1]) 31 | -------------------------------------------------------------------------------- /src/snapshot.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | use crate::libdeno::deno_buf; 3 | 4 | pub fn deno_snapshot() -> deno_buf { 5 | #[cfg(not(feature = "check-only"))] 6 | let data = 7 | include_bytes!(concat!(env!("GN_OUT_DIR"), "/gen/snapshot_deno.bin")); 8 | // The snapshot blob is not available when the Rust Language Server runs 9 | // 'cargo check'. 10 | #[cfg(feature = "check-only")] 11 | let data = vec![]; 12 | 13 | unsafe { deno_buf::from_raw_parts(data.as_ptr(), data.len()) } 14 | } 15 | 16 | pub fn compiler_snapshot() -> deno_buf { 17 | #[cfg(not(feature = "check-only"))] 18 | let data = 19 | include_bytes!(concat!(env!("GN_OUT_DIR"), "/gen/snapshot_compiler.bin")); 20 | // The snapshot blob is not available when the Rust Language Server runs 21 | // 'cargo check'. 22 | #[cfg(feature = "check-only")] 23 | let data = vec![]; 24 | 25 | unsafe { deno_buf::from_raw_parts(data.as_ptr(), data.len()) } 26 | } 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deno", 3 | "devDependencies": { 4 | "@types/base64-js": "^1.2.5", 5 | "@types/flatbuffers": "^1.9.0", 6 | "@types/prettier": "=1.15.3", 7 | "@types/text-encoding": "0.0.33", 8 | "base64-js": "^1.3.0", 9 | "flatbuffers": "^1.9.0", 10 | "magic-string": "^0.22.5", 11 | "prettier": "=1.15.3", 12 | "rollup": "0.67.0", 13 | "rollup-plugin-alias": "^1.4.0", 14 | "rollup-plugin-analyzer": "^2.1.0", 15 | "rollup-plugin-commonjs": "^9.1.3", 16 | "rollup-plugin-node-globals": "^1.2.1", 17 | "rollup-plugin-node-resolve": "^3.3.0", 18 | "rollup-plugin-replace": "^2.1.0", 19 | "rollup-plugin-string": "^2.0.2", 20 | "rollup-plugin-typescript2": "^0.16.1", 21 | "rollup-pluginutils": "^2.3.0", 22 | "ts-node": "^7.0.1", 23 | "ts-simple-ast": "17.1.0", 24 | "tslint": "^5.10.0", 25 | "tslint-eslint-rules": "^5.3.1", 26 | "tslint-no-circular-imports": "^0.5.0", 27 | "typescript": "3.2.1" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /js/format_error.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import { sendSync } from "./dispatch"; 5 | import { assert } from "./util"; 6 | 7 | export function formatError(errString: string): string { 8 | const builder = flatbuffers.createBuilder(); 9 | const errString_ = builder.createString(errString); 10 | msg.FormatError.startFormatError(builder); 11 | msg.FormatError.addError(builder, errString_); 12 | const offset = msg.FormatError.endFormatError(builder); 13 | const baseRes = sendSync(builder, msg.Any.FormatError, offset); 14 | assert(baseRes != null); 15 | assert(msg.Any.FormatErrorRes === baseRes!.innerType()); 16 | const formatErrorResMsg = new msg.FormatErrorRes(); 17 | assert(baseRes!.inner(formatErrorResMsg) != null); 18 | const formattedError = formatErrorResMsg.error(); 19 | assert(formatError != null); 20 | return formattedError!; 21 | } 22 | -------------------------------------------------------------------------------- /js/performance.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import { sendSync } from "./dispatch"; 4 | import * as flatbuffers from "./flatbuffers"; 5 | import { assert } from "./util"; 6 | 7 | export class Performance { 8 | timeOrigin = 0; 9 | 10 | constructor() { 11 | this.timeOrigin = new Date().getTime(); 12 | } 13 | 14 | /** Returns a current time from Deno's start 15 | * 16 | * const t = performance.now(); 17 | * console.log(`${t} ms since start!`); 18 | */ 19 | now(): number { 20 | const builder = flatbuffers.createBuilder(); 21 | msg.Now.startNow(builder); 22 | const inner = msg.Now.endNow(builder); 23 | const baseRes = sendSync(builder, msg.Any.Now, inner)!; 24 | assert(msg.Any.NowRes === baseRes.innerType()); 25 | const res = new msg.NowRes(); 26 | assert(baseRes.inner(res) != null); 27 | return res.time().toFloat64() - this.timeOrigin; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tests/http_bench.ts: -------------------------------------------------------------------------------- 1 | // Used for benchmarking Deno's networking. See tools/http_benchmark.py 2 | // TODO Replace this with a real HTTP server once 3 | // https://github.com/denoland/deno/issues/726 is completed. 4 | // Note: this is a keep-alive server. 5 | const addr = Deno.args[1] || "127.0.0.1:4500"; 6 | const listener = Deno.listen("tcp", addr); 7 | const response = new TextEncoder().encode( 8 | "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" 9 | ); 10 | 11 | async function handle(conn: Deno.Conn): Promise { 12 | const buffer = new Uint8Array(1024); 13 | try { 14 | while (true) { 15 | const r = await conn.read(buffer); 16 | if (r.eof) { 17 | break; 18 | } 19 | await conn.write(response); 20 | } 21 | } finally { 22 | conn.close(); 23 | } 24 | } 25 | 26 | async function main(): Promise { 27 | console.log("Listening on", addr); 28 | while (true) { 29 | const conn = await listener.accept(); 30 | handle(conn); 31 | } 32 | } 33 | 34 | main(); 35 | -------------------------------------------------------------------------------- /tools/docs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import os 4 | import tempfile 5 | from util import run, root_path 6 | 7 | target_path = os.path.join(root_path, "target/") 8 | 9 | os.chdir(root_path) 10 | 11 | # Builds into target/doc 12 | run(["cargo", "doc", "--no-deps", "-vv"]) 13 | 14 | # 'deno --types' is stored in target/debug/gen/lib/lib.deno_runtime.d.ts 15 | # We want to run typedoc on that declaration file only. 16 | os.chdir(os.path.join(target_path, "debug/gen/lib/")) 17 | 18 | # You must have typedoc installed seprately. 19 | # TODO Replace typedoc with something else ASAP. It's very awful. 20 | run([ 21 | "typedoc", "lib.deno_runtime.d.ts", "--out", 22 | os.path.join(target_path, "typedoc"), "--entryPoint", "\"deno\"", 23 | "--ignoreCompilerErrors", "--includeDeclarations", "--excludeExternals", 24 | "--excludePrivate", "--excludeProtected", "--mode", "file", "--name", 25 | "deno", "--theme", "minimal", "--readme", "none" 26 | ]) 27 | -------------------------------------------------------------------------------- /libdeno/test.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #include "test.h" 3 | #include 4 | #include "file_util.h" 5 | 6 | deno_buf snapshot = {nullptr, 0, nullptr, 0, 0}; 7 | 8 | int main(int argc, char** argv) { 9 | // Locate the snapshot. 10 | std::string exe_path; 11 | if (!deno::ExePath(&exe_path)) { 12 | std::cerr << "deno::ExePath() failed" << std::endl; 13 | return 1; 14 | } 15 | std::string snapshot_path = deno::Dirname(exe_path) + SNAPSHOT_PATH; 16 | 17 | // Load the snapshot. 18 | std::string contents; 19 | if (!deno::ReadFileToString(snapshot_path.c_str(), &contents)) { 20 | std::cerr << "Failed to read snapshot from " << snapshot_path << std::endl; 21 | return 1; 22 | } 23 | snapshot.data_ptr = 24 | reinterpret_cast(const_cast(contents.c_str())); 25 | snapshot.data_len = contents.size(); 26 | 27 | testing::InitGoogleTest(&argc, argv); 28 | deno_init(); 29 | deno_set_v8_flags(&argc, argv); 30 | return RUN_ALL_TESTS(); 31 | } 32 | -------------------------------------------------------------------------------- /src/msg.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #![allow(unused_imports)] 3 | #![allow(dead_code)] 4 | #![cfg_attr( 5 | feature = "cargo-clippy", 6 | allow(clippy::all, clippy::pedantic) 7 | )] 8 | use flatbuffers; 9 | use std::sync::atomic::Ordering; 10 | 11 | // GN_OUT_DIR is set either by build.rs (for the Cargo build), or by 12 | // build_extra/rust/run.py (for the GN+Ninja build). 13 | include!(concat!(env!("GN_OUT_DIR"), "/gen/msg_generated.rs")); 14 | 15 | impl<'a> From<&'a super::isolate::Metrics> for MetricsResArgs { 16 | fn from(m: &'a super::isolate::Metrics) -> Self { 17 | MetricsResArgs { 18 | ops_dispatched: m.ops_dispatched.load(Ordering::SeqCst) as u64, 19 | ops_completed: m.ops_completed.load(Ordering::SeqCst) as u64, 20 | bytes_sent_control: m.bytes_sent_control.load(Ordering::SeqCst) as u64, 21 | bytes_sent_data: m.bytes_sent_data.load(Ordering::SeqCst) as u64, 22 | bytes_received: m.bytes_received.load(Ordering::SeqCst) as u64, 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tools/lint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | # Does google-lint on c++ files and ts-lint on typescript files 4 | 5 | import os 6 | import sys 7 | from util import enable_ansi_colors, find_exts, root_path, run 8 | 9 | enable_ansi_colors() 10 | 11 | third_party_path = os.path.join(root_path, "third_party") 12 | cpplint = os.path.join(third_party_path, "cpplint", "cpplint.py") 13 | tslint = os.path.join(third_party_path, "node_modules", "tslint", "bin", 14 | "tslint") 15 | 16 | os.chdir(root_path) 17 | run([ 18 | "python", cpplint, "--filter=-build/include_subdir", 19 | "--repository=libdeno", "--extensions=cc,h", "--recursive", "libdeno" 20 | ]) 21 | 22 | run(["node", tslint, "-p", ".", "--exclude", "**/gen/**/*.ts"]) 23 | run([ 24 | "node", tslint, "./js/**/*_test.ts", "./tests/**/*.ts", "./core/*.js", 25 | "--exclude", "**/gen/**/*.ts", "--project", "tsconfig.json" 26 | ]) 27 | 28 | run([sys.executable, "third_party/depot_tools/pylint.py"] + 29 | find_exts(["tools", "build_extra"], [".py"], skip=["tools/clang"])) 30 | -------------------------------------------------------------------------------- /js/resources.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import { assert } from "./util"; 5 | import * as dispatch from "./dispatch"; 6 | 7 | export type ResourceMap = { [rid: number]: string }; 8 | 9 | /** Returns a map of open _file like_ resource ids along with their string 10 | * representation. 11 | */ 12 | export function resources(): ResourceMap { 13 | const builder = flatbuffers.createBuilder(); 14 | msg.Resources.startResources(builder); 15 | const inner = msg.Resource.endResource(builder); 16 | const baseRes = dispatch.sendSync(builder, msg.Any.Resources, inner); 17 | assert(baseRes !== null); 18 | assert(msg.Any.ResourcesRes === baseRes!.innerType()); 19 | const res = new msg.ResourcesRes(); 20 | assert(baseRes!.inner(res) !== null); 21 | 22 | const resources = {} as ResourceMap; 23 | 24 | for (let i = 0; i < res.resourcesLength(); i++) { 25 | const item = res.resources(i)!; 26 | resources[item.rid()!] = item.repr()!; 27 | } 28 | 29 | return resources; 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018-2019 the Deno authors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /js/blob_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert, assertEqual } from "./test_util.ts"; 3 | 4 | test(function blobString() { 5 | const b1 = new Blob(["Hello World"]); 6 | const str = "Test"; 7 | const b2 = new Blob([b1, str]); 8 | assertEqual(b2.size, b1.size + str.length); 9 | }); 10 | 11 | test(function blobBuffer() { 12 | const buffer = new ArrayBuffer(12); 13 | const u8 = new Uint8Array(buffer); 14 | const f1 = new Float32Array(buffer); 15 | const b1 = new Blob([buffer, u8]); 16 | assertEqual(b1.size, 2 * u8.length); 17 | const b2 = new Blob([b1, f1]); 18 | assertEqual(b2.size, 3 * u8.length); 19 | }); 20 | 21 | test(function blobSlice() { 22 | const blob = new Blob(["Deno", "Foo"]); 23 | const b1 = blob.slice(0, 3, "Text/HTML"); 24 | assert(b1 instanceof Blob); 25 | assertEqual(b1.size, 3); 26 | assertEqual(b1.type, "text/html"); 27 | const b2 = blob.slice(-1, 3); 28 | assertEqual(b2.size, 0); 29 | const b3 = blob.slice(100, 3); 30 | assertEqual(b3.size, 0); 31 | const b4 = blob.slice(0, 10); 32 | assertEqual(b4.size, blob.size); 33 | }); 34 | 35 | // TODO(qti3e) Test the stored data in a Blob after implementing FileReader API. 36 | -------------------------------------------------------------------------------- /js/chmod.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | /** Changes the permission of a specific file/directory of specified path 7 | * synchronously. 8 | * 9 | * Deno.chmodSync("/path/to/file", 0o666); 10 | */ 11 | export function chmodSync(path: string, mode: number): void { 12 | dispatch.sendSync(...req(path, mode)); 13 | } 14 | 15 | /** Changes the permission of a specific file/directory of specified path. 16 | * 17 | * await Deno.chmod("/path/to/file", 0o666); 18 | */ 19 | export async function chmod(path: string, mode: number): Promise { 20 | await dispatch.sendAsync(...req(path, mode)); 21 | } 22 | 23 | function req( 24 | path: string, 25 | mode: number 26 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 27 | const builder = flatbuffers.createBuilder(); 28 | const path_ = builder.createString(path); 29 | msg.Chmod.startChmod(builder); 30 | msg.Chmod.addPath(builder, path_); 31 | msg.Chmod.addMode(builder, mode); 32 | const inner = msg.Chmod.endChmod(builder); 33 | return [builder, msg.Any.Chmod, inner]; 34 | } 35 | -------------------------------------------------------------------------------- /tools/fmt_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import os 4 | import sys 5 | from util import mkdtemp, root_path, tests_path, run, green_ok 6 | import shutil 7 | 8 | 9 | def fmt_test(deno_exe): 10 | sys.stdout.write("fmt_test...") 11 | sys.stdout.flush() 12 | d = mkdtemp() 13 | try: 14 | fixed_filename = os.path.join(tests_path, "badly_formatted_fixed.js") 15 | src = os.path.join(tests_path, "badly_formatted.js") 16 | dst = os.path.join(d, "badly_formatted.js") 17 | shutil.copyfile(src, dst) 18 | # Set DENO_DIR to //js/ so we don't have to rely on an intenet 19 | # connection to download https://deno.land/x/std/prettier/main.ts 20 | deno_dir = os.path.join(root_path, "js") 21 | run([deno_exe, dst, "--fmt", "--allow-read"], 22 | merge_env={"DENO_DIR": deno_dir}) 23 | with open(fixed_filename) as f: 24 | expected = f.read() 25 | with open(dst) as f: 26 | actual = f.read() 27 | assert expected == actual 28 | finally: 29 | shutil.rmtree(d) 30 | print green_ok() 31 | 32 | 33 | if __name__ == "__main__": 34 | fmt_test(sys.argv[1]) 35 | -------------------------------------------------------------------------------- /tests/019_media_types.ts: -------------------------------------------------------------------------------- 1 | // When run against the test HTTP server, it will serve different media types 2 | // based on the URL containing `.t#.` strings, which exercises the different 3 | // mapping of media types end to end. 4 | 5 | // tslint:disable:max-line-length 6 | import { loaded as loadedTs1 } from "http://localhost:4545/tests/subdir/mt_text_typescript.t1.ts"; 7 | import { loaded as loadedTs2 } from "http://localhost:4545/tests/subdir/mt_video_vdn.t2.ts"; 8 | import { loaded as loadedTs3 } from "http://localhost:4545/tests/subdir/mt_video_mp2t.t3.ts"; 9 | import { loaded as loadedTs4 } from "http://localhost:4545/tests/subdir/mt_application_x_typescript.t4.ts"; 10 | import { loaded as loadedJs1 } from "http://localhost:4545/tests/subdir/mt_text_javascript.j1.js"; 11 | import { loaded as loadedJs2 } from "http://localhost:4545/tests/subdir/mt_application_ecmascript.j2.js"; 12 | import { loaded as loadedJs3 } from "http://localhost:4545/tests/subdir/mt_text_ecmascript.j3.js"; 13 | import { loaded as loadedJs4 } from "http://localhost:4545/tests/subdir/mt_application_x_javascript.j4.js"; 14 | 15 | console.log( 16 | "success", 17 | loadedTs1, 18 | loadedTs2, 19 | loadedTs3, 20 | loadedTs4, 21 | loadedJs1, 22 | loadedJs2, 23 | loadedJs3, 24 | loadedJs4 25 | ); 26 | -------------------------------------------------------------------------------- /tools/prebuilt.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import sys 3 | import os 4 | from util import run, root_path 5 | from third_party import tp, google_env 6 | 7 | 8 | def download_prebuilt(sha1_file): 9 | run([ 10 | "python", 11 | tp('depot_tools/download_from_google_storage.py'), 12 | '--platform=' + sys.platform, 13 | '--no_auth', 14 | '--bucket=denoland', 15 | '--sha1_file', 16 | sha1_file, 17 | ], 18 | env=google_env()) 19 | 20 | 21 | def load_sccache(): 22 | if sys.platform == 'win32': 23 | p = "prebuilt/win/sccache.exe" 24 | elif sys.platform.startswith('linux'): 25 | p = "prebuilt/linux64/sccache" 26 | elif sys.platform == 'darwin': 27 | p = "prebuilt/mac/sccache" 28 | download_prebuilt(p + ".sha1") 29 | return os.path.join(root_path, p) 30 | 31 | 32 | def load_hyperfine(): 33 | if sys.platform == 'win32': 34 | p = "prebuilt/win/hyperfine.exe" 35 | elif sys.platform.startswith('linux'): 36 | p = "prebuilt/linux64/hyperfine" 37 | elif sys.platform == 'darwin': 38 | p = "prebuilt/mac/hyperfine" 39 | download_prebuilt(p + ".sha1") 40 | return os.path.join(root_path, p) 41 | -------------------------------------------------------------------------------- /js/errors.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { Base, ErrorKind } from "gen/msg_generated"; 3 | export { ErrorKind } from "gen/msg_generated"; 4 | 5 | /** A Deno specific error. The `kind` property is set to a specific error code 6 | * which can be used to in application logic. 7 | * 8 | * try { 9 | * somethingThatMightThrow(); 10 | * } catch (e) { 11 | * if ( 12 | * e instanceof Deno.DenoError && 13 | * e.kind === Deno.ErrorKind.Overflow 14 | * ) { 15 | * console.error("Overflow error!"); 16 | * } 17 | * } 18 | * 19 | */ 20 | export class DenoError extends Error { 21 | constructor(readonly kind: T, msg: string) { 22 | super(msg); 23 | this.name = ErrorKind[kind]; 24 | } 25 | } 26 | 27 | // @internal 28 | export function maybeThrowError(base: Base): void { 29 | const err = maybeError(base); 30 | if (err != null) { 31 | throw err; 32 | } 33 | } 34 | 35 | // @internal 36 | export function maybeError(base: Base): null | DenoError { 37 | const kind = base.errorKind(); 38 | if (kind === ErrorKind.NoError) { 39 | return null; 40 | } else { 41 | return new DenoError(kind, base.error()!); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tools/hyper_hello.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | // Adapted from https://github.com/hyperium/hyper/blob/master/examples/hello.rs 3 | 4 | #![deny(warnings)] 5 | extern crate hyper; 6 | 7 | use std::env; 8 | use hyper::{Body, Response, Server}; 9 | use hyper::service::service_fn_ok; 10 | use hyper::rt::{self, Future}; 11 | 12 | static PHRASE: &'static [u8] = b"Hello World!"; 13 | 14 | fn main() { 15 | let mut port: u16 = 4544; 16 | if let Some(custom_port) = env::args().nth(1) { 17 | port = custom_port.parse::().unwrap(); 18 | } 19 | 20 | let addr = ([127, 0, 0, 1], port).into(); 21 | 22 | // new_service is run for each connection, creating a 'service' 23 | // to handle requests for that specific connection. 24 | let new_service = || { 25 | // This is the `Service` that will handle the connection. 26 | // `service_fn_ok` is a helper to convert a function that 27 | // returns a Response into a `Service`. 28 | service_fn_ok(|_| { 29 | Response::new(Body::from(PHRASE)) 30 | }) 31 | }; 32 | 33 | let server = Server::bind(&addr) 34 | .serve(new_service) 35 | .map_err(|e| eprintln!("server error: {}", e)); 36 | 37 | println!("Listening on http://{}", addr); 38 | 39 | rt::run(server); 40 | } 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # deno 2 | 3 | | **Linux & Mac** | **Windows** | 4 | | :------------------------: | :------------------------: | 5 | | [![][tci badge]][tci link] | [![][avy badge]][avy link] | 6 | 7 | 8 | [avy badge]: https://ci.appveyor.com/api/projects/status/yel7wtcqwoy0to8x?branch=master&svg=true 9 | [avy link]: https://ci.appveyor.com/project/deno/deno 10 | [tci badge]: https://travis-ci.com/denoland/deno.svg?branch=master 11 | [tci link]: https://travis-ci.com/denoland/deno 12 | 13 | Deno is a browser-like command line program for executing JavaScript. 14 | 15 | Deno aims to provide a productive and secure scripting environment for the 16 | modern programmer. It is built on top of V8, Rust, and TypeScript. 17 | 18 | Please read the [introduction](https://deno.land/manual.html#introduction) for 19 | more specifics. 20 | 21 | [Website](https://deno.land/) 22 | 23 | [Manual](https://deno.land/manual.html) 24 | 25 | [Install](https://github.com/denoland/deno_install) 26 | 27 | [API Reference](https://deno.land/typedoc/) 28 | 29 | [Style Guide](https://deno.land/style_guide.html) 30 | 31 | [Module Repository](https://deno.land/x/) 32 | 33 | [Releases](Releases.md) 34 | 35 | [Chat](https://gitter.im/denolife/Lobby) 36 | 37 | [More links](https://github.com/denolib/awesome-deno) 38 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | # Dummy package info required by `cargo fetch`. 3 | # Use tools/sync_third_party.py to install deps after editing this file. 4 | # Deno does not build with cargo. Deno uses a build system called gn. 5 | # See build_extra/rust/BUILD.gn for the manually built configuration of rust 6 | # crates. 7 | 8 | [workspace] 9 | members = [ 10 | "./", 11 | "core", 12 | ] 13 | 14 | [package] 15 | name = "deno" 16 | version = "0.3.1" 17 | edition = "2018" 18 | 19 | [dependencies] 20 | deno_core = { path = "./core" } 21 | 22 | ansi_term = "0.11.0" 23 | atty = "0.2.11" 24 | dirs = "1.0.5" 25 | flatbuffers = "0.5.0" 26 | futures = "0.1.25" 27 | getopts = "0.2.18" 28 | http = "0.1.16" 29 | hyper = "0.12.24" 30 | hyper-rustls = "0.16.0" 31 | integer-atomics = "1.0.2" 32 | lazy_static = "1.3.0" 33 | libc = "0.2.49" 34 | log = "0.4.6" 35 | rand = "0.6.5" 36 | regex = "1.1.0" 37 | remove_dir_all = "0.5.1" 38 | ring = "0.14.6" 39 | rustyline = "3.0.0" 40 | serde_json = "1.0.38" 41 | source-map-mappings = "0.5.0" 42 | tempfile = "3.0.7" 43 | tokio = "0.1.15" 44 | tokio-executor = "0.1.6" 45 | tokio-fs = "0.1.5" 46 | tokio-io = "0.1.11" 47 | tokio-process = "0.2.3" 48 | tokio-threadpool = "0.1.11" 49 | url = "1.7.2" 50 | 51 | [target.'cfg(windows)'.dependencies] 52 | winapi = "0.3.6" 53 | -------------------------------------------------------------------------------- /js/truncate.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | /** Truncates or extends the specified file synchronously, updating the size of 7 | * this file to become size. 8 | * 9 | * Deno.truncateSync("hello.txt", 10); 10 | */ 11 | export function truncateSync(name: string, len?: number): void { 12 | dispatch.sendSync(...req(name, len)); 13 | } 14 | 15 | /** 16 | * Truncates or extends the specified file, updating the size of this file to 17 | * become size. 18 | * 19 | * await Deno.truncate("hello.txt", 10); 20 | */ 21 | export async function truncate(name: string, len?: number): Promise { 22 | await dispatch.sendAsync(...req(name, len)); 23 | } 24 | 25 | function req( 26 | name: string, 27 | len?: number 28 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 29 | const builder = flatbuffers.createBuilder(); 30 | const name_ = builder.createString(name); 31 | len = len && len > 0 ? Math.floor(len) : 0; 32 | msg.Truncate.startTruncate(builder); 33 | msg.Truncate.addName(builder, name_); 34 | msg.Truncate.addLen(builder, len); 35 | const inner = msg.Truncate.endTruncate(builder); 36 | return [builder, msg.Any.Truncate, inner]; 37 | } 38 | -------------------------------------------------------------------------------- /tools/ts_library_builder/main.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as path from "path"; 3 | import { main as buildRuntimeLib } from "./build_library"; 4 | 5 | // this is very simplistic argument parsing, just enough to integrate into 6 | // the build scripts, versus being very robust 7 | let basePath = process.cwd(); 8 | let buildPath = path.join(basePath, "out", "debug"); 9 | let outFile = path.join(buildPath, "gen", "lib", "lib.d.ts"); 10 | let inline: string[] = []; 11 | let debug = false; 12 | let silent = false; 13 | 14 | process.argv.forEach((arg, i, argv) => { 15 | // tslint:disable-next-line:switch-default 16 | switch (arg) { 17 | case "--basePath": 18 | basePath = path.resolve(argv[i + 1]); 19 | break; 20 | case "--buildPath": 21 | buildPath = path.resolve(argv[i + 1]); 22 | break; 23 | case "--inline": 24 | inline = argv[i + 1].split(",").map(filename => { 25 | return path.resolve(filename); 26 | }); 27 | break; 28 | case "--outFile": 29 | outFile = path.resolve(argv[i + 1]); 30 | break; 31 | case "--debug": 32 | debug = true; 33 | break; 34 | case "--silent": 35 | silent = true; 36 | break; 37 | } 38 | }); 39 | 40 | buildRuntimeLib({ 41 | basePath, 42 | buildPath, 43 | debug, 44 | inline, 45 | outFile, 46 | silent 47 | }); 48 | -------------------------------------------------------------------------------- /js/metrics.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import { assert } from "./util"; 5 | import * as dispatch from "./dispatch"; 6 | 7 | export interface Metrics { 8 | opsDispatched: number; 9 | opsCompleted: number; 10 | bytesSentControl: number; 11 | bytesSentData: number; 12 | bytesReceived: number; 13 | } 14 | 15 | /** Receive metrics from the privileged side of Deno. */ 16 | export function metrics(): Metrics { 17 | return res(dispatch.sendSync(...req())); 18 | } 19 | 20 | function req(): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 21 | const builder = flatbuffers.createBuilder(); 22 | msg.Metrics.startMetrics(builder); 23 | const inner = msg.Metrics.endMetrics(builder); 24 | return [builder, msg.Any.Metrics, inner]; 25 | } 26 | 27 | function res(baseRes: null | msg.Base): Metrics { 28 | assert(baseRes !== null); 29 | assert(msg.Any.MetricsRes === baseRes!.innerType()); 30 | const res = new msg.MetricsRes(); 31 | assert(baseRes!.inner(res) !== null); 32 | 33 | return { 34 | opsDispatched: res.opsDispatched().toFloat64(), 35 | opsCompleted: res.opsCompleted().toFloat64(), 36 | bytesSentControl: res.bytesSentControl().toFloat64(), 37 | bytesSentData: res.bytesSentData().toFloat64(), 38 | bytesReceived: res.bytesReceived().toFloat64() 39 | }; 40 | } 41 | -------------------------------------------------------------------------------- /js/location.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { URL } from "./url"; 3 | import { notImplemented } from "./util"; 4 | import { Location } from "./dom_types"; 5 | import { window } from "./window"; 6 | 7 | export function setLocation(url: string): void { 8 | window.location = new LocationImpl(url); 9 | Object.freeze(window.location); 10 | } 11 | 12 | export class LocationImpl implements Location { 13 | constructor(url: string) { 14 | const u = new URL(url); 15 | this.url = u; 16 | this.hash = u.hash; 17 | this.host = u.host; 18 | this.href = u.href; 19 | this.hostname = u.hostname; 20 | this.origin = u.protocol + "//" + u.host; 21 | this.pathname = u.pathname; 22 | this.protocol = u.protocol; 23 | this.port = u.port; 24 | this.search = u.search; 25 | } 26 | 27 | private url: URL; 28 | 29 | toString(): string { 30 | return this.url.toString(); 31 | } 32 | 33 | readonly ancestorOrigins: string[] = []; 34 | hash: string; 35 | host: string; 36 | hostname: string; 37 | href: string; 38 | readonly origin: string; 39 | pathname: string; 40 | port: string; 41 | protocol: string; 42 | search: string; 43 | assign(url: string): void { 44 | throw notImplemented(); 45 | } 46 | reload(): void { 47 | throw notImplemented(); 48 | } 49 | replace(url: string): void { 50 | throw notImplemented(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | # Integration Tests 2 | 3 | This path contains integration tests. When the integration tests are run, the 4 | test harness will execute tests which are defined in a `.test` file and located 5 | in the base of this path. 6 | 7 | A `.test` file is a simple configuration format where each option is specified 8 | on a single line. The key is the string to the left of the `:` deliminator and 9 | the value is the string to the right. 10 | 11 | | Key | Required | Description | 12 | | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 13 | | `args` | Yes | Specifies the command line arguments for the test. This should typically be input script for the test and a `--reload` to help ensure Deno doesn't leverage the cache. | 14 | | `output` | Yes | This is a text file which represents the output of the command. The string `[WILDCARD]` can be used in the output to specify ranges of text which any output is accepted. | 15 | | `exit_code` | No | If not present, it is assumed the script would exit normally (`0`). If specified, the harness will ensure the proper code is received. | 16 | -------------------------------------------------------------------------------- /js/dir.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import { assert } from "./util"; 4 | import * as flatbuffers from "./flatbuffers"; 5 | import { sendSync } from "./dispatch"; 6 | 7 | /** 8 | * cwd() Return a string representing the current working directory. 9 | * If the current directory can be reached via multiple paths 10 | * (due to symbolic links), cwd() may return 11 | * any one of them. 12 | * throws NotFound exception if directory not available 13 | */ 14 | export function cwd(): string { 15 | const builder = flatbuffers.createBuilder(); 16 | msg.Cwd.startCwd(builder); 17 | const inner = msg.Cwd.endCwd(builder); 18 | const baseRes = sendSync(builder, msg.Any.Cwd, inner); 19 | assert(baseRes != null); 20 | assert(msg.Any.CwdRes === baseRes!.innerType()); 21 | const res = new msg.CwdRes(); 22 | assert(baseRes!.inner(res) != null); 23 | return res.cwd()!; 24 | } 25 | 26 | /** 27 | * chdir() Change the current working directory to path. 28 | * throws NotFound exception if directory not available 29 | */ 30 | export function chdir(directory: string): void { 31 | const builder = flatbuffers.createBuilder(); 32 | const directory_ = builder.createString(directory); 33 | msg.Chdir.startChdir(builder); 34 | msg.Chdir.addDirectory(builder, directory_); 35 | const inner = msg.Chdir.endChdir(builder); 36 | sendSync(builder, msg.Any.Chdir, inner); 37 | } 38 | -------------------------------------------------------------------------------- /libdeno/snapshot_creator.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | // Hint: --trace_serializer is a useful debugging flag. 3 | #include 4 | #include 5 | #include "deno.h" 6 | #include "file_util.h" 7 | #include "internal.h" 8 | #include "third_party/v8/include/v8.h" 9 | #include "third_party/v8/src/base/logging.h" 10 | 11 | namespace deno {} // namespace deno 12 | 13 | int main(int argc, char** argv) { 14 | const char* snapshot_out_bin = argv[1]; 15 | const char* js_fn = argv[2]; 16 | 17 | deno_set_v8_flags(&argc, argv); 18 | 19 | CHECK_NOT_NULL(js_fn); 20 | CHECK_NOT_NULL(snapshot_out_bin); 21 | 22 | std::string js_source; 23 | CHECK(deno::ReadFileToString(js_fn, &js_source)); 24 | 25 | deno_init(); 26 | deno_config config = {1, deno::empty_buf, deno::empty_buf, nullptr}; 27 | Deno* d = deno_new(config); 28 | 29 | deno_execute(d, nullptr, js_fn, js_source.c_str()); 30 | if (deno_last_exception(d) != nullptr) { 31 | std::cerr << "Snapshot Exception " << std::endl; 32 | std::cerr << deno_last_exception(d) << std::endl; 33 | deno_delete(d); 34 | return 1; 35 | } 36 | 37 | auto snapshot = deno_get_snapshot(d); 38 | 39 | std::ofstream file_(snapshot_out_bin, std::ios::binary); 40 | file_.write(reinterpret_cast(snapshot.data_ptr), snapshot.data_len); 41 | file_.close(); 42 | 43 | delete[] snapshot.data_ptr; 44 | deno_delete(d); 45 | 46 | return file_.bad(); 47 | } 48 | -------------------------------------------------------------------------------- /js/resources_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, testPerm, assertEqual } from "./test_util.ts"; 3 | 4 | test(function resourcesStdio() { 5 | const res = Deno.resources(); 6 | 7 | assertEqual(res[0], "stdin"); 8 | assertEqual(res[1], "stdout"); 9 | assertEqual(res[2], "stderr"); 10 | }); 11 | 12 | testPerm({ net: true }, async function resourcesNet() { 13 | const addr = "127.0.0.1:4501"; 14 | const listener = Deno.listen("tcp", addr); 15 | 16 | const dialerConn = await Deno.dial("tcp", addr); 17 | const listenerConn = await listener.accept(); 18 | 19 | const res = Deno.resources(); 20 | assertEqual(Object.values(res).filter(r => r === "tcpListener").length, 1); 21 | assertEqual(Object.values(res).filter(r => r === "tcpStream").length, 2); 22 | 23 | listenerConn.close(); 24 | dialerConn.close(); 25 | listener.close(); 26 | }); 27 | 28 | testPerm({ read: true }, async function resourcesFile() { 29 | const resourcesBefore = Deno.resources(); 30 | await Deno.open("tests/hello.txt"); 31 | const resourcesAfter = Deno.resources(); 32 | 33 | // check that exactly one new resource (file) was added 34 | assertEqual( 35 | Object.keys(resourcesAfter).length, 36 | Object.keys(resourcesBefore).length + 1 37 | ); 38 | const newRid = Object.keys(resourcesAfter).find(rid => { 39 | return !resourcesBefore.hasOwnProperty(rid); 40 | }); 41 | assertEqual(resourcesAfter[newRid], "fsFile"); 42 | }); 43 | -------------------------------------------------------------------------------- /js/libdeno.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { window } from "./window"; 3 | 4 | // The libdeno functions are moved so that users can't access them. 5 | type MessageCallback = (msg: Uint8Array) => void; 6 | 7 | interface EvalErrorInfo { 8 | // Is the object thrown a native Error? 9 | isNativeError: boolean; 10 | // Was the error happened during compilation? 11 | isCompileError: boolean; 12 | // The actual thrown entity 13 | // (might be an Error or anything else thrown by the user) 14 | // If isNativeError is true, this is an Error 15 | thrown: any; // tslint:disable-line:no-any 16 | } 17 | 18 | interface Libdeno { 19 | recv(cb: MessageCallback): void; 20 | 21 | send(control: ArrayBufferView, data?: ArrayBufferView): null | Uint8Array; 22 | 23 | print(x: string, isErr?: boolean): void; 24 | 25 | shared: ArrayBuffer; 26 | 27 | // DEPRECATED 28 | builtinModules: { [s: string]: object }; 29 | 30 | /** Evaluate provided code in the current context. 31 | * It differs from eval(...) in that it does not create a new context. 32 | * Returns an array: [output, errInfo]. 33 | * If an error occurs, `output` becomes null and `errInfo` is non-null. 34 | */ 35 | evalContext( 36 | code: string 37 | ): [any, EvalErrorInfo | null] /* tslint:disable-line:no-any */; 38 | 39 | // tslint:disable-next-line:no-any 40 | errorToJSON: (e: Error) => string; 41 | } 42 | 43 | export const libdeno = window.libdeno as Libdeno; 44 | -------------------------------------------------------------------------------- /js/read_link.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import { assert } from "./util"; 5 | import * as dispatch from "./dispatch"; 6 | 7 | /** Returns the destination of the named symbolic link synchronously. 8 | * 9 | * const targetPath = Deno.readlinkSync("symlink/path"); 10 | */ 11 | export function readlinkSync(name: string): string { 12 | return res(dispatch.sendSync(...req(name))); 13 | } 14 | 15 | /** Returns the destination of the named symbolic link. 16 | * 17 | * const targetPath = await Deno.readlink("symlink/path"); 18 | */ 19 | export async function readlink(name: string): Promise { 20 | return res(await dispatch.sendAsync(...req(name))); 21 | } 22 | 23 | function req(name: string): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 24 | const builder = flatbuffers.createBuilder(); 25 | const name_ = builder.createString(name); 26 | msg.Readlink.startReadlink(builder); 27 | msg.Readlink.addName(builder, name_); 28 | const inner = msg.Readlink.endReadlink(builder); 29 | return [builder, msg.Any.Readlink, inner]; 30 | } 31 | 32 | function res(baseRes: null | msg.Base): string { 33 | assert(baseRes !== null); 34 | assert(msg.Any.ReadlinkRes === baseRes!.innerType()); 35 | const res = new msg.ReadlinkRes(); 36 | assert(baseRes!.inner(res) !== null); 37 | const path = res.path(); 38 | assert(path !== null); 39 | return path!; 40 | } 41 | -------------------------------------------------------------------------------- /core/shared.rs: -------------------------------------------------------------------------------- 1 | use crate::libdeno::deno_buf; 2 | use std::mem; 3 | 4 | // TODO this is where we abstract flatbuffers at. 5 | // TODO make these constants private to this file. 6 | const INDEX_NUM_RECORDS: usize = 0; 7 | const INDEX_RECORDS: usize = 1; 8 | pub const RECORD_OFFSET_PROMISE_ID: usize = 0; 9 | pub const RECORD_OFFSET_OP: usize = 1; 10 | pub const RECORD_OFFSET_ARG: usize = 2; 11 | pub const RECORD_OFFSET_RESULT: usize = 3; 12 | const RECORD_SIZE: usize = 4; 13 | const NUM_RECORDS: usize = 100; 14 | 15 | /// Represents the shared buffer between JS and Rust. 16 | /// Used for FFI. 17 | pub struct Shared(Vec); 18 | 19 | impl Shared { 20 | pub fn new() -> Shared { 21 | let mut vec = Vec::::new(); 22 | vec.resize(INDEX_RECORDS + RECORD_SIZE * NUM_RECORDS, 0); 23 | Shared(vec) 24 | } 25 | 26 | pub fn set_record(&mut self, i: usize, off: usize, value: i32) { 27 | assert!(i < NUM_RECORDS); 28 | self.0[INDEX_RECORDS + RECORD_SIZE * i + off] = value; 29 | } 30 | 31 | pub fn get_record(&self, i: usize, off: usize) -> i32 { 32 | assert!(i < NUM_RECORDS); 33 | return self.0[INDEX_RECORDS + RECORD_SIZE * i + off]; 34 | } 35 | 36 | pub fn set_num_records(&mut self, num_records: i32) { 37 | self.0[INDEX_NUM_RECORDS] = num_records; 38 | } 39 | 40 | pub fn get_num_records(&self) -> i32 { 41 | return self.0[INDEX_NUM_RECORDS]; 42 | } 43 | 44 | pub fn as_deno_buf(&mut self) -> deno_buf { 45 | let ptr = self.0.as_mut_ptr() as *mut u8; 46 | let len = mem::size_of::() * self.0.len(); 47 | unsafe { deno_buf::from_raw_parts(ptr, len) } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /gclient_config.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | solutions = [{ 3 | 'url': 4 | 'https://chromium.googlesource.com/v8/v8.git@7.4.238', 5 | 'name': 'v8', 6 | 'deps_file': 'DEPS', 7 | 'custom_deps': { 8 | 'v8/build': None, 9 | 'v8/third_party/catapult': None, 10 | 'v8/third_party/colorama/src': None, 11 | 'v8/testing/gmock': None, 12 | 'v8/tools/swarming_client': None, 13 | 'v8/tools/gyp': None, 14 | 'v8/third_party/instrumented_libraries': None, 15 | 'v8/third_party/android_tools': None, 16 | 'v8/third_party/depot_tools': None, 17 | 'v8/test/wasm-js': None, 18 | 'v8/test/benchmarks/data': None, 19 | 'v8/test/mozilla/data': None, 20 | 'v8/third_party/icu': None, 21 | 'v8/test/test262/data': None, 22 | 'v8/test/test262/harness': None, 23 | 'v8/tools/luci-go': None 24 | } 25 | }, { 26 | 'url': 27 | 'https://chromium.googlesource.com/chromium/tools/depot_tools@40bacee96a94600ad2179d69a8025469d119960f', 28 | 'name': 29 | 'depot_tools' 30 | }, { 31 | 'url': 32 | 'https://chromium.googlesource.com/chromium/src/third_party/zlib@39b4a6260702da4c089eca57136abf40a39667e9', 33 | 'name': 34 | 'zlib' 35 | }, { 36 | 'url': 37 | 'https://github.com/cpplint/cpplint.git@a33992f68f36fcaa6d0f531a25012a4c474d3542', 38 | 'name': 39 | 'cpplint' 40 | }, { 41 | 'url': 42 | 'https://github.com/google/flatbuffers.git@80d148b1757f0fab9305616d69d876378405843a', 43 | 'name': 44 | 'flatbuffers' 45 | }] 46 | -------------------------------------------------------------------------------- /tools/deno_dir_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | # Check deno dir is created properly 4 | # Usage: deno_dir_test.py [path to deno dir] 5 | import os 6 | import subprocess 7 | import sys 8 | from util import rmtree, run 9 | 10 | 11 | def deno_dir_test(deno_exe, deno_dir): 12 | assert os.path.isfile(deno_exe) 13 | 14 | old_deno_dir = None 15 | if "DENO_DIR" in os.environ: 16 | old_deno_dir = os.environ["DENO_DIR"] 17 | del os.environ["DENO_DIR"] 18 | 19 | if os.path.isdir(deno_dir): 20 | rmtree(deno_dir) 21 | 22 | # Run deno with no env flag 23 | run_deno(deno_exe) 24 | assert not os.path.isdir(deno_dir) 25 | 26 | # Run deno with DENO_DIR env flag 27 | run_deno(deno_exe, deno_dir) 28 | assert os.path.isdir(deno_dir) 29 | assert os.path.isdir(os.path.join(deno_dir, "deps")) 30 | assert os.path.isdir(os.path.join(deno_dir, "gen")) 31 | rmtree(deno_dir) 32 | 33 | if old_deno_dir is not None: 34 | os.environ["DENO_DIR"] = old_deno_dir 35 | 36 | 37 | def run_deno(deno_exe, deno_dir=None): 38 | cmd = [deno_exe, "tests/002_hello.ts"] 39 | deno_dir_env = {"DENO_DIR": deno_dir} if deno_dir is not None else None 40 | run(cmd, quiet=True, env=deno_dir_env) 41 | 42 | 43 | USAGE = "./tools/deno_dir_test.py target/debug/deno target/debug/.deno_dir" 44 | 45 | 46 | def main(argv): 47 | if len(sys.argv) != 3: 48 | print "Usage: " + USAGE 49 | sys.exit(1) 50 | deno_dir_test(argv[1], argv[2]) 51 | 52 | 53 | if __name__ == '__main__': 54 | sys.exit(main(sys.argv)) 55 | -------------------------------------------------------------------------------- /js/rename.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | /** Synchronously renames (moves) `oldpath` to `newpath`. If `newpath` already 7 | * exists and is not a directory, `renameSync()` replaces it. OS-specific 8 | * restrictions may apply when `oldpath` and `newpath` are in different 9 | * directories. 10 | * 11 | * Deno.renameSync("old/path", "new/path"); 12 | */ 13 | export function renameSync(oldpath: string, newpath: string): void { 14 | dispatch.sendSync(...req(oldpath, newpath)); 15 | } 16 | 17 | /** Renames (moves) `oldpath` to `newpath`. If `newpath` already exists and is 18 | * not a directory, `rename()` replaces it. OS-specific restrictions may apply 19 | * when `oldpath` and `newpath` are in different directories. 20 | * 21 | * await Deno.rename("old/path", "new/path"); 22 | */ 23 | export async function rename(oldpath: string, newpath: string): Promise { 24 | await dispatch.sendAsync(...req(oldpath, newpath)); 25 | } 26 | 27 | function req( 28 | oldpath: string, 29 | newpath: string 30 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 31 | const builder = flatbuffers.createBuilder(); 32 | const oldpath_ = builder.createString(oldpath); 33 | const newpath_ = builder.createString(newpath); 34 | msg.Rename.startRename(builder); 35 | msg.Rename.addOldpath(builder, oldpath_); 36 | msg.Rename.addNewpath(builder, newpath_); 37 | const inner = msg.Rename.endRename(builder); 38 | return [builder, msg.Any.Rename, inner]; 39 | } 40 | -------------------------------------------------------------------------------- /js/metrics_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, testPerm, assert } from "./test_util.ts"; 3 | 4 | test(async function metrics() { 5 | const m1 = Deno.metrics(); 6 | assert(m1.opsDispatched > 0); 7 | assert(m1.opsCompleted > 0); 8 | assert(m1.bytesSentControl > 0); 9 | assert(m1.bytesSentData >= 0); 10 | assert(m1.bytesReceived > 0); 11 | 12 | // Write to stdout to ensure a "data" message gets sent instead of just 13 | // control messages. 14 | const dataMsg = new Uint8Array([41, 42, 43]); 15 | await Deno.stdout.write(dataMsg); 16 | 17 | const m2 = Deno.metrics(); 18 | assert(m2.opsDispatched > m1.opsDispatched); 19 | assert(m2.opsCompleted > m1.opsCompleted); 20 | assert(m2.bytesSentControl > m1.bytesSentControl); 21 | assert(m2.bytesSentData >= m1.bytesSentData + dataMsg.byteLength); 22 | assert(m2.bytesReceived > m1.bytesReceived); 23 | }); 24 | 25 | testPerm({ write: true }, function metricsUpdatedIfNoResponseSync() { 26 | const filename = Deno.makeTempDirSync() + "/test.txt"; 27 | 28 | const data = new Uint8Array([41, 42, 43]); 29 | Deno.writeFileSync(filename, data, { perm: 0o666 }); 30 | 31 | const metrics = Deno.metrics(); 32 | assert(metrics.opsDispatched === metrics.opsCompleted); 33 | }); 34 | 35 | testPerm({ write: true }, async function metricsUpdatedIfNoResponseAsync() { 36 | const filename = Deno.makeTempDirSync() + "/test.txt"; 37 | 38 | const data = new Uint8Array([41, 42, 43]); 39 | await Deno.writeFile(filename, data, { perm: 0o666 }); 40 | 41 | const metrics = Deno.metrics(); 42 | assert(metrics.opsDispatched === metrics.opsCompleted); 43 | }); 44 | -------------------------------------------------------------------------------- /js/read_dir.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | import { FileInfo, FileInfoImpl } from "./file_info"; 6 | import { assert } from "./util"; 7 | 8 | /** Reads the directory given by path and returns a list of file info 9 | * synchronously. 10 | * 11 | * const files = Deno.readDirSync("/"); 12 | */ 13 | export function readDirSync(path: string): FileInfo[] { 14 | return res(dispatch.sendSync(...req(path))); 15 | } 16 | 17 | /** Reads the directory given by path and returns a list of file info. 18 | * 19 | * const files = await Deno.readDir("/"); 20 | */ 21 | export async function readDir(path: string): Promise { 22 | return res(await dispatch.sendAsync(...req(path))); 23 | } 24 | 25 | function req(path: string): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 26 | const builder = flatbuffers.createBuilder(); 27 | const path_ = builder.createString(path); 28 | msg.ReadDir.startReadDir(builder); 29 | msg.ReadDir.addPath(builder, path_); 30 | const inner = msg.ReadDir.endReadDir(builder); 31 | return [builder, msg.Any.ReadDir, inner]; 32 | } 33 | 34 | function res(baseRes: null | msg.Base): FileInfo[] { 35 | assert(baseRes != null); 36 | assert(msg.Any.ReadDirRes === baseRes!.innerType()); 37 | const res = new msg.ReadDirRes(); 38 | assert(baseRes!.inner(res) != null); 39 | const fileInfos: FileInfo[] = []; 40 | for (let i = 0; i < res.entriesLength(); i++) { 41 | fileInfos.push(new FileInfoImpl(res.entries(i)!)); 42 | } 43 | return fileInfos; 44 | } 45 | -------------------------------------------------------------------------------- /js/remove.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | export interface RemoveOption { 7 | recursive?: boolean; 8 | } 9 | 10 | /** Removes the named file or directory synchronously. Would throw 11 | * error if permission denied, not found, or directory not empty if `recursive` 12 | * set to false. 13 | * `recursive` is set to false by default. 14 | * 15 | * Deno.removeSync("/path/to/dir/or/file", {recursive: false}); 16 | */ 17 | export function removeSync(path: string, options: RemoveOption = {}): void { 18 | dispatch.sendSync(...req(path, options)); 19 | } 20 | 21 | /** Removes the named file or directory. Would throw error if 22 | * permission denied, not found, or directory not empty if `recursive` set 23 | * to false. 24 | * `recursive` is set to false by default. 25 | * 26 | * await Deno.remove("/path/to/dir/or/file", {recursive: false}); 27 | */ 28 | export async function remove( 29 | path: string, 30 | options: RemoveOption = {} 31 | ): Promise { 32 | await dispatch.sendAsync(...req(path, options)); 33 | } 34 | 35 | function req( 36 | path: string, 37 | options: RemoveOption 38 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 39 | const builder = flatbuffers.createBuilder(); 40 | const path_ = builder.createString(path); 41 | msg.Remove.startRemove(builder); 42 | msg.Remove.addPath(builder, path_); 43 | msg.Remove.addRecursive(builder, !!options.recursive); 44 | const inner = msg.Remove.endRemove(builder); 45 | return [builder, msg.Any.Remove, inner]; 46 | } 47 | -------------------------------------------------------------------------------- /js/copy_file.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | /** Copies the contents of a file to another by name synchronously. 7 | * Creates a new file if target does not exists, and if target exists, 8 | * overwrites original content of the target file. 9 | * 10 | * It would also copy the permission of the original file 11 | * to the destination. 12 | * 13 | * Deno.copyFileSync("from.txt", "to.txt"); 14 | */ 15 | export function copyFileSync(from: string, to: string): void { 16 | dispatch.sendSync(...req(from, to)); 17 | } 18 | 19 | /** Copies the contents of a file to another by name. 20 | * 21 | * Creates a new file if target does not exists, and if target exists, 22 | * overwrites original content of the target file. 23 | * 24 | * It would also copy the permission of the original file 25 | * to the destination. 26 | * 27 | * await Deno.copyFile("from.txt", "to.txt"); 28 | */ 29 | export async function copyFile(from: string, to: string): Promise { 30 | await dispatch.sendAsync(...req(from, to)); 31 | } 32 | 33 | function req( 34 | from: string, 35 | to: string 36 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 37 | const builder = flatbuffers.createBuilder(); 38 | const from_ = builder.createString(from); 39 | const to_ = builder.createString(to); 40 | msg.CopyFile.startCopyFile(builder); 41 | msg.CopyFile.addFrom(builder, from_); 42 | msg.CopyFile.addTo(builder, to_); 43 | const inner = msg.CopyFile.endCopyFile(builder); 44 | return [builder, msg.Any.CopyFile, inner]; 45 | } 46 | -------------------------------------------------------------------------------- /src/tokio_write.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | // TODO Submit this file upstream into tokio-io/src/io/write.rs 3 | use std::io; 4 | use std::mem; 5 | 6 | use futures::{Future, Poll}; 7 | use tokio::io::AsyncWrite; 8 | 9 | /// A future used to write some data to a stream. 10 | /// 11 | /// This is created by the [`write`] top-level method. 12 | /// 13 | /// [`write`]: fn.write.html 14 | #[derive(Debug)] 15 | pub struct Write { 16 | state: State, 17 | } 18 | 19 | #[derive(Debug)] 20 | enum State { 21 | Pending { a: A, buf: T }, 22 | Empty, 23 | } 24 | 25 | /// Creates a future that will write some of the buffer `buf` to 26 | /// the stream `a` provided. 27 | /// 28 | /// Any error which happens during writing will cause both the stream and the 29 | /// buffer to get destroyed. 30 | pub fn write(a: A, buf: T) -> Write 31 | where 32 | A: AsyncWrite, 33 | T: AsRef<[u8]>, 34 | { 35 | Write { 36 | state: State::Pending { a, buf }, 37 | } 38 | } 39 | 40 | impl Future for Write 41 | where 42 | A: AsyncWrite, 43 | T: AsRef<[u8]>, 44 | { 45 | type Item = (A, T, usize); 46 | type Error = io::Error; 47 | 48 | fn poll(&mut self) -> Poll<(A, T, usize), io::Error> { 49 | let nwritten = match self.state { 50 | State::Pending { 51 | ref mut a, 52 | ref mut buf, 53 | } => try_ready!(a.poll_write(buf.as_ref())), 54 | State::Empty => panic!("poll a Read after it's done"), 55 | }; 56 | 57 | match mem::replace(&mut self.state, State::Empty) { 58 | State::Pending { a, buf } => Ok((a, buf, nwritten).into()), 59 | State::Empty => panic!("invalid internal state"), 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /js/dir_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | test(function dirCwdNotNull() { 5 | assert(Deno.cwd() != null); 6 | }); 7 | 8 | testPerm({ write: true }, function dirCwdChdirSuccess() { 9 | const initialdir = Deno.cwd(); 10 | const path = Deno.makeTempDirSync(); 11 | Deno.chdir(path); 12 | const current = Deno.cwd(); 13 | if (Deno.platform.os === "mac") { 14 | assertEqual(current, "/private" + path); 15 | } else { 16 | assertEqual(current, path); 17 | } 18 | Deno.chdir(initialdir); 19 | }); 20 | 21 | testPerm({ write: true }, function dirCwdError() { 22 | // excluding windows since it throws resource busy, while removeSync 23 | if (["linux", "mac"].includes(Deno.platform.os)) { 24 | const initialdir = Deno.cwd(); 25 | const path = Deno.makeTempDirSync(); 26 | Deno.chdir(path); 27 | Deno.removeSync(path); 28 | try { 29 | Deno.cwd(); 30 | throw Error("current directory removed, should throw error"); 31 | } catch (err) { 32 | if (err instanceof Deno.DenoError) { 33 | console.log(err.name === "NotFound"); 34 | } else { 35 | throw Error("raised different exception"); 36 | } 37 | } 38 | Deno.chdir(initialdir); 39 | } 40 | }); 41 | 42 | testPerm({ write: true }, function dirChdirError() { 43 | const path = Deno.makeTempDirSync() + "test"; 44 | try { 45 | Deno.chdir(path); 46 | throw Error("directory not available, should throw error"); 47 | } catch (err) { 48 | if (err instanceof Deno.DenoError) { 49 | console.log(err.name === "NotFound"); 50 | } else { 51 | throw Error("raised different exception"); 52 | } 53 | } 54 | }); 55 | -------------------------------------------------------------------------------- /tools/benchmark_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import sys 3 | import os 4 | import benchmark 5 | 6 | 7 | def strace_parse_test(): 8 | with open(os.path.join(sys.path[0], "testdata/strace_summary.out"), 9 | "r") as f: 10 | summary = benchmark.strace_parse(f.read()) 11 | # first syscall line 12 | assert summary["munmap"]["calls"] == 60 13 | assert summary["munmap"]["errors"] == 0 14 | # line with errors 15 | assert summary["mkdir"]["errors"] == 2 16 | # last syscall line 17 | assert summary["prlimit64"]["calls"] == 2 18 | assert summary["prlimit64"]["% time"] == 0 19 | # summary line 20 | assert summary["total"]["calls"] == 704 21 | 22 | 23 | def binary_size_test(build_dir): 24 | binary_size_dict = benchmark.get_binary_sizes(build_dir) 25 | assert binary_size_dict["deno"] > 0 26 | assert binary_size_dict["main.js"] > 0 27 | assert binary_size_dict["main.js.map"] > 0 28 | assert binary_size_dict["snapshot_deno.bin"] > 0 29 | 30 | 31 | def thread_count_test(deno_path): 32 | thread_count_dict = benchmark.run_thread_count_benchmark(deno_path) 33 | assert "set_timeout" in thread_count_dict 34 | assert thread_count_dict["set_timeout"] > 1 35 | 36 | 37 | def syscall_count_test(deno_path): 38 | syscall_count_dict = benchmark.run_syscall_count_benchmark(deno_path) 39 | assert "hello" in syscall_count_dict 40 | assert syscall_count_dict["hello"] > 1 41 | 42 | 43 | def benchmark_test(build_dir, deno_path): 44 | strace_parse_test() 45 | binary_size_test(build_dir) 46 | if "linux" in sys.platform: 47 | thread_count_test(deno_path) 48 | syscall_count_test(deno_path) 49 | -------------------------------------------------------------------------------- /js/read_file.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import { assert } from "./util"; 5 | import * as dispatch from "./dispatch"; 6 | 7 | /** Read the entire contents of a file synchronously. 8 | * 9 | * const decoder = new TextDecoder("utf-8"); 10 | * const data = Deno.readFileSync("hello.txt"); 11 | * console.log(decoder.decode(data)); 12 | */ 13 | export function readFileSync(filename: string): Uint8Array { 14 | return res(dispatch.sendSync(...req(filename))); 15 | } 16 | 17 | /** Read the entire contents of a file. 18 | * 19 | * const decoder = new TextDecoder("utf-8"); 20 | * const data = await Deno.readFile("hello.txt"); 21 | * console.log(decoder.decode(data)); 22 | */ 23 | export async function readFile(filename: string): Promise { 24 | return res(await dispatch.sendAsync(...req(filename))); 25 | } 26 | 27 | function req( 28 | filename: string 29 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 30 | const builder = flatbuffers.createBuilder(); 31 | const filename_ = builder.createString(filename); 32 | msg.ReadFile.startReadFile(builder); 33 | msg.ReadFile.addFilename(builder, filename_); 34 | const inner = msg.ReadFile.endReadFile(builder); 35 | return [builder, msg.Any.ReadFile, inner]; 36 | } 37 | 38 | function res(baseRes: null | msg.Base): Uint8Array { 39 | assert(baseRes != null); 40 | assert(msg.Any.ReadFileRes === baseRes!.innerType()); 41 | const inner = new msg.ReadFileRes(); 42 | assert(baseRes!.inner(inner) != null); 43 | const dataArray = inner.dataArray(); 44 | assert(dataArray != null); 45 | return new Uint8Array(dataArray!); 46 | } 47 | -------------------------------------------------------------------------------- /js/unit_tests.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | // This test is executed as part of tools/test.py 4 | // But it can also be run manually: ./target/debug/deno js/unit_tests.ts 5 | 6 | import "./blob_test.ts"; 7 | import "./buffer_test.ts"; 8 | import "./chmod_test.ts"; 9 | // TODO find a way to test the compiler with split snapshots 10 | // import "./compiler_test.ts"; 11 | import "./console_test.ts"; 12 | import "./copy_file_test.ts"; 13 | import "./custom_event_test.ts"; 14 | import "./dir_test.ts"; 15 | import "./event_test.ts"; 16 | import "./event_target_test.ts"; 17 | import "./fetch_test.ts"; 18 | // TODO The global "File" has been temporarily disabled. See the note in 19 | // js/globals.ts 20 | // import "./file_test.ts"; 21 | import "./files_test.ts"; 22 | import "./form_data_test.ts"; 23 | import "./globals_test.ts"; 24 | import "./headers_test.ts"; 25 | import "./location_test.ts"; 26 | import "./make_temp_dir_test.ts"; 27 | import "./metrics_test.ts"; 28 | import "./mixins/dom_iterable_test.ts"; 29 | import "./mkdir_test.ts"; 30 | import "./net_test.ts"; 31 | import "./os_test.ts"; 32 | import "./platform_test.ts"; 33 | import "./process_test.ts"; 34 | import "./read_dir_test.ts"; 35 | import "./read_file_test.ts"; 36 | import "./read_link_test.ts"; 37 | import "./rename_test.ts"; 38 | import "./resources_test.ts"; 39 | import "./stat_test.ts"; 40 | import "./symlink_test.ts"; 41 | import "./text_encoding_test.ts"; 42 | import "./timers_test.ts"; 43 | import "./truncate_test.ts"; 44 | import "./url_test.ts"; 45 | import "./url_search_params_test.ts"; 46 | import "./write_file_test.ts"; 47 | import "./performance_test.ts"; 48 | import "./version_test.ts"; 49 | 50 | import "../website/app_test.js"; 51 | 52 | import "deps/https/deno.land/x/std/testing/main.ts"; 53 | -------------------------------------------------------------------------------- /website/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | color: #444; 3 | background: #f0f0f0; 4 | padding: 0; 5 | 6 | line-height: 1.5; 7 | font-family: sans-serif; 8 | 9 | margin: 5ex 10ex; 10 | max-width: 80ex; 11 | } 12 | 13 | #manual img { 14 | width: 100%; 15 | max-width: 800px; 16 | } 17 | 18 | 19 | h1, h2, h3, h4 { 20 | font-weight: normal; 21 | margin-bottom: 0; 22 | } 23 | 24 | h1, h2, h3, h4, p, table { 25 | margin-left: 8px; 26 | margin-right: 8px; 27 | } 28 | 29 | table { 30 | border-collapse: collapse; 31 | margin-top: 8px; 32 | } 33 | td, th { 34 | font-weight: normal; 35 | text-align: center; 36 | border: 1px dotted #bbb; 37 | padding: 4px; 38 | } 39 | 40 | svg { 41 | margin: 0px; 42 | width: 100%; 43 | height: 300px; 44 | } 45 | 46 | a { 47 | color: #106ad5; 48 | } 49 | 50 | pre a { 51 | color: #001631; 52 | } 53 | 54 | h2 a, h3 a { 55 | display: none; 56 | color: #3bace5; 57 | text-decoration: none; 58 | } 59 | 60 | h2:hover a, 61 | h3:hover a { 62 | display: inline; 63 | } 64 | 65 | pre { 66 | /* background: rgba(36, 126, 233, 0.03); */ 67 | color: #161616; 68 | background: rgba(36, 126, 233, 0.1); 69 | padding: 15px; 70 | word-wrap: normal; 71 | overflow-x: auto; 72 | } 73 | 74 | header { 75 | display: flex; 76 | align-items: center; 77 | margin: 16px 4px; 78 | } 79 | 80 | header > * { 81 | margin: 16px; 82 | } 83 | 84 | header h1 { 85 | margin: 8px 0; 86 | } 87 | 88 | 89 | @media only screen and (max-device-width: 480px) { 90 | body { 91 | margin: 0; 92 | } 93 | } 94 | 95 | code { 96 | background: rgba(36, 126, 233, 0.1); 97 | padding: 2px 5px; 98 | color: #333; 99 | } 100 | 101 | .hljs { 102 | background: transparent; 103 | } -------------------------------------------------------------------------------- /js/symlink.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | import * as util from "./util"; 6 | 7 | /** Synchronously creates `newname` as a symbolic link to `oldname`. The type 8 | * argument can be set to `dir` or `file` and is only available on Windows 9 | * (ignored on other platforms). 10 | * 11 | * Deno.symlinkSync("old/name", "new/name"); 12 | */ 13 | export function symlinkSync( 14 | oldname: string, 15 | newname: string, 16 | type?: string 17 | ): void { 18 | dispatch.sendSync(...req(oldname, newname, type)); 19 | } 20 | 21 | /** Creates `newname` as a symbolic link to `oldname`. The type argument can be 22 | * set to `dir` or `file` and is only available on Windows (ignored on other 23 | * platforms). 24 | * 25 | * await Deno.symlink("old/name", "new/name"); 26 | */ 27 | export async function symlink( 28 | oldname: string, 29 | newname: string, 30 | type?: string 31 | ): Promise { 32 | await dispatch.sendAsync(...req(oldname, newname, type)); 33 | } 34 | 35 | function req( 36 | oldname: string, 37 | newname: string, 38 | type?: string 39 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 40 | // TODO Use type for Windows. 41 | if (type) { 42 | return util.notImplemented(); 43 | } 44 | const builder = flatbuffers.createBuilder(); 45 | const oldname_ = builder.createString(oldname); 46 | const newname_ = builder.createString(newname); 47 | msg.Symlink.startSymlink(builder); 48 | msg.Symlink.addOldname(builder, oldname_); 49 | msg.Symlink.addNewname(builder, newname_); 50 | const inner = msg.Symlink.endSymlink(builder); 51 | return [builder, msg.Any.Symlink, inner]; 52 | } 53 | -------------------------------------------------------------------------------- /tools/throughput_benchmark.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | # Performs benchmark and append data to //website/data.json. 4 | # If //website/data.json doesn't exist, this script tries to import it from 5 | # gh-pages branch. 6 | # To view the results locally run ./tools/http_server.py and visit 7 | # http://localhost:4545/website 8 | 9 | import os 10 | import sys 11 | import util 12 | import time 13 | import subprocess 14 | 15 | MB = 1024 * 1024 16 | ADDR = "127.0.0.1:4544" 17 | 18 | 19 | def cat(deno_exe, megs): 20 | size = megs * MB 21 | start = time.time() 22 | cmd = deno_exe + " tests/cat.ts --allow-read /dev/zero | head -c %s " % size 23 | print cmd 24 | subprocess.check_output(cmd, shell=True) 25 | end = time.time() 26 | return end - start 27 | 28 | 29 | def tcp(deno_exe, megs): 30 | size = megs * MB 31 | # Run deno echo server in the background. 32 | echo_server = subprocess.Popen( 33 | [deno_exe, "--allow-net", "tests/echo_server.ts", ADDR]) 34 | 35 | time.sleep(5) # wait for deno to wake up. TODO racy. 36 | try: 37 | start = time.time() 38 | cmd = ("head -c %s /dev/zero " % size) + "| nc " + ADDR.replace( 39 | ":", " ") 40 | print cmd 41 | subprocess.check_output(cmd, shell=True) 42 | end = time.time() 43 | return end - start 44 | finally: 45 | echo_server.kill() 46 | 47 | 48 | def main(): 49 | deno_exe = sys.argv[1] 50 | megs = int(sys.argv[2]) 51 | if not deno_exe or not megs: 52 | print "Usage ./tools/throughput_benchmark.py target/debug/deno 100" 53 | sys.exit(1) 54 | secs = tcp(sys.argv[1], megs) 55 | print secs, "seconds" 56 | 57 | 58 | if __name__ == '__main__': 59 | main() 60 | -------------------------------------------------------------------------------- /tools/format.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018 the Deno authors. All rights reserved. MIT license. 3 | from glob import glob 4 | import os 5 | import sys 6 | from third_party import fix_symlinks, google_env, python_env 7 | from third_party import clang_format_path, third_party_path 8 | from util import root_path, run, find_exts, platform 9 | 10 | fix_symlinks() 11 | 12 | prettier = os.path.join(third_party_path, "node_modules", "prettier", 13 | "bin-prettier.js") 14 | tools_path = os.path.join(root_path, "tools") 15 | rustfmt_config = os.path.join(root_path, ".rustfmt.toml") 16 | 17 | os.chdir(root_path) 18 | 19 | 20 | def qrun(cmd, env=None): 21 | run(cmd, quiet=True, env=env) 22 | 23 | 24 | print "clang_format" 25 | qrun([clang_format_path, "-i", "-style", "Google"] + 26 | find_exts(["libdeno"], [".cc", ".h"])) 27 | 28 | print "gn format" 29 | for fn in ["BUILD.gn", ".gn"] + find_exts(["build_extra", "libdeno"], 30 | [".gn", ".gni"]): 31 | qrun(["third_party/depot_tools/gn", "format", fn], env=google_env()) 32 | 33 | print "yapf" 34 | qrun( 35 | [sys.executable, "third_party/python_packages/bin/yapf", "-i"] + find_exts( 36 | ["tools", "build_extra"], [".py"], skip=["tools/clang"]), 37 | env=python_env()) 38 | 39 | print "prettier" 40 | qrun(["node", prettier, "--write", "--loglevel=error"] + ["rollup.config.js"] + 41 | glob("*.json") + glob("*.md") + 42 | find_exts([".github", "js", "tests", "tools", "website", "core"], 43 | [".js", ".json", ".ts", ".md"], 44 | skip=["tools/clang", "js/deps"])) 45 | 46 | print "rustfmt" 47 | qrun([ 48 | "third_party/rustfmt/" + platform() + 49 | "/rustfmt", "--config-path", rustfmt_config, "build.rs" 50 | ] + find_exts(["src", "core"], [".rs"])) 51 | -------------------------------------------------------------------------------- /js/event_target.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as domTypes from "./dom_types"; 3 | 4 | /* TODO: This is an incomplete implementation to provide functionality 5 | * for Event. A proper spec is still required for a proper Web API. 6 | */ 7 | export class EventTarget implements domTypes.EventTarget { 8 | public listeners: { 9 | [type in string]: domTypes.EventListenerOrEventListenerObject[] 10 | } = {}; 11 | 12 | public addEventListener( 13 | type: string, 14 | listener: domTypes.EventListenerOrEventListenerObject | null, 15 | options?: boolean | domTypes.AddEventListenerOptions 16 | ): void { 17 | if (!(type in this.listeners)) { 18 | this.listeners[type] = []; 19 | } 20 | if (listener !== null) { 21 | this.listeners[type].push(listener); 22 | } 23 | } 24 | 25 | public removeEventListener( 26 | type: string, 27 | callback: domTypes.EventListenerOrEventListenerObject | null, 28 | options?: domTypes.EventListenerOptions | boolean 29 | ): void { 30 | if (type in this.listeners && callback !== null) { 31 | this.listeners[type] = this.listeners[type].filter( 32 | listener => listener !== callback 33 | ); 34 | } 35 | } 36 | 37 | public dispatchEvent(event: domTypes.Event): boolean { 38 | if (!(event.type in this.listeners)) { 39 | return true; 40 | } 41 | const stack = this.listeners[event.type].slice(); 42 | 43 | for (const stackElement of stack) { 44 | if ((stackElement as domTypes.EventListenerObject).handleEvent) { 45 | (stackElement as domTypes.EventListenerObject).handleEvent(event); 46 | } else { 47 | (stackElement as domTypes.EventListener).call(this, event); 48 | } 49 | } 50 | return !event.defaultPrevented; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /js/mkdir.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | /** Creates a new directory with the specified path synchronously. 7 | * If `recursive` is set to true, nested directories will be created (also known 8 | * as "mkdir -p"). 9 | * `mode` sets permission bits (before umask) on UNIX and does nothing on 10 | * Windows. 11 | * 12 | * Deno.mkdirSync("new_dir"); 13 | * Deno.mkdirSync("nested/directories", true); 14 | */ 15 | export function mkdirSync(path: string, recursive = false, mode = 0o777): void { 16 | dispatch.sendSync(...req(path, recursive, mode)); 17 | } 18 | 19 | /** Creates a new directory with the specified path. 20 | * If `recursive` is set to true, nested directories will be created (also known 21 | * as "mkdir -p"). 22 | * `mode` sets permission bits (before umask) on UNIX and does nothing on 23 | * Windows. 24 | * 25 | * await Deno.mkdir("new_dir"); 26 | * await Deno.mkdir("nested/directories", true); 27 | */ 28 | export async function mkdir( 29 | path: string, 30 | recursive = false, 31 | mode = 0o777 32 | ): Promise { 33 | await dispatch.sendAsync(...req(path, recursive, mode)); 34 | } 35 | 36 | function req( 37 | path: string, 38 | recursive: boolean, 39 | mode: number 40 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 41 | const builder = flatbuffers.createBuilder(); 42 | const path_ = builder.createString(path); 43 | msg.Mkdir.startMkdir(builder); 44 | msg.Mkdir.addPath(builder, path_); 45 | msg.Mkdir.addRecursive(builder, recursive); 46 | msg.Mkdir.addMode(builder, mode); 47 | const inner = msg.Mkdir.endMkdir(builder); 48 | return [builder, msg.Any.Mkdir, inner]; 49 | } 50 | -------------------------------------------------------------------------------- /js/read_file_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ read: true }, function readFileSyncSuccess() { 5 | const data = Deno.readFileSync("package.json"); 6 | assert(data.byteLength > 0); 7 | const decoder = new TextDecoder("utf-8"); 8 | const json = decoder.decode(data); 9 | const pkg = JSON.parse(json); 10 | assertEqual(pkg.name, "deno"); 11 | }); 12 | 13 | testPerm({ read: false }, function readFileSyncPerm() { 14 | let caughtError = false; 15 | try { 16 | const data = Deno.readFileSync("package.json"); 17 | } catch (e) { 18 | caughtError = true; 19 | assertEqual(e.kind, Deno.ErrorKind.PermissionDenied); 20 | assertEqual(e.name, "PermissionDenied"); 21 | } 22 | assert(caughtError); 23 | }); 24 | 25 | testPerm({ read: true }, function readFileSyncNotFound() { 26 | let caughtError = false; 27 | let data; 28 | try { 29 | data = Deno.readFileSync("bad_filename"); 30 | } catch (e) { 31 | caughtError = true; 32 | assertEqual(e.kind, Deno.ErrorKind.NotFound); 33 | } 34 | assert(caughtError); 35 | assert(data === undefined); 36 | }); 37 | 38 | testPerm({ read: true }, async function readFileSuccess() { 39 | const data = await Deno.readFile("package.json"); 40 | assert(data.byteLength > 0); 41 | const decoder = new TextDecoder("utf-8"); 42 | const json = decoder.decode(data); 43 | const pkg = JSON.parse(json); 44 | assertEqual(pkg.name, "deno"); 45 | }); 46 | 47 | testPerm({ read: false }, async function readFilePerm() { 48 | let caughtError = false; 49 | try { 50 | await Deno.readFile("package.json"); 51 | } catch (e) { 52 | caughtError = true; 53 | assertEqual(e.kind, Deno.ErrorKind.PermissionDenied); 54 | assertEqual(e.name, "PermissionDenied"); 55 | } 56 | assert(caughtError); 57 | }); 58 | -------------------------------------------------------------------------------- /js/rename_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ read: true, write: true }, function renameSyncSuccess() { 5 | const testDir = Deno.makeTempDirSync(); 6 | const oldpath = testDir + "/oldpath"; 7 | const newpath = testDir + "/newpath"; 8 | Deno.mkdirSync(oldpath); 9 | Deno.renameSync(oldpath, newpath); 10 | const newPathInfo = Deno.statSync(newpath); 11 | assert(newPathInfo.isDirectory()); 12 | 13 | let caughtErr = false; 14 | let oldPathInfo; 15 | 16 | try { 17 | oldPathInfo = Deno.statSync(oldpath); 18 | } catch (e) { 19 | caughtErr = true; 20 | assertEqual(e.kind, Deno.ErrorKind.NotFound); 21 | } 22 | assert(caughtErr); 23 | assertEqual(oldPathInfo, undefined); 24 | }); 25 | 26 | testPerm({ read: true, write: false }, function renameSyncPerm() { 27 | let err; 28 | try { 29 | const oldpath = "/oldbaddir"; 30 | const newpath = "/newbaddir"; 31 | Deno.renameSync(oldpath, newpath); 32 | } catch (e) { 33 | err = e; 34 | } 35 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 36 | assertEqual(err.name, "PermissionDenied"); 37 | }); 38 | 39 | testPerm({ read: true, write: true }, async function renameSuccess() { 40 | const testDir = Deno.makeTempDirSync(); 41 | const oldpath = testDir + "/oldpath"; 42 | const newpath = testDir + "/newpath"; 43 | Deno.mkdirSync(oldpath); 44 | await Deno.rename(oldpath, newpath); 45 | const newPathInfo = Deno.statSync(newpath); 46 | assert(newPathInfo.isDirectory()); 47 | 48 | let caughtErr = false; 49 | let oldPathInfo; 50 | 51 | try { 52 | oldPathInfo = Deno.statSync(oldpath); 53 | } catch (e) { 54 | caughtErr = true; 55 | assertEqual(e.kind, Deno.ErrorKind.NotFound); 56 | } 57 | assert(caughtErr); 58 | assertEqual(oldPathInfo, undefined); 59 | }); 60 | -------------------------------------------------------------------------------- /js/text_encoding_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert, assertEqual } from "./test_util.ts"; 3 | 4 | test(function atobSuccess() { 5 | const text = "hello world"; 6 | const encoded = btoa(text); 7 | assertEqual(encoded, "aGVsbG8gd29ybGQ="); 8 | }); 9 | 10 | test(function btoaSuccess() { 11 | const encoded = "aGVsbG8gd29ybGQ="; 12 | const decoded = atob(encoded); 13 | assertEqual(decoded, "hello world"); 14 | }); 15 | 16 | test(function btoaFailed() { 17 | const text = "你好"; 18 | let err; 19 | try { 20 | btoa(text); 21 | } catch (e) { 22 | err = e; 23 | } 24 | assert(!!err); 25 | assertEqual(err.name, "InvalidInput"); 26 | }); 27 | 28 | test(function textDecoder2() { 29 | // prettier-ignore 30 | const fixture = new Uint8Array([ 31 | 0xf0, 0x9d, 0x93, 0xbd, 32 | 0xf0, 0x9d, 0x93, 0xae, 33 | 0xf0, 0x9d, 0x94, 0x81, 34 | 0xf0, 0x9d, 0x93, 0xbd 35 | ]); 36 | const decoder = new TextDecoder(); 37 | assertEqual(decoder.decode(fixture), "𝓽𝓮𝔁𝓽"); 38 | }); 39 | 40 | test(function textDecoderASCII() { 41 | const fixture = new Uint8Array([0x89, 0x95, 0x9f, 0xbf]); 42 | const decoder = new TextDecoder("ascii"); 43 | assertEqual(decoder.decode(fixture), "‰•Ÿ¿"); 44 | }); 45 | 46 | test(function textDecoderErrorEncoding() { 47 | let didThrow = false; 48 | try { 49 | const decoder = new TextDecoder("foo"); 50 | } catch (e) { 51 | didThrow = true; 52 | assertEqual(e.message, "The encoding label provided ('foo') is invalid."); 53 | } 54 | assert(didThrow); 55 | }); 56 | 57 | test(function textEncoder2() { 58 | const fixture = "𝓽𝓮𝔁𝓽"; 59 | const encoder = new TextEncoder(); 60 | // prettier-ignore 61 | assertEqual(Array.from(encoder.encode(fixture)), [ 62 | 0xf0, 0x9d, 0x93, 0xbd, 63 | 0xf0, 0x9d, 0x93, 0xae, 64 | 0xf0, 0x9d, 0x94, 0x81, 65 | 0xf0, 0x9d, 0x93, 0xbd 66 | ]); 67 | }); 68 | -------------------------------------------------------------------------------- /js/main.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | // tslint:disable-next-line:no-reference 3 | /// 4 | 5 | import "./globals"; 6 | 7 | import { assert, log } from "./util"; 8 | import * as os from "./os"; 9 | import { libdeno } from "./libdeno"; 10 | import { args } from "./deno"; 11 | import { replLoop } from "./repl"; 12 | import { setVersions } from "./version"; 13 | import { setLocation } from "./location"; 14 | 15 | // builtin modules 16 | import * as deno from "./deno"; 17 | 18 | // TODO(kitsonk) remove with `--types` below 19 | import libDts from "gen/lib/lib.deno_runtime.d.ts!string"; 20 | 21 | /* tslint:disable-next-line:no-default-export */ 22 | export default function denoMain() { 23 | const startResMsg = os.start(); 24 | 25 | // TODO(kitsonk) remove when import "deno" no longer supported 26 | libdeno.builtinModules["deno"] = deno; 27 | Object.freeze(libdeno.builtinModules); 28 | 29 | setVersions(startResMsg.denoVersion()!, startResMsg.v8Version()!); 30 | 31 | // handle `--version` 32 | if (startResMsg.versionFlag()) { 33 | console.log("deno:", deno.version.deno); 34 | console.log("v8:", deno.version.v8); 35 | console.log("typescript:", deno.version.typescript); 36 | os.exit(0); 37 | } 38 | 39 | // handle `--types` 40 | // TODO(kitsonk) move to Rust fetching from compiler 41 | if (startResMsg.typesFlag()) { 42 | console.log(libDts); 43 | os.exit(0); 44 | } 45 | 46 | const mainModule = startResMsg.mainModule(); 47 | if (mainModule) { 48 | assert(mainModule.length > 0); 49 | setLocation(mainModule); 50 | } 51 | 52 | const cwd = startResMsg.cwd(); 53 | log("cwd", cwd); 54 | 55 | for (let i = 1; i < startResMsg.argvLength(); i++) { 56 | args.push(startResMsg.argv(i)); 57 | } 58 | log("args", args); 59 | Object.freeze(args); 60 | 61 | if (!mainModule) { 62 | replLoop(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /js/custom_event.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 the Deno authors. All rights reserved. MIT license. 2 | import * as domTypes from "./dom_types"; 3 | import * as event from "./event"; 4 | import { getPrivateValue } from "./util"; 5 | 6 | // WeakMaps are recommended for private attributes (see MDN link below) 7 | // tslint:disable-next-line:max-line-length 8 | // https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Add-on_SDK/Guides/Contributor_s_Guide/Private_Properties#Using_WeakMaps 9 | export const customEventAttributes = new WeakMap(); 10 | 11 | export class CustomEventInit extends event.EventInit 12 | implements domTypes.CustomEventInit { 13 | // tslint:disable-next-line:no-any 14 | detail: any; 15 | 16 | constructor({ 17 | bubbles = false, 18 | cancelable = false, 19 | composed = false, 20 | detail = null 21 | }: domTypes.CustomEventInit) { 22 | super({ bubbles, cancelable, composed }); 23 | this.detail = detail; 24 | } 25 | } 26 | 27 | export class CustomEvent extends event.Event implements domTypes.CustomEvent { 28 | constructor( 29 | type: string, 30 | customEventInitDict: domTypes.CustomEventInit = {} 31 | ) { 32 | super(type, customEventInitDict); 33 | const { detail = null } = customEventInitDict; 34 | customEventAttributes.set(this, { detail }); 35 | } 36 | 37 | // tslint:disable-next-line:no-any 38 | get detail(): any { 39 | return getPrivateValue(this, customEventAttributes, "detail"); 40 | } 41 | 42 | initCustomEvent( 43 | type: string, 44 | bubbles?: boolean, 45 | cancelable?: boolean, 46 | // tslint:disable-next-line:no-any 47 | detail?: any 48 | ) { 49 | if (this.dispatched) { 50 | return; 51 | } 52 | 53 | customEventAttributes.set(this, { detail }); 54 | } 55 | } 56 | 57 | /** Built-in objects providing `get` methods for our 58 | * interceptable JavaScript operations. 59 | */ 60 | Reflect.defineProperty(CustomEvent.prototype, "detail", { enumerable: true }); 61 | -------------------------------------------------------------------------------- /libdeno/file_util_test.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #include "testing/gtest/include/gtest/gtest.h" 3 | 4 | #include "file_util.h" 5 | 6 | TEST(FileUtilTest, ReadFileToStringFileNotExist) { 7 | std::string output; 8 | EXPECT_FALSE(deno::ReadFileToString("/should_error_out.txt", &output)); 9 | } 10 | 11 | TEST(FileUtilTest, Basename) { 12 | EXPECT_EQ("foo.txt", deno::Basename("foo.txt")); 13 | EXPECT_EQ("foo.txt", deno::Basename("/foo.txt")); 14 | EXPECT_EQ("", deno::Basename("/foo/")); 15 | EXPECT_EQ("", deno::Basename("foo/")); 16 | EXPECT_EQ("", deno::Basename("/")); 17 | EXPECT_EQ("foo.txt", deno::Basename(".\\foo.txt")); 18 | EXPECT_EQ("foo.txt", deno::Basename("/home/ryan/foo.txt")); 19 | EXPECT_EQ("foo.txt", deno::Basename("C:\\home\\ryan\\foo.txt")); 20 | } 21 | 22 | TEST(FileUtilTest, Dirname) { 23 | EXPECT_EQ("home/dank/", deno::Dirname("home/dank/memes.gif")); 24 | EXPECT_EQ("/home/dank/", deno::Dirname("/home/dank/memes.gif")); 25 | EXPECT_EQ("/home/dank/", deno::Dirname("/home/dank/")); 26 | EXPECT_EQ("home/dank/", deno::Dirname("home/dank/memes.gif")); 27 | EXPECT_EQ("/", deno::Dirname("/")); 28 | EXPECT_EQ(".\\", deno::Dirname(".\\memes.gif")); 29 | EXPECT_EQ("c:\\", deno::Dirname("c:\\stuff")); 30 | EXPECT_EQ("./", deno::Dirname("nothing")); 31 | EXPECT_EQ("./", deno::Dirname("")); 32 | } 33 | 34 | TEST(FileUtilTest, ExePath) { 35 | std::string exe_path; 36 | EXPECT_TRUE(deno::ExePath(&exe_path)); 37 | // Path is absolute. 38 | EXPECT_TRUE(exe_path.find("/") == 0 || exe_path.find(":\\") == 1); 39 | // FIlename is the name of the test binary. 40 | std::string exe_filename = deno::Basename(exe_path); 41 | EXPECT_EQ(exe_filename.find("test_cc"), 0u); 42 | // Path exists (also tests ReadFileToString). 43 | std::string contents; 44 | EXPECT_TRUE(deno::ReadFileToString(exe_path.c_str(), &contents)); 45 | EXPECT_NE(contents.find("Inception :)"), std::string::npos); 46 | } 47 | -------------------------------------------------------------------------------- /libdeno/deno.gni: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import("//build/compiled_action.gni") 3 | 4 | # Tempalte to generate a Rollup bundle of code. 5 | template("bundle") { 6 | action(target_name) { 7 | forward_variables_from(invoker, "*") 8 | script = "//tools/run_node.py" 9 | outputs = [ 10 | out_dir + out_name + ".js", 11 | out_dir + out_name + ".js.map", 12 | ] 13 | inputs = [ 14 | "js/" + out_name + ".ts", 15 | "rollup.config.js", 16 | ] 17 | depfile = out_dir + out_name + ".d" 18 | args = [ 19 | rebase_path("third_party/node_modules/rollup/bin/rollup", root_build_dir), 20 | "-c", 21 | rebase_path("rollup.config.js", root_build_dir), 22 | "-i", 23 | rebase_path(inputs[0], root_build_dir), 24 | "-o", 25 | rebase_path(outputs[0], root_build_dir), 26 | "--sourcemapFile", 27 | rebase_path("."), 28 | "--silent", 29 | ] 30 | } 31 | } 32 | 33 | template("run_node") { 34 | action(target_name) { 35 | forward_variables_from(invoker, "*") 36 | script = "//tools/run_node.py" 37 | } 38 | } 39 | 40 | # Template to generate different V8 snapshots based on different runtime flags. 41 | template("snapshot") { 42 | compiled_action(target_name) { 43 | forward_variables_from(invoker, 44 | [ 45 | "testonly", 46 | "deps", 47 | ]) 48 | tool = "//libdeno:snapshot_creator" 49 | visibility = [ ":*" ] # Only targets in this file can depend on this. 50 | snapshot_out_bin = "$target_gen_dir/$target_name.bin" 51 | inputs = [ 52 | invoker.source_root, 53 | ] 54 | 55 | outputs = [ 56 | snapshot_out_bin, 57 | ] 58 | args = rebase_path(outputs, root_build_dir) + 59 | rebase_path(inputs, root_build_dir) 60 | 61 | # To debug snapshotting problems: 62 | # args += ["--trace-serializer"] 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/ansi.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | use ansi_term::Color::Fixed; 3 | use ansi_term::Color::Red; 4 | use ansi_term::Style; 5 | use regex::Regex; 6 | use std::borrow::Cow; 7 | use std::env; 8 | use std::fmt; 9 | 10 | lazy_static! { 11 | // STRIP_ANSI_RE and strip_ansi_codes are lifted from the "console" crate. 12 | // Copyright 2017 Armin Ronacher . MIT License. 13 | static ref STRIP_ANSI_RE: Regex = Regex::new( 14 | r"[\x1b\x9b][\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]" 15 | ).unwrap(); 16 | static ref NO_COLOR: bool = { 17 | env::var_os("NO_COLOR").is_some() 18 | }; 19 | } 20 | 21 | /// Helper function to strip ansi codes. 22 | #[allow(dead_code)] 23 | pub fn strip_ansi_codes(s: &str) -> Cow { 24 | STRIP_ANSI_RE.replace_all(s, "") 25 | } 26 | 27 | pub fn use_color() -> bool { 28 | !(*NO_COLOR) 29 | } 30 | 31 | pub fn red_bold(s: String) -> impl fmt::Display { 32 | let mut style = Style::new(); 33 | if use_color() { 34 | style = style.bold().fg(Red); 35 | } 36 | style.paint(s) 37 | } 38 | 39 | pub fn italic_bold(s: String) -> impl fmt::Display { 40 | let mut style = Style::new(); 41 | if use_color() { 42 | style = style.italic().bold(); 43 | } 44 | style.paint(s) 45 | } 46 | 47 | pub fn yellow(s: String) -> impl fmt::Display { 48 | let mut style = Style::new(); 49 | if use_color() { 50 | // matches TypeScript's ForegroundColorEscapeSequences.Yellow 51 | style = style.fg(Fixed(11)); 52 | } 53 | style.paint(s) 54 | } 55 | 56 | pub fn cyan(s: String) -> impl fmt::Display { 57 | let mut style = Style::new(); 58 | if use_color() { 59 | // matches TypeScript's ForegroundColorEscapeSequences.Cyan 60 | style = style.fg(Fixed(14)); 61 | } 62 | style.paint(s) 63 | } 64 | 65 | pub fn bold(s: String) -> impl fmt::Display { 66 | let mut style = Style::new(); 67 | if use_color() { 68 | style = style.bold(); 69 | } 70 | style.paint(s) 71 | } 72 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "array-type": [true, "array-simple"], 4 | "arrow-return-shorthand": true, 5 | "ban": [ 6 | true, 7 | ["fit"], 8 | ["fdescribe"], 9 | ["xit"], 10 | ["xdescribe"], 11 | ["fitAsync"], 12 | ["xitAsync"], 13 | ["fitFakeAsync"], 14 | ["xitFakeAsync"] 15 | ], 16 | "ban-types": [ 17 | true, 18 | ["Object", "Use {} instead."], 19 | ["String", "Use 'string' instead."], 20 | ["Number", "Use 'number' instead."], 21 | ["Boolean", "Use 'boolean' instead."] 22 | ], 23 | "class-name": true, 24 | "curly": true, 25 | "interface-name": [true, "never-prefix"], 26 | "jsdoc-format": true, 27 | "forin": false, 28 | "label-position": true, 29 | "max-line-length": [true, 80], 30 | "new-parens": true, 31 | "no-angle-bracket-type-assertion": true, 32 | "no-any": true, 33 | "no-construct": true, 34 | "no-consecutive-blank-lines": true, 35 | "no-debugger": true, 36 | "no-default-export": true, 37 | "no-inferrable-types": true, 38 | //"no-namespace": [true, "allow-declarations"], 39 | "no-reference": true, 40 | "no-require-imports": true, 41 | "no-string-throw": true, 42 | "no-unused-expression": true, 43 | "no-var-keyword": true, 44 | "object-literal-shorthand": true, 45 | "only-arrow-functions": [ 46 | true, 47 | "allow-declarations", 48 | "allow-named-functions" 49 | ], 50 | "prefer-const": true, 51 | "quotemark": [true, "double"], 52 | "radix": true, 53 | "restrict-plus-operands": true, 54 | "semicolon": [true, "always", "ignore-bound-class-methods"], 55 | "switch-default": true, 56 | "triple-equals": [true, "allow-null-check"], 57 | "use-isnan": true, 58 | "variable-name": [ 59 | true, 60 | "check-format", 61 | "ban-keywords", 62 | "allow-leading-underscore", 63 | "allow-trailing-underscore" 64 | ] 65 | }, 66 | "extends": ["tslint-no-circular-imports"] 67 | } 68 | -------------------------------------------------------------------------------- /js/flatbuffers.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { flatbuffers } from "flatbuffers"; 3 | import * as util from "./util"; 4 | 5 | // Re-export some types. 6 | export type Offset = flatbuffers.Offset; 7 | export class ByteBuffer extends flatbuffers.ByteBuffer {} 8 | export interface Builder extends flatbuffers.Builder { 9 | inUse: boolean; 10 | } 11 | 12 | const globalBuilder = new flatbuffers.Builder() as Builder; 13 | globalBuilder.inUse = false; 14 | 15 | // This is a wrapper around the real Builder . 16 | // The purpose is to reuse a single ArrayBuffer for every message. 17 | // We can do this because the "control" messages sent to the privileged 18 | // side are guaranteed to be used during the call to libdeno.send(). 19 | export function createBuilder(): Builder { 20 | // tslint:disable-next-line:no-any 21 | const gb = globalBuilder as any; 22 | util.assert(!gb.inUse); 23 | 24 | let bb = globalBuilder.dataBuffer(); 25 | // Only create a new backing ArrayBuffer if the previous one had grown very 26 | // large in capacity. This should only happen rarely. 27 | if (bb.capacity() > 1024) { 28 | util.log(`realloc flatbuffer ArrayBuffer because it was ${bb.capacity()}`); 29 | bb = ByteBuffer.allocate(1024); 30 | } 31 | gb.bb = bb; 32 | // Remaining space in the ByteBuffer. 33 | gb.space = globalBuilder.dataBuffer().capacity(); 34 | // Minimum alignment encountered so far. 35 | gb.minalign = 1; 36 | // The vtable for the current table. 37 | gb.vtable = null; 38 | // The amount of fields we're actually using. 39 | gb.vtable_in_use = 0; 40 | // Whether we are currently serializing a table. 41 | gb.isNested = false; 42 | // Starting offset of the current struct/table. 43 | gb.object_start = 0; 44 | // List of offsets of all vtables. 45 | gb.vtables = []; 46 | // For the current vector being built. 47 | gb.vector_num_elems = 0; 48 | // False omits default values from the serialized data 49 | gb.force_defaults = false; 50 | 51 | gb.inUse = true; 52 | 53 | return gb as Builder; 54 | } 55 | -------------------------------------------------------------------------------- /js/mkdir_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ read: true, write: true }, function mkdirSyncSuccess() { 5 | const path = Deno.makeTempDirSync() + "/dir"; 6 | Deno.mkdirSync(path); 7 | const pathInfo = Deno.statSync(path); 8 | assert(pathInfo.isDirectory()); 9 | }); 10 | 11 | testPerm({ read: true, write: true }, function mkdirSyncMode() { 12 | const path = Deno.makeTempDirSync() + "/dir"; 13 | Deno.mkdirSync(path, false, 0o755); // no perm for x 14 | const pathInfo = Deno.statSync(path); 15 | if (pathInfo.mode !== null) { 16 | // Skip windows 17 | assertEqual(pathInfo.mode & 0o777, 0o755); 18 | } 19 | }); 20 | 21 | testPerm({ write: false }, function mkdirSyncPerm() { 22 | let err; 23 | try { 24 | Deno.mkdirSync("/baddir"); 25 | } catch (e) { 26 | err = e; 27 | } 28 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 29 | assertEqual(err.name, "PermissionDenied"); 30 | }); 31 | 32 | testPerm({ read: true, write: true }, async function mkdirSuccess() { 33 | const path = Deno.makeTempDirSync() + "/dir"; 34 | await Deno.mkdir(path); 35 | const pathInfo = Deno.statSync(path); 36 | assert(pathInfo.isDirectory()); 37 | }); 38 | 39 | testPerm({ write: true }, function mkdirErrIfExists() { 40 | let err; 41 | try { 42 | Deno.mkdirSync("."); 43 | } catch (e) { 44 | err = e; 45 | } 46 | assertEqual(err.kind, Deno.ErrorKind.AlreadyExists); 47 | assertEqual(err.name, "AlreadyExists"); 48 | }); 49 | 50 | testPerm({ read: true, write: true }, function mkdirSyncRecursive() { 51 | const path = Deno.makeTempDirSync() + "/nested/directory"; 52 | Deno.mkdirSync(path, true); 53 | const pathInfo = Deno.statSync(path); 54 | assert(pathInfo.isDirectory()); 55 | }); 56 | 57 | testPerm({ read: true, write: true }, async function mkdirRecursive() { 58 | const path = Deno.makeTempDirSync() + "/nested/directory"; 59 | await Deno.mkdir(path, true); 60 | const pathInfo = Deno.statSync(path); 61 | assert(pathInfo.isDirectory()); 62 | }); 63 | -------------------------------------------------------------------------------- /js/workers.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as dispatch from "./dispatch"; 3 | import * as msg from "gen/msg_generated"; 4 | import * as flatbuffers from "./flatbuffers"; 5 | import { assert, log } from "./util"; 6 | import { window } from "./window"; 7 | 8 | export async function postMessage(data: Uint8Array): Promise { 9 | const builder = flatbuffers.createBuilder(); 10 | msg.WorkerPostMessage.startWorkerPostMessage(builder); 11 | const inner = msg.WorkerPostMessage.endWorkerPostMessage(builder); 12 | const baseRes = await dispatch.sendAsync( 13 | builder, 14 | msg.Any.WorkerPostMessage, 15 | inner, 16 | data 17 | ); 18 | assert(baseRes != null); 19 | } 20 | 21 | export async function getMessage(): Promise { 22 | log("getMessage"); 23 | const builder = flatbuffers.createBuilder(); 24 | msg.WorkerGetMessage.startWorkerGetMessage(builder); 25 | const inner = msg.WorkerGetMessage.endWorkerGetMessage(builder); 26 | const baseRes = await dispatch.sendAsync( 27 | builder, 28 | msg.Any.WorkerGetMessage, 29 | inner 30 | ); 31 | assert(baseRes != null); 32 | assert( 33 | msg.Any.WorkerGetMessageRes === baseRes!.innerType(), 34 | `base.innerType() unexpectedly is ${baseRes!.innerType()}` 35 | ); 36 | const res = new msg.WorkerGetMessageRes(); 37 | assert(baseRes!.inner(res) != null); 38 | 39 | const dataArray = res.dataArray(); 40 | if (dataArray == null) { 41 | return null; 42 | } else { 43 | return new Uint8Array(dataArray!); 44 | } 45 | } 46 | 47 | let isClosing = false; 48 | 49 | export function workerClose(): void { 50 | isClosing = true; 51 | } 52 | 53 | export async function workerMain() { 54 | log("workerMain"); 55 | 56 | while (!isClosing) { 57 | const data = await getMessage(); 58 | if (data == null) { 59 | log("workerMain got null message. quitting."); 60 | break; 61 | } 62 | if (window["onmessage"]) { 63 | const event = { data }; 64 | window.onmessage(event); 65 | } else { 66 | break; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /tools/sha256sum.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | """ 3 | Computes the SHA256 hash and formats the result. 4 | """ 5 | 6 | import argparse 7 | from hashlib import sha256 8 | import os 9 | import sys 10 | 11 | 12 | def main(): 13 | parser = argparse.ArgumentParser(description=__doc__) 14 | 15 | # Arguments specifying where input comes from. 16 | # If multiple sources are specified, they are all concatenated together. 17 | parser.add_argument( 18 | "--input", 19 | action="append", 20 | dest="input", 21 | type=str, 22 | metavar="TEXT", 23 | help="Hash literal text specified on the command line.") 24 | parser.add_argument( 25 | "--infile", 26 | action="append", 27 | dest="input", 28 | type=read_file, 29 | metavar="FILE", 30 | help="Hash the contents of a file.") 31 | 32 | # Arguments dealing with output. 33 | parser.add_argument( 34 | "--format", 35 | type=str, 36 | dest="format", 37 | default="%s", 38 | metavar="TEMPLATE", 39 | help="Format output using Python template (default = '%%s').") 40 | parser.add_argument( 41 | "--outfile", 42 | dest="outfile", 43 | type=argparse.FileType("wb"), 44 | default=sys.stdout, 45 | metavar="FILE", 46 | help="Write the formatted hash to a file (default = stdout).") 47 | 48 | # Parse arguments. Print usage and exit if given no input. 49 | args = parser.parse_args() 50 | if (not args.input): 51 | parser.print_usage() 52 | return 1 53 | 54 | # Compute the hash of all inputs concatenated together. 55 | hasher = sha256() 56 | for data in args.input: 57 | hasher.update(data) 58 | h = hasher.hexdigest() 59 | 60 | # Format and write to specified out file (or the default, stdout). 61 | args.outfile.write(args.format % h) 62 | 63 | 64 | def read_file(filename): 65 | with open(filename, "rb") as f: 66 | return f.read() 67 | 68 | 69 | if __name__ == '__main__': 70 | sys.exit(main()) 71 | -------------------------------------------------------------------------------- /js/event_target_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assertEqual } from "./test_util.ts"; 3 | 4 | test(function addEventListenerTest() { 5 | const document = new EventTarget(); 6 | 7 | assertEqual(document.addEventListener("x", null, false), undefined); 8 | assertEqual(document.addEventListener("x", null, true), undefined); 9 | assertEqual(document.addEventListener("x", null), undefined); 10 | }); 11 | 12 | test(function constructedEventTargetCanBeUsedAsExpected() { 13 | const target = new EventTarget(); 14 | const event = new Event("foo", { bubbles: true, cancelable: false }); 15 | let callCount = 0; 16 | 17 | function listener(e) { 18 | assertEqual(e, event); 19 | ++callCount; 20 | } 21 | 22 | target.addEventListener("foo", listener); 23 | 24 | target.dispatchEvent(event); 25 | assertEqual(callCount, 1); 26 | 27 | target.dispatchEvent(event); 28 | assertEqual(callCount, 2); 29 | 30 | target.removeEventListener("foo", listener); 31 | target.dispatchEvent(event); 32 | assertEqual(callCount, 2); 33 | }); 34 | 35 | test(function anEventTargetCanBeSubclassed() { 36 | class NicerEventTarget extends EventTarget { 37 | on(type, callback?, options?) { 38 | this.addEventListener(type, callback, options); 39 | } 40 | 41 | off(type, callback?, options?) { 42 | this.removeEventListener(type, callback, options); 43 | } 44 | } 45 | 46 | const target = new NicerEventTarget(); 47 | const event = new Event("foo", { bubbles: true, cancelable: false }); 48 | let callCount = 0; 49 | 50 | function listener() { 51 | ++callCount; 52 | } 53 | 54 | target.on("foo", listener); 55 | assertEqual(callCount, 0); 56 | 57 | target.off("foo", listener); 58 | assertEqual(callCount, 0); 59 | }); 60 | 61 | test(function removingNullEventListenerShouldSucceed() { 62 | const document = new EventTarget(); 63 | assertEqual(document.removeEventListener("x", null, false), undefined); 64 | assertEqual(document.removeEventListener("x", null, true), undefined); 65 | assertEqual(document.removeEventListener("x", null), undefined); 66 | }); 67 | -------------------------------------------------------------------------------- /tools/testdata/unit_test_output2.txt: -------------------------------------------------------------------------------- 1 | running 96 tests 2 | test permSerialization_permW0N0E0 3 | ... ok 4 | test permFromStringThrows_permW0N0E0 5 | ... ok 6 | test compilerInstance_permW0N0E0 7 | ... ok 8 | test compilerRun_permW0N0E0 9 | Compiling /root/project/foo/bar.ts 10 | ... ok 11 | test compilerRunMultiModule_permW0N0E0 12 | ... ok 13 | test compilerRunCircularDependency_permW0N0E0 14 | Compiling modA 15 | Compiling modB 16 | ... ok 17 | test compilerResolveModule_permW0N0E0 18 | ... ok 19 | test compilerGetModuleDependencies_permW0N0E0 20 | ... ok 21 | test compilerGetCompilationSettings_permW0N0E0 22 | ... ok 23 | test compilerGetNewLine_permW0N0E0 24 | ... ok 25 | test compilerGetScriptFileNames_permW0N0E0 26 | Compiling /root/project/foo/bar.ts 27 | ... ok 28 | test compilerRecompileFlag_permW0N0E0 29 | Compiling /root/project/foo/bar.ts 30 | Compiling /root/project/foo/bar.ts 31 | ... ok 32 | test compilerGetScriptKind_permW0N0E0 33 | ... ok 34 | test compilerGetScriptVersion_permW0N0E0 35 | Compiling /root/project/foo/bar.ts 36 | ... ok 37 | test compilerGetScriptVersionUnknown_permW0N0E0 38 | ... ok 39 | test compilerGetScriptSnapshot_permW0N0E0 40 | ... ok 41 | test compilerGetCurrentDirectory_permW0N0E0 42 | ... ok 43 | test compilerGetDefaultLibFileName_permW0N0E0 44 | ... ok 45 | test compilerUseCaseSensitiveFileNames_permW0N0E0 46 | ... ok 47 | test compilerReadFile_permW0N0E0 48 | ... ok 49 | test compilerFileExists_permW0N0E0 50 | ... ok 51 | test compilerResolveModuleNames_permW0N0E0 52 | ... ok 53 | test consoleTestAssert_permW0N0E0 54 | ... ok 55 | test consoleTestStringifyComplexObjects_permW0N0E0 56 | ... ok 57 | test consoleTestStringifyCircular_permW0N0E0 58 | ... ok 59 | test consoleTestStringifyWithDepth_permW0N0E0 60 | ... ok 61 | test consoleTestError_permW0N0E0 62 | ... ok 63 | test consoleDetachedLog_permW0N0E0 64 | Hello world 65 | Hello world 66 | Hello world 67 | Hello world 68 | Hello world 69 | Hello world 70 | ... ok 71 | test fetchPerm_permW0N0E0 72 | -------------------------------------------------------------------------------- /website/manual.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Deno Manual 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 |
18 | 19 | 20 | 21 | 51 |
52 | 53 | 54 | -------------------------------------------------------------------------------- /website/style_guide.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Deno Style Guide 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 |
19 | 20 | 21 | 22 | 52 |
53 | 54 | 55 | -------------------------------------------------------------------------------- /.gn: -------------------------------------------------------------------------------- 1 | # This file is used by the GN meta build system to find the root of the source 2 | # tree and to set startup options. For documentation on the values set in this 3 | # file, run "gn help dotfile" at the command line. 4 | 5 | # The location of the build configuration file. 6 | buildconfig = "//build/config/BUILDCONFIG.gn" 7 | 8 | # These are the targets to check headers for by default. The files in targets 9 | # matching these patterns (see "gn help label_pattern" for format) will have 10 | # their includes checked for proper dependencies when you run either 11 | # "gn check" or "gn gen --check". 12 | check_targets = [] 13 | 14 | default_args = { 15 | # Various global chrome args that are unrelated to deno. 16 | proprietary_codecs = false 17 | safe_browsing_mode = 0 18 | toolkit_views = false 19 | use_aura = false 20 | use_dbus = false 21 | use_gio = false 22 | use_glib = false 23 | use_ozone = false 24 | use_udev = false 25 | 26 | # To disable "use_atk" and other features that we don't need. 27 | is_desktop_linux = false 28 | 29 | # TODO(ry) We may want to turn on CFI at some point. Disabling for simplicity 30 | # for now. See http://clang.llvm.org/docs/ControlFlowIntegrity.html 31 | is_cfi = false 32 | 33 | # TODO(ry) Remove this so debug builds can link faster. Currently removing 34 | # this breaks cargo build in debug mode in OSX. 35 | is_component_build = false 36 | 37 | # Enable Jumbo build for a faster build. 38 | # https://chromium.googlesource.com/chromium/src/+/master/docs/jumbo.md 39 | use_jumbo_build = true 40 | 41 | symbol_level = 1 42 | treat_warnings_as_errors = true 43 | rust_treat_warnings_as_errors = true 44 | 45 | # https://cs.chromium.org/chromium/src/docs/ccache_mac.md 46 | clang_use_chrome_plugins = false 47 | 48 | v8_deprecation_warnings = false 49 | v8_enable_gdbjit = false 50 | v8_enable_i18n_support = false 51 | v8_experimental_extra_library_files = [] 52 | v8_extra_library_files = [] 53 | v8_imminent_deprecation_warnings = false 54 | v8_monolithic = false 55 | v8_untrusted_code_mitigations = false 56 | v8_use_external_startup_data = false 57 | v8_use_snapshot = true 58 | v8_postmortem_support = true # for https://github.com/nodejs/llnode/ 59 | } 60 | -------------------------------------------------------------------------------- /js/deno.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | 3 | // Public deno module. 4 | export { noColor, pid, env, exit, isTTY, execPath } from "./os"; 5 | export { chdir, cwd } from "./dir"; 6 | export { 7 | File, 8 | open, 9 | stdin, 10 | stdout, 11 | stderr, 12 | read, 13 | write, 14 | seek, 15 | close, 16 | OpenMode 17 | } from "./files"; 18 | export { 19 | copy, 20 | toAsyncIterator, 21 | ReadResult, 22 | SeekMode, 23 | Reader, 24 | Writer, 25 | Closer, 26 | Seeker, 27 | ReadCloser, 28 | WriteCloser, 29 | ReadSeeker, 30 | WriteSeeker, 31 | ReadWriteCloser, 32 | ReadWriteSeeker 33 | } from "./io"; 34 | export { Buffer, readAll } from "./buffer"; 35 | export { mkdirSync, mkdir } from "./mkdir"; 36 | export { 37 | makeTempDirSync, 38 | makeTempDir, 39 | MakeTempDirOptions 40 | } from "./make_temp_dir"; 41 | export { chmodSync, chmod } from "./chmod"; 42 | export { removeSync, remove, RemoveOption } from "./remove"; 43 | export { renameSync, rename } from "./rename"; 44 | export { readFileSync, readFile } from "./read_file"; 45 | export { readDirSync, readDir } from "./read_dir"; 46 | export { copyFileSync, copyFile } from "./copy_file"; 47 | export { readlinkSync, readlink } from "./read_link"; 48 | export { statSync, lstatSync, stat, lstat } from "./stat"; 49 | export { symlinkSync, symlink } from "./symlink"; 50 | export { writeFileSync, writeFile, WriteFileOptions } from "./write_file"; 51 | export { ErrorKind, DenoError } from "./errors"; 52 | export { libdeno } from "./libdeno"; 53 | export { platform } from "./platform"; 54 | export { truncateSync, truncate } from "./truncate"; 55 | export { FileInfo } from "./file_info"; 56 | export { connect, dial, listen, Listener, Conn } from "./net"; 57 | export { metrics, Metrics } from "./metrics"; 58 | export { resources } from "./resources"; 59 | export { run, RunOptions, Process, ProcessStatus } from "./process"; 60 | export { inspect } from "./console"; 61 | export { version } from "./version"; 62 | export const args: string[] = []; 63 | 64 | // TODO Don't expose Console nor stringifyArgs. 65 | /** @internal */ 66 | export { Console, stringifyArgs } from "./console"; 67 | // TODO Don't expose DomIterableMixin. 68 | /** @internal */ 69 | export { DomIterableMixin } from "./mixins/dom_iterable"; 70 | -------------------------------------------------------------------------------- /tools/setup_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import os 3 | from setup import gn_string, read_gn_args, write_gn_args 4 | from shutil import rmtree 5 | from tempfile import mktemp 6 | 7 | 8 | def gn_string_test(): 9 | assert '"abc"' == gn_string('abc') 10 | assert '"foo\\$bar\\"baz"' == gn_string('foo$bar"baz') 11 | assert '"do\\not\\escape"' == gn_string('do\\not\\escape') 12 | assert '"so\\\\\\very\\\\\\"fun\\"' == gn_string('so\\\\very\\"fun\\') 13 | 14 | 15 | def read_gn_args_test(): 16 | # Args file doesn't exist. 17 | (args, hand_edited) = read_gn_args("/baddir/hopefully/nonexistent/args.gn") 18 | assert args is None 19 | assert hand_edited == False 20 | 21 | # Handwritten empty args file. 22 | filename = mktemp() 23 | with open(filename, "w"): 24 | pass 25 | (args, hand_edited) = read_gn_args(filename) 26 | os.remove(filename) 27 | assert args == [] 28 | assert hand_edited == True 29 | 30 | # Handwritten non-empty args file. 31 | expect_args = ['some_number=2', 'another_string="ran/dom#yes"'] 32 | filename = mktemp() 33 | with open(filename, "w") as f: 34 | f.write("\n".join(expect_args + ["", "# A comment to be ignored"])) 35 | (args, hand_edited) = read_gn_args(filename) 36 | os.remove(filename) 37 | assert args == expect_args 38 | assert hand_edited == True 39 | 40 | 41 | def write_gn_args_test(): 42 | # Build a nonexistent path; write_gn_args() should call mkdir as needed. 43 | d = mktemp() 44 | filename = os.path.join(d, "args.gn") 45 | assert not os.path.exists(d) 46 | assert not os.path.exists(filename) 47 | # Write some args. 48 | args = ['lalala=42', 'foo_bar_baz="lorem ipsum dolor#amet"'] 49 | write_gn_args(filename, args) 50 | # Directory and args file should now be created. 51 | assert os.path.isdir(d) 52 | assert os.path.isfile(filename) 53 | # Validate that the right contents were written. 54 | (check_args, hand_edited) = read_gn_args(filename) 55 | assert check_args == args 56 | assert hand_edited == False 57 | # Clean up. 58 | rmtree(d) 59 | 60 | 61 | def setup_test(): 62 | gn_string_test() 63 | read_gn_args_test() 64 | write_gn_args_test() 65 | 66 | 67 | if __name__ == '__main__': 68 | setup_test() 69 | -------------------------------------------------------------------------------- /js/read_link_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ write: true, read: true }, function readlinkSyncSuccess() { 5 | const testDir = Deno.makeTempDirSync(); 6 | const target = testDir + "/target"; 7 | const symlink = testDir + "/symln"; 8 | Deno.mkdirSync(target); 9 | // TODO Add test for Windows once symlink is implemented for Windows. 10 | // See https://github.com/denoland/deno/issues/815. 11 | if (Deno.platform.os !== "win") { 12 | Deno.symlinkSync(target, symlink); 13 | const targetPath = Deno.readlinkSync(symlink); 14 | assertEqual(targetPath, target); 15 | } 16 | }); 17 | 18 | testPerm({ read: false }, async function readlinkSyncPerm() { 19 | let caughtError = false; 20 | try { 21 | Deno.readlinkSync("/symlink"); 22 | } catch (e) { 23 | caughtError = true; 24 | assertEqual(e.kind, Deno.ErrorKind.PermissionDenied); 25 | assertEqual(e.name, "PermissionDenied"); 26 | } 27 | assert(caughtError); 28 | }); 29 | 30 | testPerm({ read: true }, function readlinkSyncNotFound() { 31 | let caughtError = false; 32 | let data; 33 | try { 34 | data = Deno.readlinkSync("bad_filename"); 35 | } catch (e) { 36 | caughtError = true; 37 | assertEqual(e.kind, Deno.ErrorKind.NotFound); 38 | } 39 | assert(caughtError); 40 | assertEqual(data, undefined); 41 | }); 42 | 43 | testPerm({ write: true, read: true }, async function readlinkSuccess() { 44 | const testDir = Deno.makeTempDirSync(); 45 | const target = testDir + "/target"; 46 | const symlink = testDir + "/symln"; 47 | Deno.mkdirSync(target); 48 | // TODO Add test for Windows once symlink is implemented for Windows. 49 | // See https://github.com/denoland/deno/issues/815. 50 | if (Deno.platform.os !== "win") { 51 | Deno.symlinkSync(target, symlink); 52 | const targetPath = await Deno.readlink(symlink); 53 | assertEqual(targetPath, target); 54 | } 55 | }); 56 | 57 | testPerm({ read: false }, async function readlinkPerm() { 58 | let caughtError = false; 59 | try { 60 | await Deno.readlink("/symlink"); 61 | } catch (e) { 62 | caughtError = true; 63 | assertEqual(e.kind, Deno.ErrorKind.PermissionDenied); 64 | assertEqual(e.name, "PermissionDenied"); 65 | } 66 | assert(caughtError); 67 | }); 68 | -------------------------------------------------------------------------------- /js/symlink_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ read: true, write: true }, function symlinkSyncSuccess() { 5 | const testDir = Deno.makeTempDirSync(); 6 | const oldname = testDir + "/oldname"; 7 | const newname = testDir + "/newname"; 8 | Deno.mkdirSync(oldname); 9 | let errOnWindows; 10 | // Just for now, until we implement symlink for Windows. 11 | try { 12 | Deno.symlinkSync(oldname, newname); 13 | } catch (e) { 14 | errOnWindows = e; 15 | } 16 | if (errOnWindows) { 17 | assertEqual(errOnWindows.kind, Deno.ErrorKind.Other); 18 | assertEqual(errOnWindows.message, "Not implemented"); 19 | } else { 20 | const newNameInfoLStat = Deno.lstatSync(newname); 21 | const newNameInfoStat = Deno.statSync(newname); 22 | assert(newNameInfoLStat.isSymlink()); 23 | assert(newNameInfoStat.isDirectory()); 24 | } 25 | }); 26 | 27 | test(function symlinkSyncPerm() { 28 | let err; 29 | try { 30 | Deno.symlinkSync("oldbaddir", "newbaddir"); 31 | } catch (e) { 32 | err = e; 33 | } 34 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 35 | assertEqual(err.name, "PermissionDenied"); 36 | }); 37 | 38 | // Just for now, until we implement symlink for Windows. 39 | testPerm({ write: true }, function symlinkSyncNotImplemented() { 40 | let err; 41 | try { 42 | Deno.symlinkSync("oldname", "newname", "dir"); 43 | } catch (e) { 44 | err = e; 45 | } 46 | assertEqual(err.message, "Not implemented"); 47 | }); 48 | 49 | testPerm({ read: true, write: true }, async function symlinkSuccess() { 50 | const testDir = Deno.makeTempDirSync(); 51 | const oldname = testDir + "/oldname"; 52 | const newname = testDir + "/newname"; 53 | Deno.mkdirSync(oldname); 54 | let errOnWindows; 55 | // Just for now, until we implement symlink for Windows. 56 | try { 57 | await Deno.symlink(oldname, newname); 58 | } catch (e) { 59 | errOnWindows = e; 60 | } 61 | if (errOnWindows) { 62 | assertEqual(errOnWindows.kind, Deno.ErrorKind.Other); 63 | assertEqual(errOnWindows.message, "Not implemented"); 64 | } else { 65 | const newNameInfoLStat = Deno.lstatSync(newname); 66 | const newNameInfoStat = Deno.statSync(newname); 67 | assert(newNameInfoLStat.isSymlink()); 68 | assert(newNameInfoStat.isDirectory()); 69 | } 70 | }); 71 | -------------------------------------------------------------------------------- /js/event_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assertEqual } from "./test_util.ts"; 3 | 4 | test(function eventInitializedWithType() { 5 | const type = "click"; 6 | const event = new Event(type); 7 | 8 | assertEqual(event.isTrusted, false); 9 | assertEqual(event.target, null); 10 | assertEqual(event.currentTarget, null); 11 | assertEqual(event.type, "click"); 12 | assertEqual(event.bubbles, false); 13 | assertEqual(event.cancelable, false); 14 | }); 15 | 16 | test(function eventInitializedWithTypeAndDict() { 17 | const init = "submit"; 18 | const eventInitDict = new EventInit({ bubbles: true, cancelable: true }); 19 | const event = new Event(init, eventInitDict); 20 | 21 | assertEqual(event.isTrusted, false); 22 | assertEqual(event.target, null); 23 | assertEqual(event.currentTarget, null); 24 | assertEqual(event.type, "submit"); 25 | assertEqual(event.bubbles, true); 26 | assertEqual(event.cancelable, true); 27 | }); 28 | 29 | test(function eventComposedPathSuccess() { 30 | const type = "click"; 31 | const event = new Event(type); 32 | const composedPath = event.composedPath(); 33 | 34 | assertEqual(composedPath, []); 35 | }); 36 | 37 | test(function eventStopPropagationSuccess() { 38 | const type = "click"; 39 | const event = new Event(type); 40 | 41 | assertEqual(event.cancelBubble, false); 42 | event.stopPropagation(); 43 | assertEqual(event.cancelBubble, true); 44 | }); 45 | 46 | test(function eventStopImmediatePropagationSuccess() { 47 | const type = "click"; 48 | const event = new Event(type); 49 | 50 | assertEqual(event.cancelBubble, false); 51 | assertEqual(event.cancelBubbleImmediately, false); 52 | event.stopImmediatePropagation(); 53 | assertEqual(event.cancelBubble, true); 54 | assertEqual(event.cancelBubbleImmediately, true); 55 | }); 56 | 57 | test(function eventPreventDefaultSuccess() { 58 | const type = "click"; 59 | const event = new Event(type); 60 | 61 | assertEqual(event.defaultPrevented, false); 62 | event.preventDefault(); 63 | assertEqual(event.defaultPrevented, false); 64 | 65 | const eventInitDict = new EventInit({ bubbles: true, cancelable: true }); 66 | const cancelableEvent = new Event(type, eventInitDict); 67 | assertEqual(cancelableEvent.defaultPrevented, false); 68 | cancelableEvent.preventDefault(); 69 | assertEqual(cancelableEvent.defaultPrevented, true); 70 | }); 71 | -------------------------------------------------------------------------------- /js/read_dir_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | type FileInfo = Deno.FileInfo; 5 | 6 | function assertSameContent(files: FileInfo[]) { 7 | let counter = 0; 8 | 9 | for (const file of files) { 10 | if (file.name === "subdir") { 11 | assert(file.isDirectory()); 12 | counter++; 13 | } 14 | 15 | if (file.name === "002_hello.ts") { 16 | assertEqual(file.path, `tests/${file.name}`); 17 | assertEqual(file.mode!, Deno.statSync(`tests/${file.name}`).mode!); 18 | counter++; 19 | } 20 | } 21 | 22 | assertEqual(counter, 2); 23 | } 24 | 25 | testPerm({ read: true }, function readDirSyncSuccess() { 26 | const files = Deno.readDirSync("tests/"); 27 | assertSameContent(files); 28 | }); 29 | 30 | testPerm({ read: false }, function readDirSyncPerm() { 31 | let caughtError = false; 32 | try { 33 | const files = Deno.readDirSync("tests/"); 34 | } catch (e) { 35 | caughtError = true; 36 | assertEqual(e.kind, Deno.ErrorKind.PermissionDenied); 37 | assertEqual(e.name, "PermissionDenied"); 38 | } 39 | assert(caughtError); 40 | }); 41 | 42 | testPerm({ read: true }, function readDirSyncNotDir() { 43 | let caughtError = false; 44 | let src; 45 | 46 | try { 47 | src = Deno.readDirSync("package.json"); 48 | } catch (err) { 49 | caughtError = true; 50 | assertEqual(err.kind, Deno.ErrorKind.Other); 51 | } 52 | assert(caughtError); 53 | assertEqual(src, undefined); 54 | }); 55 | 56 | testPerm({ read: true }, function readDirSyncNotFound() { 57 | let caughtError = false; 58 | let src; 59 | 60 | try { 61 | src = Deno.readDirSync("bad_dir_name"); 62 | } catch (err) { 63 | caughtError = true; 64 | assertEqual(err.kind, Deno.ErrorKind.NotFound); 65 | } 66 | assert(caughtError); 67 | assertEqual(src, undefined); 68 | }); 69 | 70 | testPerm({ read: true }, async function readDirSuccess() { 71 | const files = await Deno.readDir("tests/"); 72 | assertSameContent(files); 73 | }); 74 | 75 | testPerm({ read: false }, async function readDirPerm() { 76 | let caughtError = false; 77 | try { 78 | const files = await Deno.readDir("tests/"); 79 | } catch (e) { 80 | caughtError = true; 81 | assertEqual(e.kind, Deno.ErrorKind.PermissionDenied); 82 | assertEqual(e.name, "PermissionDenied"); 83 | } 84 | assert(caughtError); 85 | }); 86 | -------------------------------------------------------------------------------- /tools/testdata/strace_summary.out: -------------------------------------------------------------------------------- 1 | % time seconds usecs/call calls errors syscall 2 | ------ ----------- ----------- --------- --------- ---------------- 3 | 65.76 0.005881 98 60 munmap 4 | 13.79 0.001233 2 462 mprotect 5 | 7.13 0.000638 11 56 mmap 6 | 3.57 0.000319 22 14 openat 7 | 1.65 0.000148 10 14 fstat 8 | 1.58 0.000141 7 20 read 9 | 1.53 0.000137 7 18 close 10 | 1.49 0.000133 16 8 madvise 11 | 1.10 0.000098 98 1 execve 12 | 0.30 0.000027 9 3 prctl 13 | 0.29 0.000026 26 1 1 access 14 | 0.25 0.000022 11 2 2 mkdir 15 | 0.23 0.000021 7 3 write 16 | 0.18 0.000016 4 4 set_robust_list 17 | 0.16 0.000014 7 2 brk 18 | 0.15 0.000013 13 1 pipe2 19 | 0.11 0.000010 3 3 clone 20 | 0.11 0.000010 3 3 sigaltstack 21 | 0.10 0.000009 4 2 stat 22 | 0.10 0.000009 9 1 arch_prctl 23 | 0.10 0.000009 9 1 epoll_create1 24 | 0.09 0.000008 8 1 epoll_ctl 25 | 0.08 0.000007 3 2 getrandom 26 | 0.04 0.000004 4 1 getcwd 27 | 0.04 0.000004 2 2 sched_getaffinity 28 | 0.03 0.000003 3 1 1 ioctl 29 | 0.03 0.000003 1 3 futex 30 | 0.00 0.000000 0 1 open 31 | 0.00 0.000000 0 5 rt_sigaction 32 | 0.00 0.000000 0 1 rt_sigprocmask 33 | 0.00 0.000000 0 1 fcntl 34 | 0.00 0.000000 0 1 1 readlink 35 | 0.00 0.000000 0 1 set_tid_address 36 | 0.00 0.000000 0 3 epoll_wait 37 | 0.00 0.000000 0 2 prlimit64 38 | ------ ----------- ----------- --------- --------- ---------------- 39 | 100.00 0.008943 704 5 total 40 | -------------------------------------------------------------------------------- /js/truncate_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { testPerm, assertEqual } from "./test_util.ts"; 3 | 4 | function readDataSync(name: string): string { 5 | const data = Deno.readFileSync(name); 6 | const decoder = new TextDecoder("utf-8"); 7 | const text = decoder.decode(data); 8 | return text; 9 | } 10 | 11 | async function readData(name: string): Promise { 12 | const data = await Deno.readFile(name); 13 | const decoder = new TextDecoder("utf-8"); 14 | const text = decoder.decode(data); 15 | return text; 16 | } 17 | 18 | testPerm({ read: true, write: true }, function truncateSyncSuccess() { 19 | const enc = new TextEncoder(); 20 | const d = enc.encode("Hello"); 21 | const filename = Deno.makeTempDirSync() + "/test_truncateSync.txt"; 22 | Deno.writeFileSync(filename, d); 23 | Deno.truncateSync(filename, 20); 24 | let data = readDataSync(filename); 25 | assertEqual(data.length, 20); 26 | Deno.truncateSync(filename, 5); 27 | data = readDataSync(filename); 28 | assertEqual(data.length, 5); 29 | Deno.truncateSync(filename, -5); 30 | data = readDataSync(filename); 31 | assertEqual(data.length, 0); 32 | Deno.removeSync(filename); 33 | }); 34 | 35 | testPerm({ read: true, write: true }, async function truncateSuccess() { 36 | const enc = new TextEncoder(); 37 | const d = enc.encode("Hello"); 38 | const filename = Deno.makeTempDirSync() + "/test_truncate.txt"; 39 | await Deno.writeFile(filename, d); 40 | await Deno.truncate(filename, 20); 41 | let data = await readData(filename); 42 | assertEqual(data.length, 20); 43 | await Deno.truncate(filename, 5); 44 | data = await readData(filename); 45 | assertEqual(data.length, 5); 46 | await Deno.truncate(filename, -5); 47 | data = await readData(filename); 48 | assertEqual(data.length, 0); 49 | await Deno.remove(filename); 50 | }); 51 | 52 | testPerm({ write: false }, function truncateSyncPerm() { 53 | let err; 54 | try { 55 | Deno.mkdirSync("/test_truncateSyncPermission.txt"); 56 | } catch (e) { 57 | err = e; 58 | } 59 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 60 | assertEqual(err.name, "PermissionDenied"); 61 | }); 62 | 63 | testPerm({ write: false }, async function truncatePerm() { 64 | let err; 65 | try { 66 | await Deno.mkdir("/test_truncatePermission.txt"); 67 | } catch (e) { 68 | err = e; 69 | } 70 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 71 | assertEqual(err.name, "PermissionDenied"); 72 | }); 73 | -------------------------------------------------------------------------------- /js/mixins/dom_iterable_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, assert, assertEqual } from "../test_util.ts"; 3 | 4 | function setup() { 5 | const dataSymbol = Symbol("data symbol"); 6 | class Base { 7 | private [dataSymbol] = new Map(); 8 | 9 | constructor( 10 | data: Array<[string, number]> | IterableIterator<[string, number]> 11 | ) { 12 | for (const [key, value] of data) { 13 | this[dataSymbol].set(key, value); 14 | } 15 | } 16 | } 17 | 18 | return { 19 | Base, 20 | // This is using an internal API we don't want published as types, so having 21 | // to cast to any to "trick" TypeScript 22 | // tslint:disable-next-line:no-any 23 | DomIterable: (Deno as any).DomIterableMixin(Base, dataSymbol) 24 | }; 25 | } 26 | 27 | test(function testDomIterable() { 28 | // tslint:disable-next-line:variable-name 29 | const { DomIterable, Base } = setup(); 30 | 31 | const fixture: Array<[string, number]> = [["foo", 1], ["bar", 2]]; 32 | 33 | const domIterable = new DomIterable(fixture); 34 | 35 | assertEqual(Array.from(domIterable.entries()), fixture); 36 | assertEqual(Array.from(domIterable.values()), [1, 2]); 37 | assertEqual(Array.from(domIterable.keys()), ["foo", "bar"]); 38 | 39 | let result: Array<[string, number]> = []; 40 | for (const [key, value] of domIterable) { 41 | assert(key != null); 42 | assert(value != null); 43 | result.push([key, value]); 44 | } 45 | assertEqual(fixture, result); 46 | 47 | result = []; 48 | const scope = {}; 49 | function callback(value, key, parent) { 50 | assertEqual(parent, domIterable); 51 | assert(key != null); 52 | assert(value != null); 53 | assert(this === scope); 54 | result.push([key, value]); 55 | } 56 | domIterable.forEach(callback, scope); 57 | assertEqual(fixture, result); 58 | 59 | assertEqual(DomIterable.name, Base.name); 60 | }); 61 | 62 | test(function testDomIterableScope() { 63 | // tslint:disable-next-line:variable-name 64 | const { DomIterable } = setup(); 65 | 66 | const domIterable = new DomIterable([["foo", 1]]); 67 | 68 | // tslint:disable-next-line:no-any 69 | function checkScope(thisArg: any, expected: any) { 70 | function callback() { 71 | assertEqual(this, expected); 72 | } 73 | domIterable.forEach(callback, thisArg); 74 | } 75 | 76 | checkScope(0, Object(0)); 77 | checkScope("", Object("")); 78 | checkScope(null, window); 79 | checkScope(undefined, window); 80 | }); 81 | -------------------------------------------------------------------------------- /js/write_file.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | 6 | /** Options for writing to a file. 7 | * `perm` would change the file's permission if set. 8 | * `create` decides if the file should be created if not exists (default: true) 9 | * `append` decides if the file should be appended (default: false) 10 | */ 11 | export interface WriteFileOptions { 12 | perm?: number; 13 | create?: boolean; 14 | append?: boolean; 15 | } 16 | 17 | /** Write a new file, with given filename and data synchronously. 18 | * 19 | * const encoder = new TextEncoder(); 20 | * const data = encoder.encode("Hello world\n"); 21 | * Deno.writeFileSync("hello.txt", data); 22 | */ 23 | export function writeFileSync( 24 | filename: string, 25 | data: Uint8Array, 26 | options: WriteFileOptions = {} 27 | ): void { 28 | dispatch.sendSync(...req(filename, data, options)); 29 | } 30 | 31 | /** Write a new file, with given filename and data. 32 | * 33 | * const encoder = new TextEncoder(); 34 | * const data = encoder.encode("Hello world\n"); 35 | * await Deno.writeFile("hello.txt", data); 36 | */ 37 | export async function writeFile( 38 | filename: string, 39 | data: Uint8Array, 40 | options: WriteFileOptions = {} 41 | ): Promise { 42 | await dispatch.sendAsync(...req(filename, data, options)); 43 | } 44 | 45 | function req( 46 | filename: string, 47 | data: Uint8Array, 48 | options: WriteFileOptions 49 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset, Uint8Array] { 50 | const builder = flatbuffers.createBuilder(); 51 | const filename_ = builder.createString(filename); 52 | msg.WriteFile.startWriteFile(builder); 53 | msg.WriteFile.addFilename(builder, filename_); 54 | // Perm is not updated by default 55 | if (options.perm !== undefined && options.perm !== null) { 56 | msg.WriteFile.addUpdatePerm(builder, true); 57 | msg.WriteFile.addPerm(builder, options.perm!); 58 | } else { 59 | msg.WriteFile.addUpdatePerm(builder, false); 60 | msg.WriteFile.addPerm(builder, 0o666); 61 | } 62 | // Create is turned on by default 63 | if (options.create !== undefined) { 64 | msg.WriteFile.addIsCreate(builder, !!options.create); 65 | } else { 66 | msg.WriteFile.addIsCreate(builder, true); 67 | } 68 | msg.WriteFile.addIsAppend(builder, !!options.append); 69 | const inner = msg.WriteFile.endWriteFile(builder); 70 | return [builder, msg.Any.WriteFile, inner, data]; 71 | } 72 | -------------------------------------------------------------------------------- /js/stat.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import * as msg from "gen/msg_generated"; 3 | import * as flatbuffers from "./flatbuffers"; 4 | import * as dispatch from "./dispatch"; 5 | import { assert } from "./util"; 6 | import { FileInfo, FileInfoImpl } from "./file_info"; 7 | 8 | /** Queries the file system for information on the path provided. If the given 9 | * path is a symlink information about the symlink will be returned. 10 | * 11 | * const fileInfo = await Deno.lstat("hello.txt"); 12 | * assert(fileInfo.isFile()); 13 | */ 14 | export async function lstat(filename: string): Promise { 15 | return res(await dispatch.sendAsync(...req(filename, true))); 16 | } 17 | 18 | /** Queries the file system for information on the path provided synchronously. 19 | * If the given path is a symlink information about the symlink will be 20 | * returned. 21 | * 22 | * const fileInfo = Deno.lstatSync("hello.txt"); 23 | * assert(fileInfo.isFile()); 24 | */ 25 | export function lstatSync(filename: string): FileInfo { 26 | return res(dispatch.sendSync(...req(filename, true))); 27 | } 28 | 29 | /** Queries the file system for information on the path provided. `stat` Will 30 | * always follow symlinks. 31 | * 32 | * const fileInfo = await Deno.stat("hello.txt"); 33 | * assert(fileInfo.isFile()); 34 | */ 35 | export async function stat(filename: string): Promise { 36 | return res(await dispatch.sendAsync(...req(filename, false))); 37 | } 38 | 39 | /** Queries the file system for information on the path provided synchronously. 40 | * `statSync` Will always follow symlinks. 41 | * 42 | * const fileInfo = Deno.statSync("hello.txt"); 43 | * assert(fileInfo.isFile()); 44 | */ 45 | export function statSync(filename: string): FileInfo { 46 | return res(dispatch.sendSync(...req(filename, false))); 47 | } 48 | 49 | function req( 50 | filename: string, 51 | lstat: boolean 52 | ): [flatbuffers.Builder, msg.Any, flatbuffers.Offset] { 53 | const builder = flatbuffers.createBuilder(); 54 | const filename_ = builder.createString(filename); 55 | msg.Stat.startStat(builder); 56 | msg.Stat.addFilename(builder, filename_); 57 | msg.Stat.addLstat(builder, lstat); 58 | const inner = msg.Stat.endStat(builder); 59 | return [builder, msg.Any.Stat, inner]; 60 | } 61 | 62 | function res(baseRes: null | msg.Base): FileInfo { 63 | assert(baseRes != null); 64 | assert(msg.Any.StatRes === baseRes!.innerType()); 65 | const res = new msg.StatRes(); 66 | assert(baseRes!.inner(res) != null); 67 | return new FileInfoImpl(res); 68 | } 69 | -------------------------------------------------------------------------------- /tools/unit_tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 3 | import util 4 | import sys 5 | import subprocess 6 | import re 7 | 8 | 9 | def run_unit_test2(cmd): 10 | process = subprocess.Popen( 11 | cmd, 12 | bufsize=1, 13 | universal_newlines=True, 14 | stdout=subprocess.PIPE, 15 | stderr=subprocess.STDOUT) 16 | (actual, expected) = util.parse_unit_test_output(process.stdout, True) 17 | process.wait() 18 | errcode = process.returncode 19 | if errcode != 0: 20 | sys.exit(errcode) 21 | if actual == None and expected == None: 22 | raise AssertionError("Bad js/unit_test.ts output") 23 | if expected != actual: 24 | print "expected", expected, "actual", actual 25 | raise AssertionError("expected tests did not equal actual") 26 | process.wait() 27 | errcode = process.returncode 28 | if errcode != 0: 29 | sys.exit(errcode) 30 | 31 | 32 | def run_unit_test(deno_exe, permStr, flags=None): 33 | if flags is None: 34 | flags = [] 35 | cmd = [deno_exe, "--reload", "js/unit_tests.ts", permStr] + flags 36 | run_unit_test2(cmd) 37 | 38 | 39 | # We want to test many ops in deno which have different behavior depending on 40 | # the permissions set. These tests can specify which permissions they expect, 41 | # which appends a special string like "permW1N0" to the end of the test name. 42 | # Here we run several copies of deno with different permissions, filtering the 43 | # tests by the special string. permW0N0 means allow-write but not allow-net. 44 | # See js/test_util.ts for more details. 45 | def unit_tests(deno_exe): 46 | run_unit_test(deno_exe, "permR0W0N0E0U0") 47 | run_unit_test(deno_exe, "permR1W0N0E0U0", ["--allow-read"]) 48 | run_unit_test(deno_exe, "permR0W1N0E0U0", ["--allow-write"]) 49 | run_unit_test(deno_exe, "permR1W1N0E0U0", 50 | ["--allow-read", "--allow-write"]) 51 | run_unit_test(deno_exe, "permR1W0N1E0U0", ["--allow-read", "--allow-net"]) 52 | run_unit_test(deno_exe, "permR0W0N0E1U0", ["--allow-env"]) 53 | run_unit_test(deno_exe, "permR0W0N0E0U1", ["--allow-run"]) 54 | run_unit_test(deno_exe, "permR0W1N0E0U1", ["--allow-run", "--allow-write"]) 55 | # TODO We might accidentally miss some. We should be smarter about which we 56 | # run. Maybe we can use the "filtered out" number to check this. 57 | 58 | 59 | if __name__ == '__main__': 60 | if len(sys.argv) < 2: 61 | print "Usage ./tools/unit_tests.py target/debug/deno" 62 | sys.exit(1) 63 | unit_tests(sys.argv[1]) 64 | -------------------------------------------------------------------------------- /js/make_temp_dir_test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | import { test, testPerm, assert, assertEqual } from "./test_util.ts"; 3 | 4 | testPerm({ write: true }, function makeTempDirSyncSuccess() { 5 | const dir1 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" }); 6 | const dir2 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" }); 7 | // Check that both dirs are different. 8 | assert(dir1 !== dir2); 9 | for (const dir of [dir1, dir2]) { 10 | // Check that the prefix and suffix are applied. 11 | const lastPart = dir.replace(/^.*[\\\/]/, ""); 12 | assert(lastPart.startsWith("hello")); 13 | assert(lastPart.endsWith("world")); 14 | } 15 | // Check that the `dir` option works. 16 | const dir3 = Deno.makeTempDirSync({ dir: dir1 }); 17 | assert(dir3.startsWith(dir1)); 18 | assert(/^[\\\/]/.test(dir3.slice(dir1.length))); 19 | // Check that creating a temp dir inside a nonexisting directory fails. 20 | let err; 21 | try { 22 | Deno.makeTempDirSync({ dir: "/baddir" }); 23 | } catch (err_) { 24 | err = err_; 25 | } 26 | assertEqual(err.kind, Deno.ErrorKind.NotFound); 27 | assertEqual(err.name, "NotFound"); 28 | }); 29 | 30 | test(function makeTempDirSyncPerm() { 31 | // makeTempDirSync should require write permissions (for now). 32 | let err; 33 | try { 34 | Deno.makeTempDirSync({ dir: "/baddir" }); 35 | } catch (err_) { 36 | err = err_; 37 | } 38 | assertEqual(err.kind, Deno.ErrorKind.PermissionDenied); 39 | assertEqual(err.name, "PermissionDenied"); 40 | }); 41 | 42 | testPerm({ write: true }, async function makeTempDirSuccess() { 43 | const dir1 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); 44 | const dir2 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); 45 | // Check that both dirs are different. 46 | assert(dir1 !== dir2); 47 | for (const dir of [dir1, dir2]) { 48 | // Check that the prefix and suffix are applied. 49 | const lastPart = dir.replace(/^.*[\\\/]/, ""); 50 | assert(lastPart.startsWith("hello")); 51 | assert(lastPart.endsWith("world")); 52 | } 53 | // Check that the `dir` option works. 54 | const dir3 = await Deno.makeTempDir({ dir: dir1 }); 55 | assert(dir3.startsWith(dir1)); 56 | assert(/^[\\\/]/.test(dir3.slice(dir1.length))); 57 | // Check that creating a temp dir inside a nonexisting directory fails. 58 | let err; 59 | try { 60 | await Deno.makeTempDir({ dir: "/baddir" }); 61 | } catch (err_) { 62 | err = err_; 63 | } 64 | assertEqual(err.kind, Deno.ErrorKind.NotFound); 65 | assertEqual(err.name, "NotFound"); 66 | }); 67 | -------------------------------------------------------------------------------- /libdeno/file_util.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #ifdef __APPLE__ 12 | #include 13 | #endif 14 | 15 | #ifdef _WIN32 16 | #include 17 | #endif 18 | 19 | #include "file_util.h" 20 | 21 | namespace deno { 22 | 23 | bool ReadFileToString(const char* fn, std::string* contents) { 24 | std::ifstream file(fn, std::ios::binary); 25 | if (file.fail()) { 26 | return false; 27 | } 28 | contents->assign(std::istreambuf_iterator{file}, {}); 29 | return !file.fail(); 30 | } 31 | 32 | std::string Basename(std::string const& filename) { 33 | for (auto it = filename.rbegin(); it != filename.rend(); ++it) { 34 | char ch = *it; 35 | if (ch == '\\' || ch == '/') { 36 | return std::string(it.base(), filename.end()); 37 | } 38 | } 39 | return filename; 40 | } 41 | 42 | // Returns the directory component from a filename. The returned path always 43 | // ends with a slash. This function does not understand Windows drive letters. 44 | std::string Dirname(std::string const& filename) { 45 | for (auto it = filename.rbegin(); it != filename.rend(); ++it) { 46 | char ch = *it; 47 | if (ch == '\\' || ch == '/') { 48 | return std::string(filename.begin(), it.base()); 49 | } 50 | } 51 | return std::string("./"); 52 | } 53 | 54 | // Returns the full path the currently running executable. 55 | // This implementation is very basic. Caveats: 56 | // * OS X: fails if buffer is too small, does not retry with a bigger buffer. 57 | // * Windows: ANSI only, no unicode. Fails if path is longer than 260 chars. 58 | bool ExePath(std::string* path) { 59 | #ifdef _WIN32 60 | // Windows only. 61 | char exe_buf[MAX_PATH]; 62 | DWORD len = GetModuleFileNameA(NULL, exe_buf, sizeof exe_buf); 63 | if (len == 0 || len == sizeof exe_buf) { 64 | return false; 65 | } 66 | #else 67 | #ifdef __APPLE__ 68 | // OS X only. 69 | char link_buf[PATH_MAX * 2]; // Exe may be longer than MAX_PATH, says Apple. 70 | uint32_t len = sizeof link_buf; 71 | if (_NSGetExecutablePath(link_buf, &len) < 0) { 72 | return false; 73 | } 74 | #else 75 | // Linux only. 76 | static const char* link_buf = "/proc/self/exe"; 77 | #endif 78 | // Linux and OS X. 79 | char exe_buf[PATH_MAX]; 80 | char* r = realpath(link_buf, exe_buf); 81 | if (r == NULL) { 82 | return false; 83 | } 84 | #endif 85 | // All platforms. 86 | path->assign(exe_buf); 87 | return true; 88 | } 89 | 90 | } // namespace deno 91 | --------------------------------------------------------------------------------