summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--cli/js/buffer.ts88
-rw-r--r--cli/js/build.ts2
-rw-r--r--cli/js/colors.ts2
-rw-r--r--cli/js/compiler.ts44
-rw-r--r--cli/js/compiler/api.ts10
-rw-r--r--cli/js/compiler/bootstrap.ts4
-rw-r--r--cli/js/compiler/bundler.ts8
-rw-r--r--cli/js/compiler/host.ts90
-rw-r--r--cli/js/compiler/imports.ts4
-rw-r--r--cli/js/compiler/sourcefile.ts32
-rw-r--r--cli/js/compiler/type_directives.ts4
-rw-r--r--cli/js/compiler/util.ts6
-rw-r--r--cli/js/deno.ts16
-rw-r--r--cli/js/diagnostics.ts2
-rw-r--r--cli/js/diagnostics_util.ts12
-rw-r--r--cli/js/error_stack.ts4
-rw-r--r--cli/js/errors.ts4
-rw-r--r--cli/js/file_info.ts38
-rw-r--r--cli/js/files.ts6
-rw-r--r--cli/js/globals.ts14
-rw-r--r--cli/js/internals.ts2
-rw-r--r--cli/js/io.ts6
-rw-r--r--cli/js/lib.deno.ns.d.ts20
-rw-r--r--cli/js/lib.deno.shared_globals.d.ts224
-rw-r--r--cli/js/main.ts6
-rw-r--r--cli/js/net.ts4
-rw-r--r--cli/js/ops/compiler.ts4
-rw-r--r--cli/js/ops/dispatch_minimal.ts2
-rw-r--r--cli/js/ops/errors.ts4
-rw-r--r--cli/js/ops/fs/open.ts2
-rw-r--r--cli/js/ops/fs/stat.ts8
-rw-r--r--cli/js/ops/fs/utime.ts4
-rw-r--r--cli/js/ops/fs_events.ts2
-rw-r--r--cli/js/ops/net.ts2
-rw-r--r--cli/js/ops/os.ts2
-rw-r--r--cli/js/ops/tty.ts2
-rw-r--r--cli/js/ops/worker_host.ts2
-rw-r--r--cli/js/plugins.ts18
-rw-r--r--cli/js/process.ts4
-rw-r--r--cli/js/rbtree.ts77
-rw-r--r--cli/js/repl.ts18
-rw-r--r--cli/js/runtime_main.ts6
-rw-r--r--cli/js/runtime_worker.ts4
-rw-r--r--cli/js/signals.ts41
-rw-r--r--cli/js/symbols.ts2
-rw-r--r--cli/js/testing.ts78
-rw-r--r--cli/js/tests/blob_test.ts4
-rw-r--r--cli/js/tests/body_test.ts4
-rw-r--r--cli/js/tests/buffer_test.ts2
-rw-r--r--cli/js/tests/chmod_test.ts4
-rw-r--r--cli/js/tests/chown_test.ts4
-rw-r--r--cli/js/tests/console_test.ts31
-rw-r--r--cli/js/tests/custom_event_test.ts2
-rw-r--r--cli/js/tests/dispatch_minimal_test.ts2
-rw-r--r--cli/js/tests/dom_iterable_test.ts6
-rw-r--r--cli/js/tests/error_stack_test.ts6
-rw-r--r--cli/js/tests/event_target_test.ts8
-rw-r--r--cli/js/tests/fetch_test.ts58
-rw-r--r--cli/js/tests/file_test.ts2
-rw-r--r--cli/js/tests/files_test.ts26
-rw-r--r--cli/js/tests/form_data_test.ts4
-rw-r--r--cli/js/tests/format_error_test.ts4
-rw-r--r--cli/js/tests/headers_test.ts8
-rw-r--r--cli/js/tests/internals_test.ts2
-rw-r--r--cli/js/tests/net_test.ts34
-rw-r--r--cli/js/tests/os_test.ts66
-rw-r--r--cli/js/tests/process_test.ts42
-rw-r--r--cli/js/tests/realpath_test.ts4
-rw-r--r--cli/js/tests/request_test.ts6
-rw-r--r--cli/js/tests/signal_test.ts2
-rw-r--r--cli/js/tests/test_util.ts50
-rw-r--r--cli/js/tests/testing_test.ts4
-rw-r--r--cli/js/tests/text_encoding_test.ts2
-rw-r--r--cli/js/tests/timers_test.ts10
-rw-r--r--cli/js/tests/tls_test.ts30
-rw-r--r--cli/js/tests/umask_test.ts2
-rwxr-xr-xcli/js/tests/unit_test_runner.ts18
-rw-r--r--cli/js/tests/url_search_params_test.ts8
-rw-r--r--cli/js/tests/url_test.ts8
-rw-r--r--cli/js/tests/utime_test.ts4
-rw-r--r--cli/js/tls.ts8
-rw-r--r--cli/js/util.ts2
-rw-r--r--cli/js/version.ts2
-rw-r--r--cli/js/web/blob.ts11
-rw-r--r--cli/js/web/body.ts8
-rw-r--r--cli/js/web/console.ts30
-rw-r--r--cli/js/web/console_table.ts2
-rw-r--r--cli/js/web/custom_event.ts23
-rw-r--r--cli/js/web/dom_iterable.ts2
-rw-r--r--cli/js/web/dom_types.ts163
-rw-r--r--cli/js/web/dom_util.ts17
-rw-r--r--cli/js/web/event.ts22
-rw-r--r--cli/js/web/event_target.ts18
-rw-r--r--cli/js/web/fetch.ts102
-rw-r--r--cli/js/web/form_data.ts8
-rw-r--r--cli/js/web/headers.ts80
-rw-r--r--cli/js/web/location.ts15
-rw-r--r--cli/js/web/request.ts2
-rw-r--r--cli/js/web/streams/readable-byte-stream-controller.ts2
-rw-r--r--cli/js/web/streams/readable-internals.ts22
-rw-r--r--cli/js/web/streams/readable-stream.ts14
-rw-r--r--cli/js/web/streams/shared-internals.ts14
-rw-r--r--cli/js/web/text_encoding.ts191
-rw-r--r--cli/js/web/timers.ts2
-rw-r--r--cli/js/web/url.ts97
-rw-r--r--cli/js/web/url_search_params.ts167
-rw-r--r--cli/js/web/util.ts17
-rw-r--r--cli/js/web/workers.ts41
-rw-r--r--cli/tests/015_duplicate_parallel_import.js2
-rw-r--r--cli/tests/045_proxy_test.ts12
-rw-r--r--cli/tests/053_import_compression/main.ts4
-rw-r--r--cli/tests/057_revoke_permissions.ts2
-rw-r--r--cli/tests/cafile_ts_fetch.ts4
-rw-r--r--cli/tests/compiler_api_test.ts32
-rw-r--r--cli/tests/complex_permissions_test.ts14
-rw-r--r--cli/tests/error_003_typescript.ts12
-rw-r--r--cli/tests/lib_ref.ts4
-rw-r--r--cli/tests/lib_runtime_api.ts4
-rw-r--r--cli/tests/lock_write_fetch.ts10
-rw-r--r--cli/tests/permission_test.ts6
-rw-r--r--cli/tests/subdir/bench_worker.ts4
-rw-r--r--cli/tests/subdir/nested_worker.js8
-rw-r--r--cli/tests/subdir/sibling_worker.js2
-rw-r--r--cli/tests/subdir/test_worker.js4
-rw-r--r--cli/tests/subdir/test_worker.ts2
-rw-r--r--cli/tests/subdir/test_worker_basic.js4
-rw-r--r--cli/tests/workers_test.ts26
-rw-r--r--core/examples/http_bench.js2
-rw-r--r--core/shared_queue.js6
-rw-r--r--deno_typescript/compiler_main.js10
-rw-r--r--deno_typescript/system_loader.js12
-rw-r--r--std/archive/tar.ts46
-rw-r--r--std/archive/tar_test.ts6
-rw-r--r--std/bytes/test.ts4
-rw-r--r--std/datetime/README.md2
-rw-r--r--std/datetime/mod.ts2
-rw-r--r--std/datetime/test.ts4
-rw-r--r--std/encoding/README.md6
-rw-r--r--std/encoding/base32_test.ts38
-rw-r--r--std/encoding/binary.ts2
-rw-r--r--std/encoding/binary_test.ts2
-rw-r--r--std/encoding/csv.ts8
-rw-r--r--std/encoding/csv_test.ts204
-rw-r--r--std/encoding/hex_test.ts24
-rw-r--r--std/encoding/mod.ts4
-rw-r--r--std/encoding/toml_test.ts118
-rw-r--r--std/encoding/yaml.ts2
-rw-r--r--std/encoding/yaml/dumper/dumper.ts2
-rw-r--r--std/encoding/yaml/dumper/dumper_state.ts2
-rw-r--r--std/encoding/yaml/example/dump.ts10
-rw-r--r--std/encoding/yaml/example/inout.ts10
-rw-r--r--std/encoding/yaml/loader/loader.ts22
-rw-r--r--std/encoding/yaml/loader/loader_state.ts2
-rw-r--r--std/encoding/yaml/parse_test.ts12
-rw-r--r--std/encoding/yaml/schema.ts2
-rw-r--r--std/encoding/yaml/schema/core.ts2
-rw-r--r--std/encoding/yaml/schema/default.ts2
-rw-r--r--std/encoding/yaml/schema/failsafe.ts2
-rw-r--r--std/encoding/yaml/schema/json.ts2
-rw-r--r--std/encoding/yaml/stringify_test.ts12
-rw-r--r--std/encoding/yaml/type/binary.ts2
-rw-r--r--std/encoding/yaml/type/bool.ts4
-rw-r--r--std/encoding/yaml/type/float.ts2
-rw-r--r--std/encoding/yaml/type/int.ts21
-rw-r--r--std/encoding/yaml/type/map.ts2
-rw-r--r--std/encoding/yaml/type/merge.ts2
-rw-r--r--std/encoding/yaml/type/nil.ts4
-rw-r--r--std/encoding/yaml/type/omap.ts2
-rw-r--r--std/encoding/yaml/type/pairs.ts2
-rw-r--r--std/encoding/yaml/type/seq.ts2
-rw-r--r--std/encoding/yaml/type/set.ts2
-rw-r--r--std/encoding/yaml/type/str.ts2
-rw-r--r--std/encoding/yaml/type/timestamp.ts2
-rw-r--r--std/examples/chat/server.ts20
-rw-r--r--std/examples/chat/server_test.ts6
-rwxr-xr-xstd/examples/gist.ts6
-rw-r--r--std/examples/test.ts4
-rw-r--r--std/examples/tests/cat_test.ts4
-rw-r--r--std/examples/tests/catj_test.ts6
-rw-r--r--std/examples/tests/colors_test.ts2
-rw-r--r--std/examples/tests/curl_test.ts4
-rw-r--r--std/examples/tests/echo_server_test.ts2
-rw-r--r--std/examples/tests/welcome_test.ts2
-rw-r--r--std/examples/tests/xeval_test.ts12
-rw-r--r--std/examples/xeval.ts8
-rwxr-xr-xstd/flags/all_bool_test.ts8
-rwxr-xr-xstd/flags/bool_test.ts42
-rwxr-xr-xstd/flags/dash_test.ts2
-rwxr-xr-xstd/flags/default_bool_test.ts8
-rwxr-xr-xstd/flags/dotted_test.ts2
-rwxr-xr-xstd/flags/long_test.ts4
-rw-r--r--std/flags/mod.ts12
-rwxr-xr-xstd/flags/num_test.ts4
-rwxr-xr-xstd/flags/parse_test.ts28
-rwxr-xr-xstd/flags/short_test.ts8
-rwxr-xr-xstd/flags/stop_early_test.ts4
-rwxr-xr-xstd/flags/unknown_test.ts14
-rw-r--r--std/fmt/colors.ts2
-rw-r--r--std/fmt/sprintf.ts6
-rw-r--r--std/fmt/sprintf_test.ts11
-rw-r--r--std/fs/README.md6
-rw-r--r--std/fs/copy_test.ts14
-rw-r--r--std/fs/empty_dir_test.ts24
-rw-r--r--std/fs/ensure_link_test.ts2
-rw-r--r--std/fs/ensure_symlink_test.ts2
-rw-r--r--std/fs/eol.ts2
-rw-r--r--std/fs/eol_test.ts10
-rw-r--r--std/fs/exists_test.ts38
-rw-r--r--std/fs/expand_glob.ts24
-rw-r--r--std/fs/expand_glob_test.ts18
-rw-r--r--std/fs/move_test.ts10
-rw-r--r--std/fs/read_json_test.ts2
l---------std/fs/testdata/0-link1
l---------std/fs/testdata/0-link.ts1
-rw-r--r--std/fs/testdata/empty_dir.ts6
-rw-r--r--std/fs/testdata/exists_sync.ts8
-rw-r--r--std/fs/utils_test.ts8
-rw-r--r--std/fs/walk.ts8
-rw-r--r--std/fs/write_json_test.ts6
-rw-r--r--std/http/cookie.ts2
-rw-r--r--std/http/cookie_test.ts28
-rwxr-xr-xstd/http/file_server.ts37
-rw-r--r--std/http/file_server_test.ts8
-rw-r--r--std/http/http_bench.ts2
-rw-r--r--std/http/http_status.ts8
-rw-r--r--std/http/io.ts10
-rw-r--r--std/http/io_test.ts48
-rw-r--r--std/http/mock.ts6
-rw-r--r--std/http/racing_server_test.ts4
-rw-r--r--std/http/server.ts4
-rw-r--r--std/http/server_test.ts38
-rw-r--r--std/io/bufio.ts3
-rw-r--r--std/io/bufio_test.ts12
-rw-r--r--std/io/ioutil_test.ts2
-rw-r--r--std/io/util_test.ts8
-rw-r--r--std/log/README.md12
-rw-r--r--std/log/handlers_test.ts22
-rw-r--r--std/log/levels.ts4
-rw-r--r--std/log/logger.ts2
-rw-r--r--std/log/logger_test.ts4
-rw-r--r--std/log/mod.ts16
-rw-r--r--std/log/test.ts28
-rw-r--r--std/manual.md24
-rw-r--r--std/media_types/test.ts2
-rw-r--r--std/mime/multipart.ts6
-rw-r--r--std/mime/multipart_test.ts4
-rw-r--r--std/node/_fs/_fs_appendFile.ts2
-rw-r--r--std/node/_fs/_fs_appendFile_test.ts30
-rw-r--r--std/node/_fs/_fs_chmod.ts2
-rw-r--r--std/node/_fs/_fs_chmod_test.ts6
-rw-r--r--std/node/_fs/_fs_chown.ts2
-rw-r--r--std/node/_fs/_fs_chown_test.ts6
-rw-r--r--std/node/_fs/_fs_close.ts2
-rw-r--r--std/node/_fs/_fs_close_test.ts6
-rw-r--r--std/node/_fs/_fs_dir.ts4
-rw-r--r--std/node/_fs/_fs_dir_test.ts16
-rw-r--r--std/node/_fs/_fs_dirent_test.ts14
-rw-r--r--std/node/_fs/_fs_readFile.ts2
-rw-r--r--std/node/_fs/_fs_readlink.ts2
-rw-r--r--std/node/_fs/_fs_readlink_test.ts8
-rw-r--r--std/node/_utils.ts8
-rw-r--r--std/node/events.ts8
-rw-r--r--std/node/events_test.ts78
-rwxr-xr-xstd/node/fs.ts2
-rw-r--r--std/node/module.ts46
-rw-r--r--std/node/os.ts2
-rw-r--r--std/node/os_test.ts32
-rw-r--r--std/node/process.ts4
-rw-r--r--std/node/process_test.ts18
-rw-r--r--std/node/querystring.ts2
-rw-r--r--std/node/querystring_test.ts8
-rw-r--r--std/node/tests/cjs/cjs_builtin.js2
-rw-r--r--std/node/tests/node_modules/left-pad/index.js34
-rw-r--r--std/node/util_test.ts26
-rw-r--r--std/path/extname_test.ts6
-rw-r--r--std/path/glob.ts2
-rw-r--r--std/path/glob_test.ts24
-rw-r--r--std/path/globrex.ts4
-rw-r--r--std/path/globrex_test.ts66
-rw-r--r--std/path/join_test.ts10
-rw-r--r--std/path/parse_format_test.ts35
-rw-r--r--std/path/posix.ts5
-rw-r--r--std/path/relative_test.ts94
-rw-r--r--std/path/resolve_test.ts10
-rw-r--r--std/path/utils.ts2
-rw-r--r--std/path/win32.ts15
-rw-r--r--std/permissions/mod.ts2
-rw-r--r--std/permissions/test.ts14
-rw-r--r--std/signal/mod.ts4
-rw-r--r--std/signal/test.ts2
-rw-r--r--std/strings/README.md2
-rw-r--r--std/strings/pad.ts2
-rw-r--r--std/strings/pad_test.ts12
-rw-r--r--std/testing/README.md4
-rw-r--r--std/testing/asserts.ts2
-rw-r--r--std/testing/asserts_test.ts28
-rw-r--r--std/testing/bench.ts6
-rw-r--r--std/testing/bench_example.ts2
-rw-r--r--std/testing/bench_test.ts6
-rw-r--r--std/testing/diff.ts15
-rw-r--r--std/testing/diff_test.ts32
-rw-r--r--std/testing/format.ts12
-rw-r--r--std/testing/format_test.ts184
-rwxr-xr-xstd/testing/runner.ts16
-rw-r--r--std/textproto/test.ts24
-rw-r--r--std/types/react-dom.d.ts2
-rw-r--r--std/types/react.d.ts4
-rw-r--r--std/types/tests/react-dom_mock.js2
-rw-r--r--std/types/tests/react_mock.js2
-rw-r--r--std/util/deep_assign_test.ts4
-rw-r--r--std/uuid/mod.ts2
-rw-r--r--std/uuid/tests/isNil.ts2
-rw-r--r--std/uuid/tests/v4/generate.ts4
-rw-r--r--std/uuid/tests/v4/validate.ts2
-rw-r--r--std/uuid/v4.ts2
-rw-r--r--std/ws/README.md8
-rw-r--r--std/ws/example_client.ts4
-rw-r--r--std/ws/example_server.ts4
-rw-r--r--std/ws/mod.ts28
-rw-r--r--std/ws/sha1.ts2
-rw-r--r--std/ws/test.ts46
-rw-r--r--test_plugin/tests/test.js2
m---------third_party0
-rw-r--r--tools/deno_http_proxy.ts2
-rw-r--r--tools/deno_tcp_proxy.ts2
-rw-r--r--tools/node_http_proxy.js4
-rw-r--r--tools/node_tcp.js6
-rw-r--r--tools/node_tcp_promise.js4
-rw-r--r--tools/node_tcp_proxy.js20
329 files changed, 2783 insertions, 2426 deletions
diff --git a/cli/js/buffer.ts b/cli/js/buffer.ts
index db2bb22e4..fcb688b9b 100644
--- a/cli/js/buffer.ts
+++ b/cli/js/buffer.ts
@@ -28,37 +28,37 @@ function copyBytes(dst: Uint8Array, src: Uint8Array, off = 0): number {
}
export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
- private buf: Uint8Array; // contents are the bytes buf[off : len(buf)]
- private off = 0; // read at buf[off], write at buf[buf.byteLength]
+ #buf: Uint8Array; // contents are the bytes buf[off : len(buf)]
+ #off = 0; // read at buf[off], write at buf[buf.byteLength]
constructor(ab?: ArrayBuffer) {
if (ab == null) {
- this.buf = new Uint8Array(0);
+ this.#buf = new Uint8Array(0);
return;
}
- this.buf = new Uint8Array(ab);
+ this.#buf = new Uint8Array(ab);
}
bytes(): Uint8Array {
- return this.buf.subarray(this.off);
+ return this.#buf.subarray(this.#off);
}
toString(): string {
const decoder = new TextDecoder();
- return decoder.decode(this.buf.subarray(this.off));
+ return decoder.decode(this.#buf.subarray(this.#off));
}
empty(): boolean {
- return this.buf.byteLength <= this.off;
+ return this.#buf.byteLength <= this.#off;
}
get length(): number {
- return this.buf.byteLength - this.off;
+ return this.#buf.byteLength - this.#off;
}
get capacity(): number {
- return this.buf.buffer.byteLength;
+ return this.#buf.buffer.byteLength;
}
truncate(n: number): void {
@@ -69,27 +69,27 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
if (n < 0 || n > this.length) {
throw Error("bytes.Buffer: truncation out of range");
}
- this._reslice(this.off + n);
+ this.#reslice(this.#off + n);
}
reset(): void {
- this._reslice(0);
- this.off = 0;
+ this.#reslice(0);
+ this.#off = 0;
}
- private _tryGrowByReslice(n: number): number {
- const l = this.buf.byteLength;
+ #tryGrowByReslice = (n: number): number => {
+ const l = this.#buf.byteLength;
if (n <= this.capacity - l) {
- this._reslice(l + n);
+ this.#reslice(l + n);
return l;
}
return -1;
- }
+ };
- private _reslice(len: number): void {
- assert(len <= this.buf.buffer.byteLength);
- this.buf = new Uint8Array(this.buf.buffer, 0, len);
- }
+ #reslice = (len: number): void => {
+ assert(len <= this.#buf.buffer.byteLength);
+ this.#buf = new Uint8Array(this.#buf.buffer, 0, len);
+ };
readSync(p: Uint8Array): number | EOF {
if (this.empty()) {
@@ -101,8 +101,8 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
}
return EOF;
}
- const nread = copyBytes(p, this.buf.subarray(this.off));
- this.off += nread;
+ const nread = copyBytes(p, this.#buf.subarray(this.#off));
+ this.#off += nread;
return nread;
}
@@ -112,8 +112,8 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
}
writeSync(p: Uint8Array): number {
- const m = this._grow(p.byteLength);
- return copyBytes(this.buf, p, m);
+ const m = this.#grow(p.byteLength);
+ return copyBytes(this.#buf, p, m);
}
write(p: Uint8Array): Promise<number> {
@@ -121,14 +121,14 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
return Promise.resolve(n);
}
- private _grow(n: number): number {
+ #grow = (n: number): number => {
const m = this.length;
// If buffer is empty, reset to recover space.
- if (m === 0 && this.off !== 0) {
+ if (m === 0 && this.#off !== 0) {
this.reset();
}
// Fast: Try to grow by means of a reslice.
- const i = this._tryGrowByReslice(n);
+ const i = this.#tryGrowByReslice(n);
if (i >= 0) {
return i;
}
@@ -138,41 +138,41 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
// ArrayBuffer. We only need m+n <= c to slide, but
// we instead let capacity get twice as large so we
// don't spend all our time copying.
- copyBytes(this.buf, this.buf.subarray(this.off));
+ copyBytes(this.#buf, this.#buf.subarray(this.#off));
} else if (c > MAX_SIZE - c - n) {
throw new Error("The buffer cannot be grown beyond the maximum size.");
} else {
// Not enough space anywhere, we need to allocate.
const buf = new Uint8Array(2 * c + n);
- copyBytes(buf, this.buf.subarray(this.off));
- this.buf = buf;
+ copyBytes(buf, this.#buf.subarray(this.#off));
+ this.#buf = buf;
}
- // Restore this.off and len(this.buf).
- this.off = 0;
- this._reslice(m + n);
+ // Restore this.#off and len(this.#buf).
+ this.#off = 0;
+ this.#reslice(m + n);
return m;
- }
+ };
grow(n: number): void {
if (n < 0) {
throw Error("Buffer.grow: negative count");
}
- const m = this._grow(n);
- this._reslice(m);
+ const m = this.#grow(n);
+ this.#reslice(m);
}
async readFrom(r: Reader): Promise<number> {
let n = 0;
while (true) {
try {
- const i = this._grow(MIN_READ);
- this._reslice(i);
- const fub = new Uint8Array(this.buf.buffer, i);
+ const i = this.#grow(MIN_READ);
+ this.#reslice(i);
+ const fub = new Uint8Array(this.#buf.buffer, i);
const nread = await r.read(fub);
if (nread === EOF) {
return n;
}
- this._reslice(i + nread);
+ this.#reslice(i + nread);
n += nread;
} catch (e) {
return n;
@@ -184,14 +184,14 @@ export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
let n = 0;
while (true) {
try {
- const i = this._grow(MIN_READ);
- this._reslice(i);
- const fub = new Uint8Array(this.buf.buffer, i);
+ const i = this.#grow(MIN_READ);
+ this.#reslice(i);
+ const fub = new Uint8Array(this.#buf.buffer, i);
const nread = r.readSync(fub);
if (nread === EOF) {
return n;
}
- this._reslice(i + nread);
+ this.#reslice(i + nread);
n += nread;
} catch (e) {
return n;
diff --git a/cli/js/build.ts b/cli/js/build.ts
index c34706139..f00c5b463 100644
--- a/cli/js/build.ts
+++ b/cli/js/build.ts
@@ -13,7 +13,7 @@ export interface BuildInfo {
export const build: BuildInfo = {
arch: "" as Arch,
- os: "" as OperatingSystem
+ os: "" as OperatingSystem,
};
export function setBuildInfo(os: OperatingSystem, arch: Arch): void {
diff --git a/cli/js/colors.ts b/cli/js/colors.ts
index 372e90ba5..d0ecdd139 100644
--- a/cli/js/colors.ts
+++ b/cli/js/colors.ts
@@ -17,7 +17,7 @@ function code(open: number, close: number): Code {
return {
open: `\x1b[${open}m`,
close: `\x1b[${close}m`,
- regexp: new RegExp(`\\x1b\\[${close}m`, "g")
+ regexp: new RegExp(`\\x1b\\[${close}m`, "g"),
};
}
diff --git a/cli/js/compiler.ts b/cli/js/compiler.ts
index 419f07063..b3cd3a481 100644
--- a/cli/js/compiler.ts
+++ b/cli/js/compiler.ts
@@ -21,12 +21,12 @@ import {
defaultBundlerOptions,
defaultRuntimeCompileOptions,
defaultTranspileOptions,
- Host
+ Host,
} from "./compiler/host.ts";
import {
processImports,
processLocalImports,
- resolveModules
+ resolveModules,
} from "./compiler/imports.ts";
import {
createWriteFile,
@@ -35,7 +35,7 @@ import {
ignoredDiagnostics,
WriteFileState,
processConfigureResponse,
- base64ToUint8Array
+ base64ToUint8Array,
} from "./compiler/util.ts";
import { Diagnostic, DiagnosticItem } from "./diagnostics.ts";
import { fromTypeScriptDiagnostic } from "./diagnostics_util.ts";
@@ -93,7 +93,7 @@ async function compile(
const { bundle, config, configPath, outFile, rootNames, target } = request;
util.log(">>> compile start", {
rootNames,
- type: CompilerRequestType[request.type]
+ type: CompilerRequestType[request.type],
});
// When a programme is emitted, TypeScript will call `writeFile` with
@@ -108,14 +108,14 @@ async function compile(
bundle,
host: undefined,
outFile,
- rootNames
+ rootNames,
};
const writeFile = createWriteFile(state);
const host = (state.host = new Host({
bundle,
target,
- writeFile
+ writeFile,
}));
let diagnostics: readonly ts.Diagnostic[] | undefined;
@@ -129,7 +129,7 @@ async function compile(
// requesting those from the privileged side, populating the in memory
// cache which will be used by the host, before resolving.
const resolvedRootModules = await processImports(
- rootNames.map(rootName => [rootName, rootName]),
+ rootNames.map((rootName) => [rootName, rootName]),
undefined,
bundle || host.getCompilationSettings().checkJs
);
@@ -143,7 +143,7 @@ async function compile(
rootNames,
options,
host,
- oldProgram: TS_SNAPSHOT_PROGRAM
+ oldProgram: TS_SNAPSHOT_PROGRAM,
});
diagnostics = ts
@@ -171,12 +171,12 @@ async function compile(
emitSkipped,
diagnostics: diagnostics.length
? fromTypeScriptDiagnostic(diagnostics)
- : undefined
+ : undefined,
};
util.log("<<< compile end", {
rootNames,
- type: CompilerRequestType[request.type]
+ type: CompilerRequestType[request.type],
});
return result;
@@ -190,7 +190,7 @@ async function runtimeCompile(
util.log(">>> runtime compile start", {
rootName,
bundle,
- sources: sources ? Object.keys(sources) : undefined
+ sources: sources ? Object.keys(sources) : undefined,
});
// resolve the root name, if there are sources, the root name does not
@@ -232,7 +232,7 @@ async function runtimeCompile(
const resolvedNames = resolveModules(additionalFiles);
rootNames.push(
...(await processImports(
- resolvedNames.map(rn => [rn, rn]),
+ resolvedNames.map((rn) => [rn, rn]),
undefined,
checkJsImports
))
@@ -246,14 +246,14 @@ async function runtimeCompile(
rootNames,
sources,
emitMap: {},
- emitBundle: undefined
+ emitBundle: undefined,
};
const writeFile = createWriteFile(state);
const host = (state.host = new Host({
bundle,
target,
- writeFile
+ writeFile,
}));
const compilerOptions = [defaultRuntimeCompileOptions];
if (convertedOptions) {
@@ -268,7 +268,7 @@ async function runtimeCompile(
rootNames,
options: host.getCompilationSettings(),
host,
- oldProgram: TS_SNAPSHOT_PROGRAM
+ oldProgram: TS_SNAPSHOT_PROGRAM,
});
if (bundle) {
@@ -288,7 +288,7 @@ async function runtimeCompile(
rootName,
sources: sources ? Object.keys(sources) : undefined,
bundle,
- emitMap: Object.keys(state.emitMap)
+ emitMap: Object.keys(state.emitMap),
});
const maybeDiagnostics = diagnostics.length
@@ -320,7 +320,7 @@ function runtimeTranspile(
inputText,
{
fileName,
- compilerOptions
+ compilerOptions,
}
);
result[fileName] = { source, map };
@@ -329,7 +329,7 @@ function runtimeTranspile(
}
async function tsCompilerOnMessage({
- data: request
+ data: request,
}: {
data: CompilerRequest;
}): Promise<void> {
@@ -364,7 +364,7 @@ async function tsCompilerOnMessage({
}
async function wasmCompilerOnMessage({
- data: binary
+ data: binary,
}: {
data: string;
}): Promise<void> {
@@ -411,12 +411,12 @@ Object.defineProperties(globalThis, {
value: bootstrapWasmCompilerRuntime,
enumerable: false,
writable: false,
- configurable: false
+ configurable: false,
},
bootstrapTsCompilerRuntime: {
value: bootstrapTsCompilerRuntime,
enumerable: false,
writable: false,
- configurable: false
- }
+ configurable: false,
+ },
});
diff --git a/cli/js/compiler/api.ts b/cli/js/compiler/api.ts
index 409ad94db..b7c57b528 100644
--- a/cli/js/compiler/api.ts
+++ b/cli/js/compiler/api.ts
@@ -157,7 +157,7 @@ export async function transpileOnly(
util.log("Deno.transpileOnly", { sources: Object.keys(sources), options });
const payload = {
sources,
- options: JSON.stringify(options)
+ options: JSON.stringify(options),
};
const result = await runtimeCompilerOps.transpile(payload);
return JSON.parse(result);
@@ -172,12 +172,12 @@ export async function compile(
rootName: sources ? rootName : checkRelative(rootName),
sources,
options: JSON.stringify(options),
- bundle: false
+ bundle: false,
};
util.log("Deno.compile", {
rootName: payload.rootName,
sources: !!sources,
- options
+ options,
});
const result = await runtimeCompilerOps.compile(payload);
return JSON.parse(result);
@@ -192,12 +192,12 @@ export async function bundle(
rootName: sources ? rootName : checkRelative(rootName),
sources,
options: JSON.stringify(options),
- bundle: true
+ bundle: true,
};
util.log("Deno.bundle", {
rootName: payload.rootName,
sources: !!sources,
- options
+ options,
});
const result = await runtimeCompilerOps.compile(payload);
return JSON.parse(result);
diff --git a/cli/js/compiler/bootstrap.ts b/cli/js/compiler/bootstrap.ts
index 978ddbaf8..63de783cf 100644
--- a/cli/js/compiler/bootstrap.ts
+++ b/cli/js/compiler/bootstrap.ts
@@ -9,7 +9,7 @@ import { getAsset } from "./util.ts";
// load all type definitions and snapshot them.
const host = new Host({
target: CompilerHostTarget.Main,
- writeFile(): void {}
+ writeFile(): void {},
});
const options = host.getCompilationSettings();
@@ -34,7 +34,7 @@ host.getSourceFile(
export const TS_SNAPSHOT_PROGRAM = ts.createProgram({
rootNames: [`${ASSETS}/bootstrap.ts`],
options,
- host
+ host,
});
export const SYSTEM_LOADER = getAsset("system_loader.js");
diff --git a/cli/js/compiler/bundler.ts b/cli/js/compiler/bundler.ts
index 8e35befc8..c9578fe20 100644
--- a/cli/js/compiler/bundler.ts
+++ b/cli/js/compiler/bundler.ts
@@ -14,7 +14,7 @@ function normalizeUrl(rootName: string): string {
path,
false,
"/",
- code => code === CHAR_FORWARD_SLASH
+ (code) => code === CHAR_FORWARD_SLASH
)}`;
} else {
return rootName;
@@ -29,7 +29,7 @@ export function buildBundle(
// when outputting to AMD and a single outfile, TypeScript makes up the module
// specifiers which are used to define the modules, and doesn't expose them
// publicly, so we have to try to replicate
- const sources = sourceFiles.map(sf => sf.fileName);
+ const sources = sourceFiles.map((sf) => sf.fileName);
const sharedPath = commonPath(sources);
rootName = normalizeUrl(rootName)
.replace(sharedPath, "")
@@ -79,7 +79,7 @@ export function setRootExports(program: ts.Program, rootModule: string): void {
// that when there isn't. There appears to be no clean way of figuring that
// out, so inspecting SymbolFlags that might be present that are type only
.filter(
- sym =>
+ (sym) =>
sym.flags & ts.SymbolFlags.Class ||
!(
sym.flags & ts.SymbolFlags.Interface ||
@@ -94,5 +94,5 @@ export function setRootExports(program: ts.Program, rootModule: string): void {
sym.flags & ts.SymbolFlags.TypeAliasExcludes
)
)
- .map(sym => sym.getName());
+ .map((sym) => sym.getName());
}
diff --git a/cli/js/compiler/host.ts b/cli/js/compiler/host.ts
index 457388bd9..70e712ffe 100644
--- a/cli/js/compiler/host.ts
+++ b/cli/js/compiler/host.ts
@@ -9,7 +9,7 @@ import * as util from "../util.ts";
export enum CompilerHostTarget {
Main = "main",
Runtime = "runtime",
- Worker = "worker"
+ Worker = "worker",
}
export interface CompilerHostOptions {
@@ -32,7 +32,7 @@ export const defaultBundlerOptions: ts.CompilerOptions = {
outDir: undefined,
outFile: `${OUT_DIR}/bundle.js`,
// disabled until we have effective way to modify source maps
- sourceMap: false
+ sourceMap: false,
};
export const defaultCompileOptions: ts.CompilerOptions = {
@@ -47,11 +47,11 @@ export const defaultCompileOptions: ts.CompilerOptions = {
sourceMap: true,
strict: true,
stripComments: true,
- target: ts.ScriptTarget.ESNext
+ target: ts.ScriptTarget.ESNext,
};
export const defaultRuntimeCompileOptions: ts.CompilerOptions = {
- outDir: undefined
+ outDir: undefined,
};
export const defaultTranspileOptions: ts.CompilerOptions = {
@@ -59,7 +59,7 @@ export const defaultTranspileOptions: ts.CompilerOptions = {
module: ts.ModuleKind.ESNext,
sourceMap: true,
scriptComments: true,
- target: ts.ScriptTarget.ESNext
+ target: ts.ScriptTarget.ESNext,
};
const ignoredCompilerOptions: readonly string[] = [
@@ -117,43 +117,41 @@ const ignoredCompilerOptions: readonly string[] = [
"types",
"typeRoots",
"version",
- "watch"
+ "watch",
];
-export class Host implements ts.CompilerHost {
- private readonly _options = defaultCompileOptions;
-
- private _target: CompilerHostTarget;
-
- private _writeFile: WriteFileCallback;
-
- private _getAsset(filename: string): SourceFile {
- const lastSegment = filename.split("/").pop()!;
- const url = ts.libMap.has(lastSegment)
- ? ts.libMap.get(lastSegment)!
- : lastSegment;
- const sourceFile = SourceFile.get(url);
- if (sourceFile) {
- return sourceFile;
- }
- const name = url.includes(".") ? url : `${url}.d.ts`;
- const sourceCode = getAsset(name);
- return new SourceFile({
- url,
- filename: `${ASSETS}/${name}`,
- mediaType: MediaType.TypeScript,
- sourceCode
- });
+function getAssetInternal(filename: string): SourceFile {
+ const lastSegment = filename.split("/").pop()!;
+ const url = ts.libMap.has(lastSegment)
+ ? ts.libMap.get(lastSegment)!
+ : lastSegment;
+ const sourceFile = SourceFile.get(url);
+ if (sourceFile) {
+ return sourceFile;
}
+ const name = url.includes(".") ? url : `${url}.d.ts`;
+ const sourceCode = getAsset(name);
+ return new SourceFile({
+ url,
+ filename: `${ASSETS}/${name}`,
+ mediaType: MediaType.TypeScript,
+ sourceCode,
+ });
+}
+
+export class Host implements ts.CompilerHost {
+ readonly #options = defaultCompileOptions;
+ #target: CompilerHostTarget;
+ #writeFile: WriteFileCallback;
/* Deno specific APIs */
constructor({ bundle = false, target, writeFile }: CompilerHostOptions) {
- this._target = target;
- this._writeFile = writeFile;
+ this.#target = target;
+ this.#writeFile = writeFile;
if (bundle) {
// options we need to change when we are generating a bundle
- Object.assign(this._options, defaultBundlerOptions);
+ Object.assign(this.#options, defaultBundlerOptions);
}
}
@@ -175,22 +173,22 @@ export class Host implements ts.CompilerHost {
for (const key of Object.keys(options)) {
if (
ignoredCompilerOptions.includes(key) &&
- (!(key in this._options) || options[key] !== this._options[key])
+ (!(key in this.#options) || options[key] !== this.#options[key])
) {
ignoredOptions.push(key);
delete options[key];
}
}
- Object.assign(this._options, options);
+ Object.assign(this.#options, options);
return {
ignoredOptions: ignoredOptions.length ? ignoredOptions : undefined,
- diagnostics: errors.length ? errors : undefined
+ diagnostics: errors.length ? errors : undefined,
};
}
mergeOptions(...options: ts.CompilerOptions[]): ts.CompilerOptions {
- Object.assign(this._options, ...options);
- return Object.assign({}, this._options);
+ Object.assign(this.#options, ...options);
+ return Object.assign({}, this.#options);
}
/* TypeScript CompilerHost APIs */
@@ -205,7 +203,7 @@ export class Host implements ts.CompilerHost {
getCompilationSettings(): ts.CompilerOptions {
util.log("compiler::host.getCompilationSettings()");
- return this._options;
+ return this.#options;
}
getCurrentDirectory(): string {
@@ -214,7 +212,7 @@ export class Host implements ts.CompilerHost {
getDefaultLibFileName(_options: ts.CompilerOptions): string {
util.log("compiler::host.getDefaultLibFileName()");
- switch (this._target) {
+ switch (this.#target) {
case CompilerHostTarget.Main:
case CompilerHostTarget.Runtime:
return `${ASSETS}/lib.deno.window.d.ts`;
@@ -237,7 +235,7 @@ export class Host implements ts.CompilerHost {
try {
assert(!shouldCreateNewSourceFile);
const sourceFile = fileName.startsWith(ASSETS)
- ? this._getAsset(fileName)
+ ? getAssetInternal(fileName)
: SourceFile.get(fileName);
assert(sourceFile != null);
if (!sourceFile.tsSourceFile) {
@@ -278,12 +276,12 @@ export class Host implements ts.CompilerHost {
): Array<ts.ResolvedModuleFull | undefined> {
util.log("compiler::host.resolveModuleNames", {
moduleNames,
- containingFile
+ containingFile,
});
- return moduleNames.map(specifier => {
+ return moduleNames.map((specifier) => {
const url = SourceFile.getUrl(specifier, containingFile);
const sourceFile = specifier.startsWith(ASSETS)
- ? this._getAsset(specifier)
+ ? getAssetInternal(specifier)
: url
? SourceFile.get(url)
: undefined;
@@ -293,7 +291,7 @@ export class Host implements ts.CompilerHost {
return {
resolvedFileName: sourceFile.url,
isExternalLibraryImport: specifier.startsWith(ASSETS),
- extension: sourceFile.extension
+ extension: sourceFile.extension,
};
});
}
@@ -310,6 +308,6 @@ export class Host implements ts.CompilerHost {
sourceFiles?: readonly ts.SourceFile[]
): void {
util.log("compiler::host.writeFile", fileName);
- this._writeFile(fileName, data, sourceFiles);
+ this.#writeFile(fileName, data, sourceFiles);
}
}
diff --git a/cli/js/compiler/imports.ts b/cli/js/compiler/imports.ts
index a3246c32f..6b48ec945 100644
--- a/cli/js/compiler/imports.ts
+++ b/cli/js/compiler/imports.ts
@@ -34,7 +34,7 @@ function resolvePath(...pathSegments: string[]): string {
resolvedPath,
!resolvedAbsolute,
"/",
- code => code === CHAR_FORWARD_SLASH
+ (code) => code === CHAR_FORWARD_SLASH
);
if (resolvedAbsolute) {
@@ -120,7 +120,7 @@ export function processLocalImports(
url: moduleName,
filename: moduleName,
sourceCode: sources[moduleName],
- mediaType: getMediaType(moduleName)
+ mediaType: getMediaType(moduleName),
});
sourceFile.cache(specifiers[i][0], referrer);
if (!sourceFile.processed) {
diff --git a/cli/js/compiler/sourcefile.ts b/cli/js/compiler/sourcefile.ts
index e400acbf5..a55de080b 100644
--- a/cli/js/compiler/sourcefile.ts
+++ b/cli/js/compiler/sourcefile.ts
@@ -12,7 +12,7 @@ export enum MediaType {
TSX = 3,
Json = 4,
Wasm = 5,
- Unknown = 6
+ Unknown = 6,
}
export interface SourceFileJson {
@@ -50,6 +50,11 @@ function getExtension(fileName: string, mediaType: MediaType): ts.Extension {
}
}
+/** A global cache of module source files that have been loaded. */
+const moduleCache: Map<string, SourceFile> = new Map();
+/** A map of maps which cache source files for quicker modules resolution. */
+const specifierCache: Map<string, Map<string, SourceFile>> = new Map();
+
export class SourceFile {
extension!: ts.Extension;
filename!: string;
@@ -63,20 +68,20 @@ export class SourceFile {
url!: string;
constructor(json: SourceFileJson) {
- if (SourceFile._moduleCache.has(json.url)) {
+ if (moduleCache.has(json.url)) {
throw new TypeError("SourceFile already exists");
}
Object.assign(this, json);
this.extension = getExtension(this.url, this.mediaType);
- SourceFile._moduleCache.set(this.url, this);
+ moduleCache.set(this.url, this);
}
cache(moduleSpecifier: string, containingFile?: string): void {
containingFile = containingFile || "";
- let innerCache = SourceFile._specifierCache.get(containingFile);
+ let innerCache = specifierCache.get(containingFile);
if (!innerCache) {
innerCache = new Map();
- SourceFile._specifierCache.set(containingFile, innerCache);
+ specifierCache.set(containingFile, innerCache);
}
innerCache.set(moduleSpecifier, this);
}
@@ -112,14 +117,14 @@ export class SourceFile {
importedFiles,
referencedFiles,
libReferenceDirectives,
- typeReferenceDirectives
+ typeReferenceDirectives,
} = preProcessedFileInfo;
const typeDirectives = parseTypeDirectives(this.sourceCode);
if (typeDirectives) {
for (const importedFile of importedFiles) {
files.push([
importedFile.fileName,
- getMappedModuleName(importedFile, typeDirectives)
+ getMappedModuleName(importedFile, typeDirectives),
]);
}
} else if (
@@ -145,18 +150,11 @@ export class SourceFile {
return files;
}
- private static _moduleCache: Map<string, SourceFile> = new Map();
-
- private static _specifierCache: Map<
- string,
- Map<string, SourceFile>
- > = new Map();
-
static getUrl(
moduleSpecifier: string,
containingFile: string
): string | undefined {
- const containingCache = this._specifierCache.get(containingFile);
+ const containingCache = specifierCache.get(containingFile);
if (containingCache) {
const sourceFile = containingCache.get(moduleSpecifier);
return sourceFile && sourceFile.url;
@@ -165,10 +163,10 @@ export class SourceFile {
}
static get(url: string): SourceFile | undefined {
- return this._moduleCache.get(url);
+ return moduleCache.get(url);
}
static has(url: string): boolean {
- return this._moduleCache.has(url);
+ return moduleCache.has(url);
}
}
diff --git a/cli/js/compiler/type_directives.ts b/cli/js/compiler/type_directives.ts
index 299532f98..5f33f4b33 100644
--- a/cli/js/compiler/type_directives.ts
+++ b/cli/js/compiler/type_directives.ts
@@ -39,7 +39,7 @@ export function parseTypeDirectives(
directives.push({
fileName,
pos,
- end: pos + matchString.length
+ end: pos + matchString.length,
});
}
if (!directives.length) {
@@ -60,7 +60,7 @@ export function parseTypeDirectives(
const target: FileReference = {
fileName: targetFileName,
pos: targetPos,
- end: targetPos + targetFileName.length
+ end: targetPos + targetFileName.length,
};
results.set(target, fileName);
}
diff --git a/cli/js/compiler/util.ts b/cli/js/compiler/util.ts
index 8acc83a2d..170dff30f 100644
--- a/cli/js/compiler/util.ts
+++ b/cli/js/compiler/util.ts
@@ -33,7 +33,7 @@ export interface WriteFileState {
export enum CompilerRequestType {
Compile = 0,
RuntimeCompile = 1,
- RuntimeTranspile = 2
+ RuntimeTranspile = 2,
}
export const OUT_DIR = "$deno$";
@@ -255,7 +255,7 @@ export function convertCompilerOptions(
}
return {
options: out as ts.CompilerOptions,
- files: files.length ? files : undefined
+ files: files.length ? files : undefined,
};
}
@@ -287,7 +287,7 @@ export const ignoredDiagnostics = [
// TS7016: Could not find a declaration file for module '...'. '...'
// implicitly has an 'any' type. This is due to `allowJs` being off by
// default but importing of a JavaScript module.
- 7016
+ 7016,
];
export function processConfigureResponse(
diff --git a/cli/js/deno.ts b/cli/js/deno.ts
index f42e39754..2c1d2a5b7 100644
--- a/cli/js/deno.ts
+++ b/cli/js/deno.ts
@@ -6,7 +6,7 @@ export {
readAll,
readAllSync,
writeAll,
- writeAllSync
+ writeAllSync,
} from "./buffer.ts";
export { build, OperatingSystem, Arch } from "./build.ts";
export { chmodSync, chmod } from "./ops/fs/chmod.ts";
@@ -18,7 +18,7 @@ export {
Diagnostic,
DiagnosticCategory,
DiagnosticItem,
- DiagnosticMessageChain
+ DiagnosticMessageChain,
} from "./diagnostics.ts";
export { chdir, cwd } from "./ops/fs/dir.ts";
export { applySourceMap, formatDiagnostics } from "./ops/errors.ts";
@@ -36,7 +36,7 @@ export {
seek,
seekSync,
OpenOptions,
- OpenMode
+ OpenMode,
} from "./files.ts";
export { read, readSync, write, writeSync } from "./ops/io.ts";
export { FsEvent, fsEvents } from "./ops/fs_events.ts";
@@ -57,7 +57,7 @@ export {
ReadSeeker,
WriteSeeker,
ReadWriteCloser,
- ReadWriteSeeker
+ ReadWriteSeeker,
} from "./io.ts";
export { linkSync, link } from "./ops/fs/link.ts";
export {
@@ -65,7 +65,7 @@ export {
makeTempDir,
makeTempFileSync,
makeTempFile,
- MakeTempOptions
+ MakeTempOptions,
} from "./ops/fs/make_temp.ts";
export { metrics, Metrics } from "./ops/runtime.ts";
export { mkdirSync, mkdir, MkdirOptions } from "./ops/fs/mkdir.ts";
@@ -76,7 +76,7 @@ export {
Listener,
Conn,
ShutdownMode,
- shutdown
+ shutdown,
} from "./net.ts";
export {
dir,
@@ -85,14 +85,14 @@ export {
execPath,
hostname,
loadavg,
- osRelease
+ osRelease,
} from "./ops/os.ts";
export {
permissions,
PermissionName,
PermissionState,
PermissionStatus,
- Permissions
+ Permissions,
} from "./permissions.ts";
export { openPlugin } from "./plugins.ts";
export { kill } from "./ops/process.ts";
diff --git a/cli/js/diagnostics.ts b/cli/js/diagnostics.ts
index 41a8ea8b2..d8a3f2a3c 100644
--- a/cli/js/diagnostics.ts
+++ b/cli/js/diagnostics.ts
@@ -10,7 +10,7 @@ export enum DiagnosticCategory {
Info = 2,
Error = 3,
Warning = 4,
- Suggestion = 5
+ Suggestion = 5,
}
export interface DiagnosticMessageChain {
diff --git a/cli/js/diagnostics_util.ts b/cli/js/diagnostics_util.ts
index 24a893678..17e73e377 100644
--- a/cli/js/diagnostics_util.ts
+++ b/cli/js/diagnostics_util.ts
@@ -7,7 +7,7 @@ import {
Diagnostic,
DiagnosticCategory,
DiagnosticMessageChain,
- DiagnosticItem
+ DiagnosticItem,
} from "./diagnostics.ts";
interface SourceInformation {
@@ -45,7 +45,7 @@ function getSourceInformation(
const scriptResourceName = sourceFile.fileName;
const {
line: lineNumber,
- character: startColumn
+ character: startColumn,
} = sourceFile.getLineAndCharacterOfPosition(start);
const endPosition = sourceFile.getLineAndCharacterOfPosition(start + length);
const endColumn =
@@ -67,7 +67,7 @@ function getSourceInformation(
lineNumber,
scriptResourceName,
startColumn,
- endColumn
+ endColumn,
};
}
@@ -83,7 +83,7 @@ function fromDiagnosticMessageChain(
message,
code,
category: fromDiagnosticCategory(category),
- next: fromDiagnosticMessageChain(next)
+ next: fromDiagnosticMessageChain(next),
};
});
}
@@ -97,7 +97,7 @@ function parseDiagnostic(
code,
file,
start: startPosition,
- length
+ length,
} = item;
const sourceInfo =
file && startPosition && length
@@ -122,7 +122,7 @@ function parseDiagnostic(
code,
category,
startPosition,
- endPosition
+ endPosition,
};
return sourceInfo ? { ...base, ...sourceInfo } : base;
diff --git a/cli/js/error_stack.ts b/cli/js/error_stack.ts
index 6ec8752e6..97e9f68de 100644
--- a/cli/js/error_stack.ts
+++ b/cli/js/error_stack.ts
@@ -54,7 +54,7 @@ function patchCallSite(callSite: CallSite, location: Location): CallSite {
},
getPromiseIndex(): number | null {
return callSite.getPromiseIndex();
- }
+ },
};
}
@@ -181,7 +181,7 @@ function prepareStackTrace(
applySourceMap({
filename,
line,
- column
+ column,
})
);
}
diff --git a/cli/js/errors.ts b/cli/js/errors.ts
index 6aced228a..fc4021321 100644
--- a/cli/js/errors.ts
+++ b/cli/js/errors.ts
@@ -22,7 +22,7 @@ export enum ErrorKind {
Http = 19,
URIError = 20,
TypeError = 21,
- Other = 22
+ Other = 22,
}
export function getErrorClass(kind: ErrorKind): { new (msg: string): Error } {
@@ -190,5 +190,5 @@ export const errors = {
WriteZero: WriteZero,
UnexpectedEof: UnexpectedEof,
BadResource: BadResource,
- Http: Http
+ Http: Http,
};
diff --git a/cli/js/file_info.ts b/cli/js/file_info.ts
index 827239769..c5b884f75 100644
--- a/cli/js/file_info.ts
+++ b/cli/js/file_info.ts
@@ -24,8 +24,8 @@ export interface FileInfo {
// @internal
export class FileInfoImpl implements FileInfo {
- private readonly _isFile: boolean;
- private readonly _isSymlink: boolean;
+ readonly #isFile: boolean;
+ readonly #isSymlink: boolean;
size: number;
modified: number | null;
accessed: number | null;
@@ -43,28 +43,18 @@ export class FileInfoImpl implements FileInfo {
blocks: number | null;
/* @internal */
- constructor(private _res: StatResponse) {
+ constructor(res: StatResponse) {
const isUnix = build.os === "mac" || build.os === "linux";
- const modified = this._res.modified;
- const accessed = this._res.accessed;
- const created = this._res.created;
- const name = this._res.name;
+ const modified = res.modified;
+ const accessed = res.accessed;
+ const created = res.created;
+ const name = res.name;
// Unix only
- const {
- dev,
- ino,
- mode,
- nlink,
- uid,
- gid,
- rdev,
- blksize,
- blocks
- } = this._res;
+ const { dev, ino, mode, nlink, uid, gid, rdev, blksize, blocks } = res;
- this._isFile = this._res.isFile;
- this._isSymlink = this._res.isSymlink;
- this.size = this._res.size;
+ this.#isFile = res.isFile;
+ this.#isSymlink = res.isSymlink;
+ this.size = res.size;
this.modified = modified ? modified : null;
this.accessed = accessed ? accessed : null;
this.created = created ? created : null;
@@ -82,14 +72,14 @@ export class FileInfoImpl implements FileInfo {
}
isFile(): boolean {
- return this._isFile;
+ return this.#isFile;
}
isDirectory(): boolean {
- return !this._isFile && !this._isSymlink;
+ return !this.#isFile && !this.#isSymlink;
}
isSymlink(): boolean {
- return this._isSymlink;
+ return this.#isSymlink;
}
}
diff --git a/cli/js/files.ts b/cli/js/files.ts
index 99ae19879..d09fcf8db 100644
--- a/cli/js/files.ts
+++ b/cli/js/files.ts
@@ -8,7 +8,7 @@ import {
SeekMode,
SyncReader,
SyncWriter,
- SyncSeeker
+ SyncSeeker,
} from "./io.ts";
import { close } from "./ops/resources.ts";
import { read, readSync, write, writeSync } from "./ops/io.ts";
@@ -18,7 +18,7 @@ import {
open as opOpen,
openSync as opOpenSync,
OpenOptions,
- OpenMode
+ OpenMode,
} from "./ops/fs/open.ts";
export { OpenOptions, OpenMode } from "./ops/fs/open.ts";
@@ -119,7 +119,7 @@ export const stdout = new File(1);
export const stderr = new File(2);
function checkOpenOptions(options: OpenOptions): void {
- if (Object.values(options).filter(val => val === true).length === 0) {
+ if (Object.values(options).filter((val) => val === true).length === 0) {
throw new Error("OpenOptions requires at least one option to be true");
}
diff --git a/cli/js/globals.ts b/cli/js/globals.ts
index d71a96d39..87ff13b22 100644
--- a/cli/js/globals.ts
+++ b/cli/js/globals.ts
@@ -160,7 +160,7 @@ export function writable(value: unknown): PropertyDescriptor {
value,
writable: true,
enumerable: true,
- configurable: true
+ configurable: true,
};
}
@@ -168,14 +168,14 @@ export function nonEnumerable(value: unknown): PropertyDescriptor {
return {
value,
writable: true,
- configurable: true
+ configurable: true,
};
}
export function readOnly(value: unknown): PropertyDescriptor {
return {
value,
- enumerable: true
+ enumerable: true,
};
}
@@ -183,7 +183,7 @@ export function readOnly(value: unknown): PropertyDescriptor {
export function getterOnly(getter: () => any): PropertyDescriptor {
return {
get: getter,
- enumerable: true
+ enumerable: true,
};
}
@@ -196,7 +196,7 @@ export const windowOrWorkerGlobalScopeMethods = {
fetch: writable(fetchTypes.fetch),
// queueMicrotask is bound in Rust
setInterval: writable(timers.setInterval),
- setTimeout: writable(timers.setTimeout)
+ setTimeout: writable(timers.setTimeout),
};
// Other properties shared between WindowScope and WorkerGlobalScope
@@ -216,7 +216,7 @@ export const windowOrWorkerGlobalScopeProperties = {
Request: nonEnumerable(request.Request),
Response: nonEnumerable(fetchTypes.Response),
performance: writable(new performanceUtil.Performance()),
- Worker: nonEnumerable(workers.WorkerImpl)
+ Worker: nonEnumerable(workers.WorkerImpl),
};
export const eventTargetProperties = {
@@ -233,5 +233,5 @@ export const eventTargetProperties = {
dispatchEvent: readOnly(eventTarget.EventTarget.prototype.dispatchEvent),
removeEventListener: readOnly(
eventTarget.EventTarget.prototype.removeEventListener
- )
+ ),
};
diff --git a/cli/js/internals.ts b/cli/js/internals.ts
index 6aae1be48..174e9a0d4 100644
--- a/cli/js/internals.ts
+++ b/cli/js/internals.ts
@@ -11,6 +11,6 @@ export const internalObject: { [key: string]: any } = {};
export function exposeForTest(name: string, value: any): void {
Object.defineProperty(internalObject, name, {
value,
- enumerable: false
+ enumerable: false,
});
}
diff --git a/cli/js/io.ts b/cli/js/io.ts
index 5e0ee7903..b5af34224 100644
--- a/cli/js/io.ts
+++ b/cli/js/io.ts
@@ -11,7 +11,7 @@ export type EOF = typeof EOF;
export enum SeekMode {
SEEK_START = 0,
SEEK_CURRENT = 1,
- SEEK_END = 2
+ SEEK_END = 2,
}
// Reader is the interface that wraps the basic read() method.
@@ -99,8 +99,8 @@ export function toAsyncIterator(r: Reader): AsyncIterableIterator<Uint8Array> {
return {
value: b.subarray(0, result),
- done: false
+ done: false,
};
- }
+ },
};
}
diff --git a/cli/js/lib.deno.ns.d.ts b/cli/js/lib.deno.ns.d.ts
index 781387f51..ffaff4e8a 100644
--- a/cli/js/lib.deno.ns.d.ts
+++ b/cli/js/lib.deno.ns.d.ts
@@ -38,7 +38,7 @@ declare namespace Deno {
enum TestStatus {
Passed = "passed",
Failed = "failed",
- Ignored = "ignored"
+ Ignored = "ignored",
}
interface TestResult {
@@ -60,7 +60,7 @@ declare namespace Deno {
Start = "start",
TestStart = "testStart",
TestEnd = "testEnd",
- End = "end"
+ End = "end",
}
interface TestEventStart {
@@ -402,7 +402,7 @@ declare namespace Deno {
export enum SeekMode {
SEEK_START = 0,
SEEK_CURRENT = 1,
- SEEK_END = 2
+ SEEK_END = 2,
}
/** **UNSTABLE**: might make `Reader` into iterator of some sort. */
@@ -766,12 +766,6 @@ declare namespace Deno {
*
* Based on [Go Buffer](https://golang.org/pkg/bytes/#Buffer). */
export class Buffer implements Reader, SyncReader, Writer, SyncWriter {
- private buf;
- private off;
- private _tryGrowByReslice;
- private _reslice;
- private _grow;
-
constructor(ab?: ArrayBuffer);
/** Returns a slice holding the unread portion of the buffer.
*
@@ -1603,7 +1597,7 @@ declare namespace Deno {
export enum ShutdownMode {
Read = 0,
Write,
- ReadWrite // TODO(ry) panics on ReadWrite.
+ ReadWrite, // TODO(ry) panics on ReadWrite.
}
/** **UNSTABLE**: Maybe should remove `how` parameter maybe remove
@@ -1998,7 +1992,7 @@ declare namespace Deno {
SIGWINCH = 28,
SIGIO = 29,
SIGPWR = 30,
- SIGSYS = 31
+ SIGSYS = 31,
}
enum MacOSSignal {
SIGHUP = 1,
@@ -2031,7 +2025,7 @@ declare namespace Deno {
SIGWINCH = 28,
SIGINFO = 29,
SIGUSR1 = 30,
- SIGUSR2 = 31
+ SIGUSR2 = 31,
}
/** **UNSTABLE**: make platform independent.
@@ -2108,7 +2102,7 @@ declare namespace Deno {
Info = 2,
Error = 3,
Warning = 4,
- Suggestion = 5
+ Suggestion = 5,
}
export interface DiagnosticMessageChain {
diff --git a/cli/js/lib.deno.shared_globals.d.ts b/cli/js/lib.deno.shared_globals.d.ts
index 959dcbfe9..565121bea 100644
--- a/cli/js/lib.deno.shared_globals.d.ts
+++ b/cli/js/lib.deno.shared_globals.d.ts
@@ -339,12 +339,8 @@ declare namespace __domTypes {
export enum NodeType {
ELEMENT_NODE = 1,
TEXT_NODE = 3,
- DOCUMENT_FRAGMENT_NODE = 11
+ DOCUMENT_FRAGMENT_NODE = 11,
}
- export const eventTargetHost: unique symbol;
- export const eventTargetListeners: unique symbol;
- export const eventTargetMode: unique symbol;
- export const eventTargetNodeType: unique symbol;
export interface EventListener {
(evt: Event): void | Promise<void>;
}
@@ -358,11 +354,11 @@ declare namespace __domTypes {
callback: EventListenerOrEventListenerObject;
options: AddEventListenerOptions;
}
+ export const eventTargetHost: unique symbol;
+ export const eventTargetListeners: unique symbol;
+ export const eventTargetMode: unique symbol;
+ export const eventTargetNodeType: unique symbol;
export interface EventTarget {
- [eventTargetHost]: EventTarget | null;
- [eventTargetListeners]: { [type in string]: EventListener[] };
- [eventTargetMode]: string;
- [eventTargetNodeType]: NodeType;
addEventListener(
type: string,
callback: EventListenerOrEventListenerObject | null,
@@ -438,7 +434,7 @@ declare namespace __domTypes {
NONE = 0,
CAPTURING_PHASE = 1,
AT_TARGET = 2,
- BUBBLING_PHASE = 3
+ BUBBLING_PHASE = 3,
}
export interface EventPath {
item: EventTarget;
@@ -532,16 +528,78 @@ declare namespace __domTypes {
options?: boolean | EventListenerOptions
): void;
}
- export interface ReadableStream {
+ export interface ReadableStreamReadDoneResult<T> {
+ done: true;
+ value?: T;
+ }
+ export interface ReadableStreamReadValueResult<T> {
+ done: false;
+ value: T;
+ }
+ export type ReadableStreamReadResult<T> =
+ | ReadableStreamReadValueResult<T>
+ | ReadableStreamReadDoneResult<T>;
+ export interface ReadableStreamDefaultReader<R = any> {
+ readonly closed: Promise<void>;
+ cancel(reason?: any): Promise<void>;
+ read(): Promise<ReadableStreamReadResult<R>>;
+ releaseLock(): void;
+ }
+ export interface PipeOptions {
+ preventAbort?: boolean;
+ preventCancel?: boolean;
+ preventClose?: boolean;
+ signal?: AbortSignal;
+ }
+ /** This Streams API interface represents a readable stream of byte data. The
+ * Fetch API offers a concrete instance of a ReadableStream through the body
+ * property of a Response object. */
+ export interface ReadableStream<R = any> {
readonly locked: boolean;
- cancel(): Promise<void>;
- getReader(): ReadableStreamReader;
- tee(): [ReadableStream, ReadableStream];
+ cancel(reason?: any): Promise<void>;
+ getReader(options: { mode: "byob" }): ReadableStreamBYOBReader;
+ getReader(): ReadableStreamDefaultReader<R>;
+ /* disabled for now
+ pipeThrough<T>(
+ {
+ writable,
+ readable
+ }: {
+ writable: WritableStream<R>;
+ readable: ReadableStream<T>;
+ },
+ options?: PipeOptions
+ ): ReadableStream<T>;
+ pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>;
+ */
+ tee(): [ReadableStream<R>, ReadableStream<R>];
+ }
+ export interface ReadableStreamReader<R = any> {
+ cancel(reason: any): Promise<void>;
+ read(): Promise<ReadableStreamReadResult<R>>;
+ releaseLock(): void;
}
- export interface ReadableStreamReader {
- cancel(): Promise<void>;
- read(): Promise<any>;
+ export interface ReadableStreamBYOBReader {
+ readonly closed: Promise<void>;
+ cancel(reason?: any): Promise<void>;
+ read<T extends ArrayBufferView>(
+ view: T
+ ): Promise<ReadableStreamReadResult<T>>;
+ releaseLock(): void;
+ }
+ export interface WritableStream<W = any> {
+ readonly locked: boolean;
+ abort(reason?: any): Promise<void>;
+ getWriter(): WritableStreamDefaultWriter<W>;
+ }
+ export interface WritableStreamDefaultWriter<W = any> {
+ readonly closed: Promise<void>;
+ readonly desiredSize: number | null;
+ readonly ready: Promise<void>;
+ abort(reason?: any): Promise<void>;
+ close(): Promise<void>;
releaseLock(): void;
+ write(chunk: W): Promise<void>;
}
export interface FormData extends DomIterable<string, FormDataEntryValue> {
append(name: string, value: string | Blob, fileName?: string): void;
@@ -570,7 +628,7 @@ declare namespace __domTypes {
}
export interface Body {
/** A simple getter used to expose a `ReadableStream` of the body contents. */
- readonly body: ReadableStream | null;
+ readonly body: ReadableStream<Uint8Array> | null;
/** Stores a `Boolean` that declares whether the body has been used in a
* response yet.
*/
@@ -799,58 +857,63 @@ declare namespace __domTypes {
/** Creates a clone of a `Response` object. */
clone(): Response;
}
+ export interface DOMStringList {
+ /** Returns the number of strings in strings. */
+ readonly length: number;
+ /** Returns true if strings contains string, and false otherwise. */
+ contains(string: string): boolean;
+ /** Returns the string with index index from strings. */
+ item(index: number): string | null;
+ [index: number]: string;
+ }
+ /** The location (URL) of the object it is linked to. Changes done on it are
+ * reflected on the object it relates to. Both the Document and Window
+ * interface have such a linked Location, accessible via Document.location and
+ * Window.location respectively. */
export interface Location {
- /**
- * Returns a DOMStringList object listing the origins of the ancestor browsing
- * contexts, from the parent browsing context to the top-level browsing
- * context.
- */
- readonly ancestorOrigins: string[];
- /**
- * Returns the Location object's URL's fragment (includes leading "#" if
+ /** Returns a DOMStringList object listing the origins of the ancestor
+ * browsing contexts, from the parent browsing context to the top-level
+ * browsing context. */
+ readonly ancestorOrigins: DOMStringList;
+ /** Returns the Location object's URL's fragment (includes leading "#" if
* non-empty).
+ *
* Can be set, to navigate to the same URL with a changed fragment (ignores
- * leading "#").
- */
+ * leading "#"). */
hash: string;
- /**
- * Returns the Location object's URL's host and port (if different from the
- * default port for the scheme). Can be set, to navigate to the same URL with
- * a changed host and port.
- */
+ /** Returns the Location object's URL's host and port (if different from the
+ * default port for the scheme).
+ *
+ * Can be set, to navigate to the same URL with a changed host and port. */
host: string;
- /**
- * Returns the Location object's URL's host. Can be set, to navigate to the
- * same URL with a changed host.
- */
+ /** Returns the Location object's URL's host.
+ *
+ * Can be set, to navigate to the same URL with a changed host. */
hostname: string;
- /**
- * Returns the Location object's URL. Can be set, to navigate to the given
- * URL.
- */
+ /** Returns the Location object's URL.
+ *
+ * Can be set, to navigate to the given URL. */
href: string;
+ toString(): string;
/** Returns the Location object's URL's origin. */
readonly origin: string;
- /**
- * Returns the Location object's URL's path.
- * Can be set, to navigate to the same URL with a changed path.
- */
+ /** Returns the Location object's URL's path.
+ *
+ * Can be set, to navigate to the same URL with a changed path. */
pathname: string;
- /**
- * Returns the Location object's URL's port.
- * Can be set, to navigate to the same URL with a changed port.
- */
+ /** Returns the Location object's URL's port.
+ *
+ * Can be set, to navigate to the same URL with a changed port. */
port: string;
- /**
- * Returns the Location object's URL's scheme.
- * Can be set, to navigate to the same URL with a changed scheme.
- */
+ /** Returns the Location object's URL's scheme.
+ *
+ * Can be set, to navigate to the same URL with a changed scheme. */
protocol: string;
- /**
- * Returns the Location object's URL's query (includes leading "?" if
- * non-empty). Can be set, to navigate to the same URL with a changed query
- * (ignores leading "?").
- */
+ /** Returns the Location object's URL's query (includes leading "?" if
+ * non-empty).
+ *
+ * Can be set, to navigate to the same URL with a changed query (ignores
+ * leading "?"). */
search: string;
/**
* Navigates to the given URL.
@@ -860,21 +923,14 @@ declare namespace __domTypes {
* Reloads the current page.
*/
reload(): void;
- /** @deprecated */
- reload(forcedReload: boolean): void;
- /**
- * Removes the current page from the session history and navigates to the
- * given URL.
- */
+ /** Removes the current page from the session history and navigates to the
+ * given URL. */
replace(url: string): void;
}
}
declare namespace __blob {
- export const bytesSymbol: unique symbol;
- export const blobBytesWeakMap: WeakMap<__domTypes.Blob, Uint8Array>;
export class DenoBlob implements __domTypes.Blob {
- private readonly [bytesSymbol];
readonly size: number;
readonly type: string;
/** A blob object represents a file-like object of immutable, raw data. */
@@ -899,7 +955,6 @@ declare namespace __console {
}
const isConsoleInstance: unique symbol;
export class Console {
- private printFunc;
indentLevel: number;
[isConsoleInstance]: boolean;
/** Writes the arguments to stdout */
@@ -982,7 +1037,7 @@ declare namespace __event {
constructor({
bubbles,
cancelable,
- composed
+ composed,
}?: {
bubbles?: boolean | undefined;
cancelable?: boolean | undefined;
@@ -1053,7 +1108,7 @@ declare namespace __customEvent {
bubbles,
cancelable,
composed,
- detail
+ detail,
}: __domTypes.CustomEventInit);
}
export class CustomEvent extends __event.Event
@@ -1083,7 +1138,7 @@ declare namespace __eventTarget {
constructor({
capture,
passive,
- once
+ once,
}?: {
capture?: boolean | undefined;
passive?: boolean | undefined;
@@ -1123,7 +1178,7 @@ declare namespace __io {
export enum SeekMode {
SEEK_START = 0,
SEEK_CURRENT = 1,
- SEEK_END = 2
+ SEEK_END = 2,
}
export interface Reader {
/** Reads up to p.byteLength bytes into `p`. It resolves to the number
@@ -1213,16 +1268,15 @@ declare namespace __io {
declare namespace __fetch {
class Body
- implements __domTypes.Body, __domTypes.ReadableStream, __io.ReadCloser {
- private rid;
+ implements
+ __domTypes.Body,
+ __domTypes.ReadableStream<Uint8Array>,
+ __io.ReadCloser {
readonly contentType: string;
bodyUsed: boolean;
- private _bodyPromise;
- private _data;
readonly locked: boolean;
- readonly body: null | Body;
+ readonly body: __domTypes.ReadableStream<Uint8Array>;
constructor(rid: number, contentType: string);
- private _bodyBuffer;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<__domTypes.Blob>;
formData(): Promise<__domTypes.FormData>;
@@ -1231,7 +1285,9 @@ declare namespace __fetch {
read(p: Uint8Array): Promise<number | Deno.EOF>;
close(): void;
cancel(): Promise<void>;
- getReader(): __domTypes.ReadableStreamReader;
+ getReader(options: { mode: "byob" }): __domTypes.ReadableStreamBYOBReader;
+ getReader(): __domTypes.ReadableStreamDefaultReader<Uint8Array>;
+ getReader(): __domTypes.ReadableStreamBYOBReader;
tee(): [__domTypes.ReadableStream, __domTypes.ReadableStream];
[Symbol.asyncIterator](): AsyncIterableIterator<Uint8Array>;
}
@@ -1283,7 +1339,6 @@ declare namespace __textEncoding {
ignoreBOM?: boolean;
}
export class TextDecoder {
- private _encoding;
/** Returns encoding's name, lowercased. */
readonly encoding: string;
/** Returns `true` if error mode is "fatal", and `false` otherwise. */
@@ -1333,10 +1388,7 @@ declare namespace __timers {
declare namespace __urlSearchParams {
export class URLSearchParams {
- private params;
- private url;
constructor(init?: string | string[][] | Record<string, string>);
- private updateSteps;
/** Appends a specified key/value pair as a new search parameter.
*
* searchParams.append('name', 'first');
@@ -1431,8 +1483,6 @@ declare namespace __urlSearchParams {
* searchParams.toString();
*/
toString(): string;
- private _handleStringInitialization;
- private _handleArrayInitialization;
}
}
@@ -1475,16 +1525,12 @@ declare namespace __workers {
name?: string;
}
export class WorkerImpl implements Worker {
- private readonly id;
- private isClosing;
- private readonly isClosedPromise;
onerror?: (e: Event) => void;
onmessage?: (data: any) => void;
onmessageerror?: () => void;
constructor(specifier: string, options?: WorkerOptions);
postMessage(data: any): void;
terminate(): void;
- private run;
}
}
diff --git a/cli/js/main.ts b/cli/js/main.ts
index 881d3ad4a..bd30d33f7 100644
--- a/cli/js/main.ts
+++ b/cli/js/main.ts
@@ -13,12 +13,12 @@ Object.defineProperties(globalThis, {
value: bootstrapMainRuntime,
enumerable: false,
writable: false,
- configurable: false
+ configurable: false,
},
bootstrapWorkerRuntime: {
value: bootstrapWorkerRuntime,
enumerable: false,
writable: false,
- configurable: false
- }
+ configurable: false,
+ },
});
diff --git a/cli/js/net.ts b/cli/js/net.ts
index 9be97dc2e..7c0edf1f3 100644
--- a/cli/js/net.ts
+++ b/cli/js/net.ts
@@ -168,7 +168,7 @@ export function listen(
res = netOps.listen({
transport: "tcp",
hostname: "127.0.0.1",
- ...(options as ListenOptions)
+ ...(options as ListenOptions),
});
}
@@ -205,7 +205,7 @@ export async function connect(
res = await netOps.connect({
transport: "tcp",
hostname: "127.0.0.1",
- ...options
+ ...options,
});
}
diff --git a/cli/js/ops/compiler.ts b/cli/js/ops/compiler.ts
index 0cbde6543..825cadc16 100644
--- a/cli/js/ops/compiler.ts
+++ b/cli/js/ops/compiler.ts
@@ -24,7 +24,7 @@ export function fetchSourceFiles(
> {
return sendAsync("op_fetch_source_files", {
specifiers,
- referrer
+ referrer,
});
}
@@ -47,6 +47,6 @@ export function cache(
sendSync("op_cache", {
extension,
moduleId,
- contents
+ contents,
});
}
diff --git a/cli/js/ops/dispatch_minimal.ts b/cli/js/ops/dispatch_minimal.ts
index 61d630240..570463583 100644
--- a/cli/js/ops/dispatch_minimal.ts
+++ b/cli/js/ops/dispatch_minimal.ts
@@ -54,7 +54,7 @@ export function recordFromBufMinimal(ui8: Uint8Array): RecordMinimal {
promiseId,
arg,
result,
- err
+ err,
};
}
diff --git a/cli/js/ops/errors.ts b/cli/js/ops/errors.ts
index 39793a85d..5b65d102a 100644
--- a/cli/js/ops/errors.ts
+++ b/cli/js/ops/errors.ts
@@ -21,11 +21,11 @@ export function applySourceMap(location: Location): Location {
const res = sendSync("op_apply_source_map", {
filename,
line: line - 1,
- column: column - 1
+ column: column - 1,
});
return {
filename: res.filename,
line: res.line + 1,
- column: res.column + 1
+ column: res.column + 1,
};
}
diff --git a/cli/js/ops/fs/open.ts b/cli/js/ops/fs/open.ts
index 87696935f..b587f491d 100644
--- a/cli/js/ops/fs/open.ts
+++ b/cli/js/ops/fs/open.ts
@@ -36,6 +36,6 @@ export function open(
path,
options,
openMode,
- mode
+ mode,
});
}
diff --git a/cli/js/ops/fs/stat.ts b/cli/js/ops/fs/stat.ts
index 20ca3e6b1..f455484c1 100644
--- a/cli/js/ops/fs/stat.ts
+++ b/cli/js/ops/fs/stat.ts
@@ -25,7 +25,7 @@ export interface StatResponse {
export async function lstat(path: string): Promise<FileInfo> {
const res = (await sendAsync("op_stat", {
path,
- lstat: true
+ lstat: true,
})) as StatResponse;
return new FileInfoImpl(res);
}
@@ -33,7 +33,7 @@ export async function lstat(path: string): Promise<FileInfo> {
export function lstatSync(path: string): FileInfo {
const res = sendSync("op_stat", {
path,
- lstat: true
+ lstat: true,
}) as StatResponse;
return new FileInfoImpl(res);
}
@@ -41,7 +41,7 @@ export function lstatSync(path: string): FileInfo {
export async function stat(path: string): Promise<FileInfo> {
const res = (await sendAsync("op_stat", {
path,
- lstat: false
+ lstat: false,
})) as StatResponse;
return new FileInfoImpl(res);
}
@@ -49,7 +49,7 @@ export async function stat(path: string): Promise<FileInfo> {
export function statSync(path: string): FileInfo {
const res = sendSync("op_stat", {
path,
- lstat: false
+ lstat: false,
}) as StatResponse;
return new FileInfoImpl(res);
}
diff --git a/cli/js/ops/fs/utime.ts b/cli/js/ops/fs/utime.ts
index 13cac8cb6..cd195531c 100644
--- a/cli/js/ops/fs/utime.ts
+++ b/cli/js/ops/fs/utime.ts
@@ -14,7 +14,7 @@ export function utimeSync(
path,
// TODO(ry) split atime, mtime into [seconds, nanoseconds] tuple
atime: toSecondsFromEpoch(atime),
- mtime: toSecondsFromEpoch(mtime)
+ mtime: toSecondsFromEpoch(mtime),
});
}
@@ -27,6 +27,6 @@ export async function utime(
path,
// TODO(ry) split atime, mtime into [seconds, nanoseconds] tuple
atime: toSecondsFromEpoch(atime),
- mtime: toSecondsFromEpoch(mtime)
+ mtime: toSecondsFromEpoch(mtime),
});
}
diff --git a/cli/js/ops/fs_events.ts b/cli/js/ops/fs_events.ts
index 4c08995b8..30a74f291 100644
--- a/cli/js/ops/fs_events.ts
+++ b/cli/js/ops/fs_events.ts
@@ -17,7 +17,7 @@ class FsEvents implements AsyncIterableIterator<FsEvent> {
next(): Promise<IteratorResult<FsEvent>> {
return sendAsync("op_fs_events_poll", {
- rid: this.rid
+ rid: this.rid,
});
}
diff --git a/cli/js/ops/net.ts b/cli/js/ops/net.ts
index 7734e8811..369f2ca3c 100644
--- a/cli/js/ops/net.ts
+++ b/cli/js/ops/net.ts
@@ -19,7 +19,7 @@ export enum ShutdownMode {
// Corresponding to SHUT_RD, SHUT_WR, SHUT_RDWR
Read = 0,
Write,
- ReadWrite // unused
+ ReadWrite, // unused
}
export function shutdown(rid: number, how: ShutdownMode): void {
diff --git a/cli/js/ops/os.ts b/cli/js/ops/os.ts
index d2fa4f2bb..e01718c8c 100644
--- a/cli/js/ops/os.ts
+++ b/cli/js/ops/os.ts
@@ -40,7 +40,7 @@ export function env(
set(obj, prop: string, value: string): boolean {
setEnv(prop, value);
return Reflect.set(obj, prop, value);
- }
+ },
});
}
diff --git a/cli/js/ops/tty.ts b/cli/js/ops/tty.ts
index 2d5649623..f848d2774 100644
--- a/cli/js/ops/tty.ts
+++ b/cli/js/ops/tty.ts
@@ -7,6 +7,6 @@ export function isatty(rid: number): boolean {
export function setRaw(rid: number, mode: boolean): void {
sendSync("op_set_raw", {
rid,
- mode
+ mode,
});
}
diff --git a/cli/js/ops/worker_host.ts b/cli/js/ops/worker_host.ts
index 0b9f81795..d483a5313 100644
--- a/cli/js/ops/worker_host.ts
+++ b/cli/js/ops/worker_host.ts
@@ -12,7 +12,7 @@ export function createWorker(
specifier,
hasSourceCode,
sourceCode,
- name
+ name,
});
}
diff --git a/cli/js/plugins.ts b/cli/js/plugins.ts
index 061193b4f..3fe0574ca 100644
--- a/cli/js/plugins.ts
+++ b/cli/js/plugins.ts
@@ -14,17 +14,21 @@ interface PluginOp {
}
class PluginOpImpl implements PluginOp {
- constructor(private readonly opId: number) {}
+ readonly #opId: number;
+
+ constructor(opId: number) {
+ this.#opId = opId;
+ }
dispatch(
control: Uint8Array,
zeroCopy?: ArrayBufferView | null
): Uint8Array | null {
- return core.dispatch(this.opId, control, zeroCopy);
+ return core.dispatch(this.#opId, control, zeroCopy);
}
setAsyncHandler(handler: AsyncHandler): void {
- core.setAsyncHandler(this.opId, handler);
+ core.setAsyncHandler(this.#opId, handler);
}
}
@@ -37,16 +41,16 @@ interface Plugin {
}
class PluginImpl implements Plugin {
- private _ops: { [name: string]: PluginOp } = {};
+ #ops: { [name: string]: PluginOp } = {};
- constructor(private readonly rid: number, ops: { [name: string]: number }) {
+ constructor(_rid: number, ops: { [name: string]: number }) {
for (const op in ops) {
- this._ops[op] = new PluginOpImpl(ops[op]);
+ this.#ops[op] = new PluginOpImpl(ops[op]);
}
}
get ops(): { [name: string]: PluginOp } {
- return Object.assign({}, this._ops);
+ return Object.assign({}, this.#ops);
}
}
diff --git a/cli/js/process.ts b/cli/js/process.ts
index 057e97f11..c72fdef30 100644
--- a/cli/js/process.ts
+++ b/cli/js/process.ts
@@ -113,7 +113,7 @@ export function run({
env = {},
stdout = "inherit",
stderr = "inherit",
- stdin = "inherit"
+ stdin = "inherit",
}: RunOptions): Process {
const res = runOp({
cmd: cmd.map(String),
@@ -124,7 +124,7 @@ export function run({
stderr: isRid(stderr) ? "" : stderr,
stdinRid: isRid(stdin) ? stdin : 0,
stdoutRid: isRid(stdout) ? stdout : 0,
- stderrRid: isRid(stderr) ? stderr : 0
+ stderrRid: isRid(stderr) ? stderr : 0,
}) as RunResponse;
return new Process(res);
}
diff --git a/cli/js/rbtree.ts b/cli/js/rbtree.ts
index 5de9f125d..7b01024f7 100644
--- a/cli/js/rbtree.ts
+++ b/cli/js/rbtree.ts
@@ -1,5 +1,7 @@
// Derived from https://github.com/vadimg/js_bintrees. MIT Licensed.
+import { assert } from "./util.ts";
+
class RBNode<T> {
public left: this | null;
public right: this | null;
@@ -24,16 +26,18 @@ class RBNode<T> {
}
}
-class RBTree<T> {
- private root: RBNode<T> | null;
+export class RBTree<T> {
+ #comparator: (a: T, b: T) => number;
+ #root: RBNode<T> | null;
- constructor(private comparator: (a: T, b: T) => number) {
- this.root = null;
+ constructor(comparator: (a: T, b: T) => number) {
+ this.#comparator = comparator;
+ this.#root = null;
}
- // returns null if tree is empty
+ /** Returns `null` if tree is empty. */
min(): T | null {
- let res = this.root;
+ let res = this.#root;
if (res === null) {
return null;
}
@@ -43,11 +47,11 @@ class RBTree<T> {
return res.data;
}
- // returns node data if found, null otherwise
+ /** Returns node `data` if found, `null` otherwise. */
find(data: T): T | null {
- let res = this.root;
+ let res = this.#root;
while (res !== null) {
- const c = this.comparator(data, res.data!);
+ const c = this.#comparator(data, res.data);
if (c === 0) {
return res.data;
} else {
@@ -57,13 +61,13 @@ class RBTree<T> {
return null;
}
- // returns true if inserted, false if duplicate
+ /** returns `true` if inserted, `false` if duplicate. */
insert(data: T): boolean {
let ret = false;
- if (this.root === null) {
+ if (this.#root === null) {
// empty tree
- this.root = new RBNode(data);
+ this.#root = new RBNode(data);
ret = true;
} else {
const head = new RBNode((null as unknown) as T); // fake tree root
@@ -75,8 +79,8 @@ class RBTree<T> {
let gp = null; // grandparent
let ggp = head; // grand-grand-parent
let p: RBNode<T> | null = null; // parent
- let node: RBNode<T> | null = this.root;
- ggp.right = this.root;
+ let node: RBNode<T> | null = this.#root;
+ ggp.right = this.#root;
// search down
while (true) {
@@ -96,14 +100,15 @@ class RBTree<T> {
if (isRed(node) && isRed(p)) {
const dir2 = ggp.right === gp;
+ assert(gp);
if (node === p!.getChild(last)) {
- ggp.setChild(dir2, singleRotate(gp!, !last));
+ ggp.setChild(dir2, singleRotate(gp, !last));
} else {
- ggp.setChild(dir2, doubleRotate(gp!, !last));
+ ggp.setChild(dir2, doubleRotate(gp, !last));
}
}
- const cmp = this.comparator(node.data!, data);
+ const cmp = this.#comparator(node.data, data);
// stop if found
if (cmp === 0) {
@@ -123,24 +128,24 @@ class RBTree<T> {
}
// update root
- this.root = head.right;
+ this.#root = head.right;
}
// make root black
- this.root!.red = false;
+ this.#root!.red = false;
return ret;
}
- // returns true if removed, false if not found
+ /** Returns `true` if removed, `false` if not found. */
remove(data: T): boolean {
- if (this.root === null) {
+ if (this.#root === null) {
return false;
}
const head = new RBNode((null as unknown) as T); // fake tree root
let node = head;
- node.right = this.root;
+ node.right = this.#root;
let p = null; // parent
let gp = null; // grand parent
let found = null; // found item
@@ -154,7 +159,7 @@ class RBTree<T> {
p = node;
node = node.getChild(dir)!;
- const cmp = this.comparator(data, node.data);
+ const cmp = this.#comparator(data, node.data);
dir = cmp > 0;
@@ -181,7 +186,8 @@ class RBTree<T> {
sibling.red = true;
node.red = true;
} else {
- const dir2 = gp!.right === p;
+ assert(gp);
+ const dir2 = gp.right === p;
if (isRed(sibling.getChild(last))) {
gp!.setChild(dir2, doubleRotate(p, last));
@@ -190,11 +196,14 @@ class RBTree<T> {
}
// ensure correct coloring
- const gpc = gp!.getChild(dir2)!;
+ const gpc = gp.getChild(dir2);
+ assert(gpc);
gpc.red = true;
node.red = true;
- gpc.left!.red = false;
- gpc.right!.red = false;
+ assert(gpc.left);
+ gpc.left.red = false;
+ assert(gpc.right);
+ gpc.right.red = false;
}
}
}
@@ -204,13 +213,14 @@ class RBTree<T> {
// replace and remove if found
if (found !== null) {
found.data = node.data;
- p!.setChild(p!.right === node, node.getChild(node.left === null));
+ assert(p);
+ p.setChild(p.right === node, node.getChild(node.left === null));
}
// update root and make it black
- this.root = head.right;
- if (this.root !== null) {
- this.root.red = false;
+ this.#root = head.right;
+ if (this.#root !== null) {
+ this.#root.red = false;
}
return found !== null;
@@ -222,7 +232,8 @@ function isRed<T>(node: RBNode<T> | null): boolean {
}
function singleRotate<T>(root: RBNode<T>, dir: boolean | number): RBNode<T> {
- const save = root.getChild(!dir)!;
+ const save = root.getChild(!dir);
+ assert(save);
root.setChild(!dir, save.getChild(dir));
save.setChild(dir, root);
@@ -237,5 +248,3 @@ function doubleRotate<T>(root: RBNode<T>, dir: boolean | number): RBNode<T> {
root.setChild(!dir, singleRotate(root.getChild(!dir)!, !dir));
return singleRotate(root, dir);
}
-
-export { RBTree };
diff --git a/cli/js/repl.ts b/cli/js/repl.ts
index f1b0723c8..044713678 100644
--- a/cli/js/repl.ts
+++ b/cli/js/repl.ts
@@ -17,20 +17,20 @@ const helpMsg = [
"_ Get last evaluation result",
"_error Get last thrown error",
"exit Exit the REPL",
- "help Print this help message"
+ "help Print this help message",
].join("\n");
const replCommands = {
exit: {
get(): void {
exit(0);
- }
+ },
},
help: {
get(): string {
return helpMsg;
- }
- }
+ },
+ },
};
// Error messages that allow users to continue input
@@ -42,7 +42,7 @@ const recoverableErrorMessages = [
"Missing initializer in const declaration", // const a
"Missing catch or finally after try", // try {}
"missing ) after argument list", // console.log(1
- "Unterminated template literal" // `template
+ "Unterminated template literal", // `template
// TODO(kevinkassimo): need a parser to handling errors such as:
// "Missing } in template expression" // `${ or `${ a 123 }`
];
@@ -105,10 +105,10 @@ export async function replLoop(): Promise<void> {
value: value,
writable: true,
enumerable: true,
- configurable: true
+ configurable: true,
});
console.log("Last evaluation result is no longer saved to _.");
- }
+ },
});
// Configure globalThis._error to give the last thrown error.
@@ -120,10 +120,10 @@ export async function replLoop(): Promise<void> {
value: value,
writable: true,
enumerable: true,
- configurable: true
+ configurable: true,
});
console.log("Last thrown error is no longer saved to _error.");
- }
+ },
});
while (true) {
diff --git a/cli/js/runtime_main.ts b/cli/js/runtime_main.ts
index 4c506e0ce..edb02d2d6 100644
--- a/cli/js/runtime_main.ts
+++ b/cli/js/runtime_main.ts
@@ -17,7 +17,7 @@ import {
writable,
windowOrWorkerGlobalScopeMethods,
windowOrWorkerGlobalScopeProperties,
- eventTargetProperties
+ eventTargetProperties,
} from "./globals.ts";
import { internalObject } from "./internals.ts";
import { setSignals } from "./signals.ts";
@@ -63,7 +63,7 @@ export const mainRuntimeGlobalProperties = {
onload: writable(undefined),
onunload: writable(undefined),
close: writable(windowClose),
- closed: getterOnly(() => windowIsClosing)
+ closed: getterOnly(() => windowIsClosing),
};
let hasBootstrapped = false;
@@ -102,7 +102,7 @@ export function bootstrapMainRuntime(): void {
Object.defineProperties(Deno, {
pid: readOnly(s.pid),
noColor: readOnly(s.noColor),
- args: readOnly(Object.freeze(s.args))
+ args: readOnly(Object.freeze(s.args)),
});
// Setup `Deno` global - we're actually overriding already
// existing global `Deno` with `Deno` namespace from "./deno.ts".
diff --git a/cli/js/runtime_worker.ts b/cli/js/runtime_worker.ts
index bd051dbf2..c7742cf31 100644
--- a/cli/js/runtime_worker.ts
+++ b/cli/js/runtime_worker.ts
@@ -14,7 +14,7 @@ import {
nonEnumerable,
windowOrWorkerGlobalScopeMethods,
windowOrWorkerGlobalScopeProperties,
- eventTargetProperties
+ eventTargetProperties,
} from "./globals.ts";
import * as webWorkerOps from "./ops/web_worker.ts";
import { LocationImpl } from "./web/location.ts";
@@ -85,7 +85,7 @@ export const workerRuntimeGlobalProperties = {
// TODO: should be readonly?
close: nonEnumerable(close),
postMessage: writable(postMessage),
- workerMessageRecvCallback: nonEnumerable(workerMessageRecvCallback)
+ workerMessageRecvCallback: nonEnumerable(workerMessageRecvCallback),
};
export function bootstrapWorkerRuntime(name: string): void {
diff --git a/cli/js/signals.ts b/cli/js/signals.ts
index 28bc271c4..e7fd8c04d 100644
--- a/cli/js/signals.ts
+++ b/cli/js/signals.ts
@@ -34,7 +34,7 @@ enum LinuxSignal {
SIGWINCH = 28,
SIGIO = 29,
SIGPWR = 30,
- SIGSYS = 31
+ SIGSYS = 31,
}
// From `kill -l`
@@ -69,7 +69,7 @@ enum MacOSSignal {
SIGWINCH = 28,
SIGINFO = 29,
SIGUSR1 = 30,
- SIGUSR2 = 31
+ SIGUSR2 = 31,
}
export const Signal: { [key: string]: number } = {};
@@ -122,39 +122,40 @@ export const signals = {
},
windowChange(): SignalStream {
return signal(Signal.SIGWINCH);
- }
+ },
};
export class SignalStream
implements AsyncIterableIterator<void>, PromiseLike<void> {
- private rid: number;
- private pollingPromise: Promise<boolean> = Promise.resolve(false);
- private disposed = false;
+ #disposed = false;
+ #pollingPromise: Promise<boolean> = Promise.resolve(false);
+ #rid: number;
+
constructor(signo: number) {
- this.rid = bindSignal(signo).rid;
- this.loop();
+ this.#rid = bindSignal(signo).rid;
+ this.#loop();
}
- private async pollSignal(): Promise<boolean> {
- const res = await pollSignal(this.rid);
+ #pollSignal = async (): Promise<boolean> => {
+ const res = await pollSignal(this.#rid);
return res.done;
- }
+ };
- private async loop(): Promise<void> {
+ #loop = async (): Promise<void> => {
do {
- this.pollingPromise = this.pollSignal();
- } while (!(await this.pollingPromise) && !this.disposed);
- }
+ this.#pollingPromise = this.#pollSignal();
+ } while (!(await this.#pollingPromise) && !this.#disposed);
+ };
then<T, S>(
f: (v: void) => T | Promise<T>,
g?: (v: Error) => S | Promise<S>
): Promise<T | S> {
- return this.pollingPromise.then((_): void => {}).then(f, g);
+ return this.#pollingPromise.then(() => {}).then(f, g);
}
async next(): Promise<IteratorResult<void>> {
- return { done: await this.pollingPromise, value: undefined };
+ return { done: await this.#pollingPromise, value: undefined };
}
[Symbol.asyncIterator](): AsyncIterableIterator<void> {
@@ -162,10 +163,10 @@ export class SignalStream
}
dispose(): void {
- if (this.disposed) {
+ if (this.#disposed) {
throw new Error("The stream has already been disposed.");
}
- this.disposed = true;
- unbindSignal(this.rid);
+ this.#disposed = true;
+ unbindSignal(this.#rid);
}
}
diff --git a/cli/js/symbols.ts b/cli/js/symbols.ts
index 785b47357..59d0751c0 100644
--- a/cli/js/symbols.ts
+++ b/cli/js/symbols.ts
@@ -4,5 +4,5 @@ import { customInspect } from "./web/console.ts";
export const symbols = {
internal: internalSymbol,
- customInspect
+ customInspect,
};
diff --git a/cli/js/testing.ts b/cli/js/testing.ts
index 22e719719..94a4cc702 100644
--- a/cli/js/testing.ts
+++ b/cli/js/testing.ts
@@ -11,7 +11,7 @@ import { assert } from "./util.ts";
const RED_FAILED = red("FAILED");
const GREEN_OK = green("ok");
const YELLOW_IGNORED = yellow("ignored");
-const disabledConsole = new Console((_x: string, _isErr?: boolean): void => {});
+const disabledConsole = new Console((): void => {});
function formatDuration(time = 0): string {
const timeStr = `(${time}ms)`;
@@ -140,7 +140,7 @@ export interface RunTestsOptions {
enum TestStatus {
Passed = "passed",
Failed = "failed",
- Ignored = "ignored"
+ Ignored = "ignored",
}
interface TestResult {
@@ -154,7 +154,7 @@ export enum TestEvent {
Start = "start",
TestStart = "testStart",
TestEnd = "testEnd",
- End = "end"
+ End = "end",
}
interface TestEventStart {
@@ -188,7 +188,7 @@ class TestApi {
ignored: 0,
measured: 0,
passed: 0,
- failed: 0
+ failed: 0,
};
constructor(
@@ -205,7 +205,7 @@ class TestApi {
> {
yield {
kind: TestEvent.Start,
- tests: this.testsToRun.length
+ tests: this.testsToRun.length,
};
const results: TestResult[] = [];
@@ -243,7 +243,7 @@ class TestApi {
kind: TestEvent.End,
stats: this.stats,
results,
- duration
+ duration,
};
}
}
@@ -283,33 +283,15 @@ interface TestReporter {
}
export class ConsoleTestReporter implements TestReporter {
- private encoder: TextEncoder;
-
- constructor() {
- this.encoder = new TextEncoder();
- }
-
- private log(msg: string, noNewLine = false): Promise<void> {
- if (!noNewLine) {
- msg += "\n";
- }
-
- // Using `stdout` here because it doesn't force new lines
- // compared to `console.log`; `core.print` on the other hand
- // is line-buffered and doesn't output message without newline
- stdout.writeSync(this.encoder.encode(msg));
- return Promise.resolve();
- }
-
start(event: TestEventStart): Promise<void> {
- this.log(`running ${event.tests} tests`);
+ ConsoleTestReporter.log(`running ${event.tests} tests`);
return Promise.resolve();
}
testStart(event: TestEventTestStart): Promise<void> {
const { name } = event;
- this.log(`test ${name} ... `, true);
+ ConsoleTestReporter.log(`test ${name} ... `, true);
return Promise.resolve();
}
@@ -318,13 +300,19 @@ export class ConsoleTestReporter implements TestReporter {
switch (result.status) {
case TestStatus.Passed:
- this.log(`${GREEN_OK} ${formatDuration(result.duration)}`);
+ ConsoleTestReporter.log(
+ `${GREEN_OK} ${formatDuration(result.duration)}`
+ );
break;
case TestStatus.Failed:
- this.log(`${RED_FAILED} ${formatDuration(result.duration)}`);
+ ConsoleTestReporter.log(
+ `${RED_FAILED} ${formatDuration(result.duration)}`
+ );
break;
case TestStatus.Ignored:
- this.log(`${YELLOW_IGNORED} ${formatDuration(result.duration)}`);
+ ConsoleTestReporter.log(
+ `${YELLOW_IGNORED} ${formatDuration(result.duration)}`
+ );
break;
}
@@ -334,25 +322,25 @@ export class ConsoleTestReporter implements TestReporter {
end(event: TestEventEnd): Promise<void> {
const { stats, duration, results } = event;
// Attempting to match the output of Rust's test runner.
- const failedTests = results.filter(r => r.error);
+ const failedTests = results.filter((r) => r.error);
if (failedTests.length > 0) {
- this.log(`\nfailures:\n`);
+ ConsoleTestReporter.log(`\nfailures:\n`);
for (const result of failedTests) {
- this.log(`${result.name}`);
- this.log(`${stringifyArgs([result.error!])}`);
- this.log("");
+ ConsoleTestReporter.log(`${result.name}`);
+ ConsoleTestReporter.log(`${stringifyArgs([result.error!])}`);
+ ConsoleTestReporter.log("");
}
- this.log(`failures:\n`);
+ ConsoleTestReporter.log(`failures:\n`);
for (const result of failedTests) {
- this.log(`\t${result.name}`);
+ ConsoleTestReporter.log(`\t${result.name}`);
}
}
- this.log(
+ ConsoleTestReporter.log(
`\ntest result: ${stats.failed ? RED_FAILED : GREEN_OK}. ` +
`${stats.passed} passed; ${stats.failed} failed; ` +
`${stats.ignored} ignored; ${stats.measured} measured; ` +
@@ -362,6 +350,20 @@ export class ConsoleTestReporter implements TestReporter {
return Promise.resolve();
}
+
+ static encoder = new TextEncoder();
+
+ static log(msg: string, noNewLine = false): Promise<void> {
+ if (!noNewLine) {
+ msg += "\n";
+ }
+
+ // Using `stdout` here because it doesn't force new lines
+ // compared to `console.log`; `core.print` on the other hand
+ // is line-buffered and doesn't output message without newline
+ stdout.writeSync(ConsoleTestReporter.encoder.encode(msg));
+ return Promise.resolve();
+ }
}
export async function runTests({
@@ -370,7 +372,7 @@ export async function runTests({
only = undefined,
skip = undefined,
disableLog = false,
- reporter = undefined
+ reporter = undefined,
}: RunTestsOptions = {}): Promise<{
results: TestResult[];
stats: TestStats;
diff --git a/cli/js/tests/blob_test.ts b/cli/js/tests/blob_test.ts
index 54071a11e..57793af0e 100644
--- a/cli/js/tests/blob_test.ts
+++ b/cli/js/tests/blob_test.ts
@@ -38,7 +38,7 @@ unitTest(function blobShouldNotThrowError(): void {
try {
const options1: object = {
ending: "utf8",
- hasOwnProperty: "hasOwnProperty"
+ hasOwnProperty: "hasOwnProperty",
};
const options2: object = Object.create(null);
new Blob(["Hello World"], options1);
@@ -52,7 +52,7 @@ unitTest(function blobShouldNotThrowError(): void {
unitTest(function nativeEndLine(): void {
const options: object = {
- ending: "native"
+ ending: "native",
};
const blob = new Blob(["Hello\nWorld"], options);
diff --git a/cli/js/tests/body_test.ts b/cli/js/tests/body_test.ts
index 23f6d89e4..c8f783e04 100644
--- a/cli/js/tests/body_test.ts
+++ b/cli/js/tests/body_test.ts
@@ -5,7 +5,7 @@ import { unitTest, assertEquals, assert } from "./test_util.ts";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function buildBody(body: any): Body {
const stub = new Request("", {
- body: body
+ body: body,
});
return stub as Body;
}
@@ -19,7 +19,7 @@ const intArrays = [
Uint32Array,
Uint8ClampedArray,
Float32Array,
- Float64Array
+ Float64Array,
];
unitTest(async function arrayBufferFromByteArrays(): Promise<void> {
const buffer = new TextEncoder().encode("ahoyhoy8").buffer;
diff --git a/cli/js/tests/buffer_test.ts b/cli/js/tests/buffer_test.ts
index 163ed0a30..9cfb71669 100644
--- a/cli/js/tests/buffer_test.ts
+++ b/cli/js/tests/buffer_test.ts
@@ -7,7 +7,7 @@ import {
assertEquals,
assert,
assertStrContains,
- unitTest
+ unitTest,
} from "./test_util.ts";
const { Buffer, readAll, readAllSync, writeAll, writeAllSync } = Deno;
diff --git a/cli/js/tests/chmod_test.ts b/cli/js/tests/chmod_test.ts
index e71e0bf26..8a534c701 100644
--- a/cli/js/tests/chmod_test.ts
+++ b/cli/js/tests/chmod_test.ts
@@ -22,7 +22,7 @@ unitTest(
unitTest(
{
ignore: Deno.build.os === "win",
- perms: { read: true, write: true }
+ perms: { read: true, write: true },
},
function chmodSyncSymlinkSuccess(): void {
const enc = new TextEncoder();
@@ -94,7 +94,7 @@ unitTest(
unitTest(
{
ignore: Deno.build.os === "win",
- perms: { read: true, write: true }
+ perms: { read: true, write: true },
},
async function chmodSymlinkSuccess(): Promise<void> {
const enc = new TextEncoder();
diff --git a/cli/js/tests/chown_test.ts b/cli/js/tests/chown_test.ts
index f1847a08c..2d1dc7756 100644
--- a/cli/js/tests/chown_test.ts
+++ b/cli/js/tests/chown_test.ts
@@ -7,11 +7,11 @@ if (Deno.build.os !== "win") {
// get the user ID and group ID of the current process
const uidProc = Deno.run({
stdout: "piped",
- cmd: ["python", "-c", "import os; print(os.getuid())"]
+ cmd: ["python", "-c", "import os; print(os.getuid())"],
});
const gidProc = Deno.run({
stdout: "piped",
- cmd: ["python", "-c", "import os; print(os.getgid())"]
+ cmd: ["python", "-c", "import os; print(os.getgid())"],
});
assertEquals((await uidProc.status()).code, 0);
diff --git a/cli/js/tests/console_test.ts b/cli/js/tests/console_test.ts
index e571b02fb..b4848332f 100644
--- a/cli/js/tests/console_test.ts
+++ b/cli/js/tests/console_test.ts
@@ -6,14 +6,14 @@ import { assert, assertEquals, unitTest } from "./test_util.ts";
const {
inspect,
writeSync,
- stdout
+ stdout,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} = Deno as any;
const customInspect = Deno.symbols.customInspect;
const {
Console,
- stringifyArgs
+ stringifyArgs,
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
} = Deno[Deno.symbols.internal];
@@ -37,7 +37,7 @@ unitTest(function consoleHasRightInstance(): void {
});
unitTest(function consoleTestAssertShouldNotThrowError(): void {
- mockConsole(console => {
+ mockConsole((console) => {
console.assert(true);
let hasThrown = undefined;
try {
@@ -92,7 +92,7 @@ unitTest(function consoleTestStringifyCircular(): void {
arrowFunc: () => {},
extendedClass: new Extended(),
nFunc: new Function(),
- extendedCstr: Extended
+ extendedCstr: Extended,
};
const circularObj = {
@@ -105,7 +105,7 @@ unitTest(function consoleTestStringifyCircular(): void {
nested: nestedObj,
emptyObj: {},
arr: [1, "s", false, null, nestedObj],
- baseClass: new Base()
+ baseClass: new Base(),
};
nestedObj.o = circularObj;
@@ -154,7 +154,7 @@ unitTest(function consoleTestStringifyCircular(): void {
stringify(
new Map([
[1, "one"],
- [2, "two"]
+ [2, "two"],
])
),
`Map { 1 => "one", 2 => "two" }`
@@ -192,7 +192,6 @@ unitTest(function consoleTestStringifyCircular(): void {
assertEquals(
stringify(console),
`{
- printFunc: [Function],
log: [Function],
debug: [Function],
info: [Function],
@@ -261,8 +260,8 @@ unitTest(function consoleTestStringifyLargeObject(): void {
g: 10,
asd: 2,
asda: 3,
- x: { a: "asd", x: 3 }
- }
+ x: { a: "asd", x: 3 },
+ },
};
assertEquals(
stringify(obj),
@@ -394,14 +393,14 @@ unitTest(function consoleTestWithVariousOrInvalidFormatSpecifier(): void {
unitTest(function consoleTestCallToStringOnLabel(): void {
const methods = ["count", "countReset", "time", "timeLog", "timeEnd"];
- mockConsole(console => {
+ mockConsole((console) => {
for (const method of methods) {
let hasCalled = false;
// @ts-ignore
console[method]({
toString(): void {
hasCalled = true;
- }
+ },
});
assertEquals(hasCalled, true);
}
@@ -446,7 +445,7 @@ unitTest(function consoleTestClear(): void {
// Test bound this issue
unitTest(function consoleDetachedLog(): void {
- mockConsole(console => {
+ mockConsole((console) => {
const log = console.log;
const dir = console.dir;
const dirxml = console.dirxml;
@@ -635,7 +634,7 @@ unitTest(function consoleTable(): void {
console.table(
new Map([
[1, "one"],
- [2, "two"]
+ [2, "two"],
])
);
assertEquals(
@@ -655,7 +654,7 @@ unitTest(function consoleTable(): void {
b: { c: { d: 10 }, e: [1, 2, [5, 6]] },
f: "test",
g: new Set([1, 2, 3, "test"]),
- h: new Map([[1, "one"]])
+ h: new Map([[1, "one"]]),
});
assertEquals(
out.toString(),
@@ -677,7 +676,7 @@ unitTest(function consoleTable(): void {
"test",
false,
{ a: 10 },
- ["test", { b: 20, c: "test" }]
+ ["test", { b: 20, c: "test" }],
]);
assertEquals(
out.toString(),
@@ -745,7 +744,7 @@ unitTest(function consoleTable(): void {
// console.log(Error) test
unitTest(function consoleLogShouldNotThrowError(): void {
- mockConsole(console => {
+ mockConsole((console) => {
let result = 0;
try {
console.log(new Error("foo"));
diff --git a/cli/js/tests/custom_event_test.ts b/cli/js/tests/custom_event_test.ts
index 7a5cc44ca..a8b2fcf88 100644
--- a/cli/js/tests/custom_event_test.ts
+++ b/cli/js/tests/custom_event_test.ts
@@ -7,7 +7,7 @@ unitTest(function customEventInitializedWithDetail(): void {
const customEventInit = {
bubbles: true,
cancelable: true,
- detail
+ detail,
} as CustomEventInit;
const event = new CustomEvent(type, customEventInit);
diff --git a/cli/js/tests/dispatch_minimal_test.ts b/cli/js/tests/dispatch_minimal_test.ts
index 60bb620db..afc17f4fb 100644
--- a/cli/js/tests/dispatch_minimal_test.ts
+++ b/cli/js/tests/dispatch_minimal_test.ts
@@ -3,7 +3,7 @@ import {
assertEquals,
assertMatch,
unitTest,
- unreachable
+ unreachable,
} from "./test_util.ts";
const readErrorStackPattern = new RegExp(
diff --git a/cli/js/tests/dom_iterable_test.ts b/cli/js/tests/dom_iterable_test.ts
index e16378945..827a788a9 100644
--- a/cli/js/tests/dom_iterable_test.ts
+++ b/cli/js/tests/dom_iterable_test.ts
@@ -5,7 +5,7 @@ import { unitTest, assert, assertEquals } from "./test_util.ts";
function setup() {
const dataSymbol = Symbol("data symbol");
class Base {
- private [dataSymbol] = new Map<string, number>();
+ [dataSymbol] = new Map<string, number>();
constructor(
data: Array<[string, number]> | IterableIterator<[string, number]>
@@ -21,7 +21,7 @@ function setup() {
// This is using an internal API we don't want published as types, so having
// to cast to any to "trick" TypeScript
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
- DomIterable: Deno[Deno.symbols.internal].DomIterableMixin(Base, dataSymbol)
+ DomIterable: Deno[Deno.symbols.internal].DomIterableMixin(Base, dataSymbol),
};
}
@@ -30,7 +30,7 @@ unitTest(function testDomIterable(): void {
const fixture: Array<[string, number]> = [
["foo", 1],
- ["bar", 2]
+ ["bar", 2],
];
const domIterable = new DomIterable(fixture);
diff --git a/cli/js/tests/error_stack_test.ts b/cli/js/tests/error_stack_test.ts
index 7acbd3a3d..6868be215 100644
--- a/cli/js/tests/error_stack_test.ts
+++ b/cli/js/tests/error_stack_test.ts
@@ -76,7 +76,7 @@ function getMockCallSite(
},
getPromiseIndex(): null {
return null;
- }
+ },
};
}
@@ -90,7 +90,7 @@ unitTest(function prepareStackTrace(): void {
structuredStackTrace: CallSite[]
) => string = MockError.prepareStackTrace;
const result = prepareStackTrace(new Error("foo"), [
- getMockCallSite("CLI_SNAPSHOT.js", 23, 0)
+ getMockCallSite("CLI_SNAPSHOT.js", 23, 0),
]);
assert(result.startsWith("Error: foo\n"));
assert(result.includes(".ts:"), "should remap to something in 'js/'");
@@ -100,7 +100,7 @@ unitTest(function applySourceMap(): void {
const result = Deno.applySourceMap({
filename: "CLI_SNAPSHOT.js",
line: 23,
- column: 0
+ column: 0,
});
assert(result.filename.endsWith(".ts"));
assert(result.line != null);
diff --git a/cli/js/tests/event_target_test.ts b/cli/js/tests/event_target_test.ts
index 020db1acd..45f626502 100644
--- a/cli/js/tests/event_target_test.ts
+++ b/cli/js/tests/event_target_test.ts
@@ -114,7 +114,7 @@ unitTest(function dispatchEventShouldNotThrowError(): void {
const target = new EventTarget();
const event = new Event("hasOwnProperty", {
bubbles: true,
- cancelable: false
+ cancelable: false,
});
const listener = (): void => {};
target.addEventListener("hasOwnProperty", listener);
@@ -130,7 +130,7 @@ unitTest(function eventTargetThisShouldDefaultToWindow(): void {
const {
addEventListener,
dispatchEvent,
- removeEventListener
+ removeEventListener,
} = EventTarget.prototype;
let n = 1;
const event = new Event("hello");
@@ -164,7 +164,7 @@ unitTest(function eventTargetShouldAcceptEventListenerObject(): void {
handleEvent(e: Event): void {
assertEquals(e, event);
++callCount;
- }
+ },
};
target.addEventListener("foo", listener);
@@ -213,7 +213,7 @@ unitTest(
handleEvent(e: Event): void {
assertEquals(e, event);
++callCount;
- }
+ },
};
target.addEventListener("foo", listener);
diff --git a/cli/js/tests/fetch_test.ts b/cli/js/tests/fetch_test.ts
index 67675177e..432ecd59c 100644
--- a/cli/js/tests/fetch_test.ts
+++ b/cli/js/tests/fetch_test.ts
@@ -5,7 +5,7 @@ import {
assertEquals,
assertStrContains,
assertThrows,
- fail
+ fail,
} from "./test_util.ts";
unitTest({ perms: { net: true } }, async function fetchProtocolError(): Promise<
@@ -174,7 +174,7 @@ unitTest(
unitTest(
{
- perms: { net: true }
+ perms: { net: true },
},
async function fetchWithRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/"); // will redirect to http://localhost:4545/
@@ -188,7 +188,7 @@ unitTest(
unitTest(
{
- perms: { net: true }
+ perms: { net: true },
},
async function fetchWithRelativeRedirection(): Promise<void> {
const response = await fetch("http://localhost:4545/cli/tests"); // will redirect to /cli/tests/
@@ -204,7 +204,7 @@ unitTest(
// FIXME(bartlomieju):
// The feature below is not implemented, but the test should work after implementation
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function fetchWithInfRedirection(): Promise<void> {
const response = await fetch("http://localhost:4549/cli/tests"); // will redirect to the same place
@@ -218,7 +218,7 @@ unitTest(
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
- body: data
+ body: data,
});
const text = await response.text();
assertEquals(text, data);
@@ -232,7 +232,7 @@ unitTest(
const data = "Hello World";
const req = new Request("http://localhost:4545/echo_server", {
method: "POST",
- body: data
+ body: data,
});
const response = await fetch(req);
const text = await response.text();
@@ -246,7 +246,7 @@ unitTest(
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
- body: new TextEncoder().encode(data)
+ body: new TextEncoder().encode(data),
});
const text = await response.text();
assertEquals(text, data);
@@ -260,7 +260,7 @@ unitTest(
const params = new URLSearchParams(data);
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
- body: params
+ body: params,
});
const text = await response.text();
assertEquals(text, data);
@@ -277,11 +277,11 @@ unitTest({ perms: { net: true } }, async function fetchInitBlobBody(): Promise<
> {
const data = "const a = 1";
const blob = new Blob([data], {
- type: "text/javascript"
+ type: "text/javascript",
});
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
- body: blob
+ body: blob,
});
const text = await response.text();
assertEquals(text, data);
@@ -295,7 +295,7 @@ unitTest(
form.append("field", "value");
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
- body: form
+ body: form,
});
const resultForm = await response.formData();
assertEquals(form.get("field"), resultForm.get("field"));
@@ -308,7 +308,7 @@ unitTest({ perms: { net: true } }, async function fetchUserAgent(): Promise<
const data = "Hello World";
const response = await fetch("http://localhost:4545/echo_server", {
method: "POST",
- body: new TextEncoder().encode(data)
+ body: new TextEncoder().encode(data),
});
assertEquals(response.headers.get("user-agent"), `Deno/${Deno.version.deno}`);
await response.text();
@@ -337,7 +337,7 @@ function bufferServer(addr: string): Deno.Buffer {
const [hostname, port] = addr.split(":");
const listener = Deno.listen({
hostname,
- port: Number(port)
+ port: Number(port),
}) as Deno.Listener;
const buf = new Deno.Buffer();
listener.accept().then(async (conn: Deno.Conn) => {
@@ -364,7 +364,7 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function fetchRequest(): Promise<void> {
const addr = "127.0.0.1:4501";
@@ -373,8 +373,8 @@ unitTest(
method: "POST",
headers: [
["Hello", "World"],
- ["Foo", "Bar"]
- ]
+ ["Foo", "Bar"],
+ ],
});
assertEquals(response.status, 404);
assertEquals(response.headers.get("Content-Length"), "2");
@@ -384,7 +384,7 @@ unitTest(
"POST /blah HTTP/1.1\r\n",
"hello: World\r\n",
"foo: Bar\r\n",
- `host: ${addr}\r\n\r\n`
+ `host: ${addr}\r\n\r\n`,
].join("");
assertEquals(actual, expected);
}
@@ -394,7 +394,7 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function fetchPostBodyString(): Promise<void> {
const addr = "127.0.0.1:4502";
@@ -404,9 +404,9 @@ unitTest(
method: "POST",
headers: [
["Hello", "World"],
- ["Foo", "Bar"]
+ ["Foo", "Bar"],
],
- body
+ body,
});
assertEquals(response.status, 404);
assertEquals(response.headers.get("Content-Length"), "2");
@@ -418,7 +418,7 @@ unitTest(
"foo: Bar\r\n",
`host: ${addr}\r\n`,
`content-length: ${body.length}\r\n\r\n`,
- body
+ body,
].join("");
assertEquals(actual, expected);
}
@@ -428,7 +428,7 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function fetchPostBodyTypedArray(): Promise<void> {
const addr = "127.0.0.1:4503";
@@ -439,9 +439,9 @@ unitTest(
method: "POST",
headers: [
["Hello", "World"],
- ["Foo", "Bar"]
+ ["Foo", "Bar"],
],
- body
+ body,
});
assertEquals(response.status, 404);
assertEquals(response.headers.get("Content-Length"), "2");
@@ -453,7 +453,7 @@ unitTest(
"foo: Bar\r\n",
`host: ${addr}\r\n`,
`content-length: ${body.byteLength}\r\n\r\n`,
- bodyStr
+ bodyStr,
].join("");
assertEquals(actual, expected);
}
@@ -461,11 +461,11 @@ unitTest(
unitTest(
{
- perms: { net: true }
+ perms: { net: true },
},
async function fetchWithManualRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/", {
- redirect: "manual"
+ redirect: "manual",
}); // will redirect to http://localhost:4545/
assertEquals(response.status, 0);
assertEquals(response.statusText, "");
@@ -484,11 +484,11 @@ unitTest(
unitTest(
{
- perms: { net: true }
+ perms: { net: true },
},
async function fetchWithErrorRedirection(): Promise<void> {
const response = await fetch("http://localhost:4546/", {
- redirect: "error"
+ redirect: "error",
}); // will redirect to http://localhost:4545/
assertEquals(response.status, 0);
assertEquals(response.statusText, "");
diff --git a/cli/js/tests/file_test.ts b/cli/js/tests/file_test.ts
index 1a7a5f88b..4941554ad 100644
--- a/cli/js/tests/file_test.ts
+++ b/cli/js/tests/file_test.ts
@@ -58,7 +58,7 @@ unitTest(function fileVariousFileBits(): void {
new Blob(),
new Uint8Array([0x50, 0x41]),
new Uint16Array([0x5353]),
- new Uint32Array([0x53534150])
+ new Uint32Array([0x53534150]),
],
16
);
diff --git a/cli/js/tests/files_test.ts b/cli/js/tests/files_test.ts
index 39af460b8..f81ed3c47 100644
--- a/cli/js/tests/files_test.ts
+++ b/cli/js/tests/files_test.ts
@@ -3,7 +3,7 @@ import {
unitTest,
assert,
assertEquals,
- assertStrContains
+ assertStrContains,
} from "./test_util.ts";
unitTest(function filesStdioFileDescriptors(): void {
@@ -46,15 +46,17 @@ unitTest(async function readerToAsyncIterator(): Promise<void> {
const encoder = new TextEncoder();
class TestReader implements Deno.Reader {
- private offset = 0;
- private buf = new Uint8Array(encoder.encode(this.s));
+ #offset = 0;
+ #buf: Uint8Array;
- constructor(private readonly s: string) {}
+ constructor(s: string) {
+ this.#buf = new Uint8Array(encoder.encode(s));
+ }
read(p: Uint8Array): Promise<number | Deno.EOF> {
- const n = Math.min(p.byteLength, this.buf.byteLength - this.offset);
- p.set(this.buf.slice(this.offset, this.offset + n));
- this.offset += n;
+ const n = Math.min(p.byteLength, this.#buf.byteLength - this.#offset);
+ p.set(this.#buf.slice(this.#offset, this.#offset + n));
+ this.#offset += n;
if (n === 0) {
return Promise.resolve(Deno.EOF);
@@ -76,14 +78,14 @@ unitTest(async function readerToAsyncIterator(): Promise<void> {
unitTest(
{
- perms: { read: true, write: true }
+ perms: { read: true, write: true },
},
function openSyncMode(): void {
const path = Deno.makeTempDirSync() + "/test_openSync.txt";
const file = Deno.openSync(path, {
write: true,
createNew: true,
- mode: 0o626
+ mode: 0o626,
});
file.close();
const pathInfo = Deno.statSync(path);
@@ -95,14 +97,14 @@ unitTest(
unitTest(
{
- perms: { read: true, write: true }
+ perms: { read: true, write: true },
},
async function openMode(): Promise<void> {
const path = (await Deno.makeTempDir()) + "/test_open.txt";
const file = await Deno.open(path, {
write: true,
createNew: true,
- mode: 0o626
+ mode: 0o626,
});
file.close();
const pathInfo = Deno.statSync(path);
@@ -198,7 +200,7 @@ unitTest(
const w = {
write: true,
truncate: true,
- create: true
+ create: true,
};
const file = await Deno.open(filename, w);
diff --git a/cli/js/tests/form_data_test.ts b/cli/js/tests/form_data_test.ts
index 9b218547c..f51a51190 100644
--- a/cli/js/tests/form_data_test.ts
+++ b/cli/js/tests/form_data_test.ts
@@ -88,7 +88,7 @@ unitTest(function formDataSetEmptyBlobSuccess(): void {
unitTest(function formDataParamsForEachSuccess(): void {
const init = [
["a", "54"],
- ["b", "true"]
+ ["b", "true"],
];
const formData = new FormData();
for (const [name, value] of init) {
@@ -110,7 +110,7 @@ unitTest(function formDataParamsArgumentsCheck(): void {
"getAll",
"get",
"has",
- "forEach"
+ "forEach",
] as const;
const methodRequireTwoParams = ["append", "set"] as const;
diff --git a/cli/js/tests/format_error_test.ts b/cli/js/tests/format_error_test.ts
index 9831ef160..42c16b0c0 100644
--- a/cli/js/tests/format_error_test.ts
+++ b/cli/js/tests/format_error_test.ts
@@ -11,8 +11,8 @@ unitTest(function formatDiagnosticBasic() {
scriptResourceName: "foo.ts",
startColumn: 1,
endColumn: 2,
- code: 4000
- }
+ code: 4000,
+ },
];
const out = Deno.formatDiagnostics(fixture);
assert(out.includes("Example error"));
diff --git a/cli/js/tests/headers_test.ts b/cli/js/tests/headers_test.ts
index fcb5385a5..1ed58c9a4 100644
--- a/cli/js/tests/headers_test.ts
+++ b/cli/js/tests/headers_test.ts
@@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { unitTest, assert, assertEquals } from "./test_util.ts";
const {
- stringifyArgs
+ stringifyArgs,
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
} = Deno[Deno.symbols.internal];
@@ -29,7 +29,7 @@ const headerDict: Record<string, string> = {
name3: "value3",
// @ts-ignore
name4: undefined,
- "Content-Type": "value4"
+ "Content-Type": "value4",
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const headerSeq: any[] = [];
@@ -142,7 +142,7 @@ const headerEntriesDict: Record<string, string> = {
name: "value3",
"content-Type": "value4",
"Content-Typ": "value5",
- "Content-Types": "value6"
+ "Content-Types": "value6",
};
unitTest(function headerForEachSuccess(): void {
@@ -346,7 +346,7 @@ unitTest(function customInspectReturnsCorrectHeadersFormat(): void {
);
const multiParamHeader = new Headers([
["Content-Type", "application/json"],
- ["Content-Length", "1337"]
+ ["Content-Length", "1337"],
]);
assertEquals(
stringify(multiParamHeader),
diff --git a/cli/js/tests/internals_test.ts b/cli/js/tests/internals_test.ts
index fb712707c..b794bb5e8 100644
--- a/cli/js/tests/internals_test.ts
+++ b/cli/js/tests/internals_test.ts
@@ -3,7 +3,7 @@ import { unitTest, assert } from "./test_util.ts";
unitTest(function internalsExists(): void {
const {
- stringifyArgs
+ stringifyArgs,
// @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol
} = Deno[Deno.symbols.internal];
assert(!!stringifyArgs);
diff --git a/cli/js/tests/net_test.ts b/cli/js/tests/net_test.ts
index 2c077c102..6eb0f0dc6 100644
--- a/cli/js/tests/net_test.ts
+++ b/cli/js/tests/net_test.ts
@@ -3,7 +3,7 @@ import {
unitTest,
assert,
assertEquals,
- createResolvable
+ createResolvable,
} from "./test_util.ts";
unitTest({ perms: { net: true } }, function netTcpListenClose(): void {
@@ -18,13 +18,13 @@ unitTest(
{
perms: { net: true },
// TODO:
- ignore: Deno.build.os === "win"
+ ignore: Deno.build.os === "win",
},
function netUdpListenClose(): void {
const socket = Deno.listen({
hostname: "127.0.0.1",
port: 4500,
- transport: "udp"
+ transport: "udp",
});
assert(socket.addr.transport === "udp");
assertEquals(socket.addr.hostname, "127.0.0.1");
@@ -39,7 +39,7 @@ unitTest(
const filePath = Deno.makeTempFileSync();
const socket = Deno.listen({
address: filePath,
- transport: "unix"
+ transport: "unix",
});
assert(socket.addr.transport === "unix");
assertEquals(socket.addr.address, filePath);
@@ -53,7 +53,7 @@ unitTest(
const filePath = Deno.makeTempFileSync();
const socket = Deno.listen({
address: filePath,
- transport: "unixpacket"
+ transport: "unixpacket",
});
assert(socket.addr.transport === "unixpacket");
assertEquals(socket.addr.address, filePath);
@@ -63,7 +63,7 @@ unitTest(
unitTest(
{
- perms: { net: true }
+ perms: { net: true },
},
async function netTcpCloseWhileAccept(): Promise<void> {
const listener = Deno.listen({ port: 4501 });
@@ -87,7 +87,7 @@ unitTest(
const filePath = await Deno.makeTempFile();
const listener = Deno.listen({
address: filePath,
- transport: "unix"
+ transport: "unix",
});
const p = listener.accept();
listener.close();
@@ -337,7 +337,7 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function netListenAsyncIterator(): Promise<void> {
const addr = { hostname: "127.0.0.1", port: 4500 };
@@ -372,14 +372,14 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function netCloseReadSuccess() {
const addr = { hostname: "127.0.0.1", port: 4500 };
const listener = Deno.listen(addr);
const closeDeferred = createResolvable();
const closeReadDeferred = createResolvable();
- listener.accept().then(async conn => {
+ listener.accept().then(async (conn) => {
await closeReadDeferred;
await conn.write(new Uint8Array([1, 2, 3]));
const buf = new Uint8Array(1024);
@@ -409,13 +409,13 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function netDoubleCloseRead() {
const addr = { hostname: "127.0.0.1", port: 4500 };
const listener = Deno.listen(addr);
const closeDeferred = createResolvable();
- listener.accept().then(async conn => {
+ listener.accept().then(async (conn) => {
await conn.write(new Uint8Array([1, 2, 3]));
await closeDeferred;
conn.close();
@@ -441,13 +441,13 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function netCloseWriteSuccess() {
const addr = { hostname: "127.0.0.1", port: 4500 };
const listener = Deno.listen(addr);
const closeDeferred = createResolvable();
- listener.accept().then(async conn => {
+ listener.accept().then(async (conn) => {
await conn.write(new Uint8Array([1, 2, 3]));
await closeDeferred;
conn.close();
@@ -480,13 +480,13 @@ unitTest(
{
// FIXME(bartlomieju)
ignore: true,
- perms: { net: true }
+ perms: { net: true },
},
async function netDoubleCloseWrite() {
const addr = { hostname: "127.0.0.1", port: 4500 };
const listener = Deno.listen(addr);
const closeDeferred = createResolvable();
- listener.accept().then(async conn => {
+ listener.accept().then(async (conn) => {
await closeDeferred;
conn.close();
});
@@ -509,7 +509,7 @@ unitTest(
unitTest(
{
- perms: { net: true }
+ perms: { net: true },
},
async function netHangsOnClose() {
let acceptedConn: Deno.Conn;
diff --git a/cli/js/tests/os_test.ts b/cli/js/tests/os_test.ts
index ef45d36fe..423cded50 100644
--- a/cli/js/tests/os_test.ts
+++ b/cli/js/tests/os_test.ts
@@ -4,7 +4,7 @@ import {
assertEquals,
assertNotEquals,
assertThrows,
- unitTest
+ unitTest,
} from "./test_util.ts";
unitTest({ perms: { env: true } }, function envSuccess(): void {
@@ -67,7 +67,7 @@ unitTest(
const proc = Deno.run({
cmd: [Deno.execPath(), "eval", src],
env: inputEnv,
- stdout: "piped"
+ stdout: "piped",
});
const status = await proc.status();
assertEquals(status.success, true);
@@ -134,121 +134,121 @@ unitTest({ perms: { env: true } }, function getDir(): void {
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "cache",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "executable",
runtime: [
{ os: "mac", shouldHaveValue: false },
{ os: "win", shouldHaveValue: false },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "data",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "data_local",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "audio",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "desktop",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "document",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "download",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "font",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: false },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "picture",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "public",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "template",
runtime: [
{ os: "mac", shouldHaveValue: false },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
+ { os: "linux", shouldHaveValue: false },
+ ],
},
{
kind: "tmp",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: true }
- ]
+ { os: "linux", shouldHaveValue: true },
+ ],
},
{
kind: "video",
runtime: [
{ os: "mac", shouldHaveValue: true },
{ os: "win", shouldHaveValue: true },
- { os: "linux", shouldHaveValue: false }
- ]
- }
+ { os: "linux", shouldHaveValue: false },
+ ],
+ },
];
for (const s of scenes) {
diff --git a/cli/js/tests/process_test.ts b/cli/js/tests/process_test.ts
index 216b8a3bd..47efd86d5 100644
--- a/cli/js/tests/process_test.ts
+++ b/cli/js/tests/process_test.ts
@@ -3,7 +3,7 @@ import {
assert,
assertEquals,
assertStrContains,
- unitTest
+ unitTest,
} from "./test_util.ts";
const { kill, run, readFile, open, makeTempDir, writeFile } = Deno;
@@ -22,7 +22,7 @@ unitTest({ perms: { run: true } }, async function runSuccess(): Promise<void> {
const p = run({
cmd: ["python", "-c", "print('hello world')"],
stdout: "piped",
- stderr: "null"
+ stderr: "null",
});
const status = await p.status();
assertEquals(status.success, true);
@@ -36,7 +36,7 @@ unitTest(
{ perms: { run: true } },
async function runCommandFailedWithCode(): Promise<void> {
const p = run({
- cmd: ["python", "-c", "import sys;sys.exit(41 + 1)"]
+ cmd: ["python", "-c", "import sys;sys.exit(41 + 1)"],
});
const status = await p.status();
assertEquals(status.success, false);
@@ -50,11 +50,11 @@ unitTest(
{
// No signals on windows.
ignore: Deno.build.os === "win",
- perms: { run: true }
+ perms: { run: true },
},
async function runCommandFailedWithSignal(): Promise<void> {
const p = run({
- cmd: ["python", "-c", "import os;os.kill(os.getpid(), 9)"]
+ cmd: ["python", "-c", "import os;os.kill(os.getpid(), 9)"],
});
const status = await p.status();
assertEquals(status.success, false);
@@ -102,7 +102,7 @@ while True:
Deno.writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram));
const p = run({
cwd,
- cmd: ["python", `${pyProgramFile}.py`]
+ cmd: ["python", `${pyProgramFile}.py`],
});
// Write the expected exit code *after* starting python.
@@ -123,7 +123,7 @@ unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise<
> {
const p = run({
cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
- stdin: "piped"
+ stdin: "piped",
});
assert(p.stdin);
assert(!p.stdout);
@@ -147,7 +147,7 @@ unitTest({ perms: { run: true } }, async function runStdoutPiped(): Promise<
> {
const p = run({
cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"],
- stdout: "piped"
+ stdout: "piped",
});
assert(!p.stdin);
assert(!p.stderr);
@@ -176,7 +176,7 @@ unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
> {
const p = run({
cmd: ["python", "-c", "import sys; sys.stderr.write('hello')"],
- stderr: "piped"
+ stderr: "piped",
});
assert(!p.stdin);
assert(!p.stdout);
@@ -203,7 +203,7 @@ unitTest({ perms: { run: true } }, async function runStderrPiped(): Promise<
unitTest({ perms: { run: true } }, async function runOutput(): Promise<void> {
const p = run({
cmd: ["python", "-c", "import sys; sys.stdout.write('hello')"],
- stdout: "piped"
+ stdout: "piped",
});
const output = await p.output();
const s = new TextDecoder().decode(output);
@@ -216,7 +216,7 @@ unitTest({ perms: { run: true } }, async function runStderrOutput(): Promise<
> {
const p = run({
cmd: ["python", "-c", "import sys; sys.stderr.write('error')"],
- stderr: "piped"
+ stderr: "piped",
});
const error = await p.stderrOutput();
const s = new TextDecoder().decode(error);
@@ -235,10 +235,10 @@ unitTest(
cmd: [
"python",
"-c",
- "import sys; sys.stderr.write('error\\n'); sys.stdout.write('output\\n');"
+ "import sys; sys.stderr.write('error\\n'); sys.stdout.write('output\\n');",
],
stdout: file.rid,
- stderr: file.rid
+ stderr: file.rid,
});
await p.status();
@@ -265,7 +265,7 @@ unitTest(
const p = run({
cmd: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"],
- stdin: file.rid
+ stdin: file.rid,
});
const status = await p.status();
@@ -280,13 +280,13 @@ unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> {
cmd: [
"python",
"-c",
- "import os, sys; sys.stdout.write(os.environ.get('FOO', '') + os.environ.get('BAR', ''))"
+ "import os, sys; sys.stdout.write(os.environ.get('FOO', '') + os.environ.get('BAR', ''))",
],
env: {
FOO: "0123",
- BAR: "4567"
+ BAR: "4567",
},
- stdout: "piped"
+ stdout: "piped",
});
const output = await p.output();
const s = new TextDecoder().decode(output);
@@ -299,9 +299,9 @@ unitTest({ perms: { run: true } }, async function runClose(): Promise<void> {
cmd: [
"python",
"-c",
- "from time import sleep; import sys; sleep(10000); sys.stderr.write('error')"
+ "from time import sleep; import sys; sleep(10000); sys.stderr.write('error')",
],
- stderr: "piped"
+ stderr: "piped",
});
assert(!p.stdin);
assert(!p.stdout);
@@ -343,7 +343,7 @@ if (Deno.build.os !== "win") {
void
> {
const p = run({
- cmd: ["python", "-c", "from time import sleep; sleep(10000)"]
+ cmd: ["python", "-c", "from time import sleep; sleep(10000)"],
});
assertEquals(Deno.Signal.SIGINT, 2);
@@ -361,7 +361,7 @@ if (Deno.build.os !== "win") {
unitTest({ perms: { run: true } }, function killFailed(): void {
const p = run({
- cmd: ["python", "-c", "from time import sleep; sleep(10000)"]
+ cmd: ["python", "-c", "from time import sleep; sleep(10000)"],
});
assert(!p.stdin);
assert(!p.stdout);
diff --git a/cli/js/tests/realpath_test.ts b/cli/js/tests/realpath_test.ts
index d185e4095..7725a3aa8 100644
--- a/cli/js/tests/realpath_test.ts
+++ b/cli/js/tests/realpath_test.ts
@@ -15,7 +15,7 @@ unitTest({ perms: { read: true } }, function realpathSyncSuccess(): void {
unitTest(
{
ignore: Deno.build.os === "win",
- perms: { read: true, write: true }
+ perms: { read: true, write: true },
},
function realpathSyncSymlink(): void {
const testDir = Deno.makeTempDirSync();
@@ -67,7 +67,7 @@ unitTest({ perms: { read: true } }, async function realpathSuccess(): Promise<
unitTest(
{
ignore: Deno.build.os === "win",
- perms: { read: true, write: true }
+ perms: { read: true, write: true },
},
async function realpathSymlink(): Promise<void> {
const testDir = Deno.makeTempDirSync();
diff --git a/cli/js/tests/request_test.ts b/cli/js/tests/request_test.ts
index 15e19e285..8a276c5e7 100644
--- a/cli/js/tests/request_test.ts
+++ b/cli/js/tests/request_test.ts
@@ -6,8 +6,8 @@ unitTest(function fromInit(): void {
body: "ahoyhoy",
method: "POST",
headers: {
- "test-header": "value"
- }
+ "test-header": "value",
+ },
});
// @ts-ignore
@@ -34,7 +34,7 @@ unitTest(async function cloneRequestBodyStream(): Promise<void> {
// hack to get a stream
const stream = new Request("", { body: "a test body" }).body;
const r1 = new Request("https://example.com", {
- body: stream
+ body: stream,
});
const r2 = r1.clone();
diff --git a/cli/js/tests/signal_test.ts b/cli/js/tests/signal_test.ts
index c966e696b..a51df09d7 100644
--- a/cli/js/tests/signal_test.ts
+++ b/cli/js/tests/signal_test.ts
@@ -4,7 +4,7 @@ import {
assert,
assertEquals,
assertThrows,
- createResolvable
+ createResolvable,
} from "./test_util.ts";
function defer(n: number): Promise<void> {
diff --git a/cli/js/tests/test_util.ts b/cli/js/tests/test_util.ts
index 980d32bac..da2e917f8 100644
--- a/cli/js/tests/test_util.ts
+++ b/cli/js/tests/test_util.ts
@@ -10,7 +10,7 @@ export {
assertStrictEq,
assertStrContains,
unreachable,
- fail
+ fail,
} from "../../../std/testing/asserts.ts";
export { readLines } from "../../../std/io/bufio.ts";
export { parse as parseArgs } from "../../../std/flags/mod.ts";
@@ -28,7 +28,7 @@ export interface Permissions {
export function fmtPerms(perms: Permissions): string {
const p = Object.keys(perms)
.filter((e): boolean => perms[e as keyof Permissions] === true)
- .map(key => `--allow-${key}`);
+ .map((key) => `--allow-${key}`);
if (p.length) {
return p.join(" ");
@@ -48,7 +48,7 @@ export async function getProcessPermissions(): Promise<Permissions> {
net: await isGranted("net"),
env: await isGranted("env"),
plugin: await isGranted("plugin"),
- hrtime: await isGranted("hrtime")
+ hrtime: await isGranted("hrtime"),
};
}
@@ -108,7 +108,7 @@ function normalizeTestPermissions(perms: UnitTestPermissions): Permissions {
run: !!perms.run,
env: !!perms.env,
plugin: !!perms.plugin,
- hrtime: !!perms.hrtime
+ hrtime: !!perms.hrtime,
};
}
@@ -170,7 +170,7 @@ export function unitTest(
name,
fn,
ignore: !!options.ignore,
- perms: normalizedPerms
+ perms: normalizedPerms,
};
REGISTERED_UNIT_TESTS.push(unitTestDefinition);
@@ -194,17 +194,19 @@ export function createResolvable<T>(): Resolvable<T> {
return Object.assign(promise, methods!) as Resolvable<T>;
}
+const encoder = new TextEncoder();
+
export class SocketReporter implements Deno.TestReporter {
- private encoder: TextEncoder;
+ #conn: Deno.Conn;
- constructor(private conn: Deno.Conn) {
- this.encoder = new TextEncoder();
+ constructor(conn: Deno.Conn) {
+ this.#conn = conn;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async write(msg: any): Promise<void> {
- const encodedMsg = this.encoder.encode(JSON.stringify(msg) + "\n");
- await Deno.writeAll(this.conn, encodedMsg);
+ const encodedMsg = encoder.encode(JSON.stringify(msg) + "\n");
+ await Deno.writeAll(this.#conn, encodedMsg);
}
async start(msg: Deno.TestEventStart): Promise<void> {
@@ -229,9 +231,9 @@ export class SocketReporter implements Deno.TestReporter {
}
async end(msg: Deno.TestEventEnd): Promise<void> {
- const encodedMsg = this.encoder.encode(JSON.stringify(msg));
- await Deno.writeAll(this.conn, encodedMsg);
- this.conn.closeWrite();
+ const encodedMsg = encoder.encode(JSON.stringify(msg));
+ await Deno.writeAll(this.#conn, encodedMsg);
+ this.#conn.closeWrite();
}
}
@@ -245,7 +247,7 @@ unitTest(function permissionsMatches(): void {
env: false,
run: false,
plugin: false,
- hrtime: false
+ hrtime: false,
},
normalizeTestPermissions({ read: true })
)
@@ -260,7 +262,7 @@ unitTest(function permissionsMatches(): void {
env: false,
run: false,
plugin: false,
- hrtime: false
+ hrtime: false,
},
normalizeTestPermissions({})
)
@@ -275,7 +277,7 @@ unitTest(function permissionsMatches(): void {
env: true,
run: true,
plugin: true,
- hrtime: true
+ hrtime: true,
},
normalizeTestPermissions({ read: true })
),
@@ -291,7 +293,7 @@ unitTest(function permissionsMatches(): void {
env: false,
run: false,
plugin: false,
- hrtime: false
+ hrtime: false,
},
normalizeTestPermissions({ read: true })
),
@@ -307,7 +309,7 @@ unitTest(function permissionsMatches(): void {
env: true,
run: true,
plugin: true,
- hrtime: true
+ hrtime: true,
},
{
read: true,
@@ -316,7 +318,7 @@ unitTest(function permissionsMatches(): void {
env: true,
run: true,
plugin: true,
- hrtime: true
+ hrtime: true,
}
)
);
@@ -330,9 +332,9 @@ unitTest(
{ perms: { read: true } },
function assertAllUnitTestFilesImported(): void {
const directoryTestFiles = Deno.readdirSync("./cli/js/tests/")
- .map(k => k.name)
+ .map((k) => k.name)
.filter(
- file =>
+ (file) =>
file!.endsWith(".ts") &&
!file!.endsWith("unit_tests.ts") &&
!file!.endsWith("test_util.ts") &&
@@ -344,12 +346,12 @@ unitTest(
const importLines = new TextDecoder("utf-8")
.decode(unitTestsFile)
.split("\n")
- .filter(line => line.startsWith("import"));
+ .filter((line) => line.startsWith("import"));
const importedTestFiles = importLines.map(
- relativeFilePath => relativeFilePath.match(/\/([^\/]+)";/)![1]
+ (relativeFilePath) => relativeFilePath.match(/\/([^\/]+)";/)![1]
);
- directoryTestFiles.forEach(dirFile => {
+ directoryTestFiles.forEach((dirFile) => {
if (!importedTestFiles.includes(dirFile!)) {
throw new Error(
"cil/js/tests/unit_tests.ts is missing import of test file: cli/js/" +
diff --git a/cli/js/tests/testing_test.ts b/cli/js/tests/testing_test.ts
index 9ed89f532..09378ec30 100644
--- a/cli/js/tests/testing_test.ts
+++ b/cli/js/tests/testing_test.ts
@@ -18,7 +18,7 @@ unitTest(function nameOfTestCaseCantBeEmpty(): void {
() => {
Deno.test({
name: "",
- fn: () => {}
+ fn: () => {},
});
},
TypeError,
@@ -29,7 +29,7 @@ unitTest(function nameOfTestCaseCantBeEmpty(): void {
unitTest(function testFnCantBeAnonymous(): void {
assertThrows(
() => {
- Deno.test(function() {});
+ Deno.test(function () {});
},
TypeError,
"The test function can't be anonymous"
diff --git a/cli/js/tests/text_encoding_test.ts b/cli/js/tests/text_encoding_test.ts
index e85655feb..c8a7fbe42 100644
--- a/cli/js/tests/text_encoding_test.ts
+++ b/cli/js/tests/text_encoding_test.ts
@@ -21,7 +21,7 @@ unitTest(function atobWithAsciiWhitespace(): void {
"aGVsbG8gd29ybGQ=\n",
"aGVsbG\t8gd29ybGQ=",
`aGVsbG\t8g
- d29ybGQ=`
+ d29ybGQ=`,
];
for (const encoded of encodedList) {
diff --git a/cli/js/tests/timers_test.ts b/cli/js/tests/timers_test.ts
index f758d5fca..7adff0095 100644
--- a/cli/js/tests/timers_test.ts
+++ b/cli/js/tests/timers_test.ts
@@ -4,7 +4,7 @@ import {
createResolvable,
assert,
assertEquals,
- assertNotEquals
+ assertNotEquals,
} from "./test_util.ts";
function deferred(): {
@@ -23,7 +23,7 @@ function deferred(): {
return {
promise,
resolve: resolve!,
- reject: reject!
+ reject: reject!,
};
}
@@ -180,7 +180,7 @@ unitTest(async function timeoutCallbackThis(): Promise<void> {
foo(): void {
assertEquals(this, window);
resolve();
- }
+ },
};
setTimeout(obj.foo, 1);
await promise;
@@ -198,7 +198,7 @@ unitTest(async function timeoutBindThis(): Promise<void> {
[],
"foo",
(): void => {},
- Object.prototype
+ Object.prototype,
];
for (const thisArg of thisCheckPassed) {
@@ -240,7 +240,7 @@ unitTest(function clearTimeoutShouldConvertToNumber(): void {
valueOf(): number {
called = true;
return 1;
- }
+ },
};
clearTimeout((obj as unknown) as number);
assert(called);
diff --git a/cli/js/tests/tls_test.ts b/cli/js/tests/tls_test.ts
index 20dd62f9b..019b81652 100644
--- a/cli/js/tests/tls_test.ts
+++ b/cli/js/tests/tls_test.ts
@@ -3,7 +3,7 @@ import {
assert,
assertEquals,
createResolvable,
- unitTest
+ unitTest,
} from "./test_util.ts";
import { BufWriter, BufReader } from "../../../std/io/bufio.ts";
import { TextProtoReader } from "../../../std/textproto/mod.ts";
@@ -28,7 +28,7 @@ unitTest(async function connectTLSCertFileNoReadPerm(): Promise<void> {
await Deno.connectTLS({
hostname: "github.com",
port: 443,
- certFile: "cli/tests/tls/RootCA.crt"
+ certFile: "cli/tests/tls/RootCA.crt",
});
} catch (e) {
err = e;
@@ -45,13 +45,13 @@ unitTest(
hostname: "localhost",
port: 4500,
certFile: "cli/tests/tls/localhost.crt",
- keyFile: "cli/tests/tls/localhost.key"
+ keyFile: "cli/tests/tls/localhost.key",
};
try {
Deno.listenTLS({
...options,
- certFile: "./non/existent/file"
+ certFile: "./non/existent/file",
});
} catch (e) {
err = e;
@@ -61,7 +61,7 @@ unitTest(
try {
Deno.listenTLS({
...options,
- keyFile: "./non/existent/file"
+ keyFile: "./non/existent/file",
});
} catch (e) {
err = e;
@@ -77,7 +77,7 @@ unitTest({ perms: { net: true } }, function listenTLSNoReadPerm(): void {
hostname: "localhost",
port: 4500,
certFile: "cli/tests/tls/localhost.crt",
- keyFile: "cli/tests/tls/localhost.key"
+ keyFile: "cli/tests/tls/localhost.key",
});
} catch (e) {
err = e;
@@ -88,7 +88,7 @@ unitTest({ perms: { net: true } }, function listenTLSNoReadPerm(): void {
unitTest(
{
- perms: { read: true, write: true, net: true }
+ perms: { read: true, write: true, net: true },
},
function listenTLSEmptyKeyFile(): void {
let err;
@@ -96,19 +96,19 @@ unitTest(
hostname: "localhost",
port: 4500,
certFile: "cli/tests/tls/localhost.crt",
- keyFile: "cli/tests/tls/localhost.key"
+ keyFile: "cli/tests/tls/localhost.key",
};
const testDir = Deno.makeTempDirSync();
const keyFilename = testDir + "/key.pem";
Deno.writeFileSync(keyFilename, new Uint8Array([]), {
- mode: 0o666
+ mode: 0o666,
});
try {
Deno.listenTLS({
...options,
- keyFile: keyFilename
+ keyFile: keyFilename,
});
} catch (e) {
err = e;
@@ -125,19 +125,19 @@ unitTest(
hostname: "localhost",
port: 4500,
certFile: "cli/tests/tls/localhost.crt",
- keyFile: "cli/tests/tls/localhost.key"
+ keyFile: "cli/tests/tls/localhost.key",
};
const testDir = Deno.makeTempDirSync();
const certFilename = testDir + "/cert.crt";
Deno.writeFileSync(certFilename, new Uint8Array([]), {
- mode: 0o666
+ mode: 0o666,
});
try {
Deno.listenTLS({
...options,
- certFile: certFilename
+ certFile: certFilename,
});
} catch (e) {
err = e;
@@ -157,7 +157,7 @@ unitTest(
hostname,
port,
certFile: "cli/tests/tls/localhost.crt",
- keyFile: "cli/tests/tls/localhost.key"
+ keyFile: "cli/tests/tls/localhost.key",
});
const response = encoder.encode(
@@ -180,7 +180,7 @@ unitTest(
const conn = await Deno.connectTLS({
hostname,
port,
- certFile: "cli/tests/tls/RootCA.pem"
+ certFile: "cli/tests/tls/RootCA.pem",
});
assert(conn.rid > 0);
const w = new BufWriter(conn);
diff --git a/cli/js/tests/umask_test.ts b/cli/js/tests/umask_test.ts
index e4576c515..71a5e71f8 100644
--- a/cli/js/tests/umask_test.ts
+++ b/cli/js/tests/umask_test.ts
@@ -3,7 +3,7 @@ import { unitTest, assertEquals } from "./test_util.ts";
unitTest(
{
- ignore: Deno.build.os === "win"
+ ignore: Deno.build.os === "win",
},
function umaskSuccess(): void {
const prevMask = Deno.umask(0o020);
diff --git a/cli/js/tests/unit_test_runner.ts b/cli/js/tests/unit_test_runner.ts
index e79e1b7ea..8d3eaa4f5 100755
--- a/cli/js/tests/unit_test_runner.ts
+++ b/cli/js/tests/unit_test_runner.ts
@@ -8,7 +8,7 @@ import {
registerUnitTests,
SocketReporter,
fmtPerms,
- parseArgs
+ parseArgs,
} from "./test_util.ts";
interface PermissionSetTestResult {
@@ -27,7 +27,7 @@ const PERMISSIONS: Deno.PermissionName[] = [
"env",
"run",
"plugin",
- "hrtime"
+ "hrtime",
];
/**
@@ -69,7 +69,7 @@ async function workerRunnerMain(
failFast: false,
exitOnFail: false,
reporter: socketReporter,
- only: filter
+ only: filter,
});
}
@@ -93,7 +93,7 @@ function spawnWorkerRunner(
"cli/js/tests/unit_test_runner.ts",
"--worker",
`--addr=${addr}`,
- `--perms=${permStr}`
+ `--perms=${permStr}`,
];
if (filter) {
@@ -107,7 +107,7 @@ function spawnWorkerRunner(
cmd,
stdin: ioMode,
stdout: ioMode,
- stderr: ioMode
+ stderr: ioMode,
});
return p;
@@ -177,7 +177,7 @@ async function runTestsForPermissionSet(
permsStr: permsFmt,
duration: endEvent.duration,
stats: endEvent.stats,
- results: endEvent.results
+ results: endEvent.results,
};
}
@@ -223,7 +223,7 @@ async function masterRunnerMain(
kind: Deno.TestEvent.End,
stats,
duration,
- results
+ results,
});
testsPassed = testsPassed && testResult.passed;
}
@@ -288,7 +288,7 @@ function assertOrHelp(expr: unknown): asserts expr {
async function main(): Promise<void> {
const args = parseArgs(Deno.args, {
boolean: ["master", "worker", "verbose"],
- "--": true
+ "--": true,
});
if (args.help) {
@@ -315,7 +315,7 @@ async function main(): Promise<void> {
await Deno.runTests({
failFast: false,
exitOnFail: true,
- only: filter
+ only: filter,
});
}
diff --git a/cli/js/tests/url_search_params_test.ts b/cli/js/tests/url_search_params_test.ts
index b256395a0..3e71d2900 100644
--- a/cli/js/tests/url_search_params_test.ts
+++ b/cli/js/tests/url_search_params_test.ts
@@ -13,7 +13,7 @@ unitTest(function urlSearchParamsInitString(): void {
unitTest(function urlSearchParamsInitIterable(): void {
const init = [
["a", "54"],
- ["b", "true"]
+ ["b", "true"],
];
const searchParams = new URLSearchParams(init);
assertEquals(searchParams.toString(), "a=54&b=true");
@@ -94,7 +94,7 @@ unitTest(function urlSearchParamsSortSuccess(): void {
unitTest(function urlSearchParamsForEachSuccess(): void {
const init = [
["a", "54"],
- ["b", "true"]
+ ["b", "true"],
];
const searchParams = new URLSearchParams(init);
let callNum = 0;
@@ -225,7 +225,7 @@ unitTest(function urlSearchParamsDeletingAppendedMultiple(): void {
// ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-constructor.any.js#L176-L182
unitTest(function urlSearchParamsCustomSymbolIterator(): void {
const params = new URLSearchParams();
- params[Symbol.iterator] = function*(): IterableIterator<[string, string]> {
+ params[Symbol.iterator] = function* (): IterableIterator<[string, string]> {
yield ["a", "b"];
};
const params1 = new URLSearchParams((params as unknown) as string[][]);
@@ -236,7 +236,7 @@ unitTest(
function urlSearchParamsCustomSymbolIteratorWithNonStringParams(): void {
const params = {};
// @ts-ignore
- params[Symbol.iterator] = function*(): IterableIterator<[number, number]> {
+ params[Symbol.iterator] = function* (): IterableIterator<[number, number]> {
yield [1, 2];
};
const params1 = new URLSearchParams((params as unknown) as string[][]);
diff --git a/cli/js/tests/url_test.ts b/cli/js/tests/url_test.ts
index 5b3067e4b..e1b2d47bd 100644
--- a/cli/js/tests/url_test.ts
+++ b/cli/js/tests/url_test.ts
@@ -98,6 +98,12 @@ unitTest(function urlModifyHref(): void {
assertEquals(url.hash, "#qux");
});
+unitTest(function urlNormalize(): void {
+ const url = new URL("http://example.com");
+ assertEquals(url.pathname, "/");
+ assertEquals(url.href, "http://example.com/");
+});
+
unitTest(function urlModifyPathname(): void {
const url = new URL("http://foo.bar/baz%qat/qux%quux");
assertEquals(url.pathname, "/baz%qat/qux%quux");
@@ -183,7 +189,7 @@ unitTest(function sortingNonExistentParamRemovesQuestionMarkFromURL(): void {
unitTest(
{
// FIXME(bartlomieju)
- ignore: true
+ ignore: true,
},
function customInspectFunction(): void {
const url = new URL("http://example.com/?");
diff --git a/cli/js/tests/utime_test.ts b/cli/js/tests/utime_test.ts
index 8cd34d39a..917b8b8b6 100644
--- a/cli/js/tests/utime_test.ts
+++ b/cli/js/tests/utime_test.ts
@@ -15,7 +15,7 @@ unitTest(
const testDir = Deno.makeTempDirSync();
const filename = testDir + "/file.txt";
Deno.writeFileSync(filename, new TextEncoder().encode("hello"), {
- mode: 0o666
+ mode: 0o666,
});
const atime = 1000;
@@ -115,7 +115,7 @@ unitTest(
const testDir = Deno.makeTempDirSync();
const filename = testDir + "/file.txt";
Deno.writeFileSync(filename, new TextEncoder().encode("hello"), {
- mode: 0o666
+ mode: 0o666,
});
const atime = 1000;
diff --git a/cli/js/tls.ts b/cli/js/tls.ts
index 5a9b9ace0..ef87b5aa1 100644
--- a/cli/js/tls.ts
+++ b/cli/js/tls.ts
@@ -15,13 +15,13 @@ export async function connectTLS({
port,
hostname = "127.0.0.1",
transport = "tcp",
- certFile = undefined
+ certFile = undefined,
}: ConnectTLSOptions): Promise<Conn> {
const res = await tlsOps.connectTLS({
port,
hostname,
transport,
- certFile
+ certFile,
});
return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!);
}
@@ -46,14 +46,14 @@ export function listenTLS({
certFile,
keyFile,
hostname = "0.0.0.0",
- transport = "tcp"
+ transport = "tcp",
}: ListenTLSOptions): Listener {
const res = tlsOps.listenTLS({
port,
certFile,
keyFile,
hostname,
- transport
+ transport,
});
return new TLSListenerImpl(res.rid, res.localAddr);
}
diff --git a/cli/js/util.ts b/cli/js/util.ts
index 692ea6d00..6db8ade7b 100644
--- a/cli/js/util.ts
+++ b/cli/js/util.ts
@@ -67,6 +67,6 @@ export function immutableDefine(
Object.defineProperty(o, p, {
value,
configurable: false,
- writable: false
+ writable: false,
});
}
diff --git a/cli/js/version.ts b/cli/js/version.ts
index 8f7851589..534195ce5 100644
--- a/cli/js/version.ts
+++ b/cli/js/version.ts
@@ -8,7 +8,7 @@ interface Version {
export const version: Version = {
deno: "",
v8: "",
- typescript: ""
+ typescript: "",
};
export function setVersions(
diff --git a/cli/js/web/blob.ts b/cli/js/web/blob.ts
index 31674a62d..5309ddaf4 100644
--- a/cli/js/web/blob.ts
+++ b/cli/js/web/blob.ts
@@ -124,12 +124,8 @@ function processBlobParts(
return bytes;
}
-// A WeakMap holding blob to byte array mapping.
-// Ensures it does not impact garbage collection.
-export const blobBytesWeakMap = new WeakMap<domTypes.Blob, Uint8Array>();
-
export class DenoBlob implements domTypes.Blob {
- private readonly [bytesSymbol]: Uint8Array;
+ [bytesSymbol]: Uint8Array;
readonly size: number = 0;
readonly type: string = "";
@@ -165,14 +161,11 @@ export class DenoBlob implements domTypes.Blob {
this[bytesSymbol] = bytes;
this.size = bytes.byteLength;
this.type = normalizedType;
-
- // Register bytes for internal private use.
- blobBytesWeakMap.set(this, bytes);
}
slice(start?: number, end?: number, contentType?: string): DenoBlob {
return new DenoBlob([this[bytesSymbol].slice(start, end)], {
- type: contentType || this.type
+ type: contentType || this.type,
});
}
}
diff --git a/cli/js/web/body.ts b/cli/js/web/body.ts
index 03c35848a..a16f872b9 100644
--- a/cli/js/web/body.ts
+++ b/cli/js/web/body.ts
@@ -124,7 +124,7 @@ export const BodyUsedError =
"Failed to execute 'clone' on 'Body': body is already used";
export class Body implements domTypes.Body {
- protected _stream: domTypes.ReadableStream | null;
+ protected _stream: domTypes.ReadableStream<string | ArrayBuffer> | null;
constructor(protected _bodySource: BodySource, readonly contentType: string) {
validateBodyType(this, _bodySource);
@@ -148,8 +148,8 @@ export class Body implements domTypes.Body {
start(controller: ReadableStreamController): void {
controller.enqueue(bodySource);
controller.close();
- }
- });
+ },
+ }) as domTypes.ReadableStream<ArrayBuffer | string>;
}
return this._stream;
}
@@ -247,7 +247,7 @@ export class Body implements domTypes.Body {
if (dispositionParams.has("filename")) {
const filename = dispositionParams.get("filename")!;
const blob = new DenoBlob([enc.encode(octets)], {
- type: partContentType
+ type: partContentType,
});
// TODO: based on spec
// https://xhr.spec.whatwg.org/#dom-formdata-append
diff --git a/cli/js/web/console.ts b/cli/js/web/console.ts
index f95e50b40..554c5a1b3 100644
--- a/cli/js/web/console.ts
+++ b/cli/js/web/console.ts
@@ -174,7 +174,7 @@ function createArrayString(
displayName: "",
delims: ["[", "]"],
entryHandler: (el, ctx, level, maxLevel): string =>
- stringifyWithQuotes(el, ctx, level + 1, maxLevel)
+ stringifyWithQuotes(el, ctx, level + 1, maxLevel),
};
return createIterableString(value, ctx, level, maxLevel, printConfig);
}
@@ -191,7 +191,7 @@ function createTypedArrayString(
displayName: typedArrayName,
delims: ["[", "]"],
entryHandler: (el, ctx, level, maxLevel): string =>
- stringifyWithQuotes(el, ctx, level + 1, maxLevel)
+ stringifyWithQuotes(el, ctx, level + 1, maxLevel),
};
return createIterableString(value, ctx, level, maxLevel, printConfig);
}
@@ -207,7 +207,7 @@ function createSetString(
displayName: "Set",
delims: ["{", "}"],
entryHandler: (el, ctx, level, maxLevel): string =>
- stringifyWithQuotes(el, ctx, level + 1, maxLevel)
+ stringifyWithQuotes(el, ctx, level + 1, maxLevel),
};
return createIterableString(value, ctx, level, maxLevel, printConfig);
}
@@ -230,7 +230,7 @@ function createMapString(
level + 1,
maxLevel
)} => ${stringifyWithQuotes(val, ctx, level + 1, maxLevel)}`;
- }
+ },
};
return createIterableString(value, ctx, level, maxLevel, printConfig);
}
@@ -494,10 +494,12 @@ const timerMap = new Map<string, number>();
const isConsoleInstance = Symbol("isConsoleInstance");
export class Console {
+ #printFunc: PrintFunc;
indentLevel: number;
[isConsoleInstance] = false;
- constructor(private printFunc: PrintFunc) {
+ constructor(printFunc: PrintFunc) {
+ this.#printFunc = printFunc;
this.indentLevel = 0;
this[isConsoleInstance] = true;
@@ -511,9 +513,9 @@ export class Console {
}
log = (...args: unknown[]): void => {
- this.printFunc(
+ this.#printFunc(
stringifyArgs(args, {
- indentLevel: this.indentLevel
+ indentLevel: this.indentLevel,
}) + "\n",
false
);
@@ -523,15 +525,15 @@ export class Console {
info = this.log;
dir = (obj: unknown, options: InspectOptions = {}): void => {
- this.printFunc(stringifyArgs([obj], options) + "\n", false);
+ this.#printFunc(stringifyArgs([obj], options) + "\n", false);
};
dirxml = this.dir;
warn = (...args: unknown[]): void => {
- this.printFunc(
+ this.#printFunc(
stringifyArgs(args, {
- indentLevel: this.indentLevel
+ indentLevel: this.indentLevel,
}) + "\n",
true
);
@@ -604,7 +606,7 @@ export class Console {
this.log(cliTable(header, body));
const createColumn = (value: unknown, shift?: number): string[] => [
...(shift ? [...new Array(shift)].map((): string => "") : []),
- stringifyValue(value)
+ stringifyValue(value),
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -660,8 +662,8 @@ export class Console {
indexKey,
...(properties || [
...headerKeys,
- !isMap && values.length > 0 && valuesKey
- ])
+ !isMap && values.length > 0 && valuesKey,
+ ]),
].filter(Boolean) as string[];
const body = [indexKeys, ...bodyValues, values];
@@ -733,7 +735,7 @@ export class Console {
const message = stringifyArgs(args, { indentLevel: 0 });
const err = {
name: "Trace",
- message
+ message,
};
// @ts-ignore
Error.captureStackTrace(err, this.trace);
diff --git a/cli/js/web/console_table.ts b/cli/js/web/console_table.ts
index 7e698f712..2cb0005d7 100644
--- a/cli/js/web/console_table.ts
+++ b/cli/js/web/console_table.ts
@@ -19,7 +19,7 @@ const tableChars = {
rightMiddle: "┤",
left: "│ ",
right: " │",
- middle: " │ "
+ middle: " │ ",
};
const colorRegExp = /\u001b\[\d\d?m/g;
diff --git a/cli/js/web/custom_event.ts b/cli/js/web/custom_event.ts
index 24a263baf..418b7ea34 100644
--- a/cli/js/web/custom_event.ts
+++ b/cli/js/web/custom_event.ts
@@ -1,32 +1,31 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as domTypes from "./dom_types.ts";
import * as event from "./event.ts";
-import { getPrivateValue, requiredArguments } from "./util.ts";
-
-// WeakMaps are recommended for private attributes (see MDN link below)
-// https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Add-on_SDK/Guides/Contributor_s_Guide/Private_Properties#Using_WeakMaps
-export const customEventAttributes = new WeakMap();
+import { requiredArguments } from "./util.ts";
export class CustomEvent extends event.Event implements domTypes.CustomEvent {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ #detail: any;
+
constructor(
type: string,
customEventInitDict: domTypes.CustomEventInit = {}
) {
- requiredArguments("CustomEvent", arguments.length, 1);
super(type, customEventInitDict);
+ requiredArguments("CustomEvent", arguments.length, 1);
const { detail = null } = customEventInitDict;
- customEventAttributes.set(this, { detail });
+ this.#detail = detail;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get detail(): any {
- return getPrivateValue(this, customEventAttributes, "detail");
+ return this.#detail;
}
initCustomEvent(
- type: string,
- bubbles?: boolean,
- cancelable?: boolean,
+ _type: string,
+ _bubbles?: boolean,
+ _cancelable?: boolean,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
detail?: any
): void {
@@ -34,7 +33,7 @@ export class CustomEvent extends event.Event implements domTypes.CustomEvent {
return;
}
- customEventAttributes.set(this, { detail });
+ this.#detail = detail;
}
get [Symbol.toStringTag](): string {
diff --git a/cli/js/web/dom_iterable.ts b/cli/js/web/dom_iterable.ts
index e9be9009f..191958f11 100644
--- a/cli/js/web/dom_iterable.ts
+++ b/cli/js/web/dom_iterable.ts
@@ -72,7 +72,7 @@ export function DomIterableMixin<K, V, TBase extends Constructor>(
// we want the Base class name to be the name of the class.
Object.defineProperty(DomIterable, "name", {
value: Base.name,
- configurable: true
+ configurable: true,
});
return DomIterable;
diff --git a/cli/js/web/dom_types.ts b/cli/js/web/dom_types.ts
index bcc6be468..33cda1582 100644
--- a/cli/js/web/dom_types.ts
+++ b/cli/js/web/dom_types.ts
@@ -68,7 +68,7 @@ interface AbortSignalEventMap {
export enum NodeType {
ELEMENT_NODE = 1,
TEXT_NODE = 3,
- DOCUMENT_FRAGMENT_NODE = 11
+ DOCUMENT_FRAGMENT_NODE = 11,
}
export const eventTargetHost: unique symbol = Symbol();
@@ -153,7 +153,7 @@ export enum EventPhase {
NONE = 0,
CAPTURING_PHASE = 1,
AT_TARGET = 2,
- BUBBLING_PHASE = 3
+ BUBBLING_PHASE = 3,
}
export interface EventPath {
@@ -280,7 +280,7 @@ export interface Blob {
}
export interface Body {
- readonly body: ReadableStream | null;
+ readonly body: ReadableStream<Uint8Array> | null;
readonly bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
@@ -289,11 +289,78 @@ export interface Body {
text(): Promise<string>;
}
-export interface ReadableStream {
+export interface ReadableStreamReadDoneResult<T> {
+ done: true;
+ value?: T;
+}
+
+export interface ReadableStreamReadValueResult<T> {
+ done: false;
+ value: T;
+}
+
+export type ReadableStreamReadResult<T> =
+ | ReadableStreamReadValueResult<T>
+ | ReadableStreamReadDoneResult<T>;
+
+export interface ReadableStreamDefaultReader<R = any> {
+ readonly closed: Promise<void>;
+ cancel(reason?: any): Promise<void>;
+ read(): Promise<ReadableStreamReadResult<R>>;
+ releaseLock(): void;
+}
+
+export interface PipeOptions {
+ preventAbort?: boolean;
+ preventCancel?: boolean;
+ preventClose?: boolean;
+ signal?: AbortSignal;
+}
+
+export interface ReadableStream<R = any> {
readonly locked: boolean;
cancel(reason?: any): Promise<void>;
- getReader(): ReadableStreamReader;
- tee(): ReadableStream[];
+ getReader(options: { mode: "byob" }): ReadableStreamBYOBReader;
+ getReader(): ReadableStreamDefaultReader<R>;
+ /* disabled for now
+ pipeThrough<T>(
+ {
+ writable,
+ readable
+ }: {
+ writable: WritableStream<R>;
+ readable: ReadableStream<T>;
+ },
+ options?: PipeOptions
+ ): ReadableStream<T>;
+ pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>;
+ */
+ tee(): [ReadableStream<R>, ReadableStream<R>];
+}
+
+export interface ReadableStreamBYOBReader {
+ readonly closed: Promise<void>;
+ cancel(reason?: any): Promise<void>;
+ read<T extends ArrayBufferView>(
+ view: T
+ ): Promise<ReadableStreamReadResult<T>>;
+ releaseLock(): void;
+}
+
+export interface WritableStream<W = any> {
+ readonly locked: boolean;
+ abort(reason?: any): Promise<void>;
+ getWriter(): WritableStreamDefaultWriter<W>;
+}
+
+export interface WritableStreamDefaultWriter<W = any> {
+ readonly closed: Promise<void>;
+ readonly desiredSize: number | null;
+ readonly ready: Promise<void>;
+ abort(reason?: any): Promise<void>;
+ close(): Promise<void>;
+ releaseLock(): void;
+ write(chunk: W): Promise<void>;
}
export interface UnderlyingSource<R = any> {
@@ -311,9 +378,9 @@ export interface UnderlyingByteSource {
type: "bytes";
}
-export interface ReadableStreamReader {
- cancel(reason?: any): Promise<void>;
- read(): Promise<any>;
+export interface ReadableStreamReader<R = any> {
+ cancel(reason: any): Promise<void>;
+ read(): Promise<ReadableStreamReadResult<R>>;
releaseLock(): void;
}
@@ -530,12 +597,20 @@ export interface Response extends Body {
clone(): Response;
}
+export interface DOMStringList {
+ readonly length: number;
+ contains(string: string): boolean;
+ item(index: number): string | null;
+ [index: number]: string;
+}
+
export interface Location {
- readonly ancestorOrigins: string[];
+ readonly ancestorOrigins: DOMStringList;
hash: string;
host: string;
hostname: string;
href: string;
+ toString(): string;
readonly origin: string;
pathname: string;
port: string;
@@ -543,6 +618,72 @@ export interface Location {
search: string;
assign(url: string): void;
reload(): void;
- reload(forcedReload: boolean): void;
replace(url: string): void;
}
+
+export interface URL {
+ hash: string;
+ host: string;
+ hostname: string;
+ href: string;
+ toString(): string;
+ readonly origin: string;
+ password: string;
+ pathname: string;
+ port: string;
+ protocol: string;
+ search: string;
+ readonly searchParams: URLSearchParams;
+ username: string;
+ toJSON(): string;
+}
+
+export interface URLSearchParams {
+ /**
+ * Appends a specified key/value pair as a new search parameter.
+ */
+ append(name: string, value: string): void;
+ /**
+ * Deletes the given search parameter, and its associated value, from the list of all search parameters.
+ */
+ delete(name: string): void;
+ /**
+ * Returns the first value associated to the given search parameter.
+ */
+ get(name: string): string | null;
+ /**
+ * Returns all the values association with a given search parameter.
+ */
+ getAll(name: string): string[];
+ /**
+ * Returns a Boolean indicating if such a search parameter exists.
+ */
+ has(name: string): boolean;
+ /**
+ * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
+ */
+ set(name: string, value: string): void;
+ sort(): void;
+ /**
+ * Returns a string containing a query string suitable for use in a URL. Does not include the question mark.
+ */
+ toString(): string;
+ forEach(
+ callbackfn: (value: string, key: string, parent: URLSearchParams) => void,
+ thisArg?: any
+ ): void;
+
+ [Symbol.iterator](): IterableIterator<[string, string]>;
+ /**
+ * Returns an array of key, value pairs for every entry in the search params.
+ */
+ entries(): IterableIterator<[string, string]>;
+ /**
+ * Returns a list of keys in the search params.
+ */
+ keys(): IterableIterator<string>;
+ /**
+ * Returns a list of values in the search params.
+ */
+ values(): IterableIterator<string>;
+}
diff --git a/cli/js/web/dom_util.ts b/cli/js/web/dom_util.ts
index 5780d9c52..40a8c618f 100644
--- a/cli/js/web/dom_util.ts
+++ b/cli/js/web/dom_util.ts
@@ -2,6 +2,23 @@
// Utility functions for DOM nodes
import * as domTypes from "./dom_types.ts";
+export function getDOMStringList(arr: string[]): domTypes.DOMStringList {
+ Object.defineProperties(arr, {
+ contains: {
+ value(searchElement: string): boolean {
+ return arr.includes(searchElement);
+ },
+ enumerable: true,
+ },
+ item: {
+ value(idx: number): string | null {
+ return idx in arr ? arr[idx] : null;
+ },
+ },
+ });
+ return (arr as unknown) as domTypes.DOMStringList;
+}
+
export function isNode(nodeImpl: domTypes.EventTarget | null): boolean {
return Boolean(nodeImpl && "nodeType" in nodeImpl);
}
diff --git a/cli/js/web/event.ts b/cli/js/web/event.ts
index ef5c4d175..b063efa60 100644
--- a/cli/js/web/event.ts
+++ b/cli/js/web/event.ts
@@ -39,11 +39,11 @@ export class Event implements domTypes.Event {
isTrusted: false,
relatedTarget: null,
target: null,
- timeStamp: Date.now()
+ timeStamp: Date.now(),
});
Reflect.defineProperty(this, "isTrusted", {
enumerable: true,
- get: isTrusted
+ get: isTrusted,
});
}
@@ -90,7 +90,7 @@ export class Event implements domTypes.Event {
isTrusted: this.isTrusted,
relatedTarget: this.relatedTarget,
target: this.target,
- timeStamp: this.timeStamp
+ timeStamp: this.timeStamp,
});
}
@@ -121,7 +121,7 @@ export class Event implements domTypes.Event {
isTrusted: this.isTrusted,
relatedTarget: this.relatedTarget,
target: this.target,
- timeStamp: this.timeStamp
+ timeStamp: this.timeStamp,
});
}
@@ -156,7 +156,7 @@ export class Event implements domTypes.Event {
isTrusted: this.isTrusted,
relatedTarget: value,
target: this.target,
- timeStamp: this.timeStamp
+ timeStamp: this.timeStamp,
});
}
@@ -175,7 +175,7 @@ export class Event implements domTypes.Event {
isTrusted: this.isTrusted,
relatedTarget: this.relatedTarget,
target: value,
- timeStamp: this.timeStamp
+ timeStamp: this.timeStamp,
});
}
@@ -200,8 +200,8 @@ export class Event implements domTypes.Event {
rootOfClosedTree: false,
slotInClosedTree: false,
target: null,
- touchTargetList: []
- }
+ touchTargetList: [],
+ },
];
let currentTargetIndex = 0;
@@ -242,7 +242,7 @@ export class Event implements domTypes.Event {
rootOfClosedTree: false,
slotInClosedTree: false,
target: null,
- touchTargetList: []
+ touchTargetList: [],
});
}
@@ -277,7 +277,7 @@ export class Event implements domTypes.Event {
rootOfClosedTree: false,
slotInClosedTree: false,
target: null,
- touchTargetList: []
+ touchTargetList: [],
});
}
@@ -314,7 +314,7 @@ Reflect.defineProperty(Event.prototype, "cancelable", { enumerable: true });
Reflect.defineProperty(Event.prototype, "composed", { enumerable: true });
Reflect.defineProperty(Event.prototype, "currentTarget", { enumerable: true });
Reflect.defineProperty(Event.prototype, "defaultPrevented", {
- enumerable: true
+ enumerable: true,
});
Reflect.defineProperty(Event.prototype, "dispatched", { enumerable: true });
Reflect.defineProperty(Event.prototype, "eventPhase", { enumerable: true });
diff --git a/cli/js/web/event_target.ts b/cli/js/web/event_target.ts
index 7fe26441d..605504a3a 100644
--- a/cli/js/web/event_target.ts
+++ b/cli/js/web/event_target.ts
@@ -7,7 +7,7 @@ import {
isShadowRoot,
isShadowInclusiveAncestor,
isSlotable,
- retarget
+ retarget,
} from "./dom_util.ts";
// https://dom.spec.whatwg.org/#get-the-parent
@@ -70,7 +70,7 @@ export class EventTarget implements domTypes.EventTarget {
listeners[type].push({
callback,
- options: normalizedOptions
+ options: normalizedOptions,
});
}
@@ -438,7 +438,7 @@ const eventTargetHelpers = {
const returnValue: domTypes.AddEventListenerOptions = {
capture: Boolean(options),
once: false,
- passive: false
+ passive: false,
};
return returnValue;
@@ -452,7 +452,7 @@ const eventTargetHelpers = {
): domTypes.EventListenerOptions {
if (typeof options === "boolean" || typeof options === "undefined") {
const returnValue: domTypes.EventListenerOptions = {
- capture: Boolean(options)
+ capture: Boolean(options),
};
return returnValue;
@@ -481,17 +481,17 @@ const eventTargetHelpers = {
relatedTarget,
touchTargetList: touchTargets,
rootOfClosedTree,
- slotInClosedTree
+ slotInClosedTree,
});
- }
+ },
};
Reflect.defineProperty(EventTarget.prototype, "addEventListener", {
- enumerable: true
+ enumerable: true,
});
Reflect.defineProperty(EventTarget.prototype, "removeEventListener", {
- enumerable: true
+ enumerable: true,
});
Reflect.defineProperty(EventTarget.prototype, "dispatchEvent", {
- enumerable: true
+ enumerable: true,
});
diff --git a/cli/js/web/fetch.ts b/cli/js/web/fetch.ts
index 62e5d7928..6438838c7 100644
--- a/cli/js/web/fetch.ts
+++ b/cli/js/web/fetch.ts
@@ -32,53 +32,58 @@ function hasHeaderValueOf(s: string, value: string): boolean {
return new RegExp(`^${value}[\t\s]*;?`).test(s);
}
-class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
- private _bodyUsed = false;
- private _bodyPromise: null | Promise<ArrayBuffer> = null;
- private _data: ArrayBuffer | null = null;
+class Body
+ implements domTypes.Body, domTypes.ReadableStream<Uint8Array>, io.ReadCloser {
+ #bodyUsed = false;
+ #bodyPromise: Promise<ArrayBuffer> | null = null;
+ #data: ArrayBuffer | null = null;
+ #rid: number;
readonly locked: boolean = false; // TODO
- readonly body: null | Body = this;
+ readonly body: domTypes.ReadableStream<Uint8Array>;
- constructor(private rid: number, readonly contentType: string) {}
+ constructor(rid: number, readonly contentType: string) {
+ this.#rid = rid;
+ this.body = this;
+ }
- private async _bodyBuffer(): Promise<ArrayBuffer> {
- assert(this._bodyPromise == null);
+ #bodyBuffer = async (): Promise<ArrayBuffer> => {
+ assert(this.#bodyPromise == null);
const buf = new Buffer();
try {
const nread = await buf.readFrom(this);
const ui8 = buf.bytes();
assert(ui8.byteLength === nread);
- this._data = ui8.buffer.slice(
+ this.#data = ui8.buffer.slice(
ui8.byteOffset,
ui8.byteOffset + nread
) as ArrayBuffer;
- assert(this._data.byteLength === nread);
+ assert(this.#data.byteLength === nread);
} finally {
this.close();
}
- return this._data;
- }
+ return this.#data;
+ };
// eslint-disable-next-line require-await
async arrayBuffer(): Promise<ArrayBuffer> {
// If we've already bufferred the response, just return it.
- if (this._data != null) {
- return this._data;
+ if (this.#data != null) {
+ return this.#data;
}
// If there is no _bodyPromise yet, start it.
- if (this._bodyPromise == null) {
- this._bodyPromise = this._bodyBuffer();
+ if (this.#bodyPromise == null) {
+ this.#bodyPromise = this.#bodyBuffer();
}
- return this._bodyPromise;
+ return this.#bodyPromise;
}
async blob(): Promise<domTypes.Blob> {
const arrayBuffer = await this.arrayBuffer();
return new DenoBlob([arrayBuffer], {
- type: this.contentType
+ type: this.contentType,
});
}
@@ -164,7 +169,7 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
if (dispositionParams.has("filename")) {
const filename = dispositionParams.get("filename")!;
const blob = new DenoBlob([enc.encode(octets)], {
- type: partContentType
+ type: partContentType,
});
// TODO: based on spec
// https://xhr.spec.whatwg.org/#dom-formdata-append
@@ -220,12 +225,12 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
}
read(p: Uint8Array): Promise<number | io.EOF> {
- this._bodyUsed = true;
- return read(this.rid, p);
+ this.#bodyUsed = true;
+ return read(this.#rid, p);
}
close(): Promise<void> {
- close(this.rid);
+ close(this.#rid);
return Promise.resolve();
}
@@ -233,7 +238,11 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
return notImplemented();
}
- getReader(): domTypes.ReadableStreamReader {
+ getReader(options: { mode: "byob" }): domTypes.ReadableStreamBYOBReader;
+ getReader(): domTypes.ReadableStreamDefaultReader<Uint8Array>;
+ getReader():
+ | domTypes.ReadableStreamBYOBReader
+ | domTypes.ReadableStreamDefaultReader<Uint8Array> {
return notImplemented();
}
@@ -246,7 +255,24 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
}
get bodyUsed(): boolean {
- return this._bodyUsed;
+ return this.#bodyUsed;
+ }
+
+ pipeThrough<T>(
+ _: {
+ writable: domTypes.WritableStream<Uint8Array>;
+ readable: domTypes.ReadableStream<T>;
+ },
+ _options?: domTypes.PipeOptions
+ ): domTypes.ReadableStream<T> {
+ return notImplemented();
+ }
+
+ pipeTo(
+ _dest: domTypes.WritableStream<Uint8Array>,
+ _options?: domTypes.PipeOptions
+ ): Promise<void> {
+ return notImplemented();
}
}
@@ -255,7 +281,7 @@ export class Response implements domTypes.Response {
readonly redirected: boolean;
headers: domTypes.Headers;
readonly trailer: Promise<domTypes.Headers>;
- readonly body: null | Body;
+ readonly body: Body | null;
constructor(
readonly url: string,
@@ -308,7 +334,7 @@ export class Response implements domTypes.Response {
"Content-Type",
"Expires",
"Last-Modified",
- "Pragma"
+ "Pragma",
].map((c: string) => c.toLowerCase());
for (const h of this.headers) {
/* Technically this is still not standards compliant because we are
@@ -337,35 +363,36 @@ export class Response implements domTypes.Response {
this.redirected = redirected_;
}
- private bodyViewable(): boolean {
+ #bodyViewable = (): boolean => {
if (
this.type == "error" ||
this.type == "opaque" ||
this.type == "opaqueredirect" ||
this.body == undefined
- )
+ ) {
return true;
+ }
return false;
- }
+ };
arrayBuffer(): Promise<ArrayBuffer> {
/* You have to do the null check here and not in the function because
* otherwise TS complains about this.body potentially being null */
- if (this.bodyViewable() || this.body == null) {
+ if (this.#bodyViewable() || this.body == null) {
return Promise.reject(new Error("Response body is null"));
}
return this.body.arrayBuffer();
}
blob(): Promise<domTypes.Blob> {
- if (this.bodyViewable() || this.body == null) {
+ if (this.#bodyViewable() || this.body == null) {
return Promise.reject(new Error("Response body is null"));
}
return this.body.blob();
}
formData(): Promise<domTypes.FormData> {
- if (this.bodyViewable() || this.body == null) {
+ if (this.#bodyViewable() || this.body == null) {
return Promise.reject(new Error("Response body is null"));
}
return this.body.formData();
@@ -373,14 +400,14 @@ export class Response implements domTypes.Response {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
json(): Promise<any> {
- if (this.bodyViewable() || this.body == null) {
+ if (this.#bodyViewable() || this.body == null) {
return Promise.reject(new Error("Response body is null"));
}
return this.body.json();
}
text(): Promise<string> {
- if (this.bodyViewable() || this.body == null) {
+ if (this.#bodyViewable() || this.body == null) {
return Promise.reject(new Error("Response body is null"));
}
return this.body.text();
@@ -453,7 +480,7 @@ function sendFetchReq(
const args = {
method,
url,
- headers: headerArray
+ headers: headerArray,
};
return opFetch(args, body);
@@ -527,8 +554,9 @@ export async function fetch(
}
part += "\r\n";
if (fieldValue instanceof DomFileImpl) {
- part += `Content-Type: ${fieldValue.type ||
- "application/octet-stream"}\r\n`;
+ part += `Content-Type: ${
+ fieldValue.type || "application/octet-stream"
+ }\r\n`;
}
part += "\r\n";
if (fieldValue instanceof DomFileImpl) {
diff --git a/cli/js/web/form_data.ts b/cli/js/web/form_data.ts
index f60a146d9..db5d24ad4 100644
--- a/cli/js/web/form_data.ts
+++ b/cli/js/web/form_data.ts
@@ -8,7 +8,7 @@ import { requiredArguments } from "./util.ts";
const dataSymbol = Symbol("data");
class FormDataBase {
- private [dataSymbol]: Array<[string, domTypes.FormDataEntryValue]> = [];
+ [dataSymbol]: Array<[string, domTypes.FormDataEntryValue]> = [];
append(name: string, value: string): void;
append(name: string, value: blob.DenoBlob, filename?: string): void;
@@ -17,7 +17,7 @@ class FormDataBase {
name = String(name);
if (value instanceof blob.DenoBlob) {
const dfile = new domFile.DomFileImpl([value], filename || name, {
- type: value.type
+ type: value.type,
});
this[dataSymbol].push([name, dfile]);
} else {
@@ -84,7 +84,7 @@ class FormDataBase {
if (!found) {
if (value instanceof blob.DenoBlob) {
const dfile = new domFile.DomFileImpl([value], filename || name, {
- type: value.type
+ type: value.type,
});
this[dataSymbol][i][1] = dfile;
} else {
@@ -103,7 +103,7 @@ class FormDataBase {
if (!found) {
if (value instanceof blob.DenoBlob) {
const dfile = new domFile.DomFileImpl([value], filename || name, {
- type: value.type
+ type: value.type,
});
this[dataSymbol].push([name, dfile]);
} else {
diff --git a/cli/js/web/headers.ts b/cli/js/web/headers.ts
index 9ff594224..e1d81393d 100644
--- a/cli/js/web/headers.ts
+++ b/cli/js/web/headers.ts
@@ -17,32 +17,32 @@ function isHeaders(value: any): value is domTypes.Headers {
const headerMap = Symbol("header map");
-// ref: https://fetch.spec.whatwg.org/#dom-headers
-class HeadersBase {
- private [headerMap]: Map<string, string>;
- // TODO: headerGuard? Investigate if it is needed
- // node-fetch did not implement this but it is in the spec
-
- private _normalizeParams(name: string, value?: string): string[] {
- name = String(name).toLowerCase();
- value = String(value).trim();
- return [name, value];
- }
+// TODO: headerGuard? Investigate if it is needed
+// node-fetch did not implement this but it is in the spec
+function normalizeParams(name: string, value?: string): string[] {
+ name = String(name).toLowerCase();
+ value = String(value).trim();
+ return [name, value];
+}
- // The following name/value validations are copied from
- // https://github.com/bitinn/node-fetch/blob/master/src/headers.js
- // Copyright (c) 2016 David Frank. MIT License.
- private _validateName(name: string): void {
- if (invalidTokenRegex.test(name) || name === "") {
- throw new TypeError(`${name} is not a legal HTTP header name`);
- }
+// The following name/value validations are copied from
+// https://github.com/bitinn/node-fetch/blob/master/src/headers.js
+// Copyright (c) 2016 David Frank. MIT License.
+function validateName(name: string): void {
+ if (invalidTokenRegex.test(name) || name === "") {
+ throw new TypeError(`${name} is not a legal HTTP header name`);
}
+}
- private _validateValue(value: string): void {
- if (invalidHeaderCharRegex.test(value)) {
- throw new TypeError(`${value} is not a legal HTTP header value`);
- }
+function validateValue(value: string): void {
+ if (invalidHeaderCharRegex.test(value)) {
+ throw new TypeError(`${value} is not a legal HTTP header value`);
}
+}
+
+// ref: https://fetch.spec.whatwg.org/#dom-headers
+class HeadersBase {
+ [headerMap]: Map<string, string>;
constructor(init?: domTypes.HeadersInit) {
if (init === null) {
@@ -64,9 +64,9 @@ class HeadersBase {
2
);
- const [name, value] = this._normalizeParams(tuple[0], tuple[1]);
- this._validateName(name);
- this._validateValue(value);
+ const [name, value] = normalizeParams(tuple[0], tuple[1]);
+ validateName(name);
+ validateValue(value);
const existingValue = this[headerMap].get(name);
this[headerMap].set(
name,
@@ -77,9 +77,9 @@ class HeadersBase {
const names = Object.keys(init);
for (const rawName of names) {
const rawValue = init[rawName];
- const [name, value] = this._normalizeParams(rawName, rawValue);
- this._validateName(name);
- this._validateValue(value);
+ const [name, value] = normalizeParams(rawName, rawValue);
+ validateName(name);
+ validateValue(value);
this[headerMap].set(name, value);
}
}
@@ -101,9 +101,9 @@ class HeadersBase {
// ref: https://fetch.spec.whatwg.org/#concept-headers-append
append(name: string, value: string): void {
requiredArguments("Headers.append", arguments.length, 2);
- const [newname, newvalue] = this._normalizeParams(name, value);
- this._validateName(newname);
- this._validateValue(newvalue);
+ const [newname, newvalue] = normalizeParams(name, value);
+ validateName(newname);
+ validateValue(newvalue);
const v = this[headerMap].get(newname);
const str = v ? `${v}, ${newvalue}` : newvalue;
this[headerMap].set(newname, str);
@@ -111,31 +111,31 @@ class HeadersBase {
delete(name: string): void {
requiredArguments("Headers.delete", arguments.length, 1);
- const [newname] = this._normalizeParams(name);
- this._validateName(newname);
+ const [newname] = normalizeParams(name);
+ validateName(newname);
this[headerMap].delete(newname);
}
get(name: string): string | null {
requiredArguments("Headers.get", arguments.length, 1);
- const [newname] = this._normalizeParams(name);
- this._validateName(newname);
+ const [newname] = normalizeParams(name);
+ validateName(newname);
const value = this[headerMap].get(newname);
return value || null;
}
has(name: string): boolean {
requiredArguments("Headers.has", arguments.length, 1);
- const [newname] = this._normalizeParams(name);
- this._validateName(newname);
+ const [newname] = normalizeParams(name);
+ validateName(newname);
return this[headerMap].has(newname);
}
set(name: string, value: string): void {
requiredArguments("Headers.set", arguments.length, 2);
- const [newname, newvalue] = this._normalizeParams(name, value);
- this._validateName(newname);
- this._validateValue(newvalue);
+ const [newname, newvalue] = normalizeParams(name, value);
+ validateName(newname);
+ validateValue(newvalue);
this[headerMap].set(newname, newvalue);
}
diff --git a/cli/js/web/location.ts b/cli/js/web/location.ts
index d48cce3c7..862a4c1e4 100644
--- a/cli/js/web/location.ts
+++ b/cli/js/web/location.ts
@@ -1,12 +1,15 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { URL } from "./url.ts";
import { notImplemented } from "../util.ts";
-import { Location } from "./dom_types.ts";
+import { DOMStringList, Location } from "./dom_types.ts";
+import { getDOMStringList } from "./dom_util.ts";
export class LocationImpl implements Location {
+ #url: URL;
+
constructor(url: string) {
const u = new URL(url);
- this.url = u;
+ this.#url = u;
this.hash = u.hash;
this.host = u.host;
this.href = u.href;
@@ -18,13 +21,11 @@ export class LocationImpl implements Location {
this.search = u.search;
}
- private url: URL;
-
toString(): string {
- return this.url.toString();
+ return this.#url.toString();
}
- readonly ancestorOrigins: string[] = [];
+ readonly ancestorOrigins: DOMStringList = getDOMStringList([]);
hash: string;
host: string;
hostname: string;
@@ -45,6 +46,8 @@ export class LocationImpl implements Location {
}
}
+/** Sets the `window.location` at runtime.
+ * @internal */
export function setLocation(url: string): void {
globalThis.location = new LocationImpl(url);
Object.freeze(globalThis.location);
diff --git a/cli/js/web/request.ts b/cli/js/web/request.ts
index 8afc35e7a..96edaf59e 100644
--- a/cli/js/web/request.ts
+++ b/cli/js/web/request.ts
@@ -136,7 +136,7 @@ export class Request extends body.Body implements domTypes.Request {
body: body2,
method: this.method,
headers: new Headers(headersList),
- credentials: this.credentials
+ credentials: this.credentials,
});
return cloned;
}
diff --git a/cli/js/web/streams/readable-byte-stream-controller.ts b/cli/js/web/streams/readable-byte-stream-controller.ts
index 8067b5d35..1b473b77a 100644
--- a/cli/js/web/streams/readable-byte-stream-controller.ts
+++ b/cli/js/web/streams/readable-byte-stream-controller.ts
@@ -148,7 +148,7 @@ export class ReadableByteStreamController
bytesFilled: 0,
elementSize: 1,
ctor: Uint8Array,
- readerType: "default"
+ readerType: "default",
};
this[rs.pendingPullIntos_].push(pullIntoDescriptor);
}
diff --git a/cli/js/web/streams/readable-internals.ts b/cli/js/web/streams/readable-internals.ts
index b96262ef7..f46c79850 100644
--- a/cli/js/web/streams/readable-internals.ts
+++ b/cli/js/web/streams/readable-internals.ts
@@ -10,7 +10,7 @@ import {
QueuingStrategy,
QueuingStrategySizeCallback,
UnderlyingSource,
- UnderlyingByteSource
+ UnderlyingByteSource,
} from "../dom_types.ts";
// ReadableStreamDefaultController
@@ -345,7 +345,7 @@ export function readableStreamCancel<OutputType>(
const sourceCancelPromise = stream[readableStreamController_][cancelSteps_](
reason
);
- return sourceCancelPromise.then(_ => undefined);
+ return sourceCancelPromise.then((_) => undefined);
}
export function readableStreamClose<OutputType>(
@@ -558,13 +558,13 @@ export function setUpReadableStreamDefaultController<OutputType>(
const startResult = startAlgorithm();
Promise.resolve(startResult).then(
- _ => {
+ (_) => {
controller[started_] = true;
// Assert: controller.[[pulling]] is false.
// Assert: controller.[[pullAgain]] is false.
readableStreamDefaultControllerCallPullIfNeeded(controller);
},
- error => {
+ (error) => {
readableStreamDefaultControllerError(controller, error);
}
);
@@ -678,14 +678,14 @@ export function readableStreamDefaultControllerCallPullIfNeeded<OutputType>(
controller[pulling_] = true;
controller[pullAlgorithm_](controller).then(
- _ => {
+ (_) => {
controller[pulling_] = false;
if (controller[pullAgain_]) {
controller[pullAgain_] = false;
readableStreamDefaultControllerCallPullIfNeeded(controller);
}
},
- error => {
+ (error) => {
readableStreamDefaultControllerError(controller, error);
}
);
@@ -768,13 +768,13 @@ export function setUpReadableByteStreamController(
// Let startResult be the result of performing startAlgorithm.
const startResult = startAlgorithm();
Promise.resolve(startResult).then(
- _ => {
+ (_) => {
controller[started_] = true;
// Assert: controller.[[pulling]] is false.
// Assert: controller.[[pullAgain]] is false.
readableByteStreamControllerCallPullIfNeeded(controller);
},
- error => {
+ (error) => {
readableByteStreamControllerError(controller, error);
}
);
@@ -811,14 +811,14 @@ export function readableByteStreamControllerCallPullIfNeeded(
// Assert: controller.[[pullAgain]] is false.
controller[pulling_] = true;
controller[pullAlgorithm_](controller).then(
- _ => {
+ (_) => {
controller[pulling_] = false;
if (controller[pullAgain_]) {
controller[pullAgain_] = false;
readableByteStreamControllerCallPullIfNeeded(controller);
}
},
- error => {
+ (error) => {
readableByteStreamControllerError(controller, error);
}
);
@@ -1122,7 +1122,7 @@ export function readableByteStreamControllerPullInto(
bytesFilled: 0,
elementSize,
ctor,
- readerType: "byob"
+ readerType: "byob",
};
if (controller[pendingPullIntos_].length > 0) {
diff --git a/cli/js/web/streams/readable-stream.ts b/cli/js/web/streams/readable-stream.ts
index e062c278e..50753260d 100644
--- a/cli/js/web/streams/readable-stream.ts
+++ b/cli/js/web/streams/readable-stream.ts
@@ -11,18 +11,18 @@ import {
QueuingStrategy,
QueuingStrategySizeCallback,
UnderlyingSource,
- UnderlyingByteSource
+ UnderlyingByteSource,
} from "../dom_types.ts";
import {
ReadableStreamDefaultController,
- setUpReadableStreamDefaultControllerFromUnderlyingSource
+ setUpReadableStreamDefaultControllerFromUnderlyingSource,
} from "./readable-stream-default-controller.ts";
import { ReadableStreamDefaultReader } from "./readable-stream-default-reader.ts";
import {
ReadableByteStreamController,
- setUpReadableByteStreamControllerFromUnderlyingSource
+ setUpReadableByteStreamControllerFromUnderlyingSource,
} from "./readable-byte-stream-controller.ts";
import { SDReadableStreamBYOBReader } from "./readable-stream-byob-reader.ts";
@@ -123,7 +123,7 @@ export class SDReadableStream<OutputType>
return rs.readableStreamCancel(this, reason);
}
- tee(): Array<SDReadableStream<OutputType>> {
+ tee(): [SDReadableStream<OutputType>, SDReadableStream<OutputType>] {
return readableStreamTee(this, false);
}
@@ -280,7 +280,9 @@ export function readableStreamTee<OutputType>(
let branch2: SDReadableStream<OutputType>;
let cancelResolve: (reason: shared.ErrorResult) => void;
- const cancelPromise = new Promise<void>(resolve => (cancelResolve = resolve));
+ const cancelPromise = new Promise<void>(
+ (resolve) => (cancelResolve = resolve)
+ );
const pullAlgorithm = (): Promise<void> => {
return rs
@@ -362,7 +364,7 @@ export function readableStreamTee<OutputType>(
cancel2Algorithm
);
- reader[rs.closedPromise_].promise.catch(error => {
+ reader[rs.closedPromise_].promise.catch((error) => {
if (!closedOrErrored) {
rs.readableStreamDefaultControllerError(
branch1![
diff --git a/cli/js/web/streams/shared-internals.ts b/cli/js/web/streams/shared-internals.ts
index 3d802b083..7b0de2274 100644
--- a/cli/js/web/streams/shared-internals.ts
+++ b/cli/js/web/streams/shared-internals.ts
@@ -223,7 +223,7 @@ export function createAlgorithmFromUnderlyingMethod<
if (typeof method !== "function") {
throw new TypeError(`Field "${methodName}" is not a function.`);
}
- return function(...fnArgs: any[]): any {
+ return function (...fnArgs: any[]): any {
return promiseCall(method, obj, fnArgs.concat(extraArgs));
};
}
@@ -252,7 +252,7 @@ export function makeSizeAlgorithmFromSizeFunction<T>(
if (typeof sizeFn !== "function" && typeof sizeFn !== "undefined") {
throw new TypeError("size function must be undefined or a function");
}
- return function(chunk: T): number {
+ return function (chunk: T): number {
if (typeof sizeFn === "function") {
return sizeFn(chunk);
}
@@ -265,7 +265,7 @@ export function makeSizeAlgorithmFromSizeFunction<T>(
export const enum ControlledPromiseState {
Pending,
Resolved,
- Rejected
+ Rejected,
}
export interface ControlledPromise<V> {
@@ -277,14 +277,14 @@ export interface ControlledPromise<V> {
export function createControlledPromise<V>(): ControlledPromise<V> {
const conProm = {
- state: ControlledPromiseState.Pending
+ state: ControlledPromiseState.Pending,
} as ControlledPromise<V>;
- conProm.promise = new Promise<V>(function(resolve, reject) {
- conProm.resolve = function(v?: V): void {
+ conProm.promise = new Promise<V>(function (resolve, reject) {
+ conProm.resolve = function (v?: V): void {
conProm.state = ControlledPromiseState.Resolved;
resolve(v);
};
- conProm.reject = function(e?: ErrorResult): void {
+ conProm.reject = function (e?: ErrorResult): void {
conProm.state = ControlledPromiseState.Rejected;
reject(e);
};
diff --git a/cli/js/web/text_encoding.ts b/cli/js/web/text_encoding.ts
index 5f04972aa..6fd498e59 100644
--- a/cli/js/web/text_encoding.ts
+++ b/cli/js/web/text_encoding.ts
@@ -149,8 +149,8 @@ interface Encoder {
}
class SingleByteDecoder implements Decoder {
- private _index: number[];
- private _fatal: boolean;
+ #index: number[];
+ #fatal: boolean;
constructor(
index: number[],
@@ -159,20 +159,20 @@ class SingleByteDecoder implements Decoder {
if (ignoreBOM) {
throw new TypeError("Ignoring the BOM is available only with utf-8.");
}
- this._fatal = fatal;
- this._index = index;
+ this.#fatal = fatal;
+ this.#index = index;
}
- handler(stream: Stream, byte: number): number {
+ handler(_stream: Stream, byte: number): number {
if (byte === END_OF_STREAM) {
return FINISHED;
}
if (isASCIIByte(byte)) {
return byte;
}
- const codePoint = this._index[byte - 0x80];
+ const codePoint = this.#index[byte - 0x80];
if (codePoint == null) {
- return decoderError(this._fatal);
+ return decoderError(this.#fatal);
}
return codePoint;
@@ -199,9 +199,9 @@ const encodingMap: { [key: string]: string[] } = {
"latin1",
"us-ascii",
"windows-1252",
- "x-cp1252"
+ "x-cp1252",
],
- "utf-8": ["unicode-1-1-utf-8", "utf-8", "utf8"]
+ "utf-8": ["unicode-1-1-utf-8", "utf-8", "utf8"],
};
// We convert these into a Map where every label resolves to its canonical
// encoding type.
@@ -221,13 +221,134 @@ const decoders = new Map<string, (options: DecoderOptions) => Decoder>();
const encodingIndexes = new Map<string, number[]>();
// prettier-ignore
encodingIndexes.set("windows-1252", [
- 8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,
- 8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376,160,161,
- 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,
- 181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,
- 200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,
- 219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,
- 238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
+ 8364,
+ 129,
+ 8218,
+ 402,
+ 8222,
+ 8230,
+ 8224,
+ 8225,
+ 710,
+ 8240,
+ 352,
+ 8249,
+ 338,
+ 141,
+ 381,
+ 143,
+ 144,
+ 8216,
+ 8217,
+ 8220,
+ 8221,
+ 8226,
+ 8211,
+ 8212,
+ 732,
+ 8482,
+ 353,
+ 8250,
+ 339,
+ 157,
+ 382,
+ 376,
+ 160,
+ 161,
+ 162,
+ 163,
+ 164,
+ 165,
+ 166,
+ 167,
+ 168,
+ 169,
+ 170,
+ 171,
+ 172,
+ 173,
+ 174,
+ 175,
+ 176,
+ 177,
+ 178,
+ 179,
+ 180,
+ 181,
+ 182,
+ 183,
+ 184,
+ 185,
+ 186,
+ 187,
+ 188,
+ 189,
+ 190,
+ 191,
+ 192,
+ 193,
+ 194,
+ 195,
+ 196,
+ 197,
+ 198,
+ 199,
+ 200,
+ 201,
+ 202,
+ 203,
+ 204,
+ 205,
+ 206,
+ 207,
+ 208,
+ 209,
+ 210,
+ 211,
+ 212,
+ 213,
+ 214,
+ 215,
+ 216,
+ 217,
+ 218,
+ 219,
+ 220,
+ 221,
+ 222,
+ 223,
+ 224,
+ 225,
+ 226,
+ 227,
+ 228,
+ 229,
+ 230,
+ 231,
+ 232,
+ 233,
+ 234,
+ 235,
+ 236,
+ 237,
+ 238,
+ 239,
+ 240,
+ 241,
+ 242,
+ 243,
+ 244,
+ 245,
+ 246,
+ 247,
+ 248,
+ 249,
+ 250,
+ 251,
+ 252,
+ 253,
+ 254,
+ 255
]);
for (const [key, index] of encodingIndexes) {
decoders.set(
@@ -247,37 +368,37 @@ function codePointsToString(codePoints: number[]): string {
}
class Stream {
- private _tokens: number[];
+ #tokens: number[];
constructor(tokens: number[] | Uint8Array) {
- this._tokens = [].slice.call(tokens);
- this._tokens.reverse();
+ this.#tokens = [...tokens];
+ this.#tokens.reverse();
}
endOfStream(): boolean {
- return !this._tokens.length;
+ return !this.#tokens.length;
}
read(): number {
- return !this._tokens.length ? END_OF_STREAM : this._tokens.pop()!;
+ return !this.#tokens.length ? END_OF_STREAM : this.#tokens.pop()!;
}
prepend(token: number | number[]): void {
if (Array.isArray(token)) {
while (token.length) {
- this._tokens.push(token.pop()!);
+ this.#tokens.push(token.pop()!);
}
} else {
- this._tokens.push(token);
+ this.#tokens.push(token);
}
}
push(token: number | number[]): void {
if (Array.isArray(token)) {
while (token.length) {
- this._tokens.unshift(token.shift()!);
+ this.#tokens.unshift(token.shift()!);
}
} else {
- this._tokens.unshift(token);
+ this.#tokens.unshift(token);
}
}
}
@@ -299,10 +420,10 @@ function isEitherArrayBuffer(x: any): x is EitherArrayBuffer {
}
export class TextDecoder {
- private _encoding: string;
+ #encoding: string;
get encoding(): string {
- return this._encoding;
+ return this.#encoding;
}
readonly fatal: boolean = false;
readonly ignoreBOM: boolean = false;
@@ -314,9 +435,7 @@ export class TextDecoder {
if (options.fatal) {
this.fatal = true;
}
- label = String(label)
- .trim()
- .toLowerCase();
+ label = String(label).trim().toLowerCase();
const encoding = encodings.get(label);
if (!encoding) {
throw new RangeError(
@@ -326,7 +445,7 @@ export class TextDecoder {
if (!decoders.has(encoding) && encoding !== "utf-8") {
throw new TypeError(`Internal decoder ('${encoding}') not found.`);
}
- this._encoding = encoding;
+ this.#encoding = encoding;
}
decode(
@@ -354,7 +473,7 @@ export class TextDecoder {
// For simple utf-8 decoding "Deno.core.decode" can be used for performance
if (
- this._encoding === "utf-8" &&
+ this.#encoding === "utf-8" &&
this.fatal === false &&
this.ignoreBOM === false
) {
@@ -363,13 +482,13 @@ export class TextDecoder {
// For performance reasons we utilise a highly optimised decoder instead of
// the general decoder.
- if (this._encoding === "utf-8") {
+ if (this.#encoding === "utf-8") {
return decodeUtf8(bytes, this.fatal, this.ignoreBOM);
}
- const decoder = decoders.get(this._encoding)!({
+ const decoder = decoders.get(this.#encoding)!({
fatal: this.fatal,
- ignoreBOM: this.ignoreBOM
+ ignoreBOM: this.ignoreBOM,
});
const inputStream = new Stream(bytes);
const output: number[] = [];
@@ -455,7 +574,7 @@ export class TextEncoder {
return {
read,
- written
+ written,
};
}
get [Symbol.toStringTag](): string {
diff --git a/cli/js/web/timers.ts b/cli/js/web/timers.ts
index 9a957f3fe..ff18543fa 100644
--- a/cli/js/web/timers.ts
+++ b/cli/js/web/timers.ts
@@ -223,7 +223,7 @@ function setTimer(
delay,
due: now + delay,
repeat,
- scheduled: false
+ scheduled: false,
};
// Register the timer's existence in the id-to-timer map.
idMap.set(timer.id, timer);
diff --git a/cli/js/web/url.ts b/cli/js/web/url.ts
index 6ef6b367c..2b6a0d341 100644
--- a/cli/js/web/url.ts
+++ b/cli/js/web/url.ts
@@ -1,8 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-import * as urlSearchParams from "./url_search_params.ts";
+import { customInspect } from "./console.ts";
import * as domTypes from "./dom_types.ts";
+import { urls, URLSearchParams } from "./url_search_params.ts";
import { getRandomValues } from "../ops/get_random_values.ts";
-import { customInspect } from "./console.ts";
interface URLParts {
protocol: string;
@@ -24,7 +24,7 @@ const patterns = {
authentication: "(?:([^:]*)(?::([^@]*))?@)",
hostname: "([^:]+)",
- port: "(?::(\\d+))"
+ port: "(?::(\\d+))",
};
const urlRegExp = new RegExp(
@@ -35,10 +35,10 @@ const authorityRegExp = new RegExp(
`^${patterns.authentication}?${patterns.hostname}${patterns.port}?$`
);
-const searchParamsMethods: Array<keyof urlSearchParams.URLSearchParams> = [
+const searchParamsMethods: Array<keyof URLSearchParams> = [
"append",
"delete",
- "set"
+ "set",
];
function parse(url: string): URLParts | undefined {
@@ -57,7 +57,7 @@ function parse(url: string): URLParts | undefined {
port: authorityMatch[4] || "",
path: urlMatch[3] || "",
query: urlMatch[4] || "",
- hash: urlMatch[5] || ""
+ hash: urlMatch[5] || "",
};
}
}
@@ -136,9 +136,11 @@ function resolvePathFromBase(path: string, basePath: string): string {
return normalizePath(prefix + suffix);
}
-export class URL {
- private _parts: URLParts;
- private _searchParams!: urlSearchParams.URLSearchParams;
+/** @internal */
+export const parts = new WeakMap<URL, URLParts>();
+
+export class URL implements domTypes.URL {
+ #searchParams!: URLSearchParams;
[customInspect](): string {
const keys = [
@@ -152,7 +154,7 @@ export class URL {
"port",
"pathname",
"hash",
- "search"
+ "search",
];
const objectString = keys
.map((key: string) => `${key}: "${this[key as keyof this] || ""}"`)
@@ -160,8 +162,8 @@ export class URL {
return `URL { ${objectString} }`;
}
- private _updateSearchParams(): void {
- const searchParams = new urlSearchParams.URLSearchParams(this.search);
+ #updateSearchParams = (): void => {
+ const searchParams = new URLSearchParams(this.search);
for (const methodName of searchParamsMethods) {
/* eslint-disable @typescript-eslint/no-explicit-any */
@@ -172,27 +174,25 @@ export class URL {
};
/* eslint-enable */
}
- this._searchParams = searchParams;
+ this.#searchParams = searchParams;
- // convert to `any` that has avoided the private limit
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (this._searchParams as any).url = this;
- }
+ urls.set(searchParams, this);
+ };
get hash(): string {
- return this._parts.hash;
+ return parts.get(this)!.hash;
}
set hash(value: string) {
value = unescape(String(value));
if (!value) {
- this._parts.hash = "";
+ parts.get(this)!.hash = "";
} else {
if (value.charAt(0) !== "#") {
value = `#${value}`;
}
// hashes can contain % and # unescaped
- this._parts.hash = escape(value)
+ parts.get(this)!.hash = escape(value)
.replace(/%25/g, "%")
.replace(/%23/g, "#");
}
@@ -205,17 +205,17 @@ export class URL {
set host(value: string) {
value = String(value);
const url = new URL(`http://${value}`);
- this._parts.hostname = url.hostname;
- this._parts.port = url.port;
+ parts.get(this)!.hostname = url.hostname;
+ parts.get(this)!.port = url.port;
}
get hostname(): string {
- return this._parts.hostname;
+ return parts.get(this)!.hostname;
}
set hostname(value: string) {
value = String(value);
- this._parts.hostname = encodeURIComponent(value);
+ parts.get(this)!.hostname = encodeURIComponent(value);
}
get href(): string {
@@ -234,8 +234,8 @@ export class URL {
value = String(value);
if (value !== this.href) {
const url = new URL(value);
- this._parts = { ...url._parts };
- this._updateSearchParams();
+ parts.set(this, { ...parts.get(url)! });
+ this.#updateSearchParams();
}
}
@@ -247,16 +247,16 @@ export class URL {
}
get password(): string {
- return this._parts.password;
+ return parts.get(this)!.password;
}
set password(value: string) {
value = String(value);
- this._parts.password = encodeURIComponent(value);
+ parts.get(this)!.password = encodeURIComponent(value);
}
get pathname(): string {
- return this._parts.path ? this._parts.path : "/";
+ return parts.get(this)?.path || "/";
}
set pathname(value: string) {
@@ -265,22 +265,22 @@ export class URL {
value = `/${value}`;
}
// paths can contain % unescaped
- this._parts.path = escape(value).replace(/%25/g, "%");
+ parts.get(this)!.path = escape(value).replace(/%25/g, "%");
}
get port(): string {
- return this._parts.port;
+ return parts.get(this)!.port;
}
set port(value: string) {
const port = parseInt(String(value), 10);
- this._parts.port = isNaN(port)
+ parts.get(this)!.port = isNaN(port)
? ""
: Math.max(0, port % 2 ** 16).toString();
}
get protocol(): string {
- return `${this._parts.protocol}:`;
+ return `${parts.get(this)!.protocol}:`;
}
set protocol(value: string) {
@@ -289,16 +289,17 @@ export class URL {
if (value.charAt(value.length - 1) === ":") {
value = value.slice(0, -1);
}
- this._parts.protocol = encodeURIComponent(value);
+ parts.get(this)!.protocol = encodeURIComponent(value);
}
}
get search(): string {
- if (this._parts.query === null || this._parts.query === "") {
+ const query = parts.get(this)!.query;
+ if (query === null || query === "") {
return "";
}
- return this._parts.query;
+ return query;
}
set search(value: string) {
@@ -313,27 +314,27 @@ export class URL {
query = value;
}
- this._parts.query = query;
- this._updateSearchParams();
+ parts.get(this)!.query = query;
+ this.#updateSearchParams();
}
get username(): string {
- return this._parts.username;
+ return parts.get(this)!.username;
}
set username(value: string) {
value = String(value);
- this._parts.username = encodeURIComponent(value);
+ parts.get(this)!.username = encodeURIComponent(value);
}
- get searchParams(): urlSearchParams.URLSearchParams {
- return this._searchParams;
+ get searchParams(): URLSearchParams {
+ return this.#searchParams;
}
constructor(url: string, base?: string | URL) {
let baseParts: URLParts | undefined;
if (base) {
- baseParts = typeof base === "string" ? parse(base) : base._parts;
+ baseParts = typeof base === "string" ? parse(base) : parts.get(base);
if (!baseParts || baseParts.protocol == "") {
throw new TypeError("Invalid base URL.");
}
@@ -345,9 +346,9 @@ export class URL {
}
if (urlParts.protocol) {
- this._parts = urlParts;
+ parts.set(this, urlParts);
} else if (baseParts) {
- this._parts = {
+ parts.set(this, {
protocol: baseParts.protocol,
username: baseParts.username,
password: baseParts.password,
@@ -355,12 +356,12 @@ export class URL {
port: baseParts.port,
path: resolvePathFromBase(urlParts.path, baseParts.path || "/"),
query: urlParts.query,
- hash: urlParts.hash
- };
+ hash: urlParts.hash,
+ });
} else {
throw new TypeError("URL requires a base URL.");
}
- this._updateSearchParams();
+ this.#updateSearchParams();
}
toString(): string {
diff --git a/cli/js/web/url_search_params.ts b/cli/js/web/url_search_params.ts
index 8f60f2918..aad59bb8c 100644
--- a/cli/js/web/url_search_params.ts
+++ b/cli/js/web/url_search_params.ts
@@ -1,33 +1,61 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
-import { URL } from "./url.ts";
-import { requiredArguments } from "./util.ts";
-
-// Returns whether o is iterable.
-// @internal
-export function isIterable<T, P extends keyof T, K extends T[P]>(
- o: T
-): o is T & Iterable<[P, K]> {
- // checks for null and undefined
- if (o == null) {
- return false;
- }
- return (
- typeof ((o as unknown) as Iterable<[P, K]>)[Symbol.iterator] === "function"
- );
+import * as domTypes from "./dom_types.ts";
+import { URL, parts } from "./url.ts";
+import { isIterable, requiredArguments } from "./util.ts";
+
+/** @internal */
+export const urls = new WeakMap<URLSearchParams, URL | null>();
+
+function handleStringInitialization(
+ searchParams: URLSearchParams,
+ init: string
+): void {
+ // Overload: USVString
+ // If init is a string and starts with U+003F (?),
+ // remove the first code point from init.
+ if (init.charCodeAt(0) === 0x003f) {
+ init = init.slice(1);
+ }
+
+ for (const pair of init.split("&")) {
+ // Empty params are ignored
+ if (pair.length === 0) {
+ continue;
+ }
+ const position = pair.indexOf("=");
+ const name = pair.slice(0, position === -1 ? pair.length : position);
+ const value = pair.slice(name.length + 1);
+ searchParams.append(decodeURIComponent(name), decodeURIComponent(value));
+ }
+}
+
+function handleArrayInitialization(
+ searchParams: URLSearchParams,
+ init: string[][] | Iterable<[string, string]>
+): void {
+ // Overload: sequence<sequence<USVString>>
+ for (const tuple of init) {
+ // If pair does not contain exactly two items, then throw a TypeError.
+ if (tuple.length !== 2) {
+ throw new TypeError(
+ "URLSearchParams.constructor tuple array argument must only contain pair elements"
+ );
+ }
+ searchParams.append(tuple[0], tuple[1]);
+ }
}
-export class URLSearchParams {
- private params: Array<[string, string]> = [];
- private url: URL | null = null;
+export class URLSearchParams implements domTypes.URLSearchParams {
+ #params: Array<[string, string]> = [];
constructor(init: string | string[][] | Record<string, string> = "") {
if (typeof init === "string") {
- this._handleStringInitialization(init);
+ handleStringInitialization(this, init);
return;
}
if (Array.isArray(init) || isIterable(init)) {
- this._handleArrayInitialization(init);
+ handleArrayInitialization(this, init);
return;
}
@@ -36,7 +64,7 @@ export class URLSearchParams {
}
if (init instanceof URLSearchParams) {
- this.params = init.params;
+ this.#params = [...init.#params];
return;
}
@@ -44,10 +72,13 @@ export class URLSearchParams {
for (const key of Object.keys(init)) {
this.append(key, init[key]);
}
+
+ urls.set(this, null);
}
- private updateSteps(): void {
- if (this.url === null) {
+ #updateSteps = (): void => {
+ const url = urls.get(this);
+ if (url == null) {
return;
}
@@ -56,35 +87,34 @@ export class URLSearchParams {
query = null;
}
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (this.url as any)._parts.query = query;
- }
+ parts.get(url)!.query = query;
+ };
append(name: string, value: string): void {
requiredArguments("URLSearchParams.append", arguments.length, 2);
- this.params.push([String(name), String(value)]);
- this.updateSteps();
+ this.#params.push([String(name), String(value)]);
+ this.#updateSteps();
}
delete(name: string): void {
requiredArguments("URLSearchParams.delete", arguments.length, 1);
name = String(name);
let i = 0;
- while (i < this.params.length) {
- if (this.params[i][0] === name) {
- this.params.splice(i, 1);
+ while (i < this.#params.length) {
+ if (this.#params[i][0] === name) {
+ this.#params.splice(i, 1);
} else {
i++;
}
}
- this.updateSteps();
+ this.#updateSteps();
}
getAll(name: string): string[] {
requiredArguments("URLSearchParams.getAll", arguments.length, 1);
name = String(name);
const values = [];
- for (const entry of this.params) {
+ for (const entry of this.#params) {
if (entry[0] === name) {
values.push(entry[1]);
}
@@ -96,7 +126,7 @@ export class URLSearchParams {
get(name: string): string | null {
requiredArguments("URLSearchParams.get", arguments.length, 1);
name = String(name);
- for (const entry of this.params) {
+ for (const entry of this.#params) {
if (entry[0] === name) {
return entry[1];
}
@@ -108,7 +138,7 @@ export class URLSearchParams {
has(name: string): boolean {
requiredArguments("URLSearchParams.has", arguments.length, 1);
name = String(name);
- return this.params.some((entry): boolean => entry[0] === name);
+ return this.#params.some((entry) => entry[0] === name);
}
set(name: string, value: string): void {
@@ -121,14 +151,14 @@ export class URLSearchParams {
value = String(value);
let found = false;
let i = 0;
- while (i < this.params.length) {
- if (this.params[i][0] === name) {
+ while (i < this.#params.length) {
+ if (this.#params[i][0] === name) {
if (!found) {
- this.params[i][1] = value;
+ this.#params[i][1] = value;
found = true;
i++;
} else {
- this.params.splice(i, 1);
+ this.#params.splice(i, 1);
}
} else {
i++;
@@ -141,14 +171,12 @@ export class URLSearchParams {
this.append(name, value);
}
- this.updateSteps();
+ this.#updateSteps();
}
sort(): void {
- this.params = this.params.sort((a, b): number =>
- a[0] === b[0] ? 0 : a[0] > b[0] ? 1 : -1
- );
- this.updateSteps();
+ this.#params.sort((a, b) => (a[0] === b[0] ? 0 : a[0] > b[0] ? 1 : -1));
+ this.#updateSteps();
}
forEach(
@@ -168,66 +196,31 @@ export class URLSearchParams {
}
*keys(): IterableIterator<string> {
- for (const entry of this.params) {
- yield entry[0];
+ for (const [key] of this.#params) {
+ yield key;
}
}
*values(): IterableIterator<string> {
- for (const entry of this.params) {
- yield entry[1];
+ for (const [, value] of this.#params) {
+ yield value;
}
}
*entries(): IterableIterator<[string, string]> {
- yield* this.params;
+ yield* this.#params;
}
*[Symbol.iterator](): IterableIterator<[string, string]> {
- yield* this.params;
+ yield* this.#params;
}
toString(): string {
- return this.params
+ return this.#params
.map(
- (tuple): string =>
+ (tuple) =>
`${encodeURIComponent(tuple[0])}=${encodeURIComponent(tuple[1])}`
)
.join("&");
}
-
- private _handleStringInitialization(init: string): void {
- // Overload: USVString
- // If init is a string and starts with U+003F (?),
- // remove the first code point from init.
- if (init.charCodeAt(0) === 0x003f) {
- init = init.slice(1);
- }
-
- for (const pair of init.split("&")) {
- // Empty params are ignored
- if (pair.length === 0) {
- continue;
- }
- const position = pair.indexOf("=");
- const name = pair.slice(0, position === -1 ? pair.length : position);
- const value = pair.slice(name.length + 1);
- this.append(decodeURIComponent(name), decodeURIComponent(value));
- }
- }
-
- private _handleArrayInitialization(
- init: string[][] | Iterable<[string, string]>
- ): void {
- // Overload: sequence<sequence<USVString>>
- for (const tuple of init) {
- // If pair does not contain exactly two items, then throw a TypeError.
- if (tuple.length !== 2) {
- throw new TypeError(
- "URLSearchParams.constructor tuple array argument must only contain pair elements"
- );
- }
- this.append(tuple[0], tuple[1]);
- }
- }
}
diff --git a/cli/js/web/util.ts b/cli/js/web/util.ts
index 8d248ce1f..19a30a675 100644
--- a/cli/js/web/util.ts
+++ b/cli/js/web/util.ts
@@ -31,7 +31,7 @@ export function immutableDefine(
Object.defineProperty(o, p, {
value,
configurable: false,
- writable: false
+ writable: false,
});
}
@@ -53,3 +53,18 @@ export function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean {
}
return Object.prototype.hasOwnProperty.call(obj, v);
}
+
+/** Returns whether o is iterable.
+ *
+ * @internal */
+export function isIterable<T, P extends keyof T, K extends T[P]>(
+ o: T
+): o is T & Iterable<[P, K]> {
+ // checks for null and undefined
+ if (o == null) {
+ return false;
+ }
+ return (
+ typeof ((o as unknown) as Iterable<[P, K]>)[Symbol.iterator] === "function"
+ );
+}
diff --git a/cli/js/web/workers.ts b/cli/js/web/workers.ts
index 256090d57..834d0f297 100644
--- a/cli/js/web/workers.ts
+++ b/cli/js/web/workers.ts
@@ -4,13 +4,12 @@ import {
createWorker,
hostTerminateWorker,
hostPostMessage,
- hostGetMessage
+ hostGetMessage,
} from "../ops/worker_host.ts";
import { log } from "../util.ts";
import { TextDecoder, TextEncoder } from "./text_encoding.ts";
/*
import { blobURLMap } from "./web/url.ts";
-import { blobBytesWeakMap } from "./web/blob.ts";
*/
import { Event } from "./event.ts";
import { EventTarget } from "./event_target.ts";
@@ -48,13 +47,13 @@ export interface WorkerOptions {
}
export class WorkerImpl extends EventTarget implements Worker {
- private readonly id: number;
- private isClosing = false;
+ readonly #id: number;
+ #name: string;
+ #terminated = false;
+
public onerror?: (e: any) => void;
public onmessage?: (data: any) => void;
public onmessageerror?: () => void;
- private name: string;
- private terminated = false;
constructor(specifier: string, options?: WorkerOptions) {
super();
@@ -66,7 +65,7 @@ export class WorkerImpl extends EventTarget implements Worker {
);
}
- this.name = name;
+ this.#name = name;
const hasSourceCode = false;
const sourceCode = decoder.decode(new Uint8Array());
@@ -92,11 +91,11 @@ export class WorkerImpl extends EventTarget implements Worker {
sourceCode,
options?.name
);
- this.id = id;
+ this.#id = id;
this.poll();
}
- private handleError(e: any): boolean {
+ #handleError = (e: any): boolean => {
// TODO: this is being handled in a type unsafe way, it should be type safe
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const event = new Event("error", { cancelable: true }) as any;
@@ -115,14 +114,14 @@ export class WorkerImpl extends EventTarget implements Worker {
}
return handled;
- }
+ };
async poll(): Promise<void> {
- while (!this.terminated) {
- const event = await hostGetMessage(this.id);
+ while (!this.#terminated) {
+ const event = await hostGetMessage(this.#id);
// If terminate was called then we ignore all messages
- if (this.terminated) {
+ if (this.#terminated) {
return;
}
@@ -137,15 +136,15 @@ export class WorkerImpl extends EventTarget implements Worker {
}
if (type === "error") {
- if (!this.handleError(event.error)) {
+ if (!this.#handleError(event.error)) {
throw Error(event.error.message);
}
continue;
}
if (type === "close") {
- log(`Host got "close" message from worker: ${this.name}`);
- this.terminated = true;
+ log(`Host got "close" message from worker: ${this.#name}`);
+ this.#terminated = true;
return;
}
@@ -154,17 +153,17 @@ export class WorkerImpl extends EventTarget implements Worker {
}
postMessage(data: any): void {
- if (this.terminated) {
+ if (this.#terminated) {
return;
}
- hostPostMessage(this.id, encodeMessage(data));
+ hostPostMessage(this.#id, encodeMessage(data));
}
terminate(): void {
- if (!this.terminated) {
- this.terminated = true;
- hostTerminateWorker(this.id);
+ if (!this.#terminated) {
+ this.#terminated = true;
+ hostTerminateWorker(this.#id);
}
}
}
diff --git a/cli/tests/015_duplicate_parallel_import.js b/cli/tests/015_duplicate_parallel_import.js
index 37033cfa2..172eeaf53 100644
--- a/cli/tests/015_duplicate_parallel_import.js
+++ b/cli/tests/015_duplicate_parallel_import.js
@@ -5,7 +5,7 @@ const promises = new Array(100)
.fill(null)
.map(() => import("./subdir/mod1.ts"));
-Promise.all(promises).then(imports => {
+Promise.all(promises).then((imports) => {
const mod = imports.reduce((first, cur) => {
if (typeof first !== "object") {
throw new Error("Expected an object.");
diff --git a/cli/tests/045_proxy_test.ts b/cli/tests/045_proxy_test.ts
index 98293c2a0..6f8b45fd1 100644
--- a/cli/tests/045_proxy_test.ts
+++ b/cli/tests/045_proxy_test.ts
@@ -17,7 +17,7 @@ async function proxyRequest(req: ServerRequest): Promise<void> {
console.log(`Proxy request to: ${req.url}`);
const resp = await fetch(req.url, {
method: req.method,
- headers: req.headers
+ headers: req.headers,
});
req.respond(resp);
}
@@ -27,8 +27,8 @@ async function testFetch(): Promise<void> {
cmd: [Deno.execPath(), "--reload", "--allow-net", "045_proxy_client.ts"],
stdout: "piped",
env: {
- HTTP_PROXY: `http://${addr}`
- }
+ HTTP_PROXY: `http://${addr}`,
+ },
});
const status = await c.status();
@@ -42,12 +42,12 @@ async function testModuleDownload(): Promise<void> {
Deno.execPath(),
"--reload",
"fetch",
- "http://localhost:4545/std/examples/colors.ts"
+ "http://localhost:4545/std/examples/colors.ts",
],
stdout: "piped",
env: {
- HTTP_PROXY: `http://${addr}`
- }
+ HTTP_PROXY: `http://${addr}`,
+ },
});
const httpStatus = await http.status();
diff --git a/cli/tests/053_import_compression/main.ts b/cli/tests/053_import_compression/main.ts
index b6f7e2c9a..d18363b7d 100644
--- a/cli/tests/053_import_compression/main.ts
+++ b/cli/tests/053_import_compression/main.ts
@@ -4,10 +4,10 @@ import "http://127.0.0.1:4545/cli/tests/053_import_compression/brotli";
console.log(
await fetch(
"http://127.0.0.1:4545/cli/tests/053_import_compression/gziped"
- ).then(res => res.text())
+ ).then((res) => res.text())
);
console.log(
await fetch(
"http://127.0.0.1:4545/cli/tests/053_import_compression/brotli"
- ).then(res => res.text())
+ ).then((res) => res.text())
);
diff --git a/cli/tests/057_revoke_permissions.ts b/cli/tests/057_revoke_permissions.ts
index 4481dbfd9..d93ae3538 100644
--- a/cli/tests/057_revoke_permissions.ts
+++ b/cli/tests/057_revoke_permissions.ts
@@ -7,7 +7,7 @@ const knownPermissions: Deno.PermissionName[] = [
"net",
"env",
"plugin",
- "hrtime"
+ "hrtime",
];
export function assert(cond: unknown): asserts cond {
diff --git a/cli/tests/cafile_ts_fetch.ts b/cli/tests/cafile_ts_fetch.ts
index be158bf70..14f39ef97 100644
--- a/cli/tests/cafile_ts_fetch.ts
+++ b/cli/tests/cafile_ts_fetch.ts
@@ -1,3 +1,3 @@
fetch("https://localhost:5545/cli/tests/cafile_ts_fetch.ts.out")
- .then(r => r.text())
- .then(t => console.log(t.trimEnd()));
+ .then((r) => r.text())
+ .then((t) => console.log(t.trimEnd()));
diff --git a/cli/tests/compiler_api_test.ts b/cli/tests/compiler_api_test.ts
index 540ac6680..4886e03b8 100644
--- a/cli/tests/compiler_api_test.ts
+++ b/cli/tests/compiler_api_test.ts
@@ -6,7 +6,7 @@ const { compile, transpileOnly, bundle, test } = Deno;
test(async function compilerApiCompileSources() {
const [diagnostics, actual] = await compile("/foo.ts", {
"/foo.ts": `import * as bar from "./bar.ts";\n\nconsole.log(bar);\n`,
- "/bar.ts": `export const bar = "bar";\n`
+ "/bar.ts": `export const bar = "bar";\n`,
});
assert(diagnostics == null);
assert(actual);
@@ -14,7 +14,7 @@ test(async function compilerApiCompileSources() {
"/bar.js.map",
"/bar.js",
"/foo.js.map",
- "/foo.js"
+ "/foo.js",
]);
});
@@ -32,11 +32,11 @@ test(async function compilerApiCompileOptions() {
const [diagnostics, actual] = await compile(
"/foo.ts",
{
- "/foo.ts": `export const foo = "foo";`
+ "/foo.ts": `export const foo = "foo";`,
},
{
module: "amd",
- sourceMap: false
+ sourceMap: false,
}
);
assert(diagnostics == null);
@@ -50,10 +50,10 @@ test(async function compilerApiCompileLib() {
"/foo.ts",
{
"/foo.ts": `console.log(document.getElementById("foo"));
- console.log(Deno.args);`
+ console.log(Deno.args);`,
},
{
- lib: ["dom", "es2018", "deno.ns"]
+ lib: ["dom", "es2018", "deno.ns"],
}
);
assert(diagnostics == null);
@@ -65,10 +65,10 @@ test(async function compilerApiCompileTypes() {
const [diagnostics, actual] = await compile(
"/foo.ts",
{
- "/foo.ts": `console.log(Foo.bar);`
+ "/foo.ts": `console.log(Foo.bar);`,
},
{
- types: ["./subdir/foo_types.d.ts"]
+ types: ["./subdir/foo_types.d.ts"],
}
);
assert(diagnostics == null);
@@ -78,7 +78,7 @@ test(async function compilerApiCompileTypes() {
test(async function transpileOnlyApi() {
const actual = await transpileOnly({
- "foo.ts": `export enum Foo { Foo, Bar, Baz };\n`
+ "foo.ts": `export enum Foo { Foo, Bar, Baz };\n`,
});
assert(actual);
assertEquals(Object.keys(actual), ["foo.ts"]);
@@ -89,11 +89,11 @@ test(async function transpileOnlyApi() {
test(async function transpileOnlyApiConfig() {
const actual = await transpileOnly(
{
- "foo.ts": `export enum Foo { Foo, Bar, Baz };\n`
+ "foo.ts": `export enum Foo { Foo, Bar, Baz };\n`,
},
{
sourceMap: false,
- module: "amd"
+ module: "amd",
}
);
assert(actual);
@@ -105,7 +105,7 @@ test(async function transpileOnlyApiConfig() {
test(async function bundleApiSources() {
const [diagnostics, actual] = await bundle("/foo.ts", {
"/foo.ts": `export * from "./bar.ts";\n`,
- "/bar.ts": `export const bar = "bar";\n`
+ "/bar.ts": `export const bar = "bar";\n`,
});
assert(diagnostics == null);
assert(actual.includes(`__instantiate("foo")`));
@@ -124,10 +124,10 @@ test(async function bundleApiConfig() {
"/foo.ts",
{
"/foo.ts": `// random comment\nexport * from "./bar.ts";\n`,
- "/bar.ts": `export const bar = "bar";\n`
+ "/bar.ts": `export const bar = "bar";\n`,
},
{
- removeComments: true
+ removeComments: true,
}
);
assert(diagnostics == null);
@@ -137,7 +137,7 @@ test(async function bundleApiConfig() {
test(async function bundleApiJsModules() {
const [diagnostics, actual] = await bundle("/foo.js", {
"/foo.js": `export * from "./bar.js";\n`,
- "/bar.js": `export const bar = "bar";\n`
+ "/bar.js": `export const bar = "bar";\n`,
});
assert(diagnostics == null);
assert(actual.includes(`System.register("bar",`));
@@ -145,7 +145,7 @@ test(async function bundleApiJsModules() {
test(async function diagnosticsTest() {
const [diagnostics] = await compile("/foo.ts", {
- "/foo.ts": `document.getElementById("foo");`
+ "/foo.ts": `document.getElementById("foo");`,
});
assert(Array.isArray(diagnostics));
assert(diagnostics.length === 1);
diff --git a/cli/tests/complex_permissions_test.ts b/cli/tests/complex_permissions_test.ts
index 401c8cd81..55b4ead35 100644
--- a/cli/tests/complex_permissions_test.ts
+++ b/cli/tests/complex_permissions_test.ts
@@ -4,23 +4,23 @@ const { args, readFileSync, writeFileSync, exit } = Deno;
const name = args[0];
const test: { [key: string]: Function } = {
read(files: string[]): void {
- files.forEach(file => readFileSync(file));
+ files.forEach((file) => readFileSync(file));
},
write(files: string[]): void {
- files.forEach(file =>
+ files.forEach((file) =>
writeFileSync(file, new Uint8Array(0), { append: true })
);
},
netFetch(hosts: string[]): void {
- hosts.forEach(host => fetch(host));
+ hosts.forEach((host) => fetch(host));
},
netListen(endpoints: string[]): void {
- endpoints.forEach(endpoint => {
+ endpoints.forEach((endpoint) => {
const [hostname, port] = endpoint.split(":");
const listener = Deno.listen({
transport: "tcp",
hostname,
- port: parseInt(port, 10)
+ port: parseInt(port, 10),
});
listener.close();
});
@@ -31,11 +31,11 @@ const test: { [key: string]: Function } = {
const listener = await Deno.connect({
transport: "tcp",
hostname,
- port: parseInt(port, 10)
+ port: parseInt(port, 10),
});
listener.close();
}
- }
+ },
};
if (!test[name]) {
diff --git a/cli/tests/error_003_typescript.ts b/cli/tests/error_003_typescript.ts
index 4ce86bb83..e06e466e7 100644
--- a/cli/tests/error_003_typescript.ts
+++ b/cli/tests/error_003_typescript.ts
@@ -4,17 +4,17 @@ let x = {
b: {
c() {
return { d: "hello" };
- }
- }
- }
+ },
+ },
+ },
};
let y = {
a: {
b: {
c() {
return { d: 1234 };
- }
- }
- }
+ },
+ },
+ },
};
x = y;
diff --git a/cli/tests/lib_ref.ts b/cli/tests/lib_ref.ts
index 9fc84ea3e..1b9f243c8 100644
--- a/cli/tests/lib_ref.ts
+++ b/cli/tests/lib_ref.ts
@@ -1,11 +1,11 @@
const [errors, program] = await Deno.compile(
"main.ts",
{
- "main.ts": `/// <reference lib="dom" />\n\ndocument.getElementById("foo");\nDeno.args;`
+ "main.ts": `/// <reference lib="dom" />\n\ndocument.getElementById("foo");\nDeno.args;`,
},
{
target: "es2018",
- lib: ["es2018", "deno.ns"]
+ lib: ["es2018", "deno.ns"],
}
);
diff --git a/cli/tests/lib_runtime_api.ts b/cli/tests/lib_runtime_api.ts
index 848b523a1..5d76ea1c5 100644
--- a/cli/tests/lib_runtime_api.ts
+++ b/cli/tests/lib_runtime_api.ts
@@ -1,10 +1,10 @@
const [errors, program] = await Deno.compile(
"main.ts",
{
- "main.ts": `document.getElementById("foo");`
+ "main.ts": `document.getElementById("foo");`,
},
{
- lib: ["dom", "esnext"]
+ lib: ["dom", "esnext"],
}
);
diff --git a/cli/tests/lock_write_fetch.ts b/cli/tests/lock_write_fetch.ts
index 206a2f864..2e9735313 100644
--- a/cli/tests/lock_write_fetch.ts
+++ b/cli/tests/lock_write_fetch.ts
@@ -11,8 +11,8 @@ const fetchProc = Deno.run({
"--reload",
"--lock=lock_write_fetch.json",
"--lock-write",
- "https_import.ts"
- ]
+ "https_import.ts",
+ ],
});
const fetchCode = (await fetchProc.status()).code;
@@ -25,8 +25,8 @@ const fetchCheckProc = Deno.run({
Deno.execPath(),
"fetch",
"--lock=lock_write_fetch.json",
- "https_import.ts"
- ]
+ "https_import.ts",
+ ],
});
const fetchCheckProcCode = (await fetchCheckProc.status()).code;
@@ -35,7 +35,7 @@ console.log(`fetch check code: ${fetchCheckProcCode}`);
const runProc = Deno.run({
stdout: "null",
stderr: "null",
- cmd: [Deno.execPath(), "--lock=lock_write_fetch.json", "https_import.ts"]
+ cmd: [Deno.execPath(), "--lock=lock_write_fetch.json", "https_import.ts"],
});
const runCode = (await runProc.status()).code;
diff --git a/cli/tests/permission_test.ts b/cli/tests/permission_test.ts
index 33c3859cb..1e6abae21 100644
--- a/cli/tests/permission_test.ts
+++ b/cli/tests/permission_test.ts
@@ -21,10 +21,10 @@ const test: { [key: string]: Function } = {
cmd: [
"python",
"-c",
- "import sys; sys.stdout.write('hello'); sys.stdout.flush()"
- ]
+ "import sys; sys.stdout.write('hello'); sys.stdout.flush()",
+ ],
});
- }
+ },
};
if (!test[name]) {
diff --git a/cli/tests/subdir/bench_worker.ts b/cli/tests/subdir/bench_worker.ts
index 619a35fa2..7e85eed03 100644
--- a/cli/tests/subdir/bench_worker.ts
+++ b/cli/tests/subdir/bench_worker.ts
@@ -1,10 +1,10 @@
-onmessage = function(e): void {
+onmessage = function (e): void {
const { cmdId, action, data } = e.data;
switch (action) {
case 0: // Static response
postMessage({
cmdId,
- data: "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
+ data: "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n",
});
break;
case 1: // Respond with request data
diff --git a/cli/tests/subdir/nested_worker.js b/cli/tests/subdir/nested_worker.js
index a4eed723a..f5ac23a19 100644
--- a/cli/tests/subdir/nested_worker.js
+++ b/cli/tests/subdir/nested_worker.js
@@ -1,18 +1,18 @@
// Specifier should be resolved relative to current file
const jsWorker = new Worker("./sibling_worker.js", {
type: "module",
- name: "sibling"
+ name: "sibling",
});
-jsWorker.onerror = _e => {
+jsWorker.onerror = (_e) => {
postMessage({ type: "error" });
};
-jsWorker.onmessage = e => {
+jsWorker.onmessage = (e) => {
postMessage({ type: "msg", text: e });
close();
};
-onmessage = function(e) {
+onmessage = function (e) {
jsWorker.postMessage(e.data);
};
diff --git a/cli/tests/subdir/sibling_worker.js b/cli/tests/subdir/sibling_worker.js
index 0e91141ce..99707e5d6 100644
--- a/cli/tests/subdir/sibling_worker.js
+++ b/cli/tests/subdir/sibling_worker.js
@@ -1,4 +1,4 @@
-onmessage = e => {
+onmessage = (e) => {
postMessage(e.data);
close();
};
diff --git a/cli/tests/subdir/test_worker.js b/cli/tests/subdir/test_worker.js
index 9c1e555b5..02cd86eac 100644
--- a/cli/tests/subdir/test_worker.js
+++ b/cli/tests/subdir/test_worker.js
@@ -4,7 +4,7 @@ if (self.name !== "jsWorker") {
throw Error(`Bad worker name: ${self.name}, expected jsWorker`);
}
-onmessage = function(e) {
+onmessage = function (e) {
if (thrown === false) {
thrown = true;
throw new SyntaxError("[test error]");
@@ -14,6 +14,6 @@ onmessage = function(e) {
close();
};
-onerror = function() {
+onerror = function () {
return false;
};
diff --git a/cli/tests/subdir/test_worker.ts b/cli/tests/subdir/test_worker.ts
index 1f924c073..ca79dcfe4 100644
--- a/cli/tests/subdir/test_worker.ts
+++ b/cli/tests/subdir/test_worker.ts
@@ -2,7 +2,7 @@ if (self.name !== "tsWorker") {
throw Error(`Invalid worker name: ${self.name}, expected tsWorker`);
}
-onmessage = function(e): void {
+onmessage = function (e): void {
postMessage(e.data);
close();
};
diff --git a/cli/tests/subdir/test_worker_basic.js b/cli/tests/subdir/test_worker_basic.js
index aef1658c0..aea360872 100644
--- a/cli/tests/subdir/test_worker_basic.js
+++ b/cli/tests/subdir/test_worker_basic.js
@@ -5,11 +5,11 @@ if (self.name !== "jsWorker") {
throw Error(`Bad worker name: ${self.name}, expected jsWorker`);
}
-onmessage = function(e) {
+onmessage = function (e) {
postMessage(e.data);
close();
};
-onerror = function() {
+onerror = function () {
return false;
};
diff --git a/cli/tests/workers_test.ts b/cli/tests/workers_test.ts
index 84eeabf12..42bd96d96 100644
--- a/cli/tests/workers_test.ts
+++ b/cli/tests/workers_test.ts
@@ -31,15 +31,15 @@ Deno.test({
name: "workersBasic",
// FIXME(bartlomieju):
disableOpSanitizer: true,
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
const promise = createResolvable();
const jsWorker = new Worker("../tests/subdir/test_worker.js", {
type: "module",
- name: "jsWorker"
+ name: "jsWorker",
});
const tsWorker = new Worker("../tests/subdir/test_worker.ts", {
type: "module",
- name: "tsWorker"
+ name: "tsWorker",
});
tsWorker.onmessage = (e): void => {
@@ -59,19 +59,19 @@ Deno.test({
jsWorker.postMessage("Hello World");
await promise;
- }
+ },
});
Deno.test({
name: "nestedWorker",
// FIXME(bartlomieju):
disableOpSanitizer: true,
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
const promise = createResolvable();
const nestedWorker = new Worker("../tests/subdir/nested_worker.js", {
type: "module",
- name: "nested"
+ name: "nested",
});
nestedWorker.onmessage = (e): void => {
@@ -81,17 +81,17 @@ Deno.test({
nestedWorker.postMessage("Hello World");
await promise;
- }
+ },
});
Deno.test({
name: "workerThrowsWhenExecuting",
// FIXME(bartlomieju):
disableOpSanitizer: true,
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
const promise = createResolvable();
const throwingWorker = new Worker("../tests/subdir/throwing_worker.js", {
- type: "module"
+ type: "module",
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -102,18 +102,18 @@ Deno.test({
};
await promise;
- }
+ },
});
Deno.test({
name: "workerCanUseFetch",
// FIXME(bartlomieju):
disableOpSanitizer: true,
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
const promise = createResolvable();
const fetchingWorker = new Worker("../tests/subdir/fetching_worker.js", {
- type: "module"
+ type: "module",
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -129,5 +129,5 @@ Deno.test({
};
await promise;
- }
+ },
});
diff --git a/core/examples/http_bench.js b/core/examples/http_bench.js
index 72f53550d..d9878cbe7 100644
--- a/core/examples/http_bench.js
+++ b/core/examples/http_bench.js
@@ -5,7 +5,7 @@ const requestBuf = new Uint8Array(64 * 1024);
const responseBuf = new Uint8Array(
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
.split("")
- .map(c => c.charCodeAt(0))
+ .map((c) => c.charCodeAt(0))
);
const promiseMap = new Map();
let nextPromiseId = 1;
diff --git a/core/shared_queue.js b/core/shared_queue.js
index 742a90995..1750740d6 100644
--- a/core/shared_queue.js
+++ b/core/shared_queue.js
@@ -18,7 +18,7 @@ SharedQueue Binary Layout
/* eslint-disable @typescript-eslint/no-use-before-define */
-(window => {
+((window) => {
const GLOBAL_NAMESPACE = "Deno";
const CORE_NAMESPACE = "core";
const MAX_RECORDS = 100;
@@ -200,9 +200,9 @@ SharedQueue Binary Layout
size,
push,
reset,
- shift
+ shift,
},
- ops
+ ops,
};
assert(window[GLOBAL_NAMESPACE] != null);
diff --git a/deno_typescript/compiler_main.js b/deno_typescript/compiler_main.js
index 781550246..234ed6002 100644
--- a/deno_typescript/compiler_main.js
+++ b/deno_typescript/compiler_main.js
@@ -93,7 +93,7 @@ function decodeAscii(ui8) {
* @param {string} str
*/
function encode(str) {
- const charCodes = str.split("").map(c => c.charCodeAt(0));
+ const charCodes = str.split("").map((c) => c.charCodeAt(0));
const ui8 = new Uint8Array(charCodes);
return ui8;
}
@@ -185,7 +185,7 @@ class Host {
const { sourceCode } = dispatch("op_load_module", {
moduleUrl,
languageVersion,
- shouldCreateNewSourceFile
+ shouldCreateNewSourceFile,
});
const sourceFile = ts.createSourceFile(
@@ -260,10 +260,10 @@ class Host {
/** @type {string[]} */
const resolvedNames = dispatch("op_resolve_module_names", {
moduleNames,
- containingFile
+ containingFile,
});
/** @type {ts.ResolvedModule[]} */
- const r = resolvedNames.map(resolvedFileName => {
+ const r = resolvedNames.map((resolvedFileName) => {
const extension = getExtension(resolvedFileName);
if (!moduleMap.has(resolvedFileName)) {
// If we match the external specifier regex, we will then create an internal
@@ -299,7 +299,7 @@ function configure(configurationText) {
);
return {
options,
- diagnostics: errors.length ? errors : undefined
+ diagnostics: errors.length ? errors : undefined,
};
}
diff --git a/deno_typescript/system_loader.js b/deno_typescript/system_loader.js
index 41748c46e..b5b10af48 100644
--- a/deno_typescript/system_loader.js
+++ b/deno_typescript/system_loader.js
@@ -12,14 +12,14 @@ let System, __instantiateAsync, __instantiate;
System = {
register(id, d, f) {
r.set(id, { d, f, exp: {} });
- }
+ },
};
function gC(id, main) {
return {
id,
- import: async id => r.get(id)?.exp,
- meta: { url: id, main }
+ import: async (id) => r.get(id)?.exp,
+ meta: { url: id, main },
};
}
@@ -30,7 +30,7 @@ let System, __instantiateAsync, __instantiate;
Object.defineProperty(exp, id, {
value,
writable: true,
- enumerable: true
+ enumerable: true,
});
}
};
@@ -73,13 +73,13 @@ let System, __instantiateAsync, __instantiate;
return m.exp;
}
- __instantiateAsync = async m => {
+ __instantiateAsync = async (m) => {
System = __instantiateAsync = __instantiate = undefined;
rF(m);
return gExpA(m);
};
- __instantiate = m => {
+ __instantiate = (m) => {
System = __instantiateAsync = __instantiate = undefined;
rF(m);
return gExp(m);
diff --git a/std/archive/tar.ts b/std/archive/tar.ts
index 2680bcff2..cafef8723 100644
--- a/std/archive/tar.ts
+++ b/std/archive/tar.ts
@@ -104,68 +104,68 @@ struct posix_header { // byte offset
const ustarStructure: Array<{ field: string; length: number }> = [
{
field: "fileName",
- length: 100
+ length: 100,
},
{
field: "fileMode",
- length: 8
+ length: 8,
},
{
field: "uid",
- length: 8
+ length: 8,
},
{
field: "gid",
- length: 8
+ length: 8,
},
{
field: "fileSize",
- length: 12
+ length: 12,
},
{
field: "mtime",
- length: 12
+ length: 12,
},
{
field: "checksum",
- length: 8
+ length: 8,
},
{
field: "type",
- length: 1
+ length: 1,
},
{
field: "linkName",
- length: 100
+ length: 100,
},
{
field: "ustar",
- length: 8
+ length: 8,
},
{
field: "owner",
- length: 32
+ length: 32,
},
{
field: "group",
- length: 32
+ length: 32,
},
{
field: "majorNumber",
- length: 8
+ length: 8,
},
{
field: "minorNumber",
- length: 8
+ length: 8,
},
{
field: "fileNamePrefix",
- length: 155
+ length: 155,
},
{
field: "padding",
- length: 12
- }
+ length: 12,
+ },
];
/**
@@ -175,7 +175,7 @@ function formatHeader(data: TarData): Uint8Array {
const encoder = new TextEncoder(),
buffer = clean(512);
let offset = 0;
- ustarStructure.forEach(function(value): void {
+ ustarStructure.forEach(function (value): void {
const entry = encoder.encode(data[value.field as keyof TarData] || "");
buffer.set(entry, offset);
offset += value.length; // space it out with nulls
@@ -190,7 +190,7 @@ function formatHeader(data: TarData): Uint8Array {
function parseHeader(buffer: Uint8Array): { [key: string]: Uint8Array } {
const data: { [key: string]: Uint8Array } = {};
let offset = 0;
- ustarStructure.forEach(function(value): void {
+ ustarStructure.forEach(function (value): void {
const arr = buffer.subarray(offset, offset + value.length);
data[value.field] = arr;
offset += value.length;
@@ -350,7 +350,7 @@ export class Tar {
owner: opts.owner || "",
group: opts.group || "",
filePath: opts.filePath,
- reader: opts.reader
+ reader: opts.reader,
};
// calculate the checksum
@@ -358,7 +358,7 @@ export class Tar {
const encoder = new TextEncoder();
Object.keys(tarData)
.filter((key): boolean => ["filePath", "reader"].indexOf(key) < 0)
- .forEach(function(key): void {
+ .forEach(function (key): void {
checksum += encoder
.encode(tarData[key as keyof TarData])
.reduce((p, c): number => p + c, 0);
@@ -424,7 +424,7 @@ export class Untar {
decoder = new TextDecoder("ascii");
Object.keys(header)
.filter((key): boolean => key !== "checksum")
- .forEach(function(key): void {
+ .forEach(function (key): void {
checksum += header[key].reduce((p, c): number => p + c, 0);
});
checksum += encoder.encode(" ").reduce((p, c): number => p + c, 0);
@@ -440,7 +440,7 @@ export class Untar {
// get meta data
const meta: UntarOptions = {
- fileName: decoder.decode(trim(header.fileName))
+ fileName: decoder.decode(trim(header.fileName)),
};
const fileNamePrefix = trim(header.fileNamePrefix);
if (fileNamePrefix.byteLength > 0) {
diff --git a/std/archive/tar_test.ts b/std/archive/tar_test.ts
index 1bac623b0..ae3ee8138 100644
--- a/std/archive/tar_test.ts
+++ b/std/archive/tar_test.ts
@@ -23,7 +23,7 @@ Deno.test(async function createTarArchive(): Promise<void> {
const content = new TextEncoder().encode("hello tar world!");
await tar.append("output.txt", {
reader: new Deno.Buffer(content),
- contentSize: content.byteLength
+ contentSize: content.byteLength,
});
// put a file
@@ -49,7 +49,7 @@ Deno.test(async function deflateTarArchive(): Promise<void> {
const content = new TextEncoder().encode(text);
await tar.append(fileName, {
reader: new Deno.Buffer(content),
- contentSize: content.byteLength
+ contentSize: content.byteLength,
});
// read data from a tar archive
@@ -73,7 +73,7 @@ Deno.test(async function appendFileWithLongNameToTarArchive(): Promise<void> {
const content = new TextEncoder().encode(text);
await tar.append(fileName, {
reader: new Deno.Buffer(content),
- contentSize: content.byteLength
+ contentSize: content.byteLength,
});
// read data from a tar archive
diff --git a/std/bytes/test.ts b/std/bytes/test.ts
index 3ded0cd85..5efddf77f 100644
--- a/std/bytes/test.ts
+++ b/std/bytes/test.ts
@@ -6,7 +6,7 @@ import {
equal,
hasPrefix,
repeat,
- concat
+ concat,
} from "./mod.ts";
import { assertEquals, assertThrows, assert } from "../testing/asserts.ts";
import { encode, decode } from "../strings/mod.ts";
@@ -58,7 +58,7 @@ Deno.test("[bytes] repeat", () => {
["-", "", 0],
["-", "-", -1, "bytes: negative repeat count"],
["-", "----------", 10],
- ["abc ", "abc abc abc ", 3]
+ ["abc ", "abc abc abc ", 3],
];
for (const [input, output, count, errMsg] of repeatTestCase) {
if (errMsg) {
diff --git a/std/datetime/README.md b/std/datetime/README.md
index e3d935bc0..6c29f65e4 100644
--- a/std/datetime/README.md
+++ b/std/datetime/README.md
@@ -31,7 +31,7 @@ parseDateTime("16:34 01-20-2019", "hh:mm mm-dd-yyyy") // output : new Date(2019,
```ts
import {
dayOfYear,
- currentDayOfYear
+ currentDayOfYear,
} from "https://deno.land/std/datetime/mod.ts";
dayOfYear(new Date("2019-03-11T03:24:00")); // output: 70
diff --git a/std/datetime/mod.ts b/std/datetime/mod.ts
index 124f73911..036cd2cc5 100644
--- a/std/datetime/mod.ts
+++ b/std/datetime/mod.ts
@@ -145,7 +145,7 @@ export function toIMF(date: Date): string {
"Sep",
"Oct",
"Nov",
- "Dec"
+ "Dec",
];
return `${days[date.getUTCDay()]}, ${d} ${
months[date.getUTCMonth()]
diff --git a/std/datetime/test.ts b/std/datetime/test.ts
index 979fd34be..dc93095f4 100644
--- a/std/datetime/test.ts
+++ b/std/datetime/test.ts
@@ -82,7 +82,7 @@ Deno.test({
const actual = datetime.toIMF(new Date(Date.UTC(1994, 3, 5, 15, 32)));
const expected = "Tue, 05 Apr 1994 15:32:00 GMT";
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -91,5 +91,5 @@ Deno.test({
const actual = datetime.toIMF(new Date(0));
const expected = "Thu, 01 Jan 1970 00:00:00 GMT";
assertEquals(actual, expected);
- }
+ },
});
diff --git a/std/encoding/README.md b/std/encoding/README.md
index 2b2d416b1..e6604c605 100644
--- a/std/encoding/README.md
+++ b/std/encoding/README.md
@@ -39,7 +39,7 @@ const string = "a,b,c\nd,e,f";
console.log(
await parseCsv(string, {
- header: false
+ header: false,
})
);
// output:
@@ -161,9 +161,9 @@ import { stringify } from "./parser.ts";
const obj = {
bin: [
{ name: "deno", path: "cli/main.rs" },
- { name: "deno_core", path: "src/foo.rs" }
+ { name: "deno_core", path: "src/foo.rs" },
],
- nib: [{ name: "node", path: "not_found" }]
+ nib: [{ name: "node", path: "not_found" }],
};
const tomlString = stringify(obj);
```
diff --git a/std/encoding/base32_test.ts b/std/encoding/base32_test.ts
index 28550d57a..2bd7acea1 100644
--- a/std/encoding/base32_test.ts
+++ b/std/encoding/base32_test.ts
@@ -6,7 +6,7 @@ import { encode, decode } from "./base32.ts";
// Lifted from https://stackoverflow.com/questions/38987784
const fromHexString = (hexString: string): Uint8Array =>
- new Uint8Array(hexString.match(/.{1,2}/g)!.map(byte => parseInt(byte, 16)));
+ new Uint8Array(hexString.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)));
const toHexString = (bytes: Uint8Array): string =>
bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
@@ -34,56 +34,56 @@ const testCases = [
["ddf80ebe21bf1b1e12a64c5cc6a74b5d92dd", "3X4A5PRBX4NR4EVGJROMNJ2LLWJN2==="],
[
"c0cae52c6f641ce04a7ee5b9a8fa8ded121bca",
- "YDFOKLDPMQOOAST64W42R6UN5UJBXSQ="
+ "YDFOKLDPMQOOAST64W42R6UN5UJBXSQ=",
],
[
"872840a355c8c70586f462c9e669ee760cb3537e",
- "Q4UEBI2VZDDQLBXUMLE6M2POOYGLGU36"
+ "Q4UEBI2VZDDQLBXUMLE6M2POOYGLGU36",
],
[
"5773fe22662818a120c5688824c935fe018208a496",
- "K5Z74ITGFAMKCIGFNCECJSJV7YAYECFESY======"
+ "K5Z74ITGFAMKCIGFNCECJSJV7YAYECFESY======",
],
[
"416e23abc524d1b85736e2bea6cfecd5192789034a28",
- "IFXCHK6FETI3QVZW4K7KNT7M2UMSPCIDJIUA===="
+ "IFXCHK6FETI3QVZW4K7KNT7M2UMSPCIDJIUA====",
],
[
"83d2386ebdd7e8e818ec00e3ccd882aa933b905b7e2e44",
- "QPJDQ3V527UOQGHMADR4ZWECVKJTXEC3PYXEI==="
+ "QPJDQ3V527UOQGHMADR4ZWECVKJTXEC3PYXEI===",
],
[
"a2fa8b881f3b8024f52745763c4ae08ea12bdf8bef1a72f8",
- "UL5IXCA7HOACJ5JHIV3DYSXAR2QSXX4L54NHF6A="
+ "UL5IXCA7HOACJ5JHIV3DYSXAR2QSXX4L54NHF6A=",
],
[
"b074ae8b9efde0f17f37bccadde006d039997b59c8efb05add",
- "WB2K5C467XQPC7ZXXTFN3YAG2A4ZS62ZZDX3AWW5"
+ "WB2K5C467XQPC7ZXXTFN3YAG2A4ZS62ZZDX3AWW5",
],
[
"764fef941aee7e416dc204ae5ab9c5b9ce644567798e6849aea9",
- "OZH67FA25Z7EC3OCASXFVOOFXHHGIRLHPGHGQSNOVE======"
+ "OZH67FA25Z7EC3OCASXFVOOFXHHGIRLHPGHGQSNOVE======",
],
[
"4995d9811f37f59797d7c3b9b9e5325aa78277415f70f4accf588c",
- "JGK5TAI7G72ZPF6XYO43TZJSLKTYE52BL5YPJLGPLCGA===="
+ "JGK5TAI7G72ZPF6XYO43TZJSLKTYE52BL5YPJLGPLCGA====",
],
[
"24f0812ca8eed58374c11a7008f0b262698b72fd2792709208eaacb2",
- "ETYICLFI53KYG5GBDJYAR4FSMJUYW4X5E6JHBEQI5KWLE==="
+ "ETYICLFI53KYG5GBDJYAR4FSMJUYW4X5E6JHBEQI5KWLE===",
],
[
"d70692543810d4bf50d81cf44a55801a557a388a341367c7ea077ca306",
- "24DJEVBYCDKL6UGYDT2EUVMADJKXUOEKGQJWPR7KA56KGBQ="
+ "24DJEVBYCDKL6UGYDT2EUVMADJKXUOEKGQJWPR7KA56KGBQ=",
],
[
"6e08a89ca36b677ff8fe99e68a1241c8d8cef2570a5f60b6417d2538b30c",
- "NYEKRHFDNNTX76H6THTIUESBZDMM54SXBJPWBNSBPUSTRMYM"
+ "NYEKRHFDNNTX76H6THTIUESBZDMM54SXBJPWBNSBPUSTRMYM",
],
[
"f2fc2319bd29457ccd01e8e194ee9bd7e97298b6610df4ab0f3d5baa0b2d7ccf69829edb74edef",
- "6L6CGGN5FFCXZTIB5DQZJ3U327UXFGFWMEG7JKYPHVN2UCZNPTHWTAU63N2O33Y="
- ]
+ "6L6CGGN5FFCXZTIB5DQZJ3U327UXFGFWMEG7JKYPHVN2UCZNPTHWTAU63N2O33Y=",
+ ],
];
Deno.test({
@@ -92,7 +92,7 @@ Deno.test({
for (const [bin, b32] of testCases) {
assertEquals(encode(fromHexString(bin)), b32);
}
- }
+ },
});
Deno.test({
@@ -101,7 +101,7 @@ Deno.test({
for (const [bin, b32] of testCases) {
assertEquals(toHexString(decode(b32)), bin);
}
- }
+ },
});
Deno.test({
@@ -117,7 +117,7 @@ Deno.test({
errorCaught = true;
}
assert(errorCaught);
- }
+ },
});
Deno.test({
@@ -131,5 +131,5 @@ Deno.test({
errorCaught = true;
}
assert(errorCaught);
- }
+ },
});
diff --git a/std/encoding/binary.ts b/std/encoding/binary.ts
index 2eec9b4ab..cd338703b 100644
--- a/std/encoding/binary.ts
+++ b/std/encoding/binary.ts
@@ -34,7 +34,7 @@ const rawTypeSizes = {
int64: 8,
uint64: 8,
float32: 4,
- float64: 8
+ float64: 8,
};
/** Returns the number of bytes required to store the given data-type. */
diff --git a/std/encoding/binary_test.ts b/std/encoding/binary_test.ts
index 54f8cbded..084ca2fa4 100644
--- a/std/encoding/binary_test.ts
+++ b/std/encoding/binary_test.ts
@@ -11,7 +11,7 @@ import {
varbig,
varnum,
writeVarbig,
- writeVarnum
+ writeVarnum,
} from "./binary.ts";
Deno.test(async function testGetNBytes(): Promise<void> {
diff --git a/std/encoding/csv.ts b/std/encoding/csv.ts
index 12336b10d..c8c7719ca 100644
--- a/std/encoding/csv.ts
+++ b/std/encoding/csv.ts
@@ -118,7 +118,7 @@ export async function readMatrix(
opt: ReadOptions = {
comma: ",",
trimLeadingSpace: false,
- lazyQuotes: false
+ lazyQuotes: false,
}
): Promise<string[][]> {
const result: string[][] = [];
@@ -195,7 +195,7 @@ export interface ParseOptions extends ReadOptions {
export async function parse(
input: string | BufReader,
opt: ParseOptions = {
- header: false
+ header: false,
}
): Promise<unknown[]> {
let r: string[][];
@@ -215,7 +215,7 @@ export async function parse(
headers = h.map(
(e): HeaderOptions => {
return {
- name: e
+ name: e,
};
}
);
@@ -226,7 +226,7 @@ export async function parse(
headers = head.map(
(e): HeaderOptions => {
return {
- name: e
+ name: e,
};
}
);
diff --git a/std/encoding/csv_test.ts b/std/encoding/csv_test.ts
index 74ad00c72..cb61de433 100644
--- a/std/encoding/csv_test.ts
+++ b/std/encoding/csv_test.ts
@@ -14,20 +14,20 @@ const testCases = [
{
Name: "Simple",
Input: "a,b,c\n",
- Output: [["a", "b", "c"]]
+ Output: [["a", "b", "c"]],
},
{
Name: "CRLF",
Input: "a,b\r\nc,d\r\n",
Output: [
["a", "b"],
- ["c", "d"]
- ]
+ ["c", "d"],
+ ],
},
{
Name: "BareCR",
Input: "a,b\rc,d\r\n",
- Output: [["a", "b\rc", "d"]]
+ Output: [["a", "b\rc", "d"]],
},
{
Name: "RFC4180test",
@@ -41,20 +41,20 @@ zzz,yyy,xxx`,
["#field1", "field2", "field3"],
["aaa", "bbb", "ccc"],
["a,a", `bbb`, "ccc"],
- ["zzz", "yyy", "xxx"]
+ ["zzz", "yyy", "xxx"],
],
- ignore: true
+ ignore: true,
},
{
Name: "NoEOLTest",
Input: "a,b,c",
- Output: [["a", "b", "c"]]
+ Output: [["a", "b", "c"]],
},
{
Name: "Semicolon",
Input: "a;b;c\n",
Output: [["a", "b", "c"]],
- Comma: ";"
+ Comma: ";",
},
{
Name: "MultiLine",
@@ -63,103 +63,103 @@ line","one line","three
line
field"`,
Output: [["two\nline"], ["one line"], ["three\nline\nfield"]],
- ignore: true
+ ignore: true,
},
{
Name: "BlankLine",
Input: "a,b,c\n\nd,e,f\n\n",
Output: [
["a", "b", "c"],
- ["d", "e", "f"]
- ]
+ ["d", "e", "f"],
+ ],
},
{
Name: "BlankLineFieldCount",
Input: "a,b,c\n\nd,e,f\n\n",
Output: [
["a", "b", "c"],
- ["d", "e", "f"]
+ ["d", "e", "f"],
],
UseFieldsPerRecord: true,
- FieldsPerRecord: 0
+ FieldsPerRecord: 0,
},
{
Name: "TrimSpace",
Input: " a, b, c\n",
Output: [["a", "b", "c"]],
- TrimLeadingSpace: true
+ TrimLeadingSpace: true,
},
{
Name: "LeadingSpace",
Input: " a, b, c\n",
- Output: [[" a", " b", " c"]]
+ Output: [[" a", " b", " c"]],
},
{
Name: "Comment",
Input: "#1,2,3\na,b,c\n#comment",
Output: [["a", "b", "c"]],
- Comment: "#"
+ Comment: "#",
},
{
Name: "NoComment",
Input: "#1,2,3\na,b,c",
Output: [
["#1", "2", "3"],
- ["a", "b", "c"]
- ]
+ ["a", "b", "c"],
+ ],
},
{
Name: "LazyQuotes",
Input: `a "word","1"2",a","b`,
Output: [[`a "word"`, `1"2`, `a"`, `b`]],
- LazyQuotes: true
+ LazyQuotes: true,
},
{
Name: "BareQuotes",
Input: `a "word","1"2",a"`,
Output: [[`a "word"`, `1"2`, `a"`]],
- LazyQuotes: true
+ LazyQuotes: true,
},
{
Name: "BareDoubleQuotes",
Input: `a""b,c`,
Output: [[`a""b`, `c`]],
- LazyQuotes: true
+ LazyQuotes: true,
},
{
Name: "BadDoubleQuotes",
Input: `a""b,c`,
- Error: ErrBareQuote
+ Error: ErrBareQuote,
// Error: &ParseError{StartLine: 1, Line: 1, Column: 1, Err: ErrBareQuote},
},
{
Name: "TrimQuote",
Input: ` "a"," b",c`,
Output: [["a", " b", "c"]],
- TrimLeadingSpace: true
+ TrimLeadingSpace: true,
},
{
Name: "BadBareQuote",
Input: `a "word","b"`,
- Error: ErrBareQuote
+ Error: ErrBareQuote,
// &ParseError{StartLine: 1, Line: 1, Column: 2, Err: ErrBareQuote}
},
{
Name: "BadTrailingQuote",
Input: `"a word",b"`,
- Error: ErrBareQuote
+ Error: ErrBareQuote,
},
{
Name: "ExtraneousQuote",
Input: `"a "word","b"`,
- Error: ErrBareQuote
+ Error: ErrBareQuote,
},
{
Name: "BadFieldCount",
Input: "a,b,c\nd,e",
Error: ErrFieldCount,
UseFieldsPerRecord: true,
- FieldsPerRecord: 0
+ FieldsPerRecord: 0,
},
{
Name: "BadFieldCount1",
@@ -167,37 +167,37 @@ field"`,
// Error: &ParseError{StartLine: 1, Line: 1, Err: ErrFieldCount},
UseFieldsPerRecord: true,
FieldsPerRecord: 2,
- Error: ErrFieldCount
+ Error: ErrFieldCount,
},
{
Name: "FieldCount",
Input: "a,b,c\nd,e",
Output: [
["a", "b", "c"],
- ["d", "e"]
- ]
+ ["d", "e"],
+ ],
},
{
Name: "TrailingCommaEOF",
Input: "a,b,c,",
- Output: [["a", "b", "c", ""]]
+ Output: [["a", "b", "c", ""]],
},
{
Name: "TrailingCommaEOL",
Input: "a,b,c,\n",
- Output: [["a", "b", "c", ""]]
+ Output: [["a", "b", "c", ""]],
},
{
Name: "TrailingCommaSpaceEOF",
Input: "a,b,c, ",
Output: [["a", "b", "c", ""]],
- TrimLeadingSpace: true
+ TrimLeadingSpace: true,
},
{
Name: "TrailingCommaSpaceEOL",
Input: "a,b,c, \n",
Output: [["a", "b", "c", ""]],
- TrimLeadingSpace: true
+ TrimLeadingSpace: true,
},
{
Name: "TrailingCommaLine3",
@@ -205,14 +205,14 @@ field"`,
Output: [
["a", "b", "c"],
["d", "e", "f"],
- ["g", "hi", ""]
+ ["g", "hi", ""],
],
- TrimLeadingSpace: true
+ TrimLeadingSpace: true,
},
{
Name: "NotTrailingComma3",
Input: "a,b,c, \n",
- Output: [["a", "b", "c", " "]]
+ Output: [["a", "b", "c", " "]],
},
{
Name: "CommaFieldTest",
@@ -237,98 +237,98 @@ x,,,
["x", "y", "z", ""],
["x", "y", "", ""],
["x", "", "", ""],
- ["", "", "", ""]
- ]
+ ["", "", "", ""],
+ ],
},
{
Name: "TrailingCommaIneffective1",
Input: "a,b,\nc,d,e",
Output: [
["a", "b", ""],
- ["c", "d", "e"]
+ ["c", "d", "e"],
],
- TrimLeadingSpace: true
+ TrimLeadingSpace: true,
},
{
Name: "ReadAllReuseRecord",
Input: "a,b\nc,d",
Output: [
["a", "b"],
- ["c", "d"]
+ ["c", "d"],
],
- ReuseRecord: true
+ ReuseRecord: true,
},
{
Name: "StartLine1", // Issue 19019
Input: 'a,"b\nc"d,e',
Error: true,
// Error: &ParseError{StartLine: 1, Line: 2, Column: 1, Err: ErrQuote},
- ignore: true
+ ignore: true,
},
{
Name: "StartLine2",
Input: 'a,b\n"d\n\n,e',
Error: true,
// Error: &ParseError{StartLine: 2, Line: 5, Column: 0, Err: ErrQuote},
- ignore: true
+ ignore: true,
},
{
Name: "CRLFInQuotedField", // Issue 21201
Input: 'A,"Hello\r\nHi",B\r\n',
Output: [["A", "Hello\nHi", "B"]],
- ignore: true
+ ignore: true,
},
{
Name: "BinaryBlobField", // Issue 19410
Input: "x09\x41\xb4\x1c,aktau",
- Output: [["x09A\xb4\x1c", "aktau"]]
+ Output: [["x09A\xb4\x1c", "aktau"]],
},
{
Name: "TrailingCR",
Input: "field1,field2\r",
Output: [["field1", "field2"]],
- ignore: true
+ ignore: true,
},
{
Name: "QuotedTrailingCR",
Input: '"field"\r',
Output: [['"field"']],
- ignore: true
+ ignore: true,
},
{
Name: "QuotedTrailingCRCR",
Input: '"field"\r\r',
Error: true,
// Error: &ParseError{StartLine: 1, Line: 1, Column: 6, Err: ErrQuote},
- ignore: true
+ ignore: true,
},
{
Name: "FieldCR",
Input: "field\rfield\r",
Output: [["field\rfield"]],
- ignore: true
+ ignore: true,
},
{
Name: "FieldCRCR",
Input: "field\r\rfield\r\r",
Output: [["field\r\rfield\r"]],
- ignore: true
+ ignore: true,
},
{
Name: "FieldCRCRLF",
Input: "field\r\r\nfield\r\r\n",
- Output: [["field\r"], ["field\r"]]
+ Output: [["field\r"], ["field\r"]],
},
{
Name: "FieldCRCRLFCR",
Input: "field\r\r\n\rfield\r\r\n\r",
- Output: [["field\r"], ["\rfield\r"]]
+ Output: [["field\r"], ["\rfield\r"]],
},
{
Name: "FieldCRCRLFCRCR",
Input: "field\r\r\n\r\rfield\r\r\n\r\r",
Output: [["field\r"], ["\r\rfield\r"], ["\r"]],
- ignore: true
+ ignore: true,
},
{
Name: "MultiFieldCRCRLFCRCR",
@@ -336,9 +336,9 @@ x,,,
Output: [
["field1", "field2\r"],
["\r\rfield1", "field2\r"],
- ["\r\r", ""]
+ ["\r\r", ""],
],
- ignore: true
+ ignore: true,
},
{
Name: "NonASCIICommaAndComment",
@@ -346,14 +346,14 @@ x,,,
Output: [["a", "b,c", "d,e"]],
TrimLeadingSpace: true,
Comma: "£",
- Comment: "€"
+ Comment: "€",
},
{
Name: "NonASCIICommaAndCommentWithQuotes",
Input: 'a€" b,"€ c\nλ comment\n',
Output: [["a", " b,", " c"]],
Comma: "€",
- Comment: "λ"
+ Comment: "λ",
},
{
// λ and θ start with the same byte.
@@ -362,24 +362,24 @@ x,,,
Input: '"abθcd"λefθgh',
Output: [["abθcd", "efθgh"]],
Comma: "λ",
- Comment: "€"
+ Comment: "€",
},
{
Name: "NonASCIICommentConfusion",
Input: "λ\nλ\nθ\nλ\n",
Output: [["λ"], ["λ"], ["λ"]],
- Comment: "θ"
+ Comment: "θ",
},
{
Name: "QuotedFieldMultipleLF",
Input: '"\n\n\n\n"',
Output: [["\n\n\n\n"]],
- ignore: true
+ ignore: true,
},
{
Name: "MultipleCRLF",
Input: "\r\n\r\n\r\n\r\n",
- ignore: true
+ ignore: true,
},
/**
* The implementation may read each line in several chunks if
@@ -392,77 +392,77 @@ x,,,
"#ignore\n".repeat(10000) + "@".repeat(5000) + "," + "*".repeat(5000),
Output: [["@".repeat(5000), "*".repeat(5000)]],
Comment: "#",
- ignore: true
+ ignore: true,
},
{
Name: "QuoteWithTrailingCRLF",
Input: '"foo"bar"\r\n',
- Error: ErrBareQuote
+ Error: ErrBareQuote,
// Error: &ParseError{StartLine: 1, Line: 1, Column: 4, Err: ErrQuote},
},
{
Name: "LazyQuoteWithTrailingCRLF",
Input: '"foo"bar"\r\n',
Output: [[`foo"bar`]],
- LazyQuotes: true
+ LazyQuotes: true,
},
{
Name: "DoubleQuoteWithTrailingCRLF",
Input: '"foo""bar"\r\n',
Output: [[`foo"bar`]],
- ignore: true
+ ignore: true,
},
{
Name: "EvenQuotes",
Input: `""""""""`,
Output: [[`"""`]],
- ignore: true
+ ignore: true,
},
{
Name: "OddQuotes",
Input: `"""""""`,
Error: true,
// Error:" &ParseError{StartLine: 1, Line: 1, Column: 7, Err: ErrQuote}",
- ignore: true
+ ignore: true,
},
{
Name: "LazyOddQuotes",
Input: `"""""""`,
Output: [[`"""`]],
LazyQuotes: true,
- ignore: true
+ ignore: true,
},
{
Name: "BadComma1",
Comma: "\n",
- Error: ErrInvalidDelim
+ Error: ErrInvalidDelim,
},
{
Name: "BadComma2",
Comma: "\r",
- Error: ErrInvalidDelim
+ Error: ErrInvalidDelim,
},
{
Name: "BadComma3",
Comma: '"',
- Error: ErrInvalidDelim
+ Error: ErrInvalidDelim,
},
{
Name: "BadComment1",
Comment: "\n",
- Error: ErrInvalidDelim
+ Error: ErrInvalidDelim,
},
{
Name: "BadComment2",
Comment: "\r",
- Error: ErrInvalidDelim
+ Error: ErrInvalidDelim,
},
{
Name: "BadCommaComment",
Comma: "X",
Comment: "X",
- Error: ErrInvalidDelim
- }
+ Error: ErrInvalidDelim,
+ },
];
for (const t of testCases) {
Deno.test({
@@ -500,7 +500,7 @@ for (const t of testCases) {
comment: comment,
trimLeadingSpace: trim,
fieldsPerRecord: fieldsPerRec,
- lazyQuotes: lazyquote
+ lazyQuotes: lazyquote,
}
);
} catch (e) {
@@ -516,13 +516,13 @@ for (const t of testCases) {
comment: comment,
trimLeadingSpace: trim,
fieldsPerRecord: fieldsPerRec,
- lazyQuotes: lazyquote
+ lazyQuotes: lazyquote,
}
);
const expected = t.Output;
assertEquals(actual, expected);
}
- }
+ },
});
}
@@ -531,13 +531,13 @@ const parseTestCases = [
name: "simple",
in: "a,b,c",
header: false,
- result: [["a", "b", "c"]]
+ result: [["a", "b", "c"]],
},
{
name: "simple Bufreader",
in: new BufReader(new StringReader("a,b,c")),
header: false,
- result: [["a", "b", "c"]]
+ result: [["a", "b", "c"]],
},
{
name: "multiline",
@@ -545,14 +545,14 @@ const parseTestCases = [
header: false,
result: [
["a", "b", "c"],
- ["e", "f", "g"]
- ]
+ ["e", "f", "g"],
+ ],
},
{
name: "header mapping boolean",
in: "a,b,c\ne,f,g\n",
header: true,
- result: [{ a: "e", b: "f", c: "g" }]
+ result: [{ a: "e", b: "f", c: "g" }],
},
{
name: "header mapping array",
@@ -560,8 +560,8 @@ const parseTestCases = [
header: ["this", "is", "sparta"],
result: [
{ this: "a", is: "b", sparta: "c" },
- { this: "e", is: "f", sparta: "g" }
- ]
+ { this: "e", is: "f", sparta: "g" },
+ ],
},
{
name: "header mapping object",
@@ -569,8 +569,8 @@ const parseTestCases = [
header: [{ name: "this" }, { name: "is" }, { name: "sparta" }],
result: [
{ this: "a", is: "b", sparta: "c" },
- { this: "e", is: "f", sparta: "g" }
- ]
+ { this: "e", is: "f", sparta: "g" },
+ ],
},
{
name: "header mapping parse entry",
@@ -580,25 +580,25 @@ const parseTestCases = [
name: "this",
parse: (e: string): string => {
return `b${e}$$`;
- }
+ },
},
{
name: "is",
parse: (e: string): number => {
return e.length;
- }
+ },
},
{
name: "sparta",
parse: (e: string): unknown => {
return { bim: `boom-${e}` };
- }
- }
+ },
+ },
],
result: [
{ this: "ba$$", is: 1, sparta: { bim: `boom-c` } },
- { this: "be$$", is: 1, sparta: { bim: `boom-g` } }
- ]
+ { this: "be$$", is: 1, sparta: { bim: `boom-g` } },
+ ],
},
{
name: "multiline parse",
@@ -609,8 +609,8 @@ const parseTestCases = [
header: false,
result: [
{ super: "a", street: "b", fighter: "c" },
- { super: "e", street: "f", fighter: "g" }
- ]
+ { super: "e", street: "f", fighter: "g" },
+ ],
},
{
name: "header mapping object parseline",
@@ -621,9 +621,9 @@ const parseTestCases = [
},
result: [
{ super: "a", street: "b", fighter: "c" },
- { super: "e", street: "f", fighter: "g" }
- ]
- }
+ { super: "e", street: "f", fighter: "g" },
+ ],
+ },
];
for (const testCase of parseTestCases) {
@@ -632,9 +632,9 @@ for (const testCase of parseTestCases) {
async fn(): Promise<void> {
const r = await parse(testCase.in, {
header: testCase.header,
- parse: testCase.parse as (input: unknown) => unknown
+ parse: testCase.parse as (input: unknown) => unknown,
});
assertEquals(r, testCase.result);
- }
+ },
});
}
diff --git a/std/encoding/hex_test.ts b/std/encoding/hex_test.ts
index f98fe5422..56bdbf4f0 100644
--- a/std/encoding/hex_test.ts
+++ b/std/encoding/hex_test.ts
@@ -14,7 +14,7 @@ import {
decode,
decodeString,
errLength,
- errInvalidByte
+ errInvalidByte,
} from "./hex.ts";
function toByte(s: string): number {
@@ -29,7 +29,7 @@ const testCases = [
["f0f1f2f3f4f5f6f7", [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7]],
["f8f9fafbfcfdfeff", [0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]],
["67", Array.from(new TextEncoder().encode("g"))],
- ["e3a1", [0xe3, 0xa1]]
+ ["e3a1", [0xe3, 0xa1]],
];
const errCases = [
@@ -42,7 +42,7 @@ const errCases = [
["0g", "", errInvalidByte(new TextEncoder().encode("g")[0])],
["00gg", "\x00", errInvalidByte(new TextEncoder().encode("g")[0])],
["0\x01", "", errInvalidByte(new TextEncoder().encode("\x01")[0])],
- ["ffeed", "\xff\xee", errLength()]
+ ["ffeed", "\xff\xee", errLength()],
];
Deno.test({
@@ -53,7 +53,7 @@ Deno.test({
assertEquals(encodedLen(2), 4);
assertEquals(encodedLen(3), 6);
assertEquals(encodedLen(4), 8);
- }
+ },
});
Deno.test({
@@ -88,7 +88,7 @@ Deno.test({
assertEquals(dest.length, n);
assertEquals(new TextDecoder().decode(dest), enc);
}
- }
+ },
});
Deno.test({
@@ -97,7 +97,7 @@ Deno.test({
for (const [enc, dec] of testCases) {
assertEquals(encodeToString(new Uint8Array(dec as number[])), enc);
}
- }
+ },
});
Deno.test({
@@ -108,7 +108,7 @@ Deno.test({
assertEquals(decodedLen(4), 2);
assertEquals(decodedLen(6), 3);
assertEquals(decodedLen(8), 4);
- }
+ },
});
Deno.test({
@@ -117,7 +117,7 @@ Deno.test({
// Case for decoding uppercase hex characters, since
// Encode always uses lowercase.
const extraTestcase = [
- ["F8F9FAFBFCFDFEFF", [0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]]
+ ["F8F9FAFBFCFDFEFF", [0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]],
];
const cases = testCases.concat(extraTestcase);
@@ -129,7 +129,7 @@ Deno.test({
assertEquals(err, undefined);
assertEquals(Array.from(dest), Array.from(dec as number[]));
}
- }
+ },
});
Deno.test({
@@ -140,7 +140,7 @@ Deno.test({
assertEquals(dec, Array.from(dst));
}
- }
+ },
});
Deno.test({
@@ -155,7 +155,7 @@ Deno.test({
);
assertEquals(err, expectedErr);
}
- }
+ },
});
Deno.test({
@@ -175,5 +175,5 @@ Deno.test({
assertEquals(new TextDecoder("ascii").decode(out), output as string);
}
}
- }
+ },
});
diff --git a/std/encoding/mod.ts b/std/encoding/mod.ts
index d63cf47f3..eaa28ae27 100644
--- a/std/encoding/mod.ts
+++ b/std/encoding/mod.ts
@@ -2,13 +2,13 @@ export {
HeaderOptions as CsvHeaderOptions,
ParseError as CsvParseError,
ParseOptions as ParseCsvOptions,
- parse as parseCsv
+ parse as parseCsv,
} from "./csv.ts";
export {
decode as decodeHex,
decodeString as decodeHexString,
encode as encodeToHex,
- encodeToString as encodeToHexString
+ encodeToString as encodeToHexString,
} from "./hex.ts";
export { parse as parseToml, stringify as tomlStringify } from "./toml.ts";
export { parse as parseYaml, stringify as yamlStringify } from "./yaml.ts";
diff --git a/std/encoding/toml_test.ts b/std/encoding/toml_test.ts
index 425b8a22c..d272a29ff 100644
--- a/std/encoding/toml_test.ts
+++ b/std/encoding/toml_test.ts
@@ -29,12 +29,12 @@ Deno.test({
str6: "The quick brown\nfox jumps over\nthe lazy dog.",
lines:
"The first newline is\ntrimmed in raw strings.\n All other " +
- "whitespace\n is preserved."
- }
+ "whitespace\n is preserved.",
+ },
};
const actual = parseFile(path.join(testFilesDir, "string.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -43,7 +43,7 @@ Deno.test({
const expected = { boolean: { bool1: true, bool2: false } };
const actual = parseFile(path.join(testFilesDir, "CRLF.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -52,7 +52,7 @@ Deno.test({
const expected = { boolean: { bool1: true, bool2: false } };
const actual = parseFile(path.join(testFilesDir, "boolean.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -72,12 +72,12 @@ Deno.test({
hex3: "0xdead_beef",
oct1: "0o01234567",
oct2: "0o755",
- bin1: "0b11010110"
- }
+ bin1: "0b11010110",
+ },
};
const actual = parseFile(path.join(testFilesDir, "integer.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -98,12 +98,12 @@ Deno.test({
sf3: -Infinity,
sf4: NaN,
sf5: NaN,
- sf6: NaN
- }
+ sf6: NaN,
+ },
};
const actual = parseFile(path.join(testFilesDir, "float.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -113,14 +113,14 @@ Deno.test({
arrays: {
data: [
["gamma", "delta"],
- [1, 2]
+ [1, 2],
],
- hosts: ["alpha", "omega"]
- }
+ hosts: ["alpha", "omega"],
+ },
};
const actual = parseFile(path.join(testFilesDir, "arrays.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -133,27 +133,27 @@ Deno.test({
in: {
the: {
toml: {
- name: "Tom Preston-Werner"
- }
- }
- }
- }
- }
+ name: "Tom Preston-Werner",
+ },
+ },
+ },
+ },
+ },
},
servers: {
alpha: {
ip: "10.0.0.1",
- dc: "eqdc10"
+ dc: "eqdc10",
},
beta: {
ip: "10.0.0.2",
- dc: "eqdc20"
- }
- }
+ dc: "eqdc20",
+ },
+ },
};
const actual = parseFile(path.join(testFilesDir, "table.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -164,11 +164,11 @@ Deno.test({
not: "[node]",
regex: "<ic*s*>",
NANI: "何?!",
- comment: "Comment inside # the comment"
+ comment: "Comment inside # the comment",
};
const actual = parseFile(path.join(testFilesDir, "simple.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -182,12 +182,12 @@ Deno.test({
odt4: new Date("1979-05-27 07:32:00Z"),
ld1: new Date("1979-05-27"),
lt1: "07:32:00",
- lt2: "00:32:00.999999"
- }
+ lt2: "00:32:00.999999",
+ },
};
const actual = parseFile(path.join(testFilesDir, "datetime.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -200,39 +200,39 @@ Deno.test({
malevolant: {
creation: {
drum: {
- kit: "Tama"
- }
- }
- }
+ kit: "Tama",
+ },
+ },
+ },
},
derek: {
- roddy: "drummer"
- }
+ roddy: "drummer",
+ },
},
name: {
first: "Tom",
- last: "Preston-Werner"
+ last: "Preston-Werner",
},
point: {
x: 1,
- y: 2
+ y: 2,
},
dog: {
type: {
- name: "pug"
- }
+ name: "pug",
+ },
},
"tosin.abasi": "guitarist",
animal: {
as: {
- leaders: "tosin"
- }
- }
- }
+ leaders: "tosin",
+ },
+ },
+ },
};
const actual = parseFile(path.join(testFilesDir, "inlineTable.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -241,13 +241,13 @@ Deno.test({
const expected = {
bin: [
{ name: "deno", path: "cli/main.rs" },
- { name: "deno_core", path: "src/foo.rs" }
+ { name: "deno_core", path: "src/foo.rs" },
],
- nib: [{ name: "node", path: "not_found" }]
+ nib: [{ name: "node", path: "not_found" }],
};
const actual = parseFile(path.join(testFilesDir, "arrayTable.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -286,14 +286,14 @@ Deno.test({
"tokio-io": "0.1.11",
"tokio-process": "0.2.3",
"tokio-threadpool": "0.1.11",
- url: "1.7.2"
+ url: "1.7.2",
},
- target: { "cfg(windows)": { dependencies: { winapi: "0.3.6" } } }
+ target: { "cfg(windows)": { dependencies: { winapi: "0.3.6" } } },
};
/* eslint-enable @typescript-eslint/camelcase */
const actual = parseFile(path.join(testFilesDir, "cargo.toml"));
assertEquals(actual, expected);
- }
+ },
});
Deno.test({
@@ -303,15 +303,15 @@ Deno.test({
foo: { bar: "deno" },
this: { is: { nested: "denonono" } },
"https://deno.land/std": {
- $: "doller"
+ $: "doller",
},
"##": {
deno: {
"https://deno.land": {
proto: "https",
- ":80": "port"
- }
- }
+ ":80": "port",
+ },
+ },
},
arrayObjects: [{ stuff: "in" }, {}, { the: "array" }],
deno: "is",
@@ -347,9 +347,9 @@ Deno.test({
sf6: NaN,
data: [
["gamma", "delta"],
- [1, 2]
+ [1, 2],
],
- hosts: ["alpha", "omega"]
+ hosts: ["alpha", "omega"],
};
const expected = `deno = "is"
not = "[node]"
@@ -408,5 +408,5 @@ the = "array"
`;
const actual = stringify(src);
assertEquals(actual, expected);
- }
+ },
});
diff --git a/std/encoding/yaml.ts b/std/encoding/yaml.ts
index a8784319b..76b1b8379 100644
--- a/std/encoding/yaml.ts
+++ b/std/encoding/yaml.ts
@@ -6,6 +6,6 @@
export { ParseOptions, parse, parseAll } from "./yaml/parse.ts";
export {
DumpOptions as StringifyOptions,
- stringify
+ stringify,
} from "./yaml/stringify.ts";
export * from "./yaml/schema/mod.ts";
diff --git a/std/encoding/yaml/dumper/dumper.ts b/std/encoding/yaml/dumper/dumper.ts
index 3a34e14cc..1280ee757 100644
--- a/std/encoding/yaml/dumper/dumper.ts
+++ b/std/encoding/yaml/dumper/dumper.ts
@@ -73,7 +73,7 @@ const DEPRECATED_BOOLEANS_SYNTAX = [
"NO",
"off",
"Off",
- "OFF"
+ "OFF",
];
function encodeHex(character: number): string {
diff --git a/std/encoding/yaml/dumper/dumper_state.ts b/std/encoding/yaml/dumper/dumper_state.ts
index 88164a0d2..94cd84878 100644
--- a/std/encoding/yaml/dumper/dumper_state.ts
+++ b/std/encoding/yaml/dumper/dumper_state.ts
@@ -121,7 +121,7 @@ export class DumperState extends State {
lineWidth = 80,
noRefs = false,
noCompatMode = false,
- condenseFlow = false
+ condenseFlow = false,
}: DumperStateOptions) {
super(schema);
this.indent = Math.max(1, indent);
diff --git a/std/encoding/yaml/example/dump.ts b/std/encoding/yaml/example/dump.ts
index 746c3be01..db3647274 100644
--- a/std/encoding/yaml/example/dump.ts
+++ b/std/encoding/yaml/example/dump.ts
@@ -10,13 +10,13 @@ console.log(
"a",
"b",
{
- a: false
+ a: false,
},
{
- a: false
- }
- ]
+ a: false,
+ },
+ ],
},
- test: "foobar"
+ test: "foobar",
})
);
diff --git a/std/encoding/yaml/example/inout.ts b/std/encoding/yaml/example/inout.ts
index 80cad8258..b0b47e3fe 100644
--- a/std/encoding/yaml/example/inout.ts
+++ b/std/encoding/yaml/example/inout.ts
@@ -9,14 +9,14 @@ const test = {
"a",
"b",
{
- a: false
+ a: false,
},
{
- a: false
- }
- ]
+ a: false,
+ },
+ ],
},
- test: "foobar"
+ test: "foobar",
};
const string = stringify(test);
diff --git a/std/encoding/yaml/loader/loader.ts b/std/encoding/yaml/loader/loader.ts
index 1ab4fc7f5..f0d535624 100644
--- a/std/encoding/yaml/loader/loader.ts
+++ b/std/encoding/yaml/loader/loader.ts
@@ -37,11 +37,11 @@ function _class(obj: unknown): string {
}
function isEOL(c: number): boolean {
- return c === 0x0a /* LF */ || c === 0x0d /* CR */;
+ return c === 0x0a || /* LF */ c === 0x0d /* CR */;
}
function isWhiteSpace(c: number): boolean {
- return c === 0x09 /* Tab */ || c === 0x20 /* Space */;
+ return c === 0x09 || /* Tab */ c === 0x20 /* Space */;
}
function isWsOrEol(c: number): boolean {
@@ -64,13 +64,13 @@ function isFlowIndicator(c: number): boolean {
}
function fromHexCode(c: number): number {
- if (0x30 /* 0 */ <= c && c <= 0x39 /* 9 */) {
+ if (0x30 <= /* 0 */ c && c <= 0x39 /* 9 */) {
return c - 0x30;
}
const lc = c | 0x20;
- if (0x61 /* a */ <= lc && lc <= 0x66 /* f */) {
+ if (0x61 <= /* a */ lc && lc <= 0x66 /* f */) {
return lc - 0x61 + 10;
}
@@ -91,7 +91,7 @@ function escapedHexLen(c: number): number {
}
function fromDecimalCode(c: number): number {
- if (0x30 /* 0 */ <= c && c <= 0x39 /* 9 */) {
+ if (0x30 <= /* 0 */ c && c <= 0x39 /* 9 */) {
return c - 0x30;
}
@@ -251,7 +251,7 @@ const directiveHandlers: DirectiveHandlers = {
state.tagMap = {};
}
state.tagMap[handle] = prefix;
- }
+ },
};
function captureSegment(
@@ -414,7 +414,7 @@ function skipSeparationSpace(
if (allowComments && ch === 0x23 /* # */) {
do {
ch = state.input.charCodeAt(++state.position);
- } while (ch !== 0x0a /* LF */ && ch !== 0x0d /* CR */ && ch !== 0);
+ } while (ch !== 0x0a && /* LF */ ch !== 0x0d && /* CR */ ch !== 0);
}
if (isEOL(ch)) {
@@ -451,7 +451,7 @@ function testDocumentSeparator(state: LoaderState): boolean {
// Condition state.position === state.lineStart is tested
// in parent on each call, for efficiency. No needs to test here again.
if (
- (ch === 0x2d /* - */ || ch === 0x2e) /* . */ &&
+ (ch === 0x2d || /* - */ ch === 0x2e) /* . */ &&
ch === state.input.charCodeAt(_position + 1) &&
ch === state.input.charCodeAt(_position + 2)
) {
@@ -503,7 +503,7 @@ function readPlainScalar(
}
let following: number;
- if (ch === 0x3f /* ? */ || ch === 0x2d /* - */) {
+ if (ch === 0x3f || /* ? */ ch === 0x2d /* - */) {
following = state.input.charCodeAt(state.position + 1);
if (
@@ -869,7 +869,7 @@ function readBlockScalar(state: LoaderState, nodeIndent: number): boolean {
while (ch !== 0) {
ch = state.input.charCodeAt(++state.position);
- if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
+ if (ch === 0x2b || /* + */ ch === 0x2d /* - */) {
if (CHOMPING_CLIP === chomping) {
chomping = ch === 0x2b /* + */ ? CHOMPING_KEEP : CHOMPING_STRIP;
} else {
@@ -1103,7 +1103,7 @@ function readBlockMapping(
// Explicit notation case. There are two separate blocks:
// first for the key (denoted by "?") and second for the value (denoted by ":")
//
- if ((ch === 0x3f /* ? */ || ch === 0x3a) /* : */ && isWsOrEol(following)) {
+ if ((ch === 0x3f || /* ? */ ch === 0x3a) && /* : */ isWsOrEol(following)) {
if (ch === 0x3f /* ? */) {
if (atExplicitKey) {
storeMappingPair(
diff --git a/std/encoding/yaml/loader/loader_state.ts b/std/encoding/yaml/loader/loader_state.ts
index 1e136025c..ca50fcaf1 100644
--- a/std/encoding/yaml/loader/loader_state.ts
+++ b/std/encoding/yaml/loader/loader_state.ts
@@ -56,7 +56,7 @@ export class LoaderState extends State {
onWarning,
legacy = false,
json = false,
- listener = null
+ listener = null,
}: LoaderStateOptions
) {
super(schema);
diff --git a/std/encoding/yaml/parse_test.ts b/std/encoding/yaml/parse_test.ts
index bdcd8db62..21f1b893b 100644
--- a/std/encoding/yaml/parse_test.ts
+++ b/std/encoding/yaml/parse_test.ts
@@ -20,7 +20,7 @@ Deno.test({
const expected = { test: "toto", foo: { bar: true, baz: 1, qux: null } };
assertEquals(parse(yaml), expected);
- }
+ },
});
Deno.test({
@@ -40,17 +40,17 @@ name: Eve
const expected = [
{
id: 1,
- name: "Alice"
+ name: "Alice",
},
{
id: 2,
- name: "Bob"
+ name: "Bob",
},
{
id: 3,
- name: "Eve"
- }
+ name: "Eve",
+ },
];
assertEquals(parseAll(yaml), expected);
- }
+ },
});
diff --git a/std/encoding/yaml/schema.ts b/std/encoding/yaml/schema.ts
index 1968e34c1..579644dbb 100644
--- a/std/encoding/yaml/schema.ts
+++ b/std/encoding/yaml/schema.ts
@@ -45,7 +45,7 @@ function compileMap(...typesList: Type[][]): TypeMap {
fallback: {},
mapping: {},
scalar: {},
- sequence: {}
+ sequence: {},
};
for (const types of typesList) {
diff --git a/std/encoding/yaml/schema/core.ts b/std/encoding/yaml/schema/core.ts
index 82a512a1e..4fadc9bfe 100644
--- a/std/encoding/yaml/schema/core.ts
+++ b/std/encoding/yaml/schema/core.ts
@@ -9,5 +9,5 @@ import { json } from "./json.ts";
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
export const core = new Schema({
- include: [json]
+ include: [json],
});
diff --git a/std/encoding/yaml/schema/default.ts b/std/encoding/yaml/schema/default.ts
index 0fe1dbf12..4c5ceeba7 100644
--- a/std/encoding/yaml/schema/default.ts
+++ b/std/encoding/yaml/schema/default.ts
@@ -12,5 +12,5 @@ import { core } from "./core.ts";
export const def = new Schema({
explicit: [binary, omap, pairs, set],
implicit: [timestamp, merge],
- include: [core]
+ include: [core],
});
diff --git a/std/encoding/yaml/schema/failsafe.ts b/std/encoding/yaml/schema/failsafe.ts
index 0fbb74ca9..74e1897be 100644
--- a/std/encoding/yaml/schema/failsafe.ts
+++ b/std/encoding/yaml/schema/failsafe.ts
@@ -9,5 +9,5 @@ import { map, seq, str } from "../type/mod.ts";
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346
export const failsafe = new Schema({
- explicit: [str, seq, map]
+ explicit: [str, seq, map],
});
diff --git a/std/encoding/yaml/schema/json.ts b/std/encoding/yaml/schema/json.ts
index dae469f35..c30166fdf 100644
--- a/std/encoding/yaml/schema/json.ts
+++ b/std/encoding/yaml/schema/json.ts
@@ -11,5 +11,5 @@ import { failsafe } from "./failsafe.ts";
// http://www.yaml.org/spec/1.2/spec.html#id2803231
export const json = new Schema({
implicit: [nil, bool, int, float],
- include: [failsafe]
+ include: [failsafe],
});
diff --git a/std/encoding/yaml/stringify_test.ts b/std/encoding/yaml/stringify_test.ts
index 941beb789..03a3090d9 100644
--- a/std/encoding/yaml/stringify_test.ts
+++ b/std/encoding/yaml/stringify_test.ts
@@ -16,14 +16,14 @@ Deno.test({
"a",
"b",
{
- a: false
+ a: false,
},
{
- a: false
- }
- ]
+ a: false,
+ },
+ ],
},
- test: "foobar"
+ test: "foobar",
};
const ASSERTS = `foo:
@@ -37,5 +37,5 @@ test: foobar
`;
assertEquals(stringify(FIXTURE), ASSERTS);
- }
+ },
});
diff --git a/std/encoding/yaml/type/binary.ts b/std/encoding/yaml/type/binary.ts
index 8cfe54f79..f4823b3f7 100644
--- a/std/encoding/yaml/type/binary.ts
+++ b/std/encoding/yaml/type/binary.ts
@@ -135,5 +135,5 @@ export const binary = new Type("tag:yaml.org,2002:binary", {
kind: "scalar",
predicate: isBinary,
represent: representYamlBinary,
- resolve: resolveYamlBinary
+ resolve: resolveYamlBinary,
});
diff --git a/std/encoding/yaml/type/bool.ts b/std/encoding/yaml/type/bool.ts
index e39823872..a5a85cf9e 100644
--- a/std/encoding/yaml/type/bool.ts
+++ b/std/encoding/yaml/type/bool.ts
@@ -33,7 +33,7 @@ export const bool = new Type("tag:yaml.org,2002:bool", {
},
camelcase(object: boolean): string {
return object ? "True" : "False";
- }
+ },
},
- resolve: resolveYamlBoolean
+ resolve: resolveYamlBoolean,
});
diff --git a/std/encoding/yaml/type/float.ts b/std/encoding/yaml/type/float.ts
index acb12f5b0..5ae0689b2 100644
--- a/std/encoding/yaml/type/float.ts
+++ b/std/encoding/yaml/type/float.ts
@@ -121,5 +121,5 @@ export const float = new Type("tag:yaml.org,2002:float", {
kind: "scalar",
predicate: isFloat,
represent: representYamlFloat,
- resolve: resolveYamlFloat
+ resolve: resolveYamlFloat,
});
diff --git a/std/encoding/yaml/type/int.ts b/std/encoding/yaml/type/int.ts
index 93ec8260e..6a86aafe9 100644
--- a/std/encoding/yaml/type/int.ts
+++ b/std/encoding/yaml/type/int.ts
@@ -8,18 +8,18 @@ import { isNegativeZero, Any } from "../utils.ts";
function isHexCode(c: number): boolean {
return (
- (0x30 /* 0 */ <= c && c <= 0x39) /* 9 */ ||
- (0x41 /* A */ <= c && c <= 0x46) /* F */ ||
- (0x61 /* a */ <= c && c <= 0x66) /* f */
+ (0x30 <= /* 0 */ c && c <= 0x39) /* 9 */ ||
+ (0x41 <= /* A */ c && c <= 0x46) /* F */ ||
+ (0x61 <= /* a */ c && c <= 0x66) /* f */
);
}
function isOctCode(c: number): boolean {
- return 0x30 /* 0 */ <= c && c <= 0x37 /* 7 */;
+ return 0x30 <= /* 0 */ c && c <= 0x37 /* 7 */;
}
function isDecCode(c: number): boolean {
- return 0x30 /* 0 */ <= c && c <= 0x39 /* 9 */;
+ return 0x30 <= /* 0 */ c && c <= 0x39 /* 9 */;
}
function resolveYamlInteger(data: string): boolean {
@@ -175,17 +175,14 @@ export const int = new Type("tag:yaml.org,2002:int", {
hexadecimal(obj: number): string {
return obj >= 0
? `0x${obj.toString(16).toUpperCase()}`
- : `-0x${obj
- .toString(16)
- .toUpperCase()
- .slice(1)}`;
- }
+ : `-0x${obj.toString(16).toUpperCase().slice(1)}`;
+ },
},
resolve: resolveYamlInteger,
styleAliases: {
binary: [2, "bin"],
decimal: [10, "dec"],
hexadecimal: [16, "hex"],
- octal: [8, "oct"]
- }
+ octal: [8, "oct"],
+ },
});
diff --git a/std/encoding/yaml/type/map.ts b/std/encoding/yaml/type/map.ts
index 60e678657..dcd99abca 100644
--- a/std/encoding/yaml/type/map.ts
+++ b/std/encoding/yaml/type/map.ts
@@ -10,5 +10,5 @@ export const map = new Type("tag:yaml.org,2002:map", {
construct(data): Any {
return data !== null ? data : {};
},
- kind: "mapping"
+ kind: "mapping",
});
diff --git a/std/encoding/yaml/type/merge.ts b/std/encoding/yaml/type/merge.ts
index 77b34025b..68314bf2e 100644
--- a/std/encoding/yaml/type/merge.ts
+++ b/std/encoding/yaml/type/merge.ts
@@ -11,5 +11,5 @@ function resolveYamlMerge(data: string): boolean {
export const merge = new Type("tag:yaml.org,2002:merge", {
kind: "scalar",
- resolve: resolveYamlMerge
+ resolve: resolveYamlMerge,
});
diff --git a/std/encoding/yaml/type/nil.ts b/std/encoding/yaml/type/nil.ts
index 00627514c..8a48d02fb 100644
--- a/std/encoding/yaml/type/nil.ts
+++ b/std/encoding/yaml/type/nil.ts
@@ -39,7 +39,7 @@ export const nil = new Type("tag:yaml.org,2002:null", {
},
camelcase(): string {
return "Null";
- }
+ },
},
- resolve: resolveYamlNull
+ resolve: resolveYamlNull,
});
diff --git a/std/encoding/yaml/type/omap.ts b/std/encoding/yaml/type/omap.ts
index 541e31df6..d6d751505 100644
--- a/std/encoding/yaml/type/omap.ts
+++ b/std/encoding/yaml/type/omap.ts
@@ -42,5 +42,5 @@ function constructYamlOmap(data: Any): Any {
export const omap = new Type("tag:yaml.org,2002:omap", {
construct: constructYamlOmap,
kind: "sequence",
- resolve: resolveYamlOmap
+ resolve: resolveYamlOmap,
});
diff --git a/std/encoding/yaml/type/pairs.ts b/std/encoding/yaml/type/pairs.ts
index c964524b5..e999748ae 100644
--- a/std/encoding/yaml/type/pairs.ts
+++ b/std/encoding/yaml/type/pairs.ts
@@ -45,5 +45,5 @@ function constructYamlPairs(data: string): Any[] {
export const pairs = new Type("tag:yaml.org,2002:pairs", {
construct: constructYamlPairs,
kind: "sequence",
- resolve: resolveYamlPairs
+ resolve: resolveYamlPairs,
});
diff --git a/std/encoding/yaml/type/seq.ts b/std/encoding/yaml/type/seq.ts
index bd7ceb945..b19565dbc 100644
--- a/std/encoding/yaml/type/seq.ts
+++ b/std/encoding/yaml/type/seq.ts
@@ -10,5 +10,5 @@ export const seq = new Type("tag:yaml.org,2002:seq", {
construct(data): Any {
return data !== null ? data : [];
},
- kind: "sequence"
+ kind: "sequence",
});
diff --git a/std/encoding/yaml/type/set.ts b/std/encoding/yaml/type/set.ts
index 3b7fca0e9..0bfe1c8db 100644
--- a/std/encoding/yaml/type/set.ts
+++ b/std/encoding/yaml/type/set.ts
@@ -27,5 +27,5 @@ function constructYamlSet(data: string): Any {
export const set = new Type("tag:yaml.org,2002:set", {
construct: constructYamlSet,
kind: "mapping",
- resolve: resolveYamlSet
+ resolve: resolveYamlSet,
});
diff --git a/std/encoding/yaml/type/str.ts b/std/encoding/yaml/type/str.ts
index c7227743e..cd6e9430f 100644
--- a/std/encoding/yaml/type/str.ts
+++ b/std/encoding/yaml/type/str.ts
@@ -8,5 +8,5 @@ export const str = new Type("tag:yaml.org,2002:str", {
construct(data): string {
return data !== null ? data : "";
},
- kind: "scalar"
+ kind: "scalar",
});
diff --git a/std/encoding/yaml/type/timestamp.ts b/std/encoding/yaml/type/timestamp.ts
index 14d24077a..eb03b3825 100644
--- a/std/encoding/yaml/type/timestamp.ts
+++ b/std/encoding/yaml/type/timestamp.ts
@@ -92,5 +92,5 @@ export const timestamp = new Type("tag:yaml.org,2002:timestamp", {
instanceOf: Date,
kind: "scalar",
represent: representYamlTimestamp,
- resolve: resolveYamlTimestamp
+ resolve: resolveYamlTimestamp,
});
diff --git a/std/examples/chat/server.ts b/std/examples/chat/server.ts
index 08aede05b..eb5b2f7d4 100644
--- a/std/examples/chat/server.ts
+++ b/std/examples/chat/server.ts
@@ -3,7 +3,7 @@ import {
acceptWebSocket,
acceptable,
WebSocket,
- isWebSocketCloseEvent
+ isWebSocketCloseEvent,
} from "../../ws/mod.ts";
const clients = new Map<number, WebSocket>();
@@ -29,19 +29,19 @@ async function wsHandler(ws: WebSocket): Promise<void> {
}
}
-listenAndServe({ port: 8080 }, async req => {
+listenAndServe({ port: 8080 }, async (req) => {
if (req.method === "GET" && req.url === "/") {
//Serve with hack
const u = new URL("./index.html", import.meta.url);
if (u.protocol.startsWith("http")) {
// server launched by deno run http(s)://.../server.ts,
- fetch(u.href).then(resp => {
+ fetch(u.href).then((resp) => {
return req.respond({
status: resp.status,
headers: new Headers({
- "content-type": "text/html"
+ "content-type": "text/html",
}),
- body: resp.body
+ body: resp.body,
});
});
} else {
@@ -50,9 +50,9 @@ listenAndServe({ port: 8080 }, async req => {
req.respond({
status: 200,
headers: new Headers({
- "content-type": "text/html"
+ "content-type": "text/html",
}),
- body: file
+ body: file,
});
}
}
@@ -60,8 +60,8 @@ listenAndServe({ port: 8080 }, async req => {
req.respond({
status: 302,
headers: new Headers({
- location: "https://deno.land/favicon.ico"
- })
+ location: "https://deno.land/favicon.ico",
+ }),
});
}
if (req.method === "GET" && req.url === "/ws") {
@@ -70,7 +70,7 @@ listenAndServe({ port: 8080 }, async req => {
conn: req.conn,
bufReader: req.r,
bufWriter: req.w,
- headers: req.headers
+ headers: req.headers,
}).then(wsHandler);
}
}
diff --git a/std/examples/chat/server_test.ts b/std/examples/chat/server_test.ts
index 13a5c337c..673b61174 100644
--- a/std/examples/chat/server_test.ts
+++ b/std/examples/chat/server_test.ts
@@ -11,7 +11,7 @@ async function startServer(): Promise<Deno.Process> {
const server = Deno.run({
cmd: [Deno.execPath(), "--allow-net", "--allow-read", "server.ts"],
cwd: "examples/chat",
- stdout: "piped"
+ stdout: "piped",
});
try {
assert(server.stdout != null);
@@ -45,7 +45,7 @@ test({
server.stdout!.close();
}
await delay(10);
- }
+ },
});
test({
@@ -65,5 +65,5 @@ test({
server.stdout!.close();
ws!.conn.close();
}
- }
+ },
});
diff --git a/std/examples/gist.ts b/std/examples/gist.ts
index 15f00ff5d..a11a92383 100755
--- a/std/examples/gist.ts
+++ b/std/examples/gist.ts
@@ -35,7 +35,7 @@ for (const filename of parsedArgs._) {
const content = {
description: parsedArgs.title || parsedArgs.t || "Example",
public: false,
- files: files
+ files: files,
};
const body = JSON.stringify(content);
@@ -44,9 +44,9 @@ const res = await fetch("https://api.github.com/gists", {
headers: [
["Content-Type", "application/json"],
["User-Agent", "Deno-Gist"],
- ["Authorization", `token ${token}`]
+ ["Authorization", `token ${token}`],
],
- body
+ body,
});
if (res.ok) {
diff --git a/std/examples/test.ts b/std/examples/test.ts
index d5dd8bedc..6e26407fb 100644
--- a/std/examples/test.ts
+++ b/std/examples/test.ts
@@ -19,10 +19,10 @@ Deno.test(async function catSmoke(): Promise<void> {
"run",
"--allow-read",
"examples/cat.ts",
- "README.md"
+ "README.md",
],
stdout: "null",
- stderr: "null"
+ stderr: "null",
});
const s = await p.status();
assertEquals(s.code, 0);
diff --git a/std/examples/tests/cat_test.ts b/std/examples/tests/cat_test.ts
index 0f17b798d..b12a6916f 100644
--- a/std/examples/tests/cat_test.ts
+++ b/std/examples/tests/cat_test.ts
@@ -9,10 +9,10 @@ Deno.test("[examples/cat] print multiple files", async () => {
"--allow-read",
"cat.ts",
"testdata/cat/hello.txt",
- "testdata/cat/world.txt"
+ "testdata/cat/world.txt",
],
cwd: "examples",
- stdout: "piped"
+ stdout: "piped",
});
try {
diff --git a/std/examples/tests/catj_test.ts b/std/examples/tests/catj_test.ts
index 3f246a65f..53b36bef8 100644
--- a/std/examples/tests/catj_test.ts
+++ b/std/examples/tests/catj_test.ts
@@ -12,7 +12,7 @@ Deno.test("[examples/catj] print an array", async () => {
".[1] = 100",
'.[2].key = "value"',
'.[2].array[0] = "foo"',
- '.[2].array[1] = "bar"'
+ '.[2].array[1] = "bar"',
].join("\n");
assertStrictEq(actual, expected);
@@ -31,7 +31,7 @@ Deno.test("[examples/catj] print an object", async () => {
const expected = [
'.string = "foobar"',
".number = 123",
- '.array[0].message = "hello"'
+ '.array[0].message = "hello"',
].join("\n");
assertStrictEq(actual, expected);
@@ -81,6 +81,6 @@ function catj(...files: string[]): Deno.Process {
cwd: "examples",
stdin: "piped",
stdout: "piped",
- env: { NO_COLOR: "true" }
+ env: { NO_COLOR: "true" },
});
}
diff --git a/std/examples/tests/colors_test.ts b/std/examples/tests/colors_test.ts
index 7c01cd8d6..ac779adb8 100644
--- a/std/examples/tests/colors_test.ts
+++ b/std/examples/tests/colors_test.ts
@@ -6,7 +6,7 @@ Deno.test("[examples/colors] print a colored text", async () => {
const process = Deno.run({
cmd: [Deno.execPath(), "colors.ts"],
cwd: "examples",
- stdout: "piped"
+ stdout: "piped",
});
try {
const output = await process.output();
diff --git a/std/examples/tests/curl_test.ts b/std/examples/tests/curl_test.ts
index 8d7634525..9b2870216 100644
--- a/std/examples/tests/curl_test.ts
+++ b/std/examples/tests/curl_test.ts
@@ -16,7 +16,7 @@ Deno.test({
const process = Deno.run({
cmd: [Deno.execPath(), "--allow-net", "curl.ts", "http://localhost:8081"],
cwd: "examples",
- stdout: "piped"
+ stdout: "piped",
});
try {
@@ -30,5 +30,5 @@ Deno.test({
process.close();
await serverPromise;
}
- }
+ },
});
diff --git a/std/examples/tests/echo_server_test.ts b/std/examples/tests/echo_server_test.ts
index dd7336023..fecc7d6a6 100644
--- a/std/examples/tests/echo_server_test.ts
+++ b/std/examples/tests/echo_server_test.ts
@@ -8,7 +8,7 @@ Deno.test("[examples/echo_server]", async () => {
const process = Deno.run({
cmd: [Deno.execPath(), "--allow-net", "echo_server.ts"],
cwd: "examples",
- stdout: "piped"
+ stdout: "piped",
});
let conn: Deno.Conn | undefined;
diff --git a/std/examples/tests/welcome_test.ts b/std/examples/tests/welcome_test.ts
index 60c55dc0b..cacb77ab9 100644
--- a/std/examples/tests/welcome_test.ts
+++ b/std/examples/tests/welcome_test.ts
@@ -6,7 +6,7 @@ Deno.test("[examples/welcome] print a welcome message", async () => {
const process = Deno.run({
cmd: [Deno.execPath(), "welcome.ts"],
cwd: "examples",
- stdout: "piped"
+ stdout: "piped",
});
try {
const output = await process.output();
diff --git a/std/examples/tests/xeval_test.ts b/std/examples/tests/xeval_test.ts
index 92e9e1bfe..25f99c9f0 100644
--- a/std/examples/tests/xeval_test.ts
+++ b/std/examples/tests/xeval_test.ts
@@ -5,7 +5,7 @@ import { decode, encode } from "../../strings/mod.ts";
import {
assertEquals,
assertStrContains,
- assert
+ assert,
} from "../../testing/asserts.ts";
const { execPath, run } = Deno;
@@ -18,7 +18,7 @@ Deno.test(async function xevalSuccess(): Promise<void> {
Deno.test(async function xevalDelimiter(): Promise<void> {
const chunks: string[] = [];
await xeval(stringsReader("!MADMADAMADAM!"), ($): number => chunks.push($), {
- delimiter: "MADAM"
+ delimiter: "MADAM",
});
assertEquals(chunks, ["!MAD", "ADAM!"]);
});
@@ -27,12 +27,12 @@ const xevalPath = "examples/xeval.ts";
Deno.test({
name: "xevalCliReplvar",
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
const p = run({
cmd: [execPath(), xevalPath, "--replvar=abc", "console.log(abc)"],
stdin: "piped",
stdout: "piped",
- stderr: "null"
+ stderr: "null",
});
assert(p.stdin != null);
await p.stdin.write(encode("hello"));
@@ -40,7 +40,7 @@ Deno.test({
assertEquals(await p.status(), { code: 0, success: true });
assertEquals(decode(await p.output()).trimEnd(), "hello");
p.close();
- }
+ },
});
Deno.test(async function xevalCliSyntaxError(): Promise<void> {
@@ -48,7 +48,7 @@ Deno.test(async function xevalCliSyntaxError(): Promise<void> {
cmd: [execPath(), xevalPath, "("],
stdin: "null",
stdout: "piped",
- stderr: "piped"
+ stderr: "piped",
});
assertEquals(await p.status(), { code: 1, success: false });
assertEquals(decode(await p.output()), "");
diff --git a/std/examples/xeval.ts b/std/examples/xeval.ts
index 16ce37fb4..6589fec16 100644
--- a/std/examples/xeval.ts
+++ b/std/examples/xeval.ts
@@ -5,7 +5,7 @@ type Reader = Deno.Reader;
/* eslint-disable-next-line max-len */
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction.
-const AsyncFunction = Object.getPrototypeOf(async function(): Promise<void> {})
+const AsyncFunction = Object.getPrototypeOf(async function (): Promise<void> {})
.constructor;
/* eslint-disable max-len */
@@ -59,12 +59,12 @@ async function main(): Promise<void> {
alias: {
delim: ["d"],
replvar: ["I"],
- help: ["h"]
+ help: ["h"],
},
default: {
delim: DEFAULT_DELIMITER,
- replvar: "$"
- }
+ replvar: "$",
+ },
});
if (parsedArgs._.length != 1) {
console.error(HELP_MSG);
diff --git a/std/flags/all_bool_test.ts b/std/flags/all_bool_test.ts
index 6516f48ed..cb5a36710 100755
--- a/std/flags/all_bool_test.ts
+++ b/std/flags/all_bool_test.ts
@@ -5,12 +5,12 @@ import { parse } from "./mod.ts";
// flag boolean true (default all --args to boolean)
Deno.test(function flagBooleanTrue(): void {
const argv = parse(["moo", "--honk", "cow"], {
- boolean: true
+ boolean: true,
});
assertEquals(argv, {
honk: true,
- _: ["moo", "cow"]
+ _: ["moo", "cow"],
});
assertEquals(typeof argv.honk, "boolean");
@@ -19,14 +19,14 @@ Deno.test(function flagBooleanTrue(): void {
// flag boolean true only affects double hyphen arguments without equals signs
Deno.test(function flagBooleanTrueOnlyAffectsDoubleDash(): void {
const argv = parse(["moo", "--honk", "cow", "-p", "55", "--tacos=good"], {
- boolean: true
+ boolean: true,
});
assertEquals(argv, {
honk: true,
tacos: "good",
p: 55,
- _: ["moo", "cow"]
+ _: ["moo", "cow"],
});
assertEquals(typeof argv.honk, "boolean");
diff --git a/std/flags/bool_test.ts b/std/flags/bool_test.ts
index 2d6a8b938..f2d88e617 100755
--- a/std/flags/bool_test.ts
+++ b/std/flags/bool_test.ts
@@ -5,13 +5,13 @@ import { parse } from "./mod.ts";
Deno.test(function flagBooleanDefaultFalse(): void {
const argv = parse(["moo"], {
boolean: ["t", "verbose"],
- default: { verbose: false, t: false }
+ default: { verbose: false, t: false },
});
assertEquals(argv, {
verbose: false,
t: false,
- _: ["moo"]
+ _: ["moo"],
});
assertEquals(typeof argv.verbose, "boolean");
@@ -20,14 +20,14 @@ Deno.test(function flagBooleanDefaultFalse(): void {
Deno.test(function booleanGroups(): void {
const argv = parse(["-x", "-z", "one", "two", "three"], {
- boolean: ["x", "y", "z"]
+ boolean: ["x", "y", "z"],
});
assertEquals(argv, {
x: true,
y: false,
z: true,
- _: ["one", "two", "three"]
+ _: ["one", "two", "three"],
});
assertEquals(typeof argv.x, "boolean");
@@ -40,16 +40,16 @@ Deno.test(function booleanAndAliasWithChainableApi(): void {
const regular = ["--herp", "derp"];
const aliasedArgv = parse(aliased, {
boolean: "herp",
- alias: { h: "herp" }
+ alias: { h: "herp" },
});
const propertyArgv = parse(regular, {
boolean: "herp",
- alias: { h: "herp" }
+ alias: { h: "herp" },
});
const expected = {
herp: true,
h: true,
- _: ["derp"]
+ _: ["derp"],
};
assertEquals(aliasedArgv, expected);
@@ -61,14 +61,14 @@ Deno.test(function booleanAndAliasWithOptionsHash(): void {
const regular = ["--herp", "derp"];
const opts = {
alias: { h: "herp" },
- boolean: "herp"
+ boolean: "herp",
};
const aliasedArgv = parse(aliased, opts);
const propertyArgv = parse(regular, opts);
const expected = {
herp: true,
h: true,
- _: ["derp"]
+ _: ["derp"],
};
assertEquals(aliasedArgv, expected);
assertEquals(propertyArgv, expected);
@@ -80,7 +80,7 @@ Deno.test(function booleanAndAliasArrayWithOptionsHash(): void {
const alt = ["--harp", "derp"];
const opts = {
alias: { h: ["herp", "harp"] },
- boolean: "h"
+ boolean: "h",
};
const aliasedArgv = parse(aliased, opts);
const propertyArgv = parse(regular, opts);
@@ -89,7 +89,7 @@ Deno.test(function booleanAndAliasArrayWithOptionsHash(): void {
harp: true,
herp: true,
h: true,
- _: ["derp"]
+ _: ["derp"],
};
assertEquals(aliasedArgv, expected);
assertEquals(propertyArgv, expected);
@@ -101,14 +101,14 @@ Deno.test(function booleanAndAliasUsingExplicitTrue(): void {
const regular = ["--herp", "true"];
const opts = {
alias: { h: "herp" },
- boolean: "h"
+ boolean: "h",
};
const aliasedArgv = parse(aliased, opts);
const propertyArgv = parse(regular, opts);
const expected = {
herp: true,
h: true,
- _: []
+ _: [],
};
assertEquals(aliasedArgv, expected);
@@ -119,14 +119,14 @@ Deno.test(function booleanAndAliasUsingExplicitTrue(): void {
// boolean and --x=true
Deno.test(function booleanAndNonBoolean(): void {
const parsed = parse(["--boool", "--other=true"], {
- boolean: "boool"
+ boolean: "boool",
});
assertEquals(parsed.boool, true);
assertEquals(parsed.other, "true");
const parsed2 = parse(["--boool", "--other=false"], {
- boolean: "boool"
+ boolean: "boool",
});
assertEquals(parsed2.boool, true);
@@ -136,9 +136,9 @@ Deno.test(function booleanAndNonBoolean(): void {
Deno.test(function booleanParsingTrue(): void {
const parsed = parse(["--boool=true"], {
default: {
- boool: false
+ boool: false,
},
- boolean: ["boool"]
+ boolean: ["boool"],
});
assertEquals(parsed.boool, true);
@@ -147,9 +147,9 @@ Deno.test(function booleanParsingTrue(): void {
Deno.test(function booleanParsingFalse(): void {
const parsed = parse(["--boool=false"], {
default: {
- boool: true
+ boool: true,
},
- boolean: ["boool"]
+ boolean: ["boool"],
});
assertEquals(parsed.boool, false);
@@ -187,7 +187,7 @@ Deno.test(function latestFlagIsBooleanNegation(): void {
assertEquals(parsed.foo, false);
const parsed2 = parse(["--no-foo", "--foo", "--no-foo", "123"], {
- boolean: ["foo"]
+ boolean: ["foo"],
});
assertEquals(parsed2.foo, false);
});
@@ -197,7 +197,7 @@ Deno.test(function latestFlagIsBoolean(): void {
assertEquals(parsed.foo, true);
const parsed2 = parse(["--foo", "--no-foo", "--foo", "123"], {
- boolean: ["foo"]
+ boolean: ["foo"],
});
assertEquals(parsed2.foo, true);
});
diff --git a/std/flags/dash_test.ts b/std/flags/dash_test.ts
index bdf8f502d..3df169291 100755
--- a/std/flags/dash_test.ts
+++ b/std/flags/dash_test.ts
@@ -22,7 +22,7 @@ Deno.test(function moveArgsAfterDoubleDashIntoOwnArray(): void {
{
name: "John",
_: ["before"],
- "--": ["after"]
+ "--": ["after"],
}
);
});
diff --git a/std/flags/default_bool_test.ts b/std/flags/default_bool_test.ts
index 813b6870b..4376038fe 100755
--- a/std/flags/default_bool_test.ts
+++ b/std/flags/default_bool_test.ts
@@ -5,7 +5,7 @@ import { parse } from "./mod.ts";
Deno.test(function booleanDefaultTrue(): void {
const argv = parse([], {
boolean: "sometrue",
- default: { sometrue: true }
+ default: { sometrue: true },
});
assertEquals(argv.sometrue, true);
});
@@ -13,7 +13,7 @@ Deno.test(function booleanDefaultTrue(): void {
Deno.test(function booleanDefaultFalse(): void {
const argv = parse([], {
boolean: "somefalse",
- default: { somefalse: false }
+ default: { somefalse: false },
});
assertEquals(argv.somefalse, false);
});
@@ -21,12 +21,12 @@ Deno.test(function booleanDefaultFalse(): void {
Deno.test(function booleanDefaultNull(): void {
const argv = parse([], {
boolean: "maybe",
- default: { maybe: null }
+ default: { maybe: null },
});
assertEquals(argv.maybe, null);
const argv2 = parse(["--maybe"], {
boolean: "maybe",
- default: { maybe: null }
+ default: { maybe: null },
});
assertEquals(argv2.maybe, true);
});
diff --git a/std/flags/dotted_test.ts b/std/flags/dotted_test.ts
index 93dd3031f..c86392f2a 100755
--- a/std/flags/dotted_test.ts
+++ b/std/flags/dotted_test.ts
@@ -5,7 +5,7 @@ import { parse } from "./mod.ts";
Deno.test(function dottedAlias(): void {
const argv = parse(["--a.b", "22"], {
default: { "a.b": 11 },
- alias: { "a.b": "aa.bb" }
+ alias: { "a.b": "aa.bb" },
});
assertEquals(argv.a.b, 22);
assertEquals(argv.aa.bb, 22);
diff --git a/std/flags/long_test.ts b/std/flags/long_test.ts
index e5b68f8c0..f0f4d7545 100755
--- a/std/flags/long_test.ts
+++ b/std/flags/long_test.ts
@@ -9,11 +9,11 @@ Deno.test(function longOpts(): void {
assertEquals(parse(["--host", "localhost", "--port", "555"]), {
host: "localhost",
port: 555,
- _: []
+ _: [],
});
assertEquals(parse(["--host=localhost", "--port=555"]), {
host: "localhost",
port: 555,
- _: []
+ _: [],
});
});
diff --git a/std/flags/mod.ts b/std/flags/mod.ts
index 18727a665..b334cb5b8 100644
--- a/std/flags/mod.ts
+++ b/std/flags/mod.ts
@@ -85,7 +85,7 @@ function isNumber(x: unknown): boolean {
function hasKey(obj: NestedMapping, keys: string[]): boolean {
let o = obj;
- keys.slice(0, -1).forEach(key => {
+ keys.slice(0, -1).forEach((key) => {
o = (get(o, key) ?? {}) as NestedMapping;
});
@@ -107,14 +107,14 @@ export function parse(
default: defaults = {},
stopEarly = false,
string = [],
- unknown = (i: unknown): unknown => i
+ unknown = (i: unknown): unknown => i,
}: ArgParsingOptions = {}
): Args {
const flags: Flags = {
bools: {},
strings: {},
unknownFn: unknown,
- allBools: false
+ allBools: false,
};
if (boolean !== undefined) {
@@ -139,7 +139,7 @@ export function parse(
aliases[key] = val;
}
for (const alias of getForce(aliases, key)) {
- aliases[alias] = [key].concat(aliases[key].filter(y => alias !== y));
+ aliases[alias] = [key].concat(aliases[key].filter((y) => alias !== y));
}
}
}
@@ -171,7 +171,7 @@ export function parse(
function setKey(obj: NestedMapping, keys: string[], value: unknown): void {
let o = obj;
- keys.slice(0, -1).forEach(function(key): void {
+ keys.slice(0, -1).forEach(function (key): void {
if (get(o, key) === undefined) {
o[key] = {};
}
@@ -214,7 +214,7 @@ export function parse(
function aliasIsBoolean(key: string): boolean {
return getForce(aliases, key).some(
- x => typeof get(flags.bools, x) === "boolean"
+ (x) => typeof get(flags.bools, x) === "boolean"
);
}
diff --git a/std/flags/num_test.ts b/std/flags/num_test.ts
index 0d6b634b9..f8a0d11ac 100755
--- a/std/flags/num_test.ts
+++ b/std/flags/num_test.ts
@@ -14,7 +14,7 @@ Deno.test(function nums(): void {
"10f",
"--hex",
"0xdeadbeef",
- "789"
+ "789",
]);
assertEquals(argv, {
x: 1234,
@@ -22,7 +22,7 @@ Deno.test(function nums(): void {
z: 1e7,
w: "10f",
hex: 0xdeadbeef,
- _: [789]
+ _: [789],
});
assertEquals(typeof argv.x, "number");
assertEquals(typeof argv.y, "number");
diff --git a/std/flags/parse_test.ts b/std/flags/parse_test.ts
index cd93c1f81..abba42e16 100755
--- a/std/flags/parse_test.ts
+++ b/std/flags/parse_test.ts
@@ -6,7 +6,7 @@ Deno.test(function parseArgs(): void {
assertEquals(parse(["--no-moo"]), { moo: false, _: [] });
assertEquals(parse(["-v", "a", "-v", "b", "-v", "c"]), {
v: ["a", "b", "c"],
- _: []
+ _: [],
});
});
@@ -28,7 +28,7 @@ Deno.test(function comprehensive(): void {
"--multi=baz",
"--",
"--not-a-flag",
- "eek"
+ "eek",
]),
{
c: true,
@@ -42,7 +42,7 @@ Deno.test(function comprehensive(): void {
multi: ["quux", "baz"],
meep: false,
name: "meowmers",
- _: ["bare", "--not-a-flag", "eek"]
+ _: ["bare", "--not-a-flag", "eek"],
}
);
});
@@ -56,13 +56,13 @@ Deno.test(function flagBoolean(): void {
Deno.test(function flagBooleanValue(): void {
const argv = parse(["--verbose", "false", "moo", "-t", "true"], {
boolean: ["t", "verbose"],
- default: { verbose: true }
+ default: { verbose: true },
});
assertEquals(argv, {
verbose: false,
t: true,
- _: ["moo"]
+ _: ["moo"],
});
assertEquals(typeof argv.verbose, "boolean");
@@ -110,7 +110,7 @@ Deno.test(function emptyStrings(): void {
assertEquals(typeof str, "string");
const letters = parse(["-art"], {
- string: ["a", "t"]
+ string: ["a", "t"],
});
assertEquals(letters.a, "");
@@ -121,7 +121,7 @@ Deno.test(function emptyStrings(): void {
Deno.test(function stringAndAlias(): void {
const x = parse(["--str", "000123"], {
string: "s",
- alias: { s: "str" }
+ alias: { s: "str" },
});
assertEquals(x.str, "000123");
@@ -131,7 +131,7 @@ Deno.test(function stringAndAlias(): void {
const y = parse(["-s", "000123"], {
string: "str",
- alias: { str: "s" }
+ alias: { str: "s" },
});
assertEquals(y.str, "000123");
@@ -146,13 +146,13 @@ Deno.test(function slashBreak(): void {
x: true,
y: true,
z: "/foo/bar/baz",
- _: []
+ _: [],
});
});
Deno.test(function alias(): void {
const argv = parse(["-f", "11", "--zoom", "55"], {
- alias: { z: "zoom" }
+ alias: { z: "zoom" },
});
assertEquals(argv.zoom, 55);
assertEquals(argv.z, argv.zoom);
@@ -161,7 +161,7 @@ Deno.test(function alias(): void {
Deno.test(function multiAlias(): void {
const argv = parse(["-f", "11", "--zoom", "55"], {
- alias: { z: ["zm", "zoom"] }
+ alias: { z: ["zm", "zoom"] },
});
assertEquals(argv.zoom, 55);
assertEquals(argv.z, argv.zoom);
@@ -178,7 +178,7 @@ Deno.test(function nestedDottedObjects(): void {
"--foo.quux.quibble",
"5",
"--foo.quux.oO",
- "--beep.boop"
+ "--beep.boop",
]);
assertEquals(argv.foo, {
@@ -186,8 +186,8 @@ Deno.test(function nestedDottedObjects(): void {
baz: 4,
quux: {
quibble: 5,
- oO: true
- }
+ oO: true,
+ },
});
assertEquals(argv.beep, { boop: true });
});
diff --git a/std/flags/short_test.ts b/std/flags/short_test.ts
index d7171b920..6305bbb94 100755
--- a/std/flags/short_test.ts
+++ b/std/flags/short_test.ts
@@ -16,13 +16,13 @@ Deno.test(function short(): void {
a: true,
t: true,
s: "meow",
- _: []
+ _: [],
});
assertEquals(parse(["-h", "localhost"]), { h: "localhost", _: [] });
assertEquals(parse(["-h", "localhost", "-p", "555"]), {
h: "localhost",
p: 555,
- _: []
+ _: [],
});
});
@@ -31,7 +31,7 @@ Deno.test(function mixedShortBoolAndCapture(): void {
f: true,
p: 555,
h: "localhost",
- _: ["script.js"]
+ _: ["script.js"],
});
});
@@ -40,6 +40,6 @@ Deno.test(function shortAndLong(): void {
f: true,
p: 555,
h: "localhost",
- _: ["script.js"]
+ _: ["script.js"],
});
});
diff --git a/std/flags/stop_early_test.ts b/std/flags/stop_early_test.ts
index d1996e7aa..4b7eac097 100755
--- a/std/flags/stop_early_test.ts
+++ b/std/flags/stop_early_test.ts
@@ -5,11 +5,11 @@ import { parse } from "./mod.ts";
// stops parsing on the first non-option when stopEarly is set
Deno.test(function stopParsing(): void {
const argv = parse(["--aaa", "bbb", "ccc", "--ddd"], {
- stopEarly: true
+ stopEarly: true,
});
assertEquals(argv, {
aaa: "bbb",
- _: ["ccc", "--ddd"]
+ _: ["ccc", "--ddd"],
});
});
diff --git a/std/flags/unknown_test.ts b/std/flags/unknown_test.ts
index acbb131ee..90c638b67 100755
--- a/std/flags/unknown_test.ts
+++ b/std/flags/unknown_test.ts
@@ -13,7 +13,7 @@ Deno.test(function booleanAndAliasIsNotUnknown(): void {
const opts = {
alias: { h: "herp" },
boolean: "h",
- unknown: unknownFn
+ unknown: unknownFn,
};
parse(aliased, opts);
parse(regular, opts);
@@ -29,12 +29,12 @@ Deno.test(function flagBooleanTrueAnyDoubleHyphenArgumentIsNotUnknown(): void {
}
const argv = parse(["--honk", "--tacos=good", "cow", "-p", "55"], {
boolean: true,
- unknown: unknownFn
+ unknown: unknownFn,
});
assertEquals(unknown, ["--tacos=good", "cow", "-p"]);
assertEquals(argv, {
honk: true,
- _: []
+ _: [],
});
});
@@ -49,7 +49,7 @@ Deno.test(function stringAndAliasIsNotUnkown(): void {
const opts = {
alias: { h: "herp" },
string: "h",
- unknown: unknownFn
+ unknown: unknownFn,
};
parse(aliased, opts);
parse(regular, opts);
@@ -68,7 +68,7 @@ Deno.test(function defaultAndAliasIsNotUnknown(): void {
const opts = {
default: { h: "bar" },
alias: { h: "herp" },
- unknown: unknownFn
+ unknown: unknownFn,
};
parse(aliased, opts);
parse(regular, opts);
@@ -85,13 +85,13 @@ Deno.test(function valueFollowingDoubleHyphenIsNotUnknown(): void {
const aliased = ["--bad", "--", "good", "arg"];
const opts = {
"--": true,
- unknown: unknownFn
+ unknown: unknownFn,
};
const argv = parse(aliased, opts);
assertEquals(unknown, ["--bad"]);
assertEquals(argv, {
"--": ["good", "arg"],
- _: []
+ _: [],
});
});
diff --git a/std/fmt/colors.ts b/std/fmt/colors.ts
index 9476ce076..ad2a6a1be 100644
--- a/std/fmt/colors.ts
+++ b/std/fmt/colors.ts
@@ -37,7 +37,7 @@ function code(open: number, close: number): Code {
return {
open: `\x1b[${open}m`,
close: `\x1b[${close}m`,
- regexp: new RegExp(`\\x1b\\[${close}m`, "g")
+ regexp: new RegExp(`\\x1b\\[${close}m`, "g"),
};
}
diff --git a/std/fmt/sprintf.ts b/std/fmt/sprintf.ts
index dd7ac7f55..d79b9095e 100644
--- a/std/fmt/sprintf.ts
+++ b/std/fmt/sprintf.ts
@@ -3,11 +3,11 @@ enum State {
PERCENT,
POSITIONAL,
PRECISION,
- WIDTH
+ WIDTH,
}
enum WorP {
WIDTH,
- PRECISION
+ PRECISION,
}
class Flags {
@@ -34,7 +34,7 @@ enum F {
mantissa,
fractional,
esign,
- exponent
+ exponent,
}
class Printf {
diff --git a/std/fmt/sprintf_test.ts b/std/fmt/sprintf_test.ts
index 917878bc1..24d0b4727 100644
--- a/std/fmt/sprintf_test.ts
+++ b/std/fmt/sprintf_test.ts
@@ -229,7 +229,6 @@ const tests: Array<[string, any, string]> = [
["%d", 12345, "12345"],
["%v", 12345, "12345"],
["%t", true, "true"],
-
// basic string
["%s", "abc", "abc"],
// ["%q", "abc", `"abc"`], // TODO: need %q?
@@ -248,7 +247,6 @@ const tests: Array<[string, any, string]> = [
["%#X", "xyz", "0X78797A"],
["%# x", "xyz", "0x78 0x79 0x7a"],
["%# X", "xyz", "0X78 0X79 0X7A"],
-
// basic bytes : TODO special handling for Buffer? other std types?
// escaped strings : TODO decide whether to have %q
@@ -261,7 +259,6 @@ const tests: Array<[string, any, string]> = [
["%.0c", "⌘".charCodeAt(0), "⌘"],
["%3c", "⌘".charCodeAt(0), " ⌘"],
["%-3c", "⌘".charCodeAt(0), "⌘ "],
-
// Runes that are not printable.
// {"%c", '\U00000e00', "\u0e00"}, // TODO check if \U escape exists in js
//["%c", '\U0010ffff'.codePointAt(0), "\U0010ffff"],
@@ -273,7 +270,6 @@ const tests: Array<[string, any, string]> = [
// ["%c", 0xDC80, "�"],
["%c", 0x110000, "�"],
["%c", 0xfffffffff, "�"],
-
// TODO
// escaped characters
// Runes that are not printable.
@@ -351,7 +347,6 @@ const tests: Array<[string, any, string]> = [
["%-#20.8x", 0x1234abc, "0x01234abc "],
["%-#20.8X", 0x1234abc, "0X01234ABC "],
["%-#20.8o", parseInt("01234", 8), "00001234 "],
-
// Test correct f.intbuf overflow checks. // TODO, lazy
// unicode format // TODO, decide whether unicode verb makes sense %U
@@ -433,7 +428,6 @@ const tests: Array<[string, any, string]> = [
["%+020e", Number.POSITIVE_INFINITY, " +Inf"],
["%-020f", Number.NEGATIVE_INFINITY, "-Inf "],
["%-020E", NaN, "NaN "],
-
// complex values // go specific
// old test/fmt_test.go
["%e", 1.0, "1.000000e+00"],
@@ -490,7 +484,6 @@ const tests: Array<[string, any, string]> = [
["%g", 1.23456789e-3, "0.00123457"], // see above prec6 = precdef6 - (-3+1)
//["%g", 1.23456789e20, "1.23456789e+20"],
["%g", 1.23456789e20, "1.23457e+20"],
-
// arrays // TODO
// slice : go specific
@@ -527,7 +520,6 @@ const tests: Array<[string, any, string]> = [
["% -010X", "\xab", "AB "],
["%#-10X", "\xab\xcd", "0XABCD "],
["%# -010X", "\xab\xcd", "0XAB 0XCD "],
-
// renamings
// Formatter
// GoStringer
@@ -541,7 +533,6 @@ const tests: Array<[string, any, string]> = [
["%T", S, "function"],
["%T", true, "boolean"],
["%T", Symbol(), "symbol"],
-
// %p with pointers
// erroneous things
@@ -582,7 +573,7 @@ const tests: Array<[string, any, string]> = [
["%+07.2f", 1.0, "+001.00"],
["%+07.2f", -1.0, "-001.00"],
["% +07.2f", 1.0, "+001.00"],
- ["% +07.2f", -1.0, "-001.00"]
+ ["% +07.2f", -1.0, "-001.00"],
];
Deno.test(function testThorough(): void {
diff --git a/std/fs/README.md b/std/fs/README.md
index 56c190ccc..8c69faa76 100644
--- a/std/fs/README.md
+++ b/std/fs/README.md
@@ -52,7 +52,7 @@ created.
```ts
import {
ensureSymlink,
- ensureSymlinkSync
+ ensureSymlinkSync,
} from "https://deno.land/std/fs/mod.ts";
ensureSymlink(
@@ -110,7 +110,7 @@ import { globToRegExp } from "https://deno.land/std/fs/mod.ts";
globToRegExp("foo/**/*.json", {
flags: "g",
extended: true,
- globstar: true
+ globstar: true,
}); // returns the regex to find all .json files in the folder foo
```
@@ -212,7 +212,7 @@ Write the string to file.
```ts
import {
writeFileStr,
- writeFileStrSync
+ writeFileStrSync,
} from "https://deno.land/std/fs/mod.ts";
writeFileStr("./target.dat", "file content"); // returns a promise
diff --git a/std/fs/copy_test.ts b/std/fs/copy_test.ts
index 9ba5f2b21..0fbc90579 100644
--- a/std/fs/copy_test.ts
+++ b/std/fs/copy_test.ts
@@ -3,7 +3,7 @@ import {
assertEquals,
assertThrows,
assertThrowsAsync,
- assert
+ assert,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { copy, copySync } from "./copy.ts";
@@ -22,11 +22,11 @@ function testCopy(name: string, cb: (tempDir: string) => Promise<void>): void {
name,
async fn(): Promise<void> {
const tempDir = await Deno.makeTempDir({
- prefix: "deno_std_copy_async_test_"
+ prefix: "deno_std_copy_async_test_",
});
await cb(tempDir);
await Deno.remove(tempDir, { recursive: true });
- }
+ },
});
}
@@ -35,11 +35,11 @@ function testCopySync(name: string, cb: (tempDir: string) => void): void {
name,
fn: (): void => {
const tempDir = Deno.makeTempDirSync({
- prefix: "deno_std_copy_sync_test_"
+ prefix: "deno_std_copy_sync_test_",
});
cb(tempDir);
Deno.removeSync(tempDir, { recursive: true });
- }
+ },
});
}
@@ -149,7 +149,7 @@ testCopy(
// Copy with overwrite and preserve timestamps options.
await copy(srcFile, destFile, {
overwrite: true,
- preserveTimestamps: true
+ preserveTimestamps: true,
});
const destStatInfo = await Deno.stat(destFile);
@@ -333,7 +333,7 @@ testCopySync(
// Copy with overwrite and preserve timestamps options.
copySync(srcFile, destFile, {
overwrite: true,
- preserveTimestamps: true
+ preserveTimestamps: true,
});
const destStatInfo = Deno.statSync(destFile);
diff --git a/std/fs/empty_dir_test.ts b/std/fs/empty_dir_test.ts
index 7015516ab..f30f434df 100644
--- a/std/fs/empty_dir_test.ts
+++ b/std/fs/empty_dir_test.ts
@@ -4,7 +4,7 @@ import {
assertEquals,
assertStrContains,
assertThrows,
- assertThrowsAsync
+ assertThrowsAsync,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { emptyDir, emptyDirSync } from "./empty_dir.ts";
@@ -137,59 +137,59 @@ const scenes: Scenes[] = [
read: false,
write: false,
async: true,
- output: "run again with the --allow-read flag"
+ output: "run again with the --allow-read flag",
},
{
read: false,
write: false,
async: false,
- output: "run again with the --allow-read flag"
+ output: "run again with the --allow-read flag",
},
// 2
{
read: true,
write: false,
async: true,
- output: "run again with the --allow-write flag"
+ output: "run again with the --allow-write flag",
},
{
read: true,
write: false,
async: false,
- output: "run again with the --allow-write flag"
+ output: "run again with the --allow-write flag",
},
// 3
{
read: false,
write: true,
async: true,
- output: "run again with the --allow-read flag"
+ output: "run again with the --allow-read flag",
},
{
read: false,
write: true,
async: false,
- output: "run again with the --allow-read flag"
+ output: "run again with the --allow-read flag",
},
// 4
{
read: true,
write: true,
async: true,
- output: "success"
+ output: "success",
},
{
read: true,
write: true,
async: false,
- output: "success"
- }
+ output: "success",
+ },
];
for (const s of scenes) {
let title = `test ${s.async ? "emptyDir" : "emptyDirSync"}`;
title += `("testdata/testfolder") ${s.read ? "with" : "without"}`;
title += ` --allow-read & ${s.write ? "with" : "without"} --allow-write`;
- Deno.test(`[fs] emptyDirPermission ${title}`, async function(): Promise<
+ Deno.test(`[fs] emptyDirPermission ${title}`, async function (): Promise<
void
> {
const testfolder = path.join(testdataDir, "testfolder");
@@ -221,7 +221,7 @@ for (const s of scenes) {
const p = Deno.run({
stdout: "piped",
cwd: testdataDir,
- cmd: args
+ cmd: args,
});
assert(p.stdout);
diff --git a/std/fs/ensure_link_test.ts b/std/fs/ensure_link_test.ts
index 7549814a2..3c7720dc0 100644
--- a/std/fs/ensure_link_test.ts
+++ b/std/fs/ensure_link_test.ts
@@ -3,7 +3,7 @@
import {
assertEquals,
assertThrows,
- assertThrowsAsync
+ assertThrowsAsync,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { ensureLink, ensureLinkSync } from "./ensure_link.ts";
diff --git a/std/fs/ensure_symlink_test.ts b/std/fs/ensure_symlink_test.ts
index f0dc4fbe4..5188dc035 100644
--- a/std/fs/ensure_symlink_test.ts
+++ b/std/fs/ensure_symlink_test.ts
@@ -3,7 +3,7 @@
import {
assertEquals,
assertThrows,
- assertThrowsAsync
+ assertThrowsAsync,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { ensureSymlink, ensureSymlinkSync } from "./ensure_symlink.ts";
diff --git a/std/fs/eol.ts b/std/fs/eol.ts
index d4bb8032c..2f15be269 100644
--- a/std/fs/eol.ts
+++ b/std/fs/eol.ts
@@ -3,7 +3,7 @@
/** EndOfLine character enum */
export enum EOL {
LF = "\n",
- CRLF = "\r\n"
+ CRLF = "\r\n",
}
const regDetect = /(?:\r?\n)/g;
diff --git a/std/fs/eol_test.ts b/std/fs/eol_test.ts
index aa2dcf395..35b3e0d9a 100644
--- a/std/fs/eol_test.ts
+++ b/std/fs/eol_test.ts
@@ -12,21 +12,21 @@ Deno.test({
name: "[EOL] Detect CR LF",
fn(): void {
assertEquals(detect(CRLFinput), EOL.CRLF);
- }
+ },
});
Deno.test({
name: "[EOL] Detect LF",
fn(): void {
assertEquals(detect(LFinput), EOL.LF);
- }
+ },
});
Deno.test({
name: "[EOL] Detect No New Line",
fn(): void {
assertEquals(detect(NoNLinput), null);
- }
+ },
});
Deno.test({
@@ -34,7 +34,7 @@ Deno.test({
fn(): void {
assertEquals(detect(Mixedinput), EOL.CRLF);
assertEquals(detect(Mixedinput2), EOL.CRLF);
- }
+ },
});
Deno.test({
@@ -50,5 +50,5 @@ Deno.test({
assertEquals(format(Mixedinput, EOL.LF), LFinput);
assertEquals(format(Mixedinput2, EOL.CRLF), CRLFinput);
assertEquals(format(Mixedinput2, EOL.LF), LFinput);
- }
+ },
});
diff --git a/std/fs/exists_test.ts b/std/fs/exists_test.ts
index 1f296538c..04c58d8d6 100644
--- a/std/fs/exists_test.ts
+++ b/std/fs/exists_test.ts
@@ -5,7 +5,7 @@ import { exists, existsSync } from "./exists.ts";
const testdataDir = path.resolve("fs", "testdata");
-Deno.test("[fs] existsFile", async function(): Promise<void> {
+Deno.test("[fs] existsFile", async function (): Promise<void> {
assertEquals(
await exists(path.join(testdataDir, "not_exist_file.ts")),
false
@@ -13,12 +13,12 @@ Deno.test("[fs] existsFile", async function(): Promise<void> {
assertEquals(await existsSync(path.join(testdataDir, "0.ts")), true);
});
-Deno.test("[fs] existsFileSync", function(): void {
+Deno.test("[fs] existsFileSync", function (): void {
assertEquals(existsSync(path.join(testdataDir, "not_exist_file.ts")), false);
assertEquals(existsSync(path.join(testdataDir, "0.ts")), true);
});
-Deno.test("[fs] existsDirectory", async function(): Promise<void> {
+Deno.test("[fs] existsDirectory", async function (): Promise<void> {
assertEquals(
await exists(path.join(testdataDir, "not_exist_directory")),
false
@@ -26,7 +26,7 @@ Deno.test("[fs] existsDirectory", async function(): Promise<void> {
assertEquals(existsSync(testdataDir), true);
});
-Deno.test("[fs] existsDirectorySync", function(): void {
+Deno.test("[fs] existsDirectorySync", function (): void {
assertEquals(
existsSync(path.join(testdataDir, "not_exist_directory")),
false
@@ -34,16 +34,16 @@ Deno.test("[fs] existsDirectorySync", function(): void {
assertEquals(existsSync(testdataDir), true);
});
-Deno.test("[fs] existsLinkSync", function(): void {
+Deno.test("[fs] existsLinkSync", function (): void {
// TODO(axetroy): generate link file use Deno api instead of set a link file
// in repository
- assertEquals(existsSync(path.join(testdataDir, "0-link.ts")), true);
+ assertEquals(existsSync(path.join(testdataDir, "0-link")), true);
});
-Deno.test("[fs] existsLink", async function(): Promise<void> {
+Deno.test("[fs] existsLink", async function (): Promise<void> {
// TODO(axetroy): generate link file use Deno api instead of set a link file
// in repository
- assertEquals(await exists(path.join(testdataDir, "0-link.ts")), true);
+ assertEquals(await exists(path.join(testdataDir, "0-link")), true);
});
interface Scenes {
@@ -59,59 +59,59 @@ const scenes: Scenes[] = [
read: false,
async: true,
output: "run again with the --allow-read flag",
- file: "0.ts"
+ file: "0.ts",
},
{
read: false,
async: false,
output: "run again with the --allow-read flag",
- file: "0.ts"
+ file: "0.ts",
},
// 2
{
read: true,
async: true,
output: "exist",
- file: "0.ts"
+ file: "0.ts",
},
{
read: true,
async: false,
output: "exist",
- file: "0.ts"
+ file: "0.ts",
},
// 3
{
read: false,
async: true,
output: "run again with the --allow-read flag",
- file: "no_exist_file_for_test.ts"
+ file: "no_exist_file_for_test.ts",
},
{
read: false,
async: false,
output: "run again with the --allow-read flag",
- file: "no_exist_file_for_test.ts"
+ file: "no_exist_file_for_test.ts",
},
// 4
{
read: true,
async: true,
output: "not exist",
- file: "no_exist_file_for_test.ts"
+ file: "no_exist_file_for_test.ts",
},
{
read: true,
async: false,
output: "not exist",
- file: "no_exist_file_for_test.ts"
- }
+ file: "no_exist_file_for_test.ts",
+ },
];
for (const s of scenes) {
let title = `test ${s.async ? "exists" : "existsSync"}("testdata/${s.file}")`;
title += ` ${s.read ? "with" : "without"} --allow-read`;
- Deno.test(`[fs] existsPermission ${title}`, async function(): Promise<void> {
+ Deno.test(`[fs] existsPermission ${title}`, async function (): Promise<void> {
const args = [Deno.execPath(), "run"];
if (s.read) {
@@ -124,7 +124,7 @@ for (const s of scenes) {
const p = Deno.run({
stdout: "piped",
cwd: testdataDir,
- cmd: args
+ cmd: args,
});
const output = await p.output();
diff --git a/std/fs/expand_glob.ts b/std/fs/expand_glob.ts
index c6653eda1..10a8c2c52 100644
--- a/std/fs/expand_glob.ts
+++ b/std/fs/expand_glob.ts
@@ -6,7 +6,7 @@ import {
isGlob,
isWindows,
joinGlobs,
- normalize
+ normalize,
} from "../path/mod.ts";
import { WalkInfo, walk, walkSync } from "./walk.ts";
import { assert } from "../testing/asserts.ts";
@@ -38,7 +38,7 @@ function split(path: string): SplitPath {
segments,
isAbsolute: isAbsolute_,
hasTrailingSep: !!path.match(new RegExp(`${s}$`)),
- winRoot: isWindows && isAbsolute_ ? segments.shift() : undefined
+ winRoot: isWindows && isAbsolute_ ? segments.shift() : undefined,
};
}
@@ -59,7 +59,7 @@ export async function* expandGlob(
exclude = [],
includeDirs = true,
extended = false,
- globstar = false
+ globstar = false,
}: ExpandGlobOptions = {}
): AsyncIterableIterator<WalkInfo> {
const globOptions: GlobOptions = { extended, globstar };
@@ -110,7 +110,7 @@ export async function* expandGlob(
} else if (globSegment == "**") {
return yield* walk(walkInfo.filename, {
includeFiles: false,
- skip: excludePatterns
+ skip: excludePatterns,
});
}
yield* walk(walkInfo.filename, {
@@ -119,9 +119,9 @@ export async function* expandGlob(
globToRegExp(
joinGlobs([walkInfo.filename, globSegment], globOptions),
globOptions
- )
+ ),
],
- skip: excludePatterns
+ skip: excludePatterns,
});
}
@@ -138,7 +138,7 @@ export async function* expandGlob(
currentMatches = [...nextMatchMap].sort().map(
([filename, info]): WalkInfo => ({
filename,
- info
+ info,
})
);
}
@@ -163,7 +163,7 @@ export function* expandGlobSync(
exclude = [],
includeDirs = true,
extended = false,
- globstar = false
+ globstar = false,
}: ExpandGlobOptions = {}
): IterableIterator<WalkInfo> {
const globOptions: GlobOptions = { extended, globstar };
@@ -214,7 +214,7 @@ export function* expandGlobSync(
} else if (globSegment == "**") {
return yield* walkSync(walkInfo.filename, {
includeFiles: false,
- skip: excludePatterns
+ skip: excludePatterns,
});
}
yield* walkSync(walkInfo.filename, {
@@ -223,9 +223,9 @@ export function* expandGlobSync(
globToRegExp(
joinGlobs([walkInfo.filename, globSegment], globOptions),
globOptions
- )
+ ),
],
- skip: excludePatterns
+ skip: excludePatterns,
});
}
@@ -242,7 +242,7 @@ export function* expandGlobSync(
currentMatches = [...nextMatchMap].sort().map(
([filename, info]): WalkInfo => ({
filename,
- info
+ info,
})
);
}
diff --git a/std/fs/expand_glob_test.ts b/std/fs/expand_glob_test.ts
index adc94c1e9..6be9c518f 100644
--- a/std/fs/expand_glob_test.ts
+++ b/std/fs/expand_glob_test.ts
@@ -6,12 +6,12 @@ import {
join,
joinGlobs,
normalize,
- relative
+ relative,
} from "../path/mod.ts";
import {
ExpandGlobOptions,
expandGlob,
- expandGlobSync
+ expandGlobSync,
} from "./expand_glob.ts";
async function expandGlobArray(
@@ -48,7 +48,7 @@ const EG_OPTIONS: ExpandGlobOptions = {
root: urlToFilePath(new URL(join("testdata", "glob"), import.meta.url)),
includeDirs: true,
extended: false,
- globstar: false
+ globstar: false,
};
Deno.test(async function expandGlobWildcard(): Promise<void> {
@@ -57,7 +57,7 @@ Deno.test(async function expandGlobWildcard(): Promise<void> {
"abc",
"abcdef",
"abcdefghi",
- "subdir"
+ "subdir",
]);
});
@@ -72,7 +72,7 @@ Deno.test(async function expandGlobParent(): Promise<void> {
"abc",
"abcdef",
"abcdefghi",
- "subdir"
+ "subdir",
]);
});
@@ -80,16 +80,16 @@ Deno.test(async function expandGlobExt(): Promise<void> {
const options = { ...EG_OPTIONS, extended: true };
assertEquals(await expandGlobArray("abc?(def|ghi)", options), [
"abc",
- "abcdef"
+ "abcdef",
]);
assertEquals(await expandGlobArray("abc*(def|ghi)", options), [
"abc",
"abcdef",
- "abcdefghi"
+ "abcdefghi",
]);
assertEquals(await expandGlobArray("abc+(def|ghi)", options), [
"abcdef",
- "abcdefghi"
+ "abcdefghi",
]);
assertEquals(await expandGlobArray("abc@(def|ghi)", options), ["abcdef"]);
assertEquals(await expandGlobArray("abc{def,ghi}", options), ["abcdef"]);
@@ -123,7 +123,7 @@ Deno.test(async function expandGlobPermError(): Promise<void> {
cmd: [execPath(), exampleUrl.toString()],
stdin: "null",
stdout: "piped",
- stderr: "piped"
+ stderr: "piped",
});
assertEquals(await p.status(), { code: 1, success: false });
assertEquals(decode(await p.output()), "");
diff --git a/std/fs/move_test.ts b/std/fs/move_test.ts
index b835e6dfa..999b67cf0 100644
--- a/std/fs/move_test.ts
+++ b/std/fs/move_test.ts
@@ -2,7 +2,7 @@
import {
assertEquals,
assertThrows,
- assertThrowsAsync
+ assertThrowsAsync,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { move, moveSync } from "./move.ts";
@@ -68,7 +68,7 @@ Deno.test(async function moveFileIfDestExists(): Promise<void> {
// write file content
await Promise.all([
Deno.writeFile(srcFile, srcContent),
- Deno.writeFile(destFile, destContent)
+ Deno.writeFile(destFile, destContent),
]);
// make sure the test file have been created
@@ -100,7 +100,7 @@ Deno.test(async function moveFileIfDestExists(): Promise<void> {
// clean up
await Promise.all([
Deno.remove(srcDir, { recursive: true }),
- Deno.remove(destDir, { recursive: true })
+ Deno.remove(destDir, { recursive: true }),
]);
});
@@ -141,13 +141,13 @@ Deno.test(async function moveIfSrcAndDestDirectoryExistsAndOverwrite(): Promise<
await Promise.all([
Deno.mkdir(srcDir, { recursive: true }),
- Deno.mkdir(destDir, { recursive: true })
+ Deno.mkdir(destDir, { recursive: true }),
]);
assertEquals(await exists(srcDir), true);
assertEquals(await exists(destDir), true);
await Promise.all([
Deno.writeFile(srcFile, srcContent),
- Deno.writeFile(destFile, destContent)
+ Deno.writeFile(destFile, destContent),
]);
await move(srcDir, destDir, { overwrite: true });
diff --git a/std/fs/read_json_test.ts b/std/fs/read_json_test.ts
index c394963b0..bdb5edbe5 100644
--- a/std/fs/read_json_test.ts
+++ b/std/fs/read_json_test.ts
@@ -2,7 +2,7 @@
import {
assertEquals,
assertThrowsAsync,
- assertThrows
+ assertThrows,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { readJson, readJsonSync } from "./read_json.ts";
diff --git a/std/fs/testdata/0-link b/std/fs/testdata/0-link
new file mode 120000
index 000000000..937f1e899
--- /dev/null
+++ b/std/fs/testdata/0-link
@@ -0,0 +1 @@
+0.ts \ No newline at end of file
diff --git a/std/fs/testdata/0-link.ts b/std/fs/testdata/0-link.ts
deleted file mode 120000
index 24c6b8053..000000000
--- a/std/fs/testdata/0-link.ts
+++ /dev/null
@@ -1 +0,0 @@
-./fs/testdata/0.ts \ No newline at end of file
diff --git a/std/fs/testdata/empty_dir.ts b/std/fs/testdata/empty_dir.ts
index aa9cf60a1..f8fcc1ceb 100644
--- a/std/fs/testdata/empty_dir.ts
+++ b/std/fs/testdata/empty_dir.ts
@@ -2,8 +2,8 @@ import { emptyDir } from "../empty_dir.ts";
emptyDir(Deno.args[0])
.then(() => {
- Deno.stdout.write(new TextEncoder().encode("success"))
+ Deno.stdout.write(new TextEncoder().encode("success"));
})
.catch((err) => {
- Deno.stdout.write(new TextEncoder().encode(err.message))
- }) \ No newline at end of file
+ Deno.stdout.write(new TextEncoder().encode(err.message));
+ });
diff --git a/std/fs/testdata/exists_sync.ts b/std/fs/testdata/exists_sync.ts
index 27dee268b..8cc51e9f8 100644
--- a/std/fs/testdata/exists_sync.ts
+++ b/std/fs/testdata/exists_sync.ts
@@ -1,10 +1,8 @@
import { existsSync } from "../exists.ts";
try {
- const isExist = existsSync(Deno.args[0])
- Deno.stdout.write(new TextEncoder().encode(isExist ? 'exist' :'not exist'))
+ const isExist = existsSync(Deno.args[0]);
+ Deno.stdout.write(new TextEncoder().encode(isExist ? "exist" : "not exist"));
} catch (err) {
- Deno.stdout.write(new TextEncoder().encode(err.message))
+ Deno.stdout.write(new TextEncoder().encode(err.message));
}
-
-
diff --git a/std/fs/utils_test.ts b/std/fs/utils_test.ts
index 93f4664e7..95686d824 100644
--- a/std/fs/utils_test.ts
+++ b/std/fs/utils_test.ts
@@ -17,10 +17,10 @@ Deno.test(function _isSubdir(): void {
["first", "first/second", true, path.posix.sep],
["../first", "../first/second", true, path.posix.sep],
["c:\\first", "c:\\first", false, path.win32.sep],
- ["c:\\first", "c:\\first\\second", true, path.win32.sep]
+ ["c:\\first", "c:\\first\\second", true, path.win32.sep],
];
- pairs.forEach(function(p): void {
+ pairs.forEach(function (p): void {
const src = p[0] as string;
const dest = p[1] as string;
const expected = p[2] as boolean;
@@ -36,10 +36,10 @@ Deno.test(function _isSubdir(): void {
Deno.test(function _getFileInfoType(): void {
const pairs = [
[path.join(testdataDir, "file_type_1"), "file"],
- [path.join(testdataDir, "file_type_dir_1"), "dir"]
+ [path.join(testdataDir, "file_type_dir_1"), "dir"],
];
- pairs.forEach(function(p): void {
+ pairs.forEach(function (p): void {
const filePath = p[0] as string;
const type = p[1] as PathType;
switch (type) {
diff --git a/std/fs/walk.ts b/std/fs/walk.ts
index fbd14740b..3f178c0c5 100644
--- a/std/fs/walk.ts
+++ b/std/fs/walk.ts
@@ -67,7 +67,7 @@ export async function* walk(
followSymlinks = false,
exts = undefined,
match = undefined,
- skip = undefined
+ skip = undefined,
}: WalkOptions = {}
): AsyncIterableIterator<WalkInfo> {
if (maxDepth < 0) {
@@ -105,7 +105,7 @@ export async function* walk(
followSymlinks,
exts,
match,
- skip
+ skip,
});
}
}
@@ -121,7 +121,7 @@ export function* walkSync(
followSymlinks = false,
exts = undefined,
match = undefined,
- skip = undefined
+ skip = undefined,
}: WalkOptions = {}
): IterableIterator<WalkInfo> {
if (maxDepth < 0) {
@@ -158,7 +158,7 @@ export function* walkSync(
followSymlinks,
exts,
match,
- skip
+ skip,
});
}
}
diff --git a/std/fs/write_json_test.ts b/std/fs/write_json_test.ts
index 09fa05d60..335d35bfe 100644
--- a/std/fs/write_json_test.ts
+++ b/std/fs/write_json_test.ts
@@ -2,7 +2,7 @@
import {
assertEquals,
assertThrowsAsync,
- assertThrows
+ assertThrows,
} from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { writeJson, writeJsonSync } from "./write_json.ts";
@@ -108,7 +108,7 @@ Deno.test(async function writeJsonWithReplacer(): Promise<void> {
existsJsonFile,
{ a: "1", b: "2", c: "3" },
{
- replacer: ["a"]
+ replacer: ["a"],
}
);
throw new Error("should write success");
@@ -226,7 +226,7 @@ Deno.test(function writeJsonWithReplacer(): void {
existsJsonFile,
{ a: "1", b: "2", c: "3" },
{
- replacer: ["a"]
+ replacer: ["a"],
}
);
throw new Error("should write success");
diff --git a/std/http/cookie.ts b/std/http/cookie.ts
index 10c9bd689..062019f14 100644
--- a/std/http/cookie.ts
+++ b/std/http/cookie.ts
@@ -130,6 +130,6 @@ export function delCookie(res: Response, name: string): void {
setCookie(res, {
name: name,
value: "",
- expires: new Date(0)
+ expires: new Date(0),
});
}
diff --git a/std/http/cookie_test.ts b/std/http/cookie_test.ts
index 8ab862bb3..1b78b2bff 100644
--- a/std/http/cookie_test.ts
+++ b/std/http/cookie_test.ts
@@ -27,9 +27,9 @@ test({
assertEquals(getCookies(req), {
PREF: "al=en-GB&f1=123",
wide: "1",
- SID: "123"
+ SID: "123",
});
- }
+ },
});
test({
@@ -41,7 +41,7 @@ test({
res.headers?.get("Set-Cookie"),
"deno=; Expires=Thu, 01 Jan 1970 00:00:00 GMT"
);
- }
+ },
});
test({
@@ -66,7 +66,7 @@ test({
name: "Space",
value: "Cat",
httpOnly: true,
- secure: true
+ secure: true,
});
assertEquals(res.headers.get("Set-Cookie"), "Space=Cat; Secure; HttpOnly");
@@ -76,7 +76,7 @@ test({
value: "Cat",
httpOnly: true,
secure: true,
- maxAge: 2
+ maxAge: 2,
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -91,7 +91,7 @@ test({
value: "Cat",
httpOnly: true,
secure: true,
- maxAge: 0
+ maxAge: 0,
});
} catch (e) {
error = true;
@@ -105,7 +105,7 @@ test({
httpOnly: true,
secure: true,
maxAge: 2,
- domain: "deno.land"
+ domain: "deno.land",
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -120,7 +120,7 @@ test({
secure: true,
maxAge: 2,
domain: "deno.land",
- sameSite: "Strict"
+ sameSite: "Strict",
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -136,7 +136,7 @@ test({
secure: true,
maxAge: 2,
domain: "deno.land",
- sameSite: "Lax"
+ sameSite: "Lax",
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -151,7 +151,7 @@ test({
secure: true,
maxAge: 2,
domain: "deno.land",
- path: "/"
+ path: "/",
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -167,7 +167,7 @@ test({
maxAge: 2,
domain: "deno.land",
path: "/",
- unparsed: ["unparsed=keyvalue", "batman=Bruce"]
+ unparsed: ["unparsed=keyvalue", "batman=Bruce"],
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -184,7 +184,7 @@ test({
maxAge: 2,
domain: "deno.land",
path: "/",
- expires: new Date(Date.UTC(1983, 0, 7, 15, 32))
+ expires: new Date(Date.UTC(1983, 0, 7, 15, 32)),
});
assertEquals(
res.headers.get("Set-Cookie"),
@@ -200,11 +200,11 @@ test({
setCookie(res, {
name: "__Host-Kitty",
value: "Meow",
- domain: "deno.land"
+ domain: "deno.land",
});
assertEquals(
res.headers.get("Set-Cookie"),
"__Host-Kitty=Meow; Secure; Path=/"
);
- }
+ },
});
diff --git a/std/http/file_server.ts b/std/http/file_server.ts
index 20d5d61e6..5582afd07 100755
--- a/std/http/file_server.ts
+++ b/std/http/file_server.ts
@@ -108,7 +108,7 @@ async function serveFile(
const res = {
status: 200,
body: file,
- headers
+ headers,
};
return res;
}
@@ -137,7 +137,7 @@ async function serveDir(
mode: modeToString(fileInfo.isDirectory(), mode),
size: fileInfo.isFile() ? fileLenToString(fileInfo.size) : "",
name: fileInfo.name ?? "",
- url: fileUrl
+ url: fileUrl,
});
}
listEntry.sort((a, b) =>
@@ -152,7 +152,7 @@ async function serveDir(
const res = {
status: 200,
body: page,
- headers
+ headers,
};
setContentLength(res);
return res;
@@ -162,12 +162,12 @@ function serveFallback(req: ServerRequest, e: Error): Promise<Response> {
if (e instanceof Deno.errors.NotFound) {
return Promise.resolve({
status: 404,
- body: encoder.encode("Not found")
+ body: encoder.encode("Not found"),
});
} else {
return Promise.resolve({
status: 500,
- body: encoder.encode("Internal server error")
+ body: encoder.encode("Internal server error"),
});
}
}
@@ -258,19 +258,20 @@ function dirViewerTemplate(dirname: string, entries: EntryInfo[]): string {
<th>Name</th>
</tr>
${entries.map(
- entry => html`
- <tr>
- <td class="mode">
- ${entry.mode}
- </td>
- <td>
- ${entry.size}
- </td>
- <td>
- <a href="${entry.url}">${entry.name}</a>
- </td>
- </tr>
- `
+ (entry) =>
+ html`
+ <tr>
+ <td class="mode">
+ ${entry.mode}
+ </td>
+ <td>
+ ${entry.size}
+ </td>
+ <td>
+ <a href="${entry.url}">${entry.name}</a>
+ </td>
+ </tr>
+ `
)}
</table>
</main>
diff --git a/std/http/file_server_test.ts b/std/http/file_server_test.ts
index fcf776ea2..3a3817ce0 100644
--- a/std/http/file_server_test.ts
+++ b/std/http/file_server_test.ts
@@ -14,10 +14,10 @@ async function startFileServer(): Promise<void> {
"--allow-net",
"http/file_server.ts",
".",
- "--cors"
+ "--cors",
],
stdout: "piped",
- stderr: "null"
+ stderr: "null",
});
// Once fileServer is ready it will write to its stdout.
assert(fileServer.stdout != null);
@@ -106,7 +106,7 @@ test(async function servePermissionDenied(): Promise<void> {
const deniedServer = Deno.run({
cmd: [Deno.execPath(), "run", "--allow-net", "http/file_server.ts"],
stdout: "piped",
- stderr: "piped"
+ stderr: "piped",
});
assert(deniedServer.stdout != null);
const reader = new TextProtoReader(new BufReader(deniedServer.stdout));
@@ -132,7 +132,7 @@ test(async function servePermissionDenied(): Promise<void> {
test(async function printHelp(): Promise<void> {
const helpProcess = Deno.run({
cmd: [Deno.execPath(), "run", "http/file_server.ts", "--help"],
- stdout: "piped"
+ stdout: "piped",
});
assert(helpProcess.stdout != null);
const r = new TextProtoReader(new BufReader(helpProcess.stdout));
diff --git a/std/http/http_bench.ts b/std/http/http_bench.ts
index 9d1912831..15f223323 100644
--- a/std/http/http_bench.ts
+++ b/std/http/http_bench.ts
@@ -9,7 +9,7 @@ console.log(`http://${addr}/`);
for await (const req of server) {
const res = {
body,
- headers: new Headers()
+ headers: new Headers(),
};
res.headers.set("Date", new Date().toUTCString());
res.headers.set("Connection", "keep-alive");
diff --git a/std/http/http_status.ts b/std/http/http_status.ts
index ead1e1ff0..ce4338705 100644
--- a/std/http/http_status.ts
+++ b/std/http/http_status.ts
@@ -125,14 +125,13 @@ export enum Status {
/** RFC 2774, 7 */
NotExtended = 510,
/** RFC 6585, 6 */
- NetworkAuthenticationRequired = 511
+ NetworkAuthenticationRequired = 511,
}
export const STATUS_TEXT = new Map<Status, string>([
[Status.Continue, "Continue"],
[Status.SwitchingProtocols, "Switching Protocols"],
[Status.Processing, "Processing"],
-
[Status.OK, "OK"],
[Status.Created, "Created"],
[Status.Accepted, "Accepted"],
@@ -143,7 +142,6 @@ export const STATUS_TEXT = new Map<Status, string>([
[Status.MultiStatus, "Multi-Status"],
[Status.AlreadyReported, "Already Reported"],
[Status.IMUsed, "IM Used"],
-
[Status.MultipleChoices, "Multiple Choices"],
[Status.MovedPermanently, "Moved Permanently"],
[Status.Found, "Found"],
@@ -152,7 +150,6 @@ export const STATUS_TEXT = new Map<Status, string>([
[Status.UseProxy, "Use Proxy"],
[Status.TemporaryRedirect, "Temporary Redirect"],
[Status.PermanentRedirect, "Permanent Redirect"],
-
[Status.BadRequest, "Bad Request"],
[Status.Unauthorized, "Unauthorized"],
[Status.PaymentRequired, "Payment Required"],
@@ -181,7 +178,6 @@ export const STATUS_TEXT = new Map<Status, string>([
[Status.TooManyRequests, "Too Many Requests"],
[Status.RequestHeaderFieldsTooLarge, "Request Header Fields Too Large"],
[Status.UnavailableForLegalReasons, "Unavailable For Legal Reasons"],
-
[Status.InternalServerError, "Internal Server Error"],
[Status.NotImplemented, "Not Implemented"],
[Status.BadGateway, "Bad Gateway"],
@@ -192,5 +188,5 @@ export const STATUS_TEXT = new Map<Status, string>([
[Status.InsufficientStorage, "Insufficient Storage"],
[Status.LoopDetected, "Loop Detected"],
[Status.NotExtended, "Not Extended"],
- [Status.NetworkAuthenticationRequired, "Network Authentication Required"]
+ [Status.NetworkAuthenticationRequired, "Network Authentication Required"],
]);
diff --git a/std/http/io.ts b/std/http/io.ts
index 6d5d1f665..2875be44f 100644
--- a/std/http/io.ts
+++ b/std/http/io.ts
@@ -9,7 +9,7 @@ export function emptyReader(): Deno.Reader {
return {
read(_: Uint8Array): Promise<number | Deno.EOF> {
return Promise.resolve(Deno.EOF);
- }
+ },
};
}
@@ -83,7 +83,7 @@ export function chunkedBodyReader(h: Headers, r: BufReader): Deno.Reader {
} else {
chunks.push({
offset: 0,
- data: restChunk
+ data: restChunk,
});
}
return buf.byteLength;
@@ -116,7 +116,7 @@ export function chunkedBodyReader(h: Headers, r: BufReader): Deno.Reader {
const kProhibitedTrailerHeaders = [
"transfer-encoding",
"content-length",
- "trailer"
+ "trailer",
];
/**
@@ -147,7 +147,7 @@ function parseTrailer(field: string | null): Set<string> | undefined {
if (field == null) {
return undefined;
}
- const keys = field.split(",").map(v => v.trim());
+ const keys = field.split(",").map((v) => v.trim());
if (keys.length === 0) {
throw new Error("Empty trailer");
}
@@ -196,7 +196,7 @@ export async function writeTrailers(
const writer = BufWriter.create(w);
const trailerHeaderFields = trailer
.split(",")
- .map(s => s.trim().toLowerCase());
+ .map((s) => s.trim().toLowerCase());
for (const f of trailerHeaderFields) {
assert(
!kProhibitedTrailerHeaders.includes(f),
diff --git a/std/http/io_test.ts b/std/http/io_test.ts
index 6c96d0b95..7261964d0 100644
--- a/std/http/io_test.ts
+++ b/std/http/io_test.ts
@@ -4,7 +4,7 @@ import {
assertEquals,
assert,
assertNotEOF,
- assertNotEquals
+ assertNotEquals,
} from "../testing/asserts.ts";
import {
bodyReader,
@@ -12,7 +12,7 @@ import {
readTrailers,
parseHTTPVersion,
readRequest,
- writeResponse
+ writeResponse,
} from "./io.ts";
import { encode, decode } from "../strings/mod.ts";
import { BufReader, ReadLineResult } from "../io/bufio.ts";
@@ -39,7 +39,7 @@ test("chunkedBodyReader", async () => {
chunkify(5, "b"),
chunkify(11, "c"),
chunkify(22, "d"),
- chunkify(0, "")
+ chunkify(0, ""),
].join("");
const h = new Headers();
const r = chunkedBodyReader(h, new BufReader(new Buffer(encode(body))));
@@ -64,10 +64,10 @@ test("chunkedBodyReader with trailers", async () => {
chunkify(0, ""),
"deno: land\r\n",
"node: js\r\n",
- "\r\n"
+ "\r\n",
].join("");
const h = new Headers({
- trailer: "deno,node"
+ trailer: "deno,node",
});
const r = chunkedBodyReader(h, new BufReader(new Buffer(encode(body))));
assertEquals(h.has("trailer"), true);
@@ -83,7 +83,7 @@ test("chunkedBodyReader with trailers", async () => {
test("readTrailers", async () => {
const h = new Headers({
- trailer: "deno,node"
+ trailer: "deno,node",
});
const trailer = ["deno: land", "node: js", "", ""].join("\r\n");
await readTrailers(h, new BufReader(new Buffer(encode(trailer))));
@@ -96,11 +96,11 @@ test("readTrailer should throw if undeclared headers found in trailer", async ()
const patterns = [
["deno,node", "deno: land\r\nnode: js\r\ngo: lang\r\n\r\n"],
["deno", "node: js\r\n\r\n"],
- ["deno", "node:js\r\ngo: lang\r\n\r\n"]
+ ["deno", "node:js\r\ngo: lang\r\n\r\n"],
];
for (const [header, trailer] of patterns) {
const h = new Headers({
- trailer: header
+ trailer: header,
});
await assertThrowsAsync(
async () => {
@@ -115,7 +115,7 @@ test("readTrailer should throw if undeclared headers found in trailer", async ()
test("readTrailer should throw if trailer contains prohibited fields", async () => {
for (const f of ["content-length", "trailer", "transfer-encoding"]) {
const h = new Headers({
- trailer: f
+ trailer: f,
});
await assertThrowsAsync(
async () => {
@@ -192,7 +192,7 @@ test("parseHttpVersion", (): void => {
{ in: "HTTP/-1.0", err: true },
{ in: "HTTP/0.-1", err: true },
{ in: "HTTP/", err: true },
- { in: "HTTP/1,0", err: true }
+ { in: "HTTP/1,0", err: true },
];
for (const t of testCases) {
let r, err;
@@ -320,10 +320,10 @@ test("writeResponse with trailer", async () => {
status: 200,
headers: new Headers({
"transfer-encoding": "chunked",
- trailer: "deno,node"
+ trailer: "deno,node",
}),
body,
- trailers: () => new Headers({ deno: "land", node: "js" })
+ trailers: () => new Headers({ deno: "land", node: "js" }),
});
const ret = w.toString();
const exp = [
@@ -338,7 +338,7 @@ test("writeResponse with trailer", async () => {
"deno: land",
"node: js",
"",
- ""
+ "",
].join("\r\n");
assertEquals(ret, exp);
});
@@ -365,20 +365,20 @@ test(async function testReadRequestError(): Promise<void> {
const testCases = [
{
in: "GET / HTTP/1.1\r\nheader: foo\r\n\r\n",
- headers: [{ key: "header", value: "foo" }]
+ headers: [{ key: "header", value: "foo" }],
},
{
in: "GET / HTTP/1.1\r\nheader:foo\r\n",
- err: Deno.errors.UnexpectedEof
+ err: Deno.errors.UnexpectedEof,
},
{ in: "", err: Deno.EOF },
{
in: "HEAD / HTTP/1.1\r\nContent-Length:4\r\n\r\n",
- err: "http: method cannot contain a Content-Length"
+ err: "http: method cannot contain a Content-Length",
},
{
in: "HEAD / HTTP/1.1\r\n\r\n",
- headers: []
+ headers: [],
},
// Multiple Content-Length values should either be
// deduplicated if same or reject otherwise
@@ -387,23 +387,23 @@ test(async function testReadRequestError(): Promise<void> {
in:
"POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 0\r\n\r\n" +
"Gopher hey\r\n",
- err: "cannot contain multiple Content-Length headers"
+ err: "cannot contain multiple Content-Length headers",
},
{
in:
"POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 6\r\n\r\n" +
"Gopher\r\n",
- err: "cannot contain multiple Content-Length headers"
+ err: "cannot contain multiple Content-Length headers",
},
{
in:
"PUT / HTTP/1.1\r\nContent-Length: 6 \r\nContent-Length: 6\r\n" +
"Content-Length:6\r\n\r\nGopher\r\n",
- headers: [{ key: "Content-Length", value: "6" }]
+ headers: [{ key: "Content-Length", value: "6" }],
},
{
in: "PUT / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 6 \r\n\r\n",
- err: "cannot contain multiple Content-Length headers"
+ err: "cannot contain multiple Content-Length headers",
},
// Setting an empty header is swallowed by textproto
// see: readMIMEHeader()
@@ -413,15 +413,15 @@ test(async function testReadRequestError(): Promise<void> {
// },
{
in: "HEAD / HTTP/1.1\r\nContent-Length:0\r\nContent-Length: 0\r\n\r\n",
- headers: [{ key: "Content-Length", value: "0" }]
+ headers: [{ key: "Content-Length", value: "0" }],
},
{
in:
"POST / HTTP/1.1\r\nContent-Length:0\r\ntransfer-encoding: " +
"chunked\r\n\r\n",
headers: [],
- err: "http: Transfer-Encoding and Content-Length cannot be send together"
- }
+ err: "http: Transfer-Encoding and Content-Length cannot be send together",
+ },
];
for (const test of testCases) {
const reader = new BufReader(new StringReader(test.in));
diff --git a/std/http/mock.ts b/std/http/mock.ts
index cee697bed..64bd3fcb9 100644
--- a/std/http/mock.ts
+++ b/std/http/mock.ts
@@ -4,12 +4,12 @@ export function mockConn(base: Partial<Deno.Conn> = {}): Deno.Conn {
localAddr: {
transport: "tcp",
hostname: "",
- port: 0
+ port: 0,
},
remoteAddr: {
transport: "tcp",
hostname: "",
- port: 0
+ port: 0,
},
rid: -1,
closeRead: (): void => {},
@@ -21,6 +21,6 @@ export function mockConn(base: Partial<Deno.Conn> = {}): Deno.Conn {
return Promise.resolve(-1);
},
close: (): void => {},
- ...base
+ ...base,
};
}
diff --git a/std/http/racing_server_test.ts b/std/http/racing_server_test.ts
index 865777599..037e91ef9 100644
--- a/std/http/racing_server_test.ts
+++ b/std/http/racing_server_test.ts
@@ -7,7 +7,7 @@ let server: Deno.Process;
async function startServer(): Promise<void> {
server = run({
cmd: [Deno.execPath(), "run", "-A", "http/racing_server.ts"],
- stdout: "piped"
+ stdout: "piped",
});
// Once racing server is ready it will write to its stdout.
assert(server.stdout != null);
@@ -27,7 +27,7 @@ const input = [
"POST / HTTP/1.1\r\ncontent-length: 4\r\n\r\ndeno",
"POST / HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n4\r\ndeno\r\n0\r\n\r\n",
"POST / HTTP/1.1\r\ntransfer-encoding: chunked\r\ntrailer: deno\r\n\r\n4\r\ndeno\r\n0\r\n\r\ndeno: land\r\n\r\n",
- "GET / HTTP/1.1\r\n\r\n"
+ "GET / HTTP/1.1\r\n\r\n",
].join("");
const HUGE_BODY_SIZE = 1024 * 1024;
const output = `HTTP/1.1 200 OK
diff --git a/std/http/server.ts b/std/http/server.ts
index 2cd51b005..00f401f62 100644
--- a/std/http/server.ts
+++ b/std/http/server.ts
@@ -7,7 +7,7 @@ import {
chunkedBodyReader,
emptyReader,
writeResponse,
- readRequest
+ readRequest,
} from "./io.ts";
import Listener = Deno.Listener;
import Conn = Deno.Conn;
@@ -298,7 +298,7 @@ export type HTTPSOptions = Omit<Deno.ListenTLSOptions, "transport">;
export function serveTLS(options: HTTPSOptions): Server {
const tlsOptions: Deno.ListenTLSOptions = {
...options,
- transport: "tcp"
+ transport: "tcp",
};
const listener = listenTLS(tlsOptions);
return new Server(listener);
diff --git a/std/http/server_test.ts b/std/http/server_test.ts
index f66b190b2..d6b2be053 100644
--- a/std/http/server_test.ts
+++ b/std/http/server_test.ts
@@ -11,7 +11,7 @@ import {
assertEquals,
assertNotEOF,
assertStrContains,
- assertThrowsAsync
+ assertThrowsAsync,
} from "../testing/asserts.ts";
import { Response, ServerRequest, Server, serve } from "./server.ts";
import { BufReader, BufWriter } from "../io/bufio.ts";
@@ -30,27 +30,27 @@ const responseTests: ResponseTest[] = [
// Default response
{
response: {},
- raw: "HTTP/1.1 200 OK\r\n" + "content-length: 0" + "\r\n\r\n"
+ raw: "HTTP/1.1 200 OK\r\n" + "content-length: 0" + "\r\n\r\n",
},
// Empty body with status
{
response: {
- status: 404
+ status: 404,
},
- raw: "HTTP/1.1 404 Not Found\r\n" + "content-length: 0" + "\r\n\r\n"
+ raw: "HTTP/1.1 404 Not Found\r\n" + "content-length: 0" + "\r\n\r\n",
},
// HTTP/1.1, chunked coding; empty trailer; close
{
response: {
status: 200,
- body: new Buffer(new TextEncoder().encode("abcdef"))
+ body: new Buffer(new TextEncoder().encode("abcdef")),
},
raw:
"HTTP/1.1 200 OK\r\n" +
"transfer-encoding: chunked\r\n\r\n" +
- "6\r\nabcdef\r\n0\r\n\r\n"
- }
+ "6\r\nabcdef\r\n0\r\n\r\n",
+ },
];
test(async function responseWrite(): Promise<void> {
@@ -118,7 +118,7 @@ function totalReader(r: Deno.Reader): TotalReader {
read,
get total(): number {
return _total;
- }
+ },
};
}
test(async function requestBodyWithContentLength(): Promise<void> {
@@ -169,7 +169,7 @@ test("ServerRequest.finalize() should consume unread body / chunked, trailers",
"deno: land",
"node: js",
"",
- ""
+ "",
].join("\r\n");
const req = new ServerRequest();
req.headers = new Headers();
@@ -357,7 +357,7 @@ test({
// Runs a simple server as another process
const p = Deno.run({
cmd: [Deno.execPath(), "--allow-net", "http/testdata/simple_server.ts"],
- stdout: "piped"
+ stdout: "piped",
});
let serverIsRunning = true;
@@ -387,7 +387,7 @@ test({
p.stdout!.close();
p.close();
}
- }
+ },
});
test({
@@ -401,9 +401,9 @@ test({
Deno.execPath(),
"--allow-net",
"--allow-read",
- "http/testdata/simple_https_server.ts"
+ "http/testdata/simple_https_server.ts",
],
- stdout: "piped"
+ stdout: "piped",
});
let serverIsRunning = true;
@@ -425,7 +425,7 @@ test({
const conn = await Deno.connectTLS({
hostname: "localhost",
port: 4503,
- certFile: "http/testdata/tls/RootCA.pem"
+ certFile: "http/testdata/tls/RootCA.pem",
});
await Deno.writeAll(
conn,
@@ -444,7 +444,7 @@ test({
p.stdout!.close();
p.close();
}
- }
+ },
});
test("close server while iterating", async (): Promise<void> => {
@@ -485,7 +485,7 @@ test({
const resources = Deno.resources();
assertEquals(resources[conn.rid], "tcpStream");
conn.close();
- }
+ },
});
test({
@@ -498,7 +498,7 @@ test({
await assertThrowsAsync(async () => {
await req.respond({
status: 12345,
- body: new TextEncoder().encode("Hello World")
+ body: new TextEncoder().encode("Hello World"),
});
}, Deno.errors.InvalidData);
// The connection should be destroyed
@@ -509,7 +509,7 @@ test({
const p = serverRoutine();
const conn = await Deno.connect({
hostname: "127.0.0.1",
- port: 8124
+ port: 8124,
});
await Deno.writeAll(
conn,
@@ -517,5 +517,5 @@ test({
);
conn.close();
await p;
- }
+ },
});
diff --git a/std/io/bufio.ts b/std/io/bufio.ts
index a944adfed..87613e341 100644
--- a/std/io/bufio.ts
+++ b/std/io/bufio.ts
@@ -212,8 +212,9 @@ export class BufReader implements Reader {
* For simple uses, a Scanner may be more convenient.
*/
async readString(delim: string): Promise<string | Deno.EOF> {
- if (delim.length !== 1)
+ if (delim.length !== 1) {
throw new Error("Delimiter should be a single character");
+ }
const buffer = await this.readSlice(delim.charCodeAt(0));
if (buffer == Deno.EOF) return Deno.EOF;
return new TextDecoder().decode(buffer);
diff --git a/std/io/bufio_test.ts b/std/io/bufio_test.ts
index ae38f6667..c1b1b856b 100644
--- a/std/io/bufio_test.ts
+++ b/std/io/bufio_test.ts
@@ -9,7 +9,7 @@ import {
assert,
assertEquals,
fail,
- assertNotEOF
+ assertNotEOF,
} from "../testing/asserts.ts";
import {
BufReader,
@@ -17,7 +17,7 @@ import {
BufferFullError,
PartialReadError,
readStringDelim,
- readLines
+ readLines,
} from "./bufio.ts";
import * as iotest from "./iotest.ts";
import { charCode, copyBytes, stringsReader } from "./util.ts";
@@ -55,9 +55,9 @@ const readMakers: ReadMaker[] = [
{ name: "full", fn: (r): Reader => r },
{
name: "byte",
- fn: (r): iotest.OneByteReader => new iotest.OneByteReader(r)
+ fn: (r): iotest.OneByteReader => new iotest.OneByteReader(r),
},
- { name: "half", fn: (r): iotest.HalfReader => new iotest.HalfReader(r) }
+ { name: "half", fn: (r): iotest.HalfReader => new iotest.HalfReader(r) },
// TODO { name: "data+err", r => new iotest.DataErrReader(r) },
// { name: "timeout", fn: r => new iotest.TimeoutReader(r) },
];
@@ -89,7 +89,7 @@ const bufreaders: NamedBufReader[] = [
{ name: "4", fn: (b: BufReader): Promise<string> => reads(b, 4) },
{ name: "5", fn: (b: BufReader): Promise<string> => reads(b, 5) },
{ name: "7", fn: (b: BufReader): Promise<string> => reads(b, 7) },
- { name: "bytes", fn: readBytes }
+ { name: "bytes", fn: readBytes },
// { name: "lines", fn: readLines },
];
@@ -104,7 +104,7 @@ const bufsizes: number[] = [
93,
128,
1024,
- 4096
+ 4096,
];
Deno.test(async function bufioBufReader(): Promise<void> {
diff --git a/std/io/ioutil_test.ts b/std/io/ioutil_test.ts
index 3d85a0fa1..d00986da5 100644
--- a/std/io/ioutil_test.ts
+++ b/std/io/ioutil_test.ts
@@ -7,7 +7,7 @@ import {
readInt,
readLong,
readShort,
- sliceLongToBytes
+ sliceLongToBytes,
} from "./ioutil.ts";
import { BufReader } from "./bufio.ts";
import { stringsReader } from "./util.ts";
diff --git a/std/io/util_test.ts b/std/io/util_test.ts
index 2fcad9305..17f11b945 100644
--- a/std/io/util_test.ts
+++ b/std/io/util_test.ts
@@ -4,7 +4,7 @@ import { assert, assertEquals } from "../testing/asserts.ts";
import * as path from "../path/mod.ts";
import { copyBytes, tempFile } from "./util.ts";
-test("[io/tuil] copyBytes", function(): void {
+test("[io/tuil] copyBytes", function (): void {
const dst = new Uint8Array(4);
dst.fill(0);
@@ -40,14 +40,14 @@ test("[io/tuil] copyBytes", function(): void {
test({
name: "[io/util] tempfile",
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
const f = await tempFile(".", {
prefix: "prefix-",
- postfix: "-postfix"
+ postfix: "-postfix",
});
const base = path.basename(f.filepath);
assert(!!base.match(/^prefix-.+?-postfix$/));
f.file.close();
await remove(f.filepath);
- }
+ },
});
diff --git a/std/log/README.md b/std/log/README.md
index 613e69922..dea1e5fe7 100644
--- a/std/log/README.md
+++ b/std/log/README.md
@@ -21,22 +21,22 @@ await log.setup({
file: new log.handlers.FileHandler("WARNING", {
filename: "./log.txt",
// you can change format of output message
- formatter: "{levelName} {msg}"
- })
+ formatter: "{levelName} {msg}",
+ }),
},
loggers: {
// configure default logger available via short-hand methods above
default: {
level: "DEBUG",
- handlers: ["console", "file"]
+ handlers: ["console", "file"],
},
tasks: {
level: "ERROR",
- handlers: ["console"]
- }
- }
+ handlers: ["console"],
+ },
+ },
});
let logger;
diff --git a/std/log/handlers_test.ts b/std/log/handlers_test.ts
index 693d2a485..4feffdaf9 100644
--- a/std/log/handlers_test.ts
+++ b/std/log/handlers_test.ts
@@ -21,8 +21,8 @@ test(function simpleHandler(): void {
"INFO info-test",
"WARNING warning-test",
"ERROR error-test",
- "CRITICAL critical-test"
- ]
+ "CRITICAL critical-test",
+ ],
],
[
LogLevel.INFO,
@@ -30,15 +30,15 @@ test(function simpleHandler(): void {
"INFO info-test",
"WARNING warning-test",
"ERROR error-test",
- "CRITICAL critical-test"
- ]
+ "CRITICAL critical-test",
+ ],
],
[
LogLevel.WARNING,
- ["WARNING warning-test", "ERROR error-test", "CRITICAL critical-test"]
+ ["WARNING warning-test", "ERROR error-test", "CRITICAL critical-test"],
],
[LogLevel.ERROR, ["ERROR error-test", "CRITICAL critical-test"]],
- [LogLevel.CRITICAL, ["CRITICAL critical-test"]]
+ [LogLevel.CRITICAL, ["CRITICAL critical-test"]],
]);
for (const [testCase, messages] of cases.entries()) {
@@ -52,7 +52,7 @@ test(function simpleHandler(): void {
args: [],
datetime: new Date(),
level: level,
- levelName: levelName
+ levelName: levelName,
});
}
@@ -64,7 +64,7 @@ test(function simpleHandler(): void {
test(function testFormatterAsString(): void {
const handler = new TestHandler("DEBUG", {
- formatter: "test {levelName} {msg}"
+ formatter: "test {levelName} {msg}",
});
handler.handle({
@@ -72,7 +72,7 @@ test(function testFormatterAsString(): void {
args: [],
datetime: new Date(),
level: LogLevel.DEBUG,
- levelName: "DEBUG"
+ levelName: "DEBUG",
});
assertEquals(handler.messages, ["test DEBUG Hello, world!"]);
@@ -81,7 +81,7 @@ test(function testFormatterAsString(): void {
test(function testFormatterAsFunction(): void {
const handler = new TestHandler("DEBUG", {
formatter: (logRecord): string =>
- `fn formmatter ${logRecord.levelName} ${logRecord.msg}`
+ `fn formmatter ${logRecord.levelName} ${logRecord.msg}`,
});
handler.handle({
@@ -89,7 +89,7 @@ test(function testFormatterAsFunction(): void {
args: [],
datetime: new Date(),
level: LogLevel.ERROR,
- levelName: "ERROR"
+ levelName: "ERROR",
});
assertEquals(handler.messages, ["fn formmatter ERROR Hello, world!"]);
diff --git a/std/log/levels.ts b/std/log/levels.ts
index 599629f85..be960dd57 100644
--- a/std/log/levels.ts
+++ b/std/log/levels.ts
@@ -5,7 +5,7 @@ export const LogLevel: Record<string, number> = {
INFO: 20,
WARNING: 30,
ERROR: 40,
- CRITICAL: 50
+ CRITICAL: 50,
};
const byLevel = {
@@ -14,7 +14,7 @@ const byLevel = {
[LogLevel.INFO]: "INFO",
[LogLevel.WARNING]: "WARNING",
[LogLevel.ERROR]: "ERROR",
- [LogLevel.CRITICAL]: "CRITICAL"
+ [LogLevel.CRITICAL]: "CRITICAL",
};
export function getLevelByName(name: string): number {
diff --git a/std/log/logger.ts b/std/log/logger.ts
index 99d17ef48..226b8dba6 100644
--- a/std/log/logger.ts
+++ b/std/log/logger.ts
@@ -34,7 +34,7 @@ export class Logger {
args: args,
datetime: new Date(),
level: level,
- levelName: getLevelName(level)
+ levelName: getLevelName(level),
};
this.handlers.forEach((handler): void => {
handler.handle(record);
diff --git a/std/log/logger_test.ts b/std/log/logger_test.ts
index 76ff4cf95..3e8898afa 100644
--- a/std/log/logger_test.ts
+++ b/std/log/logger_test.ts
@@ -67,7 +67,7 @@ test(function logFunctions(): void {
"INFO bar",
"WARNING baz",
"ERROR boo",
- "CRITICAL doo"
+ "CRITICAL doo",
]);
handler = doLog("INFO");
@@ -76,7 +76,7 @@ test(function logFunctions(): void {
"INFO bar",
"WARNING baz",
"ERROR boo",
- "CRITICAL doo"
+ "CRITICAL doo",
]);
handler = doLog("WARNING");
diff --git a/std/log/mod.ts b/std/log/mod.ts
index b89896264..333e90fb9 100644
--- a/std/log/mod.ts
+++ b/std/log/mod.ts
@@ -4,7 +4,7 @@ import {
BaseHandler,
ConsoleHandler,
WriterHandler,
- FileHandler
+ FileHandler,
} from "./handlers.ts";
import { assert } from "../testing/asserts.ts";
@@ -25,28 +25,28 @@ export interface LogConfig {
const DEFAULT_LEVEL = "INFO";
const DEFAULT_CONFIG: LogConfig = {
handlers: {
- default: new ConsoleHandler(DEFAULT_LEVEL)
+ default: new ConsoleHandler(DEFAULT_LEVEL),
},
loggers: {
default: {
level: DEFAULT_LEVEL,
- handlers: ["default"]
- }
- }
+ handlers: ["default"],
+ },
+ },
};
const state = {
handlers: new Map<string, BaseHandler>(),
loggers: new Map<string, Logger>(),
- config: DEFAULT_CONFIG
+ config: DEFAULT_CONFIG,
};
export const handlers = {
BaseHandler,
ConsoleHandler,
WriterHandler,
- FileHandler
+ FileHandler,
};
export function getLogger(name?: string): Logger {
@@ -81,7 +81,7 @@ export const critical = (msg: string, ...args: unknown[]): void =>
export async function setup(config: LogConfig): Promise<void> {
state.config = {
handlers: { ...DEFAULT_CONFIG.handlers, ...config.handlers },
- loggers: { ...DEFAULT_CONFIG.loggers, ...config.loggers }
+ loggers: { ...DEFAULT_CONFIG.loggers, ...config.loggers },
};
// tear down existing handlers
diff --git a/std/log/test.ts b/std/log/test.ts
index d4385968c..858f722e2 100644
--- a/std/log/test.ts
+++ b/std/log/test.ts
@@ -20,7 +20,7 @@ test(async function defaultHandlers(): Promise<void> {
INFO: log.info,
WARNING: log.warning,
ERROR: log.error,
- CRITICAL: log.critical
+ CRITICAL: log.critical,
};
for (const levelName in LogLevel) {
@@ -33,14 +33,14 @@ test(async function defaultHandlers(): Promise<void> {
await log.setup({
handlers: {
- default: handler
+ default: handler,
},
loggers: {
default: {
level: levelName,
- handlers: ["default"]
- }
- }
+ handlers: ["default"],
+ },
+ },
});
logger("foo");
@@ -55,14 +55,14 @@ test(async function getLogger(): Promise<void> {
await log.setup({
handlers: {
- default: handler
+ default: handler,
},
loggers: {
default: {
level: "DEBUG",
- handlers: ["default"]
- }
- }
+ handlers: ["default"],
+ },
+ },
});
const logger = log.getLogger();
@@ -76,14 +76,14 @@ test(async function getLoggerWithName(): Promise<void> {
await log.setup({
handlers: {
- foo: fooHandler
+ foo: fooHandler,
},
loggers: {
bar: {
level: "INFO",
- handlers: ["foo"]
- }
- }
+ handlers: ["foo"],
+ },
+ },
});
const logger = log.getLogger("bar");
@@ -95,7 +95,7 @@ test(async function getLoggerWithName(): Promise<void> {
test(async function getLoggerUnknown(): Promise<void> {
await log.setup({
handlers: {},
- loggers: {}
+ loggers: {},
});
const logger = log.getLogger("nonexistent");
diff --git a/std/manual.md b/std/manual.md
index f073d1508..1e8fefcb1 100644
--- a/std/manual.md
+++ b/std/manual.md
@@ -366,7 +366,7 @@ Example:
```ts
// create subprocess
const p = Deno.run({
- cmd: ["echo", "hello"]
+ cmd: ["echo", "hello"],
});
// await its completion
@@ -398,10 +398,10 @@ const p = Deno.run({
"run",
"--allow-read",
"https://deno.land/std/examples/cat.ts",
- ...fileNames
+ ...fileNames,
],
stdout: "piped",
- stderr: "piped"
+ stderr: "piped",
});
const { code } = await p.status();
@@ -557,7 +557,7 @@ assertion library across a large project. Rather than importing
export {
assert,
assertEquals,
- assertStrContains
+ assertStrContains,
} from "https://deno.land/std/testing/asserts.ts";
```
@@ -676,10 +676,10 @@ TypeScript `"dom"` library:
const [errors, emitted] = await Deno.compile(
"main.ts",
{
- "main.ts": `document.getElementById("foo");\n`
+ "main.ts": `document.getElementById("foo");\n`,
},
{
- lib: ["dom", "esnext"]
+ lib: ["dom", "esnext"],
}
);
```
@@ -716,10 +716,10 @@ lib in the array. For example:
const [errors, emitted] = await Deno.compile(
"main.ts",
{
- "main.ts": `document.getElementById("foo");\n`
+ "main.ts": `document.getElementById("foo");\n`,
},
{
- lib: ["dom", "esnext", "deno.ns"]
+ lib: ["dom", "esnext", "deno.ns"],
}
);
```
@@ -745,7 +745,7 @@ It would compiler without errors like this:
```ts
const [errors, emitted] = await Deno.compile("./main.ts", undefined, {
- lib: ["esnext"]
+ lib: ["esnext"],
});
```
@@ -1059,7 +1059,7 @@ An example of providing sources:
```ts
const [diagnostics, emitMap] = await Deno.compile("/foo.ts", {
"/foo.ts": `import * as bar from "./bar.ts";\nconsole.log(bar);\n`,
- "/bar.ts": `export const bar = "bar";\n`
+ "/bar.ts": `export const bar = "bar";\n`,
});
assert(diagnostics == null); // ensuring no diagnostics are returned
@@ -1104,7 +1104,7 @@ An example of providing sources:
```ts
const [diagnostics, emit] = await Deno.bundle("/foo.ts", {
"/foo.ts": `import * as bar from "./bar.ts";\nconsole.log(bar);\n`,
- "/bar.ts": `export const bar = "bar";\n`
+ "/bar.ts": `export const bar = "bar";\n`,
});
assert(diagnostics == null); // ensuring no diagnostics are returned
@@ -1145,7 +1145,7 @@ An example:
```ts
const result = await Deno.transpileOnly({
- "/foo.ts": `enum Foo { Foo, Bar, Baz };\n`
+ "/foo.ts": `enum Foo { Foo, Bar, Baz };\n`,
});
console.log(result["/foo.ts"].source);
diff --git a/std/media_types/test.ts b/std/media_types/test.ts
index 3a9a7d9fe..c3caf71df 100644
--- a/std/media_types/test.ts
+++ b/std/media_types/test.ts
@@ -8,7 +8,7 @@ import {
extension,
charset,
extensions,
- types
+ types,
} from "./mod.ts";
test(function testLookup(): void {
diff --git a/std/mime/multipart.ts b/std/mime/multipart.ts
index d4bd693fd..a0f40f3b0 100644
--- a/std/mime/multipart.ts
+++ b/std/mime/multipart.ts
@@ -305,7 +305,7 @@ export class MultipartReader {
const ext = extname(p.fileName);
const { file, filepath } = await tempFile(".", {
prefix: "multipart-",
- postfix: ext
+ postfix: ext,
});
try {
const size = await copyN(
@@ -318,7 +318,7 @@ export class MultipartReader {
filename: p.fileName,
type: contentType,
tempfile: filepath,
- size
+ size,
};
} catch (e) {
await remove(filepath);
@@ -328,7 +328,7 @@ export class MultipartReader {
filename: p.fileName,
type: contentType,
content: buf.bytes(),
- size: buf.length
+ size: buf.length,
};
maxMemory -= n;
maxValueBytes -= n;
diff --git a/std/mime/multipart_test.ts b/std/mime/multipart_test.ts
index 7c383d447..9b96a2f4c 100644
--- a/std/mime/multipart_test.ts
+++ b/std/mime/multipart_test.ts
@@ -5,7 +5,7 @@ import {
assert,
assertEquals,
assertThrows,
- assertThrowsAsync
+ assertThrowsAsync,
} from "../testing/asserts.ts";
const { test } = Deno;
import * as path from "../path/mod.ts";
@@ -15,7 +15,7 @@ import {
MultipartWriter,
isFormFile,
matchAfterPrefix,
- scanUntilBoundary
+ scanUntilBoundary,
} from "./multipart.ts";
import { StringWriter } from "../io/writers.ts";
diff --git a/std/node/_fs/_fs_appendFile.ts b/std/node/_fs/_fs_appendFile.ts
index 49a4fc29f..f3b44dd7b 100644
--- a/std/node/_fs/_fs_appendFile.ts
+++ b/std/node/_fs/_fs_appendFile.ts
@@ -55,7 +55,7 @@ export function appendFile(
closeRidIfNecessary(typeof pathOrRid === "string", rid);
callbackFn();
})
- .catch(err => {
+ .catch((err) => {
closeRidIfNecessary(typeof pathOrRid === "string", rid);
callbackFn(err);
});
diff --git a/std/node/_fs/_fs_appendFile_test.ts b/std/node/_fs/_fs_appendFile_test.ts
index 47d552740..ca48dc5d3 100644
--- a/std/node/_fs/_fs_appendFile_test.ts
+++ b/std/node/_fs/_fs_appendFile_test.ts
@@ -15,7 +15,7 @@ test({
Error,
"No callback function supplied"
);
- }
+ },
});
test({
@@ -48,12 +48,12 @@ test({
assertThrows(
() =>
appendFileSync("some/path", "some data", {
- encoding: "made-up-encoding"
+ encoding: "made-up-encoding",
}),
Error,
"Only 'utf8' encoding is currently supported"
);
- }
+ },
});
test({
@@ -63,10 +63,10 @@ test({
const file: Deno.File = await Deno.open(tempFile, {
create: true,
write: true,
- read: true
+ read: true,
});
await new Promise((resolve, reject) => {
- appendFile(file.rid, "hello world", err => {
+ appendFile(file.rid, "hello world", (err) => {
if (err) reject();
else resolve();
});
@@ -82,7 +82,7 @@ test({
Deno.close(file.rid);
await Deno.remove(tempFile);
});
- }
+ },
});
test({
@@ -90,7 +90,7 @@ test({
async fn() {
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
await new Promise((resolve, reject) => {
- appendFile("_fs_appendFile_test_file.txt", "hello world", err => {
+ appendFile("_fs_appendFile_test_file.txt", "hello world", (err) => {
if (err) reject(err);
else resolve();
});
@@ -100,13 +100,13 @@ test({
const data = await Deno.readFile("_fs_appendFile_test_file.txt");
assertEquals(decoder.decode(data), "hello world");
})
- .catch(err => {
+ .catch((err) => {
fail("No error was expected: " + err);
})
.finally(async () => {
await Deno.remove("_fs_appendFile_test_file.txt");
});
- }
+ },
});
test({
@@ -116,7 +116,7 @@ test({
const openResourcesBeforeAppend: Deno.ResourceMap = Deno.resources();
const tempFile: string = await Deno.makeTempFile();
await new Promise((resolve, reject) => {
- appendFile(tempFile, "hello world", { flag: "ax" }, err => {
+ appendFile(tempFile, "hello world", { flag: "ax" }, (err) => {
if (err) reject(err);
else resolve();
});
@@ -130,7 +130,7 @@ test({
.finally(async () => {
await Deno.remove(tempFile);
});
- }
+ },
});
test({
@@ -140,14 +140,14 @@ test({
const file: Deno.File = Deno.openSync(tempFile, {
create: true,
write: true,
- read: true
+ read: true,
});
appendFileSync(file.rid, "hello world");
Deno.close(file.rid);
const data = Deno.readFileSync(tempFile);
assertEquals(decoder.decode(data), "hello world");
Deno.removeSync(tempFile);
- }
+ },
});
test({
@@ -159,7 +159,7 @@ test({
const data = Deno.readFileSync("_fs_appendFile_test_file_sync.txt");
assertEquals(decoder.decode(data), "hello world");
Deno.removeSync("_fs_appendFile_test_file_sync.txt");
- }
+ },
});
test({
@@ -175,5 +175,5 @@ test({
);
assertEquals(Deno.resources(), openResourcesBeforeAppend);
Deno.removeSync(tempFile);
- }
+ },
});
diff --git a/std/node/_fs/_fs_chmod.ts b/std/node/_fs/_fs_chmod.ts
index cecb878ec..0eb01a8a6 100644
--- a/std/node/_fs/_fs_chmod.ts
+++ b/std/node/_fs/_fs_chmod.ts
@@ -24,7 +24,7 @@ export function chmod(
.then(() => {
callback();
})
- .catch(err => {
+ .catch((err) => {
callback(err);
});
}
diff --git a/std/node/_fs/_fs_chmod_test.ts b/std/node/_fs/_fs_chmod_test.ts
index 8d420b3be..a3d814b51 100644
--- a/std/node/_fs/_fs_chmod_test.ts
+++ b/std/node/_fs/_fs_chmod_test.ts
@@ -10,7 +10,7 @@ test({
const tempFile: string = await Deno.makeTempFile();
const originalFileMode: number | null = (await Deno.lstat(tempFile)).mode;
await new Promise((resolve, reject) => {
- chmod(tempFile, 0o777, err => {
+ chmod(tempFile, 0o777, (err) => {
if (err) reject(err);
else resolve();
});
@@ -26,7 +26,7 @@ test({
.finally(() => {
Deno.removeSync(tempFile);
});
- }
+ },
});
test({
@@ -41,5 +41,5 @@ test({
assert(newFileMode && originalFileMode);
assert(newFileMode === 33279 && newFileMode > originalFileMode);
Deno.removeSync(tempFile);
- }
+ },
});
diff --git a/std/node/_fs/_fs_chown.ts b/std/node/_fs/_fs_chown.ts
index 008b30c47..94b7401d0 100644
--- a/std/node/_fs/_fs_chown.ts
+++ b/std/node/_fs/_fs_chown.ts
@@ -23,7 +23,7 @@ export function chown(
.then(() => {
callback();
})
- .catch(err => {
+ .catch((err) => {
callback(err);
});
}
diff --git a/std/node/_fs/_fs_chown_test.ts b/std/node/_fs/_fs_chown_test.ts
index bdf2ae09a..fd31a8c62 100644
--- a/std/node/_fs/_fs_chown_test.ts
+++ b/std/node/_fs/_fs_chown_test.ts
@@ -14,7 +14,7 @@ test({
const originalUserId: number | null = (await Deno.lstat(tempFile)).uid;
const originalGroupId: number | null = (await Deno.lstat(tempFile)).gid;
await new Promise((resolve, reject) => {
- chown(tempFile, originalUserId!, originalGroupId!, err => {
+ chown(tempFile, originalUserId!, originalGroupId!, (err) => {
if (err) reject(err);
else resolve();
});
@@ -31,7 +31,7 @@ test({
.finally(() => {
Deno.removeSync(tempFile);
});
- }
+ },
});
test({
@@ -48,5 +48,5 @@ test({
assertEquals(newUserId, originalUserId);
assertEquals(newGroupId, originalGroupId);
Deno.removeSync(tempFile);
- }
+ },
});
diff --git a/std/node/_fs/_fs_close.ts b/std/node/_fs/_fs_close.ts
index 4ec10eefb..469bdc77b 100644
--- a/std/node/_fs/_fs_close.ts
+++ b/std/node/_fs/_fs_close.ts
@@ -14,7 +14,7 @@ export function close(fd: number, callback: CallbackWithError): void {
.then(() => {
callback();
})
- .catch(err => {
+ .catch((err) => {
callback(err);
});
}
diff --git a/std/node/_fs/_fs_close_test.ts b/std/node/_fs/_fs_close_test.ts
index 7c6dd684c..8bcd662c9 100644
--- a/std/node/_fs/_fs_close_test.ts
+++ b/std/node/_fs/_fs_close_test.ts
@@ -11,7 +11,7 @@ test({
assert(Deno.resources()[file.rid]);
await new Promise((resolve, reject) => {
- close(file.rid, err => {
+ close(file.rid, (err) => {
if (err) reject();
else resolve();
});
@@ -25,7 +25,7 @@ test({
.finally(async () => {
await Deno.remove(tempFile);
});
- }
+ },
});
test({
@@ -38,5 +38,5 @@ test({
closeSync(file.rid);
assert(!Deno.resources()[file.rid]);
Deno.removeSync(tempFile);
- }
+ },
});
diff --git a/std/node/_fs/_fs_dir.ts b/std/node/_fs/_fs_dir.ts
index e3830bb31..c5bb368c9 100644
--- a/std/node/_fs/_fs_dir.ts
+++ b/std/node/_fs/_fs_dir.ts
@@ -30,7 +30,7 @@ export default class Dir {
try {
if (this.initializationOfDirectoryFilesIsRequired()) {
const denoFiles: Deno.FileInfo[] = await Deno.readdir(this.path);
- this.files = denoFiles.map(file => new Dirent(file));
+ this.files = denoFiles.map((file) => new Dirent(file));
}
const nextFile = this.files.pop();
if (nextFile) {
@@ -55,7 +55,7 @@ export default class Dir {
readSync(): Dirent | null {
if (this.initializationOfDirectoryFilesIsRequired()) {
this.files.push(
- ...Deno.readdirSync(this.path).map(file => new Dirent(file))
+ ...Deno.readdirSync(this.path).map((file) => new Dirent(file))
);
}
const dirent: Dirent | undefined = this.files.pop();
diff --git a/std/node/_fs/_fs_dir_test.ts b/std/node/_fs/_fs_dir_test.ts
index be276887b..6ee044391 100644
--- a/std/node/_fs/_fs_dir_test.ts
+++ b/std/node/_fs/_fs_dir_test.ts
@@ -13,21 +13,21 @@ test({
calledBack = true;
});
assert(calledBack);
- }
+ },
});
test({
name: "Closing current directory without callback returns void Promise",
async fn() {
await new Dir(".").close();
- }
+ },
});
test({
name: "Closing current directory synchronously works",
fn() {
new Dir(".").closeSync();
- }
+ },
});
test({
@@ -37,7 +37,7 @@ test({
const enc: Uint8Array = new TextEncoder().encode("std/node");
assertEquals(new Dir(enc).path, "std/node");
- }
+ },
});
test({
@@ -64,7 +64,7 @@ test({
} finally {
Deno.removeSync(testDir);
}
- }
+ },
});
test({
@@ -103,7 +103,7 @@ test({
} finally {
Deno.removeSync(testDir, { recursive: true });
}
- }
+ },
});
test({
@@ -132,7 +132,7 @@ test({
} finally {
Deno.removeSync(testDir, { recursive: true });
}
- }
+ },
});
test({
@@ -158,5 +158,5 @@ test({
} finally {
Deno.removeSync(testDir, { recursive: true });
}
- }
+ },
});
diff --git a/std/node/_fs/_fs_dirent_test.ts b/std/node/_fs/_fs_dirent_test.ts
index 36091d3e1..1b1d38d38 100644
--- a/std/node/_fs/_fs_dirent_test.ts
+++ b/std/node/_fs/_fs_dirent_test.ts
@@ -40,7 +40,7 @@ test({
fileInfo.blocks = 5;
assert(new Dirent(fileInfo).isBlockDevice());
assert(!new Dirent(fileInfo).isCharacterDevice());
- }
+ },
});
test({
@@ -50,7 +50,7 @@ test({
fileInfo.blocks = null;
assert(new Dirent(fileInfo).isCharacterDevice());
assert(!new Dirent(fileInfo).isBlockDevice());
- }
+ },
});
test({
@@ -63,7 +63,7 @@ test({
assert(new Dirent(fileInfo).isDirectory());
assert(!new Dirent(fileInfo).isFile());
assert(!new Dirent(fileInfo).isSymbolicLink());
- }
+ },
});
test({
@@ -76,7 +76,7 @@ test({
assert(!new Dirent(fileInfo).isDirectory());
assert(new Dirent(fileInfo).isFile());
assert(!new Dirent(fileInfo).isSymbolicLink());
- }
+ },
});
test({
@@ -89,7 +89,7 @@ test({
assert(!new Dirent(fileInfo).isDirectory());
assert(!new Dirent(fileInfo).isFile());
assert(new Dirent(fileInfo).isSymbolicLink());
- }
+ },
});
test({
@@ -98,7 +98,7 @@ test({
const fileInfo: FileInfoMock = new FileInfoMock();
fileInfo.name = "my_file";
assertEquals(new Dirent(fileInfo).name, "my_file");
- }
+ },
});
test({
@@ -119,5 +119,5 @@ test({
Error,
"does not yet support"
);
- }
+ },
});
diff --git a/std/node/_fs/_fs_readFile.ts b/std/node/_fs/_fs_readFile.ts
index 05bad6f3d..13e82bfe1 100644
--- a/std/node/_fs/_fs_readFile.ts
+++ b/std/node/_fs/_fs_readFile.ts
@@ -3,7 +3,7 @@
import {
notImplemented,
intoCallbackAPIWithIntercept,
- MaybeEmpty
+ MaybeEmpty,
} from "../_utils.ts";
const { readFile: denoReadFile, readFileSync: denoReadFileSync } = Deno;
diff --git a/std/node/_fs/_fs_readlink.ts b/std/node/_fs/_fs_readlink.ts
index d1cb69f51..1fd7e3c14 100644
--- a/std/node/_fs/_fs_readlink.ts
+++ b/std/node/_fs/_fs_readlink.ts
@@ -2,7 +2,7 @@
import {
intoCallbackAPIWithIntercept,
MaybeEmpty,
- notImplemented
+ notImplemented,
} from "../_utils.ts";
const { readlink: denoReadlink, readlinkSync: denoReadlinkSync } = Deno;
diff --git a/std/node/_fs/_fs_readlink_test.ts b/std/node/_fs/_fs_readlink_test.ts
index 653d1a598..151d3f782 100644
--- a/std/node/_fs/_fs_readlink_test.ts
+++ b/std/node/_fs/_fs_readlink_test.ts
@@ -25,7 +25,7 @@ test({
assertEquals(typeof data, "string");
assertEquals(data as string, oldname);
- }
+ },
});
test({
@@ -43,7 +43,7 @@ test({
assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), oldname);
- }
+ },
});
test({
@@ -53,7 +53,7 @@ test({
const data = readlinkSync(newname);
assertEquals(typeof data, "string");
assertEquals(data as string, oldname);
- }
+ },
});
test({
@@ -63,5 +63,5 @@ test({
const data = readlinkSync(newname, { encoding: "buffer" });
assert(data instanceof Uint8Array);
assertEquals(new TextDecoder().decode(data as Uint8Array), oldname);
- }
+ },
});
diff --git a/std/node/_utils.ts b/std/node/_utils.ts
index f0808e82b..ec89d11a8 100644
--- a/std/node/_utils.ts
+++ b/std/node/_utils.ts
@@ -17,8 +17,8 @@ export function intoCallbackAPI<T>(
...args: any[]
): void {
func(...args)
- .then(value => cb && cb(null, value))
- .catch(err => cb && cb(err, null));
+ .then((value) => cb && cb(null, value))
+ .catch((err) => cb && cb(err, null));
}
export function intoCallbackAPIWithIntercept<T1, T2>(
@@ -30,6 +30,6 @@ export function intoCallbackAPIWithIntercept<T1, T2>(
...args: any[]
): void {
func(...args)
- .then(value => cb && cb(null, interceptor(value)))
- .catch(err => cb && cb(err, null));
+ .then((value) => cb && cb(null, interceptor(value)))
+ .catch((err) => cb && cb(err, null));
}
diff --git a/std/node/events.ts b/std/node/events.ts
index b2f1d6026..aa62e4d43 100644
--- a/std/node/events.ts
+++ b/std/node/events.ts
@@ -219,7 +219,7 @@ export default class EventEmitter {
eventName: string | symbol,
listener: Function
): WrappedFunction {
- const wrapper = function(
+ const wrapper = function (
this: {
eventName: string | symbol;
listener: Function;
@@ -235,7 +235,7 @@ export default class EventEmitter {
eventName: eventName,
listener: listener,
rawListener: (wrapper as unknown) as WrappedFunction,
- context: this
+ context: this,
};
const wrapped = (wrapper.bind(
wrapperContext
@@ -462,7 +462,7 @@ export function on(
}
// Wait until an event happens
- return new Promise(function(resolve, reject) {
+ return new Promise(function (resolve, reject) {
unconsumedPromises.push({ resolve, reject });
});
},
@@ -489,7 +489,7 @@ export function on(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[Symbol.asyncIterator](): any {
return this;
- }
+ },
};
emitter.on(event, eventHandler);
diff --git a/std/node/events_test.ts b/std/node/events_test.ts
index b0b74e499..5960290af 100644
--- a/std/node/events_test.ts
+++ b/std/node/events_test.ts
@@ -3,7 +3,7 @@ import {
assert,
assertEquals,
fail,
- assertThrows
+ assertThrows,
} from "../testing/asserts.ts";
import EventEmitter, { WrappedFunction, once, on } from "./events.ts";
@@ -29,7 +29,7 @@ test({
eventsFired = [];
testEmitter.emit("event");
assertEquals(eventsFired, ["event"]);
- }
+ },
});
test({
@@ -41,7 +41,7 @@ test({
testEmitter.on("removeListener", () => {
eventsFired.push("removeListener");
});
- const eventFunction = function(): void {
+ const eventFunction = function (): void {
eventsFired.push("event");
};
testEmitter.on("event", eventFunction);
@@ -49,7 +49,7 @@ test({
assertEquals(eventsFired, []);
testEmitter.removeListener("event", eventFunction);
assertEquals(eventsFired, ["removeListener"]);
- }
+ },
});
test({
@@ -62,7 +62,7 @@ test({
EventEmitter.defaultMaxListeners = 20;
assertEquals(EventEmitter.defaultMaxListeners, 20);
EventEmitter.defaultMaxListeners = 10; //reset back to original value
- }
+ },
});
test({
@@ -73,7 +73,7 @@ test({
assertEquals(1, testEmitter.listenerCount("event"));
testEmitter.on("event", shouldNeverBeEmitted);
assertEquals(2, testEmitter.listenerCount("event"));
- }
+ },
});
test({
@@ -100,7 +100,7 @@ test({
);
testEmitter.emit("event", 1, 2, 3);
assertEquals(eventsFired, ["event(1)", "event(1, 2)", "event(1, 2, 3)"]);
- }
+ },
});
test({
@@ -112,7 +112,7 @@ test({
const sym = Symbol("symbol");
testEmitter.on(sym, shouldNeverBeEmitted);
assertEquals(testEmitter.eventNames(), ["event", sym]);
- }
+ },
});
test({
@@ -122,7 +122,7 @@ test({
assertEquals(testEmitter.getMaxListeners(), 10);
testEmitter.setMaxListeners(20);
assertEquals(testEmitter.getMaxListeners(), 20);
- }
+ },
});
test({
@@ -135,9 +135,9 @@ test({
testEmitter.on("event", testFunction);
assertEquals(testEmitter.listeners("event"), [
shouldNeverBeEmitted,
- testFunction
+ testFunction,
]);
- }
+ },
});
test({
@@ -148,7 +148,7 @@ test({
assertEquals(testEmitter.listenerCount("event"), 1);
testEmitter.off("event", shouldNeverBeEmitted);
assertEquals(testEmitter.listenerCount("event"), 0);
- }
+ },
});
test({
@@ -159,7 +159,7 @@ test({
.on("event", shouldNeverBeEmitted)
.on("event", shouldNeverBeEmitted);
assertEquals(testEmitter.listenerCount("event"), 2);
- }
+ },
});
test({
@@ -183,7 +183,7 @@ test({
testEmitter.emit("single event");
testEmitter.emit("single event");
assertEquals(eventsFired, ["single event"]);
- }
+ },
});
test({
@@ -203,7 +203,7 @@ test({
});
testEmitter.emit("event");
assertEquals(eventsFired, ["third", "first", "second"]);
- }
+ },
});
test({
@@ -223,7 +223,7 @@ test({
testEmitter.emit("event");
testEmitter.emit("event");
assertEquals(eventsFired, ["third", "first", "second", "first", "second"]);
- }
+ },
});
test({
@@ -242,7 +242,7 @@ test({
assertEquals(testEmitter.listenerCount("event"), 0);
assertEquals(testEmitter.listenerCount("other event"), 0);
- }
+ },
});
test({
@@ -265,7 +265,7 @@ test({
assertEquals(testEmitter.listenerCount("event"), 0);
assertEquals(testEmitter.listenerCount("other event"), 0);
- }
+ },
});
test({
@@ -284,7 +284,7 @@ test({
testEmitter.removeListener("non-existant event", madeUpEvent);
assertEquals(testEmitter.listenerCount("event"), 1);
- }
+ },
});
test({
@@ -307,7 +307,7 @@ test({
eventsProcessed = [];
testEmitter.emit("event");
assertEquals(eventsProcessed, ["A"]);
- }
+ },
});
test({
@@ -330,7 +330,7 @@ test({
(rawListenersForOnceEvent[0] as WrappedFunction).listener,
listenerB
);
- }
+ },
});
test({
@@ -353,7 +353,7 @@ test({
wrappedFn(); // executing the wrapped listener function will remove it from the event
assertEquals(eventsProcessed, ["A"]);
assertEquals(testEmitter.listeners("once-event").length, 0);
- }
+ },
});
test({
@@ -366,7 +366,7 @@ test({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const valueArr: any[] = await once(ee, "event");
assertEquals(valueArr, [42, "foo"]);
- }
+ },
});
test({
@@ -380,7 +380,7 @@ test({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const eventObj: any[] = await once(et, "event");
assert(!eventObj[0].isTrusted);
- }
+ },
});
test({
@@ -402,7 +402,7 @@ test({
Error,
"must be 'an integer'"
);
- }
+ },
});
test({
@@ -440,7 +440,7 @@ test({
});
ee.emit("error");
assertEquals(events, ["errorMonitor event", "error"]);
- }
+ },
});
test({
@@ -468,7 +468,7 @@ test({
}
assertEquals(ee.listenerCount("foo"), 0);
assertEquals(ee.listenerCount("error"), 0);
- }
+ },
});
test({
@@ -493,7 +493,7 @@ test({
assertEquals(err, _err);
}
assertEquals(thrown, true);
- }
+ },
});
test({
@@ -522,7 +522,7 @@ test({
assertEquals(thrown, true);
assertEquals(ee.listenerCount("foo"), 0);
assertEquals(ee.listenerCount("error"), 0);
- }
+ },
});
test({
@@ -548,7 +548,7 @@ test({
assertEquals(ee.listenerCount("foo"), 0);
assertEquals(ee.listenerCount("error"), 0);
- }
+ },
});
test({
@@ -557,7 +557,7 @@ test({
const ee = new EventEmitter();
const iterable = on(ee, "foo");
- setTimeout(function() {
+ setTimeout(function () {
ee.emit("foo", "bar");
ee.emit("foo", 42);
iterable.return();
@@ -566,29 +566,29 @@ test({
const results = await Promise.all([
iterable.next(),
iterable.next(),
- iterable.next()
+ iterable.next(),
]);
assertEquals(results, [
{
value: ["bar"],
- done: false
+ done: false,
},
{
value: [42],
- done: false
+ done: false,
},
{
value: undefined,
- done: true
- }
+ done: true,
+ },
]);
assertEquals(await iterable.next(), {
value: undefined,
- done: true
+ done: true,
});
- }
+ },
});
test({
@@ -620,5 +620,5 @@ test({
assertEquals(expected.length, 0);
assertEquals(ee.listenerCount("foo"), 0);
assertEquals(ee.listenerCount("error"), 0);
- }
+ },
});
diff --git a/std/node/fs.ts b/std/node/fs.ts
index 9135441bb..0681ee5a1 100755
--- a/std/node/fs.ts
+++ b/std/node/fs.ts
@@ -24,5 +24,5 @@ export {
readFile,
readFileSync,
readlink,
- readlinkSync
+ readlinkSync,
};
diff --git a/std/node/module.ts b/std/node/module.ts
index 21992f743..522eaec7e 100644
--- a/std/node/module.ts
+++ b/std/node/module.ts
@@ -108,7 +108,7 @@ class Module {
// Proxy related code removed.
static wrapper = [
"(function (exports, require, module, __filename, __dirname) { ",
- "\n});"
+ "\n});",
];
// Loads a module at the given file path. Returns that module's
@@ -235,7 +235,9 @@ class Module {
const lookupPaths = Module._resolveLookupPaths(request, fakeParent);
for (let j = 0; j < lookupPaths!.length; j++) {
- if (!paths.includes(lookupPaths![j])) paths.push(lookupPaths![j]);
+ if (!paths.includes(lookupPaths![j])) {
+ paths.push(lookupPaths![j]);
+ }
}
}
}
@@ -357,8 +359,9 @@ class Module {
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
- if (!cachedModule.loaded)
+ if (!cachedModule.loaded) {
return getExportsForCircularRequire(cachedModule);
+ }
return cachedModule.exports;
}
delete relativeResolveCache[relResolveCacheIdentifier];
@@ -370,8 +373,9 @@ class Module {
const cachedModule = Module._cache[filename];
if (cachedModule !== undefined) {
updateChildren(parent, cachedModule, true);
- if (!cachedModule.loaded)
+ if (!cachedModule.loaded) {
return getExportsForCircularRequire(cachedModule);
+ }
return cachedModule.exports;
}
@@ -436,8 +440,9 @@ class Module {
if (
from.charCodeAt(from.length - 1) === CHAR_BACKWARD_SLASH &&
from.charCodeAt(from.length - 2) === CHAR_COLON
- )
+ ) {
return [from + "node_modules"];
+ }
const paths = [];
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
@@ -663,7 +668,7 @@ function readPackage(requestPath: string): PackageInfo | null {
name: parsed.name,
main: parsed.main,
exports: parsed.exports,
- type: parsed.type
+ type: parsed.type,
};
packageJsonCache.set(jsonPath, filtered);
return filtered;
@@ -685,11 +690,12 @@ function readPackageScope(
checkPath = checkPath.slice(0, separatorIndex);
if (checkPath.endsWith(path.sep + "node_modules")) return false;
const pjson = readPackage(checkPath);
- if (pjson)
+ if (pjson) {
return {
path: checkPath,
- data: pjson
+ data: pjson,
};
+ }
}
return false;
}
@@ -822,11 +828,13 @@ function applyExports(basePath: string, expansion: string): string {
const mappingKey = `.${expansion}`;
let pkgExports = readPackageExports(basePath);
- if (pkgExports === undefined || pkgExports === null)
+ if (pkgExports === undefined || pkgExports === null) {
return path.resolve(basePath, mappingKey);
+ }
- if (isConditionalDotExportSugar(pkgExports, basePath))
+ if (isConditionalDotExportSugar(pkgExports, basePath)) {
pkgExports = { ".": pkgExports };
+ }
if (typeof pkgExports === "object") {
if (pkgExports.hasOwnProperty(mappingKey)) {
@@ -1005,11 +1013,12 @@ const CircularRequirePrototypeWarningProxy = new Proxy(
},
getOwnPropertyDescriptor(target, prop): PropertyDescriptor | undefined {
- if (target.hasOwnProperty(prop))
+ if (target.hasOwnProperty(prop)) {
return Object.getOwnPropertyDescriptor(target, prop);
+ }
emitCircularRequireWarning(prop);
return undefined;
- }
+ },
}
);
@@ -1230,16 +1239,21 @@ function pathToFileURL(filepath: string): URL {
(filePathLast === CHAR_FORWARD_SLASH ||
(isWindows && filePathLast === CHAR_BACKWARD_SLASH)) &&
resolved[resolved.length - 1] !== path.sep
- )
+ ) {
resolved += "/";
+ }
const outURL = new URL("file://");
if (resolved.includes("%")) resolved = resolved.replace(percentRegEx, "%25");
// In posix, "/" is a valid character in paths
- if (!isWindows && resolved.includes("\\"))
+ if (!isWindows && resolved.includes("\\")) {
resolved = resolved.replace(backslashRegEx, "%5C");
- if (resolved.includes("\n")) resolved = resolved.replace(newlineRegEx, "%0A");
- if (resolved.includes("\r"))
+ }
+ if (resolved.includes("\n")) {
+ resolved = resolved.replace(newlineRegEx, "%0A");
+ }
+ if (resolved.includes("\r")) {
resolved = resolved.replace(carriageReturnRegEx, "%0D");
+ }
if (resolved.includes("\t")) resolved = resolved.replace(tabRegEx, "%09");
outURL.pathname = resolved;
return outURL;
diff --git a/std/node/os.ts b/std/node/os.ts
index 4bc70d1ff..7c61e910b 100644
--- a/std/node/os.ts
+++ b/std/node/os.ts
@@ -219,7 +219,7 @@ export const constants = {
signals: Deno.Signal,
priority: {
// see https://nodejs.org/docs/latest-v12.x/api/os.html#os_priority_constants
- }
+ },
};
export const EOL = Deno.build.os == "win" ? fsEOL.CRLF : fsEOL.LF;
diff --git a/std/node/os_test.ts b/std/node/os_test.ts
index a73a2d4e9..f0b9ca79d 100644
--- a/std/node/os_test.ts
+++ b/std/node/os_test.ts
@@ -6,42 +6,42 @@ test({
name: "build architecture is a string",
fn() {
assertEquals(typeof os.arch(), "string");
- }
+ },
});
test({
name: "home directory is a string",
fn() {
assertEquals(typeof os.homedir(), "string");
- }
+ },
});
test({
name: "tmp directory is a string",
fn() {
assertEquals(typeof os.tmpdir(), "string");
- }
+ },
});
test({
name: "hostname is a string",
fn() {
assertEquals(typeof os.hostname(), "string");
- }
+ },
});
test({
name: "platform is a string",
fn() {
assertEquals(typeof os.platform(), "string");
- }
+ },
});
test({
name: "release is a string",
fn() {
assertEquals(typeof os.release(), "string");
- }
+ },
});
test({
@@ -61,7 +61,7 @@ test({
Error,
"must be >= -2147483648 && <= 2147483647"
);
- }
+ },
});
test({
@@ -81,7 +81,7 @@ test({
Error,
"pid must be >= -2147483648 && <= 2147483647"
);
- }
+ },
});
test({
@@ -115,7 +115,7 @@ test({
Error,
"priority must be >= -20 && <= 19"
);
- }
+ },
});
test({
@@ -150,7 +150,7 @@ test({
Error,
"priority must be >= -20 && <= 19"
);
- }
+ },
});
test({
@@ -160,21 +160,21 @@ test({
assertEquals(os.constants.signals.SIGKILL, Deno.Signal.SIGKILL);
assertEquals(os.constants.signals.SIGCONT, Deno.Signal.SIGCONT);
assertEquals(os.constants.signals.SIGXFSZ, Deno.Signal.SIGXFSZ);
- }
+ },
});
test({
name: "EOL is as expected",
fn() {
assert(os.EOL == "\r\n" || os.EOL == "\n");
- }
+ },
});
test({
name: "Endianness is determined",
fn() {
assert(["LE", "BE"].includes(os.endianness()));
- }
+ },
});
test({
@@ -185,7 +185,7 @@ test({
assertEquals(typeof result[0], "number");
assertEquals(typeof result[1], "number");
assertEquals(typeof result[2], "number");
- }
+ },
});
test({
@@ -196,7 +196,7 @@ test({
assertEquals(`${os.homedir}`, os.homedir());
assertEquals(`${os.hostname}`, os.hostname());
assertEquals(`${os.platform}`, os.platform());
- }
+ },
});
test({
@@ -265,5 +265,5 @@ test({
Error,
"Not implemented"
);
- }
+ },
});
diff --git a/std/node/process.ts b/std/node/process.ts
index 35de23b88..89d383e8e 100644
--- a/std/node/process.ts
+++ b/std/node/process.ts
@@ -4,7 +4,7 @@ const version = `v${Deno.version.deno}`;
const versions = {
node: Deno.version.deno,
- ...Deno.version
+ ...Deno.version,
};
const osToPlatform = (os: Deno.OperatingSystem): string =>
@@ -38,5 +38,5 @@ export const process = {
get argv(): string[] {
// Deno.execPath() also requires --allow-env
return [Deno.execPath(), ...Deno.args];
- }
+ },
};
diff --git a/std/node/process_test.ts b/std/node/process_test.ts
index f44143acb..b9d5388ea 100644
--- a/std/node/process_test.ts
+++ b/std/node/process_test.ts
@@ -14,7 +14,7 @@ test({
assert(process.cwd().match(/\Wnode$/));
process.chdir("..");
assert(process.cwd().match(/\Wstd$/));
- }
+ },
});
test({
@@ -30,7 +30,7 @@ test({
// "The system cannot find the file specified. (os error 2)" so "file" is
// the only common string here.
);
- }
+ },
});
test({
@@ -40,14 +40,14 @@ test({
assertEquals(typeof process.version, "string");
assertEquals(typeof process.versions, "object");
assertEquals(typeof process.versions.node, "string");
- }
+ },
});
test({
name: "process.platform",
fn() {
assertEquals(typeof process.platform, "string");
- }
+ },
});
test({
@@ -56,7 +56,7 @@ test({
assertEquals(typeof process.arch, "string");
// TODO(rsp): make sure that the arch strings should be the same in Node and Deno:
assertEquals(process.arch, Deno.build.arch);
- }
+ },
});
test({
@@ -64,7 +64,7 @@ test({
fn() {
assertEquals(typeof process.pid, "number");
assertEquals(process.pid, Deno.pid);
- }
+ },
});
test({
@@ -78,7 +78,7 @@ test({
Error,
"implemented"
);
- }
+ },
});
test({
@@ -90,12 +90,12 @@ test({
"deno included in the file name of argv[0]"
);
// we cannot test for anything else (we see test runner arguments here)
- }
+ },
});
test({
name: "process.env",
fn() {
assertEquals(typeof process.env.PATH, "string");
- }
+ },
});
diff --git a/std/node/querystring.ts b/std/node/querystring.ts
index fc5a00a13..427183bf0 100644
--- a/std/node/querystring.ts
+++ b/std/node/querystring.ts
@@ -13,7 +13,7 @@ export function parse(
): { [key: string]: string[] | string } {
const entries = str
.split(sep)
- .map(entry => entry.split(eq).map(decodeURIComponent));
+ .map((entry) => entry.split(eq).map(decodeURIComponent));
const final: { [key: string]: string[] | string } = {};
let i = 0;
diff --git a/std/node/querystring_test.ts b/std/node/querystring_test.ts
index d8cb1ec35..0a37eee6b 100644
--- a/std/node/querystring_test.ts
+++ b/std/node/querystring_test.ts
@@ -10,11 +10,11 @@ test({
a: "hello",
b: 5,
c: true,
- d: ["foo", "bar"]
+ d: ["foo", "bar"],
}),
"a=hello&b=5&c=true&d=foo&d=bar"
);
- }
+ },
});
test({
@@ -24,7 +24,7 @@ test({
a: "hello",
b: "5",
c: "true",
- d: ["foo", "bar"]
+ d: ["foo", "bar"],
});
- }
+ },
});
diff --git a/std/node/tests/cjs/cjs_builtin.js b/std/node/tests/cjs/cjs_builtin.js
index 3d182981a..d821d2558 100644
--- a/std/node/tests/cjs/cjs_builtin.js
+++ b/std/node/tests/cjs/cjs_builtin.js
@@ -6,5 +6,5 @@ const path = require("path");
module.exports = {
readFileSync: fs.readFileSync,
isNull: util.isNull,
- extname: path.extname
+ extname: path.extname,
};
diff --git a/std/node/tests/node_modules/left-pad/index.js b/std/node/tests/node_modules/left-pad/index.js
index e90aec35d..8501bca1b 100644
--- a/std/node/tests/node_modules/left-pad/index.js
+++ b/std/node/tests/node_modules/left-pad/index.js
@@ -3,37 +3,37 @@
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details. */
-'use strict';
+"use strict";
module.exports = leftPad;
var cache = [
- '',
- ' ',
- ' ',
- ' ',
- ' ',
- ' ',
- ' ',
- ' ',
- ' ',
- ' '
+ "",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " ",
+ " "
];
-function leftPad (str, len, ch) {
+function leftPad(str, len, ch) {
// convert `str` to a `string`
- str = str + '';
+ str = str + "";
// `len` is the `pad`'s length now
len = len - str.length;
// doesn't need to pad
if (len <= 0) return str;
// `ch` defaults to `' '`
- if (!ch && ch !== 0) ch = ' ';
+ if (!ch && ch !== 0) ch = " ";
// convert `ch` to a `string` cuz it could be a number
- ch = ch + '';
+ ch = ch + "";
// cache common use cases
- if (ch === ' ' && len < 10) return cache[len] + str;
+ if (ch === " " && len < 10) return cache[len] + str;
// `pad` starts with an empty string
- var pad = '';
+ var pad = "";
// loop
while (true) {
// add `ch` to `pad` if `len` is odd
diff --git a/std/node/util_test.ts b/std/node/util_test.ts
index 751dba57e..05cec15df 100644
--- a/std/node/util_test.ts
+++ b/std/node/util_test.ts
@@ -11,7 +11,7 @@ test({
assert(util.isBoolean(false));
assert(!util.isBoolean("deno"));
assert(!util.isBoolean("true"));
- }
+ },
});
test({
@@ -22,7 +22,7 @@ test({
assert(!util.isNull(n));
assert(!util.isNull(0));
assert(!util.isNull({}));
- }
+ },
});
test({
@@ -33,7 +33,7 @@ test({
assert(util.isNullOrUndefined(n));
assert(!util.isNullOrUndefined({}));
assert(!util.isNullOrUndefined("undefined"));
- }
+ },
});
test({
@@ -43,7 +43,7 @@ test({
assert(util.isNumber(new Number(666)));
assert(!util.isNumber("999"));
assert(!util.isNumber(null));
- }
+ },
});
test({
@@ -52,7 +52,7 @@ test({
assert(util.isString("deno"));
assert(util.isString(new String("DIO")));
assert(!util.isString(1337));
- }
+ },
});
test({
@@ -61,7 +61,7 @@ test({
assert(util.isSymbol(Symbol()));
assert(!util.isSymbol(123));
assert(!util.isSymbol("string"));
- }
+ },
});
test({
@@ -71,7 +71,7 @@ test({
assert(util.isUndefined(t));
assert(!util.isUndefined("undefined"));
assert(!util.isUndefined({}));
- }
+ },
});
test({
@@ -81,7 +81,7 @@ test({
assert(util.isObject(dio));
assert(util.isObject(new RegExp(/Toki Wo Tomare/)));
assert(!util.isObject("Jotaro"));
- }
+ },
});
test({
@@ -93,17 +93,17 @@ test({
assert(util.isError(java));
assert(util.isError(nodejs));
assert(!util.isError(deno));
- }
+ },
});
test({
name: "[util] isFunction",
fn() {
- const f = function(): void {};
+ const f = function (): void {};
assert(util.isFunction(f));
assert(!util.isFunction({}));
assert(!util.isFunction(new RegExp(/f/)));
- }
+ },
});
test({
@@ -113,7 +113,7 @@ test({
assert(util.isRegExp(/fuManchu/));
assert(!util.isRegExp({ evil: "eye" }));
assert(!util.isRegExp(null));
- }
+ },
});
test({
@@ -122,5 +122,5 @@ test({
assert(util.isArray([]));
assert(!util.isArray({ yaNo: "array" }));
assert(!util.isArray(null));
- }
+ },
});
diff --git a/std/path/extname_test.ts b/std/path/extname_test.ts
index d9e14bb48..16ca7a2f9 100644
--- a/std/path/extname_test.ts
+++ b/std/path/extname_test.ts
@@ -49,11 +49,11 @@ const pairs = [
["file/", ""],
["file//", ""],
["file./", "."],
- ["file.//", "."]
+ ["file.//", "."],
];
test(function extname() {
- pairs.forEach(function(p) {
+ pairs.forEach(function (p) {
const input = p[0];
const expected = p[1];
assertEquals(expected, path.posix.extname(input));
@@ -71,7 +71,7 @@ test(function extname() {
});
test(function extnameWin32() {
- pairs.forEach(function(p) {
+ pairs.forEach(function (p) {
const input = p[0].replace(slashRE, "\\");
const expected = p[1];
assertEquals(expected, path.win32.extname(input));
diff --git a/std/path/glob.ts b/std/path/glob.ts
index 8eb106b25..a11865c26 100644
--- a/std/path/glob.ts
+++ b/std/path/glob.ts
@@ -44,7 +44,7 @@ export function globToRegExp(
extended,
globstar,
strict: false,
- filepath: true
+ filepath: true,
});
assert(result.path != null);
return result.path.regex;
diff --git a/std/path/glob_test.ts b/std/path/glob_test.ts
index d8da1a47b..8c49adeca 100644
--- a/std/path/glob_test.ts
+++ b/std/path/glob_test.ts
@@ -32,17 +32,17 @@ test({
);
assertEquals(
globToRegExp(join("unicorn", "!(sleeping)", "bathroom.ts"), {
- extended: true
+ extended: true,
}).test(join("unicorn", "flying", "bathroom.ts")),
true
);
assertEquals(
globToRegExp(join("unicorn", "(!sleeping)", "bathroom.ts"), {
- extended: true
+ extended: true,
}).test(join("unicorn", "sleeping", "bathroom.ts")),
false
);
- }
+ },
});
testWalk(
@@ -55,7 +55,7 @@ testWalk(
},
async function globInWalkWildcard(): Promise<void> {
const arr = await walkArray(".", {
- match: [globToRegExp(join("*", "*.ts"))]
+ match: [globToRegExp(join("*", "*.ts"))],
});
assertEquals(arr.length, 2);
assertEquals(arr[0], "a/x.ts");
@@ -74,9 +74,9 @@ testWalk(
match: [
globToRegExp(join("a", "**", "*.ts"), {
flags: "g",
- globstar: true
- })
- ]
+ globstar: true,
+ }),
+ ],
});
assertEquals(arr.length, 1);
assertEquals(arr[0], "a/yo/x.ts");
@@ -98,9 +98,9 @@ testWalk(
match: [
globToRegExp(join("a", "+(raptor|deno)", "*.ts"), {
flags: "g",
- extended: true
- })
- ]
+ extended: true,
+ }),
+ ],
});
assertEquals(arr.length, 2);
assertEquals(arr[0], "a/deno/x.ts");
@@ -116,7 +116,7 @@ testWalk(
},
async function globInWalkWildcardExtension(): Promise<void> {
const arr = await walkArray(".", {
- match: [globToRegExp("x.*", { flags: "g", globstar: true })]
+ match: [globToRegExp("x.*", { flags: "g", globstar: true })],
});
assertEquals(arr.length, 2);
assertEquals(arr[0], "x.js");
@@ -236,7 +236,7 @@ test({
assert(!isGlob("\\a/b/c/\\[a-z\\].js"));
assert(!isGlob("abc/\\(aaa|bbb).js"));
assert(!isGlob("abc/\\?.js"));
- }
+ },
});
test(function normalizeGlobGlobstar(): void {
diff --git a/std/path/globrex.ts b/std/path/globrex.ts
index 695294834..0fe833a52 100644
--- a/std/path/globrex.ts
+++ b/std/path/globrex.ts
@@ -54,7 +54,7 @@ export function globrex(
globstar = false,
strict = false,
filepath = false,
- flags = ""
+ flags = "",
}: GlobrexOptions = {}
): GlobrexResult {
const sepPattern = new RegExp(`^${SEP}${strict ? "" : "+"}$`);
@@ -319,7 +319,7 @@ export function globrex(
globstar: new RegExp(
!flags.includes("g") ? `^${GLOBSTAR_SEGMENT}$` : GLOBSTAR_SEGMENT,
flags
- )
+ ),
};
}
diff --git a/std/path/globrex_test.ts b/std/path/globrex_test.ts
index 29f039837..27541a5c8 100644
--- a/std/path/globrex_test.ts
+++ b/std/path/globrex_test.ts
@@ -34,7 +34,7 @@ test({
t.equal(typeof globrex, "function", "constructor is a typeof function");
t.equal(res instanceof Object, true, "returns object");
t.equal(res.regex.toString(), "/^.*\\.js$/", "returns regex object");
- }
+ },
});
test({
@@ -64,7 +64,7 @@ test({
true,
"match zero characters"
);
- }
+ },
});
test({
@@ -72,7 +72,7 @@ test({
fn(): void {
t.equal(
match("*.min.js", "http://example.com/jquery.min.js", {
- globstar: false
+ globstar: false,
}),
true,
"complex match"
@@ -84,7 +84,7 @@ test({
);
t.equal(
match("*/js/*.js", "http://example.com/js/jquery.min.js", {
- globstar: false
+ globstar: false,
}),
true,
"complex match"
@@ -171,11 +171,11 @@ test({
t.equal(match("/js*jq*.js", "http://example.com/js/jquery.min.js"), false);
t.equal(
match("/js*jq*.js", "http://example.com/js/jquery.min.js", {
- flags: "g"
+ flags: "g",
}),
true
);
- }
+ },
});
test({
@@ -215,7 +215,7 @@ test({
tester(true);
tester(false);
- }
+ },
});
test({
@@ -246,7 +246,7 @@ test({
tester(true);
tester(false);
- }
+ },
});
test({
@@ -304,7 +304,7 @@ test({
match("[[:digit:]b]/bar.txt", "a/bar.txt", { extended: true }),
false
);
- }
+ },
});
test({
@@ -320,7 +320,7 @@ test({
match("foo{bar,baaz}", "foobaaz", {
extended: true,
globstar,
- flag: "g"
+ flag: "g",
}),
true
);
@@ -328,7 +328,7 @@ test({
match("foo{bar,baaz}", "foobar", {
extended: true,
globstar,
- flag: "g"
+ flag: "g",
}),
true
);
@@ -336,7 +336,7 @@ test({
match("foo{bar,baaz}", "foobuzz", {
extended: true,
globstar,
- flag: "g"
+ flag: "g",
}),
false
);
@@ -344,7 +344,7 @@ test({
match("foo{bar,b*z}", "foobuzz", {
extended: true,
globstar,
- flag: "g"
+ flag: "g",
}),
true
);
@@ -352,7 +352,7 @@ test({
tester(true);
tester(false);
- }
+ },
});
test({
@@ -444,7 +444,7 @@ test({
tester(true);
tester(false);
- }
+ },
});
test({
@@ -471,7 +471,7 @@ test({
match("http://foo.com/**", "http://foo.com/bar/baz/jquery.min.js", {
extended: true,
globstar,
- flags: "g"
+ flags: "g",
}),
true
);
@@ -479,7 +479,7 @@ test({
tester(true);
tester(false);
- }
+ },
});
test({
@@ -496,7 +496,7 @@ test({
tester(true);
tester(false);
- }
+ },
});
test({
@@ -574,25 +574,25 @@ test({
t.equal(
match("http://foo.com/*", "http://foo.com/bar/baz/jquery.min.js", {
extended: true,
- globstar: true
+ globstar: true,
}),
false
);
t.equal(
match("http://foo.com/*", "http://foo.com/bar/baz/jquery.min.js", {
- globstar: true
+ globstar: true,
}),
false
);
t.equal(
match("http://foo.com/*", "http://foo.com/bar/baz/jquery.min.js", {
- globstar: false
+ globstar: false,
}),
true
);
t.equal(
match("http://foo.com/**", "http://foo.com/bar/baz/jquery.min.js", {
- globstar: true
+ globstar: true,
}),
true
);
@@ -636,7 +636,7 @@ test({
),
false
);
- }
+ },
});
test({
@@ -689,7 +689,7 @@ test({
match("?(ba[!zr]|qux)baz.txt", "bazbaz.txt", { extended: true }),
false
);
- }
+ },
});
test({
@@ -715,18 +715,18 @@ test({
t.equal(
match("*(foo|bar)/**/*.txt", "foo/hello/world/bar.txt", {
extended: true,
- globstar: true
+ globstar: true,
}),
true
);
t.equal(
match("*(foo|bar)/**/*.txt", "foo/world/bar.txt", {
extended: true,
- globstar: true
+ globstar: true,
}),
true
);
- }
+ },
});
test({
@@ -736,7 +736,7 @@ test({
t.equal(match("+foo.txt", "+foo.txt", { extended: true }), true);
t.equal(match("+(foo).txt", ".txt", { extended: true }), false);
t.equal(match("+(foo|bar).txt", "foobar.txt", { extended: true }), true);
- }
+ },
});
test({
@@ -757,7 +757,7 @@ test({
match("@(foo|baz)bar.txt", "toofoobar.txt", { extended: true }),
false
);
- }
+ },
});
test({
@@ -774,7 +774,7 @@ test({
match("!({foo,bar})baz.txt", "foobaz.txt", { extended: true }),
false
);
- }
+ },
});
test({
@@ -783,7 +783,7 @@ test({
t.equal(match("foo//bar.txt", "foo/bar.txt"), true);
t.equal(match("foo///bar.txt", "foo/bar.txt"), true);
t.equal(match("foo///bar.txt", "foo/bar.txt", { strict: true }), false);
- }
+ },
});
test({
@@ -791,7 +791,7 @@ test({
fn(): void {
t.equal(
match("**/*/?yfile.{md,js,txt}", "foo/bar/baz/myfile.md", {
- extended: true
+ extended: true,
}),
true
);
@@ -823,5 +823,5 @@ test({
match("[[:digit:]_.]/file.js", "z/file.js", { extended: true }),
false
);
- }
+ },
});
diff --git a/std/path/join_test.ts b/std/path/join_test.ts
index a73cf3679..d9a38fb82 100644
--- a/std/path/join_test.ts
+++ b/std/path/join_test.ts
@@ -53,7 +53,7 @@ const joinTests =
[["/", "//foo"], "/foo"],
[["/", "", "/foo"], "/foo"],
[["", "/", "foo"], "/foo"],
- [["", "/", "/foo"], "/foo"]
+ [["", "/", "/foo"], "/foo"],
];
// Windows-specific join tests
@@ -103,11 +103,11 @@ const windowsJoinTests = [
[["c:.", "/"], "c:.\\"],
[["c:.", "file"], "c:file"],
[["c:", "/"], "c:\\"],
- [["c:", "file"], "c:\\file"]
+ [["c:", "file"], "c:\\file"],
];
test(function join() {
- joinTests.forEach(function(p) {
+ joinTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.posix.join.apply(null, _p);
assertEquals(actual, p[1]);
@@ -115,12 +115,12 @@ test(function join() {
});
test(function joinWin32() {
- joinTests.forEach(function(p) {
+ joinTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.win32.join.apply(null, _p).replace(backslashRE, "/");
assertEquals(actual, p[1]);
});
- windowsJoinTests.forEach(function(p) {
+ windowsJoinTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.win32.join.apply(null, _p);
assertEquals(actual, p[1]);
diff --git a/std/path/parse_format_test.ts b/std/path/parse_format_test.ts
index 0a7e83bba..60be3c9a1 100644
--- a/std/path/parse_format_test.ts
+++ b/std/path/parse_format_test.ts
@@ -24,15 +24,14 @@ const winPaths = [
["C:\\", "C:\\"],
["C:\\abc", "C:\\"],
["", ""],
-
// unc
["\\\\server\\share\\file_path", "\\\\server\\share\\"],
[
"\\\\server two\\shared folder\\file path.zip",
- "\\\\server two\\shared folder\\"
+ "\\\\server two\\shared folder\\",
],
["\\\\teela\\admin$\\system32", "\\\\teela\\admin$\\"],
- ["\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\"]
+ ["\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\"],
];
const winSpecialCaseParseTests = [["/foo/bar", { root: "/" }]];
@@ -44,7 +43,7 @@ const winSpecialCaseFormatTests = [
[{ name: "index", ext: ".html" }, "index.html"],
[{ dir: "some\\dir", name: "index", ext: ".html" }, "some\\dir\\index.html"],
[{ root: "C:\\", name: "index", ext: ".html" }, "C:\\index.html"],
- [{}, ""]
+ [{}, ""],
];
const unixPaths = [
@@ -68,7 +67,7 @@ const unixPaths = [
["/.", "/"],
["/.foo", "/"],
["/.foo.bar", "/"],
- ["/foo/bar.baz", "/"]
+ ["/foo/bar.baz", "/"],
];
const unixSpecialCaseFormatTests = [
@@ -78,11 +77,11 @@ const unixSpecialCaseFormatTests = [
[{ name: "index", ext: ".html" }, "index.html"],
[{ dir: "some/dir", name: "index", ext: ".html" }, "some/dir/index.html"],
[{ root: "/", name: "index", ext: ".html" }, "/index.html"],
- [{}, ""]
+ [{}, ""],
];
function checkParseFormat(path: any, paths: any): void {
- paths.forEach(function(p: Array<Record<string, unknown>>) {
+ paths.forEach(function (p: Array<Record<string, unknown>>) {
const element = p[0];
const output = path.parse(element);
assertEquals(typeof output.root, "string");
@@ -98,18 +97,18 @@ function checkParseFormat(path: any, paths: any): void {
}
function checkSpecialCaseParseFormat(path: any, testCases: any): void {
- testCases.forEach(function(testCase: Array<Record<string, unknown>>) {
+ testCases.forEach(function (testCase: Array<Record<string, unknown>>) {
const element = testCase[0];
const expect = testCase[1];
const output = path.parse(element);
- Object.keys(expect).forEach(function(key) {
+ Object.keys(expect).forEach(function (key) {
assertEquals(output[key], expect[key]);
});
});
}
function checkFormat(path: any, testCases: unknown[][]): void {
- testCases.forEach(function(testCase) {
+ testCases.forEach(function (testCase) {
assertEquals(path.format(testCase[0]), testCase[1]);
});
}
@@ -138,7 +137,7 @@ const windowsTrailingTests = [
["\\\\", { root: "\\", dir: "\\", base: "", ext: "", name: "" }],
[
"c:\\foo\\\\\\",
- { root: "c:\\", dir: "c:\\", base: "foo", ext: "", name: "foo" }
+ { root: "c:\\", dir: "c:\\", base: "foo", ext: "", name: "foo" },
],
[
"D:\\foo\\\\\\bar.baz",
@@ -147,9 +146,9 @@ const windowsTrailingTests = [
dir: "D:\\foo\\\\",
base: "bar.baz",
ext: ".baz",
- name: "bar"
- }
- ]
+ name: "bar",
+ },
+ ],
];
const posixTrailingTests = [
@@ -159,12 +158,12 @@ const posixTrailingTests = [
["/foo///", { root: "/", dir: "/", base: "foo", ext: "", name: "foo" }],
[
"/foo///bar.baz",
- { root: "/", dir: "/foo//", base: "bar.baz", ext: ".baz", name: "bar" }
- ]
+ { root: "/", dir: "/foo//", base: "bar.baz", ext: ".baz", name: "bar" },
+ ],
];
test(function parseTrailingWin32() {
- windowsTrailingTests.forEach(function(p) {
+ windowsTrailingTests.forEach(function (p) {
const actual = path.win32.parse(p[0] as string);
const expected = p[1];
assertEquals(actual, expected);
@@ -172,7 +171,7 @@ test(function parseTrailingWin32() {
});
test(function parseTrailing() {
- posixTrailingTests.forEach(function(p) {
+ posixTrailingTests.forEach(function (p) {
const actual = path.posix.parse(p[0] as string);
const expected = p[1];
assertEquals(actual, expected);
diff --git a/std/path/posix.ts b/std/path/posix.ts
index 4377fd542..ba4cf7499 100644
--- a/std/path/posix.ts
+++ b/std/path/posix.ts
@@ -9,7 +9,7 @@ import {
assertPath,
normalizeString,
isPosixPathSeparator,
- _format
+ _format,
} from "./utils.ts";
export const sep = "/";
@@ -205,8 +205,9 @@ export function dirname(path: string): string {
}
export function basename(path: string, ext = ""): string {
- if (ext !== undefined && typeof ext !== "string")
+ if (ext !== undefined && typeof ext !== "string") {
throw new TypeError('"ext" argument must be a string');
+ }
assertPath(path);
let start = 0;
diff --git a/std/path/relative_test.ts b/std/path/relative_test.ts
index 3fe5aab4b..af5896236 100644
--- a/std/path/relative_test.ts
+++ b/std/path/relative_test.ts
@@ -6,58 +6,52 @@ import { assertEquals } from "../testing/asserts.ts";
import * as path from "./mod.ts";
const relativeTests = {
- win32:
- // arguments result
- [
- ["c:/blah\\blah", "d:/games", "d:\\games"],
- ["c:/aaaa/bbbb", "c:/aaaa", ".."],
- ["c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"],
- ["c:/aaaa/bbbb", "c:/aaaa/bbbb", ""],
- ["c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"],
- ["c:/aaaa/", "c:/aaaa/cccc", "cccc"],
- ["c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"],
- ["c:/aaaa/bbbb", "d:\\", "d:\\"],
- ["c:/AaAa/bbbb", "c:/aaaa/bbbb", ""],
- ["c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"],
- ["C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."],
- [
- "C:\\foo\\test",
- "C:\\foo\\test\\bar\\package.json",
- "bar\\package.json"
- ],
- ["C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"],
- ["C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"],
- ["\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"],
- ["\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."],
- ["\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"],
- ["\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"],
- ["C:\\baz-quux", "C:\\baz", "..\\baz"],
- ["C:\\baz", "C:\\baz-quux", "..\\baz-quux"],
- ["\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz"],
- ["\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux"],
- ["C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"],
- ["\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"]
- ],
- posix:
- // arguments result
- [
- ["/var/lib", "/var", ".."],
- ["/var/lib", "/bin", "../../bin"],
- ["/var/lib", "/var/lib", ""],
- ["/var/lib", "/var/apache", "../apache"],
- ["/var/", "/var/lib", "lib"],
- ["/", "/var/lib", "var/lib"],
- ["/foo/test", "/foo/test/bar/package.json", "bar/package.json"],
- ["/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."],
- ["/foo/bar/baz-quux", "/foo/bar/baz", "../baz"],
- ["/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"],
- ["/baz-quux", "/baz", "../baz"],
- ["/baz", "/baz-quux", "../baz-quux"]
- ]
+ // arguments result
+ win32: [
+ ["c:/blah\\blah", "d:/games", "d:\\games"],
+ ["c:/aaaa/bbbb", "c:/aaaa", ".."],
+ ["c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"],
+ ["c:/aaaa/bbbb", "c:/aaaa/bbbb", ""],
+ ["c:/aaaa/bbbb", "c:/aaaa/cccc", "..\\cccc"],
+ ["c:/aaaa/", "c:/aaaa/cccc", "cccc"],
+ ["c:/", "c:\\aaaa\\bbbb", "aaaa\\bbbb"],
+ ["c:/aaaa/bbbb", "d:\\", "d:\\"],
+ ["c:/AaAa/bbbb", "c:/aaaa/bbbb", ""],
+ ["c:/aaaaa/", "c:/aaaa/cccc", "..\\aaaa\\cccc"],
+ ["C:\\foo\\bar\\baz\\quux", "C:\\", "..\\..\\..\\.."],
+ ["C:\\foo\\test", "C:\\foo\\test\\bar\\package.json", "bar\\package.json"],
+ ["C:\\foo\\bar\\baz-quux", "C:\\foo\\bar\\baz", "..\\baz"],
+ ["C:\\foo\\bar\\baz", "C:\\foo\\bar\\baz-quux", "..\\baz-quux"],
+ ["\\\\foo\\bar", "\\\\foo\\bar\\baz", "baz"],
+ ["\\\\foo\\bar\\baz", "\\\\foo\\bar", ".."],
+ ["\\\\foo\\bar\\baz-quux", "\\\\foo\\bar\\baz", "..\\baz"],
+ ["\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz-quux", "..\\baz-quux"],
+ ["C:\\baz-quux", "C:\\baz", "..\\baz"],
+ ["C:\\baz", "C:\\baz-quux", "..\\baz-quux"],
+ ["\\\\foo\\baz-quux", "\\\\foo\\baz", "..\\baz"],
+ ["\\\\foo\\baz", "\\\\foo\\baz-quux", "..\\baz-quux"],
+ ["C:\\baz", "\\\\foo\\bar\\baz", "\\\\foo\\bar\\baz"],
+ ["\\\\foo\\bar\\baz", "C:\\baz", "C:\\baz"],
+ ],
+ // arguments result
+ posix: [
+ ["/var/lib", "/var", ".."],
+ ["/var/lib", "/bin", "../../bin"],
+ ["/var/lib", "/var/lib", ""],
+ ["/var/lib", "/var/apache", "../apache"],
+ ["/var/", "/var/lib", "lib"],
+ ["/", "/var/lib", "var/lib"],
+ ["/foo/test", "/foo/test/bar/package.json", "bar/package.json"],
+ ["/Users/a/web/b/test/mails", "/Users/a/web/b", "../.."],
+ ["/foo/bar/baz-quux", "/foo/bar/baz", "../baz"],
+ ["/foo/bar/baz", "/foo/bar/baz-quux", "../baz-quux"],
+ ["/baz-quux", "/baz", "../baz"],
+ ["/baz", "/baz-quux", "../baz-quux"],
+ ],
};
test(function relative() {
- relativeTests.posix.forEach(function(p) {
+ relativeTests.posix.forEach(function (p) {
const expected = p[2];
const actual = path.posix.relative(p[0], p[1]);
assertEquals(actual, expected);
@@ -65,7 +59,7 @@ test(function relative() {
});
test(function relativeWin32() {
- relativeTests.win32.forEach(function(p) {
+ relativeTests.win32.forEach(function (p) {
const expected = p[2];
const actual = path.win32.relative(p[0], p[1]);
assertEquals(actual, expected);
diff --git a/std/path/resolve_test.ts b/std/path/resolve_test.ts
index 2fc49e398..95aa84cce 100644
--- a/std/path/resolve_test.ts
+++ b/std/path/resolve_test.ts
@@ -20,8 +20,8 @@ const windowsTests =
[["c:/", "///some//dir"], "c:\\some\\dir"],
[
["C:\\foo\\tmp.3\\", "..\\tmp.3\\cycles\\root.js"],
- "C:\\foo\\tmp.3\\cycles\\root.js"
- ]
+ "C:\\foo\\tmp.3\\cycles\\root.js",
+ ],
];
const posixTests =
// arguments result
@@ -31,11 +31,11 @@ const posixTests =
[["a/b/c/", "../../.."], cwd()],
[["."], cwd()],
[["/some/dir", ".", "/absolute/"], "/absolute"],
- [["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"]
+ [["/foo/tmp.3/", "../tmp.3/cycles/root.js"], "/foo/tmp.3/cycles/root.js"],
];
test(function resolve() {
- posixTests.forEach(function(p) {
+ posixTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.posix.resolve.apply(null, _p);
assertEquals(actual, p[1]);
@@ -43,7 +43,7 @@ test(function resolve() {
});
test(function resolveWin32() {
- windowsTests.forEach(function(p) {
+ windowsTests.forEach(function (p) {
const _p = p[0] as string[];
const actual = path.win32.resolve.apply(null, _p);
assertEquals(actual, p[1]);
diff --git a/std/path/utils.ts b/std/path/utils.ts
index cb1c14c16..fc3dc5be9 100644
--- a/std/path/utils.ts
+++ b/std/path/utils.ts
@@ -9,7 +9,7 @@ import {
CHAR_LOWERCASE_Z,
CHAR_DOT,
CHAR_FORWARD_SLASH,
- CHAR_BACKWARD_SLASH
+ CHAR_BACKWARD_SLASH,
} from "./constants.ts";
export function assertPath(path: string): void {
diff --git a/std/path/win32.ts b/std/path/win32.ts
index 2f28d22c1..d4febf706 100644
--- a/std/path/win32.ts
+++ b/std/path/win32.ts
@@ -7,7 +7,7 @@ import {
CHAR_DOT,
CHAR_BACKWARD_SLASH,
CHAR_COLON,
- CHAR_QUESTION_MARK
+ CHAR_QUESTION_MARK,
} from "./constants.ts";
import {
@@ -15,7 +15,7 @@ import {
isPathSeparator,
isWindowsDeviceRoot,
normalizeString,
- _format
+ _format,
} from "./utils.ts";
import { assert } from "../testing/asserts.ts";
@@ -259,8 +259,9 @@ export function normalize(path: string): string {
tail = "";
}
if (tail.length === 0 && !isAbsolute) tail = ".";
- if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1)))
+ if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) {
tail += "\\";
+ }
if (device === undefined) {
if (isAbsolute) {
if (tail.length > 0) return `\\${tail}`;
@@ -459,8 +460,9 @@ export function relative(from: string, to: string): string {
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
- if (out.length > 0) return out + toOrig.slice(toStart + lastCommonSep, toEnd);
- else {
+ if (out.length > 0) {
+ return out + toOrig.slice(toStart + lastCommonSep, toEnd);
+ } else {
toStart += lastCommonSep;
if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart;
return toOrig.slice(toStart, toEnd);
@@ -590,8 +592,9 @@ export function dirname(path: string): string {
}
export function basename(path: string, ext = ""): string {
- if (ext !== undefined && typeof ext !== "string")
+ if (ext !== undefined && typeof ext !== "string") {
throw new TypeError('"ext" argument must be a string');
+ }
assertPath(path);
diff --git a/std/permissions/mod.ts b/std/permissions/mod.ts
index e11493426..b7f80117b 100644
--- a/std/permissions/mod.ts
+++ b/std/permissions/mod.ts
@@ -5,7 +5,7 @@ const { PermissionDenied } = Deno.errors;
function getPermissionString(descriptors: Deno.PermissionDescriptor[]): string {
return descriptors.length
? ` ${descriptors
- .map(pd => {
+ .map((pd) => {
switch (pd.name) {
case "read":
case "write":
diff --git a/std/permissions/test.ts b/std/permissions/test.ts
index 2c96dfea1..6a9955b6a 100644
--- a/std/permissions/test.ts
+++ b/std/permissions/test.ts
@@ -10,9 +10,9 @@ test({
async fn() {
assertEquals(await grant({ name: "net" }, { name: "env" }), [
{ name: "net" },
- { name: "env" }
+ { name: "env" },
]);
- }
+ },
});
test({
@@ -20,28 +20,28 @@ test({
async fn() {
assertEquals(await grant([{ name: "net" }, { name: "env" }]), [
{ name: "net" },
- { name: "env" }
+ { name: "env" },
]);
- }
+ },
});
test({
name: "grant logic",
async fn() {
assert(await grant({ name: "net" }));
- }
+ },
});
test({
name: "grantOrThrow basic",
async fn() {
await grantOrThrow({ name: "net" }, { name: "env" });
- }
+ },
});
test({
name: "grantOrThrow array",
async fn() {
await grantOrThrow([{ name: "net" }, { name: "env" }]);
- }
+ },
});
diff --git a/std/signal/mod.ts b/std/signal/mod.ts
index e368edbd1..0f2b47534 100644
--- a/std/signal/mod.ts
+++ b/std/signal/mod.ts
@@ -13,13 +13,13 @@ export function signal(
const streams = signos.map(Deno.signal);
- streams.forEach(stream => {
+ streams.forEach((stream) => {
mux.add(stream);
});
// Create dispose method for the muxer of signal streams.
const dispose = (): void => {
- streams.forEach(stream => {
+ streams.forEach((stream) => {
stream.dispose();
});
};
diff --git a/std/signal/test.ts b/std/signal/test.ts
index d59484e12..16d1458a2 100644
--- a/std/signal/test.ts
+++ b/std/signal/test.ts
@@ -56,6 +56,6 @@ if (Deno.build.os !== "win") {
// yet resolved, delay to next turn of event loop otherwise,
// we'll be leaking resources.
await delay(10);
- }
+ },
});
}
diff --git a/std/strings/README.md b/std/strings/README.md
index 7621248bb..43be553b8 100644
--- a/std/strings/README.md
+++ b/std/strings/README.md
@@ -21,6 +21,6 @@ pad("denosorusrex", 6, {
side: "left",
strict: true,
strictSide: "right",
- strictChar: "..."
+ strictChar: "...",
}); // output : "den..."
```
diff --git a/std/strings/pad.ts b/std/strings/pad.ts
index dc75a2954..b72ae2074 100644
--- a/std/strings/pad.ts
+++ b/std/strings/pad.ts
@@ -48,7 +48,7 @@ export function pad(
strict: false,
side: "left",
strictChar: "",
- strictSide: "right"
+ strictSide: "right",
}
): string {
let out = input;
diff --git a/std/strings/pad_test.ts b/std/strings/pad_test.ts
index 9a125b9d2..806874bd0 100644
--- a/std/strings/pad_test.ts
+++ b/std/strings/pad_test.ts
@@ -18,7 +18,7 @@ test(function padTest(): void {
pad("denosorusrex", 4, {
char: "*",
side: "right",
- strict: false
+ strict: false,
}),
expected4
);
@@ -27,7 +27,7 @@ test(function padTest(): void {
char: "*",
side: "left",
strict: true,
- strictSide: "right"
+ strictSide: "right",
}),
expected5
);
@@ -36,7 +36,7 @@ test(function padTest(): void {
char: "*",
side: "left",
strict: true,
- strictSide: "left"
+ strictSide: "left",
}),
expected6
);
@@ -46,7 +46,7 @@ test(function padTest(): void {
side: "left",
strict: true,
strictSide: "right",
- strictChar: "..."
+ strictChar: "...",
}),
expected7
);
@@ -56,7 +56,7 @@ test(function padTest(): void {
side: "left",
strict: true,
strictSide: "left",
- strictChar: "..."
+ strictChar: "...",
}),
expected8
);
@@ -66,7 +66,7 @@ test(function padTest(): void {
side: "left",
strict: true,
strictSide: "right",
- strictChar: "..."
+ strictChar: "...",
}),
expected2
);
diff --git a/std/testing/README.md b/std/testing/README.md
index a3640e728..c7c614103 100644
--- a/std/testing/README.md
+++ b/std/testing/README.md
@@ -44,7 +44,7 @@ Deno.test({
fn(): void {
assertEquals("world", "world");
assertEquals({ hello: "world" }, { hello: "world" });
- }
+ },
});
await Deno.runTests();
@@ -165,7 +165,7 @@ bench({
b.start();
for (let i = 0; i < 1e6; i++);
b.stop();
- }
+ },
});
```
diff --git a/std/testing/asserts.ts b/std/testing/asserts.ts
index 44c311204..19be68763 100644
--- a/std/testing/asserts.ts
+++ b/std/testing/asserts.ts
@@ -66,7 +66,7 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] {
}
function isKeyedCollection(x: unknown): x is Set<unknown> {
- return [Symbol.iterator, "size"].every(k => k in (x as Set<unknown>));
+ return [Symbol.iterator, "size"].every((k) => k in (x as Set<unknown>));
}
export function equal(c: unknown, d: unknown): boolean {
diff --git a/std/testing/asserts_test.ts b/std/testing/asserts_test.ts
index 558ce1578..62e199298 100644
--- a/std/testing/asserts_test.ts
+++ b/std/testing/asserts_test.ts
@@ -12,7 +12,7 @@ import {
equal,
fail,
unimplemented,
- unreachable
+ unreachable,
} from "./asserts.ts";
import { red, green, white, gray, bold } from "../fmt/colors.ts";
const { test } = Deno;
@@ -53,11 +53,11 @@ test(function testingEqual(): void {
equal(
new Map([
["foo", "bar"],
- ["baz", "baz"]
+ ["baz", "baz"],
]),
new Map([
["foo", "bar"],
- ["baz", "baz"]
+ ["baz", "baz"],
])
)
);
@@ -77,11 +77,11 @@ test(function testingEqual(): void {
equal(
new Map([
["foo", "bar"],
- ["baz", "qux"]
+ ["baz", "qux"],
]),
new Map([
["baz", "qux"],
- ["foo", "bar"]
+ ["foo", "bar"],
])
)
);
@@ -92,7 +92,7 @@ test(function testingEqual(): void {
new Map([["foo", "bar"]]),
new Map([
["foo", "bar"],
- ["bar", "baz"]
+ ["bar", "baz"],
])
)
);
@@ -253,7 +253,7 @@ const createHeader = (): string[] => [
"",
` ${gray(bold("[Diff]"))} ${red(bold("Left"))} / ${green(bold("Right"))}`,
"",
- ""
+ "",
];
const added: (s: string) => string = (s: string): string => green(bold(s));
@@ -267,7 +267,7 @@ test({
assertEquals(10, 10);
assertEquals("abc", "abc");
assertEquals({ a: 10, b: { c: "1" } }, { a: 10, b: { c: "1" } });
- }
+ },
});
test({
@@ -278,7 +278,7 @@ test({
AssertionError,
[...createHeader(), removed(`- 1`), added(`+ 2`), ""].join("\n")
);
- }
+ },
});
test({
@@ -289,7 +289,7 @@ test({
AssertionError,
[...createHeader(), removed(`- 1`), added(`+ "1"`)].join("\n")
);
- }
+ },
});
test({
@@ -306,10 +306,10 @@ test({
white(' "2",'),
white(" 3,"),
white(" ]"),
- ""
+ "",
].join("\n")
);
- }
+ },
});
test({
@@ -329,8 +329,8 @@ test({
removed(`- "b": "2",`),
removed(`- "c": 3,`),
white(" }"),
- ""
+ "",
].join("\n")
);
- }
+ },
});
diff --git a/std/testing/bench.ts b/std/testing/bench.ts
index 1c4b01c0b..cd7b89e8c 100644
--- a/std/testing/bench.ts
+++ b/std/testing/bench.ts
@@ -65,7 +65,7 @@ function createBenchmarkTimer(clock: BenchmarkClock): BenchmarkTimer {
},
stop(): void {
clock.stop = performance.now();
- }
+ },
};
}
@@ -84,7 +84,7 @@ export function bench(
candidates.push({
name: benchmark.name,
runs: verifyOr1Run(benchmark.runs),
- func: benchmark.func
+ func: benchmark.func,
});
}
}
@@ -92,7 +92,7 @@ export function bench(
/** Runs all registered and non-skipped benchmarks serially. */
export async function runBenchmarks({
only = /[^\s]/,
- skip = /^\s*$/
+ skip = /^\s*$/,
}: BenchmarkRunOptions = {}): Promise<void> {
// Filtering candidates by the "only" and "skip" constraint
const benchmarks: BenchmarkDefinition[] = candidates.filter(
diff --git a/std/testing/bench_example.ts b/std/testing/bench_example.ts
index d27fb97e8..401516cca 100644
--- a/std/testing/bench_example.ts
+++ b/std/testing/bench_example.ts
@@ -16,7 +16,7 @@ bench({
b.start();
for (let i = 0; i < 1e6; i++);
b.stop();
- }
+ },
});
// Itsabug
diff --git a/std/testing/bench_test.ts b/std/testing/bench_test.ts
index 904ee2a8c..6dfc18b10 100644
--- a/std/testing/bench_test.ts
+++ b/std/testing/bench_test.ts
@@ -6,7 +6,7 @@ import "./bench_example.ts";
test({
name: "benching",
- fn: async function(): Promise<void> {
+ fn: async function (): Promise<void> {
bench(function forIncrementX1e9(b): void {
b.start();
for (let i = 0; i < 1e9; i++);
@@ -49,7 +49,7 @@ test({
b.start();
for (let i = 0; i < 1e6; i++);
b.stop();
- }
+ },
});
bench(function throwing(b): void {
@@ -58,5 +58,5 @@ test({
});
await runBenchmarks({ skip: /throw/ });
- }
+ },
});
diff --git a/std/testing/diff.ts b/std/testing/diff.ts
index 5cedb402a..97baa089f 100644
--- a/std/testing/diff.ts
+++ b/std/testing/diff.ts
@@ -7,7 +7,7 @@ interface FarthestPoint {
export enum DiffType {
removed = "removed",
common = "common",
- added = "added"
+ added = "added",
}
export interface DiffResult<T> {
@@ -60,12 +60,12 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
...A.map(
(a): DiffResult<typeof a> => ({
type: swapped ? DiffType.added : DiffType.removed,
- value: a
+ value: a,
})
),
...suffixCommon.map(
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c })
- )
+ ),
];
}
const offset = N;
@@ -107,13 +107,13 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
if (type === REMOVED) {
result.unshift({
type: swapped ? DiffType.removed : DiffType.added,
- value: B[b]
+ value: B[b],
});
b -= 1;
} else if (type === ADDED) {
result.unshift({
type: swapped ? DiffType.added : DiffType.removed,
- value: A[a]
+ value: A[a],
});
a -= 1;
} else {
@@ -133,8 +133,9 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
k: number,
M: number
): FarthestPoint {
- if (slide && slide.y === -1 && down && down.y === -1)
+ if (slide && slide.y === -1 && down && down.y === -1) {
return { y: 0, id: 0 };
+ }
if (
(down && down.y === -1) ||
k === M ||
@@ -215,6 +216,6 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> {
...backTrace(A, B, fp[delta + offset], swapped),
...suffixCommon.map(
(c): DiffResult<typeof c> => ({ type: DiffType.common, value: c })
- )
+ ),
];
}
diff --git a/std/testing/diff_test.ts b/std/testing/diff_test.ts
index 0e8416274..317dc0db8 100644
--- a/std/testing/diff_test.ts
+++ b/std/testing/diff_test.ts
@@ -6,7 +6,7 @@ test({
name: "empty",
fn(): void {
assertEquals(diff([], []), []);
- }
+ },
});
test({
@@ -14,30 +14,30 @@ test({
fn(): void {
assertEquals(diff(["a"], ["b"]), [
{ type: "removed", value: "a" },
- { type: "added", value: "b" }
+ { type: "added", value: "b" },
]);
- }
+ },
});
test({
name: '"a" vs "a"',
fn(): void {
assertEquals(diff(["a"], ["a"]), [{ type: "common", value: "a" }]);
- }
+ },
});
test({
name: '"a" vs ""',
fn(): void {
assertEquals(diff(["a"], []), [{ type: "removed", value: "a" }]);
- }
+ },
});
test({
name: '"" vs "a"',
fn(): void {
assertEquals(diff([], ["a"]), [{ type: "added", value: "a" }]);
- }
+ },
});
test({
@@ -45,9 +45,9 @@ test({
fn(): void {
assertEquals(diff(["a"], ["a", "b"]), [
{ type: "common", value: "a" },
- { type: "added", value: "b" }
+ { type: "added", value: "b" },
]);
- }
+ },
});
test({
@@ -62,9 +62,9 @@ test({
{ type: "common", value: "n" },
{ type: "common", value: "g" },
{ type: "removed", value: "t" },
- { type: "removed", value: "h" }
+ { type: "removed", value: "h" },
]);
- }
+ },
});
test({
@@ -78,9 +78,9 @@ test({
{ type: "removed", value: "n" },
{ type: "removed", value: "g" },
{ type: "removed", value: "t" },
- { type: "removed", value: "h" }
+ { type: "removed", value: "h" },
]);
- }
+ },
});
test({
@@ -94,9 +94,9 @@ test({
{ type: "added", value: "n" },
{ type: "added", value: "g" },
{ type: "added", value: "t" },
- { type: "added", value: "h" }
+ { type: "added", value: "h" },
]);
- }
+ },
});
test({
@@ -105,7 +105,7 @@ test({
assertEquals(diff(["abc", "c"], ["abc", "bcd", "c"]), [
{ type: "common", value: "abc" },
{ type: "added", value: "bcd" },
- { type: "common", value: "c" }
+ { type: "common", value: "c" },
]);
- }
+ },
});
diff --git a/std/testing/format.ts b/std/testing/format.ts
index 62fdde5eb..ee291dc23 100644
--- a/std/testing/format.ts
+++ b/std/testing/format.ts
@@ -56,7 +56,7 @@ const DEFAULT_OPTIONS: Options = {
indent: 2,
maxDepth: Infinity,
min: false,
- printFunctionName: true
+ printFunctionName: true,
};
interface BasicValueOptions {
@@ -358,8 +358,8 @@ function printIteratorValues(
return result;
}
-const getKeysOfEnumerableProperties = (object: {}): Array<string | symbol> => {
- const keys: Array<string | symbol> = Object.keys(object).sort();
+function getKeysOfEnumerableProperties<T>(object: T): Array<keyof T | symbol> {
+ const keys = Object.keys(object).sort() as Array<keyof T | symbol>;
if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(object).forEach((symbol): void => {
@@ -372,7 +372,7 @@ const getKeysOfEnumerableProperties = (object: {}): Array<string | symbol> => {
}
return keys;
-};
+}
/**
* Return properties of an object
@@ -519,7 +519,7 @@ const getConfig = (options: Options): Config => ({
...options,
indent: options.min ? "" : createIndent(options.indent),
spacingInner: options.min ? " " : "\n",
- spacingOuter: options.min ? "" : "\n"
+ spacingOuter: options.min ? "" : "\n",
});
/**
@@ -531,7 +531,7 @@ const getConfig = (options: Options): Config => ({
export function format(val: any, options: Optional<Options> = {}): string {
const opts: Options = {
...DEFAULT_OPTIONS,
- ...options
+ ...options,
};
const basicResult = printBasicValue(val, opts);
if (basicResult !== null) {
diff --git a/std/testing/format_test.ts b/std/testing/format_test.ts
index 14f84f3c2..eac5b7d84 100644
--- a/std/testing/format_test.ts
+++ b/std/testing/format_test.ts
@@ -29,12 +29,12 @@ const createVal = () => [
{
id: "8658c1d0-9eda-4a90-95e1-8001e8eb6036",
text: "Add alternative serialize API for pretty-format plugins",
- type: "ADD_TODO"
+ type: "ADD_TODO",
},
{
id: "8658c1d0-9eda-4a90-95e1-8001e8eb6036",
- type: "TOGGLE_TODO"
- }
+ type: "TOGGLE_TODO",
+ },
];
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -50,7 +50,7 @@ const createExpected = () =>
' "id": "8658c1d0-9eda-4a90-95e1-8001e8eb6036",',
' "type": "TOGGLE_TODO",',
" },",
- "]"
+ "]",
].join("\n");
test({
@@ -58,7 +58,7 @@ test({
fn(): void {
const val = returnArguments();
assertEquals(format(val), "Arguments []");
- }
+ },
});
test({
@@ -66,7 +66,7 @@ test({
fn(): void {
const val: unknown[] = [];
assertEquals(format(val), "Array []");
- }
+ },
});
test({
@@ -74,7 +74,7 @@ test({
fn(): void {
const val = [1, 2, 3];
assertEquals(format(val), "Array [\n 1,\n 2,\n 3,\n]");
- }
+ },
});
test({
@@ -82,7 +82,7 @@ test({
fn(): void {
const val = new Uint32Array(0);
assertEquals(format(val), "Uint32Array []");
- }
+ },
});
test({
@@ -90,7 +90,7 @@ test({
fn(): void {
const val = new Uint32Array(3);
assertEquals(format(val), "Uint32Array [\n 0,\n 0,\n 0,\n]");
- }
+ },
});
test({
@@ -98,7 +98,7 @@ test({
fn(): void {
const val = new ArrayBuffer(3);
assertEquals(format(val), "ArrayBuffer []");
- }
+ },
});
test({
@@ -109,7 +109,7 @@ test({
format(val),
"Array [\n Array [\n 1,\n 2,\n 3,\n ],\n]"
);
- }
+ },
});
test({
@@ -117,7 +117,7 @@ test({
fn(): void {
const val = true;
assertEquals(format(val), "true");
- }
+ },
});
test({
@@ -125,7 +125,7 @@ test({
fn(): void {
const val = false;
assertEquals(format(val), "false");
- }
+ },
});
test({
@@ -133,7 +133,7 @@ test({
fn(): void {
const val = new Error();
assertEquals(format(val), "[Error]");
- }
+ },
});
test({
@@ -141,7 +141,7 @@ test({
fn(): void {
const val = new TypeError("message");
assertEquals(format(val), "[TypeError: message]");
- }
+ },
});
test({
@@ -150,7 +150,7 @@ test({
// tslint:disable-next-line:function-constructor
const val = new Function();
assertEquals(format(val), "[Function anonymous]");
- }
+ },
});
test({
@@ -163,7 +163,7 @@ test({
// tslint:disable-next-line:no-empty
f((): void => {});
assertEquals(format(val), "[Function anonymous]");
- }
+ },
});
test({
@@ -176,7 +176,7 @@ test({
formatted === "[Function anonymous]" || formatted === "[Function val]",
true
);
- }
+ },
});
test({
@@ -185,7 +185,7 @@ test({
// tslint:disable-next-line:no-empty
const val = function named(): void {};
assertEquals(format(val), "[Function named]");
- }
+ },
});
test({
@@ -197,7 +197,7 @@ test({
yield 3;
};
assertEquals(format(val), "[Function generate]");
- }
+ },
});
test({
@@ -207,11 +207,11 @@ test({
const val = function named(): void {};
assertEquals(
format(val, {
- printFunctionName: false
+ printFunctionName: false,
}),
"[Function]"
);
- }
+ },
});
test({
@@ -219,7 +219,7 @@ test({
fn(): void {
const val = Infinity;
assertEquals(format(val), "Infinity");
- }
+ },
});
test({
@@ -227,7 +227,7 @@ test({
fn(): void {
const val = -Infinity;
assertEquals(format(val), "-Infinity");
- }
+ },
});
test({
@@ -235,7 +235,7 @@ test({
fn(): void {
const val = new Map();
assertEquals(format(val), "Map {}");
- }
+ },
});
test({
@@ -248,7 +248,7 @@ test({
format(val),
'Map {\n "prop1" => "value1",\n "prop2" => "value2",\n}'
);
- }
+ },
});
test({
@@ -267,7 +267,7 @@ test({
[Symbol("description"), "symbol"],
["Symbol(description)", "string"],
[["array", "key"], "array"],
- [{ key: "value" }, "object"]
+ [{ key: "value" }, "object"],
]);
const expected = [
"Map {",
@@ -288,10 +288,10 @@ test({
" Object {",
' "key": "value",',
' } => "object",',
- "}"
+ "}",
].join("\n");
assertEquals(format(val), expected);
- }
+ },
});
test({
@@ -299,7 +299,7 @@ test({
fn(): void {
const val = NaN;
assertEquals(format(val), "NaN");
- }
+ },
});
test({
@@ -307,7 +307,7 @@ test({
fn(): void {
const val = null;
assertEquals(format(val), "null");
- }
+ },
});
test({
@@ -315,7 +315,7 @@ test({
fn(): void {
const val = 123;
assertEquals(format(val), "123");
- }
+ },
});
test({
@@ -323,7 +323,7 @@ test({
fn(): void {
const val = -123;
assertEquals(format(val), "-123");
- }
+ },
});
test({
@@ -331,7 +331,7 @@ test({
fn(): void {
const val = 0;
assertEquals(format(val), "0");
- }
+ },
});
test({
@@ -339,7 +339,7 @@ test({
fn(): void {
const val = -0;
assertEquals(format(val), "-0");
- }
+ },
});
test({
@@ -347,7 +347,7 @@ test({
fn(): void {
const val = new Date(10e11);
assertEquals(format(val), "2001-09-09T01:46:40.000Z");
- }
+ },
});
test({
@@ -355,7 +355,7 @@ test({
fn(): void {
const val = new Date(Infinity);
assertEquals(format(val), "Date { NaN }");
- }
+ },
});
test({
@@ -363,7 +363,7 @@ test({
fn(): void {
const val = {};
assertEquals(format(val), "Object {}");
- }
+ },
});
test({
@@ -374,7 +374,7 @@ test({
format(val),
'Object {\n "prop1": "value1",\n "prop2": "value2",\n}'
);
- }
+ },
});
test({
@@ -390,7 +390,7 @@ test({
'Object {\n "prop": "value1",\n Symbol(symbol1): "value2",\n ' +
'Symbol(symbol2): "value3",\n}'
);
- }
+ },
});
test({
@@ -398,15 +398,15 @@ test({
"prints an object without non-enumerable properties which have string key",
fn(): void {
const val = {
- enumerable: true
+ enumerable: true,
};
const key = "non-enumerable";
Object.defineProperty(val, key, {
enumerable: false,
- value: false
+ value: false,
});
assertEquals(format(val), 'Object {\n "enumerable": true,\n}');
- }
+ },
});
test({
@@ -414,15 +414,15 @@ test({
"prints an object without non-enumerable properties which have symbol key",
fn(): void {
const val = {
- enumerable: true
+ enumerable: true,
};
const key = Symbol("non-enumerable");
Object.defineProperty(val, key, {
enumerable: false,
- value: false
+ value: false,
});
assertEquals(format(val), 'Object {\n "enumerable": true,\n}');
- }
+ },
});
test({
@@ -430,7 +430,7 @@ test({
fn(): void {
const val = { b: 1, a: 2 };
assertEquals(format(val), 'Object {\n "a": 2,\n "b": 1,\n}');
- }
+ },
});
test({
@@ -438,7 +438,7 @@ test({
fn(): void {
const val = new RegExp("regexp");
assertEquals(format(val), "/regexp/");
- }
+ },
});
test({
@@ -446,7 +446,7 @@ test({
fn(): void {
const val = /regexp/gi;
assertEquals(format(val), "/regexp/gi");
- }
+ },
});
test({
@@ -454,7 +454,7 @@ test({
fn(): void {
const val = /regexp\d/gi;
assertEquals(format(val), "/regexp\\d/gi");
- }
+ },
});
test({
@@ -462,7 +462,7 @@ test({
fn(): void {
const val = /regexp\d/gi;
assertEquals(format(val, { escapeRegex: true }), "/regexp\\\\d/gi");
- }
+ },
});
test({
@@ -473,7 +473,7 @@ test({
format(obj, { escapeRegex: true }),
'Object {\n "test": /regexp\\\\d/gi,\n}'
);
- }
+ },
});
test({
@@ -481,7 +481,7 @@ test({
fn(): void {
const val = new Set();
assertEquals(format(val), "Set {}");
- }
+ },
});
test({
@@ -491,7 +491,7 @@ test({
val.add("value1");
val.add("value2");
assertEquals(format(val), 'Set {\n "value1",\n "value2",\n}');
- }
+ },
});
test({
@@ -499,7 +499,7 @@ test({
fn(): void {
const val = "string";
assertEquals(format(val), '"string"');
- }
+ },
});
test({
@@ -507,7 +507,7 @@ test({
fn(): void {
const val = "\"'\\";
assertEquals(format(val), '"\\"\'\\\\"');
- }
+ },
});
test({
@@ -515,7 +515,7 @@ test({
fn(): void {
const val = "\"'\\n";
assertEquals(format(val, { escapeString: false }), '""\'\\n"');
- }
+ },
});
test({
@@ -523,7 +523,7 @@ test({
fn(): void {
assertEquals(format('"-"'), '"\\"-\\""');
assertEquals(format("\\ \\\\"), '"\\\\ \\\\\\\\"');
- }
+ },
});
test({
@@ -531,7 +531,7 @@ test({
fn(): void {
const val = ["line 1", "line 2", "line 3"].join("\n");
assertEquals(format(val), '"' + val + '"');
- }
+ },
});
test({
@@ -540,15 +540,15 @@ test({
const polyline = {
props: {
id: "J",
- points: ["0.5,0.460", "0.5,0.875", "0.25,0.875"].join("\n")
+ points: ["0.5,0.460", "0.5,0.875", "0.25,0.875"].join("\n"),
},
- type: "polyline"
+ type: "polyline",
};
const val = {
props: {
- children: polyline
+ children: polyline,
},
- type: "svg"
+ type: "svg",
};
assertEquals(
format(val),
@@ -566,10 +566,10 @@ test({
" },",
" },",
' "type": "svg",',
- "}"
+ "}",
].join("\n")
);
- }
+ },
});
test({
@@ -577,7 +577,7 @@ test({
fn(): void {
const val = Symbol("symbol");
assertEquals(format(val), "Symbol(symbol)");
- }
+ },
});
test({
@@ -585,7 +585,7 @@ test({
fn(): void {
const val = undefined;
assertEquals(format(val), "undefined");
- }
+ },
});
test({
@@ -593,7 +593,7 @@ test({
fn(): void {
const val = new WeakMap();
assertEquals(format(val), "WeakMap {}");
- }
+ },
});
test({
@@ -601,7 +601,7 @@ test({
fn(): void {
const val = new WeakSet();
assertEquals(format(val), "WeakSet {}");
- }
+ },
});
test({
@@ -613,7 +613,7 @@ test({
'Object {\n "prop": Object {\n "prop": Object {\n "prop": ' +
'"value",\n },\n },\n}'
);
- }
+ },
});
test({
@@ -623,7 +623,7 @@ test({
const val: any = {};
val.prop = val;
assertEquals(format(val), 'Object {\n "prop": [Circular],\n}');
- }
+ },
});
test({
@@ -635,21 +635,21 @@ test({
format(val),
'Object {\n "prop1": Object {},\n "prop2": Object {},\n}'
);
- }
+ },
});
test({
name: "default implicit: 2 spaces",
fn(): void {
assertEquals(format(createVal()), createExpected());
- }
+ },
});
test({
name: "default explicit: 2 spaces",
fn(): void {
assertEquals(format(createVal(), { indent: 2 }), createExpected());
- }
+ },
});
// Tests assume that no strings in val contain multiple adjacent spaces!
@@ -661,7 +661,7 @@ test({
format(createVal(), { indent }),
createExpected().replace(/ {2}/g, " ".repeat(indent))
);
- }
+ },
});
test({
@@ -672,7 +672,7 @@ test({
format(createVal(), { indent }),
createExpected().replace(/ {2}/g, " ".repeat(indent))
);
- }
+ },
});
test({
@@ -693,8 +693,8 @@ test({
"object with constructor": new MyObject("value"),
"object without constructor": Object.create(null),
"set empty": new Set(),
- "set non-empty": new Set(["value"])
- }
+ "set non-empty": new Set(["value"]),
+ },
];
assertEquals(
format(v, { maxDepth: 2 }),
@@ -715,17 +715,17 @@ test({
' "set empty": [Set],',
' "set non-empty": [Set],',
" },",
- "]"
+ "]",
].join("\n")
);
- }
+ },
});
test({
name: "prints objects with no constructor",
fn(): void {
assertEquals(format(Object.create(null)), "Object {}");
- }
+ },
});
test({
@@ -736,10 +736,10 @@ test({
const expected = [
"Object {", // Object instead of undefined
' "constructor": "constructor",',
- "}"
+ "}",
].join("\n");
assertEquals(format(obj), expected);
- }
+ },
});
test({
@@ -748,11 +748,11 @@ test({
assertEquals(
format({
toJSON: (): unknown => ({ value: false }),
- value: true
+ value: true,
}),
'Object {\n "value": false,\n}'
);
- }
+ },
});
test({
@@ -761,11 +761,11 @@ test({
assertEquals(
format({
toJSON: (): string => "[Internal Object]",
- value: true
+ value: true,
}),
'"[Internal Object]"'
);
- }
+ },
});
test({
@@ -774,11 +774,11 @@ test({
assertEquals(
format({
toJSON: false,
- value: true
+ value: true,
}),
'Object {\n "toJSON": false,\n "value": true,\n}'
);
- }
+ },
});
test({
@@ -787,11 +787,11 @@ test({
assertEquals(
format({
toJSON: (): unknown => ({ toJSON: (): unknown => ({ value: true }) }),
- value: false
+ value: false,
}),
'Object {\n "toJSON": [Function toJSON],\n}'
);
- }
+ },
});
test({
@@ -801,5 +801,5 @@ test({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(set as any).toJSON = (): string => "map";
assertEquals(format(set), '"map"');
- }
+ },
});
diff --git a/std/testing/runner.ts b/std/testing/runner.ts
index 9aa31cb4a..0abc6012b 100755
--- a/std/testing/runner.ts
+++ b/std/testing/runner.ts
@@ -75,7 +75,7 @@ export async function* findTestModules(
exclude: excludePaths,
includeDirs: true,
extended: true,
- globstar: true
+ globstar: true,
};
async function* expandDirectory(d: string): AsyncIterableIterator<string> {
@@ -83,7 +83,7 @@ export async function* findTestModules(
for await (const walkInfo of expandGlob(dirGlob, {
...expandGlobOpts,
root: d,
- includeDirs: false
+ includeDirs: false,
})) {
yield filePathToUrl(walkInfo.filename);
}
@@ -170,7 +170,7 @@ export async function runTestModules({
exitOnFail = false,
only = /[^\s]/,
skip = /^\s*$/,
- disableLog = false
+ disableLog = false,
}: RunTestModulesOptions = {}): Promise<void> {
let moduleCount = 0;
const testModules = [];
@@ -235,7 +235,7 @@ export async function runTestModules({
exitOnFail,
only,
skip,
- disableLog
+ disableLog,
});
}
@@ -247,14 +247,14 @@ async function main(): Promise<void> {
exclude: ["e"],
failfast: ["f"],
help: ["h"],
- quiet: ["q"]
+ quiet: ["q"],
},
default: {
"allow-none": false,
failfast: false,
help: false,
- quiet: false
- }
+ quiet: false,
+ },
});
if (parsedArgs.help) {
return showHelp();
@@ -277,7 +277,7 @@ async function main(): Promise<void> {
exclude,
allowNone,
disableLog,
- exitOnFail: true
+ exitOnFail: true,
});
} catch (error) {
if (!disableLog) {
diff --git a/std/textproto/test.ts b/std/textproto/test.ts
index 1dcbfd479..5833935ba 100644
--- a/std/textproto/test.ts
+++ b/std/textproto/test.ts
@@ -10,7 +10,7 @@ import {
assert,
assertEquals,
assertThrows,
- assertNotEOF
+ assertNotEOF,
} from "../testing/asserts.ts";
const { test } = Deno;
@@ -25,7 +25,7 @@ test({
const _input =
"dotlines\r\n.foo\r\n..bar\n...baz\nquux\r\n\r\n.\r\nanot.her\r\n";
return Promise.resolve();
- }
+ },
});
test("[textproto] ReadEmpty", async () => {
@@ -56,7 +56,7 @@ test({
const m = assertNotEOF(await r.readMIMEHeader());
assertEquals(m.get("My-Key"), "Value 1, Value 2");
assertEquals(m.get("Long-key"), "Even Longer Value");
- }
+ },
});
test({
@@ -66,7 +66,7 @@ test({
const r = reader(input);
const m = assertNotEOF(await r.readMIMEHeader());
assertEquals(m.get("Foo"), "bar");
- }
+ },
});
test({
@@ -76,7 +76,7 @@ test({
const r = reader(input);
const m = assertNotEOF(await r.readMIMEHeader());
assertEquals(m.get("Test-1"), "1");
- }
+ },
});
test({
@@ -91,7 +91,7 @@ test({
const r = reader(`Cookie: ${sdata}\r\n\r\n`);
const m = assertNotEOF(await r.readMIMEHeader());
assertEquals(m.get("Cookie"), sdata);
- }
+ },
});
// Test that we read slightly-bogus MIME headers seen in the wild,
@@ -115,7 +115,7 @@ test({
assertThrows((): void => {
assertEquals(m.get("Audio Mode"), "None");
});
- }
+ },
});
test({
@@ -127,7 +127,7 @@ test({
"\tNo colon first line with leading tab\r\nFoo: foo\r\n\r\n",
" First: line with leading space\r\nFoo: foo\r\n\r\n",
"\tFirst: line with leading tab\r\nFoo: foo\r\n\r\n",
- "Foo: foo\r\nNo colon second line\r\n\r\n"
+ "Foo: foo\r\nNo colon second line\r\n\r\n",
];
const r = reader(input.join(""));
@@ -138,7 +138,7 @@ test({
err = e;
}
assert(err instanceof Deno.errors.InvalidData);
- }
+ },
});
test({
@@ -160,7 +160,7 @@ test({
err = e;
}
assert(err instanceof Deno.errors.InvalidData);
- }
+ },
});
test({
@@ -170,11 +170,11 @@ test({
"Accept: */*\r\n",
'Content-Disposition: form-data; name="test"\r\n',
" \r\n",
- "------WebKitFormBoundaryimeZ2Le9LjohiUiG--\r\n\n"
+ "------WebKitFormBoundaryimeZ2Le9LjohiUiG--\r\n\n",
];
const r = reader(input.join(""));
const m = assertNotEOF(await r.readMIMEHeader());
assertEquals(m.get("Accept"), "*/*");
assertEquals(m.get("Content-Disposition"), 'form-data; name="test"');
- }
+ },
});
diff --git a/std/types/react-dom.d.ts b/std/types/react-dom.d.ts
index f135197f2..3be59411f 100644
--- a/std/types/react-dom.d.ts
+++ b/std/types/react-dom.d.ts
@@ -30,7 +30,7 @@ import {
DOMAttributes,
DOMElement,
ReactNode,
- ReactPortal
+ ReactPortal,
} from "./react.d.ts";
export function findDOMNode(
diff --git a/std/types/react.d.ts b/std/types/react.d.ts
index b512a43a2..725503b13 100644
--- a/std/types/react.d.ts
+++ b/std/types/react.d.ts
@@ -3231,9 +3231,7 @@ declare namespace React {
// naked 'any' type in a conditional type will short circuit and union both the then/else branches
// so boolean is only resolved for T = any
-type IsExactlyAny<T> = boolean extends (T extends never
-? true
-: false)
+type IsExactlyAny<T> = boolean extends (T extends never ? true : false)
? true
: false;
diff --git a/std/types/tests/react-dom_mock.js b/std/types/tests/react-dom_mock.js
index 68b4137ba..cbc20958b 100644
--- a/std/types/tests/react-dom_mock.js
+++ b/std/types/tests/react-dom_mock.js
@@ -3,7 +3,7 @@
const ReactDOM = {
render(element) {
return JSON.stringify(element);
- }
+ },
};
export default ReactDOM;
diff --git a/std/types/tests/react_mock.js b/std/types/tests/react_mock.js
index 93faa6c9b..3dec4f422 100644
--- a/std/types/tests/react_mock.js
+++ b/std/types/tests/react_mock.js
@@ -3,7 +3,7 @@
const React = {
createElement(type, props, ...children) {
return JSON.stringify({ type, props, children });
- }
+ },
};
export default React;
diff --git a/std/util/deep_assign_test.ts b/std/util/deep_assign_test.ts
index a69d30b73..e759a33ac 100644
--- a/std/util/deep_assign_test.ts
+++ b/std/util/deep_assign_test.ts
@@ -13,10 +13,10 @@ test(function deepAssignTest(): void {
const expected = {
foo: {
deno: new Date("1979-05-27T07:32:00Z"),
- bar: "deno"
+ bar: "deno",
},
deno: { bar: { deno: ["is", "not", "node"] } },
- reg: RegExp(/DENOWOWO/)
+ reg: RegExp(/DENOWOWO/),
};
assert(date !== expected.foo.deno);
assert(reg !== expected.reg);
diff --git a/std/uuid/mod.ts b/std/uuid/mod.ts
index 26e4b43ff..8e312c558 100644
--- a/std/uuid/mod.ts
+++ b/std/uuid/mod.ts
@@ -14,7 +14,7 @@ const NOT_IMPLEMENTED = {
},
validate(): never {
throw new Error("Not implemented");
- }
+ },
};
// TODO Implement
diff --git a/std/uuid/tests/isNil.ts b/std/uuid/tests/isNil.ts
index 7719f1229..4514576da 100644
--- a/std/uuid/tests/isNil.ts
+++ b/std/uuid/tests/isNil.ts
@@ -11,5 +11,5 @@ test({
const u = "582cbcff-dad6-4f28-888a-e062ae36bafc";
assert(isNil(nil));
assert(!isNil(u));
- }
+ },
});
diff --git a/std/uuid/tests/v4/generate.ts b/std/uuid/tests/v4/generate.ts
index c9946d46c..897a53fde 100644
--- a/std/uuid/tests/v4/generate.ts
+++ b/std/uuid/tests/v4/generate.ts
@@ -9,7 +9,7 @@ test({
const u = generate();
assertEquals(typeof u, "string", "returns a string");
assert(u !== "", "return string is not empty");
- }
+ },
});
test({
@@ -19,5 +19,5 @@ test({
const u = generate() as string;
assert(validate(u), `${u} is not a valid uuid v4`);
}
- }
+ },
});
diff --git a/std/uuid/tests/v4/validate.ts b/std/uuid/tests/v4/validate.ts
index feeecf6b7..3735de51e 100644
--- a/std/uuid/tests/v4/validate.ts
+++ b/std/uuid/tests/v4/validate.ts
@@ -12,5 +12,5 @@ Deno.test({
assert(validate(u), `generated ${u} should be valid`);
assert(validate(t), `${t} should be valid`);
assert(!validate(n), `${n} should not be valid`);
- }
+ },
});
diff --git a/std/uuid/v4.ts b/std/uuid/v4.ts
index 7688a5306..d291b5478 100644
--- a/std/uuid/v4.ts
+++ b/std/uuid/v4.ts
@@ -28,6 +28,6 @@ export function generate(): string {
"-",
...bits.slice(8, 10),
"-",
- ...bits.slice(10)
+ ...bits.slice(10),
].join("");
}
diff --git a/std/ws/README.md b/std/ws/README.md
index a8101f9f0..2379d9f96 100644
--- a/std/ws/README.md
+++ b/std/ws/README.md
@@ -12,7 +12,7 @@ import {
acceptWebSocket,
isWebSocketCloseEvent,
isWebSocketPingEvent,
- WebSocket
+ WebSocket,
} from "https://deno.land/std/ws/mod.ts";
/** websocket echo server */
@@ -24,7 +24,7 @@ for await (const req of serve(`:${port}`)) {
conn,
headers,
bufReader: req.r,
- bufWriter: req.w
+ bufWriter: req.w,
})
.then(
async (sock: WebSocket): Promise<void> => {
@@ -73,7 +73,7 @@ import {
connectWebSocket,
isWebSocketCloseEvent,
isWebSocketPingEvent,
- isWebSocketPongEvent
+ isWebSocketPongEvent,
} from "https://deno.land/std/ws/mod.ts";
import { encode } from "https://deno.land/std/strings/mod.ts";
import { BufReader } from "https://deno.land/std/io/bufio.ts";
@@ -84,7 +84,7 @@ const endpoint = Deno.args[0] || "ws://127.0.0.1:8080";
/** simple websocket cli */
const sock = await connectWebSocket(endpoint);
console.log(green("ws connected! (type 'close' to quit)"));
-(async function(): Promise<void> {
+(async function (): Promise<void> {
for await (const msg of sock.receive()) {
if (typeof msg === "string") {
console.log(yellow("< " + msg));
diff --git a/std/ws/example_client.ts b/std/ws/example_client.ts
index 664073210..e6653362d 100644
--- a/std/ws/example_client.ts
+++ b/std/ws/example_client.ts
@@ -2,7 +2,7 @@ import {
connectWebSocket,
isWebSocketCloseEvent,
isWebSocketPingEvent,
- isWebSocketPongEvent
+ isWebSocketPongEvent,
} from "../ws/mod.ts";
import { encode } from "../strings/mod.ts";
import { BufReader } from "../io/bufio.ts";
@@ -13,7 +13,7 @@ const endpoint = Deno.args[0] || "ws://127.0.0.1:8080";
/** simple websocket cli */
const sock = await connectWebSocket(endpoint);
console.log(green("ws connected! (type 'close' to quit)"));
-(async function(): Promise<void> {
+(async function (): Promise<void> {
for await (const msg of sock.receive()) {
if (typeof msg === "string") {
console.log(yellow("< " + msg));
diff --git a/std/ws/example_server.ts b/std/ws/example_server.ts
index 03adc0a49..048198326 100644
--- a/std/ws/example_server.ts
+++ b/std/ws/example_server.ts
@@ -4,7 +4,7 @@ import {
acceptWebSocket,
isWebSocketCloseEvent,
isWebSocketPingEvent,
- WebSocket
+ WebSocket,
} from "./mod.ts";
/** websocket echo server */
@@ -16,7 +16,7 @@ for await (const req of serve(`:${port}`)) {
conn,
headers,
bufReader: req.r,
- bufWriter: req.w
+ bufWriter: req.w,
})
.then(
async (sock: WebSocket): Promise<void> => {
diff --git a/std/ws/mod.ts b/std/ws/mod.ts
index 6101260e9..a9b8cb675 100644
--- a/std/ws/mod.ts
+++ b/std/ws/mod.ts
@@ -19,7 +19,7 @@ export enum OpCode {
BinaryFrame = 0x2,
Close = 0x8,
Ping = 0x9,
- Pong = 0xa
+ Pong = 0xa,
}
export type WebSocketEvent =
@@ -125,13 +125,13 @@ export async function writeFrame(
0x80 | frame.opcode,
hasMask | 0b01111110,
payloadLength >>> 8,
- payloadLength & 0x00ff
+ payloadLength & 0x00ff,
]);
} else {
header = new Uint8Array([
0x80 | frame.opcode,
hasMask | 0b01111111,
- ...sliceLongToBytes(payloadLength)
+ ...sliceLongToBytes(payloadLength),
]);
}
if (frame.mask) {
@@ -186,7 +186,7 @@ export async function readFrame(buf: BufReader): Promise<WebSocketFrame> {
isLastFrame,
opcode,
mask,
- payload
+ payload,
};
}
@@ -209,7 +209,7 @@ class WebSocketImpl implements WebSocket {
conn,
bufReader,
bufWriter,
- mask
+ mask,
}: {
conn: Conn;
bufReader?: BufReader;
@@ -271,7 +271,7 @@ class WebSocketImpl implements WebSocket {
await this.enqueue({
opcode: OpCode.Pong,
payload: frame.payload,
- isLastFrame: true
+ isLastFrame: true,
});
yield ["ping", frame.payload] as WebSocketPingEvent;
break;
@@ -290,7 +290,7 @@ class WebSocketImpl implements WebSocket {
const { d, frame } = entry;
writeFrame(frame, this.bufWriter)
.then(() => d.resolve())
- .catch(e => d.reject(e))
+ .catch((e) => d.reject(e))
.finally(() => {
this.sendQueue.shift();
this.dequeue();
@@ -318,7 +318,7 @@ class WebSocketImpl implements WebSocket {
isLastFrame,
opcode,
payload,
- mask: this.mask
+ mask: this.mask,
};
return this.enqueue(frame);
}
@@ -329,7 +329,7 @@ class WebSocketImpl implements WebSocket {
isLastFrame: true,
opcode: OpCode.Ping,
mask: this.mask,
- payload
+ payload,
};
return this.enqueue(frame);
}
@@ -355,7 +355,7 @@ class WebSocketImpl implements WebSocket {
isLastFrame: true,
opcode: OpCode.Close,
mask: this.mask,
- payload
+ payload,
});
} catch (e) {
throw e;
@@ -378,7 +378,7 @@ class WebSocketImpl implements WebSocket {
this._isClosed = true;
const rest = this.sendQueue;
this.sendQueue = [];
- rest.forEach(e =>
+ rest.forEach((e) =>
e.d.reject(
new Deno.errors.ConnectionReset("Socket has already been closed")
)
@@ -431,8 +431,8 @@ export async function acceptWebSocket(req: {
headers: new Headers({
Upgrade: "websocket",
Connection: "Upgrade",
- "Sec-WebSocket-Accept": secAccept
- })
+ "Sec-WebSocket-Accept": secAccept,
+ }),
});
return sock;
}
@@ -543,7 +543,7 @@ export async function connectWebSocket(
conn,
bufWriter,
bufReader,
- mask: createMask()
+ mask: createMask(),
});
}
diff --git a/std/ws/sha1.ts b/std/ws/sha1.ts
index dc8ba680c..fc86881f8 100644
--- a/std/ws/sha1.ts
+++ b/std/ws/sha1.ts
@@ -358,7 +358,7 @@ export class Sha1 {
(h4 >> 24) & 0xff,
(h4 >> 16) & 0xff,
(h4 >> 8) & 0xff,
- h4 & 0xff
+ h4 & 0xff,
];
}
diff --git a/std/ws/test.ts b/std/ws/test.ts
index f1efa8e40..583750bb1 100644
--- a/std/ws/test.ts
+++ b/std/ws/test.ts
@@ -14,7 +14,7 @@ import {
readFrame,
unmask,
writeFrame,
- createWebSocket
+ createWebSocket,
} from "./mod.ts";
import { encode, decode } from "../strings/mod.ts";
import Writer = Deno.Writer;
@@ -50,7 +50,7 @@ test("[ws] read masked text frame", async () => {
0x9f,
0x4d,
0x51,
- 0x58
+ 0x58,
])
)
);
@@ -136,8 +136,8 @@ test("[ws] acceptable", () => {
const ret = acceptable({
headers: new Headers({
upgrade: "websocket",
- "sec-websocket-key": "aaa"
- })
+ "sec-websocket-key": "aaa",
+ }),
});
assertEquals(ret, true);
@@ -148,12 +148,12 @@ test("[ws] acceptable", () => {
["host", "127.0.0.1:9229"],
[
"sec-websocket-extensions",
- "permessage-deflate; client_max_window_bits"
+ "permessage-deflate; client_max_window_bits",
],
["sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ=="],
["sec-websocket-version", "13"],
- ["upgrade", "WebSocket"]
- ])
+ ["upgrade", "WebSocket"],
+ ]),
})
);
});
@@ -161,25 +161,25 @@ test("[ws] acceptable", () => {
test("[ws] acceptable should return false when headers invalid", () => {
assertEquals(
acceptable({
- headers: new Headers({ "sec-websocket-key": "aaa" })
+ headers: new Headers({ "sec-websocket-key": "aaa" }),
}),
false
);
assertEquals(
acceptable({
- headers: new Headers({ upgrade: "websocket" })
+ headers: new Headers({ upgrade: "websocket" }),
}),
false
);
assertEquals(
acceptable({
- headers: new Headers({ upgrade: "invalid", "sec-websocket-key": "aaa" })
+ headers: new Headers({ upgrade: "invalid", "sec-websocket-key": "aaa" }),
}),
false
);
assertEquals(
acceptable({
- headers: new Headers({ upgrade: "websocket", "sec-websocket-ky": "" })
+ headers: new Headers({ upgrade: "websocket", "sec-websocket-ky": "" }),
}),
false
);
@@ -205,7 +205,7 @@ test("[ws] write and read masked frame", async () => {
isLastFrame: true,
mask,
opcode: OpCode.TextFrame,
- payload: encode(msg)
+ payload: encode(msg),
},
buf
);
@@ -282,19 +282,19 @@ function dummyConn(r: Reader, w: Writer): Conn {
write: (x): Promise<number> => w.write(x),
close: (): void => {},
localAddr: { transport: "tcp", hostname: "0.0.0.0", port: 0 },
- remoteAddr: { transport: "tcp", hostname: "0.0.0.0", port: 0 }
+ remoteAddr: { transport: "tcp", hostname: "0.0.0.0", port: 0 },
};
}
function delayedWriter(ms: number, dest: Writer): Writer {
return {
write(p: Uint8Array): Promise<number> {
- return new Promise<number>(resolve => {
+ return new Promise<number>((resolve) => {
setTimeout(async (): Promise<void> => {
resolve(await dest.write(p));
}, ms);
});
- }
+ },
};
}
test({
@@ -308,7 +308,7 @@ test({
sock.send("first"),
sock.send("second"),
sock.ping(),
- sock.send(new Uint8Array([3]))
+ sock.send(new Uint8Array([3])),
]);
const bufr = new BufReader(buf);
const first = await readFrame(bufr);
@@ -322,7 +322,7 @@ test({
assertEquals(ping.opcode, OpCode.Ping);
assertEquals(third.opcode, OpCode.BinaryFrame);
assertEquals(bytes.equal(third.payload, new Uint8Array([3])), true);
- }
+ },
});
test("[ws] createSecKeyHasCorrectLength", () => {
@@ -337,7 +337,7 @@ test("[ws] WebSocket should throw `Deno.errors.ConnectionReset` when peer closed
const eofReader: Deno.Reader = {
read(_: Uint8Array): Promise<number | Deno.EOF> {
return Promise.resolve(Deno.EOF);
- }
+ },
};
const conn = dummyConn(eofReader, buf);
const sock = createWebSocket({ conn });
@@ -355,7 +355,7 @@ test("[ws] WebSocket shouldn't throw `Deno.errors.UnexpectedEof` on recive()", a
const eofReader: Deno.Reader = {
read(_: Uint8Array): Promise<number | Deno.EOF> {
return Promise.resolve(Deno.EOF);
- }
+ },
};
const conn = dummyConn(eofReader, buf);
const sock = createWebSocket({ conn });
@@ -373,10 +373,10 @@ test({
let timer: number | undefined;
const lazyWriter: Deno.Writer = {
write(_: Uint8Array): Promise<number> {
- return new Promise(resolve => {
+ return new Promise((resolve) => {
timer = setTimeout(() => resolve(0), 1000);
});
- }
+ },
};
const conn = dummyConn(buf, lazyWriter);
const sock = createWebSocket({ conn });
@@ -384,7 +384,7 @@ test({
const p = Promise.all([
sock.send("hello").catch(onError),
sock.send(new Uint8Array([1, 2])).catch(onError),
- sock.ping().catch(onError)
+ sock.ping().catch(onError),
]);
sock.closeForce();
assertEquals(sock.isClosed, true);
@@ -396,5 +396,5 @@ test({
// Wait for another event loop turn for `timeout` op promise
// to resolve, otherwise we'll get "op leak".
await delay(10);
- }
+ },
});
diff --git a/test_plugin/tests/test.js b/test_plugin/tests/test.js
index 49b126e62..d6d531f14 100644
--- a/test_plugin/tests/test.js
+++ b/test_plugin/tests/test.js
@@ -28,7 +28,7 @@ function runTestSync() {
console.log(`Plugin Sync Response: ${textDecoder.decode(response)}`);
}
-testAsync.setAsyncHandler(response => {
+testAsync.setAsyncHandler((response) => {
console.log(`Plugin Async Response: ${textDecoder.decode(response)}`);
});
diff --git a/third_party b/third_party
-Subproject 94aa8c0992fc13ad571de4286e008b6ac6e34d0
+Subproject 4a3ade332261afb8fcb8b364e59d3cca7c975d3
diff --git a/tools/deno_http_proxy.ts b/tools/deno_http_proxy.ts
index 589a14338..6e5141377 100644
--- a/tools/deno_http_proxy.ts
+++ b/tools/deno_http_proxy.ts
@@ -9,7 +9,7 @@ async function proxyRequest(req: ServerRequest): Promise<void> {
const url = `http://${originAddr}${req.url}`;
const resp = await fetch(url, {
method: req.method,
- headers: req.headers
+ headers: req.headers,
});
req.respond(resp);
}
diff --git a/tools/deno_tcp_proxy.ts b/tools/deno_tcp_proxy.ts
index cd1bad247..43c61831c 100644
--- a/tools/deno_tcp_proxy.ts
+++ b/tools/deno_tcp_proxy.ts
@@ -10,7 +10,7 @@ const listener = Deno.listen({ hostname, port: Number(port) });
async function handle(conn: Deno.Conn): Promise<void> {
const origin = await Deno.connect({
hostname: originHostname,
- port: Number(originPort)
+ port: Number(originPort),
});
try {
await Promise.all([Deno.copy(conn, origin), Deno.copy(origin, conn)]);
diff --git a/tools/node_http_proxy.js b/tools/node_http_proxy.js
index d90cbe835..b984c484f 100644
--- a/tools/node_http_proxy.js
+++ b/tools/node_http_proxy.js
@@ -9,10 +9,10 @@ http
port: originPort,
path: req.url,
method: req.method,
- headers: req.headers
+ headers: req.headers,
};
- const proxy = http.request(options, proxyRes => {
+ const proxy = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
diff --git a/tools/node_tcp.js b/tools/node_tcp.js
index 3899a671a..7c6147dbf 100644
--- a/tools/node_tcp.js
+++ b/tools/node_tcp.js
@@ -8,11 +8,11 @@ const response = Buffer.from(
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
);
-Server(socket => {
- socket.on("data", _ => {
+Server((socket) => {
+ socket.on("data", (_) => {
socket.write(response);
});
- socket.on("error", _ => {
+ socket.on("error", (_) => {
socket.destroy();
});
}).listen(port);
diff --git a/tools/node_tcp_promise.js b/tools/node_tcp_promise.js
index d522f1751..c59a9a7b4 100644
--- a/tools/node_tcp_promise.js
+++ b/tools/node_tcp_promise.js
@@ -15,8 +15,8 @@ function write(socket, buffer) {
return Promise.resolve(p);
}
-Server(async socket => {
- socket.on("error", _ => {
+Server(async (socket) => {
+ socket.on("error", (_) => {
socket.destroy();
});
for await (const _ of socket) {
diff --git a/tools/node_tcp_proxy.js b/tools/node_tcp_proxy.js
index 7dc1b2612..304ed0407 100644
--- a/tools/node_tcp_proxy.js
+++ b/tools/node_tcp_proxy.js
@@ -1,6 +1,6 @@
const net = require("net");
-process.on("uncaughtException", function(error) {
+process.on("uncaughtException", function (error) {
console.error(error);
});
@@ -14,46 +14,46 @@ const remoteport = process.argv[3];
const remotehost = "127.0.0.1";
-const server = net.createServer(function(localsocket) {
+const server = net.createServer(function (localsocket) {
const remotesocket = new net.Socket();
remotesocket.connect(remoteport, remotehost);
- localsocket.on("data", function(data) {
+ localsocket.on("data", function (data) {
const flushed = remotesocket.write(data);
if (!flushed) {
localsocket.pause();
}
});
- remotesocket.on("data", function(data) {
+ remotesocket.on("data", function (data) {
const flushed = localsocket.write(data);
if (!flushed) {
remotesocket.pause();
}
});
- localsocket.on("drain", function() {
+ localsocket.on("drain", function () {
remotesocket.resume();
});
- remotesocket.on("drain", function() {
+ remotesocket.on("drain", function () {
localsocket.resume();
});
- localsocket.on("close", function() {
+ localsocket.on("close", function () {
remotesocket.end();
});
- remotesocket.on("close", function() {
+ remotesocket.on("close", function () {
localsocket.end();
});
- localsocket.on("error", function() {
+ localsocket.on("error", function () {
localsocket.end();
});
- remotesocket.on("error", function() {
+ remotesocket.on("error", function () {
remotesocket.end();
});
});