diff options
author | Ryan Dahl <ry@tinyclouds.org> | 2019-04-21 16:40:10 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-04-21 16:40:10 -0400 |
commit | 9dfebbc9496138efbeedc431068f41662c780f3e (patch) | |
tree | c3718c3dc132d11c08c8fc18933daebf886bf787 /js | |
parent | 6cded14bdf313762956d4d5361cfe8115628b535 (diff) |
Fix eslint warnings (#2151)
Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
Co-authored-by: LE GOFF Vincent <g_n_s@hotmail.fr>
Diffstat (limited to 'js')
59 files changed, 1077 insertions, 910 deletions
diff --git a/js/blob.ts b/js/blob.ts index 092bfaa08..7b4d23c46 100644 --- a/js/blob.ts +++ b/js/blob.ts @@ -60,8 +60,8 @@ function processBlobParts( // instead of dynamic allocation. const uint8Arrays = toUint8Arrays(blobParts, normalizeLineEndingsToNative); const byteLength = uint8Arrays - .map(u8 => u8.byteLength) - .reduce((a, b) => a + b, 0); + .map((u8): number => u8.byteLength) + .reduce((a, b): number => a + b, 0); const ab = new ArrayBuffer(byteLength); const bytes = new Uint8Array(ab); diff --git a/js/blob_test.ts b/js/blob_test.ts index 3c778a0e1..b11a22f3c 100644 --- a/js/blob_test.ts +++ b/js/blob_test.ts @@ -1,14 +1,14 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEquals } from "./test_util.ts"; -test(function blobString() { +test(function blobString(): void { const b1 = new Blob(["Hello World"]); const str = "Test"; const b2 = new Blob([b1, str]); assertEquals(b2.size, b1.size + str.length); }); -test(function blobBuffer() { +test(function blobBuffer(): void { const buffer = new ArrayBuffer(12); const u8 = new Uint8Array(buffer); const f1 = new Float32Array(buffer); @@ -18,7 +18,7 @@ test(function blobBuffer() { assertEquals(b2.size, 3 * u8.length); }); -test(function blobSlice() { +test(function blobSlice(): void { const blob = new Blob(["Deno", "Foo"]); const b1 = blob.slice(0, 3, "Text/HTML"); assert(b1 instanceof Blob); @@ -32,7 +32,7 @@ test(function blobSlice() { assertEquals(b4.size, blob.size); }); -test(function blobShouldNotThrowError() { +test(function blobShouldNotThrowError(): void { let hasThrown = false; try { diff --git a/js/buffer_test.ts b/js/buffer_test.ts index f07d9d65d..b4ed3a58a 100644 --- a/js/buffer_test.ts +++ b/js/buffer_test.ts @@ -76,13 +76,13 @@ function repeat(c: string, bytes: number): Uint8Array { return ui8; } -test(function bufferNewBuffer() { +test(function bufferNewBuffer(): void { init(); const buf = new Buffer(testBytes.buffer as ArrayBuffer); check(buf, testString); }); -test(async function bufferBasicOperations() { +test(async function bufferBasicOperations(): Promise<void> { init(); let buf = new Buffer(); for (let i = 0; i < 5; i++) { @@ -120,7 +120,7 @@ test(async function bufferBasicOperations() { } }); -test(async function bufferReadEmptyAtEOF() { +test(async function bufferReadEmptyAtEOF(): Promise<void> { // check that EOF of 'buf' is not reached (even though it's empty) if // results are written to buffer that has 0 length (ie. it can't store any data) let buf = new Buffer(); @@ -130,7 +130,7 @@ test(async function bufferReadEmptyAtEOF() { assertEquals(result.eof, false); }); -test(async function bufferLargeByteWrites() { +test(async function bufferLargeByteWrites(): Promise<void> { init(); const buf = new Buffer(); const limit = 9; @@ -141,7 +141,7 @@ test(async function bufferLargeByteWrites() { check(buf, ""); }); -test(async function bufferTooLargeByteWrites() { +test(async function bufferTooLargeByteWrites(): Promise<void> { init(); const tmp = new Uint8Array(72); const growLen = Number.MAX_VALUE; @@ -160,7 +160,7 @@ test(async function bufferTooLargeByteWrites() { assertEquals(err.name, "TooLarge"); }); -test(async function bufferLargeByteReads() { +test(async function bufferLargeByteReads(): Promise<void> { init(); const buf = new Buffer(); for (let i = 3; i < 30; i += 3) { @@ -171,12 +171,12 @@ test(async function bufferLargeByteReads() { check(buf, ""); }); -test(function bufferCapWithPreallocatedSlice() { +test(function bufferCapWithPreallocatedSlice(): void { const buf = new Buffer(new ArrayBuffer(10)); assertEquals(buf.capacity, 10); }); -test(async function bufferReadFrom() { +test(async function bufferReadFrom(): Promise<void> { init(); const buf = new Buffer(); for (let i = 3; i < 30; i += 3) { @@ -193,7 +193,7 @@ test(async function bufferReadFrom() { } }); -test(async function bufferReadFromSync() { +test(async function bufferReadFromSync(): Promise<void> { init(); const buf = new Buffer(); for (let i = 3; i < 30; i += 3) { @@ -210,7 +210,7 @@ test(async function bufferReadFromSync() { } }); -test(async function bufferTestGrow() { +test(async function bufferTestGrow(): Promise<void> { const tmp = new Uint8Array(72); for (let startLen of [0, 100, 1000, 10000, 100000]) { const xBytes = repeat("x", startLen); @@ -234,7 +234,7 @@ test(async function bufferTestGrow() { } }); -test(async function testReadAll() { +test(async function testReadAll(): Promise<void> { init(); const reader = new Buffer(testBytes.buffer as ArrayBuffer); const actualBytes = await readAll(reader); @@ -244,7 +244,7 @@ test(async function testReadAll() { } }); -test(function testReadAllSync() { +test(function testReadAllSync(): void { init(); const reader = new Buffer(testBytes.buffer as ArrayBuffer); const actualBytes = readAllSync(reader); diff --git a/js/build_test.ts b/js/build_test.ts index 106b5b184..4a254e7a6 100644 --- a/js/build_test.ts +++ b/js/build_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert } from "./test_util.ts"; -test(function buildInfo() { +test(function buildInfo(): void { // Deno.build is injected by rollup at compile time. Here // we check it has been properly transformed. const { arch, os } = Deno.build; @@ -9,6 +9,6 @@ test(function buildInfo() { assert(os === "mac" || os === "win" || os === "linux"); }); -test(function buildGnArgs() { +test(function buildGnArgs(): void { assert(Deno.build.args.length > 100); }); diff --git a/js/chmod_test.ts b/js/chmod_test.ts index 32e3ed1d1..420f4f313 100644 --- a/js/chmod_test.ts +++ b/js/chmod_test.ts @@ -3,7 +3,7 @@ import { testPerm, assertEquals } from "./test_util.ts"; const isNotWindows = Deno.build.os !== "win"; -testPerm({ read: true, write: true }, function chmodSyncSuccess() { +testPerm({ read: true, write: true }, function chmodSyncSuccess(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -22,30 +22,33 @@ testPerm({ read: true, write: true }, function chmodSyncSuccess() { // Check symlink when not on windows if (isNotWindows) { - testPerm({ read: true, write: true }, function chmodSyncSymlinkSuccess() { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const tempDir = Deno.makeTempDirSync(); - - const filename = tempDir + "/test.txt"; - Deno.writeFileSync(filename, data, { perm: 0o666 }); - const symlinkName = tempDir + "/test_symlink.txt"; - Deno.symlinkSync(filename, symlinkName); - - let symlinkInfo = Deno.lstatSync(symlinkName); - 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); - symlinkInfo = Deno.lstatSync(symlinkName); - assertEquals(symlinkInfo.mode & 0o777, symlinkMode); - }); + testPerm( + { read: true, write: true }, + function chmodSyncSymlinkSuccess(): void { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const tempDir = Deno.makeTempDirSync(); + + const filename = tempDir + "/test.txt"; + Deno.writeFileSync(filename, data, { perm: 0o666 }); + const symlinkName = tempDir + "/test_symlink.txt"; + Deno.symlinkSync(filename, symlinkName); + + let symlinkInfo = Deno.lstatSync(symlinkName); + 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); + symlinkInfo = Deno.lstatSync(symlinkName); + assertEquals(symlinkInfo.mode & 0o777, symlinkMode); + } + ); } -testPerm({ write: true }, function chmodSyncFailure() { +testPerm({ write: true }, function chmodSyncFailure(): void { let err; try { const filename = "/badfile.txt"; @@ -57,7 +60,7 @@ testPerm({ write: true }, function chmodSyncFailure() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: false }, function chmodSyncPerm() { +testPerm({ write: false }, function chmodSyncPerm(): void { let err; try { Deno.chmodSync("/somefile.txt", 0o777); @@ -68,7 +71,9 @@ testPerm({ write: false }, function chmodSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ read: true, write: true }, async function chmodSuccess() { +testPerm({ read: true, write: true }, async function chmodSuccess(): Promise< + void +> { const enc = new TextEncoder(); const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); @@ -87,30 +92,33 @@ testPerm({ read: true, write: true }, async function chmodSuccess() { // Check symlink when not on windows if (isNotWindows) { - testPerm({ read: true, write: true }, async function chmodSymlinkSuccess() { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const tempDir = Deno.makeTempDirSync(); - - const filename = tempDir + "/test.txt"; - Deno.writeFileSync(filename, data, { perm: 0o666 }); - const symlinkName = tempDir + "/test_symlink.txt"; - Deno.symlinkSync(filename, symlinkName); - - let symlinkInfo = Deno.lstatSync(symlinkName); - 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); - symlinkInfo = Deno.lstatSync(symlinkName); - assertEquals(symlinkInfo.mode & 0o777, symlinkMode); - }); + testPerm( + { read: true, write: true }, + async function chmodSymlinkSuccess(): Promise<void> { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const tempDir = Deno.makeTempDirSync(); + + const filename = tempDir + "/test.txt"; + Deno.writeFileSync(filename, data, { perm: 0o666 }); + const symlinkName = tempDir + "/test_symlink.txt"; + Deno.symlinkSync(filename, symlinkName); + + let symlinkInfo = Deno.lstatSync(symlinkName); + 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); + symlinkInfo = Deno.lstatSync(symlinkName); + assertEquals(symlinkInfo.mode & 0o777, symlinkMode); + } + ); } -testPerm({ write: true }, async function chmodFailure() { +testPerm({ write: true }, async function chmodFailure(): Promise<void> { let err; try { const filename = "/badfile.txt"; @@ -122,7 +130,7 @@ testPerm({ write: true }, async function chmodFailure() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: false }, async function chmodPerm() { +testPerm({ write: false }, async function chmodPerm(): Promise<void> { let err; try { await Deno.chmod("/somefile.txt", 0o777); diff --git a/js/compiler.ts b/js/compiler.ts index 1a85de5f5..fffb9e852 100644 --- a/js/compiler.ts +++ b/js/compiler.ts @@ -349,7 +349,7 @@ class Compiler implements ts.LanguageServiceHost, ts.FormatDiagnosticsHost { // so we will ignore complaints about this compiler setting. ...service .getCompilerOptionsDiagnostics() - .filter(diagnostic => diagnostic.code !== 5070), + .filter((diagnostic): boolean => diagnostic.code !== 5070), ...service.getSyntacticDiagnostics(fileName), ...service.getSemanticDiagnostics(fileName) ]; @@ -519,9 +519,9 @@ window.TextEncoder = TextEncoder; // provide the "main" function that will be called by the privileged side when // lazy instantiating the compiler web worker -window.compilerMain = function compilerMain() { +window.compilerMain = function compilerMain(): void { // workerMain should have already been called since a compiler is a worker. - window.onmessage = ({ data }: { data: CompilerLookup }) => { + window.onmessage = ({ data }: { data: CompilerLookup }): void => { const { specifier, referrer, cmdId } = data; try { diff --git a/js/console.ts b/js/console.ts index c16ea0302..b2f7e7cbb 100644 --- a/js/console.ts +++ b/js/console.ts @@ -171,7 +171,7 @@ function createArrayString( typeName: "Array", displayName: "", delims: ["[", "]"], - entryHandler: (el, ctx, level, maxLevel) => + entryHandler: (el, ctx, level, maxLevel): string => stringifyWithQuotes(el, ctx, level + 1, maxLevel) }; return createIterableString(value, ctx, level, maxLevel, printConfig); @@ -188,7 +188,7 @@ function createTypedArrayString( typeName: typedArrayName, displayName: typedArrayName, delims: ["[", "]"], - entryHandler: (el, ctx, level, maxLevel) => + entryHandler: (el, ctx, level, maxLevel): string => stringifyWithQuotes(el, ctx, level + 1, maxLevel) }; return createIterableString(value, ctx, level, maxLevel, printConfig); @@ -204,7 +204,7 @@ function createSetString( typeName: "Set", displayName: "Set", delims: ["{", "}"], - entryHandler: (el, ctx, level, maxLevel) => + entryHandler: (el, ctx, level, maxLevel): string => stringifyWithQuotes(el, ctx, level + 1, maxLevel) }; return createIterableString(value, ctx, level, maxLevel, printConfig); @@ -220,7 +220,7 @@ function createMapString( typeName: "Map", displayName: "Map", delims: ["{", "}"], - entryHandler: (el, ctx, level, maxLevel) => { + entryHandler: (el, ctx, level, maxLevel): string => { const [key, val] = el; return `${stringifyWithQuotes( key, @@ -288,18 +288,20 @@ function createRawObjectString( shouldShowClassName = true; } const keys = Object.keys(value); - const entries: string[] = keys.map(key => { - if (keys.length > OBJ_ABBREVIATE_SIZE) { - return key; - } else { - return `${key}: ${stringifyWithQuotes( - value[key], - ctx, - level + 1, - maxLevel - )}`; + const entries: string[] = keys.map( + (key): string => { + if (keys.length > OBJ_ABBREVIATE_SIZE) { + return key; + } else { + return `${key}: ${stringifyWithQuotes( + value[key], + ctx, + level + 1, + maxLevel + )}`; + } } - }); + ); ctx.delete(value); @@ -514,7 +516,7 @@ export class Console { info = this.log; /** Writes the properties of the supplied `obj` to stdout */ - dir = (obj: unknown, options: ConsoleOptions = {}) => { + dir = (obj: unknown, options: ConsoleOptions = {}): void => { this.log(stringifyArgs([obj], options)); }; @@ -601,7 +603,7 @@ export class Console { const toTable = (header: string[], body: string[][]): void => this.log(cliTable(header, body)); const createColumn = (value: unknown, shift?: number): string[] => [ - ...(shift ? [...new Array(shift)].map(() => "") : []), + ...(shift ? [...new Array(shift)].map((): string => "") : []), stringifyValue(value) ]; @@ -617,39 +619,43 @@ export class Console { let idx = 0; resultData = {}; - data.forEach((v: unknown, k: unknown) => { - resultData[idx] = { Key: k, Values: v }; - idx++; - }); + data.forEach( + (v: unknown, k: unknown): void => { + resultData[idx] = { Key: k, Values: v }; + idx++; + } + ); } else { resultData = data!; } - Object.keys(resultData).forEach((k, idx) => { - const value: unknown = resultData[k]!; + Object.keys(resultData).forEach( + (k, idx): void => { + const value: unknown = resultData[k]!; - if (value !== null && typeof value === "object") { - Object.entries(value as { [key: string]: unknown }).forEach( - ([k, v]) => { - if (properties && !properties.includes(k)) { - return; - } + if (value !== null && typeof value === "object") { + Object.entries(value as { [key: string]: unknown }).forEach( + ([k, v]): void => { + if (properties && !properties.includes(k)) { + return; + } - if (objectValues[k]) { - objectValues[k].push(stringifyValue(v)); - } else { - objectValues[k] = createColumn(v, idx); + if (objectValues[k]) { + objectValues[k].push(stringifyValue(v)); + } else { + objectValues[k] = createColumn(v, idx); + } } - } - ); + ); - values.push(""); - } else { - values.push(stringifyValue(value)); - } + values.push(""); + } else { + values.push(stringifyValue(value)); + } - indexKeys.push(k); - }); + indexKeys.push(k); + } + ); const headerKeys = Object.keys(objectValues); const bodyValues = Object.values(objectValues); diff --git a/js/console_table.ts b/js/console_table.ts index 43819c5fe..d4a404aa1 100644 --- a/js/console_table.ts +++ b/js/console_table.ts @@ -53,9 +53,9 @@ function renderRow(row: string[], columnWidths: number[]): string { export function cliTable(head: string[], columns: string[][]): string { const rows: string[][] = []; - const columnWidths = head.map((h: string) => countBytes(h)); + const columnWidths = head.map((h: string): number => countBytes(h)); const longestColumn = columns.reduce( - (n: number, a: string[]) => Math.max(n, a.length), + (n: number, a: string[]): number => Math.max(n, a.length), 0 ); @@ -72,8 +72,8 @@ export function cliTable(head: string[], columns: string[][]): string { } } - const divider = columnWidths.map((i: number) => - tableChars.middleMiddle.repeat(i + 2) + const divider = columnWidths.map( + (i: number): string => tableChars.middleMiddle.repeat(i + 2) ); let result = diff --git a/js/console_test.ts b/js/console_test.ts index a4ff8a4da..32e2c5ae2 100644 --- a/js/console_test.ts +++ b/js/console_test.ts @@ -12,7 +12,7 @@ function stringify(...args: unknown[]): string { // test cases from web-platform-tests // via https://github.com/web-platform-tests/wpt/blob/master/console/console-is-a-namespace.any.js -test(function consoleShouldBeANamespace() { +test(function consoleShouldBeANamespace(): void { const prototype1 = Object.getPrototypeOf(console); const prototype2 = Object.getPrototypeOf(prototype1); @@ -20,12 +20,12 @@ test(function consoleShouldBeANamespace() { assertEquals(prototype2, Object.prototype); }); -test(function consoleHasRightInstance() { +test(function consoleHasRightInstance(): void { assert(console instanceof Console); assertEquals({} instanceof Console, false); }); -test(function consoleTestAssertShouldNotThrowError() { +test(function consoleTestAssertShouldNotThrowError(): void { console.assert(true); let hasThrown = undefined; @@ -38,13 +38,13 @@ test(function consoleTestAssertShouldNotThrowError() { assertEquals(hasThrown, false); }); -test(function consoleTestStringifyComplexObjects() { +test(function consoleTestStringifyComplexObjects(): void { assertEquals(stringify("foo"), "foo"); assertEquals(stringify(["foo", "bar"]), `[ "foo", "bar" ]`); assertEquals(stringify({ foo: "bar" }), `{ foo: "bar" }`); }); -test(function consoleTestStringifyLongStrings() { +test(function consoleTestStringifyLongStrings(): void { const veryLongString = "a".repeat(200); // If we stringify an object containing the long string, it gets abbreviated. let actual = stringify({ veryLongString }); @@ -55,15 +55,16 @@ test(function consoleTestStringifyLongStrings() { assertEquals(actual, veryLongString); }); -test(function consoleTestStringifyCircular() { +/* eslint-disable @typescript-eslint/explicit-function-return-type */ +test(function consoleTestStringifyCircular(): void { class Base { a = 1; - m1(): void {} + m1() {} } class Extended extends Base { b = 2; - m2(): void {} + m2() {} } // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -121,8 +122,11 @@ test(function consoleTestStringifyCircular() { assertEquals(stringify(null), "null"); assertEquals(stringify(undefined), "undefined"); assertEquals(stringify(new Extended()), "Extended { a: 1, b: 2 }"); - assertEquals(stringify(function f() {}), "[Function: f]"); - assertEquals(stringify(async function af() {}), "[AsyncFunction: af]"); + assertEquals(stringify(function f(): void {}), "[Function: f]"); + assertEquals( + stringify(async function af(): Promise<void> {}), + "[AsyncFunction: af]" + ); assertEquals(stringify(function* gf() {}), "[GeneratorFunction: gf]"); assertEquals( stringify(async function* agf() {}), @@ -143,8 +147,9 @@ test(function consoleTestStringifyCircular() { // test inspect is working the same assertEquals(inspect(nestedObj), nestedObjExpected); }); +/* eslint-enable @typescript-eslint/explicit-function-return-type */ -test(function consoleTestStringifyWithDepth() { +test(function consoleTestStringifyWithDepth(): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any const nestedObj: any = { a: { b: { c: { d: { e: { f: 42 } } } } } }; assertEquals( @@ -167,7 +172,7 @@ test(function consoleTestStringifyWithDepth() { ); }); -test(function consoleTestWithIntegerFormatSpecifier() { +test(function consoleTestWithIntegerFormatSpecifier(): void { assertEquals(stringify("%i"), "%i"); assertEquals(stringify("%i", 42.0), "42"); assertEquals(stringify("%i", 42), "42"); @@ -186,7 +191,7 @@ test(function consoleTestWithIntegerFormatSpecifier() { ); }); -test(function consoleTestWithFloatFormatSpecifier() { +test(function consoleTestWithFloatFormatSpecifier(): void { assertEquals(stringify("%f"), "%f"); assertEquals(stringify("%f", 42.0), "42"); assertEquals(stringify("%f", 42), "42"); @@ -202,7 +207,7 @@ test(function consoleTestWithFloatFormatSpecifier() { assertEquals(stringify("%f %f", 42), "42 %f"); }); -test(function consoleTestWithStringFormatSpecifier() { +test(function consoleTestWithStringFormatSpecifier(): void { assertEquals(stringify("%s"), "%s"); assertEquals(stringify("%s", undefined), "undefined"); assertEquals(stringify("%s", "foo"), "foo"); @@ -213,7 +218,7 @@ test(function consoleTestWithStringFormatSpecifier() { assertEquals(stringify("%s", Symbol("foo")), "Symbol(foo)"); }); -test(function consoleTestWithObjectFormatSpecifier() { +test(function consoleTestWithObjectFormatSpecifier(): void { assertEquals(stringify("%o"), "%o"); assertEquals(stringify("%o", 42), "42"); assertEquals(stringify("%o", "foo"), "foo"); @@ -225,7 +230,7 @@ test(function consoleTestWithObjectFormatSpecifier() { ); }); -test(function consoleTestWithVariousOrInvalidFormatSpecifier() { +test(function consoleTestWithVariousOrInvalidFormatSpecifier(): void { assertEquals(stringify("%s:%s"), "%s:%s"); assertEquals(stringify("%i:%i"), "%i:%i"); assertEquals(stringify("%d:%d"), "%d:%d"); @@ -241,14 +246,14 @@ test(function consoleTestWithVariousOrInvalidFormatSpecifier() { assertEquals(stringify("abc%", 1), "abc% 1"); }); -test(function consoleTestCallToStringOnLabel() { +test(function consoleTestCallToStringOnLabel(): void { const methods = ["count", "countReset", "time", "timeLog", "timeEnd"]; for (const method of methods) { let hasCalled = false; console[method]({ - toString() { + toString(): void { hasCalled = true; } }); @@ -257,7 +262,7 @@ test(function consoleTestCallToStringOnLabel() { } }); -test(function consoleTestError() { +test(function consoleTestError(): void { class MyError extends Error { constructor(errStr: string) { super(errStr); @@ -275,12 +280,12 @@ test(function consoleTestError() { } }); -test(function consoleTestClear() { +test(function consoleTestClear(): void { const stdoutWrite = stdout.write; const uint8 = new TextEncoder().encode("\x1b[1;1H" + "\x1b[0J"); let buffer = new Uint8Array(0); - stdout.write = async u8 => { + stdout.write = async (u8: Uint8Array): Promise<number> => { const tmp = new Uint8Array(buffer.length + u8.length); tmp.set(buffer, 0); tmp.set(u8, buffer.length); @@ -294,7 +299,7 @@ test(function consoleTestClear() { }); // Test bound this issue -test(function consoleDetachedLog() { +test(function consoleDetachedLog(): void { const log = console.log; const dir = console.dir; const debug = console.debug; @@ -352,7 +357,7 @@ function mockConsole(f: ConsoleExamineFunc): void { const err = new StringBuffer(); const both = new StringBuffer(); const csl = new Console( - (x: string, isErr: boolean, printsNewLine: boolean) => { + (x: string, isErr: boolean, printsNewLine: boolean): void => { const content = x + (printsNewLine ? "\n" : ""); const buf = isErr ? err : out; buf.add(content); @@ -363,27 +368,28 @@ function mockConsole(f: ConsoleExamineFunc): void { } // console.group test -test(function consoleGroup() { - mockConsole((console, out) => { - console.group("1"); - console.log("2"); - console.group("3"); - console.log("4"); - console.groupEnd(); - console.groupEnd(); - - console.groupCollapsed("5"); - console.log("6"); - console.group("7"); - console.log("8"); - console.groupEnd(); - console.groupEnd(); - console.log("9"); - console.log("10"); - - assertEquals( - out.toString(), - `1 +test(function consoleGroup(): void { + mockConsole( + (console, out): void => { + console.group("1"); + console.log("2"); + console.group("3"); + console.log("4"); + console.groupEnd(); + console.groupEnd(); + + console.groupCollapsed("5"); + console.log("6"); + console.group("7"); + console.log("8"); + console.groupEnd(); + console.groupEnd(); + console.log("9"); + console.log("10"); + + assertEquals( + out.toString(), + `1 2 3 4 @@ -391,36 +397,38 @@ test(function consoleGroup() { 9 10 ` - ); - }); + ); + } + ); }); // console.group with console.warn test -test(function consoleGroupWarn() { - mockConsole((console, _out, _err, both) => { - console.warn("1"); - console.group(); - console.warn("2"); - console.group(); - console.warn("3"); - console.groupEnd(); - console.warn("4"); - console.groupEnd(); - console.warn("5"); - - console.groupCollapsed(); - console.warn("6"); - console.group(); - console.warn("7"); - console.groupEnd(); - console.warn("8"); - console.groupEnd(); - - console.warn("9"); - console.warn("10"); - assertEquals( - both.toString(), - `1 +test(function consoleGroupWarn(): void { + mockConsole( + (console, _out, _err, both): void => { + console.warn("1"); + console.group(); + console.warn("2"); + console.group(); + console.warn("3"); + console.groupEnd(); + console.warn("4"); + console.groupEnd(); + console.warn("5"); + + console.groupCollapsed(); + console.warn("6"); + console.group(); + console.warn("7"); + console.groupEnd(); + console.warn("8"); + console.groupEnd(); + + console.warn("9"); + console.warn("10"); + assertEquals( + both.toString(), + `1 2 3 4 @@ -429,43 +437,49 @@ test(function consoleGroupWarn() { 9 10 ` - ); - }); + ); + } + ); }); // console.table test -test(function consoleTable() { - mockConsole((console, out) => { - console.table({ a: "test", b: 1 }); - assertEquals( - out.toString(), - `┌─────────┬────────┐ +test(function consoleTable(): void { + mockConsole( + (console, out): void => { + console.table({ a: "test", b: 1 }); + assertEquals( + out.toString(), + `┌─────────┬────────┐ │ (index) │ Values │ ├─────────┼────────┤ │ a │ "test" │ │ b │ 1 │ └─────────┴────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table({ a: { b: 10 }, b: { b: 20, c: 30 } }, ["c"]); - assertEquals( - out.toString(), - `┌─────────┬────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table({ a: { b: 10 }, b: { b: 20, c: 30 } }, ["c"]); + assertEquals( + out.toString(), + `┌─────────┬────┐ │ (index) │ c │ ├─────────┼────┤ │ a │ │ │ b │ 30 │ └─────────┴────┘ ` - ); - }); - mockConsole((console, out) => { - console.table([1, 2, [3, [4]], [5, 6], [[7], [8]]]); - assertEquals( - out.toString(), - `┌─────────┬───────┬───────┬────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table([1, 2, [3, [4]], [5, 6], [[7], [8]]]); + assertEquals( + out.toString(), + `┌─────────┬───────┬───────┬────────┐ │ (index) │ 0 │ 1 │ Values │ ├─────────┼───────┼───────┼────────┤ │ 0 │ │ │ 1 │ @@ -475,13 +489,15 @@ test(function consoleTable() { │ 4 │ [ 7 ] │ [ 8 ] │ │ └─────────┴───────┴───────┴────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table(new Set([1, 2, 3, "test"])); - assertEquals( - out.toString(), - `┌───────────────────┬────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table(new Set([1, 2, 3, "test"])); + assertEquals( + out.toString(), + `┌───────────────────┬────────┐ │ (iteration index) │ Values │ ├───────────────────┼────────┤ │ 0 │ 1 │ @@ -490,32 +506,36 @@ test(function consoleTable() { │ 3 │ "test" │ └───────────────────┴────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table(new Map([[1, "one"], [2, "two"]])); - assertEquals( - out.toString(), - `┌───────────────────┬─────┬────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table(new Map([[1, "one"], [2, "two"]])); + assertEquals( + out.toString(), + `┌───────────────────┬─────┬────────┐ │ (iteration index) │ Key │ Values │ ├───────────────────┼─────┼────────┤ │ 0 │ 1 │ "one" │ │ 1 │ 2 │ "two" │ └───────────────────┴─────┴────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table({ - a: true, - b: { c: { d: 10 }, e: [1, 2, [5, 6]] }, - f: "test", - g: new Set([1, 2, 3, "test"]), - h: new Map([[1, "one"]]) - }); - assertEquals( - out.toString(), - `┌─────────┬───────────┬───────────────────┬────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table({ + a: true, + b: { c: { d: 10 }, e: [1, 2, [5, 6]] }, + f: "test", + g: new Set([1, 2, 3, "test"]), + h: new Map([[1, "one"]]) + }); + assertEquals( + out.toString(), + `┌─────────┬───────────┬───────────────────┬────────┐ │ (index) │ c │ e │ Values │ ├─────────┼───────────┼───────────────────┼────────┤ │ a │ │ │ true │ @@ -525,19 +545,21 @@ test(function consoleTable() { │ h │ │ │ │ └─────────┴───────────┴───────────────────┴────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table([ - 1, - "test", - false, - { a: 10 }, - ["test", { b: 20, c: "test" }] - ]); - assertEquals( - out.toString(), - `┌─────────┬────────┬──────────────────────┬────┬────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table([ + 1, + "test", + false, + { a: 10 }, + ["test", { b: 20, c: "test" }] + ]); + assertEquals( + out.toString(), + `┌─────────┬────────┬──────────────────────┬────┬────────┐ │ (index) │ 0 │ 1 │ a │ Values │ ├─────────┼────────┼──────────────────────┼────┼────────┤ │ 0 │ │ │ │ 1 │ @@ -547,60 +569,71 @@ test(function consoleTable() { │ 4 │ "test" │ { b: 20, c: "test" } │ │ │ └─────────┴────────┴──────────────────────┴────┴────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table([]); - assertEquals( - out.toString(), - `┌─────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table([]); + assertEquals( + out.toString(), + `┌─────────┐ │ (index) │ ├─────────┤ └─────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table({}); - assertEquals( - out.toString(), - `┌─────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table({}); + assertEquals( + out.toString(), + `┌─────────┐ │ (index) │ ├─────────┤ └─────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table(new Set()); - assertEquals( - out.toString(), - `┌───────────────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table(new Set()); + assertEquals( + out.toString(), + `┌───────────────────┐ │ (iteration index) │ ├───────────────────┤ └───────────────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table(new Map()); - assertEquals( - out.toString(), - `┌───────────────────┐ + ); + } + ); + mockConsole( + (console, out): void => { + console.table(new Map()); + assertEquals( + out.toString(), + `┌───────────────────┐ │ (iteration index) │ ├───────────────────┤ └───────────────────┘ ` - ); - }); - mockConsole((console, out) => { - console.table("test"); - assertEquals(out.toString(), "test\n"); - }); + ); + } + ); + mockConsole( + (console, out): void => { + console.table("test"); + assertEquals(out.toString(), "test\n"); + } + ); }); // console.log(Error) test -test(function consoleLogShouldNotThrowError() { +test(function consoleLogShouldNotThrowError(): void { let result = 0; try { console.log(new Error("foo")); @@ -611,8 +644,10 @@ test(function consoleLogShouldNotThrowError() { assertEquals(result, 1); // output errors to the console should not include "Uncaught" - mockConsole((console, out) => { - console.log(new Error("foo")); - assertEquals(out.toString().includes("Uncaught"), false); - }); + mockConsole( + (console, out): void => { + console.log(new Error("foo")); + assertEquals(out.toString().includes("Uncaught"), false); + } + ); }); diff --git a/js/copy_file_test.ts b/js/copy_file_test.ts index 5348094c4..72ae43f3e 100644 --- a/js/copy_file_test.ts +++ b/js/copy_file_test.ts @@ -19,7 +19,7 @@ function assertSameContent(filename1: string, filename2: string): void { assertEquals(data1, data2); } -testPerm({ read: true, write: true }, function copyFileSyncSuccess() { +testPerm({ read: true, write: true }, function copyFileSyncSuccess(): void { const tempDir = Deno.makeTempDirSync(); const fromFilename = tempDir + "/from.txt"; const toFilename = tempDir + "/to.txt"; @@ -31,7 +31,7 @@ testPerm({ read: true, write: true }, function copyFileSyncSuccess() { assertSameContent(fromFilename, toFilename); }); -testPerm({ write: true, read: true }, function copyFileSyncFailure() { +testPerm({ write: true, read: true }, function copyFileSyncFailure(): void { const tempDir = Deno.makeTempDirSync(); const fromFilename = tempDir + "/from.txt"; const toFilename = tempDir + "/to.txt"; @@ -47,7 +47,7 @@ testPerm({ write: true, read: true }, function copyFileSyncFailure() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true, read: false }, function copyFileSyncPerm1() { +testPerm({ write: true, read: false }, function copyFileSyncPerm1(): void { let caughtError = false; try { Deno.copyFileSync("/from.txt", "/to.txt"); @@ -59,7 +59,7 @@ testPerm({ write: true, read: false }, function copyFileSyncPerm1() { assert(caughtError); }); -testPerm({ write: false, read: true }, function copyFileSyncPerm2() { +testPerm({ write: false, read: true }, function copyFileSyncPerm2(): void { let caughtError = false; try { Deno.copyFileSync("/from.txt", "/to.txt"); @@ -71,7 +71,7 @@ testPerm({ write: false, read: true }, function copyFileSyncPerm2() { assert(caughtError); }); -testPerm({ read: true, write: true }, function copyFileSyncOverwrite() { +testPerm({ read: true, write: true }, function copyFileSyncOverwrite(): void { const tempDir = Deno.makeTempDirSync(); const fromFilename = tempDir + "/from.txt"; const toFilename = tempDir + "/to.txt"; @@ -85,7 +85,9 @@ testPerm({ read: true, write: true }, function copyFileSyncOverwrite() { assertSameContent(fromFilename, toFilename); }); -testPerm({ read: true, write: true }, async function copyFileSuccess() { +testPerm({ read: true, write: true }, async function copyFileSuccess(): Promise< + void +> { const tempDir = Deno.makeTempDirSync(); const fromFilename = tempDir + "/from.txt"; const toFilename = tempDir + "/to.txt"; @@ -97,7 +99,9 @@ testPerm({ read: true, write: true }, async function copyFileSuccess() { assertSameContent(fromFilename, toFilename); }); -testPerm({ read: true, write: true }, async function copyFileFailure() { +testPerm({ read: true, write: true }, async function copyFileFailure(): Promise< + void +> { const tempDir = Deno.makeTempDirSync(); const fromFilename = tempDir + "/from.txt"; const toFilename = tempDir + "/to.txt"; @@ -113,21 +117,26 @@ testPerm({ read: true, write: true }, async function copyFileFailure() { assertEquals(err.name, "NotFound"); }); -testPerm({ read: true, write: true }, async function copyFileOverwrite() { - const tempDir = Deno.makeTempDirSync(); - const fromFilename = tempDir + "/from.txt"; - const toFilename = tempDir + "/to.txt"; - writeFileString(fromFilename, "Hello world!"); - // Make Dest exist and have different content - writeFileString(toFilename, "Goodbye!"); - await Deno.copyFile(fromFilename, toFilename); - // No change to original file - assertEquals(readFileString(fromFilename), "Hello world!"); - // Original == Dest - assertSameContent(fromFilename, toFilename); -}); +testPerm( + { read: true, write: true }, + async function copyFileOverwrite(): Promise<void> { + const tempDir = Deno.makeTempDirSync(); + const fromFilename = tempDir + "/from.txt"; + const toFilename = tempDir + "/to.txt"; + writeFileString(fromFilename, "Hello world!"); + // Make Dest exist and have different content + writeFileString(toFilename, "Goodbye!"); + await Deno.copyFile(fromFilename, toFilename); + // No change to original file + assertEquals(readFileString(fromFilename), "Hello world!"); + // Original == Dest + assertSameContent(fromFilename, toFilename); + } +); -testPerm({ read: false, write: true }, async function copyFilePerm1() { +testPerm({ read: false, write: true }, async function copyFilePerm1(): Promise< + void +> { let caughtError = false; try { await Deno.copyFile("/from.txt", "/to.txt"); @@ -139,7 +148,9 @@ testPerm({ read: false, write: true }, async function copyFilePerm1() { assert(caughtError); }); -testPerm({ read: true, write: false }, async function copyFilePerm2() { +testPerm({ read: true, write: false }, async function copyFilePerm2(): Promise< + void +> { let caughtError = false; try { await Deno.copyFile("/from.txt", "/to.txt"); diff --git a/js/custom_event_test.ts b/js/custom_event_test.ts index 2f8f5c1a0..8a9dc9416 100644 --- a/js/custom_event_test.ts +++ b/js/custom_event_test.ts @@ -1,7 +1,7 @@ // Copyright 2018 the Deno authors. All rights reserved. MIT license. import { test, assertEquals } from "./test_util.ts"; -test(function customEventInitializedWithDetail() { +test(function customEventInitializedWithDetail(): void { const type = "touchstart"; const detail = { message: "hello" }; const customEventDict = new CustomEventInit({ @@ -20,7 +20,7 @@ test(function customEventInitializedWithDetail() { assertEquals(event.type, type); }); -test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility(): void { const type = "touchstart"; const event = new CustomEvent(type, {}); assertEquals(event.toString(), "[object CustomEvent]"); diff --git a/js/dir_test.ts b/js/dir_test.ts index bb6b053fd..6c4e36d7a 100644 --- a/js/dir_test.ts +++ b/js/dir_test.ts @@ -1,11 +1,11 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -test(function dirCwdNotNull() { +test(function dirCwdNotNull(): void { assert(Deno.cwd() != null); }); -testPerm({ write: true }, function dirCwdChdirSuccess() { +testPerm({ write: true }, function dirCwdChdirSuccess(): void { const initialdir = Deno.cwd(); const path = Deno.makeTempDirSync(); Deno.chdir(path); @@ -18,7 +18,7 @@ testPerm({ write: true }, function dirCwdChdirSuccess() { Deno.chdir(initialdir); }); -testPerm({ write: true }, function dirCwdError() { +testPerm({ write: true }, function dirCwdError(): void { // excluding windows since it throws resource busy, while removeSync if (["linux", "mac"].includes(Deno.build.os)) { const initialdir = Deno.cwd(); @@ -39,7 +39,7 @@ testPerm({ write: true }, function dirCwdError() { } }); -testPerm({ write: true }, function dirChdirError() { +testPerm({ write: true }, function dirChdirError(): void { const path = Deno.makeTempDirSync() + "test"; try { Deno.chdir(path); diff --git a/js/event_target.ts b/js/event_target.ts index 87268383e..ba086d544 100644 --- a/js/event_target.ts +++ b/js/event_target.ts @@ -32,7 +32,7 @@ export class EventTarget implements domTypes.EventTarget { requiredArguments("EventTarget.removeEventListener", arguments.length, 2); if (hasOwnProperty(this.listeners, type) && callback !== null) { this.listeners[type] = this.listeners[type].filter( - listener => listener !== callback + (listener): boolean => listener !== callback ); } } diff --git a/js/event_target_test.ts b/js/event_target_test.ts index aedbbf72a..6710b6e68 100644 --- a/js/event_target_test.ts +++ b/js/event_target_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assertEquals } from "./test_util.ts"; -test(function addEventListenerTest() { +test(function addEventListenerTest(): void { const document = new EventTarget(); assertEquals(document.addEventListener("x", null, false), undefined); @@ -9,7 +9,7 @@ test(function addEventListenerTest() { assertEquals(document.addEventListener("x", null), undefined); }); -test(function constructedEventTargetCanBeUsedAsExpected() { +test(function constructedEventTargetCanBeUsedAsExpected(): void { const target = new EventTarget(); const event = new Event("foo", { bubbles: true, cancelable: false }); let callCount = 0; @@ -32,7 +32,7 @@ test(function constructedEventTargetCanBeUsedAsExpected() { assertEquals(callCount, 2); }); -test(function anEventTargetCanBeSubclassed() { +test(function anEventTargetCanBeSubclassed(): void { class NicerEventTarget extends EventTarget { on(type, callback?, options?): void { this.addEventListener(type, callback, options); @@ -58,14 +58,14 @@ test(function anEventTargetCanBeSubclassed() { assertEquals(callCount, 0); }); -test(function removingNullEventListenerShouldSucceed() { +test(function removingNullEventListenerShouldSucceed(): void { const document = new EventTarget(); assertEquals(document.removeEventListener("x", null, false), undefined); assertEquals(document.removeEventListener("x", null, true), undefined); assertEquals(document.removeEventListener("x", null), undefined); }); -test(function constructedEventTargetUseObjectPrototype() { +test(function constructedEventTargetUseObjectPrototype(): void { const target = new EventTarget(); const event = new Event("toString", { bubbles: true, cancelable: false }); let callCount = 0; @@ -88,12 +88,12 @@ test(function constructedEventTargetUseObjectPrototype() { assertEquals(callCount, 2); }); -test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility(): void { const target = new EventTarget(); assertEquals(target.toString(), "[object EventTarget]"); }); -test(function dispatchEventShouldNotThrowError() { +test(function dispatchEventShouldNotThrowError(): void { let hasThrown = false; try { @@ -102,7 +102,7 @@ test(function dispatchEventShouldNotThrowError() { bubbles: true, cancelable: false }); - target.addEventListener("hasOwnProperty", () => {}); + target.addEventListener("hasOwnProperty", (): void => {}); target.dispatchEvent(event); } catch { hasThrown = true; diff --git a/js/event_test.ts b/js/event_test.ts index eb5521406..75ff8bed1 100644 --- a/js/event_test.ts +++ b/js/event_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assertEquals } from "./test_util.ts"; -test(function eventInitializedWithType() { +test(function eventInitializedWithType(): void { const type = "click"; const event = new Event(type); @@ -13,7 +13,7 @@ test(function eventInitializedWithType() { assertEquals(event.cancelable, false); }); -test(function eventInitializedWithTypeAndDict() { +test(function eventInitializedWithTypeAndDict(): void { const init = "submit"; const eventInitDict = new EventInit({ bubbles: true, cancelable: true }); const event = new Event(init, eventInitDict); @@ -26,7 +26,7 @@ test(function eventInitializedWithTypeAndDict() { assertEquals(event.cancelable, true); }); -test(function eventComposedPathSuccess() { +test(function eventComposedPathSuccess(): void { const type = "click"; const event = new Event(type); const composedPath = event.composedPath(); @@ -34,7 +34,7 @@ test(function eventComposedPathSuccess() { assertEquals(composedPath, []); }); -test(function eventStopPropagationSuccess() { +test(function eventStopPropagationSuccess(): void { const type = "click"; const event = new Event(type); @@ -43,7 +43,7 @@ test(function eventStopPropagationSuccess() { assertEquals(event.cancelBubble, true); }); -test(function eventStopImmediatePropagationSuccess() { +test(function eventStopImmediatePropagationSuccess(): void { const type = "click"; const event = new Event(type); @@ -54,7 +54,7 @@ test(function eventStopImmediatePropagationSuccess() { assertEquals(event.cancelBubbleImmediately, true); }); -test(function eventPreventDefaultSuccess() { +test(function eventPreventDefaultSuccess(): void { const type = "click"; const event = new Event(type); @@ -69,7 +69,7 @@ test(function eventPreventDefaultSuccess() { assertEquals(cancelableEvent.defaultPrevented, true); }); -test(function eventInitializedWithNonStringType() { +test(function eventInitializedWithNonStringType(): void { const type = undefined; const event = new Event(type); diff --git a/js/fetch.ts b/js/fetch.ts index 7cc0750ed..3489c54a0 100644 --- a/js/fetch.ts +++ b/js/fetch.ts @@ -19,10 +19,10 @@ function getHeaderValueParams(value: string): Map<string, string> { value .split(";") .slice(1) - .map(s => s.trim().split("=")) - .filter(arr => arr.length > 1) - .map(([k, v]) => [k, v.replace(/^"([^"]*)"$/, "$1")]) - .forEach(([k, v]) => params.set(k, v)); + .map((s): string[] => s.trim().split("=")) + .filter((arr): boolean => arr.length > 1) + .map(([k, v]): [string, string] => [k, v.replace(/^"([^"]*)"$/, "$1")]) + .forEach(([k, v]): Map<string, string> => params.set(k, v)); return params; } @@ -116,7 +116,7 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser { // (as long as it is not part of `delimiter`) bodyParts = bodyPreambleTrimmed .split(delimiter) - .map(s => s.replace(/^[\s\r\n\t]+/, "")); + .map((s): string => s.replace(/^[\s\r\n\t]+/, "")); // TODO: LWSP definition is actually trickier, // but should be fine in our case since without headers // we should just discard the part @@ -184,17 +184,19 @@ class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser { body .trim() .split("&") - .forEach(bytes => { - if (bytes) { - const split = bytes.split("="); - const name = split.shift()!.replace(/\+/g, " "); - const value = split.join("=").replace(/\+/g, " "); - formData.append( - decodeURIComponent(name), - decodeURIComponent(value) - ); + .forEach( + (bytes): void => { + if (bytes) { + const split = bytes.split("="); + const name = split.shift()!.replace(/\+/g, " "); + const value = split.join("=").replace(/\+/g, " "); + formData.append( + decodeURIComponent(name), + decodeURIComponent(value) + ); + } } - }); + ); } catch (e) { throw new TypeError("Invalid form urlencoded format"); } diff --git a/js/fetch_test.ts b/js/fetch_test.ts index 4197e9c71..cebef58e2 100644 --- a/js/fetch_test.ts +++ b/js/fetch_test.ts @@ -1,13 +1,13 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ net: true }, async function fetchJsonSuccess() { +testPerm({ net: true }, async function fetchJsonSuccess(): Promise<void> { const response = await fetch("http://localhost:4545/package.json"); const json = await response.json(); assertEquals(json.name, "deno"); }); -test(async function fetchPerm() { +test(async function fetchPerm(): Promise<void> { let err; try { await fetch("http://localhost:4545/package.json"); @@ -18,14 +18,14 @@ test(async function fetchPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ net: true }, async function fetchHeaders() { +testPerm({ net: true }, async function fetchHeaders(): Promise<void> { const response = await fetch("http://localhost:4545/package.json"); const headers = response.headers; assertEquals(headers.get("Content-Type"), "application/json"); assert(headers.get("Server").startsWith("SimpleHTTP")); }); -testPerm({ net: true }, async function fetchBlob() { +testPerm({ net: true }, async function fetchBlob(): Promise<void> { const response = await fetch("http://localhost:4545/package.json"); const headers = response.headers; const blob = await response.blob(); @@ -33,7 +33,7 @@ testPerm({ net: true }, async function fetchBlob() { assertEquals(blob.size, Number(headers.get("Content-Length"))); }); -testPerm({ net: true }, async function responseClone() { +testPerm({ net: true }, async function responseClone(): Promise<void> { const response = await fetch("http://localhost:4545/package.json"); const response1 = response.clone(); assert(response !== response1); @@ -46,7 +46,7 @@ testPerm({ net: true }, async function responseClone() { } }); -testPerm({ net: true }, async function fetchEmptyInvalid() { +testPerm({ net: true }, async function fetchEmptyInvalid(): Promise<void> { let err; try { await fetch(""); @@ -57,7 +57,9 @@ testPerm({ net: true }, async function fetchEmptyInvalid() { assertEquals(err.name, "InvalidUri"); }); -testPerm({ net: true }, async function fetchMultipartFormDataSuccess() { +testPerm({ net: true }, async function fetchMultipartFormDataSuccess(): Promise< + void +> { const response = await fetch( "http://localhost:4545/tests/subdir/multipart_form_data.txt" ); @@ -72,18 +74,21 @@ testPerm({ net: true }, async function fetchMultipartFormDataSuccess() { // Currently we cannot read from file... }); -testPerm({ net: true }, async function fetchURLEncodedFormDataSuccess() { - const response = await fetch( - "http://localhost:4545/tests/subdir/form_urlencoded.txt" - ); - const formData = await response.formData(); - assert(formData.has("field_1")); - assertEquals(formData.get("field_1").toString(), "Hi"); - assert(formData.has("field_2")); - assertEquals(formData.get("field_2").toString(), "<Deno>"); -}); +testPerm( + { net: true }, + async function fetchURLEncodedFormDataSuccess(): Promise<void> { + const response = await fetch( + "http://localhost:4545/tests/subdir/form_urlencoded.txt" + ); + const formData = await response.formData(); + assert(formData.has("field_1")); + assertEquals(formData.get("field_1").toString(), "Hi"); + assert(formData.has("field_2")); + assertEquals(formData.get("field_2").toString(), "<Deno>"); + } +); -testPerm({ net: true }, async function fetchInitStringBody() { +testPerm({ net: true }, async function fetchInitStringBody(): Promise<void> { const data = "Hello World"; const response = await fetch("http://localhost:4545/echo_server", { method: "POST", @@ -94,7 +99,9 @@ testPerm({ net: true }, async function fetchInitStringBody() { assert(response.headers.get("content-type").startsWith("text/plain")); }); -testPerm({ net: true }, async function fetchInitTypedArrayBody() { +testPerm({ net: true }, async function fetchInitTypedArrayBody(): Promise< + void +> { const data = "Hello World"; const response = await fetch("http://localhost:4545/echo_server", { method: "POST", @@ -104,7 +111,9 @@ testPerm({ net: true }, async function fetchInitTypedArrayBody() { assertEquals(text, data); }); -testPerm({ net: true }, async function fetchInitURLSearchParamsBody() { +testPerm({ net: true }, async function fetchInitURLSearchParamsBody(): Promise< + void +> { const data = "param1=value1¶m2=value2"; const params = new URLSearchParams(data); const response = await fetch("http://localhost:4545/echo_server", { @@ -120,7 +129,7 @@ testPerm({ net: true }, async function fetchInitURLSearchParamsBody() { ); }); -testPerm({ net: true }, async function fetchInitBlobBody() { +testPerm({ net: true }, async function fetchInitBlobBody(): Promise<void> { const data = "const a = 1"; const blob = new Blob([data], { type: "text/javascript" @@ -153,7 +162,7 @@ testPerm({ net: true }, async function fetchInitBlobBody() { // at Object.assertEquals (file:///C:/deno/js/testing/util.ts:29:11) // at fetchPostBodyString (file -/* +/* function bufferServer(addr: string): Deno.Buffer { const listener = Deno.listen("tcp", addr); const buf = new Deno.Buffer(); @@ -177,7 +186,7 @@ function bufferServer(addr: string): Deno.Buffer { return buf; } -testPerm({ net: true }, async function fetchRequest() { +testPerm({ net: true }, async function fetchRequest():Promise<void> { const addr = "127.0.0.1:4501"; const buf = bufferServer(addr); const response = await fetch(`http://${addr}/blah`, { @@ -197,7 +206,7 @@ testPerm({ net: true }, async function fetchRequest() { assertEquals(actual, expected); }); -testPerm({ net: true }, async function fetchPostBodyString() { +testPerm({ net: true }, async function fetchPostBodyString():Promise<void> { const addr = "127.0.0.1:4502"; const buf = bufferServer(addr); const body = "hello world"; @@ -221,7 +230,7 @@ testPerm({ net: true }, async function fetchPostBodyString() { assertEquals(actual, expected); }); -testPerm({ net: true }, async function fetchPostBodyTypedArray() { +testPerm({ net: true }, async function fetchPostBodyTypedArray():Promise<void> { const addr = "127.0.0.1:4503"; const buf = bufferServer(addr); const bodyStr = "hello world"; diff --git a/js/file_test.ts b/js/file_test.ts index 65ddfde92..345dcd8fe 100644 --- a/js/file_test.ts +++ b/js/file_test.ts @@ -9,47 +9,47 @@ function testFirstArgument(arg1, expectedSize): void { assertEquals(file.type, ""); } -test(function fileEmptyFileBits() { +test(function fileEmptyFileBits(): void { testFirstArgument([], 0); }); -test(function fileStringFileBits() { +test(function fileStringFileBits(): void { testFirstArgument(["bits"], 4); }); -test(function fileUnicodeStringFileBits() { +test(function fileUnicodeStringFileBits(): void { testFirstArgument(["𝓽𝓮𝔁𝓽"], 16); }); -test(function fileStringObjectFileBits() { +test(function fileStringObjectFileBits(): void { testFirstArgument([new String("string object")], 13); }); -test(function fileEmptyBlobFileBits() { +test(function fileEmptyBlobFileBits(): void { testFirstArgument([new Blob()], 0); }); -test(function fileBlobFileBits() { +test(function fileBlobFileBits(): void { testFirstArgument([new Blob(["bits"])], 4); }); -test(function fileEmptyFileFileBits() { +test(function fileEmptyFileFileBits(): void { testFirstArgument([new File([], "world.txt")], 0); }); -test(function fileFileFileBits() { +test(function fileFileFileBits(): void { testFirstArgument([new File(["bits"], "world.txt")], 4); }); -test(function fileArrayBufferFileBits() { +test(function fileArrayBufferFileBits(): void { testFirstArgument([new ArrayBuffer(8)], 8); }); -test(function fileTypedArrayFileBits() { +test(function fileTypedArrayFileBits(): void { testFirstArgument([new Uint8Array([0x50, 0x41, 0x53, 0x53])], 4); }); -test(function fileVariousFileBits() { +test(function fileVariousFileBits(): void { testFirstArgument( [ "bits", @@ -63,15 +63,15 @@ test(function fileVariousFileBits() { ); }); -test(function fileNumberInFileBits() { +test(function fileNumberInFileBits(): void { testFirstArgument([12], 2); }); -test(function fileArrayInFileBits() { +test(function fileArrayInFileBits(): void { testFirstArgument([[1, 2, 3]], 5); }); -test(function fileObjectInFileBits() { +test(function fileObjectInFileBits(): void { // "[object Object]" testFirstArgument([{}], 15); }); @@ -82,22 +82,22 @@ function testSecondArgument(arg2, expectedFileName): void { assertEquals(file.name, expectedFileName); } -test(function fileUsingFileName() { +test(function fileUsingFileName(): void { testSecondArgument("dummy", "dummy"); }); -test(function fileUsingSpecialCharacterInFileName() { +test(function fileUsingSpecialCharacterInFileName(): void { testSecondArgument("dummy/foo", "dummy:foo"); }); -test(function fileUsingNullFileName() { +test(function fileUsingNullFileName(): void { testSecondArgument(null, "null"); }); -test(function fileUsingNumberFileName() { +test(function fileUsingNumberFileName(): void { testSecondArgument(1, "1"); }); -test(function fileUsingEmptyStringFileName() { +test(function fileUsingEmptyStringFileName(): void { testSecondArgument("", ""); }); diff --git a/js/files_test.ts b/js/files_test.ts index f953946bc..2b91b9cab 100644 --- a/js/files_test.ts +++ b/js/files_test.ts @@ -1,13 +1,13 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -test(function filesStdioFileDescriptors() { +test(function filesStdioFileDescriptors(): void { assertEquals(Deno.stdin.rid, 0); assertEquals(Deno.stdout.rid, 1); assertEquals(Deno.stderr.rid, 2); }); -testPerm({ read: true }, async function filesCopyToStdout() { +testPerm({ read: true }, async function filesCopyToStdout(): Promise<void> { const filename = "package.json"; const file = await Deno.open(filename); assert(file.rid > 2); @@ -17,7 +17,7 @@ testPerm({ read: true }, async function filesCopyToStdout() { console.log("bytes written", bytesWritten); }); -testPerm({ read: true }, async function filesToAsyncIterator() { +testPerm({ read: true }, async function filesToAsyncIterator(): Promise<void> { const filename = "tests/hello.txt"; const file = await Deno.open(filename); @@ -29,7 +29,7 @@ testPerm({ read: true }, async function filesToAsyncIterator() { assertEquals(totalSize, 12); }); -testPerm({ write: false }, async function writePermFailure() { +testPerm({ write: false }, async function writePermFailure(): Promise<void> { const filename = "tests/hello.txt"; const writeModes: Deno.OpenMode[] = ["w", "a", "x"]; for (const mode of writeModes) { @@ -45,7 +45,7 @@ testPerm({ write: false }, async function writePermFailure() { } }); -testPerm({ read: false }, async function readPermFailure() { +testPerm({ read: false }, async function readPermFailure(): Promise<void> { let caughtError = false; try { await Deno.open("package.json", "r"); @@ -57,23 +57,28 @@ testPerm({ read: false }, async function readPermFailure() { assert(caughtError); }); -testPerm({ write: false, read: false }, async function readWritePermFailure() { - const filename = "tests/hello.txt"; - const writeModes: Deno.OpenMode[] = ["r+", "w+", "a+", "x+"]; - for (const mode of writeModes) { - let err; - try { - await Deno.open(filename, mode); - } catch (e) { - err = e; +testPerm( + { write: false, read: false }, + async function readWritePermFailure(): Promise<void> { + const filename = "tests/hello.txt"; + const writeModes: Deno.OpenMode[] = ["r+", "w+", "a+", "x+"]; + for (const mode of writeModes) { + let err; + try { + await Deno.open(filename, mode); + } catch (e) { + err = e; + } + assert(!!err); + assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); + assertEquals(err.name, "PermissionDenied"); } - assert(!!err); - assertEquals(err.kind, Deno.ErrorKind.PermissionDenied); - assertEquals(err.name, "PermissionDenied"); } -}); +); -testPerm({ read: true, write: true }, async function createFile() { +testPerm({ read: true, write: true }, async function createFile(): Promise< + void +> { const tempDir = await Deno.makeTempDir(); const filename = tempDir + "/test.txt"; const f = await Deno.open(filename, "w"); @@ -91,7 +96,9 @@ testPerm({ read: true, write: true }, async function createFile() { await Deno.remove(tempDir, { recursive: true }); }); -testPerm({ read: true, write: true }, async function openModeWrite() { +testPerm({ read: true, write: true }, async function openModeWrite(): Promise< + void +> { const tempDir = Deno.makeTempDirSync(); const encoder = new TextEncoder(); const filename = tempDir + "hello.txt"; @@ -125,32 +132,35 @@ testPerm({ read: true, write: true }, async function openModeWrite() { await Deno.remove(tempDir, { recursive: true }); }); -testPerm({ read: true, write: true }, async function openModeWriteRead() { - const tempDir = Deno.makeTempDirSync(); - const encoder = new TextEncoder(); - const filename = tempDir + "hello.txt"; - const data = encoder.encode("Hello world!\n"); +testPerm( + { read: true, write: true }, + async function openModeWriteRead(): Promise<void> { + const tempDir = Deno.makeTempDirSync(); + const encoder = new TextEncoder(); + const filename = tempDir + "hello.txt"; + const data = encoder.encode("Hello world!\n"); + + const file = await Deno.open(filename, "w+"); + // assert file was created + let fileInfo = Deno.statSync(filename); + assert(fileInfo.isFile()); + assertEquals(fileInfo.len, 0); + // write some data + await file.write(data); + fileInfo = Deno.statSync(filename); + assertEquals(fileInfo.len, 13); - const file = await Deno.open(filename, "w+"); - // assert file was created - let fileInfo = Deno.statSync(filename); - assert(fileInfo.isFile()); - assertEquals(fileInfo.len, 0); - // write some data - await file.write(data); - fileInfo = Deno.statSync(filename); - assertEquals(fileInfo.len, 13); - - const buf = new Uint8Array(20); - await file.seek(0, Deno.SeekMode.SEEK_START); - const result = await file.read(buf); - assertEquals(result.nread, 13); - file.close(); + const buf = new Uint8Array(20); + await file.seek(0, Deno.SeekMode.SEEK_START); + const result = await file.read(buf); + assertEquals(result.nread, 13); + file.close(); - await Deno.remove(tempDir, { recursive: true }); -}); + await Deno.remove(tempDir, { recursive: true }); + } +); -testPerm({ read: true }, async function seekStart() { +testPerm({ read: true }, async function seekStart(): Promise<void> { const filename = "tests/hello.txt"; const file = await Deno.open(filename); // Deliberately move 1 step forward @@ -163,7 +173,7 @@ testPerm({ read: true }, async function seekStart() { assertEquals(decoded, "world!"); }); -testPerm({ read: true }, function seekSyncStart() { +testPerm({ read: true }, function seekSyncStart(): void { const filename = "tests/hello.txt"; const file = Deno.openSync(filename); // Deliberately move 1 step forward @@ -176,7 +186,7 @@ testPerm({ read: true }, function seekSyncStart() { assertEquals(decoded, "world!"); }); -testPerm({ read: true }, async function seekCurrent() { +testPerm({ read: true }, async function seekCurrent(): Promise<void> { const filename = "tests/hello.txt"; const file = await Deno.open(filename); // Deliberately move 1 step forward @@ -189,7 +199,7 @@ testPerm({ read: true }, async function seekCurrent() { assertEquals(decoded, "world!"); }); -testPerm({ read: true }, function seekSyncCurrent() { +testPerm({ read: true }, function seekSyncCurrent(): void { const filename = "tests/hello.txt"; const file = Deno.openSync(filename); // Deliberately move 1 step forward @@ -202,7 +212,7 @@ testPerm({ read: true }, function seekSyncCurrent() { assertEquals(decoded, "world!"); }); -testPerm({ read: true }, async function seekEnd() { +testPerm({ read: true }, async function seekEnd(): Promise<void> { const filename = "tests/hello.txt"; const file = await Deno.open(filename); await file.seek(-6, Deno.SeekMode.SEEK_END); @@ -212,7 +222,7 @@ testPerm({ read: true }, async function seekEnd() { assertEquals(decoded, "world!"); }); -testPerm({ read: true }, function seekSyncEnd() { +testPerm({ read: true }, function seekSyncEnd(): void { const filename = "tests/hello.txt"; const file = Deno.openSync(filename); file.seekSync(-6, Deno.SeekMode.SEEK_END); @@ -222,7 +232,7 @@ testPerm({ read: true }, function seekSyncEnd() { assertEquals(decoded, "world!"); }); -testPerm({ read: true }, async function seekMode() { +testPerm({ read: true }, async function seekMode(): Promise<void> { const filename = "tests/hello.txt"; const file = await Deno.open(filename); let err; diff --git a/js/form_data.ts b/js/form_data.ts index 1a8a72826..3c40e64d3 100644 --- a/js/form_data.ts +++ b/js/form_data.ts @@ -89,7 +89,7 @@ class FormDataBase { has(name: string): boolean { requiredArguments("FormData.has", arguments.length, 1); name = String(name); - return this[dataSymbol].some(entry => entry[0] === name); + return this[dataSymbol].some((entry): boolean => entry[0] === name); } /** Sets a new value for an existing key inside a `FormData` object, or diff --git a/js/form_data_test.ts b/js/form_data_test.ts index c02811fbc..fe8b6cf32 100644 --- a/js/form_data_test.ts +++ b/js/form_data_test.ts @@ -1,17 +1,17 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEquals } from "./test_util.ts"; -test(function formDataHasCorrectNameProp() { +test(function formDataHasCorrectNameProp(): void { assertEquals(FormData.name, "FormData"); }); -test(function formDataParamsAppendSuccess() { +test(function formDataParamsAppendSuccess(): void { const formData = new FormData(); formData.append("a", "true"); assertEquals(formData.get("a"), "true"); }); -test(function formDataParamsDeleteSuccess() { +test(function formDataParamsDeleteSuccess(): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -21,7 +21,7 @@ test(function formDataParamsDeleteSuccess() { assertEquals(formData.get("b"), null); }); -test(function formDataParamsGetAllSuccess() { +test(function formDataParamsGetAllSuccess(): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -31,7 +31,7 @@ test(function formDataParamsGetAllSuccess() { assertEquals(formData.getAll("c"), []); }); -test(function formDataParamsGetSuccess() { +test(function formDataParamsGetSuccess(): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -45,7 +45,7 @@ test(function formDataParamsGetSuccess() { assertEquals(formData.get("e"), "null"); }); -test(function formDataParamsHasSuccess() { +test(function formDataParamsHasSuccess(): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -54,7 +54,7 @@ test(function formDataParamsHasSuccess() { assert(!formData.has("c")); }); -test(function formDataParamsSetSuccess() { +test(function formDataParamsSetSuccess(): void { const formData = new FormData(); formData.append("a", "true"); formData.append("b", "false"); @@ -69,7 +69,7 @@ test(function formDataParamsSetSuccess() { assertEquals(formData.get("e"), "null"); }); -test(function formDataSetEmptyBlobSuccess() { +test(function formDataSetEmptyBlobSuccess(): void { const formData = new FormData(); formData.set("a", new Blob([]), "blank.txt"); formData.get("a"); @@ -81,93 +81,99 @@ test(function formDataSetEmptyBlobSuccess() { */ }); -test(function formDataParamsForEachSuccess() { +test(function formDataParamsForEachSuccess(): void { const init = [["a", "54"], ["b", "true"]]; const formData = new FormData(); for (const [name, value] of init) { formData.append(name, value); } let callNum = 0; - formData.forEach((value, key, parent) => { - assertEquals(formData, parent); - assertEquals(value, init[callNum][1]); - assertEquals(key, init[callNum][0]); - callNum++; - }); + formData.forEach( + (value, key, parent): void => { + assertEquals(formData, parent); + assertEquals(value, init[callNum][1]); + assertEquals(key, init[callNum][0]); + callNum++; + } + ); assertEquals(callNum, init.length); }); -test(function formDataParamsArgumentsCheck() { +test(function formDataParamsArgumentsCheck(): void { const methodRequireOneParam = ["delete", "getAll", "get", "has", "forEach"]; const methodRequireTwoParams = ["append", "set"]; - methodRequireOneParam.forEach(method => { - const formData = new FormData(); - let hasThrown = 0; - let errMsg = ""; - try { - formData[method](); - hasThrown = 1; - } catch (err) { - errMsg = err.message; - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + methodRequireOneParam.forEach( + (method): void => { + const formData = new FormData(); + let hasThrown = 0; + let errMsg = ""; + try { + formData[method](); + hasThrown = 1; + } catch (err) { + errMsg = err.message; + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } + assertEquals(hasThrown, 2); + assertEquals( + errMsg, + `FormData.${method} requires at least 1 argument, but only 0 present` + ); } - assertEquals(hasThrown, 2); - assertEquals( - errMsg, - `FormData.${method} requires at least 1 argument, but only 0 present` - ); - }); - - methodRequireTwoParams.forEach(method => { - const formData = new FormData(); - let hasThrown = 0; - let errMsg = ""; - - try { - formData[method](); - hasThrown = 1; - } catch (err) { - errMsg = err.message; - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + ); + + methodRequireTwoParams.forEach( + (method: string): void => { + const formData = new FormData(); + let hasThrown = 0; + let errMsg = ""; + + try { + formData[method](); + hasThrown = 1; + } catch (err) { + errMsg = err.message; + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } - } - assertEquals(hasThrown, 2); - assertEquals( - errMsg, - `FormData.${method} requires at least 2 arguments, but only 0 present` - ); - - hasThrown = 0; - errMsg = ""; - try { - formData[method]("foo"); - hasThrown = 1; - } catch (err) { - errMsg = err.message; - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + assertEquals(hasThrown, 2); + assertEquals( + errMsg, + `FormData.${method} requires at least 2 arguments, but only 0 present` + ); + + hasThrown = 0; + errMsg = ""; + try { + formData[method]("foo"); + hasThrown = 1; + } catch (err) { + errMsg = err.message; + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } + assertEquals(hasThrown, 2); + assertEquals( + errMsg, + `FormData.${method} requires at least 2 arguments, but only 1 present` + ); } - assertEquals(hasThrown, 2); - assertEquals( - errMsg, - `FormData.${method} requires at least 2 arguments, but only 1 present` - ); - }); + ); }); -test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility(): void { const formData = new FormData(); assertEquals(formData.toString(), "[object FormData]"); }); diff --git a/js/globals_test.ts b/js/globals_test.ts index 4937e6c9a..3085118de 100644 --- a/js/globals_test.ts +++ b/js/globals_test.ts @@ -1,40 +1,40 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert } from "./test_util.ts"; -test(function globalThisExists() { +test(function globalThisExists(): void { assert(globalThis != null); }); -test(function windowExists() { +test(function windowExists(): void { assert(window != null); }); -test(function windowWindowExists() { +test(function windowWindowExists(): void { assert(window.window === window); }); -test(function globalThisEqualsWindow() { +test(function globalThisEqualsWindow(): void { // @ts-ignore (TypeScript thinks globalThis and window don't match) assert(globalThis === window); }); -test(function DenoNamespaceExists() { +test(function DenoNamespaceExists(): void { assert(Deno != null); }); -test(function DenoNamespaceEqualsWindowDeno() { +test(function DenoNamespaceEqualsWindowDeno(): void { assert(Deno === window.Deno); }); -test(function DenoNamespaceIsFrozen() { +test(function DenoNamespaceIsFrozen(): void { assert(Object.isFrozen(Deno)); }); -test(function webAssemblyExists() { +test(function webAssemblyExists(): void { assert(typeof WebAssembly.compile === "function"); }); -test(function DenoNamespaceImmutable() { +test(function DenoNamespaceImmutable(): void { const denoCopy = window.Deno; try { // @ts-ignore diff --git a/js/headers_test.ts b/js/headers_test.ts index 2e6b48e88..f08283c51 100644 --- a/js/headers_test.ts +++ b/js/headers_test.ts @@ -4,7 +4,7 @@ import { test, assert, assertEquals } from "./test_util.ts"; // Logic heavily copied from web-platform-tests, make // sure pass mostly header basic test // ref: https://github.com/web-platform-tests/wpt/blob/7c50c216081d6ea3c9afe553ee7b64534020a1b2/fetch/api/headers/headers-basic.html -test(function newHeaderTest() { +test(function newHeaderTest(): void { new Headers(); new Headers(undefined); new Headers({}); @@ -30,7 +30,7 @@ for (const name in headerDict) { headerSeq.push([name, headerDict[name]]); } -test(function newHeaderWithSequence() { +test(function newHeaderWithSequence(): void { const headers = new Headers(headerSeq); for (const name in headerDict) { assertEquals(headers.get(name), String(headerDict[name])); @@ -38,14 +38,14 @@ test(function newHeaderWithSequence() { assertEquals(headers.get("length"), null); }); -test(function newHeaderWithRecord() { +test(function newHeaderWithRecord(): void { const headers = new Headers(headerDict); for (const name in headerDict) { assertEquals(headers.get(name), String(headerDict[name])); } }); -test(function newHeaderWithHeadersInstance() { +test(function newHeaderWithHeadersInstance(): void { const headers = new Headers(headerDict); const headers2 = new Headers(headers); for (const name in headerDict) { @@ -53,7 +53,7 @@ test(function newHeaderWithHeadersInstance() { } }); -test(function headerAppendSuccess() { +test(function headerAppendSuccess(): void { const headers = new Headers(); for (const name in headerDict) { headers.append(name, headerDict[name]); @@ -61,7 +61,7 @@ test(function headerAppendSuccess() { } }); -test(function headerSetSuccess() { +test(function headerSetSuccess(): void { const headers = new Headers(); for (const name in headerDict) { headers.set(name, headerDict[name]); @@ -69,7 +69,7 @@ test(function headerSetSuccess() { } }); -test(function headerHasSuccess() { +test(function headerHasSuccess(): void { const headers = new Headers(headerDict); for (const name in headerDict) { assert(headers.has(name), "headers has name " + name); @@ -80,7 +80,7 @@ test(function headerHasSuccess() { } }); -test(function headerDeleteSuccess() { +test(function headerDeleteSuccess(): void { const headers = new Headers(headerDict); for (const name in headerDict) { assert(headers.has(name), "headers have a header: " + name); @@ -89,7 +89,7 @@ test(function headerDeleteSuccess() { } }); -test(function headerGetSuccess() { +test(function headerGetSuccess(): void { const headers = new Headers(headerDict); for (const name in headerDict) { assertEquals(headers.get(name), String(headerDict[name])); @@ -97,7 +97,7 @@ test(function headerGetSuccess() { } }); -test(function headerEntriesSuccess() { +test(function headerEntriesSuccess(): void { const headers = new Headers(headerDict); const iterators = headers.entries(); for (const it of iterators) { @@ -108,7 +108,7 @@ test(function headerEntriesSuccess() { } }); -test(function headerKeysSuccess() { +test(function headerKeysSuccess(): void { const headers = new Headers(headerDict); const iterators = headers.keys(); for (const it of iterators) { @@ -116,7 +116,7 @@ test(function headerKeysSuccess() { } }); -test(function headerValuesSuccess() { +test(function headerValuesSuccess(): void { const headers = new Headers(headerDict); const iterators = headers.values(); const entries = headers.entries(); @@ -138,24 +138,28 @@ const headerEntriesDict = { "Content-Types": "value6" }; -test(function headerForEachSuccess() { +test(function headerForEachSuccess(): void { const headers = new Headers(headerEntriesDict); const keys = Object.keys(headerEntriesDict); - keys.forEach(key => { - const value = headerEntriesDict[key]; - const newkey = key.toLowerCase(); - headerEntriesDict[newkey] = value; - }); + keys.forEach( + (key): void => { + const value = headerEntriesDict[key]; + const newkey = key.toLowerCase(); + headerEntriesDict[newkey] = value; + } + ); let callNum = 0; - headers.forEach((value, key, container) => { - assertEquals(headers, container); - assertEquals(value, headerEntriesDict[key]); - callNum++; - }); + headers.forEach( + (value, key, container): void => { + assertEquals(headers, container); + assertEquals(value, headerEntriesDict[key]); + callNum++; + } + ); assertEquals(callNum, keys.length); }); -test(function headerSymbolIteratorSuccess() { +test(function headerSymbolIteratorSuccess(): void { assert(Symbol.iterator in Headers.prototype); const headers = new Headers(headerEntriesDict); for (const header of headers) { @@ -166,7 +170,7 @@ test(function headerSymbolIteratorSuccess() { } }); -test(function headerTypesAvailable() { +test(function headerTypesAvailable(): void { function newHeaders(): Headers { return new Headers(); } @@ -176,7 +180,7 @@ test(function headerTypesAvailable() { // Modified from https://github.com/bitinn/node-fetch/blob/7d3293200a91ad52b5ca7962f9d6fd1c04983edb/test/test.js#L2001-L2014 // Copyright (c) 2016 David Frank. MIT License. -test(function headerIllegalReject() { +test(function headerIllegalReject(): void { let errorCount = 0; try { new Headers({ "He y": "ok" }); @@ -230,7 +234,7 @@ test(function headerIllegalReject() { }); // If pair does not contain exactly two items,then throw a TypeError. -test(function headerParamsShouldThrowTypeError() { +test(function headerParamsShouldThrowTypeError(): void { let hasThrown = 0; try { @@ -247,77 +251,81 @@ test(function headerParamsShouldThrowTypeError() { assertEquals(hasThrown, 2); }); -test(function headerParamsArgumentsCheck() { +test(function headerParamsArgumentsCheck(): void { const methodRequireOneParam = ["delete", "get", "has", "forEach"]; const methodRequireTwoParams = ["append", "set"]; - methodRequireOneParam.forEach(method => { - const headers = new Headers(); - let hasThrown = 0; - let errMsg = ""; - try { - headers[method](); - hasThrown = 1; - } catch (err) { - errMsg = err.message; - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + methodRequireOneParam.forEach( + (method): void => { + const headers = new Headers(); + let hasThrown = 0; + let errMsg = ""; + try { + headers[method](); + hasThrown = 1; + } catch (err) { + errMsg = err.message; + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } + assertEquals(hasThrown, 2); + assertEquals( + errMsg, + `Headers.${method} requires at least 1 argument, but only 0 present` + ); } - assertEquals(hasThrown, 2); - assertEquals( - errMsg, - `Headers.${method} requires at least 1 argument, but only 0 present` - ); - }); + ); - methodRequireTwoParams.forEach(method => { - const headers = new Headers(); - let hasThrown = 0; - let errMsg = ""; + methodRequireTwoParams.forEach( + (method): void => { + const headers = new Headers(); + let hasThrown = 0; + let errMsg = ""; - try { - headers[method](); - hasThrown = 1; - } catch (err) { - errMsg = err.message; - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + try { + headers[method](); + hasThrown = 1; + } catch (err) { + errMsg = err.message; + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } - } - assertEquals(hasThrown, 2); - assertEquals( - errMsg, - `Headers.${method} requires at least 2 arguments, but only 0 present` - ); + assertEquals(hasThrown, 2); + assertEquals( + errMsg, + `Headers.${method} requires at least 2 arguments, but only 0 present` + ); - hasThrown = 0; - errMsg = ""; - try { - headers[method]("foo"); - hasThrown = 1; - } catch (err) { - errMsg = err.message; - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + hasThrown = 0; + errMsg = ""; + try { + headers[method]("foo"); + hasThrown = 1; + } catch (err) { + errMsg = err.message; + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } + assertEquals(hasThrown, 2); + assertEquals( + errMsg, + `Headers.${method} requires at least 2 arguments, but only 1 present` + ); } - assertEquals(hasThrown, 2); - assertEquals( - errMsg, - `Headers.${method} requires at least 2 arguments, but only 1 present` - ); - }); + ); }); -test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility(): void { const headers = new Headers(); assertEquals(headers.toString(), "[object Headers]"); }); @@ -146,7 +146,7 @@ export function toAsyncIterator(r: Reader): AsyncIterableIterator<Uint8Array> { const b = new Uint8Array(1024); return { - [Symbol.asyncIterator]() { + [Symbol.asyncIterator](): AsyncIterableIterator<Uint8Array> { return this; }, diff --git a/js/link_test.ts b/js/link_test.ts index c2ca7b1f8..d6b5f0a33 100644 --- a/js/link_test.ts +++ b/js/link_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ read: true, write: true }, function linkSyncSuccess() { +testPerm({ read: true, write: true }, function linkSyncSuccess(): void { const testDir = Deno.makeTempDirSync(); const oldData = "Hardlink"; const oldName = testDir + "/oldname"; @@ -28,7 +28,7 @@ testPerm({ read: true, write: true }, function linkSyncSuccess() { assertEquals(newData3, new TextDecoder().decode(Deno.readFileSync(newName))); }); -testPerm({ read: true, write: true }, function linkSyncExists() { +testPerm({ read: true, write: true }, function linkSyncExists(): void { const testDir = Deno.makeTempDirSync(); const oldName = testDir + "/oldname"; const newName = testDir + "/newname"; @@ -48,7 +48,7 @@ testPerm({ read: true, write: true }, function linkSyncExists() { assertEquals(err.name, "AlreadyExists"); }); -testPerm({ read: true, write: true }, function linkSyncNotFound() { +testPerm({ read: true, write: true }, function linkSyncNotFound(): void { const testDir = Deno.makeTempDirSync(); const oldName = testDir + "/oldname"; const newName = testDir + "/newname"; @@ -65,7 +65,7 @@ testPerm({ read: true, write: true }, function linkSyncNotFound() { assertEquals(err.name, "NotFound"); }); -test(function linkSyncPerm() { +test(function linkSyncPerm(): void { let err; try { Deno.linkSync("oldbaddir", "newbaddir"); @@ -76,7 +76,9 @@ test(function linkSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ read: true, write: true }, async function linkSuccess() { +testPerm({ read: true, write: true }, async function linkSuccess(): Promise< + void +> { const testDir = Deno.makeTempDirSync(); const oldData = "Hardlink"; const oldName = testDir + "/oldname"; diff --git a/js/location_test.ts b/js/location_test.ts index 2302c32ed..c8daab16d 100644 --- a/js/location_test.ts +++ b/js/location_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert } from "./test_util.ts"; -test(function locationBasic() { +test(function locationBasic(): void { // location example: file:///Users/rld/src/deno/js/unit_tests.ts console.log("location", window.location.toString()); assert(window.location.toString().endsWith("unit_tests.ts")); diff --git a/js/make_temp_dir_test.ts b/js/make_temp_dir_test.ts index 46738617d..aa44b65c5 100644 --- a/js/make_temp_dir_test.ts +++ b/js/make_temp_dir_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ write: true }, function makeTempDirSyncSuccess() { +testPerm({ write: true }, function makeTempDirSyncSuccess(): void { const dir1 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" }); const dir2 = Deno.makeTempDirSync({ prefix: "hello", suffix: "world" }); // Check that both dirs are different. @@ -27,7 +27,7 @@ testPerm({ write: true }, function makeTempDirSyncSuccess() { assertEquals(err.name, "NotFound"); }); -test(function makeTempDirSyncPerm() { +test(function makeTempDirSyncPerm(): void { // makeTempDirSync should require write permissions (for now). let err; try { @@ -39,7 +39,7 @@ test(function makeTempDirSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ write: true }, async function makeTempDirSuccess() { +testPerm({ write: true }, async function makeTempDirSuccess(): Promise<void> { const dir1 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); const dir2 = await Deno.makeTempDir({ prefix: "hello", suffix: "world" }); // Check that both dirs are different. diff --git a/js/metrics_test.ts b/js/metrics_test.ts index cb76eb854..de41a0cb1 100644 --- a/js/metrics_test.ts +++ b/js/metrics_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert } from "./test_util.ts"; -test(async function metrics() { +test(async function metrics(): Promise<void> { const m1 = Deno.metrics(); assert(m1.opsDispatched > 0); assert(m1.opsCompleted > 0); @@ -22,7 +22,7 @@ test(async function metrics() { assert(m2.bytesReceived > m1.bytesReceived); }); -testPerm({ write: true }, function metricsUpdatedIfNoResponseSync() { +testPerm({ write: true }, function metricsUpdatedIfNoResponseSync(): void { const filename = Deno.makeTempDirSync() + "/test.txt"; const data = new Uint8Array([41, 42, 43]); @@ -32,12 +32,15 @@ testPerm({ write: true }, function metricsUpdatedIfNoResponseSync() { assert(metrics.opsDispatched === metrics.opsCompleted); }); -testPerm({ write: true }, async function metricsUpdatedIfNoResponseAsync() { - const filename = Deno.makeTempDirSync() + "/test.txt"; +testPerm( + { write: true }, + async function metricsUpdatedIfNoResponseAsync(): Promise<void> { + const filename = Deno.makeTempDirSync() + "/test.txt"; - const data = new Uint8Array([41, 42, 43]); - await Deno.writeFile(filename, data, { perm: 0o666 }); + const data = new Uint8Array([41, 42, 43]); + await Deno.writeFile(filename, data, { perm: 0o666 }); - const metrics = Deno.metrics(); - assert(metrics.opsDispatched === metrics.opsCompleted); -}); + const metrics = Deno.metrics(); + assert(metrics.opsDispatched === metrics.opsCompleted); + } +); diff --git a/js/mixins/dom_iterable_test.ts b/js/mixins/dom_iterable_test.ts index 36e3de678..4c84fa68e 100644 --- a/js/mixins/dom_iterable_test.ts +++ b/js/mixins/dom_iterable_test.ts @@ -25,7 +25,7 @@ function setup() { }; } -test(function testDomIterable() { +test(function testDomIterable(): void { const { DomIterable, Base } = setup(); const fixture: Array<[string, number]> = [["foo", 1], ["bar", 2]]; @@ -59,7 +59,7 @@ test(function testDomIterable() { assertEquals(DomIterable.name, Base.name); }); -test(function testDomIterableScope() { +test(function testDomIterableScope(): void { const { DomIterable } = setup(); const domIterable = new DomIterable([["foo", 1]]); diff --git a/js/mkdir_test.ts b/js/mkdir_test.ts index 2d4f951aa..9e97265f0 100644 --- a/js/mkdir_test.ts +++ b/js/mkdir_test.ts @@ -1,14 +1,14 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ read: true, write: true }, function mkdirSyncSuccess() { +testPerm({ read: true, write: true }, function mkdirSyncSuccess(): void { const path = Deno.makeTempDirSync() + "/dir"; Deno.mkdirSync(path); const pathInfo = Deno.statSync(path); assert(pathInfo.isDirectory()); }); -testPerm({ read: true, write: true }, function mkdirSyncMode() { +testPerm({ read: true, write: true }, function mkdirSyncMode(): void { const path = Deno.makeTempDirSync() + "/dir"; Deno.mkdirSync(path, false, 0o755); // no perm for x const pathInfo = Deno.statSync(path); @@ -18,7 +18,7 @@ testPerm({ read: true, write: true }, function mkdirSyncMode() { } }); -testPerm({ write: false }, function mkdirSyncPerm() { +testPerm({ write: false }, function mkdirSyncPerm(): void { let err; try { Deno.mkdirSync("/baddir"); @@ -29,14 +29,16 @@ testPerm({ write: false }, function mkdirSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ read: true, write: true }, async function mkdirSuccess() { +testPerm({ read: true, write: true }, async function mkdirSuccess(): Promise< + void +> { const path = Deno.makeTempDirSync() + "/dir"; await Deno.mkdir(path); const pathInfo = Deno.statSync(path); assert(pathInfo.isDirectory()); }); -testPerm({ write: true }, function mkdirErrIfExists() { +testPerm({ write: true }, function mkdirErrIfExists(): void { let err; try { Deno.mkdirSync("."); @@ -47,14 +49,16 @@ testPerm({ write: true }, function mkdirErrIfExists() { assertEquals(err.name, "AlreadyExists"); }); -testPerm({ read: true, write: true }, function mkdirSyncRecursive() { +testPerm({ read: true, write: true }, function mkdirSyncRecursive(): void { const path = Deno.makeTempDirSync() + "/nested/directory"; Deno.mkdirSync(path, true); const pathInfo = Deno.statSync(path); assert(pathInfo.isDirectory()); }); -testPerm({ read: true, write: true }, async function mkdirRecursive() { +testPerm({ read: true, write: true }, async function mkdirRecursive(): Promise< + void +> { const path = Deno.makeTempDirSync() + "/nested/directory"; await Deno.mkdir(path, true); const pathInfo = Deno.statSync(path); diff --git a/js/net_test.ts b/js/net_test.ts index cb9a9163a..f02fa9611 100644 --- a/js/net_test.ts +++ b/js/net_test.ts @@ -1,12 +1,12 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ net: true }, function netListenClose() { +testPerm({ net: true }, function netListenClose(): void { const listener = Deno.listen("tcp", "127.0.0.1:4500"); listener.close(); }); -testPerm({ net: true }, async function netCloseWhileAccept() { +testPerm({ net: true }, async function netCloseWhileAccept(): Promise<void> { const listener = Deno.listen("tcp", ":4501"); const p = listener.accept(); listener.close(); @@ -21,7 +21,7 @@ testPerm({ net: true }, async function netCloseWhileAccept() { assertEquals(err.message, "Listener has been closed"); }); -testPerm({ net: true }, async function netConcurrentAccept() { +testPerm({ net: true }, async function netConcurrentAccept(): Promise<void> { const listener = Deno.listen("tcp", ":4502"); let acceptErrCount = 0; const checkErr = (e): void => { @@ -42,12 +42,14 @@ testPerm({ net: true }, async function netConcurrentAccept() { assertEquals(acceptErrCount, 1); }); -testPerm({ net: true }, async function netDialListen() { +testPerm({ net: true }, async function netDialListen(): Promise<void> { const listener = Deno.listen("tcp", ":4500"); - listener.accept().then(async conn => { - await conn.write(new Uint8Array([1, 2, 3])); - conn.close(); - }); + listener.accept().then( + async (conn): Promise<void> => { + await conn.write(new Uint8Array([1, 2, 3])); + conn.close(); + } + ); const conn = await Deno.dial("tcp", "127.0.0.1:4500"); const buf = new Uint8Array(1024); const readResult = await conn.read(buf); @@ -108,7 +108,7 @@ function createEnv(inner: msg.EnvironRes): { [index: string]: string } { } return new Proxy(env, { - set(obj, prop: string, value: string) { + set(obj, prop: string, value: string): boolean { setEnv(prop, value); return Reflect.set(obj, prop, value); } diff --git a/js/os_test.ts b/js/os_test.ts index 39429d919..d3c9e6546 100644 --- a/js/os_test.ts +++ b/js/os_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ env: true }, function envSuccess() { +testPerm({ env: true }, function envSuccess(): void { const env = Deno.env(); assert(env !== null); // eslint-disable-next-line @typescript-eslint/camelcase @@ -10,7 +10,7 @@ testPerm({ env: true }, function envSuccess() { assertEquals(env.test_var, newEnv.test_var); }); -test(function envFailure() { +test(function envFailure(): void { let caughtError = false; try { Deno.env(); @@ -23,12 +23,12 @@ test(function envFailure() { assert(caughtError); }); -test(function osPid() { +test(function osPid(): void { console.log("pid", Deno.pid); assert(Deno.pid > 0); }); // See complete tests in tools/is_tty_test.py -test(function osIsTTYSmoke() { +test(function osIsTTYSmoke(): void { console.log(Deno.isTTY()); }); diff --git a/js/performance_test.ts b/js/performance_test.ts index 8f9dbc990..1238a3836 100644 --- a/js/performance_test.ts +++ b/js/performance_test.ts @@ -1,9 +1,9 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert } from "./test_util.ts"; -testPerm({ highPrecision: false }, function now() { +testPerm({ highPrecision: false }, function now(): void { const start = performance.now(); - setTimeout(() => { + setTimeout((): void => { const end = performance.now(); assert(end - start >= 10); }, 10); diff --git a/js/permissions_test.ts b/js/permissions_test.ts index c49696c01..0a16255e4 100644 --- a/js/permissions_test.ts +++ b/js/permissions_test.ts @@ -11,7 +11,7 @@ const knownPermissions: Deno.Permission[] = [ ]; for (let grant of knownPermissions) { - testPerm({ [grant]: true }, function envGranted() { + testPerm({ [grant]: true }, function envGranted(): void { const perms = Deno.permissions(); assert(perms !== null); for (const perm in perms) { diff --git a/js/process.ts b/js/process.ts index fc5e5f652..a0eef63dd 100644 --- a/js/process.ts +++ b/js/process.ts @@ -150,7 +150,7 @@ export function run(opt: RunOptions): Process { const builder = flatbuffers.createBuilder(); const argsOffset = msg.Run.createArgsVector( builder, - opt.args.map(a => builder.createString(a)) + opt.args.map((a): number => builder.createString(a)) ); const cwdOffset = opt.cwd == null ? 0 : builder.createString(opt.cwd); const kvOffset: flatbuffers.Offset[] = []; diff --git a/js/process_test.ts b/js/process_test.ts index 051841ffe..c89e1cae7 100644 --- a/js/process_test.ts +++ b/js/process_test.ts @@ -2,7 +2,7 @@ import { test, testPerm, assert, assertEquals } from "./test_util.ts"; const { run, DenoError, ErrorKind } = Deno; -test(function runPermissions() { +test(function runPermissions(): void { let caughtError = false; try { Deno.run({ args: ["python", "-c", "print('hello world')"] }); @@ -14,7 +14,7 @@ test(function runPermissions() { assert(caughtError); }); -testPerm({ run: true }, async function runSuccess() { +testPerm({ run: true }, async function runSuccess(): Promise<void> { const p = run({ args: ["python", "-c", "print('hello world')"] }); @@ -26,7 +26,9 @@ testPerm({ run: true }, async function runSuccess() { p.close(); }); -testPerm({ run: true }, async function runCommandFailedWithCode() { +testPerm({ run: true }, async function runCommandFailedWithCode(): Promise< + void +> { let p = run({ args: ["python", "-c", "import sys;sys.exit(41 + 1)"] }); @@ -37,7 +39,9 @@ testPerm({ run: true }, async function runCommandFailedWithCode() { p.close(); }); -testPerm({ run: true }, async function runCommandFailedWithSignal() { +testPerm({ run: true }, async function runCommandFailedWithSignal(): Promise< + void +> { if (Deno.build.os === "win") { return; // No signals on windows. } @@ -51,7 +55,7 @@ testPerm({ run: true }, async function runCommandFailedWithSignal() { p.close(); }); -testPerm({ run: true }, function runNotFound() { +testPerm({ run: true }, function runNotFound(): void { let error; try { run({ args: ["this file hopefully doesn't exist"] }); @@ -63,13 +67,15 @@ testPerm({ run: true }, function runNotFound() { assertEquals(error.kind, ErrorKind.NotFound); }); -testPerm({ write: true, run: true }, async function runWithCwdIsAsync() { - const enc = new TextEncoder(); - const cwd = Deno.makeTempDirSync({ prefix: "deno_command_test" }); +testPerm( + { write: true, run: true }, + async function runWithCwdIsAsync(): Promise<void> { + const enc = new TextEncoder(); + const cwd = Deno.makeTempDirSync({ prefix: "deno_command_test" }); - const exitCodeFile = "deno_was_here"; - const pyProgramFile = "poll_exit.py"; - const pyProgram = ` + const exitCodeFile = "deno_was_here"; + const pyProgramFile = "poll_exit.py"; + const pyProgram = ` from sys import exit from time import sleep @@ -85,25 +91,26 @@ while True: pass `; - Deno.writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram)); - const p = run({ - cwd, - args: ["python", `${pyProgramFile}.py`] - }); - - // Write the expected exit code *after* starting python. - // This is how we verify that `run()` is actually asynchronous. - const code = 84; - Deno.writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`)); - - const status = await p.status(); - assertEquals(status.success, false); - assertEquals(status.code, code); - assertEquals(status.signal, undefined); - p.close(); -}); + Deno.writeFileSync(`${cwd}/${pyProgramFile}.py`, enc.encode(pyProgram)); + const p = run({ + cwd, + args: ["python", `${pyProgramFile}.py`] + }); + + // Write the expected exit code *after* starting python. + // This is how we verify that `run()` is actually asynchronous. + const code = 84; + Deno.writeFileSync(`${cwd}/${exitCodeFile}`, enc.encode(`${code}`)); + + const status = await p.status(); + assertEquals(status.success, false); + assertEquals(status.code, code); + assertEquals(status.signal, undefined); + p.close(); + } +); -testPerm({ run: true }, async function runStdinPiped() { +testPerm({ run: true }, async function runStdinPiped(): Promise<void> { const p = run({ args: ["python", "-c", "import sys; assert 'hello' == sys.stdin.read();"], stdin: "piped" @@ -124,7 +131,7 @@ testPerm({ run: true }, async function runStdinPiped() { p.close(); }); -testPerm({ run: true }, async function runStdoutPiped() { +testPerm({ run: true }, async function runStdoutPiped(): Promise<void> { const p = run({ args: ["python", "-c", "import sys; sys.stdout.write('hello')"], stdout: "piped" @@ -150,7 +157,7 @@ testPerm({ run: true }, async function runStdoutPiped() { p.close(); }); -testPerm({ run: true }, async function runStderrPiped() { +testPerm({ run: true }, async function runStderrPiped(): Promise<void> { const p = run({ args: ["python", "-c", "import sys; sys.stderr.write('hello')"], stderr: "piped" @@ -176,7 +183,7 @@ testPerm({ run: true }, async function runStderrPiped() { p.close(); }); -testPerm({ run: true }, async function runOutput() { +testPerm({ run: true }, async function runOutput(): Promise<void> { const p = run({ args: ["python", "-c", "import sys; sys.stdout.write('hello')"], stdout: "piped" @@ -187,7 +194,7 @@ testPerm({ run: true }, async function runOutput() { p.close(); }); -testPerm({ run: true }, async function runStderrOutput() { +testPerm({ run: true }, async function runStderrOutput(): Promise<void> { const p = run({ args: ["python", "-c", "import sys; sys.stderr.write('error')"], stderr: "piped" @@ -198,7 +205,7 @@ testPerm({ run: true }, async function runStderrOutput() { p.close(); }); -testPerm({ run: true }, async function runEnv() { +testPerm({ run: true }, async function runEnv(): Promise<void> { const p = run({ args: [ "python", diff --git a/js/read_dir_test.ts b/js/read_dir_test.ts index c2d90642c..a8466dda9 100644 --- a/js/read_dir_test.ts +++ b/js/read_dir_test.ts @@ -22,12 +22,12 @@ function assertSameContent(files: FileInfo[]): void { assertEquals(counter, 2); } -testPerm({ read: true }, function readDirSyncSuccess() { +testPerm({ read: true }, function readDirSyncSuccess(): void { const files = Deno.readDirSync("tests/"); assertSameContent(files); }); -testPerm({ read: false }, function readDirSyncPerm() { +testPerm({ read: false }, function readDirSyncPerm(): void { let caughtError = false; try { Deno.readDirSync("tests/"); @@ -39,7 +39,7 @@ testPerm({ read: false }, function readDirSyncPerm() { assert(caughtError); }); -testPerm({ read: true }, function readDirSyncNotDir() { +testPerm({ read: true }, function readDirSyncNotDir(): void { let caughtError = false; let src; @@ -53,7 +53,7 @@ testPerm({ read: true }, function readDirSyncNotDir() { assertEquals(src, undefined); }); -testPerm({ read: true }, function readDirSyncNotFound() { +testPerm({ read: true }, function readDirSyncNotFound(): void { let caughtError = false; let src; @@ -67,12 +67,12 @@ testPerm({ read: true }, function readDirSyncNotFound() { assertEquals(src, undefined); }); -testPerm({ read: true }, async function readDirSuccess() { +testPerm({ read: true }, async function readDirSuccess(): Promise<void> { const files = await Deno.readDir("tests/"); assertSameContent(files); }); -testPerm({ read: false }, async function readDirPerm() { +testPerm({ read: false }, async function readDirPerm(): Promise<void> { let caughtError = false; try { await Deno.readDir("tests/"); diff --git a/js/read_file_test.ts b/js/read_file_test.ts index 2e0525d3f..7d4f4789c 100644 --- a/js/read_file_test.ts +++ b/js/read_file_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ read: true }, function readFileSyncSuccess() { +testPerm({ read: true }, function readFileSyncSuccess(): void { const data = Deno.readFileSync("package.json"); assert(data.byteLength > 0); const decoder = new TextDecoder("utf-8"); @@ -10,7 +10,7 @@ testPerm({ read: true }, function readFileSyncSuccess() { assertEquals(pkg.name, "deno"); }); -testPerm({ read: false }, function readFileSyncPerm() { +testPerm({ read: false }, function readFileSyncPerm(): void { let caughtError = false; try { Deno.readFileSync("package.json"); @@ -22,7 +22,7 @@ testPerm({ read: false }, function readFileSyncPerm() { assert(caughtError); }); -testPerm({ read: true }, function readFileSyncNotFound() { +testPerm({ read: true }, function readFileSyncNotFound(): void { let caughtError = false; let data; try { @@ -35,7 +35,7 @@ testPerm({ read: true }, function readFileSyncNotFound() { assert(data === undefined); }); -testPerm({ read: true }, async function readFileSuccess() { +testPerm({ read: true }, async function readFileSuccess(): Promise<void> { const data = await Deno.readFile("package.json"); assert(data.byteLength > 0); const decoder = new TextDecoder("utf-8"); @@ -44,7 +44,7 @@ testPerm({ read: true }, async function readFileSuccess() { assertEquals(pkg.name, "deno"); }); -testPerm({ read: false }, async function readFilePerm() { +testPerm({ read: false }, async function readFilePerm(): Promise<void> { let caughtError = false; try { await Deno.readFile("package.json"); diff --git a/js/read_link_test.ts b/js/read_link_test.ts index 270ae54fa..83a693e3b 100644 --- a/js/read_link_test.ts +++ b/js/read_link_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ write: true, read: true }, function readlinkSyncSuccess() { +testPerm({ write: true, read: true }, function readlinkSyncSuccess(): void { const testDir = Deno.makeTempDirSync(); const target = testDir + "/target"; const symlink = testDir + "/symln"; @@ -15,7 +15,7 @@ testPerm({ write: true, read: true }, function readlinkSyncSuccess() { } }); -testPerm({ read: false }, async function readlinkSyncPerm() { +testPerm({ read: false }, async function readlinkSyncPerm(): Promise<void> { let caughtError = false; try { Deno.readlinkSync("/symlink"); @@ -27,7 +27,7 @@ testPerm({ read: false }, async function readlinkSyncPerm() { assert(caughtError); }); -testPerm({ read: true }, function readlinkSyncNotFound() { +testPerm({ read: true }, function readlinkSyncNotFound(): void { let caughtError = false; let data; try { @@ -40,7 +40,9 @@ testPerm({ read: true }, function readlinkSyncNotFound() { assertEquals(data, undefined); }); -testPerm({ write: true, read: true }, async function readlinkSuccess() { +testPerm({ write: true, read: true }, async function readlinkSuccess(): Promise< + void +> { const testDir = Deno.makeTempDirSync(); const target = testDir + "/target"; const symlink = testDir + "/symln"; @@ -54,7 +56,7 @@ testPerm({ write: true, read: true }, async function readlinkSuccess() { } }); -testPerm({ read: false }, async function readlinkPerm() { +testPerm({ read: false }, async function readlinkPerm(): Promise<void> { let caughtError = false; try { await Deno.readlink("/symlink"); diff --git a/js/remove_test.ts b/js/remove_test.ts index e48b9a068..f14386f7f 100644 --- a/js/remove_test.ts +++ b/js/remove_test.ts @@ -3,7 +3,7 @@ import { testPerm, assert, assertEquals } from "./test_util.ts"; // SYNC -testPerm({ write: true }, function removeSyncDirSuccess() { +testPerm({ write: true }, function removeSyncDirSuccess(): void { // REMOVE EMPTY DIRECTORY const path = Deno.makeTempDirSync() + "/dir/subdir"; Deno.mkdirSync(path); @@ -22,7 +22,7 @@ testPerm({ write: true }, function removeSyncDirSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, function removeSyncFileSuccess() { +testPerm({ write: true }, function removeSyncFileSuccess(): void { // REMOVE FILE const enc = new TextEncoder(); const data = enc.encode("Hello"); @@ -43,7 +43,7 @@ testPerm({ write: true }, function removeSyncFileSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, function removeSyncFail() { +testPerm({ write: true }, function removeSyncFail(): void { // NON-EMPTY DIRECTORY const path = Deno.makeTempDirSync() + "/dir/subdir"; const subPath = path + "/subsubdir"; @@ -74,7 +74,7 @@ testPerm({ write: true }, function removeSyncFail() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: false }, function removeSyncPerm() { +testPerm({ write: false }, function removeSyncPerm(): void { let err; try { Deno.removeSync("/baddir"); @@ -85,7 +85,7 @@ testPerm({ write: false }, function removeSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ write: true }, function removeAllSyncDirSuccess() { +testPerm({ write: true }, function removeAllSyncDirSuccess(): void { // REMOVE EMPTY DIRECTORY let path = Deno.makeTempDirSync() + "/dir/subdir"; Deno.mkdirSync(path); @@ -123,7 +123,7 @@ testPerm({ write: true }, function removeAllSyncDirSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, function removeAllSyncFileSuccess() { +testPerm({ write: true }, function removeAllSyncFileSuccess(): void { // REMOVE FILE const enc = new TextEncoder(); const data = enc.encode("Hello"); @@ -144,7 +144,7 @@ testPerm({ write: true }, function removeAllSyncFileSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, function removeAllSyncFail() { +testPerm({ write: true }, function removeAllSyncFail(): void { // NON-EXISTENT DIRECTORY/FILE let err; try { @@ -157,7 +157,7 @@ testPerm({ write: true }, function removeAllSyncFail() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: false }, function removeAllSyncPerm() { +testPerm({ write: false }, function removeAllSyncPerm(): void { let err; try { Deno.removeSync("/baddir", { recursive: true }); @@ -170,7 +170,7 @@ testPerm({ write: false }, function removeAllSyncPerm() { // ASYNC -testPerm({ write: true }, async function removeDirSuccess() { +testPerm({ write: true }, async function removeDirSuccess(): Promise<void> { // REMOVE EMPTY DIRECTORY const path = Deno.makeTempDirSync() + "/dir/subdir"; Deno.mkdirSync(path); @@ -189,7 +189,7 @@ testPerm({ write: true }, async function removeDirSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, async function removeFileSuccess() { +testPerm({ write: true }, async function removeFileSuccess(): Promise<void> { // REMOVE FILE const enc = new TextEncoder(); const data = enc.encode("Hello"); @@ -210,7 +210,7 @@ testPerm({ write: true }, async function removeFileSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, async function removeFail() { +testPerm({ write: true }, async function removeFail(): Promise<void> { // NON-EMPTY DIRECTORY const path = Deno.makeTempDirSync() + "/dir/subdir"; const subPath = path + "/subsubdir"; @@ -240,7 +240,7 @@ testPerm({ write: true }, async function removeFail() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: false }, async function removePerm() { +testPerm({ write: false }, async function removePerm(): Promise<void> { let err; try { await Deno.remove("/baddir"); @@ -251,7 +251,7 @@ testPerm({ write: false }, async function removePerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ write: true }, async function removeAllDirSuccess() { +testPerm({ write: true }, async function removeAllDirSuccess(): Promise<void> { // REMOVE EMPTY DIRECTORY let path = Deno.makeTempDirSync() + "/dir/subdir"; Deno.mkdirSync(path); @@ -289,7 +289,7 @@ testPerm({ write: true }, async function removeAllDirSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, async function removeAllFileSuccess() { +testPerm({ write: true }, async function removeAllFileSuccess(): Promise<void> { // REMOVE FILE const enc = new TextEncoder(); const data = enc.encode("Hello"); @@ -310,7 +310,7 @@ testPerm({ write: true }, async function removeAllFileSuccess() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: true }, async function removeAllFail() { +testPerm({ write: true }, async function removeAllFail(): Promise<void> { // NON-EXISTENT DIRECTORY/FILE let err; try { @@ -323,7 +323,7 @@ testPerm({ write: true }, async function removeAllFail() { assertEquals(err.name, "NotFound"); }); -testPerm({ write: false }, async function removeAllPerm() { +testPerm({ write: false }, async function removeAllPerm(): Promise<void> { let err; try { await Deno.remove("/baddir", { recursive: true }); diff --git a/js/rename_test.ts b/js/rename_test.ts index 689787115..ce87a3dfe 100644 --- a/js/rename_test.ts +++ b/js/rename_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ read: true, write: true }, function renameSyncSuccess() { +testPerm({ read: true, write: true }, function renameSyncSuccess(): void { const testDir = Deno.makeTempDirSync(); const oldpath = testDir + "/oldpath"; const newpath = testDir + "/newpath"; @@ -23,7 +23,7 @@ testPerm({ read: true, write: true }, function renameSyncSuccess() { assertEquals(oldPathInfo, undefined); }); -testPerm({ read: true, write: false }, function renameSyncPerm() { +testPerm({ read: true, write: false }, function renameSyncPerm(): void { let err; try { const oldpath = "/oldbaddir"; @@ -36,7 +36,9 @@ testPerm({ read: true, write: false }, function renameSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ read: true, write: true }, async function renameSuccess() { +testPerm({ read: true, write: true }, async function renameSuccess(): Promise< + void +> { const testDir = Deno.makeTempDirSync(); const oldpath = testDir + "/oldpath"; const newpath = testDir + "/newpath"; diff --git a/js/repl.ts b/js/repl.ts index e521bf581..be162cb7e 100644 --- a/js/repl.ts +++ b/js/repl.ts @@ -16,12 +16,12 @@ const helpMsg = [ const replCommands = { exit: { - get() { + get(): void { exit(0); } }, help: { - get() { + get(): string { return helpMsg; } } diff --git a/js/resources_test.ts b/js/resources_test.ts index eeb3b3449..9d68f49f6 100644 --- a/js/resources_test.ts +++ b/js/resources_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assertEquals } from "./test_util.ts"; -test(function resourcesStdio() { +test(function resourcesStdio(): void { const res = Deno.resources(); assertEquals(res[0], "stdin"); @@ -9,7 +9,7 @@ test(function resourcesStdio() { assertEquals(res[2], "stderr"); }); -testPerm({ net: true }, async function resourcesNet() { +testPerm({ net: true }, async function resourcesNet(): Promise<void> { const addr = "127.0.0.1:4501"; const listener = Deno.listen("tcp", addr); @@ -17,15 +17,21 @@ testPerm({ net: true }, async function resourcesNet() { const listenerConn = await listener.accept(); const res = Deno.resources(); - assertEquals(Object.values(res).filter(r => r === "tcpListener").length, 1); - assertEquals(Object.values(res).filter(r => r === "tcpStream").length, 2); + assertEquals( + Object.values(res).filter((r): boolean => r === "tcpListener").length, + 1 + ); + assertEquals( + Object.values(res).filter((r): boolean => r === "tcpStream").length, + 2 + ); listenerConn.close(); dialerConn.close(); listener.close(); }); -testPerm({ read: true }, async function resourcesFile() { +testPerm({ read: true }, async function resourcesFile(): Promise<void> { const resourcesBefore = Deno.resources(); await Deno.open("tests/hello.txt"); const resourcesAfter = Deno.resources(); @@ -35,8 +41,10 @@ testPerm({ read: true }, async function resourcesFile() { Object.keys(resourcesAfter).length, Object.keys(resourcesBefore).length + 1 ); - const newRid = Object.keys(resourcesAfter).find(rid => { - return !resourcesBefore.hasOwnProperty(rid); - }); + const newRid = Object.keys(resourcesAfter).find( + (rid): boolean => { + return !resourcesBefore.hasOwnProperty(rid); + } + ); assertEquals(resourcesAfter[newRid], "fsFile"); }); diff --git a/js/stat_test.ts b/js/stat_test.ts index ae6477d79..50ee6c9d3 100644 --- a/js/stat_test.ts +++ b/js/stat_test.ts @@ -3,7 +3,7 @@ import { testPerm, assert, assertEquals } from "./test_util.ts"; // TODO Add tests for modified, accessed, and created fields once there is a way // to create temp files. -testPerm({ read: true }, async function statSyncSuccess() { +testPerm({ read: true }, async function statSyncSuccess(): Promise<void> { const packageInfo = Deno.statSync("package.json"); assert(packageInfo.isFile()); assert(!packageInfo.isSymlink()); @@ -17,7 +17,7 @@ testPerm({ read: true }, async function statSyncSuccess() { assert(!testsInfo.isSymlink()); }); -testPerm({ read: false }, async function statSyncPerm() { +testPerm({ read: false }, async function statSyncPerm(): Promise<void> { let caughtError = false; try { Deno.statSync("package.json"); @@ -29,7 +29,7 @@ testPerm({ read: false }, async function statSyncPerm() { assert(caughtError); }); -testPerm({ read: true }, async function statSyncNotFound() { +testPerm({ read: true }, async function statSyncNotFound(): Promise<void> { let caughtError = false; let badInfo; @@ -45,7 +45,7 @@ testPerm({ read: true }, async function statSyncNotFound() { assertEquals(badInfo, undefined); }); -testPerm({ read: true }, async function lstatSyncSuccess() { +testPerm({ read: true }, async function lstatSyncSuccess(): Promise<void> { const packageInfo = Deno.lstatSync("package.json"); assert(packageInfo.isFile()); assert(!packageInfo.isSymlink()); @@ -59,7 +59,7 @@ testPerm({ read: true }, async function lstatSyncSuccess() { assert(!testsInfo.isSymlink()); }); -testPerm({ read: false }, async function lstatSyncPerm() { +testPerm({ read: false }, async function lstatSyncPerm(): Promise<void> { let caughtError = false; try { Deno.lstatSync("package.json"); @@ -71,7 +71,7 @@ testPerm({ read: false }, async function lstatSyncPerm() { assert(caughtError); }); -testPerm({ read: true }, async function lstatSyncNotFound() { +testPerm({ read: true }, async function lstatSyncNotFound(): Promise<void> { let caughtError = false; let badInfo; @@ -87,7 +87,7 @@ testPerm({ read: true }, async function lstatSyncNotFound() { assertEquals(badInfo, undefined); }); -testPerm({ read: true }, async function statSuccess() { +testPerm({ read: true }, async function statSuccess(): Promise<void> { const packageInfo = await Deno.stat("package.json"); assert(packageInfo.isFile()); assert(!packageInfo.isSymlink()); @@ -101,7 +101,7 @@ testPerm({ read: true }, async function statSuccess() { assert(!testsInfo.isSymlink()); }); -testPerm({ read: false }, async function statPerm() { +testPerm({ read: false }, async function statPerm(): Promise<void> { let caughtError = false; try { await Deno.stat("package.json"); @@ -113,7 +113,7 @@ testPerm({ read: false }, async function statPerm() { assert(caughtError); }); -testPerm({ read: true }, async function statNotFound() { +testPerm({ read: true }, async function statNotFound(): Promise<void> { let caughtError = false; let badInfo; @@ -129,7 +129,7 @@ testPerm({ read: true }, async function statNotFound() { assertEquals(badInfo, undefined); }); -testPerm({ read: true }, async function lstatSuccess() { +testPerm({ read: true }, async function lstatSuccess(): Promise<void> { const packageInfo = await Deno.lstat("package.json"); assert(packageInfo.isFile()); assert(!packageInfo.isSymlink()); @@ -143,7 +143,7 @@ testPerm({ read: true }, async function lstatSuccess() { assert(!testsInfo.isSymlink()); }); -testPerm({ read: false }, async function lstatPerm() { +testPerm({ read: false }, async function lstatPerm(): Promise<void> { let caughtError = false; try { await Deno.lstat("package.json"); @@ -155,7 +155,7 @@ testPerm({ read: false }, async function lstatPerm() { assert(caughtError); }); -testPerm({ read: true }, async function lstatNotFound() { +testPerm({ read: true }, async function lstatNotFound(): Promise<void> { let caughtError = false; let badInfo; diff --git a/js/symlink_test.ts b/js/symlink_test.ts index 37b157294..ae9b0c8cc 100644 --- a/js/symlink_test.ts +++ b/js/symlink_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ read: true, write: true }, function symlinkSyncSuccess() { +testPerm({ read: true, write: true }, function symlinkSyncSuccess(): void { const testDir = Deno.makeTempDirSync(); const oldname = testDir + "/oldname"; const newname = testDir + "/newname"; @@ -24,7 +24,7 @@ testPerm({ read: true, write: true }, function symlinkSyncSuccess() { } }); -test(function symlinkSyncPerm() { +test(function symlinkSyncPerm(): void { let err; try { Deno.symlinkSync("oldbaddir", "newbaddir"); @@ -36,7 +36,7 @@ test(function symlinkSyncPerm() { }); // Just for now, until we implement symlink for Windows. -testPerm({ write: true }, function symlinkSyncNotImplemented() { +testPerm({ write: true }, function symlinkSyncNotImplemented(): void { let err; try { Deno.symlinkSync("oldname", "newname", "dir"); @@ -46,7 +46,9 @@ testPerm({ write: true }, function symlinkSyncNotImplemented() { assertEquals(err.message, "Not implemented"); }); -testPerm({ read: true, write: true }, async function symlinkSuccess() { +testPerm({ read: true, write: true }, async function symlinkSuccess(): Promise< + void +> { const testDir = Deno.makeTempDirSync(); const oldname = testDir + "/oldname"; const newname = testDir + "/newname"; diff --git a/js/test_util.ts b/js/test_util.ts index 413b287a1..9608c31a9 100644 --- a/js/test_util.ts +++ b/js/test_util.ts @@ -77,7 +77,7 @@ export function test(fn: testing.TestFunction): void { ); } -test(function permSerialization() { +test(function permSerialization(): void { for (const write of [true, false]) { for (const net of [true, false]) { for (const env of [true, false]) { @@ -103,7 +103,7 @@ test(function permSerialization() { // To better catch internal errors, permFromString should throw if it gets an // invalid permission string. -test(function permFromStringThrows() { +test(function permFromStringThrows(): void { let threw = false; try { permFromString("bad"); diff --git a/js/text_encoding.ts b/js/text_encoding.ts index a1f9d6bff..883451631 100644 --- a/js/text_encoding.ts +++ b/js/text_encoding.ts @@ -289,18 +289,24 @@ for (const key of Object.keys(encodingMap)) { // A map of functions that return new instances of a decoder indexed by the // encoding type. const decoders = new Map<string, (options: DecoderOptions) => Decoder>(); -decoders.set("utf-8", (options: DecoderOptions) => { - return new UTF8Decoder(options); -}); +decoders.set( + "utf-8", + (options: DecoderOptions): UTF8Decoder => { + return new UTF8Decoder(options); + } +); // Single byte decoders are an array of code point lookups 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]); for (const [key, index] of encodingIndexes) { - decoders.set(key, (options: DecoderOptions) => { - return new SingleByteDecoder(index, options); - }); + decoders.set( + key, + (options: DecoderOptions): SingleByteDecoder => { + return new SingleByteDecoder(index, options); + } + ); } function codePointsToString(codePoints: number[]): string { diff --git a/js/text_encoding_test.ts b/js/text_encoding_test.ts index d33537b4f..f015a9452 100644 --- a/js/text_encoding_test.ts +++ b/js/text_encoding_test.ts @@ -1,19 +1,19 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEquals } from "./test_util.ts"; -test(function atobSuccess() { +test(function atobSuccess(): void { const text = "hello world"; const encoded = btoa(text); assertEquals(encoded, "aGVsbG8gd29ybGQ="); }); -test(function btoaSuccess() { +test(function btoaSuccess(): void { const encoded = "aGVsbG8gd29ybGQ="; const decoded = atob(encoded); assertEquals(decoded, "hello world"); }); -test(function btoaFailed() { +test(function btoaFailed(): void { const text = "你好"; let err; try { @@ -25,7 +25,7 @@ test(function btoaFailed() { assertEquals(err.name, "InvalidInput"); }); -test(function textDecoder2() { +test(function textDecoder2(): void { // prettier-ignore const fixture = new Uint8Array([ 0xf0, 0x9d, 0x93, 0xbd, @@ -37,13 +37,13 @@ test(function textDecoder2() { assertEquals(decoder.decode(fixture), "𝓽𝓮𝔁𝓽"); }); -test(function textDecoderASCII() { +test(function textDecoderASCII(): void { const fixture = new Uint8Array([0x89, 0x95, 0x9f, 0xbf]); const decoder = new TextDecoder("ascii"); assertEquals(decoder.decode(fixture), "‰•Ÿ¿"); }); -test(function textDecoderErrorEncoding() { +test(function textDecoderErrorEncoding(): void { let didThrow = false; try { new TextDecoder("foo"); @@ -54,7 +54,7 @@ test(function textDecoderErrorEncoding() { assert(didThrow); }); -test(function textEncoder2() { +test(function textEncoder2(): void { const fixture = "𝓽𝓮𝔁𝓽"; const encoder = new TextEncoder(); // prettier-ignore @@ -66,7 +66,7 @@ test(function textEncoder2() { ]); }); -test(function textDecoderSharedUint8Array() { +test(function textDecoderSharedUint8Array(): void { const ab = new SharedArrayBuffer(6); const dataView = new DataView(ab); const charCodeA = "A".charCodeAt(0); @@ -79,7 +79,7 @@ test(function textDecoderSharedUint8Array() { assertEquals(actual, "ABCDEF"); }); -test(function textDecoderSharedInt32Array() { +test(function textDecoderSharedInt32Array(): void { const ab = new SharedArrayBuffer(8); const dataView = new DataView(ab); const charCodeA = "A".charCodeAt(0); @@ -92,7 +92,7 @@ test(function textDecoderSharedInt32Array() { assertEquals(actual, "ABCDEFGH"); }); -test(function toStringShouldBeWebCompatibility() { +test(function toStringShouldBeWebCompatibility(): void { const encoder = new TextEncoder(); assertEquals(encoder.toString(), "[object TextEncoder]"); diff --git a/js/timers_test.ts b/js/timers_test.ts index 51dfbd7e0..7769be010 100644 --- a/js/timers_test.ts +++ b/js/timers_test.ts @@ -9,10 +9,12 @@ function deferred(): { } { let resolve; let reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); + const promise = new Promise( + (res, rej): void => { + resolve = res; + reject = rej; + } + ); return { promise, resolve, @@ -21,13 +23,13 @@ function deferred(): { } async function waitForMs(ms): Promise<number> { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve): number => setTimeout(resolve, ms)); } -test(async function timeoutSuccess() { +test(async function timeoutSuccess(): Promise<void> { const { promise, resolve } = deferred(); let count = 0; - setTimeout(() => { + setTimeout((): void => { count++; resolve(); }, 500); @@ -36,11 +38,11 @@ test(async function timeoutSuccess() { assertEquals(count, 1); }); -test(async function timeoutArgs() { +test(async function timeoutArgs(): Promise<void> { const { promise, resolve } = deferred(); const arg = 1; setTimeout( - (a, b, c) => { + (a, b, c): void => { assertEquals(a, arg); assertEquals(b, arg.toString()); assertEquals(c, [arg]); @@ -54,9 +56,9 @@ test(async function timeoutArgs() { await promise; }); -test(async function timeoutCancelSuccess() { +test(async function timeoutCancelSuccess(): Promise<void> { let count = 0; - const id = setTimeout(() => { + const id = setTimeout((): void => { count++; }, 1); // Cancelled, count should not increment @@ -65,7 +67,7 @@ test(async function timeoutCancelSuccess() { assertEquals(count, 0); }); -test(async function timeoutCancelMultiple() { +test(async function timeoutCancelMultiple(): Promise<void> { function uncalled(): never { throw new Error("This function should not be called."); } @@ -90,11 +92,11 @@ test(async function timeoutCancelMultiple() { await waitForMs(50); }); -test(async function timeoutCancelInvalidSilentFail() { +test(async function timeoutCancelInvalidSilentFail(): Promise<void> { // Expect no panic const { promise, resolve } = deferred(); let count = 0; - const id = setTimeout(() => { + const id = setTimeout((): void => { count++; // Should have no effect clearTimeout(id); @@ -107,10 +109,10 @@ test(async function timeoutCancelInvalidSilentFail() { clearTimeout(2147483647); }); -test(async function intervalSuccess() { +test(async function intervalSuccess(): Promise<void> { const { promise, resolve } = deferred(); let count = 0; - const id = setInterval(() => { + const id = setInterval((): void => { count++; clearInterval(id); resolve(); @@ -122,9 +124,9 @@ test(async function intervalSuccess() { assertEquals(count, 1); }); -test(async function intervalCancelSuccess() { +test(async function intervalCancelSuccess(): Promise<void> { let count = 0; - const id = setInterval(() => { + const id = setInterval((): void => { count++; }, 1); clearInterval(id); @@ -132,7 +134,7 @@ test(async function intervalCancelSuccess() { assertEquals(count, 0); }); -test(async function intervalOrdering() { +test(async function intervalOrdering(): Promise<void> { const timers = []; let timeouts = 0; function onTimeout(): void { @@ -148,14 +150,16 @@ test(async function intervalOrdering() { assertEquals(timeouts, 1); }); -test(async function intervalCancelInvalidSilentFail() { +test(async function intervalCancelInvalidSilentFail(): Promise<void> { // Should silently fail (no panic) clearInterval(2147483647); }); -test(async function fireCallbackImmediatelyWhenDelayOverMaxValue() { +test(async function fireCallbackImmediatelyWhenDelayOverMaxValue(): Promise< + void +> { let count = 0; - setTimeout(() => { + setTimeout((): void => { count++; }, 2 ** 31); await waitForMs(1); diff --git a/js/truncate_test.ts b/js/truncate_test.ts index 09830c073..055db8652 100644 --- a/js/truncate_test.ts +++ b/js/truncate_test.ts @@ -15,7 +15,7 @@ async function readData(name: string): Promise<string> { return text; } -testPerm({ read: true, write: true }, function truncateSyncSuccess() { +testPerm({ read: true, write: true }, function truncateSyncSuccess(): void { const enc = new TextEncoder(); const d = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test_truncateSync.txt"; @@ -32,7 +32,9 @@ testPerm({ read: true, write: true }, function truncateSyncSuccess() { Deno.removeSync(filename); }); -testPerm({ read: true, write: true }, async function truncateSuccess() { +testPerm({ read: true, write: true }, async function truncateSuccess(): Promise< + void +> { const enc = new TextEncoder(); const d = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test_truncate.txt"; @@ -49,7 +51,7 @@ testPerm({ read: true, write: true }, async function truncateSuccess() { await Deno.remove(filename); }); -testPerm({ write: false }, function truncateSyncPerm() { +testPerm({ write: false }, function truncateSyncPerm(): void { let err; try { Deno.mkdirSync("/test_truncateSyncPermission.txt"); @@ -60,7 +62,7 @@ testPerm({ write: false }, function truncateSyncPerm() { assertEquals(err.name, "PermissionDenied"); }); -testPerm({ write: false }, async function truncatePerm() { +testPerm({ write: false }, async function truncatePerm(): Promise<void> { let err; try { await Deno.mkdir("/test_truncatePermission.txt"); @@ -73,7 +73,7 @@ export class URL { for (const methodName of searchParamsMethods) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const method: (...args: any[]) => any = searchParams[methodName]; - searchParams[methodName] = (...args: unknown[]) => { + searchParams[methodName] = (...args: unknown[]): void => { method.apply(searchParams, args); this.search = searchParams.toString(); }; diff --git a/js/url_search_params.ts b/js/url_search_params.ts index aef2f2c50..8a6d143e4 100644 --- a/js/url_search_params.ts +++ b/js/url_search_params.ts @@ -112,7 +112,7 @@ export class URLSearchParams { has(name: string): boolean { requiredArguments("URLSearchParams.has", arguments.length, 1); name = String(name); - return this.params.some(entry => entry[0] === name); + return this.params.some((entry): boolean => entry[0] === name); } /** Sets the value associated with a given search parameter to the @@ -159,8 +159,8 @@ export class URLSearchParams { * searchParams.sort(); */ sort(): void { - this.params = this.params.sort((a, b) => - a[0] === b[0] ? 0 : a[0] > b[0] ? 1 : -1 + this.params = this.params.sort( + (a, b): number => (a[0] === b[0] ? 0 : a[0] > b[0] ? 1 : -1) ); } @@ -244,7 +244,7 @@ export class URLSearchParams { toString(): string { return this.params .map( - tuple => + (tuple): string => `${encodeURIComponent(tuple[0])}=${encodeURIComponent(tuple[1])}` ) .join("&"); diff --git a/js/url_search_params_test.ts b/js/url_search_params_test.ts index b93e4f4b0..9b20b3b75 100644 --- a/js/url_search_params_test.ts +++ b/js/url_search_params_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEquals } from "./test_util.ts"; -test(function urlSearchParamsInitString() { +test(function urlSearchParamsInitString(): void { const init = "c=4&a=2&b=3&%C3%A1=1"; const searchParams = new URLSearchParams(init); assert( @@ -10,32 +10,32 @@ test(function urlSearchParamsInitString() { ); }); -test(function urlSearchParamsInitIterable() { +test(function urlSearchParamsInitIterable(): void { const init = [["a", "54"], ["b", "true"]]; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "a=54&b=true"); }); -test(function urlSearchParamsInitRecord() { +test(function urlSearchParamsInitRecord(): void { const init = { a: "54", b: "true" }; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "a=54&b=true"); }); -test(function urlSearchParamsAppendSuccess() { +test(function urlSearchParamsAppendSuccess(): void { const searchParams = new URLSearchParams(); searchParams.append("a", "true"); assertEquals(searchParams.toString(), "a=true"); }); -test(function urlSearchParamsDeleteSuccess() { +test(function urlSearchParamsDeleteSuccess(): void { const init = "a=54&b=true"; const searchParams = new URLSearchParams(init); searchParams.delete("b"); assertEquals(searchParams.toString(), "a=54"); }); -test(function urlSearchParamsGetAllSuccess() { +test(function urlSearchParamsGetAllSuccess(): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.getAll("a"), ["54", "true"]); @@ -43,7 +43,7 @@ test(function urlSearchParamsGetAllSuccess() { assertEquals(searchParams.getAll("c"), []); }); -test(function urlSearchParamsGetSuccess() { +test(function urlSearchParamsGetSuccess(): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("a"), "54"); @@ -51,7 +51,7 @@ test(function urlSearchParamsGetSuccess() { assertEquals(searchParams.get("c"), null); }); -test(function urlSearchParamsHasSuccess() { +test(function urlSearchParamsHasSuccess(): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); assert(searchParams.has("a")); @@ -59,62 +59,64 @@ test(function urlSearchParamsHasSuccess() { assert(!searchParams.has("c")); }); -test(function urlSearchParamsSetReplaceFirstAndRemoveOthers() { +test(function urlSearchParamsSetReplaceFirstAndRemoveOthers(): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); searchParams.set("a", "false"); assertEquals(searchParams.toString(), "a=false&b=true"); }); -test(function urlSearchParamsSetAppendNew() { +test(function urlSearchParamsSetAppendNew(): void { const init = "a=54&b=true&a=true"; const searchParams = new URLSearchParams(init); searchParams.set("c", "foo"); assertEquals(searchParams.toString(), "a=54&b=true&a=true&c=foo"); }); -test(function urlSearchParamsSortSuccess() { +test(function urlSearchParamsSortSuccess(): void { const init = "c=4&a=2&b=3&a=1"; const searchParams = new URLSearchParams(init); searchParams.sort(); assertEquals(searchParams.toString(), "a=2&a=1&b=3&c=4"); }); -test(function urlSearchParamsForEachSuccess() { +test(function urlSearchParamsForEachSuccess(): void { const init = [["a", "54"], ["b", "true"]]; const searchParams = new URLSearchParams(init); let callNum = 0; - searchParams.forEach((value, key, parent) => { - assertEquals(searchParams, parent); - assertEquals(value, init[callNum][1]); - assertEquals(key, init[callNum][0]); - callNum++; - }); + searchParams.forEach( + (value, key, parent): void => { + assertEquals(searchParams, parent); + assertEquals(value, init[callNum][1]); + assertEquals(key, init[callNum][0]); + callNum++; + } + ); assertEquals(callNum, init.length); }); -test(function urlSearchParamsMissingName() { +test(function urlSearchParamsMissingName(): void { const init = "=4"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get(""), "4"); assertEquals(searchParams.toString(), "=4"); }); -test(function urlSearchParamsMissingValue() { +test(function urlSearchParamsMissingValue(): void { const init = "4="; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("4"), ""); assertEquals(searchParams.toString(), "4="); }); -test(function urlSearchParamsMissingEqualSign() { +test(function urlSearchParamsMissingEqualSign(): void { const init = "4"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.get("4"), ""); assertEquals(searchParams.toString(), "4="); }); -test(function urlSearchParamsMissingPair() { +test(function urlSearchParamsMissingPair(): void { const init = "c=4&&a=54&"; const searchParams = new URLSearchParams(init); assertEquals(searchParams.toString(), "c=4&a=54"); @@ -122,7 +124,7 @@ test(function urlSearchParamsMissingPair() { // If pair does not contain exactly two items, then throw a TypeError. // ref https://url.spec.whatwg.org/#interface-urlsearchparams -test(function urlSearchParamsShouldThrowTypeError() { +test(function urlSearchParamsShouldThrowTypeError(): void { let hasThrown = 0; try { @@ -139,40 +141,44 @@ test(function urlSearchParamsShouldThrowTypeError() { assertEquals(hasThrown, 2); }); -test(function urlSearchParamsAppendArgumentsCheck() { +test(function urlSearchParamsAppendArgumentsCheck(): void { const methodRequireOneParam = ["delete", "getAll", "get", "has", "forEach"]; const methodRequireTwoParams = ["append", "set"]; - methodRequireOneParam.concat(methodRequireTwoParams).forEach(method => { - const searchParams = new URLSearchParams(); - let hasThrown = 0; - try { - searchParams[method](); - hasThrown = 1; - } catch (err) { - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + methodRequireOneParam.concat(methodRequireTwoParams).forEach( + (method: string): void => { + const searchParams = new URLSearchParams(); + let hasThrown = 0; + try { + searchParams[method](); + hasThrown = 1; + } catch (err) { + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } + assertEquals(hasThrown, 2); } - assertEquals(hasThrown, 2); - }); - - methodRequireTwoParams.forEach(method => { - const searchParams = new URLSearchParams(); - let hasThrown = 0; - try { - searchParams[method]("foo"); - hasThrown = 1; - } catch (err) { - if (err instanceof TypeError) { - hasThrown = 2; - } else { - hasThrown = 3; + ); + + methodRequireTwoParams.forEach( + (method: string): void => { + const searchParams = new URLSearchParams(); + let hasThrown = 0; + try { + searchParams[method]("foo"); + hasThrown = 1; + } catch (err) { + if (err instanceof TypeError) { + hasThrown = 2; + } else { + hasThrown = 3; + } } + assertEquals(hasThrown, 2); } - assertEquals(hasThrown, 2); - }); + ); }); diff --git a/js/url_test.ts b/js/url_test.ts index 643490e45..5744aa568 100644 --- a/js/url_test.ts +++ b/js/url_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { test, assert, assertEquals } from "./test_util.ts"; -test(function urlParsing() { +test(function urlParsing(): void { const url = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" ); @@ -31,7 +31,7 @@ test(function urlParsing() { ); }); -test(function urlModifications() { +test(function urlModifications(): void { const url = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" ); @@ -86,7 +86,7 @@ test(function urlModifications() { ); }); -test(function urlModifyHref() { +test(function urlModifyHref(): void { const url = new URL("http://example.com/"); url.href = "https://foo:bar@example.com:8080/baz/qat#qux"; assertEquals(url.protocol, "https:"); @@ -98,7 +98,7 @@ test(function urlModifyHref() { assertEquals(url.hash, "#qux"); }); -test(function urlModifyPathname() { +test(function urlModifyPathname(): void { const url = new URL("http://foo.bar/baz%qat/qux%quux"); assertEquals(url.pathname, "/baz%qat/qux%quux"); url.pathname = url.pathname; @@ -109,7 +109,7 @@ test(function urlModifyPathname() { assertEquals(url.pathname, "/baz%23qat%20qux"); }); -test(function urlModifyHash() { +test(function urlModifyHash(): void { const url = new URL("http://foo.bar"); url.hash = "%foo bar/qat%qux#bar"; assertEquals(url.hash, "#%foo%20bar/qat%qux#bar"); @@ -117,7 +117,7 @@ test(function urlModifyHash() { assertEquals(url.hash, "#%foo%20bar/qat%qux#bar"); }); -test(function urlSearchParamsReuse() { +test(function urlSearchParamsReuse(): void { const url = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" ); @@ -126,7 +126,7 @@ test(function urlSearchParamsReuse() { assert(sp === url.searchParams, "Search params should be reused."); }); -test(function urlBaseURL() { +test(function urlBaseURL(): void { const base = new URL( "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" ); @@ -134,7 +134,7 @@ test(function urlBaseURL() { assertEquals(url.href, "https://foo:bar@baz.qat:8000/foo/bar?baz=foo#qux"); }); -test(function urlBaseString() { +test(function urlBaseString(): void { const url = new URL( "/foo/bar?baz=foo#qux", "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" diff --git a/js/util.ts b/js/util.ts index 348e36a1f..033a2f754 100644 --- a/js/util.ts +++ b/js/util.ts @@ -71,9 +71,11 @@ export type Resolvable<T> = Promise<T> & ResolvableMethods<T>; // @internal export function createResolvable<T>(): Resolvable<T> { let methods: ResolvableMethods<T>; - const promise = new Promise<T>((resolve, reject) => { - methods = { resolve, reject }; - }); + const promise = new Promise<T>( + (resolve, reject): void => { + methods = { resolve, reject }; + } + ); // TypeScript doesn't know that the Promise callback occurs synchronously // therefore use of not null assertion (`!`) return Object.assign(promise, methods!) as Resolvable<T>; @@ -92,9 +94,12 @@ export function unreachable(): never { // @internal export function hexdump(u8: Uint8Array): string { return Array.prototype.map - .call(u8, (x: number) => { - return ("00" + x.toString(16)).slice(-2); - }) + .call( + u8, + (x: number): string => { + return ("00" + x.toString(16)).slice(-2); + } + ) .join(" "); } diff --git a/js/version_test.ts b/js/version_test.ts index d3d1bc3df..7cc7bd404 100644 --- a/js/version_test.ts +++ b/js/version_test.ts @@ -1,6 +1,6 @@ import { test, assert } from "./test_util.ts"; -test(function version() { +test(function version(): void { const pattern = /^\d+\.\d+\.\d+$/; assert(pattern.test(Deno.version.deno)); assert(pattern.test(Deno.version.v8)); diff --git a/js/workers.ts b/js/workers.ts index 456449d48..1531b960b 100644 --- a/js/workers.ts +++ b/js/workers.ts @@ -161,9 +161,11 @@ export class WorkerImpl implements Worker { this.rid = createWorker(specifier); this.run(); this.isClosedPromise = hostGetWorkerClosed(this.rid); - this.isClosedPromise.then(() => { - this.isClosing = true; - }); + this.isClosedPromise.then( + (): void => { + this.isClosing = true; + } + ); } get closed(): Promise<void> { diff --git a/js/write_file_test.ts b/js/write_file_test.ts index 07f8dca7a..e1bbb67b3 100644 --- a/js/write_file_test.ts +++ b/js/write_file_test.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. import { testPerm, assert, assertEquals } from "./test_util.ts"; -testPerm({ read: true, write: true }, function writeFileSyncSuccess() { +testPerm({ read: true, write: true }, function writeFileSyncSuccess(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; @@ -12,7 +12,7 @@ testPerm({ read: true, write: true }, function writeFileSyncSuccess() { assertEquals("Hello", actual); }); -testPerm({ write: true }, function writeFileSyncFail() { +testPerm({ write: true }, function writeFileSyncFail(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = "/baddir/test.txt"; @@ -28,7 +28,7 @@ testPerm({ write: true }, function writeFileSyncFail() { assert(caughtError); }); -testPerm({ write: false }, function writeFileSyncPerm() { +testPerm({ write: false }, function writeFileSyncPerm(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = "/baddir/test.txt"; @@ -44,7 +44,7 @@ testPerm({ write: false }, function writeFileSyncPerm() { assert(caughtError); }); -testPerm({ read: true, write: true }, function writeFileSyncUpdatePerm() { +testPerm({ read: true, write: true }, function writeFileSyncUpdatePerm(): void { if (Deno.build.os !== "win") { const enc = new TextEncoder(); const data = enc.encode("Hello"); @@ -56,7 +56,7 @@ testPerm({ read: true, write: true }, function writeFileSyncUpdatePerm() { } }); -testPerm({ read: true, write: true }, function writeFileSyncCreate() { +testPerm({ read: true, write: true }, function writeFileSyncCreate(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; @@ -80,7 +80,7 @@ testPerm({ read: true, write: true }, function writeFileSyncCreate() { assertEquals("Hello", actual); }); -testPerm({ read: true, write: true }, function writeFileSyncAppend() { +testPerm({ read: true, write: true }, function writeFileSyncAppend(): void { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; @@ -102,34 +102,42 @@ testPerm({ read: true, write: true }, function writeFileSyncAppend() { assertEquals("Hello", actual); }); -testPerm({ read: true, write: true }, async function writeFileSuccess() { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = Deno.makeTempDirSync() + "/test.txt"; - await Deno.writeFile(filename, data); - const dataRead = Deno.readFileSync(filename); - const dec = new TextDecoder("utf-8"); - const actual = dec.decode(dataRead); - assertEquals("Hello", actual); -}); - -testPerm({ read: true, write: true }, async function writeFileNotFound() { - const enc = new TextEncoder(); - const data = enc.encode("Hello"); - const filename = "/baddir/test.txt"; - // The following should fail because /baddir doesn't exist (hopefully). - let caughtError = false; - try { +testPerm( + { read: true, write: true }, + async function writeFileSuccess(): Promise<void> { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = Deno.makeTempDirSync() + "/test.txt"; await Deno.writeFile(filename, data); - } catch (e) { - caughtError = true; - assertEquals(e.kind, Deno.ErrorKind.NotFound); - assertEquals(e.name, "NotFound"); + const dataRead = Deno.readFileSync(filename); + const dec = new TextDecoder("utf-8"); + const actual = dec.decode(dataRead); + assertEquals("Hello", actual); } - assert(caughtError); -}); +); + +testPerm( + { read: true, write: true }, + async function writeFileNotFound(): Promise<void> { + const enc = new TextEncoder(); + const data = enc.encode("Hello"); + const filename = "/baddir/test.txt"; + // The following should fail because /baddir doesn't exist (hopefully). + let caughtError = false; + try { + await Deno.writeFile(filename, data); + } catch (e) { + caughtError = true; + assertEquals(e.kind, Deno.ErrorKind.NotFound); + assertEquals(e.name, "NotFound"); + } + assert(caughtError); + } +); -testPerm({ read: true, write: false }, async function writeFilePerm() { +testPerm({ read: true, write: false }, async function writeFilePerm(): Promise< + void +> { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = "/baddir/test.txt"; @@ -145,19 +153,24 @@ testPerm({ read: true, write: false }, async function writeFilePerm() { assert(caughtError); }); -testPerm({ read: true, write: true }, async function writeFileUpdatePerm() { - if (Deno.build.os !== "win") { - const enc = new TextEncoder(); - 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); - await Deno.writeFile(filename, data, { perm: 0o666 }); - assertEquals(Deno.statSync(filename).mode & 0o777, 0o666); +testPerm( + { read: true, write: true }, + async function writeFileUpdatePerm(): Promise<void> { + if (Deno.build.os !== "win") { + const enc = new TextEncoder(); + 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); + await Deno.writeFile(filename, data, { perm: 0o666 }); + assertEquals(Deno.statSync(filename).mode & 0o777, 0o666); + } } -}); +); -testPerm({ read: true, write: true }, async function writeFileCreate() { +testPerm({ read: true, write: true }, async function writeFileCreate(): Promise< + void +> { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; @@ -181,7 +194,9 @@ testPerm({ read: true, write: true }, async function writeFileCreate() { assertEquals("Hello", actual); }); -testPerm({ read: true, write: true }, async function writeFileAppend() { +testPerm({ read: true, write: true }, async function writeFileAppend(): Promise< + void +> { const enc = new TextEncoder(); const data = enc.encode("Hello"); const filename = Deno.makeTempDirSync() + "/test.txt"; |