From 16ab35ce2cd19b3d3f5a9b354600adc1e54a68d9 Mon Sep 17 00:00:00 2001 From: Maximilien Mellen Date: Thu, 6 Feb 2020 14:51:48 +0100 Subject: [PATCH] Update codebase to support TypeScript strict mode --- cli/compilers/ts.rs | 2 +- cli/compilers/wasm_wrap.js | 1 + cli/js/body_test.ts | 6 +-- cli/js/buffer_test.ts | 68 +++++++++++++++--------------- cli/js/chmod_test.ts | 16 +++---- cli/js/console_test.ts | 9 ++-- cli/js/error_stack_test.ts | 4 +- cli/js/event_target_test.ts | 22 ++++++++-- cli/js/event_test.ts | 7 +-- cli/js/fetch_test.ts | 15 ++++--- cli/js/file_test.ts | 6 ++- cli/js/files_test.ts | 2 + cli/js/form_data_test.ts | 7 +++ cli/js/headers_test.ts | 16 ++++--- cli/js/internals_test.ts | 4 +- cli/js/mixins/dom_iterable_test.ts | 16 ++++--- cli/js/net_test.ts | 2 +- cli/js/os_test.ts | 7 ++- cli/js/process_test.ts | 18 ++++---- cli/js/resources_test.ts | 4 +- cli/js/signal_test.ts | 2 +- cli/js/stat_test.ts | 2 +- cli/js/test_util.ts | 11 +++-- cli/js/timers_test.ts | 17 ++++---- cli/js/tls_test.ts | 2 +- cli/js/url_search_params_test.ts | 3 ++ cli/js/utime_test.ts | 28 ++++++------ cli/js/write_file_test.ts | 8 ++-- cli/tests/046_jsx_test.tsx | 5 +++ cli/tests/048_media_types_jsx.ts | 10 +++++ std/encoding/base32_test.ts | 2 +- std/encoding/yaml/loader/loader.ts | 6 +-- std/examples/gist.ts | 2 +- std/fs/empty_dir_test.ts | 2 +- std/fs/exists_test.ts | 2 +- std/fs/walk.ts | 16 +++---- std/http/cookie.ts | 2 +- std/http/file_server.ts | 14 +++--- std/http/file_server_test.ts | 2 +- std/http/server.ts | 2 +- std/http/server_test.ts | 4 +- std/node/global.ts | 1 + std/node/module.ts | 45 +++++++++++--------- std/node/os.ts | 4 +- std/path/utils.ts | 6 +-- std/path/win32.ts | 10 ++--- std/textproto/mod.ts | 4 +- std/util/deep_assign.ts | 2 +- 48 files changed, 257 insertions(+), 189 deletions(-) diff --git a/cli/compilers/ts.rs b/cli/compilers/ts.rs index d0c0d87c0ccc67..5002923b99a277 100644 --- a/cli/compilers/ts.rs +++ b/cli/compilers/ts.rs @@ -718,7 +718,7 @@ mod tests { .unwrap() .code .as_bytes() - .starts_with(b"console.log(\"Hello World\");")); + .starts_with(b"\"use strict\";\nconsole.log(\"Hello World\");")); } #[tokio::test] diff --git a/cli/compilers/wasm_wrap.js b/cli/compilers/wasm_wrap.js index c90bd55407f5bb..98892b8e0e093c 100644 --- a/cli/compilers/wasm_wrap.js +++ b/cli/compilers/wasm_wrap.js @@ -1,3 +1,4 @@ +// @ts-nocheck const importObject = Object.create(null); //IMPORTS diff --git a/cli/js/body_test.ts b/cli/js/body_test.ts index 2ac4d1314f4b5b..d7f5c6d61d3b50 100644 --- a/cli/js/body_test.ts +++ b/cli/js/body_test.ts @@ -45,7 +45,7 @@ testPerm({ net: true }, async function bodyMultipartFormData(): Promise { const formData = await body.formData(); assert(formData.has("field_1")); - assertEquals(formData.get("field_1").toString(), "value_1 \r\n"); + assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); assert(formData.has("field_2")); }); @@ -62,7 +62,7 @@ testPerm({ net: true }, async function bodyURLEncodedFormData(): Promise { const formData = await body.formData(); assert(formData.has("field_1")); - assertEquals(formData.get("field_1").toString(), "Hi"); + assertEquals(formData.get("field_1")!.toString(), "Hi"); assert(formData.has("field_2")); - assertEquals(formData.get("field_2").toString(), ""); + assertEquals(formData.get("field_2")!.toString(), ""); }); diff --git a/cli/js/buffer_test.ts b/cli/js/buffer_test.ts index 4b5701e54a2672..bb333c979e6a3e 100644 --- a/cli/js/buffer_test.ts +++ b/cli/js/buffer_test.ts @@ -78,8 +78,8 @@ function repeat(c: string, bytes: number): Uint8Array { test(function bufferNewBuffer(): void { init(); - const buf = new Buffer(testBytes.buffer as ArrayBuffer); - check(buf, testString); + const buf = new Buffer(testBytes!.buffer as ArrayBuffer); + check(buf, testString!); }); test(async function bufferBasicOperations(): Promise { @@ -94,25 +94,25 @@ test(async function bufferBasicOperations(): Promise { buf.truncate(0); check(buf, ""); - let n = await buf.write(testBytes.subarray(0, 1)); + let n = await buf.write(testBytes!.subarray(0, 1)); assertEquals(n, 1); check(buf, "a"); - n = await buf.write(testBytes.subarray(1, 2)); + n = await buf.write(testBytes!.subarray(1, 2)); assertEquals(n, 1); check(buf, "ab"); - n = await buf.write(testBytes.subarray(2, 26)); + n = await buf.write(testBytes!.subarray(2, 26)); assertEquals(n, 24); - check(buf, testString.slice(0, 26)); + check(buf, testString!.slice(0, 26)); buf.truncate(26); - check(buf, testString.slice(0, 26)); + check(buf, testString!.slice(0, 26)); buf.truncate(20); - check(buf, testString.slice(0, 20)); + check(buf, testString!.slice(0, 20)); - await empty(buf, testString.slice(0, 20), new Uint8Array(5)); + await empty(buf, testString!.slice(0, 20), new Uint8Array(5)); await empty(buf, "", new Uint8Array(100)); // TODO buf.writeByte() @@ -134,8 +134,8 @@ test(async function bufferLargeByteWrites(): Promise { const buf = new Buffer(); const limit = 9; for (let i = 3; i < limit; i += 3) { - const s = await fillBytes(buf, "", 5, testBytes); - await empty(buf, s, new Uint8Array(Math.floor(testString.length / i))); + const s = await fillBytes(buf, "", 5, testBytes!); + await empty(buf, s, new Uint8Array(Math.floor(testString!.length / i))); } check(buf, ""); }); @@ -163,9 +163,9 @@ test(async function bufferLargeByteReads(): Promise { init(); const buf = new Buffer(); for (let i = 3; i < 30; i += 3) { - const n = Math.floor(testBytes.byteLength / i); - const s = await fillBytes(buf, "", 5, testBytes.subarray(0, n)); - await empty(buf, s, new Uint8Array(testString.length)); + const n = Math.floor(testBytes!.byteLength / i); + const s = await fillBytes(buf, "", 5, testBytes!.subarray(0, n)); + await empty(buf, s, new Uint8Array(testString!.length)); } check(buf, ""); }); @@ -183,11 +183,11 @@ test(async function bufferReadFrom(): Promise { buf, "", 5, - testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) + testBytes!.subarray(0, Math.floor(testBytes!.byteLength / i)) ); const b = new Buffer(); await b.readFrom(buf); - const fub = new Uint8Array(testString.length); + const fub = new Uint8Array(testString!.length); await empty(b, s, fub); } }); @@ -200,11 +200,11 @@ test(async function bufferReadFromSync(): Promise { buf, "", 5, - testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) + testBytes!.subarray(0, Math.floor(testBytes!.byteLength / i)) ); const b = new Buffer(); b.readFromSync(buf); - const fub = new Uint8Array(testString.length); + const fub = new Uint8Array(testString!.length); await empty(b, s, fub); } }); @@ -236,42 +236,42 @@ test(async function bufferTestGrow(): Promise { test(async function testReadAll(): Promise { init(); - const reader = new Buffer(testBytes.buffer as ArrayBuffer); + const reader = new Buffer(testBytes!.buffer as ArrayBuffer); const actualBytes = await readAll(reader); - assertEquals(testBytes.byteLength, actualBytes.byteLength); - for (let i = 0; i < testBytes.length; ++i) { - assertEquals(testBytes[i], actualBytes[i]); + assertEquals(testBytes!.byteLength, actualBytes.byteLength); + for (let i = 0; i < testBytes!.length; ++i) { + assertEquals(testBytes![i], actualBytes[i]); } }); test(function testReadAllSync(): void { init(); - const reader = new Buffer(testBytes.buffer as ArrayBuffer); + const reader = new Buffer(testBytes!.buffer as ArrayBuffer); const actualBytes = readAllSync(reader); - assertEquals(testBytes.byteLength, actualBytes.byteLength); - for (let i = 0; i < testBytes.length; ++i) { - assertEquals(testBytes[i], actualBytes[i]); + assertEquals(testBytes!.byteLength, actualBytes.byteLength); + for (let i = 0; i < testBytes!.length; ++i) { + assertEquals(testBytes![i], actualBytes[i]); } }); test(async function testWriteAll(): Promise { init(); const writer = new Buffer(); - await writeAll(writer, testBytes); + await writeAll(writer, testBytes!); const actualBytes = writer.bytes(); - assertEquals(testBytes.byteLength, actualBytes.byteLength); - for (let i = 0; i < testBytes.length; ++i) { - assertEquals(testBytes[i], actualBytes[i]); + assertEquals(testBytes!.byteLength, actualBytes.byteLength); + for (let i = 0; i < testBytes!.length; ++i) { + assertEquals(testBytes![i], actualBytes[i]); } }); test(function testWriteAllSync(): void { init(); const writer = new Buffer(); - writeAllSync(writer, testBytes); + writeAllSync(writer, testBytes!); const actualBytes = writer.bytes(); - assertEquals(testBytes.byteLength, actualBytes.byteLength); - for (let i = 0; i < testBytes.length; ++i) { - assertEquals(testBytes[i], actualBytes[i]); + assertEquals(testBytes!.byteLength, actualBytes.byteLength); + for (let i = 0; i < testBytes!.length; ++i) { + assertEquals(testBytes![i], actualBytes[i]); } }); diff --git a/cli/js/chmod_test.ts b/cli/js/chmod_test.ts index 3ecb4256a88c6e..d4831c8a9c32c6 100644 --- a/cli/js/chmod_test.ts +++ b/cli/js/chmod_test.ts @@ -16,7 +16,7 @@ testPerm({ read: true, write: true }, function chmodSyncSuccess(): void { // Check success when not on windows if (isNotWindows) { const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.mode & 0o777, 0o777); + assertEquals(fileInfo.mode! & 0o777, 0o777); } }); @@ -35,15 +35,15 @@ if (isNotWindows) { Deno.symlinkSync(filename, symlinkName); let symlinkInfo = Deno.lstatSync(symlinkName); - const symlinkMode = symlinkInfo.mode & 0o777; // platform dependent + const symlinkMode = symlinkInfo.mode! & 0o777; // platform dependent Deno.chmodSync(symlinkName, 0o777); // Change actual file mode, not symlink const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.mode & 0o777, 0o777); + assertEquals(fileInfo.mode! & 0o777, 0o777); symlinkInfo = Deno.lstatSync(symlinkName); - assertEquals(symlinkInfo.mode & 0o777, symlinkMode); + assertEquals(symlinkInfo.mode! & 0o777, symlinkMode); } ); } @@ -86,7 +86,7 @@ testPerm({ read: true, write: true }, async function chmodSuccess(): Promise< // Check success when not on windows if (isNotWindows) { const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.mode & 0o777, 0o777); + assertEquals(fileInfo.mode! & 0o777, 0o777); } }); @@ -105,15 +105,15 @@ if (isNotWindows) { Deno.symlinkSync(filename, symlinkName); let symlinkInfo = Deno.lstatSync(symlinkName); - const symlinkMode = symlinkInfo.mode & 0o777; // platform dependent + const symlinkMode = symlinkInfo.mode! & 0o777; // platform dependent await Deno.chmod(symlinkName, 0o777); // Just change actual file mode, not symlink const fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.mode & 0o777, 0o777); + assertEquals(fileInfo.mode! & 0o777, 0o777); symlinkInfo = Deno.lstatSync(symlinkName); - assertEquals(symlinkInfo.mode & 0o777, symlinkMode); + assertEquals(symlinkInfo.mode! & 0o777, symlinkMode); } ); } diff --git a/cli/js/console_test.ts b/cli/js/console_test.ts index b80dd82841ea0e..6617acaef5988c 100644 --- a/cli/js/console_test.ts +++ b/cli/js/console_test.ts @@ -14,8 +14,8 @@ const customInspect = Deno.symbols.customInspect; const { Console, stringifyArgs - // eslint-disable-next-line @typescript-eslint/no-explicit-any -} = Deno[Deno.symbols.internal] as any; + // @ts-ignore +} = Deno[Deno.symbols.internal]; function stringify(...args: unknown[]): string { return stringifyArgs(args).replace(/\n$/, ""); @@ -306,6 +306,7 @@ test(function consoleTestCallToStringOnLabel(): void { for (const method of methods) { let hasCalled = false; + // @ts-ignore console[method]({ toString(): void { hasCalled = true; @@ -464,7 +465,7 @@ test(function consoleGroupWarn(): void { console.warn("6"); console.warn("7"); assertEquals( - both.toString(), + both!.toString(), `1 2 3 @@ -694,6 +695,6 @@ test(function consoleDirXml(): void { test(function consoleTrace(): void { mockConsole((console, _out, err): void => { console.trace("%s", "custom message"); - assert(err.toString().includes("Trace: custom message")); + assert(err!.toString().includes("Trace: custom message")); }); }); diff --git a/cli/js/error_stack_test.ts b/cli/js/error_stack_test.ts index e4e44c77fb0d5b..b013504db8dff1 100644 --- a/cli/js/error_stack_test.ts +++ b/cli/js/error_stack_test.ts @@ -1,8 +1,8 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { test, assert } from "./test_util.ts"; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const { setPrepareStackTrace } = Deno[Deno.symbols.internal] as any; +// @ts-ignore +const { setPrepareStackTrace } = Deno[Deno.symbols.internal]; interface CallSite { getThis(): unknown; diff --git a/cli/js/event_target_test.ts b/cli/js/event_target_test.ts index aead97ed3e102f..91e84204f4991e 100644 --- a/cli/js/event_target_test.ts +++ b/cli/js/event_target_test.ts @@ -4,8 +4,11 @@ import { test, assertEquals } from "./test_util.ts"; test(function addEventListenerTest(): void { const document = new EventTarget(); + // @ts-ignore assertEquals(document.addEventListener("x", null, false), undefined); + // @ts-ignore assertEquals(document.addEventListener("x", null, true), undefined); + // @ts-ignore assertEquals(document.addEventListener("x", null), undefined); }); @@ -14,7 +17,7 @@ test(function constructedEventTargetCanBeUsedAsExpected(): void { const event = new Event("foo", { bubbles: true, cancelable: false }); let callCount = 0; - const listener = (e): void => { + const listener = (e: Event): void => { assertEquals(e, event); ++callCount; }; @@ -34,11 +37,19 @@ test(function constructedEventTargetCanBeUsedAsExpected(): void { test(function anEventTargetCanBeSubclassed(): void { class NicerEventTarget extends EventTarget { - on(type, callback?, options?): void { + on( + type: string, + callback: (e: Event) => void, + options?: __domTypes.AddEventListenerOptions + ): void { this.addEventListener(type, callback, options); } - off(type, callback?, options?): void { + off( + type: string, + callback: (e: Event) => void, + options?: __domTypes.EventListenerOptions + ): void { this.removeEventListener(type, callback, options); } } @@ -60,8 +71,11 @@ test(function anEventTargetCanBeSubclassed(): void { test(function removingNullEventListenerShouldSucceed(): void { const document = new EventTarget(); + // @ts-ignore assertEquals(document.removeEventListener("x", null, false), undefined); + // @ts-ignore assertEquals(document.removeEventListener("x", null, true), undefined); + // @ts-ignore assertEquals(document.removeEventListener("x", null), undefined); }); @@ -70,7 +84,7 @@ test(function constructedEventTargetUseObjectPrototype(): void { const event = new Event("toString", { bubbles: true, cancelable: false }); let callCount = 0; - const listener = (e): void => { + const listener = (e: Event): void => { assertEquals(e, event); ++callCount; }; diff --git a/cli/js/event_test.ts b/cli/js/event_test.ts index affd979ee5f05f..6cefc4cd1b9463 100644 --- a/cli/js/event_test.ts +++ b/cli/js/event_test.ts @@ -71,6 +71,7 @@ test(function eventPreventDefaultSuccess(): void { test(function eventInitializedWithNonStringType(): void { const type = undefined; + // @ts-ignore const event = new Event(type); assertEquals(event.isTrusted, false); @@ -85,11 +86,11 @@ test(function eventInitializedWithNonStringType(): void { test(function eventIsTrusted(): void { const desc1 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted"); assertNotEquals(desc1, undefined); - assertEquals(typeof desc1.get, "function"); + assertEquals(typeof desc1!.get, "function"); const desc2 = Object.getOwnPropertyDescriptor(new Event("x"), "isTrusted"); assertNotEquals(desc2, undefined); - assertEquals(typeof desc2.get, "function"); + assertEquals(typeof desc2!.get, "function"); - assertEquals(desc1.get, desc2.get); + assertEquals(desc1!.get, desc2!.get); }); diff --git a/cli/js/fetch_test.ts b/cli/js/fetch_test.ts index 2b3d03a38c46f1..bbdde2cbfbde27 100644 --- a/cli/js/fetch_test.ts +++ b/cli/js/fetch_test.ts @@ -54,7 +54,7 @@ testPerm({ net: true }, async function fetchHeaders(): Promise { const response = await fetch("http://localhost:4545/cli/tests/fixture.json"); const headers = response.headers; assertEquals(headers.get("Content-Type"), "application/json"); - assert(headers.get("Server").startsWith("SimpleHTTP")); + assert(headers.get("Server")!.startsWith("SimpleHTTP")); }); testPerm({ net: true }, async function fetchBlob(): Promise { @@ -96,6 +96,7 @@ testPerm({ net: true }, async function responseClone(): Promise { const ab = await response.arrayBuffer(); const ab1 = await response1.arrayBuffer(); for (let i = 0; i < ab.byteLength; i++) { + // @ts-ignore assertEquals(ab[i], ab1[i]); } }); @@ -119,7 +120,7 @@ testPerm({ net: true }, async function fetchMultipartFormDataSuccess(): Promise< ); const formData = await response.formData(); assert(formData.has("field_1")); - assertEquals(formData.get("field_1").toString(), "value_1 \r\n"); + assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); assert(formData.has("field_2")); /* TODO(ry) Re-enable this test once we bring back the global File type. const file = formData.get("field_2") as File; @@ -136,9 +137,9 @@ testPerm( ); const formData = await response.formData(); assert(formData.has("field_1")); - assertEquals(formData.get("field_1").toString(), "Hi"); + assertEquals(formData.get("field_1")!.toString(), "Hi"); assert(formData.has("field_2")); - assertEquals(formData.get("field_2").toString(), ""); + assertEquals(formData.get("field_2")!.toString(), ""); } ); @@ -179,7 +180,7 @@ testPerm({ net: true }, async function fetchInitStringBody(): Promise { }); const text = await response.text(); assertEquals(text, data); - assert(response.headers.get("content-type").startsWith("text/plain")); + assert(response.headers.get("content-type")!.startsWith("text/plain")); }); testPerm({ net: true }, async function fetchRequestInitStringBody(): Promise< @@ -220,7 +221,7 @@ testPerm({ net: true }, async function fetchInitURLSearchParamsBody(): Promise< assertEquals(text, data); assert( response.headers - .get("content-type") + .get("content-type")! .startsWith("application/x-www-form-urlencoded") ); }); @@ -236,7 +237,7 @@ testPerm({ net: true }, async function fetchInitBlobBody(): Promise { }); const text = await response.text(); assertEquals(text, data); - assert(response.headers.get("content-type").startsWith("text/javascript")); + assert(response.headers.get("content-type")!.startsWith("text/javascript")); }); testPerm({ net: true }, async function fetchUserAgent(): Promise { diff --git a/cli/js/file_test.ts b/cli/js/file_test.ts index 2d009c0c2cfdfc..8fc37f701e9342 100644 --- a/cli/js/file_test.ts +++ b/cli/js/file_test.ts @@ -1,7 +1,8 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEquals } from "./test_util.ts"; -function testFirstArgument(arg1, expectedSize): void { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function testFirstArgument(arg1: any[], expectedSize: number): void { const file = new File(arg1, "name"); assert(file instanceof File); assertEquals(file.name, "name"); @@ -76,7 +77,8 @@ test(function fileObjectInFileBits(): void { testFirstArgument([{}], 15); }); -function testSecondArgument(arg2, expectedFileName): void { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function testSecondArgument(arg2: any, expectedFileName: string): void { const file = new File(["bits"], arg2); assert(file instanceof File); assertEquals(file.name, expectedFileName); diff --git a/cli/js/files_test.ts b/cli/js/files_test.ts index 8f4beb085fc0bc..03e4d00e922c4b 100644 --- a/cli/js/files_test.ts +++ b/cli/js/files_test.ts @@ -157,6 +157,7 @@ testPerm({ write: true }, async function writeNullBufferFailure(): Promise< // writing null should throw an error let err; try { + // @ts-ignore await file.write(null); } catch (e) { err = e; @@ -182,6 +183,7 @@ testPerm( // reading file into null buffer should throw an error let err; try { + // @ts-ignore await file.read(null); } catch (e) { err = e; diff --git a/cli/js/form_data_test.ts b/cli/js/form_data_test.ts index a40326fba6bf0b..99f7a3fa099d3a 100644 --- a/cli/js/form_data_test.ts +++ b/cli/js/form_data_test.ts @@ -36,7 +36,9 @@ test(function formDataParamsGetSuccess(): void { formData.append("a", "true"); formData.append("b", "false"); formData.append("a", "null"); + // @ts-ignore formData.append("d", undefined); + // @ts-ignore formData.append("e", null); assertEquals(formData.get("a"), "true"); assertEquals(formData.get("b"), "false"); @@ -63,8 +65,10 @@ test(function formDataParamsSetSuccess(): void { assertEquals(formData.getAll("b"), ["false"]); formData.set("a", "false"); assertEquals(formData.getAll("a"), ["false"]); + // @ts-ignore formData.set("d", undefined); assertEquals(formData.get("d"), "undefined"); + // @ts-ignore formData.set("e", null); assertEquals(formData.get("e"), "null"); }); @@ -110,6 +114,7 @@ test(function formDataParamsArgumentsCheck(): void { let hasThrown = 0; let errMsg = ""; try { + // @ts-ignore formData[method](); hasThrown = 1; } catch (err) { @@ -133,6 +138,7 @@ test(function formDataParamsArgumentsCheck(): void { let errMsg = ""; try { + // @ts-ignore formData[method](); hasThrown = 1; } catch (err) { @@ -152,6 +158,7 @@ test(function formDataParamsArgumentsCheck(): void { hasThrown = 0; errMsg = ""; try { + // @ts-ignore formData[method]("foo"); hasThrown = 1; } catch (err) { diff --git a/cli/js/headers_test.ts b/cli/js/headers_test.ts index 15e1191f5ed269..265a5948211df0 100644 --- a/cli/js/headers_test.ts +++ b/cli/js/headers_test.ts @@ -2,8 +2,8 @@ import { test, assert, assertEquals } from "./test_util.ts"; const { stringifyArgs - // eslint-disable-next-line @typescript-eslint/no-explicit-any -} = Deno[Deno.symbols.internal] as any; + // @ts-ignore +} = Deno[Deno.symbols.internal]; // Logic heavily copied from web-platform-tests, make // sure pass mostly header basic test @@ -13,6 +13,7 @@ test(function newHeaderTest(): void { new Headers(undefined); new Headers({}); try { + // @ts-ignore new Headers(null); } catch (e) { assertEquals( @@ -22,14 +23,16 @@ test(function newHeaderTest(): void { } }); -const headerDict = { +const headerDict: Record = { name1: "value1", name2: "value2", name3: "value3", + // @ts-ignore name4: undefined, "Content-Type": "value4" }; -const headerSeq = []; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const headerSeq: any[] = []; for (const name in headerDict) { headerSeq.push([name, headerDict[name]]); } @@ -133,7 +136,7 @@ test(function headerValuesSuccess(): void { } }); -const headerEntriesDict = { +const headerEntriesDict: Record = { name1: "value1", Name2: "value2", name: "value3", @@ -261,6 +264,7 @@ test(function headerParamsArgumentsCheck(): void { let hasThrown = 0; let errMsg = ""; try { + // @ts-ignore headers[method](); hasThrown = 1; } catch (err) { @@ -284,6 +288,7 @@ test(function headerParamsArgumentsCheck(): void { let errMsg = ""; try { + // @ts-ignore headers[method](); hasThrown = 1; } catch (err) { @@ -303,6 +308,7 @@ test(function headerParamsArgumentsCheck(): void { hasThrown = 0; errMsg = ""; try { + // @ts-ignore headers[method]("foo"); hasThrown = 1; } catch (err) { diff --git a/cli/js/internals_test.ts b/cli/js/internals_test.ts index 055995fdfb423b..eae47c7b03a423 100644 --- a/cli/js/internals_test.ts +++ b/cli/js/internals_test.ts @@ -4,7 +4,7 @@ import { test, assert } from "./test_util.ts"; test(function internalsExists(): void { const { stringifyArgs - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } = Deno[Deno.symbols.internal] as any; + // @ts-ignore + } = Deno[Deno.symbols.internal]; assert(!!stringifyArgs); }); diff --git a/cli/js/mixins/dom_iterable_test.ts b/cli/js/mixins/dom_iterable_test.ts index 466375d64c3d2c..fc41c4a43f6164 100644 --- a/cli/js/mixins/dom_iterable_test.ts +++ b/cli/js/mixins/dom_iterable_test.ts @@ -20,11 +20,8 @@ function setup() { Base, // This is using an internal API we don't want published as types, so having // to cast to any to "trick" TypeScript - // eslint-disable-next-line @typescript-eslint/no-explicit-any - DomIterable: (Deno[Deno.symbols.internal] as any).DomIterableMixin( - Base, - dataSymbol - ) + // @ts-ignore + DomIterable: Deno[Deno.symbols.internal].DomIterableMixin(Base, dataSymbol) }; } @@ -52,7 +49,12 @@ test(function testDomIterable(): void { result = []; const scope = {}; - function callback(value, key, parent): void { + function callback( + this: typeof scope, + value: number, + key: string, + parent: typeof domIterable + ): void { assertEquals(parent, domIterable); assert(key != null); assert(value != null); @@ -72,7 +74,7 @@ test(function testDomIterableScope(): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any function checkScope(thisArg: any, expected: any): void { - function callback(): void { + function callback(this: typeof thisArg): void { assertEquals(this, expected); } domIterable.forEach(callback, thisArg); diff --git a/cli/js/net_test.ts b/cli/js/net_test.ts index e4d0be81f9c96e..68b1918b9b32c3 100644 --- a/cli/js/net_test.ts +++ b/cli/js/net_test.ts @@ -27,7 +27,7 @@ testPerm({ net: true }, async function netCloseWhileAccept(): Promise { testPerm({ net: true }, async function netConcurrentAccept(): Promise { const listener = Deno.listen({ port: 4502 }); let acceptErrCount = 0; - const checkErr = (e): void => { + const checkErr = (e: Deno.DenoError): void => { assertEquals(e.kind, Deno.ErrorKind.Other); if (e.message === "Listener has been closed") { assertEquals(acceptErrCount, 1); diff --git a/cli/js/os_test.ts b/cli/js/os_test.ts index 6d9309000583fc..54371ea0ea79b5 100644 --- a/cli/js/os_test.ts +++ b/cli/js/os_test.ts @@ -56,7 +56,10 @@ if (Deno.build.os === "win") { // specified in `inputEnv`. The subprocess reads the environment variables // which are in the keys of `expectedEnv` and writes them to stdout as JSON. // It is then verified that these match with the values of `expectedEnv`. - const checkChildEnv = async (inputEnv, expectedEnv): Promise => { + const checkChildEnv = async ( + inputEnv: Record, + expectedEnv: Record + ): Promise => { const src = ` console.log( ${JSON.stringify(Object.keys(expectedEnv))}.map(k => Deno.env(k)) @@ -249,7 +252,7 @@ testPerm({ env: true }, function getDir(): void { if (Deno.build.os !== r.os) continue; if (r.shouldHaveValue) { const d = Deno.dir(s.kind); - assert(d.length > 0); + assert(d!.length > 0); } } } diff --git a/cli/js/process_test.ts b/cli/js/process_test.ts index 943359e54e6d73..500b93d323e05e 100644 --- a/cli/js/process_test.ts +++ b/cli/js/process_test.ts @@ -134,10 +134,10 @@ testPerm({ run: true }, async function runStdinPiped(): Promise { assert(!p.stderr); const msg = new TextEncoder().encode("hello"); - const n = await p.stdin.write(msg); + const n = await p.stdin!.write(msg); assertEquals(n, msg.byteLength); - p.stdin.close(); + p.stdin!.close(); const status = await p.status(); assertEquals(status.success, true); @@ -155,16 +155,16 @@ testPerm({ run: true }, async function runStdoutPiped(): Promise { assert(!p.stderr); const data = new Uint8Array(10); - let r = await p.stdout.read(data); + let r = await p.stdout!.read(data); if (r === Deno.EOF) { throw new Error("p.stdout.read(...) should not be EOF"); } assertEquals(r, 5); const s = new TextDecoder().decode(data.subarray(0, r)); assertEquals(s, "hello"); - r = await p.stdout.read(data); + r = await p.stdout!.read(data); assertEquals(r, Deno.EOF); - p.stdout.close(); + p.stdout!.close(); const status = await p.status(); assertEquals(status.success, true); @@ -182,16 +182,16 @@ testPerm({ run: true }, async function runStderrPiped(): Promise { assert(!p.stdout); const data = new Uint8Array(10); - let r = await p.stderr.read(data); + let r = await p.stderr!.read(data); if (r === Deno.EOF) { throw new Error("p.stderr.read should not return EOF here"); } assertEquals(r, 5); const s = new TextDecoder().decode(data.subarray(0, r)); assertEquals(s, "hello"); - r = await p.stderr.read(data); + r = await p.stderr!.read(data); assertEquals(r, Deno.EOF); - p.stderr.close(); + p.stderr!.close(); const status = await p.status(); assertEquals(status.success, true); @@ -307,7 +307,7 @@ testPerm({ run: true }, async function runClose(): Promise { p.close(); const data = new Uint8Array(10); - const r = await p.stderr.read(data); + const r = await p.stderr!.read(data); assertEquals(r, Deno.EOF); }); diff --git a/cli/js/resources_test.ts b/cli/js/resources_test.ts index 367b66217f62a5..5d1e27af71ad77 100644 --- a/cli/js/resources_test.ts +++ b/cli/js/resources_test.ts @@ -39,8 +39,8 @@ testPerm({ read: true }, async function resourcesFile(): Promise { Object.keys(resourcesAfter).length, Object.keys(resourcesBefore).length + 1 ); - const newRid = Object.keys(resourcesAfter).find((rid): boolean => { + const newRid = +Object.keys(resourcesAfter).find((rid): boolean => { return !resourcesBefore.hasOwnProperty(rid); - }); + })!; assertEquals(resourcesAfter[newRid], "fsFile"); }); diff --git a/cli/js/signal_test.ts b/cli/js/signal_test.ts index 06457314c89275..1c865847777ef3 100644 --- a/cli/js/signal_test.ts +++ b/cli/js/signal_test.ts @@ -8,7 +8,7 @@ import { } from "./test_util.ts"; function defer(n: number): Promise { - return new Promise((resolve, _) => { + return new Promise((resolve: () => void, _) => { setTimeout(resolve, n); }); } diff --git a/cli/js/stat_test.ts b/cli/js/stat_test.ts index 9b03c0ece30670..bce5449acf664f 100644 --- a/cli/js/stat_test.ts +++ b/cli/js/stat_test.ts @@ -210,7 +210,7 @@ if (isWindows) { const s = Deno.statSync(filename); assert(s.dev !== null); assert(s.ino !== null); - assertEquals(s.mode & 0o666, 0o666); + assertEquals(s.mode! & 0o666, 0o666); assertEquals(s.nlink, 2); assert(s.uid !== null); assert(s.gid !== null); diff --git a/cli/js/test_util.ts b/cli/js/test_util.ts index dbb7bf2c47fa13..3e089486b57e97 100644 --- a/cli/js/test_util.ts +++ b/cli/js/test_util.ts @@ -62,7 +62,10 @@ function permissionsMatch( requiredPerms: Permissions ): boolean { for (const permName in processPerms) { - if (processPerms[permName] !== requiredPerms[permName]) { + if ( + processPerms[permName as keyof Permissions] !== + requiredPerms[permName as keyof Permissions] + ) { return false; } } @@ -302,7 +305,7 @@ testPerm( async function assertAllUnitTestFilesImported(): Promise { const directoryTestFiles = Deno.readDirSync("./cli/js") .map(k => k.name) - .filter(file => file.endsWith("_test.ts")); + .filter(file => file!.endsWith("_test.ts")); const unitTestsFile: Uint8Array = Deno.readFileSync( "./cli/js/unit_tests.ts" ); @@ -311,11 +314,11 @@ testPerm( .split("\n") .filter(line => line.startsWith("import") && line.includes("_test.ts")); const importedTestFiles = importLines.map( - relativeFilePath => relativeFilePath.match(/\/([^\/]+)";/)[1] + relativeFilePath => relativeFilePath.match(/\/([^\/]+)";/)![1] ); directoryTestFiles.forEach(dirFile => { - if (!importedTestFiles.includes(dirFile)) { + if (!importedTestFiles.includes(dirFile!)) { throw new Error( "cil/js/unit_tests.ts is missing import of test file: cli/js/" + dirFile diff --git a/cli/js/timers_test.ts b/cli/js/timers_test.ts index b71df9254b55e7..2945857562f063 100644 --- a/cli/js/timers_test.ts +++ b/cli/js/timers_test.ts @@ -7,21 +7,22 @@ function deferred(): { // eslint-disable-next-line @typescript-eslint/no-explicit-any reject: (reason?: any) => void; } { - let resolve; - let reject; - const promise = new Promise((res, rej): void => { + let resolve: ((value?: {} | PromiseLike<{}>) => void) | undefined = undefined; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let reject: ((reason?: any) => void) | undefined = undefined; + const promise = new Promise<{}>((res, rej): void => { resolve = res; reject = rej; }); return { promise, - resolve, - reject + resolve: resolve!, + reject: reject! }; } -async function waitForMs(ms): Promise { - return new Promise((resolve): number => setTimeout(resolve, ms)); +async function waitForMs(ms: number): Promise { + return new Promise((resolve: () => void): number => setTimeout(resolve, ms)); } test(async function timeoutSuccess(): Promise { @@ -133,7 +134,7 @@ test(async function intervalCancelSuccess(): Promise { }); test(async function intervalOrdering(): Promise { - const timers = []; + const timers: number[] = []; let timeouts = 0; function onTimeout(): void { ++timeouts; diff --git a/cli/js/tls_test.ts b/cli/js/tls_test.ts index 1273da34f73d0e..ac59a2eb9ab3da 100644 --- a/cli/js/tls_test.ts +++ b/cli/js/tls_test.ts @@ -195,7 +195,7 @@ testPerm({ read: true, net: true }, async function dialAndListenTLS(): Promise< assertEquals(ok, "OK"); const headers = await tpr.readMIMEHeader(); assert(headers !== Deno.EOF); - const contentLength = parseInt(headers.get("content-length")); + const contentLength = parseInt(headers.get("content-length")!); const bodyBuf = new Uint8Array(contentLength); await r.readFull(bodyBuf); assertEquals(decoder.decode(bodyBuf), "Hello World\n"); diff --git a/cli/js/url_search_params_test.ts b/cli/js/url_search_params_test.ts index c1343e59b8e7d1..8619568bd7339f 100644 --- a/cli/js/url_search_params_test.ts +++ b/cli/js/url_search_params_test.ts @@ -177,6 +177,7 @@ test(function urlSearchParamsAppendArgumentsCheck(): void { const searchParams = new URLSearchParams(); let hasThrown = 0; try { + // @ts-ignore searchParams[method](); hasThrown = 1; } catch (err) { @@ -193,6 +194,7 @@ test(function urlSearchParamsAppendArgumentsCheck(): void { const searchParams = new URLSearchParams(); let hasThrown = 0; try { + // @ts-ignore searchParams[method]("foo"); hasThrown = 1; } catch (err) { @@ -232,6 +234,7 @@ test(function urlSearchParamsCustomSymbolIterator(): void { test(function urlSearchParamsCustomSymbolIteratorWithNonStringParams(): void { const params = {}; + // @ts-ignore params[Symbol.iterator] = function*(): IterableIterator<[number, number]> { yield [1, 2]; }; diff --git a/cli/js/utime_test.ts b/cli/js/utime_test.ts index 15c218df4213c2..251dbbc36f9311 100644 --- a/cli/js/utime_test.ts +++ b/cli/js/utime_test.ts @@ -19,8 +19,8 @@ testPerm({ read: true, write: true }, function utimeSyncFileSuccess(): void { Deno.utimeSync(filename, atime, mtime); const fileInfo = Deno.statSync(filename); - assertFuzzyTimestampEquals(fileInfo.accessed, atime); - assertFuzzyTimestampEquals(fileInfo.modified, mtime); + assertFuzzyTimestampEquals(fileInfo.accessed!, atime); + assertFuzzyTimestampEquals(fileInfo.modified!, mtime); }); testPerm( @@ -33,8 +33,8 @@ testPerm( Deno.utimeSync(testDir, atime, mtime); const dirInfo = Deno.statSync(testDir); - assertFuzzyTimestampEquals(dirInfo.accessed, atime); - assertFuzzyTimestampEquals(dirInfo.modified, mtime); + assertFuzzyTimestampEquals(dirInfo.accessed!, atime); + assertFuzzyTimestampEquals(dirInfo.modified!, mtime); } ); @@ -46,8 +46,8 @@ testPerm({ read: true, write: true }, function utimeSyncDateSuccess(): void { Deno.utimeSync(testDir, new Date(atime * 1000), new Date(mtime * 1000)); const dirInfo = Deno.statSync(testDir); - assertFuzzyTimestampEquals(dirInfo.accessed, atime); - assertFuzzyTimestampEquals(dirInfo.modified, mtime); + assertFuzzyTimestampEquals(dirInfo.accessed!, atime); + assertFuzzyTimestampEquals(dirInfo.modified!, mtime); }); testPerm( @@ -62,8 +62,8 @@ testPerm( Deno.utimeSync(testDir, atime, mtime); const dirInfo = Deno.statSync(testDir); - assertFuzzyTimestampEquals(dirInfo.accessed, atime); - assertFuzzyTimestampEquals(dirInfo.modified, mtime); + assertFuzzyTimestampEquals(dirInfo.accessed!, atime); + assertFuzzyTimestampEquals(dirInfo.modified!, mtime); } ); @@ -111,8 +111,8 @@ testPerm( await Deno.utime(filename, atime, mtime); const fileInfo = Deno.statSync(filename); - assertFuzzyTimestampEquals(fileInfo.accessed, atime); - assertFuzzyTimestampEquals(fileInfo.modified, mtime); + assertFuzzyTimestampEquals(fileInfo.accessed!, atime); + assertFuzzyTimestampEquals(fileInfo.modified!, mtime); } ); @@ -126,8 +126,8 @@ testPerm( await Deno.utime(testDir, atime, mtime); const dirInfo = Deno.statSync(testDir); - assertFuzzyTimestampEquals(dirInfo.accessed, atime); - assertFuzzyTimestampEquals(dirInfo.modified, mtime); + assertFuzzyTimestampEquals(dirInfo.accessed!, atime); + assertFuzzyTimestampEquals(dirInfo.modified!, mtime); } ); @@ -141,8 +141,8 @@ testPerm( await Deno.utime(testDir, new Date(atime * 1000), new Date(mtime * 1000)); const dirInfo = Deno.statSync(testDir); - assertFuzzyTimestampEquals(dirInfo.accessed, atime); - assertFuzzyTimestampEquals(dirInfo.modified, mtime); + assertFuzzyTimestampEquals(dirInfo.accessed!, atime); + assertFuzzyTimestampEquals(dirInfo.modified!, mtime); } ); diff --git a/cli/js/write_file_test.ts b/cli/js/write_file_test.ts index 30500b59404e69..2b952655f56b7f 100644 --- a/cli/js/write_file_test.ts +++ b/cli/js/write_file_test.ts @@ -50,9 +50,9 @@ testPerm({ read: true, write: true }, function writeFileSyncUpdatePerm(): void { const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; Deno.writeFileSync(filename, data, { perm: 0o755 }); - assertEquals(Deno.statSync(filename).mode & 0o777, 0o755); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); Deno.writeFileSync(filename, data, { perm: 0o666 }); - assertEquals(Deno.statSync(filename).mode & 0o777, 0o666); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); } }); @@ -161,9 +161,9 @@ testPerm( const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; await Deno.writeFile(filename, data, { perm: 0o755 }); - assertEquals(Deno.statSync(filename).mode & 0o777, 0o755); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o755); await Deno.writeFile(filename, data, { perm: 0o666 }); - assertEquals(Deno.statSync(filename).mode & 0o777, 0o666); + assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); } } ); diff --git a/cli/tests/046_jsx_test.tsx b/cli/tests/046_jsx_test.tsx index 4e9380eb8f6df5..a3df2aad754307 100644 --- a/cli/tests/046_jsx_test.tsx +++ b/cli/tests/046_jsx_test.tsx @@ -1,3 +1,8 @@ +declare namespace JSX { + interface IntrinsicElements { + [elemName: string]: any; + } +} const React = { createElement(factory: any, props: any, ...children: any[]) { return {factory, props, children} diff --git a/cli/tests/048_media_types_jsx.ts b/cli/tests/048_media_types_jsx.ts index c2340de35b097c..f6a498fdf0bc92 100644 --- a/cli/tests/048_media_types_jsx.ts +++ b/cli/tests/048_media_types_jsx.ts @@ -10,6 +10,16 @@ import { loaded as loadedJsx2 } from "http://localhost:4545/cli/tests/subdir/mt_ import { loaded as loadedJsx3 } from "http://localhost:4545/cli/tests/subdir/mt_text_ecmascript_jsx.j3.jsx"; import { loaded as loadedJsx4 } from "http://localhost:4545/cli/tests/subdir/mt_application_x_javascript_jsx.j4.jsx"; +declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace JSX { + interface IntrinsicElements { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [elemName: string]: any; + } + } +} + console.log( "success", loadedTsx1, diff --git a/std/encoding/base32_test.ts b/std/encoding/base32_test.ts index 6a8734fd01d3ca..eecb001147d2de 100644 --- a/std/encoding/base32_test.ts +++ b/std/encoding/base32_test.ts @@ -7,7 +7,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"), ""); diff --git a/std/encoding/yaml/loader/loader.ts b/std/encoding/yaml/loader/loader.ts index 556bd5b475fccc..7db72a01dc52b8 100644 --- a/std/encoding/yaml/loader/loader.ts +++ b/std/encoding/yaml/loader/loader.ts @@ -187,7 +187,7 @@ interface DirectiveHandlers { [directive: string]: ( state: LoaderState, name: string, - ...args: unknown[] + ...args: string[] ) => void; } @@ -362,7 +362,7 @@ function storeMappingPair( mergeMappings(state, result, valueNode[index], overridableKeys); } } else { - mergeMappings(state, result, valueNode, overridableKeys); + mergeMappings(state, result, valueNode as ArrayObject, overridableKeys); } } else { if ( @@ -1610,7 +1610,7 @@ function readDocument(state: LoaderState): void { const documentStart = state.position; let position: number, directiveName: string, - directiveArgs: unknown[], + directiveArgs: string[], hasDirectives = false, ch: number; diff --git a/std/examples/gist.ts b/std/examples/gist.ts index ead97c7e2e8184..8fc97e0f832c3a 100755 --- a/std/examples/gist.ts +++ b/std/examples/gist.ts @@ -24,7 +24,7 @@ if (parsedArgs._.length === 0) { Deno.exit(1); } -const files = {}; +const files: Record = {}; for (const filename of parsedArgs._) { const base = pathBase(filename); const content = await Deno.readFile(filename); diff --git a/std/fs/empty_dir_test.ts b/std/fs/empty_dir_test.ts index b9145767e1b201..2f5b175bea3f02 100644 --- a/std/fs/empty_dir_test.ts +++ b/std/fs/empty_dir_test.ts @@ -226,7 +226,7 @@ test(async function emptyDirPermission(): Promise { args: args }); - const output = await Deno.readAll(stdout); + const output = await Deno.readAll(stdout!); assertStrContains(new TextDecoder().decode(output), s.output); } diff --git a/std/fs/exists_test.ts b/std/fs/exists_test.ts index c7c7dc54e96905..f3b11b7dc8023d 100644 --- a/std/fs/exists_test.ts +++ b/std/fs/exists_test.ts @@ -132,7 +132,7 @@ test(async function existsPermission(): Promise { args: args }); - const output = await Deno.readAll(stdout); + const output = await Deno.readAll(stdout!); assertStrContains(new TextDecoder().decode(output), s.output); } diff --git a/std/fs/walk.ts b/std/fs/walk.ts index 108eebc46654ac..89011452572f06 100644 --- a/std/fs/walk.ts +++ b/std/fs/walk.ts @@ -65,9 +65,9 @@ export async function* walk( includeFiles = true, includeDirs = true, followSymlinks = false, - exts = null, - match = null, - skip = null + exts = undefined, + match = undefined, + skip = undefined }: WalkOptions = {} ): AsyncIterableIterator { if (maxDepth < 0) { @@ -76,7 +76,7 @@ export async function* walk( if (includeDirs && include(root, exts, match, skip)) { yield { filename: root, info: await stat(root) }; } - if (maxDepth < 1 || !include(root, null, null, skip)) { + if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { return; } const ls: FileInfo[] = await readDir(root); @@ -119,9 +119,9 @@ export function* walkSync( includeFiles = true, includeDirs = true, followSymlinks = false, - exts = null, - match = null, - skip = null + exts = undefined, + match = undefined, + skip = undefined }: WalkOptions = {} ): IterableIterator { if (maxDepth < 0) { @@ -130,7 +130,7 @@ export function* walkSync( if (includeDirs && include(root, exts, match, skip)) { yield { filename: root, info: statSync(root) }; } - if (maxDepth < 1 || !include(root, null, null, skip)) { + if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { return; } const ls: FileInfo[] = readDirSync(root); diff --git a/std/http/cookie.ts b/std/http/cookie.ts index 5e4f38a291012d..090196891061c6 100644 --- a/std/http/cookie.ts +++ b/std/http/cookie.ts @@ -45,7 +45,7 @@ function toString(cookie: Cookie): string { if (cookie.httpOnly) { out.push("HttpOnly"); } - if (Number.isInteger(cookie.maxAge)) { + if (typeof cookie.maxAge == "number" && Number.isInteger(cookie.maxAge)) { assert(cookie.maxAge > 0, "Max-Age must be an integer superior to 0"); out.push(`Max-Age=${cookie.maxAge}`); } diff --git a/std/http/file_server.ts b/std/http/file_server.ts index acf272764d5c48..619f89f7986f8e 100755 --- a/std/http/file_server.ts +++ b/std/http/file_server.ts @@ -125,8 +125,8 @@ async function serveDir( const listEntry: EntryInfo[] = []; const fileInfos = await readDir(dirPath); for (const fileInfo of fileInfos) { - const filePath = posix.join(dirPath, fileInfo.name); - const fileUrl = posix.join(dirUrl, fileInfo.name); + const filePath = posix.join(dirPath, fileInfo.name || ""); + const fileUrl = posix.join(dirUrl, fileInfo.name || ""); if (fileInfo.name === "index.html" && fileInfo.isFile()) { // in case index.html as dir... return await serveFile(req, filePath); @@ -139,7 +139,7 @@ async function serveDir( listEntry.push({ mode: modeToString(fileInfo.isDirectory(), mode), size: fileInfo.isFile() ? fileLenToString(fileInfo.len) : "", - name: fileInfo.name, + name: fileInfo.name || "", url: fileUrl }); } @@ -305,7 +305,7 @@ listenAndServe( const decodedUrl = decodeURIComponent(normalizedUrl); const fsPath = posix.join(target, decodedUrl); - let response: Response; + let response: Response | undefined; try { const info = await stat(fsPath); if (info.isDirectory()) { @@ -318,10 +318,10 @@ listenAndServe( response = await serveFallback(req, e); } finally { if (CORSEnabled) { - setCORS(response); + setCORS(response!); } - serverLog(req, response); - req.respond(response); + serverLog(req, response!); + req.respond(response!); } } ); diff --git a/std/http/file_server_test.ts b/std/http/file_server_test.ts index 099723b878edd5..3c290f8de08724 100644 --- a/std/http/file_server_test.ts +++ b/std/http/file_server_test.ts @@ -38,7 +38,7 @@ test(async function serveFile(): Promise { assert(res.headers.has("access-control-allow-origin")); assert(res.headers.has("access-control-allow-headers")); assert(res.headers.has("content-type")); - assert(res.headers.get("content-type").includes("charset=utf-8")); + assert(res.headers.get("content-type")!.includes("charset=utf-8")); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( await Deno.readFile("README.md") diff --git a/std/http/server.ts b/std/http/server.ts index b8a41379f0b6e7..be5c23139c244f 100644 --- a/std/http/server.ts +++ b/std/http/server.ts @@ -435,7 +435,7 @@ export class Server implements AsyncIterable { ): AsyncIterableIterator { const bufr = new BufReader(conn); const w = new BufWriter(conn); - let req: ServerRequest | Deno.EOF; + let req: ServerRequest | Deno.EOF | undefined; let err: Error | undefined; while (!this.closing) { diff --git a/std/http/server_test.ts b/std/http/server_test.ts index 10b0fec20fec7e..7e8975fc22d13e 100644 --- a/std/http/server_test.ts +++ b/std/http/server_test.ts @@ -545,7 +545,7 @@ test(async function testReadRequestError(): Promise { for (const test of testCases) { const reader = new BufReader(new StringReader(test.in)); let err; - let req: ServerRequest | Deno.EOF; + let req: ServerRequest | Deno.EOF | undefined; try { req = await readRequest(mockConn as Deno.Conn, reader); } catch (e) { @@ -562,7 +562,7 @@ test(async function testReadRequestError(): Promise { assert(test.headers != null); assertEquals(err, undefined); assertNotEquals(req, Deno.EOF); - for (const h of test.headers) { + for (const h of test.headers!) { assertEquals(req.headers.get(h.key), h.value); } } diff --git a/std/node/global.ts b/std/node/global.ts index c21b0b6596903f..eb66970cfd469b 100644 --- a/std/node/global.ts +++ b/std/node/global.ts @@ -1 +1,2 @@ +// @ts-ignore window["global"] = window; diff --git a/std/node/module.ts b/std/node/module.ts index ac436c55520400..1086f0bbdeeb6e 100644 --- a/std/node/module.ts +++ b/std/node/module.ts @@ -40,7 +40,7 @@ const isWindows = path.isWindows; const relativeResolveCache = Object.create(null); let requireDepth = 0; -let statCache = null; +let statCache: Map | null = null; type StatResult = -1 | 0 | 1; // Returns 0 if the path refers to @@ -64,7 +64,11 @@ function stat(filename: string): StatResult { } } -function updateChildren(parent: Module, child: Module, scan: boolean): void { +function updateChildren( + parent: Module | null, + child: Module, + scan: boolean +): void { const children = parent && parent.children; if (children && !(scan && children.includes(child))) { children.push(child); @@ -75,17 +79,17 @@ class Module { id: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any exports: any; - parent?: Module; - filename: string; + parent: Module | null; + filename: string | null; loaded: boolean; children: Module[]; paths: string[]; path: string; - constructor(id = "", parent?: Module) { + constructor(id = "", parent?: Module | null) { this.id = id; this.exports = {}; - this.parent = parent; - updateChildren(parent, this, false); + this.parent = parent || null; + updateChildren(parent || null, this, false); this.filename = null; this.loaded = false; this.children = []; @@ -229,25 +233,25 @@ class Module { fakeParent.paths = Module._nodeModulePaths(path); const lookupPaths = Module._resolveLookupPaths(request, fakeParent); - for (let j = 0; j < lookupPaths.length; j++) { - if (!paths.includes(lookupPaths[j])) paths.push(lookupPaths[j]); + for (let j = 0; j < lookupPaths!.length; j++) { + if (!paths.includes(lookupPaths![j])) paths.push(lookupPaths![j]); } } } } else if (options.paths === undefined) { - paths = Module._resolveLookupPaths(request, parent); + paths = Module._resolveLookupPaths(request, parent)!; } else { throw new Error("options.paths is invalid"); } } else { - paths = Module._resolveLookupPaths(request, parent); + paths = Module._resolveLookupPaths(request, parent)!; } // Look up the filename first, since that's the cache key. const filename = Module._findPath(request, paths, isMain); if (!filename) { const requireStack = []; - for (let cursor = parent; cursor; cursor = cursor.parent) { + for (let cursor: Module | null = parent; cursor; cursor = cursor.parent) { requireStack.push(cursor.filename || cursor.id); } let message = `Cannot find module '${request}'`; @@ -341,7 +345,7 @@ class Module { // object. // eslint-disable-next-line @typescript-eslint/no-explicit-any static _load(request: string, parent: Module, isMain: boolean): any { - let relResolveCacheIdentifier; + let relResolveCacheIdentifier: string | undefined; if (parent) { // Fast path for (lazy loaded) modules in the same directory. The indirect // caching is required to allow cache invalidation without changing the old @@ -385,7 +389,7 @@ class Module { Module._cache[filename] = module; if (parent !== undefined) { - relativeResolveCache[relResolveCacheIdentifier] = filename; + relativeResolveCache[relResolveCacheIdentifier!] = filename; } let threw = true; @@ -397,7 +401,7 @@ class Module { if (threw) { delete Module._cache[filename]; if (parent !== undefined) { - delete relativeResolveCache[relResolveCacheIdentifier]; + delete relativeResolveCache[relResolveCacheIdentifier!]; } } else if ( module.exports && @@ -602,7 +606,7 @@ for (const id of nativeModulePolyfill.keys()) { Module.builtinModules.push(id); } -let modulePaths = []; +let modulePaths: string[] = []; // Given a module name, and a list of paths to test, returns the first // matching file in the following precedence. @@ -664,7 +668,7 @@ function readPackage(requestPath: string): PackageInfo | null { } function readPackageScope( - checkPath + checkPath: string ): { path: string; data: PackageInfo } | false { const rootSeparatorIndex = checkPath.indexOf(path.sep); let separatorIndex; @@ -987,6 +991,7 @@ const CircularRequirePrototypeWarningProxy = new Proxy( { // eslint-disable-next-line @typescript-eslint/no-explicit-any get(target, prop): any { + // @ts-ignore if (prop in target) return target[prop]; emitCircularRequireWarning(prop); return undefined; @@ -1150,7 +1155,7 @@ function getPathFromURLWin32(url: URL): string { let pathname = url.pathname; for (let n = 0; n < pathname.length; n++) { if (pathname[n] === "%") { - const third = pathname.codePointAt(n + 2) | 0x20; + const third = pathname.codePointAt(n + 2)! | 0x20; if ( (pathname[n + 1] === "2" && third === 102) || // 2f 2F / (pathname[n + 1] === "5" && third === 99) @@ -1165,7 +1170,7 @@ function getPathFromURLWin32(url: URL): string { pathname = pathname.replace(forwardSlashRegEx, "\\"); pathname = decodeURIComponent(pathname); // TODO: handle windows hostname case (needs bindings) - const letter = pathname.codePointAt(1) | 0x20; + const letter = pathname.codePointAt(1)! | 0x20; const sep = pathname[2]; if ( letter < CHAR_LOWERCASE_A || @@ -1184,7 +1189,7 @@ function getPathFromURLPosix(url: URL): string { const pathname = url.pathname; for (let n = 0; n < pathname.length; n++) { if (pathname[n] === "%") { - const third = pathname.codePointAt(n + 2) | 0x20; + const third = pathname.codePointAt(n + 2)! | 0x20; if (pathname[n + 1] === "2" && third === 102) { throw new Error( "Invalid file URL path: must not include encoded / characters" diff --git a/std/node/os.ts b/std/node/os.ts index e4a00c450d3da3..3bff03a69c70e5 100644 --- a/std/node/os.ts +++ b/std/node/os.ts @@ -123,7 +123,7 @@ export function getPriority(pid = 0): number { } /** Returns the string path of the current user's home directory. */ -export function homedir(): string { +export function homedir(): string | null { return Deno.dir("home"); } @@ -157,7 +157,7 @@ export function release(): string { /** Not yet implemented */ export function setPriority(pid: number, priority?: number): void { - /* The node API has the 'pid' as the first parameter and as optional. + /* The node API has the 'pid' as the first parameter and as optional. This makes for a problematic implementation in Typescript. */ if (priority === undefined) { priority = pid; diff --git a/std/path/utils.ts b/std/path/utils.ts index 9911f5347d17dd..cb1c14c16148ac 100644 --- a/std/path/utils.ts +++ b/std/path/utils.ts @@ -46,13 +46,13 @@ export function normalizeString( let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; - let code: number; + let code: number | undefined; for (let i = 0, len = path.length; i <= len; ++i) { if (i < len) code = path.charCodeAt(i); - else if (isPathSeparator(code)) break; + else if (isPathSeparator(code!)) break; else code = CHAR_FORWARD_SLASH; - if (isPathSeparator(code)) { + if (isPathSeparator(code!)) { if (lastSlash === i - 1 || dots === 1) { // NOOP } else if (lastSlash !== i - 1 && dots === 2) { diff --git a/std/path/win32.ts b/std/path/win32.ts index 11518ee7c26f81..7c7324ed783100 100644 --- a/std/path/win32.ts +++ b/std/path/win32.ts @@ -303,7 +303,7 @@ export function join(...paths: string[]): string { if (pathsCount === 0) return "."; let joined: string | undefined; - let firstPart: string; + let firstPart: string | null = null; for (let i = 0; i < pathsCount; ++i) { const path = paths[i]; assertPath(path); @@ -331,14 +331,14 @@ export function join(...paths: string[]): string { let needsReplace = true; let slashCount = 0; assert(firstPart != null); - if (isPathSeparator(firstPart.charCodeAt(0))) { + if (isPathSeparator(firstPart!.charCodeAt(0))) { ++slashCount; - const firstLen = firstPart.length; + const firstLen = firstPart!.length; if (firstLen > 1) { - if (isPathSeparator(firstPart.charCodeAt(1))) { + if (isPathSeparator(firstPart!.charCodeAt(1))) { ++slashCount; if (firstLen > 2) { - if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; + if (isPathSeparator(firstPart!.charCodeAt(2))) ++slashCount; else { // We matched a UNC path in the first part needsReplace = false; diff --git a/std/textproto/mod.ts b/std/textproto/mod.ts index 46575382399020..dd7d3ede994d31 100644 --- a/std/textproto/mod.ts +++ b/std/textproto/mod.ts @@ -67,7 +67,7 @@ export class TextProtoReader { */ async readMIMEHeader(): Promise { const m = new Headers(); - let line: Uint8Array; + let line: Uint8Array | undefined; // The first line cannot start with a leading space. let buf = await this.r.peek(1); @@ -135,7 +135,7 @@ export class TextProtoReader { async readLineSlice(): Promise { // this.closeDot(); - let line: Uint8Array; + let line: Uint8Array | undefined; while (true) { const r = await this.r.readLine(); if (r === Deno.EOF) return Deno.EOF; diff --git a/std/util/deep_assign.ts b/std/util/deep_assign.ts index 9b57e45dc8c494..36777795c270a3 100644 --- a/std/util/deep_assign.ts +++ b/std/util/deep_assign.ts @@ -24,7 +24,7 @@ export function deepAssign( if (typeof target[key] !== `object` || !target[key]) { target[key] = {}; } - deepAssign(target[key] as Record, value); + deepAssign(target[key] as Record, value!); }); } return target;