diff --git a/.ci/template.linux.yml b/.ci/template.linux.yml index 7dd12819da..7e87e21a3f 100644 --- a/.ci/template.linux.yml +++ b/.ci/template.linux.yml @@ -1,5 +1,5 @@ steps: - - bash: npm install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier + - bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier - template: ./template.unix.yml - - bash: npx eslint **/*.ts --max-warnings=0 + - bash: npx eslint "**/*.ts" --max-warnings=0 - template: ./template.common.yml diff --git a/.ci/template.mac.yml b/.ci/template.mac.yml index 1f0481a9ea..f93f5d2a0d 100644 --- a/.ci/template.mac.yml +++ b/.ci/template.mac.yml @@ -1,6 +1,8 @@ steps: - - bash: npm install -g functional-red-black-tree - - bash: npm -g install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier + - task: NodeTool@0 + inputs: + versionSpec: '10.x' + - bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier - template: ./template.unix.yml - - bash: eslint **/*.ts --max-warnings=0 + - bash: npx eslint "**/*.ts" --max-warnings=0 - template: ./template.common.yml diff --git a/.ci/template.windows.yml b/.ci/template.windows.yml index fe5cc85a4e..3b23abe927 100644 --- a/.ci/template.windows.yml +++ b/.ci/template.windows.yml @@ -1,8 +1,8 @@ steps: - - bash: npm install eslint@5.16.0 typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@1.13.0 @typescript-eslint/parser@1.13.0 eslint-config-prettier + - bash: npm install eslint@$(ESLINT_VERSION) typescript@$(TS_VERSION) @typescript-eslint/eslint-plugin@$(TS_ESLINT_VERSION) @typescript-eslint/parser@$(TS_ESLINT_VERSION) eslint-config-prettier - powershell: iwr https://deno.land/x/install/install.ps1 -out install.ps1; .\install.ps1 $(DENO_VERSION) - bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin" - - bash: npx eslint **/*.ts --max-warnings=0 + - bash: npx eslint "**/*.ts" --max-warnings=0 - template: ./template.common.yml parameters: - exe_suffix: ".exe" \ No newline at end of file + exe_suffix: ".exe" diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000000..0bbb027f10 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +/deno.d.ts +/prettier/vendor +**/testdata/ + diff --git a/.eslintrc.json b/.eslintrc.json index 90775af9d9..b1e59a4e9a 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -2,7 +2,8 @@ "root": true, "parser": "@typescript-eslint/parser", "parserOptions": { - "project": "./tsconfig.json" + "project": "./tsconfig.json", + "createDefaultProgram": true }, "plugins": ["@typescript-eslint"], "extends": [ @@ -11,7 +12,7 @@ "prettier/@typescript-eslint" ], "rules": { - "@typescript-eslint/array-type": ["error", "array-simple"], + "@typescript-eslint/array-type": ["error", { "default": "array-simple" }], "@typescript-eslint/explicit-member-accessibility": ["off"], "@typescript-eslint/no-non-null-assertion": ["off"], "@typescript-eslint/no-parameter-properties": ["off"], @@ -19,6 +20,8 @@ "error", { "argsIgnorePattern": "^_", "varsIgnorePattern": "_" } ], + "@typescript-eslint/ban-ts-ignore": ["off"], + "@typescript-eslint/no-empty-function": ["off"], "max-len": [ "error", { diff --git a/archive/tar.ts b/archive/tar.ts index df24a291c4..8ebfa7fb5a 100644 --- a/archive/tar.ts +++ b/archive/tar.ts @@ -96,7 +96,7 @@ function clean(length: number): Uint8Array { } function pad(num: number, bytes: number, base?: number): string { - var numString = num.toString(base || 8); + const numString = num.toString(base || 8); return "000000000000".substr(numString.length + 12 - bytes) + numString; } @@ -328,7 +328,7 @@ export class Tar { // set meta data const info = opts.filePath && (await Deno.stat(opts.filePath)); - let mode = + const mode = opts.fileMode || (info && info.mode) || parseInt("777", 8) & 0xfff, mtime = opts.mtime || @@ -385,8 +385,9 @@ export class Tar { getReader(): Deno.Reader { const readers: Deno.Reader[] = []; this.data.forEach((tarData): void => { - let { filePath, reader } = tarData, - headerArr = formatHeader(tarData); + let { reader } = tarData; + const { filePath } = tarData; + const headerArr = formatHeader(tarData); readers.push(new Deno.Buffer(headerArr)); if (!reader) { reader = new FileReader(filePath!); diff --git a/azure-pipelines.yml b/azure-pipelines.yml index a72892228b..63cca75d39 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,6 +1,8 @@ variables: DENO_VERSION: "v0.19.0" TS_VERSION: "3.4.5" + ESLINT_VERSION: "6.5.1" + TS_ESLINT_VERSION: "2.3.2" # TODO Try to get eslint to run under Deno, like prettier jobs: diff --git a/bundle/test.ts b/bundle/test.ts index 87d1257ee3..504e449a67 100644 --- a/bundle/test.ts +++ b/bundle/test.ts @@ -12,6 +12,7 @@ import { instantiate, load, ModuleMetaData } from "./utils.ts"; /* eslint-disable @typescript-eslint/no-namespace */ declare global { namespace globalThis { + // eslint-disable-next-line no-var var __results: [string, string] | undefined; } } diff --git a/bundle/utils.ts b/bundle/utils.ts index 1df78b1f52..91c0820bf5 100644 --- a/bundle/utils.ts +++ b/bundle/utils.ts @@ -23,6 +23,7 @@ type Define = ( /* eslint-disable @typescript-eslint/no-namespace */ declare global { namespace globalThis { + // eslint-disable-next-line no-var var define: Define | undefined; } } diff --git a/datetime/mod.ts b/datetime/mod.ts index 1fd3b348fb..efa6e09fe3 100644 --- a/datetime/mod.ts +++ b/datetime/mod.ts @@ -118,7 +118,7 @@ export function currentDayOfYear(): number { * @return IMF date formated string */ export function toIMF(date: Date): string { - function dtPad(v: string, lPad: number = 2): string { + function dtPad(v: string, lPad = 2): string { return pad(v, lPad, { char: "0" }); } const d = dtPad(date.getUTCDate().toString()); diff --git a/encoding/csv.ts b/encoding/csv.ts index ccbfcba9ef..10d72a8a5f 100644 --- a/encoding/csv.ts +++ b/encoding/csv.ts @@ -56,7 +56,7 @@ async function read( const tp = new TextProtoReader(reader); let line: string; let result: string[] = []; - let lineIndex = Startline; + const lineIndex = Startline; const r = await tp.readLine(); if (r === Deno.EOF) return Deno.EOF; @@ -229,7 +229,7 @@ export async function parse( throw `Error number of fields line:${i}`; } i++; - let out: Record = {}; + const out: Record = {}; for (let j = 0; j < e.length; j++) { const h = headers[j]; if (h.parse) { diff --git a/encoding/hex.ts b/encoding/hex.ts index d2e499cc7f..de3d76869a 100644 --- a/encoding/hex.ts +++ b/encoding/hex.ts @@ -85,7 +85,7 @@ export function decode( dst: Uint8Array, src: Uint8Array ): [number, Error | void] { - var i = 0; + let i = 0; for (; i < Math.floor(src.length / 2); i++) { const [a, aOK] = fromHexChar(src[i * 2]); if (!aOK) { diff --git a/encoding/toml.ts b/encoding/toml.ts index 2abc039309..0cbd51ba04 100644 --- a/encoding/toml.ts +++ b/encoding/toml.ts @@ -64,8 +64,8 @@ class Parser { return line.match(/'''/) ? true : false; } - let merged = [], - acc = [], + const merged = []; + let acc = [], isLiteral = false, capture = false, captureType = "", @@ -123,14 +123,14 @@ class Parser { this.tomlLines = merged; } _unflat(keys: string[], values: object = {}, cObj: object = {}): object { - let out: Record = {}; + const out: Record = {}; if (keys.length === 0) { return cObj; } else { if (Object.keys(cObj).length === 0) { cObj = values; } - let key: string | undefined = keys.pop(); + const key: string | undefined = keys.pop(); if (key) { out[key] = cObj; } @@ -152,7 +152,7 @@ class Parser { delete this.context.currentGroup; } _split(str: string): string[] { - let out = []; + const out = []; out.push(...str.split("\n")); return out; } @@ -233,8 +233,8 @@ class Parser { const reg = /([a-zA-Z0-9-_\.]*) (=)/gi; let result; while ((result = reg.exec(dataString))) { - let ogVal = result[0]; - let newVal = ogVal + const ogVal = result[0]; + const newVal = ogVal .replace(result[1], `"${result[1]}"`) .replace(result[2], ":"); dataString = dataString.replace(ogVal, newVal); @@ -332,9 +332,9 @@ class Parser { } } if (this._isDeclaration(line)) { - let kv = this._processDeclaration(line); - let key = kv.key; - let value = kv.value; + const kv = this._processDeclaration(line); + const key = kv.key; + const value = kv.value; if (!this.context.currentGroup) { this.context.output[key] = value; } else { @@ -360,7 +360,7 @@ class Parser { let k = keys[i]; if (k) { let v = obj[k]; - let pathDeclaration = this._parseDeclarationName(k); + const pathDeclaration = this._parseDeclarationName(k); delete obj[k]; if (pathDeclaration.length > 1) { const shift = pathDeclaration.shift(); @@ -400,7 +400,7 @@ function joinKeys(keys: string[]): string { } class Dumper { - maxPad: number = 0; + maxPad = 0; srcObject: object; output: string[] = []; constructor(srcObjc: object) { @@ -507,11 +507,11 @@ class Dumper { } } _dateDeclaration(keys: string[], value: Date): string { - function dtPad(v: string, lPad: number = 2): string { + function dtPad(v: string, lPad = 2): string { return pad(v, lPad, { char: "0" }); } - let m = dtPad((value.getUTCMonth() + 1).toString()); - let d = dtPad(value.getUTCDate().toString()); + const m = dtPad((value.getUTCMonth() + 1).toString()); + const d = dtPad(value.getUTCDate().toString()); const h = dtPad(value.getUTCHours().toString()); const min = dtPad(value.getUTCMinutes().toString()); const s = dtPad(value.getUTCSeconds().toString()); diff --git a/examples/cat.ts b/examples/cat.ts index ba8b42bdf1..3626e3c296 100644 --- a/examples/cat.ts +++ b/examples/cat.ts @@ -1,7 +1,7 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. async function cat(filenames: string[]): Promise { - for (let filename of filenames) { - let file = await Deno.open(filename); + for (const filename of filenames) { + const file = await Deno.open(filename); await Deno.copy(Deno.stdout, file); file.close(); } diff --git a/examples/gist.ts b/examples/gist.ts index 7c52662b49..890d85099c 100755 --- a/examples/gist.ts +++ b/examples/gist.ts @@ -53,11 +53,11 @@ async function main(): Promise { }); if (res.ok) { - let resObj = await res.json(); + const resObj = await res.json(); console.log("Success"); console.log(resObj["html_url"]); } else { - let err = await res.text(); + const err = await res.text(); console.error("Failure to POST", err); } } diff --git a/flags/mod.ts b/flags/mod.ts index 28332ae75b..19defd1ed3 100644 --- a/flags/mod.ts +++ b/flags/mod.ts @@ -286,7 +286,7 @@ export function parse( argv._.push(flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)); } if (options.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); + argv._.push(...args.slice(i + 1)); break; } } diff --git a/fmt/sprintf.ts b/fmt/sprintf.ts index e1edb13479..dd7ac7f55e 100644 --- a/fmt/sprintf.ts +++ b/fmt/sprintf.ts @@ -17,8 +17,8 @@ class Flags { space?: boolean; zero?: boolean; lessthan?: boolean; - width: number = -1; - precision: number = -1; + width = -1; + precision = -1; } // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -44,9 +44,9 @@ class Printf { i: number; state: State = State.PASSTHROUGH; - verb: string = ""; - buf: string = ""; - argNum: number = 0; + verb = ""; + buf = ""; + argNum = 0; flags: Flags = new Flags(); haveSeen: boolean[]; @@ -64,7 +64,7 @@ class Printf { doPrintf(): string { for (; this.i < this.format.length; ++this.i) { - let c = this.format[this.i]; + const c = this.format[this.i]; switch (this.state) { case State.PASSTHROUGH: if (c === "%") { @@ -104,9 +104,9 @@ class Printf { // %[]... handleFormat(): void { this.flags = new Flags(); - let flags = this.flags; + const flags = this.flags; for (; this.i < this.format.length; ++this.i) { - let c = this.format[this.i]; + const c = this.format[this.i]; switch (this.state) { case State.PERCENT: switch (c) { @@ -152,7 +152,7 @@ class Printf { break; case State.POSITIONAL: // either a verb or * only verb for now, TODO if (c === "*") { - let worp = + const worp = this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION; this.handleWidthOrPrecisionRef(worp); this.state = State.PERCENT; @@ -171,7 +171,7 @@ class Printf { // handle Positional should have already taken care of it... return; } - let arg = this.args[this.argNum]; + const arg = this.args[this.argNum]; this.haveSeen[this.argNum] = true; if (typeof arg === "number") { switch (wOrP) { @@ -182,7 +182,7 @@ class Printf { this.flags.precision = arg; } } else { - let tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC"; + const tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC"; this.tmpError = `%!(BAD ${tmp} '${this.args[this.argNum]}')`; } this.argNum++; @@ -271,7 +271,7 @@ class Printf { return; } handleLessThan(): string { - let arg = this.args[this.argNum]; + const arg = this.args[this.argNum]; if ((arg || {}).constructor.name !== "Array") { throw new Error(`arg ${arg} is not an array. Todo better error handling`); } @@ -294,7 +294,7 @@ class Printf { } else if (this.args.length <= this.argNum) { this.buf += `%!(MISSING '${verb}')`; } else { - let arg = this.args[this.argNum]; // check out of range + const arg = this.args[this.argNum]; // check out of range this.haveSeen[this.argNum] = true; // keep track of used args if (this.flags.lessthan) { this.buf += this.handleLessThan(); @@ -404,7 +404,7 @@ class Printf { return nStr; } - fmtNumber(n: number, radix: number, upcase: boolean = false): string { + fmtNumber(n: number, radix: number, upcase = false): string { let num = Math.abs(n).toString(radix); const prec = this.flags.precision; if (prec !== -1) { @@ -484,7 +484,7 @@ class Printf { return fractional; } - fmtFloatE(n: number, upcase: boolean = false): string { + fmtFloatE(n: number, upcase = false): string { const special = this.fmtFloatSpecial(n); if (special !== "") { return special; @@ -553,7 +553,7 @@ class Printf { return this.padNum(`${dig}.${fractional}`, n < 0); } - fmtFloatG(n: number, upcase: boolean = false): string { + fmtFloatG(n: number, upcase = false): string { const special = this.fmtFloatSpecial(n); if (special !== "") { return special; @@ -591,7 +591,7 @@ class Printf { throw Error("can't happen"); } - let X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1); + const X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1); let nStr = ""; if (P > X && X >= -4) { this.flags.precision = P - (X + 1); @@ -616,14 +616,14 @@ class Printf { return this.pad(s); } - fmtHex(val: string | number, upper: boolean = false): string { + fmtHex(val: string | number, upper = false): string { // allow others types ? switch (typeof val) { case "number": return this.fmtNumber(val as number, 16, upper); break; case "string": - let sharp = this.flags.sharp && val.length !== 0; + const sharp = this.flags.sharp && val.length !== 0; let hex = sharp ? "0x" : ""; const prec = this.flags.precision; const end = prec !== -1 ? min(prec, val.length) : val.length; @@ -634,7 +634,7 @@ class Printf { // TODO: for now only taking into account the // lower half of the codePoint, ie. as if a string // is a list of 8bit values instead of UCS2 runes - let c = (val.charCodeAt(i) & 0xff).toString(16); + const c = (val.charCodeAt(i) & 0xff).toString(16); hex += c.length === 1 ? `0${c}` : c; } if (upper) { @@ -652,7 +652,7 @@ class Printf { // eslint-disable-next-line @typescript-eslint/no-explicit-any fmtV(val: any): string { if (this.flags.sharp) { - let options = + const options = this.flags.precision !== -1 ? { depth: this.flags.precision } : {}; return this.pad(Deno.inspect(val, options)); } else { @@ -669,6 +669,6 @@ class Printf { // eslint-disable-next-line @typescript-eslint/no-explicit-any export function sprintf(format: string, ...args: any[]): string { - let printf = new Printf(format, ...args); + const printf = new Printf(format, ...args); return printf.doPrintf(); } diff --git a/fmt/sprintf_test.ts b/fmt/sprintf_test.ts index 7cfe0d0a48..26757c3cc6 100644 --- a/fmt/sprintf_test.ts +++ b/fmt/sprintf_test.ts @@ -3,7 +3,7 @@ import { sprintf } from "./sprintf.ts"; import { assertEquals } from "../testing/asserts.ts"; import { test, runIfMain } from "../testing/mod.ts"; -let S = sprintf; +const S = sprintf; test(function noVerb(): void { assertEquals(sprintf("bla"), "bla"); @@ -589,8 +589,8 @@ const tests: Array<[string, any, string]> = [ test(function testThorough(): void { tests.forEach((t, i): void => { // p(t) - let is = S(t[0], t[1]); - let should = t[2]; + const is = S(t[0], t[1]); + const should = t[2]; assertEquals( is, should, @@ -608,7 +608,7 @@ test(function testWeirdos(): void { }); test(function formatV(): void { - let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; + const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; assertEquals(S("%v", a), "[object Object]"); assertEquals(S("%#v", a), "{ a: { a: { a: { a: [Object] } } } }"); assertEquals( @@ -619,18 +619,18 @@ test(function formatV(): void { }); test(function formatJ(): void { - let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; + const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; assertEquals(S("%j", a), `{"a":{"a":{"a":{"a":{"a":{"a":{"a":{}}}}}}}}`); }); test(function flagLessThan(): void { - let a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; - let aArray = [a, a, a]; + const a = { a: { a: { a: { a: { a: { a: { a: {} } } } } } } }; + const aArray = [a, a, a]; assertEquals( S("%<#.1v", aArray), "[ { a: [Object] }, { a: [Object] }, { a: [Object] } ]" ); - let fArray = [1.2345, 0.98765, 123456789.5678]; + const fArray = [1.2345, 0.98765, 123456789.5678]; assertEquals(S("%<.2f", fArray), "[ 1.23, 0.99, 123456789.57 ]"); }); diff --git a/fs/copy.ts b/fs/copy.ts index c3c97d1baa..616fba9751 100644 --- a/fs/copy.ts +++ b/fs/copy.ts @@ -21,11 +21,9 @@ async function ensureValidCopy( src: string, dest: string, options: CopyOptions, - isCopyFolder: boolean = false + isCopyFolder = false ): Promise { - let destStat: Deno.FileInfo | null; - - destStat = await Deno.lstat(dest).catch( + const destStat: Deno.FileInfo | null = await Deno.lstat(dest).catch( (): Promise => Promise.resolve(null) ); @@ -47,7 +45,7 @@ function ensureValidCopySync( src: string, dest: string, options: CopyOptions, - isCopyFolder: boolean = false + isCopyFolder = false ): Deno.FileInfo { let destStat: Deno.FileInfo | null; diff --git a/fs/glob.ts b/fs/glob.ts index d9e6560c11..86d83b4f86 100644 --- a/fs/glob.ts +++ b/fs/glob.ts @@ -112,7 +112,7 @@ export function joinGlobs( if (globs.length === 0) return "."; let joined: string | undefined; for (const glob of globs) { - let path = glob; + const path = glob; if (path.length > 0) { if (!joined) joined = path; else joined += `${SEP}${path}`; diff --git a/fs/globrex.ts b/fs/globrex.ts index 03d69fc8bc..5bf0e16a0a 100644 --- a/fs/globrex.ts +++ b/fs/globrex.ts @@ -127,7 +127,7 @@ export function globrex( if (c === ")") { if (ext.length) { add(c); - let type: string | undefined = ext.pop(); + const type: string | undefined = ext.pop(); if (type === "@") { add("{1}"); } else if (type === "!") { @@ -264,19 +264,19 @@ export function globrex( } // Move over all consecutive "*"'s. // Also store the previous and next characters - let prevChar = glob[i - 1]; + const prevChar = glob[i - 1]; let starCount = 1; while (glob[i + 1] === "*") { starCount++; i++; } - let nextChar = glob[i + 1]; + const nextChar = glob[i + 1]; if (!globstar) { // globstar is disabled, so treat any number of "*" as one add(".*"); } else { // globstar is enabled, so determine if this is a globstar segment - let isGlobstar = + const isGlobstar = starCount > 1 && // multiple "*"'s // from the start of the segment [SEP_RAW, "/", undefined].includes(prevChar) && diff --git a/fs/globrex_test.ts b/fs/globrex_test.ts index 6d421611fe..31607216d5 100644 --- a/fs/globrex_test.ts +++ b/fs/globrex_test.ts @@ -19,14 +19,14 @@ function match( opts = strWin; strWin = ""; } - let res = globrex(glob, opts); + const res = globrex(glob, opts); return res.regex.test(isWin && strWin ? strWin : strUnix); } test({ name: "globrex: standard", fn(): void { - let res = globrex("*.js"); + const res = globrex("*.js"); t.equal(typeof globrex, "function", "constructor is a typeof function"); t.equal(res instanceof Object, true, "returns object"); t.equal(res.regex.toString(), "/^.*\\.js$/", "returns regex object"); diff --git a/fs/path/parse_format_test.ts b/fs/path/parse_format_test.ts index 8829891da5..db83c33540 100644 --- a/fs/path/parse_format_test.ts +++ b/fs/path/parse_format_test.ts @@ -1,5 +1,7 @@ // Copyright the Browserify authors. MIT License. // Ported from https://github.com/browserify/path-browserify/ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// TODO(kt3k): fix any types in this file import { test } from "../../testing/mod.ts"; import { assertEquals } from "../../testing/asserts.ts"; @@ -80,7 +82,7 @@ const unixSpecialCaseFormatTests = [ ]; function checkParseFormat(path: any, paths: any): void { - paths.forEach(function(p: Record[]) { + paths.forEach(function(p: Array>) { const element = p[0]; const output = path.parse(element); assertEquals(typeof output.root, "string"); @@ -96,7 +98,7 @@ function checkParseFormat(path: any, paths: any): void { } function checkSpecialCaseParseFormat(path: any, testCases: any): void { - testCases.forEach(function(testCase: Record[]) { + testCases.forEach(function(testCase: Array>) { const element = testCase[0]; const expect = testCase[1]; const output = path.parse(element); diff --git a/fs/path/posix.ts b/fs/path/posix.ts index 4fe0f64c03..4377fd5427 100644 --- a/fs/path/posix.ts +++ b/fs/path/posix.ts @@ -83,7 +83,7 @@ export function join(...paths: string[]): string { if (paths.length === 0) return "."; let joined: string | undefined; for (let i = 0, len = paths.length; i < len; ++i) { - let path = paths[i]; + const path = paths[i]; assertPath(path); if (path.length > 0) { if (!joined) joined = path; @@ -107,11 +107,11 @@ export function relative(from: string, to: string): string { // Trim any leading backslashes let fromStart = 1; - let fromEnd = from.length; + const fromEnd = from.length; for (; fromStart < fromEnd; ++fromStart) { if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; } - let fromLen = fromEnd - fromStart; + const fromLen = fromEnd - fromStart; // Trim any leading backslashes let toStart = 1; @@ -119,10 +119,10 @@ export function relative(from: string, to: string): string { for (; toStart < toEnd; ++toStart) { if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; } - let toLen = toEnd - toStart; + const toLen = toEnd - toStart; // Compare paths to find the longest common path from root - let length = fromLen < toLen ? fromLen : toLen; + const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i = 0; for (; i <= length; ++i) { @@ -150,8 +150,8 @@ export function relative(from: string, to: string): string { } break; } - let fromCode = from.charCodeAt(fromStart + i); - let toCode = to.charCodeAt(toStart + i); + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); if (fromCode !== toCode) break; else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i; } @@ -328,6 +328,7 @@ export function extname(path: string): string { } export function format(pathObject: FormatInputPathObject): string { + /* eslint-disable max-len */ if (pathObject === null || typeof pathObject !== "object") { throw new TypeError( `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` @@ -339,9 +340,9 @@ export function format(pathObject: FormatInputPathObject): string { export function parse(path: string): ParsedPath { assertPath(path); - let ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; + const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; if (path.length === 0) return ret; - let isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; let start: number; if (isAbsolute) { ret.root = "/"; diff --git a/fs/path/win32.ts b/fs/path/win32.ts index d42cc4885d..79e04ea6eb 100644 --- a/fs/path/win32.ts +++ b/fs/path/win32.ts @@ -304,7 +304,7 @@ export function join(...paths: string[]): string { let joined: string | undefined; let firstPart: string; for (let i = 0; i < pathsCount; ++i) { - let path = paths[i]; + const path = paths[i]; assertPath(path); if (path.length > 0) { if (joined === undefined) joined = firstPart = path; @@ -369,8 +369,8 @@ export function relative(from: string, to: string): string { if (from === to) return ""; - let fromOrig = resolve(from); - let toOrig = resolve(to); + const fromOrig = resolve(from); + const toOrig = resolve(to); if (fromOrig === toOrig) return ""; @@ -389,7 +389,7 @@ export function relative(from: string, to: string): string { for (; fromEnd - 1 > fromStart; --fromEnd) { if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; } - let fromLen = fromEnd - fromStart; + const fromLen = fromEnd - fromStart; // Trim any leading backslashes let toStart = 0; @@ -401,10 +401,10 @@ export function relative(from: string, to: string): string { for (; toEnd - 1 > toStart; --toEnd) { if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; } - let toLen = toEnd - toStart; + const toLen = toEnd - toStart; // Compare paths to find the longest common path from root - let length = fromLen < toLen ? fromLen : toLen; + const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i = 0; for (; i <= length; ++i) { @@ -433,8 +433,8 @@ export function relative(from: string, to: string): string { } break; } - let fromCode = from.charCodeAt(fromStart + i); - let toCode = to.charCodeAt(toStart + i); + const fromCode = from.charCodeAt(fromStart + i); + const toCode = to.charCodeAt(toStart + i); if (fromCode !== toCode) break; else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; } @@ -737,6 +737,7 @@ export function extname(path: string): string { } export function format(pathObject: FormatInputPathObject): string { + /* eslint-disable max-len */ if (pathObject === null || typeof pathObject !== "object") { throw new TypeError( `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}` @@ -748,7 +749,7 @@ export function format(pathObject: FormatInputPathObject): string { export function parse(path: string): ParsedPath { assertPath(path); - let ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; + const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; const len = path.length; if (len === 0) return ret; diff --git a/fs/path/zero_length_strings_test.ts b/fs/path/zero_length_strings_test.ts index 20405563c8..744e97735d 100644 --- a/fs/path/zero_length_strings_test.ts +++ b/fs/path/zero_length_strings_test.ts @@ -27,7 +27,8 @@ test(function normalizeZeroLength() { }); test(function isAbsoluteZeroLength() { - // Since '' is not a valid path in any of the common environments, return false + // Since '' is not a valid path in any of the common environments, + // return false assertEquals(path.posix.isAbsolute(""), false); if (path.win32) assertEquals(path.win32.isAbsolute(""), false); }); @@ -40,7 +41,8 @@ test(function resolveZeroLength() { }); test(function relativeZeroLength() { - // relative, internally calls resolve. So, '' is actually the current directory + // relative, internally calls resolve. So, '' is actually the current + // directory assertEquals(path.relative("", pwd), ""); assertEquals(path.relative(pwd, ""), ""); assertEquals(path.relative(pwd, pwd), ""); diff --git a/fs/walk.ts b/fs/walk.ts index 583b4dd550..4808598af8 100644 --- a/fs/walk.ts +++ b/fs/walk.ts @@ -22,7 +22,7 @@ function patternTest(patterns: RegExp[], path: string): boolean { // consistent results. // See: https://stackoverflow.com/a/1520853 return patterns.some((pattern): boolean => { - let r = pattern.test(path); + const r = pattern.test(path); pattern.lastIndex = 0; return r; }); @@ -100,7 +100,7 @@ export async function* walk( options.onError(err); } } - for (let info of ls) { + for (const info of ls) { if (info.isSymlink()) { if (options.followSymlinks) { // TODO(ry) Re-enable followSymlinks. @@ -154,7 +154,7 @@ export function* walkSync( options.onError(err); } } - for (let info of ls) { + for (const info of ls) { if (info.isSymlink()) { if (options.followSymlinks) { unimplemented(); diff --git a/http/cookie.ts b/http/cookie.ts index 843f626f19..4d2704da1b 100644 --- a/http/cookie.ts +++ b/http/cookie.ts @@ -59,7 +59,7 @@ function toString(cookie: Cookie): string { out.push(`Path=${cookie.path}`); } if (cookie.expires) { - let dateString = toIMF(cookie.expires); + const dateString = toIMF(cookie.expires); out.push(`Expires=${dateString}`); } if (cookie.unparsed) { diff --git a/http/cookie_test.ts b/http/cookie_test.ts index 05ed324d21..da91102917 100644 --- a/http/cookie_test.ts +++ b/http/cookie_test.ts @@ -7,7 +7,7 @@ import { test } from "../testing/mod.ts"; test({ name: "[HTTP] Cookie parser", fn(): void { - let req = new ServerRequest(); + const req = new ServerRequest(); req.headers = new Headers(); assertEquals(getCookies(req), {}); req.headers = new Headers(); @@ -35,7 +35,7 @@ test({ test({ name: "[HTTP] Cookie Delete", fn(): void { - let res: Response = {}; + const res: Response = {}; delCookie(res, "deno"); assertEquals( res.headers!.get("Set-Cookie"), @@ -47,7 +47,7 @@ test({ test({ name: "[HTTP] Cookie Set", fn(): void { - let res: Response = {}; + const res: Response = {}; res.headers = new Headers(); setCookie(res, { name: "Space", value: "Cat" }); diff --git a/http/file_server.ts b/http/file_server.ts index dfcd40cddd..77d0cf7486 100755 --- a/http/file_server.ts +++ b/http/file_server.ts @@ -150,7 +150,7 @@ async function serveDir( const fileInfos = await readDir(dirPath); for (const fileInfo of fileInfos) { const filePath = posix.join(dirPath, fileInfo.name); - let fileUrl = posix.join(dirUrl, fileInfo.name); + const fileUrl = posix.join(dirUrl, fileInfo.name); if (fileInfo.name === "index.html" && fileInfo.isFile()) { // in case index.html as dir... return await serveFile(req, filePath); diff --git a/http/racing_server_test.ts b/http/racing_server_test.ts index a6534861e7..b669862471 100644 --- a/http/racing_server_test.ts +++ b/http/racing_server_test.ts @@ -21,7 +21,7 @@ function killServer(): void { server.stdout!.close(); } -let input = `GET / HTTP/1.1 +const input = `GET / HTTP/1.1 GET / HTTP/1.1 @@ -31,7 +31,7 @@ GET / HTTP/1.1 `; const HUGE_BODY_SIZE = 1024 * 1024; -let output = `HTTP/1.1 200 OK +const output = `HTTP/1.1 200 OK content-length: 8 Hello 1 diff --git a/http/server.ts b/http/server.ts index d9bba525af..f1ced0577b 100644 --- a/http/server.ts +++ b/http/server.ts @@ -139,7 +139,7 @@ export class ServerRequest { let line = await tp.readLine(); if (line === Deno.EOF) throw new UnexpectedEOFError(); // TODO: handle chunk extension - let [chunkSizeString] = line.split(";"); + const [chunkSizeString] = line.split(";"); let chunkSize = parseInt(chunkSizeString, 16); if (Number.isNaN(chunkSize) || chunkSize < 0) { throw new Error("Invalid chunk size"); @@ -157,7 +157,7 @@ export class ServerRequest { } const entityHeaders = await tp.readMIMEHeader(); if (entityHeaders !== Deno.EOF) { - for (let [k, v] of entityHeaders) { + for (const [k, v] of entityHeaders) { this.headers.set(k, v); } } @@ -242,8 +242,6 @@ export function parseHTTPVersion(vers: string): [number, number] { default: { const Big = 1000000; // arbitrary upper bound const digitReg = /^\d+$/; // test if string is only digit - let major: number; - let minor: number; if (!vers.startsWith("HTTP/")) { break; @@ -254,8 +252,8 @@ export function parseHTTPVersion(vers: string): [number, number] { break; } - let majorStr = vers.substring(vers.indexOf("/") + 1, dot); - major = parseInt(majorStr); + const majorStr = vers.substring(vers.indexOf("/") + 1, dot); + const major = parseInt(majorStr); if ( !digitReg.test(majorStr) || isNaN(major) || @@ -265,8 +263,8 @@ export function parseHTTPVersion(vers: string): [number, number] { break; } - let minorStr = vers.substring(dot + 1); - minor = parseInt(minorStr); + const minorStr = vers.substring(dot + 1); + const minor = parseInt(minorStr); if ( !digitReg.test(minorStr) || isNaN(minor) || diff --git a/http/server_test.ts b/http/server_test.ts index 314e5232e3..a49301790b 100644 --- a/http/server_test.ts +++ b/http/server_test.ts @@ -349,7 +349,7 @@ const mockConn = { }; test(async function readRequestError(): Promise { - let input = `GET / HTTP/1.1 + const input = `GET / HTTP/1.1 malformedHeader `; const reader = new BufReader(new StringReader(input)); diff --git a/http/testdata/simple_server.ts b/http/testdata/simple_server.ts index 4f8b0e8014..67b957ad5a 100644 --- a/http/testdata/simple_server.ts +++ b/http/testdata/simple_server.ts @@ -5,7 +5,7 @@ import { serve } from "../server.ts"; window.onload = async function main() { const addr = "0.0.0.0:4502"; console.log(`Simple server listening on ${addr}`); - for await (let req of serve(addr)) { + for await (const req of serve(addr)) { req.respond({}); } } diff --git a/installer/mod.ts b/installer/mod.ts index 1b9217cd48..ef94e2e4e6 100644 --- a/installer/mod.ts +++ b/installer/mod.ts @@ -79,7 +79,7 @@ function getFlagFromPermission(perm: Permission): string { function getInstallerDir(): string { // In Windows's Powershell $HOME environmental variable maybe null // if so use $HOMEPATH instead. - let { HOME, HOMEPATH } = env(); + const { HOME, HOMEPATH } = env(); const HOME_PATH = HOME || HOMEPATH; @@ -109,7 +109,7 @@ function checkIfExistsInPath(filePath: string): boolean { // $HOMEDRIVE is only used on Windows. const { PATH, Path, HOMEDRIVE } = env(); - let envPath = (PATH as string) || (Path as string) || ""; + const envPath = (PATH as string) || (Path as string) || ""; const paths = envPath.split(isWindows ? ";" : ":"); diff --git a/io/bufio.ts b/io/bufio.ts index 3291c8a07d..213870c3c4 100644 --- a/io/bufio.ts +++ b/io/bufio.ts @@ -407,7 +407,7 @@ export class BufReader implements Reader { */ export class BufWriter implements Writer { buf: Uint8Array; - n: number = 0; + n = 0; err: Error | null = null; /** return new BufWriter unless w is BufWriter */ diff --git a/io/bufio_test.ts b/io/bufio_test.ts index 9d1ffc307e..75664694ac 100644 --- a/io/bufio_test.ts +++ b/io/bufio_test.ts @@ -32,7 +32,7 @@ async function readBytes(buf: BufReader): Promise { const b = new Uint8Array(1000); let nb = 0; while (true) { - let c = await buf.readByte(); + const c = await buf.readByte(); if (c === Deno.EOF) { break; // EOF } @@ -122,10 +122,10 @@ test(async function bufioBufReader(): Promise { } texts[texts.length - 1] = all; - for (let text of texts) { - for (let readmaker of readMakers) { - for (let bufreader of bufreaders) { - for (let bufsize of bufsizes) { + for (const text of texts) { + for (const readmaker of readMakers) { + for (const bufreader of bufreaders) { + for (const bufsize of bufsizes) { const read = readmaker.fn(stringsReader(text)); const buf = new BufReader(read, bufsize); const s = await bufreader.fn(buf); @@ -210,8 +210,8 @@ class TestReader implements Reader { async function testReadLine(input: Uint8Array): Promise { for (let stride = 1; stride < 2; stride++) { let done = 0; - let reader = new TestReader(input, stride); - let l = new BufReader(reader, input.byteLength + 1); + const reader = new TestReader(input, stride); + const l = new BufReader(reader, input.byteLength + 1); while (true) { const r = await l.readLine(); if (r === Deno.EOF) { @@ -220,7 +220,7 @@ async function testReadLine(input: Uint8Array): Promise { const { line, more } = r; assertEquals(more, false); // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - let want = testOutput.subarray(done, done + line.byteLength); + const want = testOutput.subarray(done, done + line.byteLength); assertEquals( line, want, @@ -244,9 +244,9 @@ test(async function bufioReadLine(): Promise { test(async function bufioPeek(): Promise { const decoder = new TextDecoder(); - let p = new Uint8Array(10); + const p = new Uint8Array(10); // string is 16 (minReadBufferSize) long. - let buf = new BufReader( + const buf = new BufReader( stringsReader("abcdefghijklmnop"), MIN_READ_BUFFER_SIZE ); @@ -281,7 +281,7 @@ test(async function bufioPeek(): Promise { actual = assertNotEOF(await buf.peek(2)); assertEquals(decoder.decode(actual), "de"); - let res = await buf.read(p.subarray(0, 3)); + const res = await buf.read(p.subarray(0, 3)); assertEquals(decoder.decode(p.subarray(0, 3)), "def"); assert(res !== Deno.EOF); @@ -327,8 +327,8 @@ test(async function bufioWriter(): Promise { } const w = new Buffer(); - for (let nwrite of bufsizes) { - for (let bs of bufsizes) { + for (const nwrite of bufsizes) { + for (const bs of bufsizes) { // Write nwrite bytes using buffer size bs. // Check that the right amount makes it out // and that the data is correct. diff --git a/io/readers_test.ts b/io/readers_test.ts index f80bfd55fb..474407427a 100644 --- a/io/readers_test.ts +++ b/io/readers_test.ts @@ -17,13 +17,13 @@ test(async function ioStringReader(): Promise { test(async function ioStringReader(): Promise { const r = new StringReader("abcdef"); const buf = new Uint8Array(3); - let res1 = await r.read(buf); + const res1 = await r.read(buf); assertEquals(res1, 3); assertEquals(decode(buf), "abc"); - let res2 = await r.read(buf); + const res2 = await r.read(buf); assertEquals(res2, 3); assertEquals(decode(buf), "def"); - let res3 = await r.read(buf); + const res3 = await r.read(buf); assertEquals(res3, Deno.EOF); assertEquals(decode(buf), "def"); }); diff --git a/io/util_test.ts b/io/util_test.ts index 3302fe9e32..c616a4bba3 100644 --- a/io/util_test.ts +++ b/io/util_test.ts @@ -6,7 +6,7 @@ import { copyBytes, tempFile } from "./util.ts"; import * as path from "../fs/path.ts"; test(function testCopyBytes(): void { - let dst = new Uint8Array(4); + const dst = new Uint8Array(4); dst.fill(0); let src = Uint8Array.of(1, 2); diff --git a/io/writers.ts b/io/writers.ts index de070d48a3..91d19a9d75 100644 --- a/io/writers.ts +++ b/io/writers.ts @@ -5,7 +5,7 @@ import { decode, encode } from "../strings/mod.ts"; /** Writer utility for buffering string chunks */ export class StringWriter implements Writer { private chunks: Uint8Array[] = []; - private byteLength: number = 0; + private byteLength = 0; private cache: string | undefined; constructor(private base: string = "") { diff --git a/log/logger_test.ts b/log/logger_test.ts index 2aca71d1ca..d8d205c082 100644 --- a/log/logger_test.ts +++ b/log/logger_test.ts @@ -50,7 +50,7 @@ test(function customHandler(): void { test(function logFunctions(): void { const doLog = (level: string): TestHandler => { const handler = new TestHandler(level); - let logger = new Logger(level, [handler]); + const logger = new Logger(level, [handler]); logger.debug("foo"); logger.info("bar"); logger.warning("baz"); diff --git a/mime/multipart.ts b/mime/multipart.ts index 62a25a0b97..033d51cb09 100644 --- a/mime/multipart.ts +++ b/mime/multipart.ts @@ -130,7 +130,7 @@ export function scanUntilBoundary( class PartReader implements Reader, Closer { n: number | Deno.EOF = 0; - total: number = 0; + total = 0; constructor(private mr: MultipartReader, public readonly headers: Headers) {} @@ -312,7 +312,7 @@ export class MultipartReader { } private currentPart: PartReader | undefined; - private partsRead: number = 0; + private partsRead = 0; private async nextPart(): Promise { if (this.currentPart) { @@ -359,7 +359,7 @@ export class MultipartReader { if (!hasPrefix(line, this.dashBoundaryDash)) { return false; } - let rest = line.slice(this.dashBoundaryDash.length, line.length); + const rest = line.slice(this.dashBoundaryDash.length, line.length); return rest.length === 0 || equal(skipLWSPChar(rest), this.newLine); } @@ -375,7 +375,7 @@ export class MultipartReader { class PartWriter implements Writer { closed = false; private readonly partHeader: string; - private headersWritten: boolean = false; + private headersWritten = false; constructor( private writer: Writer, @@ -436,7 +436,7 @@ export class MultipartWriter { private lastPart: PartWriter | undefined; private bufWriter: BufWriter; - private isClosed: boolean = false; + private isClosed = false; constructor(private readonly writer: Writer, boundary?: string) { if (boundary !== void 0) { diff --git a/prettier/main_test.ts b/prettier/main_test.ts index c255ed7da7..3f6bc90e57 100644 --- a/prettier/main_test.ts +++ b/prettier/main_test.ts @@ -54,21 +54,21 @@ test(async function testPrettierCheckAndFormatFiles(): Promise { join(tempDir, "2.ts") ]; - var { code, stdout } = await run([...cmd, "--check", ...files]); - assertEquals(code, 1); - assertEquals(normalizeOutput(stdout), "Some files are not formatted"); + let p = await run([...cmd, "--check", ...files]); + assertEquals(p.code, 1); + assertEquals(normalizeOutput(p.stdout), "Some files are not formatted"); - var { code, stdout } = await run([...cmd, "--write", ...files]); - assertEquals(code, 0); + p = await run([...cmd, "--write", ...files]); + assertEquals(p.code, 0); assertEquals( - normalizeOutput(stdout), + normalizeOutput(p.stdout), normalizeOutput(`Formatting ${tempDir}/0.ts Formatting ${tempDir}/1.js`) ); - var { code, stdout } = await run([...cmd, "--check", ...files]); - assertEquals(code, 0); - assertEquals(normalizeOutput(stdout), "Every file is formatted"); + p = await run([...cmd, "--check", ...files]); + assertEquals(p.code, 0); + assertEquals(normalizeOutput(p.stdout), "Every file is formatted"); emptyDir(tempDir); }); @@ -79,23 +79,23 @@ test(async function testPrettierCheckAndFormatDirs(): Promise { const dirs = [join(tempDir, "foo"), join(tempDir, "bar")]; - var { code, stdout } = await run([...cmd, "--check", ...dirs]); - assertEquals(code, 1); - assertEquals(normalizeOutput(stdout), "Some files are not formatted"); + let p = await run([...cmd, "--check", ...dirs]); + assertEquals(p.code, 1); + assertEquals(normalizeOutput(p.stdout), "Some files are not formatted"); - var { code, stdout } = await run([...cmd, "--write", ...dirs]); - assertEquals(code, 0); + p = await run([...cmd, "--write", ...dirs]); + assertEquals(p.code, 0); assertEquals( - normalizeOutput(stdout), + normalizeOutput(p.stdout), normalizeOutput(`Formatting ${tempDir}/bar/0.ts Formatting ${tempDir}/bar/1.js Formatting ${tempDir}/foo/0.ts Formatting ${tempDir}/foo/1.js`) ); - var { code, stdout } = await run([...cmd, "--check", ...dirs]); - assertEquals(code, 0); - assertEquals(normalizeOutput(stdout), "Every file is formatted"); + p = await run([...cmd, "--check", ...dirs]); + assertEquals(p.code, 0); + assertEquals(normalizeOutput(p.stdout), "Every file is formatted"); emptyDir(tempDir); }); diff --git a/strings/pad.ts b/strings/pad.ts index 3c5084da2b..267839a397 100644 --- a/strings/pad.ts +++ b/strings/pad.ts @@ -60,7 +60,7 @@ export function pad( out = out.padEnd(strLen, opts.char); } } else if (opts.strict && outL > strLen) { - let addChar = opts.strictChar ? opts.strictChar : ""; + const addChar = opts.strictChar ? opts.strictChar : ""; if (opts.strictSide === "left") { let toDrop = outL - strLen; if (opts.strictChar) { diff --git a/testing/asserts.ts b/testing/asserts.ts index 28dfa7911f..230e2c8d28 100644 --- a/testing/asserts.ts +++ b/testing/asserts.ts @@ -235,7 +235,7 @@ export function assertArrayContains( expected: unknown[], msg?: string ): void { - let missing: unknown[] = []; + const missing: unknown[] = []; for (let i = 0; i < expected.length; i++) { let found = false; for (let j = 0; j < actual.length; j++) { diff --git a/testing/bench_test.ts b/testing/bench_test.ts index 1c6459bbb0..8af2f0d6db 100644 --- a/testing/bench_test.ts +++ b/testing/bench_test.ts @@ -19,7 +19,7 @@ test(async function benching(): Promise { bench(async function forAwaitFetchDenolandX10(b): Promise { b.start(); for (let i = 0; i < 10; i++) { - let r = await fetch("https://deno.land/"); + const r = await fetch("https://deno.land/"); await r.text(); } b.stop(); @@ -31,7 +31,7 @@ test(async function benching(): Promise { await Promise.all( urls.map( async (denoland: string): Promise => { - let r = await fetch(denoland); + const r = await fetch(denoland); await r.text(); } ) diff --git a/testing/format.ts b/testing/format.ts index 06c1b68186..953347c277 100644 --- a/testing/format.ts +++ b/testing/format.ts @@ -271,7 +271,7 @@ function printIteratorEntries( // Too bad, so sad that separator for ECMAScript Map has been ' => ' // What a distracting diff if you change a data structure to/from // ECMAScript Object or Immutable.Map/OrderedMap which use the default. - separator: string = ": " + separator = ": " ): string { let result = ""; let current = iterator.next(); diff --git a/testing/format_test.ts b/testing/format_test.ts index 39884d484d..e2bb8df239 100644 --- a/testing/format_test.ts +++ b/testing/format_test.ts @@ -13,6 +13,7 @@ import { format } from "./format.ts"; // eslint-disable-next-line max-len // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-explicit-any function returnArguments(...args: any[]): IArguments { + // eslint-disable-next-line prefer-rest-params return arguments; } diff --git a/testing/mod.ts b/testing/mod.ts index 329e02895a..3b6386d5b4 100644 --- a/testing/mod.ts +++ b/testing/mod.ts @@ -62,7 +62,7 @@ function disableConsole(): void { } const encoder = new TextEncoder(); -function print(txt: string, newline: boolean = true): void { +function print(txt: string, newline = true): void { if (newline) { txt += "\n"; } @@ -172,11 +172,11 @@ function createTestResults(tests: TestDefinition[]): TestResults { ); } -function formatTestTime(time: number = 0): string { +function formatTestTime(time = 0): string { return `${time.toFixed(2)}ms`; } -function promptTestTime(time: number = 0, displayWarning = false): string { +function promptTestTime(time = 0, displayWarning = false): string { // if time > 5s we display a warning // only for test time, not the full runtime if (displayWarning && time >= 5000) { @@ -308,10 +308,9 @@ async function runTestsSerial( print(`${yellow("RUNNING")} ${name}`, false); } try { - let start, end; - start = performance.now(); + const start = performance.now(); await fn(); - end = performance.now(); + const end = performance.now(); if (disableLog) { // Rewriting the current prompt line to erase `running ....` print(CLEAR_LINE, false); diff --git a/textproto/mod.ts b/textproto/mod.ts index 941525e950..22153d17ce 100644 --- a/textproto/mod.ts +++ b/textproto/mod.ts @@ -66,7 +66,7 @@ export class TextProtoReader { * } */ async readMIMEHeader(): Promise { - let m = new Headers(); + const m = new Headers(); let line: Uint8Array; // The first line cannot start with a leading space. @@ -87,7 +87,7 @@ export class TextProtoReader { } while (true) { - let kv = await this.readLineSlice(); // readContinuedLineSlice + const kv = await this.readLineSlice(); // readContinuedLineSlice if (kv === Deno.EOF) throw new UnexpectedEOFError(); if (kv.byteLength === 0) return m; @@ -104,7 +104,7 @@ export class TextProtoReader { } //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); - let key = str(kv.subarray(0, endKey)); + const key = str(kv.subarray(0, endKey)); // As per RFC 7230 field-name is a token, // tokens consist of one or more chars. @@ -123,7 +123,7 @@ export class TextProtoReader { ) { i++; } - let value = str(kv.subarray(i)); + const value = str(kv.subarray(i)); // In case of invalid header we swallow the error // example: "Audio Mode" => invalid due to space in the key diff --git a/tsconfig.json b/tsconfig.json index f438205b01..732e8322ce 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "tsconfig.test.json", + "extends": "./tsconfig.test.json", "compilerOptions": { "allowJs": true, "baseUrl": ".", diff --git a/util/async.ts b/util/async.ts index eaf97dd7b7..6e2db69dc6 100644 --- a/util/async.ts +++ b/util/async.ts @@ -100,7 +100,7 @@ export async function collectUint8Arrays( } const collected = new Uint8Array(length); let offset = 0; - for (let chunk of chunks) { + for (const chunk of chunks) { collected.set(chunk, offset); offset += chunk.length; } diff --git a/ws/mod.ts b/ws/mod.ts index 8bd11aa0a5..11e3ee23e4 100644 --- a/ws/mod.ts +++ b/ws/mod.ts @@ -368,7 +368,7 @@ export function createSecAccept(nonce: string): string { const sha1 = new Sha1(); sha1.update(nonce + kGUID); const bytes = sha1.digest(); - return btoa(String.fromCharCode.apply(String, bytes)); + return btoa(String.fromCharCode(...bytes)); } /** Upgrade given TCP connection into websocket connection */ @@ -480,7 +480,7 @@ export async function connectWebSocket( headers: Headers = new Headers() ): Promise { const url = new URL(endpoint); - let { hostname } = url; + const { hostname } = url; let conn: Conn; if (url.protocol === "http:" || url.protocol === "ws:") { const port = parseInt(url.port || "80"); diff --git a/xeval/mod.ts b/xeval/mod.ts index ceca25a799..5843c8650a 100644 --- a/xeval/mod.ts +++ b/xeval/mod.ts @@ -70,7 +70,7 @@ async function* chunks( let inspectIndex = 0; let matchIndex = 0; while (true) { - let result = await reader.read(inspectArr); + const result = await reader.read(inspectArr); if (result === EOF) { // Yield last chunk. const lastChunk = inputBuffer.toString(); @@ -81,7 +81,7 @@ async function* chunks( // Discard all remaining and silently fail. return; } - let sliceRead = inspectArr.subarray(0, result as number); + const sliceRead = inspectArr.subarray(0, result as number); await writeAll(inputBuffer, sliceRead); let sliceToProcess = inputBuffer.bytes();