diff options
378 files changed, 3115 insertions, 3120 deletions
diff --git a/.dprintrc.json b/.dprintrc.json new file mode 100644 index 000000000..beb5d099d --- /dev/null +++ b/.dprintrc.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://dprint.dev/schemas/v0.json", + "projectType": "openSource", + "lineWidth": 80, + "indentWidth": 2, + "typescript": { + "deno": true + }, + "markdown": { + "textWrap": "always" + }, + "includes": ["**/*.{ts,tsx,js,jsx,json,md}"], + "excludes": [ + ".cargo_home", + "deno_typescript/typescript", + "std/**/testdata", + "std/**/vendor", + "std/node_modules", + "std/hash/_wasm", + "target", + "third_party" + ], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.19.9.wasm", + "https://plugins.dprint.dev/json-0.4.1.wasm", + "https://plugins.dprint.dev/markdown-0.2.4.wasm" + ] +} diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 12d3a7aa7..000000000 --- a/.prettierignore +++ /dev/null @@ -1,9 +0,0 @@ -cli/compilers/wasm_wrap.js -cli/tests/error_syntax.js -cli/tests/badly_formatted.js -cli/tests/top_level_for_await.js -cli/tests/swc_syntax_error.ts -std/**/testdata -std/**/vendor -std/node_modules -std/hash/_wasm diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index 5b5bd9933..000000000 --- a/.prettierrc.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "proseWrap": "always" -} diff --git a/cli/js/colors.ts b/cli/js/colors.ts index eccb3567a..b98611bfa 100644 --- a/cli/js/colors.ts +++ b/cli/js/colors.ts @@ -70,7 +70,7 @@ const ANSI_PATTERN = new RegExp( "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", ].join("|"), - "g" + "g", ); export function stripColor(string: string): string { diff --git a/cli/js/compiler.ts b/cli/js/compiler.ts index fc75a7c10..7a56fe209 100644 --- a/cli/js/compiler.ts +++ b/cli/js/compiler.ts @@ -182,13 +182,15 @@ interface CompilerHostOptions { incremental?: boolean; } -type IncrementalCompilerHostOptions = Omit< - CompilerHostOptions, - "incremental" -> & { - rootNames?: string[]; - buildInfo?: string; -}; +type IncrementalCompilerHostOptions = + & Omit< + CompilerHostOptions, + "incremental" + > + & { + rootNames?: string[]; + buildInfo?: string; + }; interface HostConfigureResponse { ignoredOptions?: string[]; @@ -235,7 +237,9 @@ function getExtension(fileName: string, mediaType: MediaType): ts.Extension { case MediaType.Unknown: default: throw TypeError( - `Cannot resolve extension for "${fileName}" with mediaType "${MediaType[mediaType]}".` + `Cannot resolve extension for "${fileName}" with mediaType "${ + MediaType[mediaType] + }".`, ); } } @@ -259,7 +263,7 @@ function configure( defaultOptions: ts.CompilerOptions, source: string, path: string, - cwd: string + cwd: string, ): ConfigureResponse { const { config, error } = ts.parseConfigFileTextToJson(path, source); if (error) { @@ -267,7 +271,7 @@ function configure( } const { options, errors } = ts.convertCompilerOptionsFromJson( config.compilerOptions, - cwd + cwd, ); const ignoredOptions: string[] = []; for (const key of Object.keys(options)) { @@ -318,7 +322,7 @@ class SourceFile { static cacheResolvedUrl( resolvedUrl: string, rawModuleSpecifier: string, - containingFile?: string + containingFile?: string, ): void { containingFile = containingFile || ""; let innerCache = RESOLVED_SPECIFIER_CACHE.get(containingFile); @@ -331,7 +335,7 @@ class SourceFile { static getResolvedUrl( moduleSpecifier: string, - containingFile: string + containingFile: string, ): string | undefined { const containingCache = RESOLVED_SPECIFIER_CACHE.get(containingFile); if (containingCache) { @@ -399,14 +403,14 @@ class Host implements ts.CompilerHost { configure( cwd: string, path: string, - configurationText: string + configurationText: string, ): HostConfigureResponse { log("compiler::host.configure", path); const { options, ...result } = configure( this.#options, configurationText, path, - cwd + cwd, ); this.#options = options; return result; @@ -455,7 +459,7 @@ class Host implements ts.CompilerHost { fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void, - shouldCreateNewSourceFile?: boolean + shouldCreateNewSourceFile?: boolean, ): ts.SourceFile | undefined { log("compiler::host.getSourceFile", fileName); try { @@ -473,7 +477,7 @@ class Host implements ts.CompilerHost { sourceFile.tsSourceFile = ts.createSourceFile( tsSourceFileName, sourceFile.sourceCode, - languageVersion + languageVersion, ); sourceFile.tsSourceFile.version = sourceFile.versionHash; delete sourceFile.sourceCode; @@ -495,7 +499,7 @@ class Host implements ts.CompilerHost { resolveModuleNames( moduleNames: string[], - containingFile: string + containingFile: string, ): Array<ts.ResolvedModuleFull | undefined> { log("compiler::host.resolveModuleNames", { moduleNames, @@ -540,7 +544,7 @@ class Host implements ts.CompilerHost { data: string, _writeByteOrderMark: boolean, _onError?: (message: string) => void, - sourceFiles?: readonly ts.SourceFile[] + sourceFiles?: readonly ts.SourceFile[], ): void { log("compiler::host.writeFile", fileName); this.#writeFile(fileName, data, sourceFiles); @@ -588,23 +592,23 @@ ts.libMap.set("deno.unstable", "lib.deno.unstable.d.ts"); // are available in the future when needed. SNAPSHOT_HOST.getSourceFile( `${ASSETS}/lib.deno.ns.d.ts`, - ts.ScriptTarget.ESNext + ts.ScriptTarget.ESNext, ); SNAPSHOT_HOST.getSourceFile( `${ASSETS}/lib.deno.window.d.ts`, - ts.ScriptTarget.ESNext + ts.ScriptTarget.ESNext, ); SNAPSHOT_HOST.getSourceFile( `${ASSETS}/lib.deno.worker.d.ts`, - ts.ScriptTarget.ESNext + ts.ScriptTarget.ESNext, ); SNAPSHOT_HOST.getSourceFile( `${ASSETS}/lib.deno.shared_globals.d.ts`, - ts.ScriptTarget.ESNext + ts.ScriptTarget.ESNext, ); SNAPSHOT_HOST.getSourceFile( `${ASSETS}/lib.deno.unstable.d.ts`, - ts.ScriptTarget.ESNext + ts.ScriptTarget.ESNext, ); // We never use this program; it's only created @@ -624,7 +628,7 @@ const SYSTEM_LOADER = getAsset("system_loader.js"); const SYSTEM_LOADER_ES5 = getAsset("system_loader_es5.js"); function buildLocalSourceFileCache( - sourceFileMap: Record<string, SourceFileMapEntry> + sourceFileMap: Record<string, SourceFileMapEntry>, ): void { for (const entry of Object.values(sourceFileMap)) { assert(entry.sourceCode.length > 0); @@ -640,8 +644,7 @@ function buildLocalSourceFileCache( let mappedUrl = importDesc.resolvedSpecifier; const importedFile = sourceFileMap[importDesc.resolvedSpecifier]; assert(importedFile); - const isJsOrJsx = - importedFile.mediaType === MediaType.JavaScript || + const isJsOrJsx = importedFile.mediaType === MediaType.JavaScript || importedFile.mediaType === MediaType.JSX; // If JS or JSX perform substitution for types if available if (isJsOrJsx) { @@ -663,21 +666,21 @@ function buildLocalSourceFileCache( SourceFile.cacheResolvedUrl( fileRef.resolvedSpecifier.replace("memory://", ""), fileRef.specifier, - entry.url + entry.url, ); } for (const fileRef of entry.libDirectives) { SourceFile.cacheResolvedUrl( fileRef.resolvedSpecifier.replace("memory://", ""), fileRef.specifier, - entry.url + entry.url, ); } } } function buildSourceFileCache( - sourceFileMap: Record<string, SourceFileMapEntry> + sourceFileMap: Record<string, SourceFileMapEntry>, ): void { for (const entry of Object.values(sourceFileMap)) { SourceFile.addToCache({ @@ -700,8 +703,7 @@ function buildSourceFileCache( if (importedFile.redirect) { mappedUrl = importedFile.redirect; } - const isJsOrJsx = - importedFile.mediaType === MediaType.JavaScript || + const isJsOrJsx = importedFile.mediaType === MediaType.JavaScript || importedFile.mediaType === MediaType.JSX; // If JS or JSX perform substitution for types if available if (isJsOrJsx) { @@ -722,14 +724,14 @@ function buildSourceFileCache( SourceFile.cacheResolvedUrl( fileRef.resolvedSpecifier, fileRef.specifier, - entry.url + entry.url, ); } for (const fileRef of entry.libDirectives) { SourceFile.cacheResolvedUrl( fileRef.resolvedSpecifier, fileRef.specifier, - entry.url + entry.url, ); } } @@ -745,7 +747,7 @@ interface EmittedSource { type WriteFileCallback = ( fileName: string, data: string, - sourceFiles?: readonly ts.SourceFile[] + sourceFiles?: readonly ts.SourceFile[], ) => void; interface CompileWriteFileState { @@ -775,7 +777,7 @@ function createBundleWriteFile(state: BundleWriteFileState): WriteFileCallback { return function writeFile( _fileName: string, data: string, - sourceFiles?: readonly ts.SourceFile[] + sourceFiles?: readonly ts.SourceFile[], ): void { assert(sourceFiles != null); assert(state.host); @@ -785,18 +787,18 @@ function createBundleWriteFile(state: BundleWriteFileState): WriteFileCallback { state.rootNames[0], data, sourceFiles, - state.host.options.target ?? ts.ScriptTarget.ESNext + state.host.options.target ?? ts.ScriptTarget.ESNext, ); }; } function createCompileWriteFile( - state: CompileWriteFileState + state: CompileWriteFileState, ): WriteFileCallback { return function writeFile( fileName: string, data: string, - sourceFiles?: readonly ts.SourceFile[] + sourceFiles?: readonly ts.SourceFile[], ): void { const isBuildInfo = fileName === TS_BUILD_INFO; @@ -816,12 +818,12 @@ function createCompileWriteFile( } function createRuntimeCompileWriteFile( - state: CompileWriteFileState + state: CompileWriteFileState, ): WriteFileCallback { return function writeFile( fileName: string, data: string, - sourceFiles?: readonly ts.SourceFile[] + sourceFiles?: readonly ts.SourceFile[], ): void { assert(sourceFiles); assert(sourceFiles.length === 1); @@ -1020,14 +1022,14 @@ function performanceEnd(): Stats { // TODO(Bartlomieju): this check should be done in Rust; there should be no function processConfigureResponse( configResult: HostConfigureResponse, - configPath: string + configPath: string, ): ts.Diagnostic[] | undefined { const { ignoredOptions, diagnostics } = configResult; if (ignoredOptions) { console.warn( yellow(`Unsupported compiler options in "${configPath}"\n`) + cyan(` The following options were ignored:\n`) + - ` ${ignoredOptions.map((value): string => bold(value)).join(", ")}` + ` ${ignoredOptions.map((value): string => bold(value)).join(", ")}`, ); } return diagnostics; @@ -1130,7 +1132,7 @@ function buildBundle( rootName: string, data: string, sourceFiles: readonly ts.SourceFile[], - target: ts.ScriptTarget + target: ts.ScriptTarget, ): string { // when outputting to AMD and a single outfile, TypeScript makes up the module // specifiers which are used to define the modules, and doesn't expose them @@ -1162,8 +1164,7 @@ function buildBundle( ? `await __instantiate("${rootName}", true);\n` : `__instantiate("${rootName}", false);\n`; } - const es5Bundle = - target === ts.ScriptTarget.ES3 || + const es5Bundle = target === ts.ScriptTarget.ES3 || target === ts.ScriptTarget.ES5 || target === ts.ScriptTarget.ES2015 || target === ts.ScriptTarget.ES2016; @@ -1205,7 +1206,7 @@ function setRootExports(program: ts.Program, rootModule: string): void { sym.flags & ts.SymbolFlags.InterfaceExcludes || sym.flags & ts.SymbolFlags.TypeParameterExcludes || sym.flags & ts.SymbolFlags.TypeAliasExcludes - ) + ), ) .map((sym) => sym.getName()); } @@ -1408,7 +1409,7 @@ function compile({ ...program.getSemanticDiagnostics(), ]; diagnostics = diagnostics.filter( - ({ code }) => !ignoredDiagnostics.includes(code) + ({ code }) => !ignoredDiagnostics.includes(code), ); // We will only proceed with the emit if there are no diagnostics. @@ -1420,7 +1421,7 @@ function compile({ if (options.checkJs) { assert( emitResult.emitSkipped === false, - "Unexpected skip of the emit." + "Unexpected skip of the emit.", ); } // emitResult.diagnostics is `readonly` in TS3.5+ and can't be assigned @@ -1458,7 +1459,7 @@ function transpile({ DEFAULT_TRANSPILE_OPTIONS, configText, configPath, - cwd + cwd, ); const diagnostics = processConfigureResponse(response, configPath); if (diagnostics && diagnostics.length) { @@ -1598,7 +1599,7 @@ function bundle({ } function runtimeCompile( - request: RuntimeCompileRequest + request: RuntimeCompileRequest, ): RuntimeCompileResponse { const { options, rootNames, target, unstable, sourceFileMap } = request; @@ -1742,16 +1743,16 @@ function runtimeBundle(request: RuntimeBundleRequest): RuntimeBundleResponse { } function runtimeTranspile( - request: RuntimeTranspileRequest + request: RuntimeTranspileRequest, ): Promise<Record<string, TranspileOnlyResult>> { const result: Record<string, TranspileOnlyResult> = {}; const { sources, options } = request; const compilerOptions = options ? Object.assign( - {}, - DEFAULT_RUNTIME_TRANSPILE_OPTIONS, - convertCompilerOptions(options).options - ) + {}, + DEFAULT_RUNTIME_TRANSPILE_OPTIONS, + convertCompilerOptions(options).options, + ) : DEFAULT_RUNTIME_TRANSPILE_OPTIONS; for (const [fileName, inputText] of Object.entries(sources)) { @@ -1760,7 +1761,7 @@ function runtimeTranspile( { fileName, compilerOptions, - } + }, ); result[fileName] = { source, map }; } @@ -1807,7 +1808,7 @@ async function tsCompilerOnMessage({ log( `!!! unhandled CompilerRequestType: ${ (request as CompilerRequest).type - } (${CompilerRequestType[(request as CompilerRequest).type]})` + } (${CompilerRequestType[(request as CompilerRequest).type]})`, ); } // Shutdown after single request diff --git a/cli/js/compiler_api.ts b/cli/js/compiler_api.ts index 8a50e0b3d..e0488b7f6 100644 --- a/cli/js/compiler_api.ts +++ b/cli/js/compiler_api.ts @@ -18,7 +18,7 @@ function checkRelative(specifier: string): string { // TODO(bartlomieju): change return type to interface? export function transpileOnly( sources: Record<string, string>, - options: CompilerOptions = {} + options: CompilerOptions = {}, ): Promise<Record<string, TranspileOnlyResult>> { util.log("Deno.transpileOnly", { sources: Object.keys(sources), options }); const payload = { @@ -32,7 +32,7 @@ export function transpileOnly( export async function compile( rootName: string, sources?: Record<string, string>, - options: CompilerOptions = {} + options: CompilerOptions = {}, ): Promise<[DiagnosticItem[] | undefined, Record<string, string>]> { const payload = { rootName: sources ? rootName : checkRelative(rootName), @@ -47,8 +47,9 @@ export async function compile( }); const result = await runtimeCompilerOps.compile(payload); util.assert(result.emitMap); - const maybeDiagnostics = - result.diagnostics.length === 0 ? undefined : result.diagnostics; + const maybeDiagnostics = result.diagnostics.length === 0 + ? undefined + : result.diagnostics; const emitMap: Record<string, string> = {}; @@ -63,7 +64,7 @@ export async function compile( export async function bundle( rootName: string, sources?: Record<string, string>, - options: CompilerOptions = {} + options: CompilerOptions = {}, ): Promise<[DiagnosticItem[] | undefined, string]> { const payload = { rootName: sources ? rootName : checkRelative(rootName), @@ -78,7 +79,8 @@ export async function bundle( }); const result = await runtimeCompilerOps.compile(payload); util.assert(result.output); - const maybeDiagnostics = - result.diagnostics.length === 0 ? undefined : result.diagnostics; + const maybeDiagnostics = result.diagnostics.length === 0 + ? undefined + : result.diagnostics; return [maybeDiagnostics, result.output]; } diff --git a/cli/js/diagnostics_util.ts b/cli/js/diagnostics_util.ts index 3e0bfde27..fc2684baf 100644 --- a/cli/js/diagnostics_util.ts +++ b/cli/js/diagnostics_util.ts @@ -91,7 +91,7 @@ function transformMessageText(messageText: string, code: number): string { const suggestion = messageText.match(suggestionMessagePattern); const replacedMessageText = messageText.replace( suggestionMessagePattern, - "" + "", ); if (suggestion && unstableDenoGlobalProperties.includes(property)) { const suggestedProperty = suggestion[1]; @@ -113,7 +113,7 @@ interface SourceInformation { } function fromDiagnosticCategory( - category: ts.DiagnosticCategory + category: ts.DiagnosticCategory, ): DiagnosticCategory { switch (category) { case ts.DiagnosticCategory.Error: @@ -126,7 +126,9 @@ function fromDiagnosticCategory( return DiagnosticCategory.Warning; default: throw new Error( - `Unexpected DiagnosticCategory: "${category}"/"${ts.DiagnosticCategory[category]}"` + `Unexpected DiagnosticCategory: "${category}"/"${ + ts.DiagnosticCategory[category] + }"`, ); } } @@ -134,7 +136,7 @@ function fromDiagnosticCategory( function getSourceInformation( sourceFile: ts.SourceFile, start: number, - length: number + length: number, ): SourceInformation { const scriptResourceName = sourceFile.fileName; const { @@ -142,16 +144,16 @@ function getSourceInformation( character: startColumn, } = sourceFile.getLineAndCharacterOfPosition(start); const endPosition = sourceFile.getLineAndCharacterOfPosition(start + length); - const endColumn = - lineNumber === endPosition.line ? endPosition.character : startColumn; + const endColumn = lineNumber === endPosition.line + ? endPosition.character + : startColumn; const lastLineInFile = sourceFile.getLineAndCharacterOfPosition( - sourceFile.text.length + sourceFile.text.length, ).line; const lineStart = sourceFile.getPositionOfLineAndCharacter(lineNumber, 0); - const lineEnd = - lineNumber < lastLineInFile - ? sourceFile.getPositionOfLineAndCharacter(lineNumber + 1, 0) - : sourceFile.text.length; + const lineEnd = lineNumber < lastLineInFile + ? sourceFile.getPositionOfLineAndCharacter(lineNumber + 1, 0) + : sourceFile.text.length; const sourceLine = sourceFile.text .slice(lineStart, lineEnd) .replace(/\s+$/g, "") @@ -166,7 +168,7 @@ function getSourceInformation( } function fromDiagnosticMessageChain( - messageChain: ts.DiagnosticMessageChain[] | undefined + messageChain: ts.DiagnosticMessageChain[] | undefined, ): DiagnosticMessageChain[] | undefined { if (!messageChain) { return undefined; @@ -184,7 +186,7 @@ function fromDiagnosticMessageChain( } function parseDiagnostic( - item: ts.Diagnostic | ts.DiagnosticRelatedInformation + item: ts.Diagnostic | ts.DiagnosticRelatedInformation, ): DiagnosticItem { const { messageText, @@ -194,12 +196,12 @@ function parseDiagnostic( start: startPosition, length, } = item; - const sourceInfo = - file && startPosition && length - ? getSourceInformation(file, startPosition, length) - : undefined; - const endPosition = - startPosition && length ? startPosition + length : undefined; + const sourceInfo = file && startPosition && length + ? getSourceInformation(file, startPosition, length) + : undefined; + const endPosition = startPosition && length + ? startPosition + length + : undefined; const category = fromDiagnosticCategory(sourceCategory); let message: string; @@ -224,7 +226,7 @@ function parseDiagnostic( } function parseRelatedInformation( - relatedInformation: readonly ts.DiagnosticRelatedInformation[] + relatedInformation: readonly ts.DiagnosticRelatedInformation[], ): DiagnosticItem[] { const result: DiagnosticItem[] = []; for (const item of relatedInformation) { @@ -234,14 +236,14 @@ function parseRelatedInformation( } export function fromTypeScriptDiagnostic( - diagnostics: readonly ts.Diagnostic[] + diagnostics: readonly ts.Diagnostic[], ): Diagnostic { const items: DiagnosticItem[] = []; for (const sourceDiagnostic of diagnostics) { const item: DiagnosticItem = parseDiagnostic(sourceDiagnostic); if (sourceDiagnostic.relatedInformation) { item.relatedInformation = parseRelatedInformation( - sourceDiagnostic.relatedInformation + sourceDiagnostic.relatedInformation, ); } items.push(item); diff --git a/cli/js/error_stack.ts b/cli/js/error_stack.ts index 4c46675ca..97ce00f3a 100644 --- a/cli/js/error_stack.ts +++ b/cli/js/error_stack.ts @@ -149,7 +149,7 @@ function callSiteToString(callSite: CallSite, internal = false): string { } if (isPromiseAll) { result += colors.bold( - colors.italic(black(`Promise.all (index ${callSite.getPromiseIndex()})`)) + colors.italic(black(`Promise.all (index ${callSite.getPromiseIndex()})`)), ); return result; } @@ -218,7 +218,7 @@ function prepareStackTrace( __callSiteEvals: CallSiteEval[]; __formattedFrames: string[]; }, - callSites: CallSite[] + callSites: CallSite[], ): string { const mappedCallSites = callSites.map( (callSite): CallSite => { @@ -232,11 +232,11 @@ function prepareStackTrace( fileName, lineNumber, columnNumber, - }) + }), ); } return callSite; - } + }, ); Object.defineProperties(error, { __callSiteEvals: { value: [], configurable: true }, diff --git a/cli/js/files.ts b/cli/js/files.ts index 3afcb4878..e9f12a489 100644 --- a/cli/js/files.ts +++ b/cli/js/files.ts @@ -23,7 +23,7 @@ export type { OpenOptions } from "./ops/fs/open.ts"; export function openSync( path: string | URL, - options: OpenOptions = { read: true } + options: OpenOptions = { read: true }, ): File { checkOpenOptions(options); const rid = opOpenSync(path, options); @@ -32,7 +32,7 @@ export function openSync( export async function open( path: string | URL, - options: OpenOptions = { read: true } + options: OpenOptions = { read: true }, ): Promise<File> { checkOpenOptions(options); const rid = await opOpen(path, options); @@ -163,7 +163,7 @@ function checkOpenOptions(options: OpenOptions): void { if (createOrCreateNewWithoutWriteOrAppend) { throw new Error( - "'create' or 'createNew' options require 'write' or 'append' option" + "'create' or 'createNew' options require 'write' or 'append' option", ); } } diff --git a/cli/js/globals.ts b/cli/js/globals.ts index ff2ff8f4d..aa826f63a 100644 --- a/cli/js/globals.ts +++ b/cli/js/globals.ts @@ -104,7 +104,7 @@ declare global { evalContext( code: string, - scriptName?: string + scriptName?: string, ): [unknown, EvalErrorInfo | null]; formatError: (e: Error) => string; @@ -150,12 +150,12 @@ declare global { var onerror: | (( - msg: string, - source: string, - lineno: number, - colno: number, - e: Event - ) => boolean | void) + msg: string, + source: string, + lineno: number, + colno: number, + e: Event, + ) => boolean | void) | undefined; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -218,7 +218,7 @@ export const windowOrWorkerGlobalScopeProperties = { AbortSignal: nonEnumerable(abortSignal.AbortSignalImpl), Blob: nonEnumerable(blob.DenoBlob), ByteLengthQueuingStrategy: nonEnumerable( - queuingStrategy.ByteLengthQueuingStrategyImpl + queuingStrategy.ByteLengthQueuingStrategyImpl, ), CountQueuingStrategy: nonEnumerable(queuingStrategy.CountQueuingStrategyImpl), crypto: readOnly(csprng), @@ -254,10 +254,10 @@ export function setEventTargetData(value: any): void { export const eventTargetProperties = { addEventListener: readOnly( - eventTarget.EventTargetImpl.prototype.addEventListener + eventTarget.EventTargetImpl.prototype.addEventListener, ), dispatchEvent: readOnly(eventTarget.EventTargetImpl.prototype.dispatchEvent), removeEventListener: readOnly( - eventTarget.EventTargetImpl.prototype.removeEventListener + eventTarget.EventTargetImpl.prototype.removeEventListener, ), }; diff --git a/cli/js/io.ts b/cli/js/io.ts index 2686fd3cb..b2e6499b8 100644 --- a/cli/js/io.ts +++ b/cli/js/io.ts @@ -55,7 +55,7 @@ export async function copy( dst: Writer, options?: { bufSize?: number; - } + }, ): Promise<number> { let n = 0; const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE; @@ -80,7 +80,7 @@ export async function* iter( r: Reader, options?: { bufSize?: number; - } + }, ): AsyncIterableIterator<Uint8Array> { const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE; const b = new Uint8Array(bufSize); @@ -98,7 +98,7 @@ export function* iterSync( r: ReaderSync, options?: { bufSize?: number; - } + }, ): IterableIterator<Uint8Array> { const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE; const b = new Uint8Array(bufSize); diff --git a/cli/js/lib.deno.ns.d.ts b/cli/js/lib.deno.ns.d.ts index 47402187d..962179381 100644 --- a/cli/js/lib.deno.ns.d.ts +++ b/cli/js/lib.deno.ns.d.ts @@ -34,7 +34,7 @@ declare interface Performance { * associated name (a "measure"). */ measure( measureName: string, - options?: PerformanceMeasureOptions + options?: PerformanceMeasureOptions, ): PerformanceMeasure; } @@ -394,7 +394,7 @@ declare namespace Deno { dst: Writer, options?: { bufSize?: number; - } + }, ): Promise<number>; /** Turns a Reader, `r`, into an async iterator. @@ -430,7 +430,7 @@ declare namespace Deno { r: Reader, options?: { bufSize?: number; - } + }, ): AsyncIterableIterator<Uint8Array>; /** Turns a ReaderSync, `r`, into an iterator. @@ -466,7 +466,7 @@ declare namespace Deno { r: ReaderSync, options?: { bufSize?: number; - } + }, ): IterableIterator<Uint8Array>; /** Synchronously open a file and return an instance of `Deno.File`. The @@ -499,7 +499,7 @@ declare namespace Deno { */ export function open( path: string | URL, - options?: OpenOptions + options?: OpenOptions, ): Promise<File>; /** Creates a file if none exists or truncates an existing file and returns @@ -641,7 +641,7 @@ declare namespace Deno { export function seekSync( rid: number, offset: number, - whence: SeekMode + whence: SeekMode, ): number; /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`. @@ -673,7 +673,7 @@ declare namespace Deno { export function seek( rid: number, offset: number, - whence: SeekMode + whence: SeekMode, ): Promise<number>; /** Close the given resource ID (rid) which has been previously opened, such @@ -973,7 +973,7 @@ declare namespace Deno { * Requires `allow-write` permission. */ export function mkdir( path: string | URL, - options?: MkdirOptions + options?: MkdirOptions, ): Promise<void>; export interface MakeTempOptions { @@ -1132,7 +1132,7 @@ declare namespace Deno { export function chownSync( path: string | URL, uid: number | null, - gid: number | null + gid: number | null, ): void; /** Change owner of a regular file or directory. This functionality @@ -1153,7 +1153,7 @@ declare namespace Deno { export function chown( path: string | URL, uid: number | null, - gid: number | null + gid: number | null, ): Promise<void>; export interface RemoveOptions { @@ -1188,7 +1188,7 @@ declare namespace Deno { * Requires `allow-write` permission. */ export function remove( path: string | URL, - options?: RemoveOptions + options?: RemoveOptions, ): Promise<void>; /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or @@ -1417,7 +1417,7 @@ declare namespace Deno { * Requires `allow-write` permission on toPath. */ export function copyFileSync( fromPath: string | URL, - toPath: string | URL + toPath: string | URL, ): void; /** Copies the contents and permissions of one file to another specified path, @@ -1432,7 +1432,7 @@ declare namespace Deno { * Requires `allow-write` permission on toPath. */ export function copyFile( fromPath: string | URL, - toPath: string | URL + toPath: string | URL, ): Promise<void>; /** Returns the full path destination of the named symbolic link. @@ -1538,7 +1538,7 @@ declare namespace Deno { export function writeFileSync( path: string | URL, data: Uint8Array, - options?: WriteFileOptions + options?: WriteFileOptions, ): void; /** Write `data` to the given `path`, by default creating a new file if needed, @@ -1558,7 +1558,7 @@ declare namespace Deno { export function writeFile( path: string | URL, data: Uint8Array, - options?: WriteFileOptions + options?: WriteFileOptions, ): Promise<void>; /** Synchronously write string `data` to the given `path`, by default creating a new file if needed, @@ -1573,7 +1573,7 @@ declare namespace Deno { export function writeTextFileSync( path: string | URL, data: string, - options?: WriteFileOptions + options?: WriteFileOptions, ): void; /** Asynchronously write string `data` to the given `path`, by default creating a new file if needed, @@ -1588,7 +1588,7 @@ declare namespace Deno { export function writeTextFile( path: string | URL, data: string, - options?: WriteFileOptions + options?: WriteFileOptions, ): Promise<void>; /** Synchronously truncates or extends the specified file, to reach the @@ -1692,7 +1692,7 @@ declare namespace Deno { * * Requires `allow-net` permission. */ export function listen( - options: ListenOptions & { transport?: "tcp" } + options: ListenOptions & { transport?: "tcp" }, ): Listener; export interface ListenTlsOptions extends ListenOptions { @@ -1844,20 +1844,17 @@ declare namespace Deno { */ export function watchFs( paths: string | string[], - options?: { recursive: boolean } + options?: { recursive: boolean }, ): AsyncIterableIterator<FsEvent>; export class Process<T extends RunOptions = RunOptions> { readonly rid: number; readonly pid: number; - readonly stdin: T["stdin"] extends "piped" - ? Writer & Closer + readonly stdin: T["stdin"] extends "piped" ? Writer & Closer : (Writer & Closer) | null; - readonly stdout: T["stdout"] extends "piped" - ? Reader & Closer + readonly stdout: T["stdout"] extends "piped" ? Reader & Closer : (Reader & Closer) | null; - readonly stderr: T["stderr"] extends "piped" - ? Reader & Closer + readonly stderr: T["stderr"] extends "piped" ? Reader & Closer : (Reader & Closer) | null; /** Resolves to the current status of the process. */ status(): Promise<ProcessStatus>; @@ -1886,15 +1883,15 @@ declare namespace Deno { export type ProcessStatus = | { - success: true; - code: 0; - signal?: undefined; - } + success: true; + code: 0; + signal?: undefined; + } | { - success: false; - code: number; - signal?: number; - }; + success: false; + code: number; + signal?: number; + }; export interface RunOptions { /** Arguments to pass. Note, the first element needs to be a path to the diff --git a/cli/js/lib.deno.shared_globals.d.ts b/cli/js/lib.deno.shared_globals.d.ts index f37dfa366..c77f1ea0e 100644 --- a/cli/js/lib.deno.shared_globals.d.ts +++ b/cli/js/lib.deno.shared_globals.d.ts @@ -31,7 +31,7 @@ declare namespace WebAssembly { * its first `WebAssembly.Instance`. */ function instantiate( bufferSource: BufferSource, - importObject?: object + importObject?: object, ): Promise<WebAssemblyInstantiatedSource>; /** Takes an already-compiled `WebAssembly.Module` and returns a `Promise` @@ -39,7 +39,7 @@ declare namespace WebAssembly { * the `Module` has already been compiled. */ function instantiate( module: Module, - importObject?: object + importObject?: object, ): Promise<Instance>; /** Compiles and instantiates a WebAssembly module directly from a streamed @@ -47,7 +47,7 @@ declare namespace WebAssembly { * code. */ function instantiateStreaming( source: Promise<Response>, - importObject?: object + importObject?: object, ): Promise<WebAssemblyInstantiatedSource>; /** Validates a given typed array of WebAssembly binary code, returning @@ -73,7 +73,7 @@ declare namespace WebAssembly { * custom sections in the module with the given string name. */ static customSections( moduleObject: Module, - sectionName: string + sectionName: string, ): ArrayBuffer; /** Given a `Module`, returns an array containing descriptions of all the @@ -246,7 +246,7 @@ declare var crypto: Crypto; declare function addEventListener( type: string, callback: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions | undefined + options?: boolean | AddEventListenerOptions | undefined, ): void; /** Dispatches an event in the global scope, synchronously invoking any @@ -267,7 +267,7 @@ declare function dispatchEvent(event: Event): boolean; declare function removeEventListener( type: string, callback: EventListenerOrEventListenerObject | null, - options?: boolean | EventListenerOptions | undefined + options?: boolean | EventListenerOptions | undefined, ): void; interface DomIterable<K, V> { @@ -277,7 +277,7 @@ interface DomIterable<K, V> { [Symbol.iterator](): IterableIterator<[K, V]>; forEach( callback: (value: V, key: K, parent: this) => void, - thisArg?: any + thisArg?: any, ): void; } @@ -398,7 +398,7 @@ interface ReadableStream<R = any> { writable: WritableStream<R>; readable: ReadableStream<T>; }, - options?: PipeOptions + options?: PipeOptions, ): ReadableStream<T>; pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>; tee(): [ReadableStream<R>, ReadableStream<R>]; @@ -411,11 +411,11 @@ declare var ReadableStream: { prototype: ReadableStream; new ( underlyingSource: UnderlyingByteSource, - strategy?: { highWaterMark?: number; size?: undefined } + strategy?: { highWaterMark?: number; size?: undefined }, ): ReadableStream<Uint8Array>; new <R = any>( underlyingSource?: UnderlyingSource<R>, - strategy?: QueuingStrategy<R> + strategy?: QueuingStrategy<R>, ): ReadableStream<R>; }; @@ -428,9 +428,11 @@ interface WritableStreamDefaultControllerStartCallback { } interface WritableStreamDefaultControllerWriteCallback<W> { - (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike< - void - >; + (chunk: W, controller: WritableStreamDefaultController): + | void + | PromiseLike< + void + >; } interface WritableStreamErrorCallback { @@ -451,7 +453,7 @@ interface UnderlyingSink<W = any> { declare class WritableStream<W = any> { constructor( underlyingSink?: UnderlyingSink<W>, - strategy?: QueuingStrategy<W> + strategy?: QueuingStrategy<W>, ); readonly locked: boolean; abort(reason?: any): Promise<void>; @@ -485,7 +487,7 @@ declare class TransformStream<I = any, O = any> { constructor( transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, - readableStrategy?: QueuingStrategy<O> + readableStrategy?: QueuingStrategy<O>, ); readonly readable: ReadableStream<O>; readonly writable: WritableStream<I>; @@ -513,7 +515,7 @@ interface TransformStreamDefaultControllerCallback<O> { interface TransformStreamDefaultControllerTransformCallback<I, O> { ( chunk: I, - controller: TransformStreamDefaultController<O> + controller: TransformStreamDefaultController<O>, ): void | PromiseLike<void>; } @@ -589,7 +591,7 @@ declare class Console { options?: Partial<{ depth: number; indentLevel: number; - }> + }>, ) => void; /** From MDN: @@ -609,7 +611,7 @@ declare class Console { depth: number; colors: boolean; indentLevel: number; - }> + }>, ) => void; /** Writes the arguments to stdout */ @@ -650,9 +652,9 @@ declare interface Crypto { | Float32Array | Float64Array | DataView - | null + | null, >( - array: T + array: T, ): T; } @@ -724,7 +726,7 @@ interface Headers { set(name: string, value: string): void; forEach( callbackfn: (value: string, key: string, parent: Headers) => void, - thisArg?: any + thisArg?: any, ): void; } @@ -762,7 +764,7 @@ interface Headers extends DomIterable<string, string> { values(): IterableIterator<string>; forEach( callbackfn: (value: string, key: string, parent: this) => void, - thisArg?: any + thisArg?: any, ): void; /** The Symbol.iterator well-known symbol specifies the default * iterator for this Headers object @@ -1023,7 +1025,7 @@ declare const Response: { */ declare function fetch( input: Request | URL | string, - init?: RequestInit + init?: RequestInit, ): Promise<Response>; /** Decodes a string of data which has been encoded using base-64 encoding. @@ -1047,7 +1049,7 @@ declare class TextDecoder { readonly ignoreBOM = false; constructor( label?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } + options?: { fatal?: boolean; ignoreBOM?: boolean }, ); /** Returns the result of running encoding's decoder. */ decode(input?: BufferSource, options?: { stream?: false }): string; @@ -1061,7 +1063,7 @@ declare class TextEncoder { encode(input?: string): Uint8Array; encodeInto( input: string, - dest: Uint8Array + dest: Uint8Array, ): { read: number; written: number }; readonly [Symbol.toStringTag]: string; } @@ -1148,7 +1150,7 @@ interface URLSearchParams { */ forEach( callbackfn: (value: string, key: string, parent: this) => void, - thisArg?: any + thisArg?: any, ): void; /** Returns an iterator allowing to go through all keys contained @@ -1211,7 +1213,7 @@ interface URLSearchParams { declare const URLSearchParams: { prototype: URLSearchParams; new ( - init?: string[][] | Record<string, string> | string | URLSearchParams + init?: string[][] | Record<string, string> | string | URLSearchParams, ): URLSearchParams; toString(): string; }; @@ -1330,7 +1332,7 @@ declare class Worker extends EventTarget { * */ deno?: boolean; - } + }, ); postMessage(message: any, transfer: ArrayBuffer[]): void; postMessage(message: any, options?: PostMessageOptions): void; @@ -1357,14 +1359,14 @@ declare interface Performance { * associated name (a "measure"). */ measure( measureName: string, - options?: PerformanceMeasureOptions + options?: PerformanceMeasureOptions, ): PerformanceMeasure; /** Stores the `DOMHighResTimeStamp` duration between two marks along with the * associated name (a "measure"). */ measure( measureName: string, startMark?: string, - endMark?: string + endMark?: string, ): PerformanceMeasure; /** Returns a current time from Deno's start in milliseconds. @@ -1540,7 +1542,7 @@ declare class EventTarget { addEventListener( type: string, listener: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; /** Dispatches a synthetic event event to target and returns true if either * event's cancelable attribute value is false or its preventDefault() method @@ -1551,7 +1553,7 @@ declare class EventTarget { removeEventListener( type: string, callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean + options?: EventListenerOptions | boolean, ): void; [Symbol.toStringTag]: string; } @@ -1622,22 +1624,22 @@ interface AbortSignal extends EventTarget { addEventListener<K extends keyof AbortSignalEventMap>( type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; addEventListener( type: string, listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; removeEventListener<K extends keyof AbortSignalEventMap>( type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, - options?: boolean | EventListenerOptions + options?: boolean | EventListenerOptions, ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions + options?: boolean | EventListenerOptions, ): void; } diff --git a/cli/js/lib.deno.unstable.d.ts b/cli/js/lib.deno.unstable.d.ts index 05508a363..d23536c42 100644 --- a/cli/js/lib.deno.unstable.d.ts +++ b/cli/js/lib.deno.unstable.d.ts @@ -52,7 +52,7 @@ declare namespace Deno { * ``` */ export function consoleSize( - rid: number + rid: number, ): { columns: number; rows: number; @@ -77,7 +77,7 @@ declare namespace Deno { export function symlinkSync( oldpath: string, newpath: string, - options?: SymlinkOptions + options?: SymlinkOptions, ): void; /** **UNSTABLE**: This API needs a security review. @@ -95,7 +95,7 @@ declare namespace Deno { export function symlink( oldpath: string, newpath: string, - options?: SymlinkOptions + options?: SymlinkOptions, ): Promise<void>; /** **Unstable** There are questions around which permission this needs. And @@ -454,7 +454,7 @@ declare namespace Deno { */ export function transpileOnly( sources: Record<string, string>, - options?: CompilerOptions + options?: CompilerOptions, ): Promise<Record<string, TranspileOnlyResult>>; /** **UNSTABLE**: new API, yet to be vetted. @@ -492,7 +492,7 @@ declare namespace Deno { export function compile( rootName: string, sources?: Record<string, string>, - options?: CompilerOptions + options?: CompilerOptions, ): Promise<[DiagnosticItem[] | undefined, Record<string, string>]>; /** **UNSTABLE**: new API, yet to be vetted. @@ -535,7 +535,7 @@ declare namespace Deno { export function bundle( rootName: string, sources?: Record<string, string>, - options?: CompilerOptions + options?: CompilerOptions, ): Promise<[DiagnosticItem[] | undefined, string]>; /** **UNSTABLE**: Should not have same name as `window.location` type. */ @@ -657,7 +657,7 @@ declare namespace Deno { constructor(signal: typeof Deno.Signal); then<T, S>( f: (v: void) => T | Promise<T>, - g?: (v: void) => S | Promise<S> + g?: (v: void) => S | Promise<S>, ): Promise<T | S>; next(): Promise<IteratorResult<void>>; [Symbol.asyncIterator](): AsyncIterableIterator<void>; @@ -777,7 +777,7 @@ declare namespace Deno { export function utimeSync( path: string, atime: number | Date, - mtime: number | Date + mtime: number | Date, ): void; /** **UNSTABLE**: needs investigation into high precision time. @@ -794,7 +794,7 @@ declare namespace Deno { export function utime( path: string, atime: number | Date, - mtime: number | Date + mtime: number | Date, ): Promise<void>; /** **UNSTABLE**: Under consideration to remove `ShutdownMode` entirely. @@ -860,7 +860,7 @@ declare namespace Deno { * * Requires `allow-read` and `allow-write` permission. */ export function listen( - options: UnixListenOptions & { transport: "unix" } + options: UnixListenOptions & { transport: "unix" }, ): Listener; /** **UNSTABLE**: new API, yet to be vetted @@ -881,7 +881,7 @@ declare namespace Deno { * * Requires `allow-net` permission. */ export function listenDatagram( - options: ListenOptions & { transport: "udp" } + options: ListenOptions & { transport: "udp" }, ): DatagramConn; /** **UNSTABLE**: new API, yet to be vetted @@ -897,7 +897,7 @@ declare namespace Deno { * * Requires `allow-read` and `allow-write` permission. */ export function listenDatagram( - options: UnixListenOptions & { transport: "unixpacket" } + options: UnixListenOptions & { transport: "unixpacket" }, ): DatagramConn; export interface UnixConnectOptions { @@ -921,7 +921,7 @@ declare namespace Deno { * * Requires `allow-net` permission for "tcp" and `allow-read` for "unix". */ export function connect( - options: ConnectOptions | UnixConnectOptions + options: ConnectOptions | UnixConnectOptions, ): Promise<Conn>; export interface StartTlsOptions { @@ -950,7 +950,7 @@ declare namespace Deno { */ export function startTls( conn: Conn, - options?: StartTlsOptions + options?: StartTlsOptions, ): Promise<Conn>; /** **UNSTABLE**: The `signo` argument may change to require the Deno.Signal diff --git a/cli/js/lib.deno.worker.d.ts b/cli/js/lib.deno.worker.d.ts index 5343646f6..95aa16139 100644 --- a/cli/js/lib.deno.worker.d.ts +++ b/cli/js/lib.deno.worker.d.ts @@ -22,12 +22,12 @@ declare const self: DedicatedWorkerGlobalScope & typeof globalThis; declare let onmessage: ((e: { data: any }) => Promise<void> | void) | undefined; declare let onerror: | (( - msg: string, - source: string, - lineno: number, - colno: number, - e: Event - ) => boolean | void) + msg: string, + source: string, + lineno: number, + colno: number, + e: Event, + ) => boolean | void) | undefined; declare const close: typeof __workerMain.close; declare const name: typeof __workerMain.name; diff --git a/cli/js/net.ts b/cli/js/net.ts index a4aad0254..07feb89fe 100644 --- a/cli/js/net.ts +++ b/cli/js/net.ts @@ -37,7 +37,7 @@ export class ConnImpl implements Conn { constructor( readonly rid: number, readonly remoteAddr: Addr, - readonly localAddr: Addr + readonly localAddr: Addr, ) {} write(p: Uint8Array): Promise<number> { @@ -97,7 +97,7 @@ export class DatagramImpl implements DatagramConn { constructor( readonly rid: number, readonly addr: Addr, - public bufSize: number = 1024 + public bufSize: number = 1024, ) {} async receive(p?: Uint8Array): Promise<[Uint8Array, Addr]> { @@ -105,7 +105,7 @@ export class DatagramImpl implements DatagramConn { const { size, remoteAddr } = await netOps.receive( this.rid, this.addr.transport, - buf + buf, ); const sub = buf.subarray(0, size); return [sub, remoteAddr]; @@ -150,7 +150,7 @@ export interface ListenOptions { } export function listen( - options: ListenOptions & { transport?: "tcp" } + options: ListenOptions & { transport?: "tcp" }, ): Listener; export function listen(options: ListenOptions): Listener { const res = netOps.listen({ @@ -174,7 +174,7 @@ export interface UnixConnectOptions { export async function connect(options: UnixConnectOptions): Promise<Conn>; export async function connect(options: ConnectOptions): Promise<Conn>; export async function connect( - options: ConnectOptions | UnixConnectOptions + options: ConnectOptions | UnixConnectOptions, ): Promise<Conn> { let res; diff --git a/cli/js/net_unstable.ts b/cli/js/net_unstable.ts index 9a1d1f568..cedb68b23 100644 --- a/cli/js/net_unstable.ts +++ b/cli/js/net_unstable.ts @@ -30,10 +30,10 @@ export interface UnixConnectOptions { } export function listen( - options: ListenOptions & { transport?: "tcp" } + options: ListenOptions & { transport?: "tcp" }, ): Listener; export function listen( - options: UnixListenOptions & { transport: "unix" } + options: UnixListenOptions & { transport: "unix" }, ): Listener; export function listen(options: ListenOptions | UnixListenOptions): Listener { if (options.transport === "unix") { @@ -45,13 +45,13 @@ export function listen(options: ListenOptions | UnixListenOptions): Listener { } export function listenDatagram( - options: ListenOptions & { transport: "udp" } + options: ListenOptions & { transport: "udp" }, ): DatagramConn; export function listenDatagram( - options: UnixListenOptions & { transport: "unixpacket" } + options: UnixListenOptions & { transport: "unixpacket" }, ): DatagramConn; export function listenDatagram( - options: ListenOptions | UnixListenOptions + options: ListenOptions | UnixListenOptions, ): DatagramConn { let res; if (options.transport === "unixpacket") { @@ -68,7 +68,7 @@ export function listenDatagram( } export async function connect( - options: ConnectOptions | UnixConnectOptions + options: ConnectOptions | UnixConnectOptions, ): Promise<Conn> { if (options.transport === "unix") { const res = await netOps.connect(options); diff --git a/cli/js/ops/dispatch_minimal.ts b/cli/js/ops/dispatch_minimal.ts index ca50b00e9..cc1d97e20 100644 --- a/cli/js/ops/dispatch_minimal.ts +++ b/cli/js/ops/dispatch_minimal.ts @@ -37,7 +37,7 @@ export function recordFromBufMinimal(ui8: Uint8Array): RecordMinimal { const buf32 = new Int32Array( header.buffer, header.byteOffset, - header.byteLength / 4 + header.byteLength / 4, ); const promiseId = buf32[0]; const arg = buf32[1]; @@ -71,7 +71,7 @@ const scratch32 = new Int32Array(3); const scratchBytes = new Uint8Array( scratch32.buffer, scratch32.byteOffset, - scratch32.byteLength + scratch32.byteLength, ); util.assert(scratchBytes.byteLength === scratch32.length * 4); @@ -87,7 +87,7 @@ export function asyncMsgFromRust(ui8: Uint8Array): void { export async function sendAsyncMinimal( opName: string, arg: number, - zeroCopy: Uint8Array + zeroCopy: Uint8Array, ): Promise<number> { const promiseId = nextPromiseId(); // AKA cmdId scratch32[0] = promiseId; @@ -111,7 +111,7 @@ export async function sendAsyncMinimal( export function sendSyncMinimal( opName: string, arg: number, - zeroCopy: Uint8Array + zeroCopy: Uint8Array, ): number { scratch32[0] = 0; // promiseId 0 indicates sync scratch32[1] = arg; diff --git a/cli/js/ops/fetch.ts b/cli/js/ops/fetch.ts index 2f881cc02..e349b9de5 100644 --- a/cli/js/ops/fetch.ts +++ b/cli/js/ops/fetch.ts @@ -17,7 +17,7 @@ export interface FetchResponse { export function fetch( args: FetchRequest, - body?: ArrayBufferView + body?: ArrayBufferView, ): Promise<FetchResponse> { let zeroCopy; if (body != null) { diff --git a/cli/js/ops/fs/chown.ts b/cli/js/ops/fs/chown.ts index 52735e097..054b61f6c 100644 --- a/cli/js/ops/fs/chown.ts +++ b/cli/js/ops/fs/chown.ts @@ -6,7 +6,7 @@ import { pathFromURL } from "../../util.ts"; export function chownSync( path: string | URL, uid: number | null, - gid: number | null + gid: number | null, ): void { sendSync("op_chown", { path: pathFromURL(path), uid, gid }); } @@ -14,7 +14,7 @@ export function chownSync( export async function chown( path: string | URL, uid: number | null, - gid: number | null + gid: number | null, ): Promise<void> { await sendAsync("op_chown", { path: pathFromURL(path), uid, gid }); } diff --git a/cli/js/ops/fs/copy_file.ts b/cli/js/ops/fs/copy_file.ts index fcb147bdd..d2d2d5688 100644 --- a/cli/js/ops/fs/copy_file.ts +++ b/cli/js/ops/fs/copy_file.ts @@ -5,7 +5,7 @@ import { pathFromURL } from "../../util.ts"; export function copyFileSync( fromPath: string | URL, - toPath: string | URL + toPath: string | URL, ): void { sendSync("op_copy_file", { from: pathFromURL(fromPath), @@ -15,7 +15,7 @@ export function copyFileSync( export async function copyFile( fromPath: string | URL, - toPath: string | URL + toPath: string | URL, ): Promise<void> { await sendAsync("op_copy_file", { from: pathFromURL(fromPath), diff --git a/cli/js/ops/fs/mkdir.ts b/cli/js/ops/fs/mkdir.ts index 61ea1c218..790b2ad05 100644 --- a/cli/js/ops/fs/mkdir.ts +++ b/cli/js/ops/fs/mkdir.ts @@ -32,7 +32,7 @@ export function mkdirSync(path: string, options?: MkdirOptions): void { export async function mkdir( path: string, - options?: MkdirOptions + options?: MkdirOptions, ): Promise<void> { await sendAsync("op_mkdir", mkdirArgs(path, options)); } diff --git a/cli/js/ops/fs/open.ts b/cli/js/ops/fs/open.ts index edd52c376..f2cad5988 100644 --- a/cli/js/ops/fs/open.ts +++ b/cli/js/ops/fs/open.ts @@ -24,7 +24,7 @@ export function openSync(path: string | URL, options: OpenOptions): number { export function open( path: string | URL, - options: OpenOptions + options: OpenOptions, ): Promise<number> { const mode: number | undefined = options?.mode; return sendAsync("op_open", { path: pathFromURL(path), options, mode }); diff --git a/cli/js/ops/fs/remove.ts b/cli/js/ops/fs/remove.ts index 52f4cad40..24e23986c 100644 --- a/cli/js/ops/fs/remove.ts +++ b/cli/js/ops/fs/remove.ts @@ -9,7 +9,7 @@ export interface RemoveOptions { export function removeSync( path: string | URL, - options: RemoveOptions = {} + options: RemoveOptions = {}, ): void { sendSync("op_remove", { path: pathFromURL(path), @@ -19,7 +19,7 @@ export function removeSync( export async function remove( path: string | URL, - options: RemoveOptions = {} + options: RemoveOptions = {}, ): Promise<void> { await sendAsync("op_remove", { path: pathFromURL(path), diff --git a/cli/js/ops/fs/seek.ts b/cli/js/ops/fs/seek.ts index 8fd3964fd..4f97514ed 100644 --- a/cli/js/ops/fs/seek.ts +++ b/cli/js/ops/fs/seek.ts @@ -6,7 +6,7 @@ import type { SeekMode } from "../../io.ts"; export function seekSync( rid: number, offset: number, - whence: SeekMode + whence: SeekMode, ): number { return sendSync("op_seek", { rid, offset, whence }); } @@ -14,7 +14,7 @@ export function seekSync( export function seek( rid: number, offset: number, - whence: SeekMode + whence: SeekMode, ): Promise<number> { return sendAsync("op_seek", { rid, offset, whence }); } diff --git a/cli/js/ops/fs/symlink.ts b/cli/js/ops/fs/symlink.ts index 7d4741928..d96e05f24 100644 --- a/cli/js/ops/fs/symlink.ts +++ b/cli/js/ops/fs/symlink.ts @@ -9,7 +9,7 @@ export interface SymlinkOptions { export function symlinkSync( oldpath: string, newpath: string, - options?: SymlinkOptions + options?: SymlinkOptions, ): void { sendSync("op_symlink", { oldpath, newpath, options }); } @@ -17,7 +17,7 @@ export function symlinkSync( export async function symlink( oldpath: string, newpath: string, - options?: SymlinkOptions + options?: SymlinkOptions, ): Promise<void> { await sendAsync("op_symlink", { oldpath, newpath, options }); } diff --git a/cli/js/ops/fs/utime.ts b/cli/js/ops/fs/utime.ts index fa86038c6..bbc023ae9 100644 --- a/cli/js/ops/fs/utime.ts +++ b/cli/js/ops/fs/utime.ts @@ -9,7 +9,7 @@ function toSecondsFromEpoch(v: number | Date): number { export function utimeSync( path: string, atime: number | Date, - mtime: number | Date + mtime: number | Date, ): void { sendSync("op_utime", { path, @@ -22,7 +22,7 @@ export function utimeSync( export async function utime( path: string, atime: number | Date, - mtime: number | Date + mtime: number | Date, ): Promise<void> { await sendAsync("op_utime", { path, diff --git a/cli/js/ops/fs_events.ts b/cli/js/ops/fs_events.ts index fb78c6196..ffe19b4d7 100644 --- a/cli/js/ops/fs_events.ts +++ b/cli/js/ops/fs_events.ts @@ -38,7 +38,7 @@ class FsWatcher implements AsyncIterableIterator<FsEvent> { export function watchFs( paths: string | string[], - options: FsWatcherOptions = { recursive: true } + options: FsWatcherOptions = { recursive: true }, ): AsyncIterableIterator<FsEvent> { return new FsWatcher(Array.isArray(paths) ? paths : [paths], options); } diff --git a/cli/js/ops/get_random_values.ts b/cli/js/ops/get_random_values.ts index 95e4602e6..5a45a79d7 100644 --- a/cli/js/ops/get_random_values.ts +++ b/cli/js/ops/get_random_values.ts @@ -11,14 +11,14 @@ export function getRandomValues< | Int16Array | Uint16Array | Int32Array - | Uint32Array + | Uint32Array, >(typedArray: T): T { assert(typedArray !== null, "Input must not be null"); assert(typedArray.length <= 65536, "Input must not be longer than 65536"); const ui8 = new Uint8Array( typedArray.buffer, typedArray.byteOffset, - typedArray.byteLength + typedArray.byteLength, ); sendSync("op_get_random_values", {}, ui8); return typedArray; diff --git a/cli/js/ops/idna.ts b/cli/js/ops/idna.ts index 8459ca29c..59a9af030 100644 --- a/cli/js/ops/idna.ts +++ b/cli/js/ops/idna.ts @@ -6,7 +6,7 @@ import { sendSync } from "./dispatch_json.ts"; export function domainToAscii( domain: string, - { beStrict = false }: { beStrict?: boolean } = {} + { beStrict = false }: { beStrict?: boolean } = {}, ): string { return sendSync("op_domain_to_ascii", { domain, beStrict }); } diff --git a/cli/js/ops/io.ts b/cli/js/ops/io.ts index ecd1269d5..355a09ae0 100644 --- a/cli/js/ops/io.ts +++ b/cli/js/ops/io.ts @@ -17,7 +17,7 @@ export function readSync(rid: number, buffer: Uint8Array): number | null { export async function read( rid: number, - buffer: Uint8Array + buffer: Uint8Array, ): Promise<number | null> { if (buffer.length === 0) { return 0; diff --git a/cli/js/ops/net.ts b/cli/js/ops/net.ts index 05b1bc2cd..1dfa92bd1 100644 --- a/cli/js/ops/net.ts +++ b/cli/js/ops/net.ts @@ -36,7 +36,7 @@ interface AcceptResponse { export function accept( rid: number, - transport: string + transport: string, ): Promise<AcceptResponse> { return sendAsync("op_accept", { rid, transport }); } @@ -72,7 +72,7 @@ interface ReceiveResponse { export function receive( rid: number, transport: string, - zeroCopy: Uint8Array + zeroCopy: Uint8Array, ): Promise<ReceiveResponse> { return sendAsync("op_datagram_receive", { rid, transport }, zeroCopy); } diff --git a/cli/js/ops/runtime_compiler.ts b/cli/js/ops/runtime_compiler.ts index 671585118..ed439de4a 100644 --- a/cli/js/ops/runtime_compiler.ts +++ b/cli/js/ops/runtime_compiler.ts @@ -31,7 +31,7 @@ export interface TranspileOnlyResult { } export function transpile( - request: TranspileRequest + request: TranspileRequest, ): Promise<Record<string, TranspileOnlyResult>> { return sendAsync("op_transpile", request); } diff --git a/cli/js/ops/tls.ts b/cli/js/ops/tls.ts index b278c2d75..291fe3dd9 100644 --- a/cli/js/ops/tls.ts +++ b/cli/js/ops/tls.ts @@ -24,7 +24,7 @@ interface EstablishTLSResponse { } export function connectTls( - args: ConnectTLSRequest + args: ConnectTLSRequest, ): Promise<EstablishTLSResponse> { return sendAsync("op_connect_tls", args); } diff --git a/cli/js/ops/worker_host.ts b/cli/js/ops/worker_host.ts index 24e6b57ba..d5adfc3d5 100644 --- a/cli/js/ops/worker_host.ts +++ b/cli/js/ops/worker_host.ts @@ -12,7 +12,7 @@ export function createWorker( hasSourceCode: boolean, sourceCode: string, useDenoNamespace: boolean, - name?: string + name?: string, ): CreateWorkerResponse { return sendSync("op_create_worker", { specifier, diff --git a/cli/js/process.ts b/cli/js/process.ts index ee32eac3d..0844dd8fd 100644 --- a/cli/js/process.ts +++ b/cli/js/process.ts @@ -33,14 +33,11 @@ async function runStatus(rid: number): Promise<ProcessStatus> { export class Process<T extends RunOptions = RunOptions> { readonly rid: number; readonly pid: number; - readonly stdin!: T["stdin"] extends "piped" - ? Writer & Closer + readonly stdin!: T["stdin"] extends "piped" ? Writer & Closer : (Writer & Closer) | null; - readonly stdout!: T["stdout"] extends "piped" - ? Reader & Closer + readonly stdout!: T["stdout"] extends "piped" ? Reader & Closer : (Reader & Closer) | null; - readonly stderr!: T["stderr"] extends "piped" - ? Reader & Closer + readonly stderr!: T["stderr"] extends "piped" ? Reader & Closer : (Reader & Closer) | null; // @internal diff --git a/cli/js/repl.ts b/cli/js/repl.ts index 8a37d991f..9f2693de6 100644 --- a/cli/js/repl.ts +++ b/cli/js/repl.ts @@ -56,10 +56,9 @@ function evaluate(code: string): boolean { if (!errInfo) { // when a function is eval'ed with just "use strict" sometimes the result // is "use strict" which should be discarded - lastEvalResult = - typeof result === "string" && result === "use strict" - ? undefined - : result; + lastEvalResult = typeof result === "string" && result === "use strict" + ? undefined + : result; if (!isCloseCalled()) { replLog(lastEvalResult); } diff --git a/cli/js/runtime_main.ts b/cli/js/runtime_main.ts index 0c579626b..2983fd47f 100644 --- a/cli/js/runtime_main.ts +++ b/cli/js/runtime_main.ts @@ -48,7 +48,7 @@ function windowClose(): void { // This should be fine, since only Window/MainWorker has .close() exit(0); }, - 0 + 0, ) ); } diff --git a/cli/js/runtime_worker.ts b/cli/js/runtime_worker.ts index 3f7816990..9904ab012 100644 --- a/cli/js/runtime_worker.ts +++ b/cli/js/runtime_worker.ts @@ -93,7 +93,7 @@ export async function workerMessageRecvCallback(data: string): Promise<void> { e.fileName, e.lineNumber, e.columnNumber, - e + e, ); handled = ret === true; } @@ -122,7 +122,7 @@ export const workerRuntimeGlobalProperties = { export function bootstrapWorkerRuntime( name: string, useDenoNamespace: boolean, - internalName?: string + internalName?: string, ): void { if (hasBootstrapped) { throw new Error("Worker runtime already bootstrapped"); @@ -139,7 +139,7 @@ export function bootstrapWorkerRuntime( Object.defineProperties(globalThis, { name: readOnly(name) }); setEventTargetData(globalThis); const { unstableFlag, pid, noColor, args } = runtime.start( - internalName ?? name + internalName ?? name, ); if (unstableFlag) { diff --git a/cli/js/signals.ts b/cli/js/signals.ts index 64cf4106b..a29bac0d7 100644 --- a/cli/js/signals.ts +++ b/cli/js/signals.ts @@ -150,7 +150,7 @@ export class SignalStream then<T, S>( f: (v: void) => T | Promise<T>, - g?: (v: Error) => S | Promise<S> + g?: (v: Error) => S | Promise<S>, ): Promise<T | S> { return this.#pollingPromise.then(() => {}).then(f, g); } diff --git a/cli/js/testing.ts b/cli/js/testing.ts index d38c5427d..accbb81ee 100644 --- a/cli/js/testing.ts +++ b/cli/js/testing.ts @@ -52,7 +52,7 @@ After: - completed: ${post.opsCompletedAsync} Make sure to await all promises returned from Deno APIs before -finishing test case.` +finishing test case.`, ); }; } @@ -61,7 +61,7 @@ finishing test case.` // the test case does not "leak" resources - ie. resource table after // the test has exactly the same contents as before the test. function assertResources( - fn: () => void | Promise<void> + fn: () => void | Promise<void>, ): () => void | Promise<void> { return async function resourceSanitizer(): Promise<void> { const pre = resources(); @@ -97,7 +97,7 @@ export function test(name: string, fn: () => void | Promise<void>): void; // creates a new object with "name" and "fn" fields. export function test( t: string | TestDefinition, - fn?: () => void | Promise<void> + fn?: () => void | Promise<void>, ): void { let testDef: TestDefinition; const defaults = { @@ -220,7 +220,7 @@ function reportToConsole(message: TestMessage): void { `${message.end.passed} passed; ${message.end.failed} failed; ` + `${message.end.ignored} ignored; ${message.end.measured} measured; ` + `${message.end.filtered} filtered out ` + - `${formatDuration(message.end.duration)}\n` + `${formatDuration(message.end.duration)}\n`, ); if (message.end.usedOnly && message.end.failed == 0) { @@ -247,7 +247,7 @@ class TestRunner { constructor( tests: TestDefinition[], public filterFn: (def: TestDefinition) => boolean, - public failFast: boolean + public failFast: boolean, ) { const onlyTests = tests.filter(({ only }) => only); this.#usedOnly = onlyTests.length > 0; @@ -300,7 +300,7 @@ class TestRunner { function createFilterFn( filter: undefined | string | RegExp, - skip: undefined | string | RegExp + skip: undefined | string | RegExp, ): (def: TestDefinition) => boolean { return (def: TestDefinition): boolean => { let passes = true; diff --git a/cli/js/tls.ts b/cli/js/tls.ts index f0506898c..f266a16ea 100644 --- a/cli/js/tls.ts +++ b/cli/js/tls.ts @@ -66,7 +66,7 @@ interface StartTlsOptions { export async function startTls( conn: Conn, - { hostname = "127.0.0.1", certFile }: StartTlsOptions = {} + { hostname = "127.0.0.1", certFile }: StartTlsOptions = {}, ): Promise<Conn> { const res = await tlsOps.startTls({ rid: conn.rid, diff --git a/cli/js/util.ts b/cli/js/util.ts index 50a38978e..f1aefb601 100644 --- a/cli/js/util.ts +++ b/cli/js/util.ts @@ -73,7 +73,7 @@ export function immutableDefine( o: any, p: string | number | symbol, // eslint-disable-next-line @typescript-eslint/no-explicit-any - value: any + value: any, ): void { Object.defineProperty(o, p, { value, diff --git a/cli/js/version.ts b/cli/js/version.ts index ff9b5e972..30157af04 100644 --- a/cli/js/version.ts +++ b/cli/js/version.ts @@ -15,7 +15,7 @@ export const version: Version = { export function setVersions( denoVersion: string, v8Version: string, - tsVersion: string + tsVersion: string, ): void { version.deno = denoVersion; version.v8 = v8Version; diff --git a/cli/js/web/base64.ts b/cli/js/web/base64.ts index 328311d03..6f2459b92 100644 --- a/cli/js/web/base64.ts +++ b/cli/js/web/base64.ts @@ -45,7 +45,7 @@ export function byteLength(b64: string): number { function _byteLength( b64: string, validLen: number, - placeHoldersLen: number + placeHoldersLen: number, ): number { return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen; } @@ -65,8 +65,7 @@ export function toByteArray(b64: string): Uint8Array { let i; for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; @@ -76,15 +75,13 @@ export function toByteArray(b64: string): Uint8Array { } if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); arr[curByte++] = tmp & 0xff; } if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); arr[curByte++] = (tmp >> 8) & 0xff; @@ -107,8 +104,7 @@ function encodeChunk(uint8: Uint8Array, start: number, end: number): string { let tmp; const output = []; for (let i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xff0000) + + tmp = ((uint8[i] << 16) & 0xff0000) + ((uint8[i + 1] << 8) & 0xff00) + (uint8[i + 2] & 0xff); output.push(tripletToBase64(tmp)); @@ -129,8 +125,8 @@ export function fromByteArray(uint8: Uint8Array): string { encodeChunk( uint8, i, - i + maxChunkLength > len2 ? len2 : i + maxChunkLength - ) + i + maxChunkLength > len2 ? len2 : i + maxChunkLength, + ), ); } @@ -144,7 +140,7 @@ export function fromByteArray(uint8: Uint8Array): string { lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3f] + lookup[(tmp << 2) & 0x3f] + - "=" + "=", ); } diff --git a/cli/js/web/blob.ts b/cli/js/web/blob.ts index 92286029f..7034da723 100644 --- a/cli/js/web/blob.ts +++ b/cli/js/web/blob.ts @@ -51,7 +51,7 @@ function convertLineEndingsToNative(s: string): string { function collectSequenceNotCRLF( s: string, - position: number + position: number, ): { collected: string; newPosition: number } { const start = position; for ( @@ -64,7 +64,7 @@ function collectSequenceNotCRLF( function toUint8Arrays( blobParts: BlobPart[], - doNormalizeLineEndingsToNative: boolean + doNormalizeLineEndingsToNative: boolean, ): Uint8Array[] { const ret: Uint8Array[] = []; const enc = new TextEncoder(); @@ -103,7 +103,7 @@ function toUint8Arrays( function processBlobParts( blobParts: BlobPart[], - options: BlobPropertyBag + options: BlobPropertyBag, ): Uint8Array { const normalizeLineEndingsToNative = options.ending === "native"; // ArrayBuffer.transfer is not yet implemented in V8, so we just have to @@ -136,7 +136,7 @@ function getStream(blobBytes: Uint8Array): ReadableStream<ArrayBufferView> { } async function readBytes( - reader: ReadableStreamReader<ArrayBufferView> + reader: ReadableStreamReader<ArrayBufferView>, ): Promise<ArrayBuffer> { const chunks: Uint8Array[] = []; while (true) { diff --git a/cli/js/web/body.ts b/cli/js/web/body.ts index 69aca459f..a7a120ad6 100644 --- a/cli/js/web/body.ts +++ b/cli/js/web/body.ts @@ -40,13 +40,13 @@ function validateBodyType(owner: Body, bodySource: BodyInit | null): boolean { return true; // null body is fine } throw new Error( - `Bad ${owner.constructor.name} body type: ${bodySource.constructor.name}` + `Bad ${owner.constructor.name} body type: ${bodySource.constructor.name}`, ); } async function bufferFromStream( stream: ReadableStreamReader, - size?: number + size?: number, ): Promise<ArrayBuffer> { const encoder = new TextEncoder(); const buffer = new Buffer(); @@ -154,7 +154,7 @@ export class Body implements domTypes.Body { const value = split.join("=").replace(/\+/g, " "); formData.append( decodeURIComponent(name), - decodeURIComponent(value) + decodeURIComponent(value), ); } }); @@ -191,7 +191,7 @@ export class Body implements domTypes.Body { } else if (typeof this._bodySource === "string") { const enc = new TextEncoder(); return Promise.resolve( - enc.encode(this._bodySource).buffer as ArrayBuffer + enc.encode(this._bodySource).buffer as ArrayBuffer, ); } else if (this._bodySource instanceof ReadableStreamImpl) { return bufferFromStream(this._bodySource.getReader(), this.#size); @@ -201,13 +201,13 @@ export class Body implements domTypes.Body { ) { const enc = new TextEncoder(); return Promise.resolve( - enc.encode(this._bodySource.toString()).buffer as ArrayBuffer + enc.encode(this._bodySource.toString()).buffer as ArrayBuffer, ); } else if (!this._bodySource) { return Promise.resolve(new ArrayBuffer(0)); } throw new Error( - `Body type not yet implemented: ${this._bodySource.constructor.name}` + `Body type not yet implemented: ${this._bodySource.constructor.name}`, ); } } diff --git a/cli/js/web/console.ts b/cli/js/web/console.ts index 5ddf50114..181cdb664 100644 --- a/cli/js/web/console.ts +++ b/cli/js/web/console.ts @@ -94,7 +94,7 @@ interface InspectIterableOptions<T> { ctx: ConsoleContext, level: number, inspectOptions: Required<InspectOptions>, - next: () => IteratorResult<[unknown, T], unknown> + next: () => IteratorResult<[unknown, T], unknown>, ) => string; group: boolean; sort: boolean; @@ -107,7 +107,7 @@ function inspectIterable<T>( ctx: ConsoleContext, level: number, options: InspectIterableOptions<T>, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { if (level >= inspectOptions.depth) { return cyan(`[${options.typeName}]`); @@ -129,8 +129,8 @@ function inspectIterable<T>( ctx, level + 1, inspectOptions, - next.bind(iter) - ) + next.bind(iter), + ), ); } entriesLength++; @@ -150,25 +150,25 @@ function inspectIterable<T>( const initIndentation = `\n${DEFAULT_INDENT.repeat(level + 1)}`; const entryIndentation = `,\n${DEFAULT_INDENT.repeat(level + 1)}`; - const closingIndentation = `${ - inspectOptions.trailingComma ? "," : "" - }\n${DEFAULT_INDENT.repeat(level)}`; + const closingIndentation = `${inspectOptions.trailingComma ? "," : ""}\n${ + DEFAULT_INDENT.repeat(level) + }`; let iContent: string; if (options.group && entries.length > MIN_GROUP_LENGTH) { const groups = groupEntries(entries, level, value); - iContent = `${initIndentation}${groups.join( - entryIndentation - )}${closingIndentation}`; + iContent = `${initIndentation}${ + groups.join(entryIndentation) + }${closingIndentation}`; } else { iContent = entries.length === 0 ? "" : ` ${entries.join(", ")} `; if ( stripColor(iContent).length > LINE_BREAKING_LENGTH || !inspectOptions.compact ) { - iContent = `${initIndentation}${entries.join( - entryIndentation - )}${closingIndentation}`; + iContent = `${initIndentation}${ + entries.join(entryIndentation) + }${closingIndentation}`; } } @@ -181,7 +181,7 @@ function groupEntries<T>( entries: string[], level: number, value: Iterable<T>, - iterableLimit = 100 + iterableLimit = 100, ): string[] { let totalLength = 0; let maxLength = 0; @@ -225,12 +225,12 @@ function groupEntries<T>( // Divide that by `actualMax` to receive the correct number of columns. // The added bias increases the columns for short entries. Math.round( - Math.sqrt(approxCharHeights * biasedMax * entriesLength) / biasedMax + Math.sqrt(approxCharHeights * biasedMax * entriesLength) / biasedMax, ), // Do not exceed the breakLength. Math.floor((LINE_BREAKING_LENGTH - (level + 1)) / actualMax), // Limit the columns to a maximum of fifteen. - 15 + 15, ); // Return with the original output if no grouping should happen. if (columns <= 1) { @@ -272,8 +272,7 @@ function groupEntries<T>( str += `${entries[j]}, `[order](padding, " "); } if (order === "padStart") { - const padding = - maxLineLength[j - i] + + const padding = maxLineLength[j - i] + entries[j].length - dataLen[j] - separatorSpace; @@ -295,7 +294,7 @@ function inspectValue( value: unknown, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { switch (typeof value) { case "string": @@ -353,14 +352,13 @@ function inspectValueWithQuotes( value: unknown, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { switch (typeof value) { case "string": - const trunc = - value.length > STR_ABBREVIATE_SIZE - ? value.slice(0, STR_ABBREVIATE_SIZE) + "..." - : value; + const trunc = value.length > STR_ABBREVIATE_SIZE + ? value.slice(0, STR_ABBREVIATE_SIZE) + "..." + : value; return green(quoteString(trunc)); // Quoted strings are green default: return inspectValue(value, ctx, level, inspectOptions); @@ -371,7 +369,7 @@ function inspectArray( value: unknown[], ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { const options: InspectIterableOptions<unknown> = { typeName: "Array", @@ -404,7 +402,7 @@ function inspectTypedArray( value: TypedArray, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { const valueLength = value.length; const options: InspectIterableOptions<unknown> = { @@ -425,7 +423,7 @@ function inspectSet( value: Set<unknown>, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { const options: InspectIterableOptions<unknown> = { typeName: "Set", @@ -445,7 +443,7 @@ function inspectMap( value: Map<unknown, unknown>, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { const options: InspectIterableOptions<[unknown]> = { typeName: "Map", @@ -453,12 +451,14 @@ function inspectMap( delims: ["{", "}"], entryHandler: (entry, ctx, level, inspectOptions): string => { const [key, val] = entry; - return `${inspectValueWithQuotes( - key, - ctx, - level + 1, - inspectOptions - )} => ${inspectValueWithQuotes(val, ctx, level + 1, inspectOptions)}`; + return `${ + inspectValueWithQuotes( + key, + ctx, + level + 1, + inspectOptions, + ) + } => ${inspectValueWithQuotes(val, ctx, level + 1, inspectOptions)}`; }, group: false, sort: inspectOptions.sorted, @@ -469,7 +469,7 @@ function inspectMap( ctx, level, options, - inspectOptions + inspectOptions, ); } @@ -510,7 +510,7 @@ function inspectPromise( value: Promise<unknown>, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { const [state, result] = Deno.core.getPromiseDetails(value); @@ -518,15 +518,18 @@ function inspectPromise( return `Promise { ${cyan("<pending>")} }`; } - const prefix = - state === PromiseState.Fulfilled ? "" : `${red("<rejected>")} `; + const prefix = state === PromiseState.Fulfilled + ? "" + : `${red("<rejected>")} `; - const str = `${prefix}${inspectValueWithQuotes( - result, - ctx, - level + 1, - inspectOptions - )}`; + const str = `${prefix}${ + inspectValueWithQuotes( + result, + ctx, + level + 1, + inspectOptions, + ) + }`; if (str.length + PROMISE_STRING_BASE_LENGTH > LINE_BREAKING_LENGTH) { return `Promise {\n${DEFAULT_INDENT.repeat(level + 1)}${str}\n}`; @@ -541,7 +544,7 @@ function inspectRawObject( value: Record<string, unknown>, ctx: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { if (level >= inspectOptions.depth) { return cyan("[Object]"); // wrappers are in cyan @@ -573,28 +576,32 @@ function inspectRawObject( for (const key of stringKeys) { entries.push( - `${key}: ${inspectValueWithQuotes( - value[key], - ctx, - level + 1, - inspectOptions - )}` + `${key}: ${ + inspectValueWithQuotes( + value[key], + ctx, + level + 1, + inspectOptions, + ) + }`, ); } for (const key of symbolKeys) { entries.push( - `${key.toString()}: ${inspectValueWithQuotes( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - value[key as any], - ctx, - level + 1, - inspectOptions - )}` + `${key.toString()}: ${ + inspectValueWithQuotes( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value[key as any], + ctx, + level + 1, + inspectOptions, + ) + }`, ); } // Making sure color codes are ignored when calculating the total length - const totalLength = - entries.length + level + stripColor(entries.join("")).length; + const totalLength = entries.length + level + + stripColor(entries.join("")).length; ctx.delete(value); @@ -621,7 +628,7 @@ function inspectObject( value: {}, consoleContext: ConsoleContext, level: number, - inspectOptions: Required<InspectOptions> + inspectOptions: Required<InspectOptions>, ): string { if (customInspect in value && typeof value[customInspect] === "function") { try { @@ -658,7 +665,7 @@ function inspectObject( value, consoleContext, level, - inspectOptions + inspectOptions, ); } else { // Otherwise, default object formatting @@ -668,7 +675,7 @@ function inspectObject( export function inspectArgs( args: unknown[], - inspectOptions: InspectOptions = {} + inspectOptions: InspectOptions = {}, ): string { const rInspectOptions = { ...DEFAULT_INSPECT_OPTIONS, ...inspectOptions }; const first = args[0]; @@ -717,7 +724,7 @@ export function inspectArgs( args[++a], new Set<unknown>(), 0, - rInspectOptions + rInspectOptions, ); break; case CHAR_PERCENT: @@ -808,7 +815,7 @@ export class Console { inspectArgs(args, { indentLevel: this.indentLevel, }) + "\n", - false + false, ); }; @@ -826,7 +833,7 @@ export class Console { inspectArgs(args, { indentLevel: this.indentLevel, }) + "\n", - true + true, ); }; @@ -879,7 +886,7 @@ export class Console { if (properties !== undefined && !Array.isArray(properties)) { throw new Error( "The 'properties' argument must be of type Array. " + - "Received type string" + "Received type string", ); } @@ -927,8 +934,7 @@ export class Console { let hasPrimitives = false; Object.keys(resultData).forEach((k, idx): void => { const value: unknown = resultData[k]!; - const primitive = - value === null || + const primitive = value === null || (typeof value !== "function" && typeof value !== "object"); if (properties === undefined && primitive) { hasPrimitives = true; @@ -1047,7 +1053,7 @@ export const customInspect = Symbol("Deno.customInspect"); export function inspect( value: unknown, - inspectOptions: InspectOptions = {} + inspectOptions: InspectOptions = {}, ): string { if (typeof value === "string") { return value; diff --git a/cli/js/web/console_table.ts b/cli/js/web/console_table.ts index ba2d763b7..42667d998 100644 --- a/cli/js/web/console_table.ts +++ b/cli/js/web/console_table.ts @@ -28,8 +28,8 @@ function isFullWidthCodePoint(code: number): boolean { return ( code >= 0x1100 && (code <= 0x115f || // Hangul Jamo - code === 0x2329 || // LEFT-POINTING ANGLE BRACKET - code === 0x232a || // RIGHT-POINTING ANGLE BRACKET + code === 0x2329 || // LEFT-POINTING ANGLE BRACKET + code === 0x232a || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months (code >= 0x2e80 && code <= 0x3247 && code !== 0x303f) || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A @@ -94,7 +94,7 @@ export function cliTable(head: string[], columns: string[][]): string { const columnWidths = head.map((h: string): number => getStringWidth(h)); const longestColumn = columns.reduce( (n: number, a: string[]): number => Math.max(n, a.length), - 0 + 0, ); for (let i = 0; i < head.length; i++) { @@ -114,8 +114,7 @@ export function cliTable(head: string[], columns: string[][]): string { tableChars.middleMiddle.repeat(i + 2) ); - let result = - `${tableChars.topLeft}${divider.join(tableChars.topMiddle)}` + + let result = `${tableChars.topLeft}${divider.join(tableChars.topMiddle)}` + `${tableChars.topRight}\n${renderRow(head, columnWidths)}\n` + `${tableChars.leftMiddle}${divider.join(tableChars.rowMiddle)}` + `${tableChars.rightMiddle}\n`; @@ -124,8 +123,7 @@ export function cliTable(head: string[], columns: string[][]): string { result += `${renderRow(row, columnWidths)}\n`; } - result += - `${tableChars.bottomLeft}${divider.join(tableChars.bottomMiddle)}` + + result += `${tableChars.bottomLeft}${divider.join(tableChars.bottomMiddle)}` + tableChars.bottomRight; return result; diff --git a/cli/js/web/decode_utf8.ts b/cli/js/web/decode_utf8.ts index d82634efe..ca190134c 100644 --- a/cli/js/web/decode_utf8.ts +++ b/cli/js/web/decode_utf8.ts @@ -31,7 +31,7 @@ declare global { apply<T, R>( this: (this: T, ...args: number[]) => R, thisArg: T, - args: Uint16Array + args: Uint16Array, ): R; } } @@ -39,7 +39,7 @@ declare global { export function decodeUtf8( input: Uint8Array, fatal: boolean, - ignoreBOM: boolean + ignoreBOM: boolean, ): string { let outString = ""; @@ -61,10 +61,11 @@ export function decodeUtf8( for (; i < input.length; ++i) { // Encoding error handling if (state === 12 || (state !== 0 && (input[i] & 0xc0) !== 0x80)) { - if (fatal) + if (fatal) { throw new TypeError( - `Decoder error. Invalid byte in sequence at position ${i} in data.` + `Decoder error. Invalid byte in sequence at position ${i} in data.`, ); + } outBuffer[outIndex++] = 0xfffd; // Replacement character if (outIndex === outBufferLength) { outString += String.fromCharCode.apply(null, outBuffer); @@ -73,7 +74,7 @@ export function decodeUtf8( state = 0; } - // prettier-ignore + // deno-fmt-ignore type = [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, @@ -84,11 +85,10 @@ export function decodeUtf8( 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8 ][input[i]]; - codepoint = - state !== 0 - ? (input[i] & 0x3f) | (codepoint << 6) - : (0xff >> type) & input[i]; - // prettier-ignore + codepoint = state !== 0 + ? (input[i] & 0x3f) | (codepoint << 6) + : (0xff >> type) & input[i]; + // deno-fmt-ignore state = [ 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, diff --git a/cli/js/web/dom_file.ts b/cli/js/web/dom_file.ts index 3d65e5768..907337e59 100644 --- a/cli/js/web/dom_file.ts +++ b/cli/js/web/dom_file.ts @@ -9,7 +9,7 @@ export class DomFileImpl extends blob.DenoBlob implements File { constructor( fileBits: BlobPart[], fileName: string, - options?: FilePropertyBag + options?: FilePropertyBag, ) { const { lastModified = Date.now(), ...blobPropertyBag } = options ?? {}; super(fileBits, blobPropertyBag); diff --git a/cli/js/web/dom_iterable.ts b/cli/js/web/dom_iterable.ts index 271b2f655..7e26a12a4 100644 --- a/cli/js/web/dom_iterable.ts +++ b/cli/js/web/dom_iterable.ts @@ -14,13 +14,13 @@ export interface DomIterable<K, V> { forEach( callback: (value: V, key: K, parent: this) => void, // eslint-disable-next-line @typescript-eslint/no-explicit-any - thisArg?: any + thisArg?: any, ): void; } export function DomIterableMixin<K, V, TBase extends Constructor>( Base: TBase, - dataSymbol: symbol + dataSymbol: symbol, ): TBase & Constructor<DomIterable<K, V>> { // we have to cast `this` as `any` because there is no way to describe the // Base class in a way where the Symbol `dataSymbol` is defined. So the @@ -56,15 +56,15 @@ export function DomIterableMixin<K, V, TBase extends Constructor>( forEach( callbackfn: (value: V, key: K, parent: this) => void, // eslint-disable-next-line @typescript-eslint/no-explicit-any - thisArg?: any + thisArg?: any, ): void { requiredArguments( `${this.constructor.name}.forEach`, arguments.length, - 1 + 1, ); callbackfn = callbackfn.bind( - thisArg == null ? globalThis : Object(thisArg) + thisArg == null ? globalThis : Object(thisArg), ); // eslint-disable-next-line @typescript-eslint/no-explicit-any for (const [key, value] of (this as any)[dataSymbol]) { diff --git a/cli/js/web/dom_types.d.ts b/cli/js/web/dom_types.d.ts index 5d35c9187..b8636b7d1 100644 --- a/cli/js/web/dom_types.d.ts +++ b/cli/js/web/dom_types.d.ts @@ -220,7 +220,7 @@ interface NodeList { item(index: number): Node | null; forEach( callbackfn: (value: Node, key: number, parent: NodeList) => void, - thisArg?: any + thisArg?: any, ): void; [index: number]: Node; [Symbol.iterator](): IterableIterator<Node>; @@ -234,7 +234,7 @@ interface NodeListOf<TNode extends Node> extends NodeList { item(index: number): TNode; forEach( callbackfn: (value: TNode, key: number, parent: NodeListOf<TNode>) => void, - thisArg?: any + thisArg?: any, ): void; [index: number]: TNode; [Symbol.iterator](): IterableIterator<TNode>; diff --git a/cli/js/web/error_event.ts b/cli/js/web/error_event.ts index 8e7853875..c04a49545 100644 --- a/cli/js/web/error_event.ts +++ b/cli/js/web/error_event.ts @@ -39,7 +39,7 @@ export class ErrorEventImpl extends Event implements ErrorEvent { lineno = 0, colno = 0, error = null, - }: ErrorEventInit = {} + }: ErrorEventInit = {}, ) { super(type, { bubbles: bubbles, diff --git a/cli/js/web/event.ts b/cli/js/web/event.ts index 556d403a6..d22d41c29 100644 --- a/cli/js/web/event.ts +++ b/cli/js/web/event.ts @@ -53,7 +53,7 @@ export function getStopImmediatePropagation(event: Event): boolean { export function setCurrentTarget( event: Event, - value: EventTarget | null + value: EventTarget | null, ): void { (event as EventImpl).currentTarget = value; } @@ -85,7 +85,7 @@ export function setPath(event: Event, value: EventPath[]): void { export function setRelatedTarget<T extends Event>( event: T, - value: EventTarget | null + value: EventTarget | null, ): void { if ("relatedTarget" in event) { (event as T & { @@ -100,7 +100,7 @@ export function setTarget(event: Event, value: EventTarget | null): void { export function setStopImmediatePropagation( event: Event, - value: boolean + value: boolean, ): void { const data = eventData.get(event as Event); if (data) { @@ -111,7 +111,7 @@ export function setStopImmediatePropagation( // Type guards that widen the event type export function hasRelatedTarget( - event: Event + event: Event, ): event is domTypes.FocusEvent | domTypes.MouseEvent { return "relatedTarget" in event; } diff --git a/cli/js/web/event_target.ts b/cli/js/web/event_target.ts index 6f6897425..82935dd9c 100644 --- a/cli/js/web/event_target.ts +++ b/cli/js/web/event_target.ts @@ -46,7 +46,7 @@ function getRoot(eventTarget: EventTarget): EventTarget | null { } function isNode<T extends EventTarget>( - eventTarget: T | null + eventTarget: T | null, ): eventTarget is T & domTypes.Node { return Boolean(eventTarget && "nodeType" in eventTarget); } @@ -54,7 +54,7 @@ function isNode<T extends EventTarget>( // https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor function isShadowInclusiveAncestor( ancestor: EventTarget | null, - node: EventTarget | null + node: EventTarget | null, ): boolean { while (isNode(node)) { if (node === ancestor) { @@ -76,12 +76,12 @@ function isShadowRoot(nodeImpl: EventTarget | null): boolean { nodeImpl && isNode(nodeImpl) && nodeImpl.nodeType === DOCUMENT_FRAGMENT_NODE && - getHost(nodeImpl) != null + getHost(nodeImpl) != null, ); } function isSlotable<T extends EventTarget>( - nodeImpl: T | null + nodeImpl: T | null, ): nodeImpl is T & domTypes.Node & domTypes.Slotable { return Boolean(isNode(nodeImpl) && "assignedSlot" in nodeImpl); } @@ -98,7 +98,7 @@ function appendToEventPath( targetOverride: EventTarget | null, relatedTarget: EventTarget | null, touchTargets: EventTarget[], - slotInClosedTree: boolean + slotInClosedTree: boolean, ): void { const itemInShadowTree = isNode(target) && isShadowRoot(getRoot(target)); const rootOfClosedTree = isShadowRoot(target) && getMode(target) === "closed"; @@ -117,7 +117,7 @@ function appendToEventPath( function dispatch( targetImpl: EventTarget, eventImpl: Event, - targetOverride?: EventTarget + targetOverride?: EventTarget, ): boolean { let clearTargets = false; let activationTarget: EventTarget | null = null; @@ -139,7 +139,7 @@ function dispatch( targetOverride, relatedTarget, touchTargets, - false + false, ); const isActivationEvent = eventImpl.type === "click"; @@ -149,8 +149,9 @@ function dispatch( } let slotInClosedTree = false; - let slotable = - isSlotable(targetImpl) && getAssignedSlot(targetImpl) ? targetImpl : null; + let slotable = isSlotable(targetImpl) && getAssignedSlot(targetImpl) + ? targetImpl + : null; let parent = getParent(targetImpl); // Populate event path @@ -181,7 +182,7 @@ function dispatch( null, relatedTarget, touchTargets, - slotInClosedTree + slotInClosedTree, ); } else if (parent === relatedTarget) { parent = null; @@ -202,7 +203,7 @@ function dispatch( targetImpl, relatedTarget, touchTargets, - slotInClosedTree + slotInClosedTree, ); } @@ -226,9 +227,8 @@ function dispatch( } const clearTargetsTuple = path[clearTargetsTupleIndex]; - clearTargets = - (isNode(clearTargetsTuple.target) && - isShadowRoot(getRoot(clearTargetsTuple.target))) || + clearTargets = (isNode(clearTargetsTuple.target) && + isShadowRoot(getRoot(clearTargetsTuple.target))) || (isNode(clearTargetsTuple.relatedTarget) && isShadowRoot(getRoot(clearTargetsTuple.relatedTarget))); @@ -288,7 +288,7 @@ function dispatch( * Ref: https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke */ function innerInvokeEventListeners( eventImpl: Event, - targetListeners: Record<string, Listener[]> + targetListeners: Record<string, Listener[]>, ): boolean { let found = false; @@ -381,7 +381,7 @@ function invokeEventListeners(tuple: EventPath, eventImpl: Event): void { } function normalizeAddEventHandlerOptions( - options: boolean | AddEventListenerOptions | undefined + options: boolean | AddEventListenerOptions | undefined, ): AddEventListenerOptions { if (typeof options === "boolean" || typeof options === "undefined") { return { @@ -395,7 +395,7 @@ function normalizeAddEventHandlerOptions( } function normalizeEventHandlerOptions( - options: boolean | EventListenerOptions | undefined + options: boolean | EventListenerOptions | undefined, ): EventListenerOptions { if (typeof options === "boolean" || typeof options === "undefined") { return { @@ -456,7 +456,7 @@ function getAssignedSlot(target: EventTarget): boolean { function getHasActivationBehavior(target: EventTarget): boolean { return Boolean( - eventTargetData.get(target as EventTarget)?.hasActivationBehavior + eventTargetData.get(target as EventTarget)?.hasActivationBehavior, ); } @@ -490,7 +490,7 @@ export class EventTargetImpl implements EventTarget { public addEventListener( type: string, callback: EventListenerOrEventListenerObject | null, - options?: AddEventListenerOptions | boolean + options?: AddEventListenerOptions | boolean, ): void { requiredArguments("EventTarget.addEventListener", arguments.length, 2); if (callback === null) { @@ -522,14 +522,14 @@ export class EventTargetImpl implements EventTarget { public removeEventListener( type: string, callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean + options?: EventListenerOptions | boolean, ): void { requiredArguments("EventTarget.removeEventListener", arguments.length, 2); const listeners = eventTargetData.get(this ?? globalThis)!.listeners; if (callback !== null && type in listeners) { listeners[type] = listeners[type].filter( - (listener) => listener.callback !== callback + (listener) => listener.callback !== callback, ); } else if (callback === null || !listeners[type]) { return; diff --git a/cli/js/web/fetch.ts b/cli/js/web/fetch.ts index d692b83e1..4fe525cde 100644 --- a/cli/js/web/fetch.ts +++ b/cli/js/web/fetch.ts @@ -38,14 +38,13 @@ export class Response extends Body.Body implements domTypes.Response { let status = init.status === undefined ? 200 : Number(init.status || 0); let statusText = init.statusText ?? ""; - let headers = - init.headers instanceof Headers - ? init.headers - : new Headers(init.headers); + let headers = init.headers instanceof Headers + ? init.headers + : new Headers(init.headers); if (init.status !== undefined && (status < 200 || status > 599)) { throw new RangeError( - `The status provided (${init.status}) is outside the range [200, 599]` + `The status provided (${init.status}) is outside the range [200, 599]`, ); } @@ -156,7 +155,7 @@ export class Response extends Body.Body implements domTypes.Response { static redirect(url: URL | string, status: number): domTypes.Response { if (![301, 302, 303, 307, 308].includes(status)) { throw new RangeError( - "The redirection status must be one of 301, 302, 303, 307 and 308." + "The redirection status must be one of 301, 302, 303, 307 and 308.", ); } return new Response(null, { @@ -171,7 +170,7 @@ function sendFetchReq( url: string, method: string | null, headers: Headers | null, - body: ArrayBufferView | undefined + body: ArrayBufferView | undefined, ): Promise<FetchResponse> { let headerArray: Array<[string, string]> = []; if (headers) { @@ -189,7 +188,7 @@ function sendFetchReq( export async function fetch( input: (domTypes.Request & { _bodySource?: unknown }) | URL | string, - init?: domTypes.RequestInit + init?: domTypes.RequestInit, ): Promise<Response> { let url: string; let method: string | null = null; @@ -203,10 +202,9 @@ export async function fetch( if (init != null) { method = init.method || null; if (init.headers) { - headers = - init.headers instanceof Headers - ? init.headers - : new Headers(init.headers); + headers = init.headers instanceof Headers + ? init.headers + : new Headers(init.headers); } else { headers = null; } diff --git a/cli/js/web/fetch/multipart.ts b/cli/js/web/fetch/multipart.ts index a632d8600..f30975e5e 100644 --- a/cli/js/web/fetch/multipart.ts +++ b/cli/js/web/fetch/multipart.ts @@ -64,7 +64,7 @@ export class MultipartBuilder { #writeFileHeaders = ( field: string, filename: string, - type?: string + type?: string, ): void => { const headers = [ [ @@ -122,7 +122,7 @@ export class MultipartParser { return { headers, disposition: getHeaderValueParams( - headers.get("Content-Disposition") ?? "" + headers.get("Content-Disposition") ?? "", ), }; }; diff --git a/cli/js/web/form_data.ts b/cli/js/web/form_data.ts index 2566943f0..1a0622638 100644 --- a/cli/js/web/form_data.ts +++ b/cli/js/web/form_data.ts @@ -16,7 +16,7 @@ class FormDataBase { append( name: string, value: string | blob.DenoBlob | domFile.DomFileImpl, - filename?: string + filename?: string, ): void { requiredArguments("FormData.append", arguments.length, 2); name = String(name); @@ -82,7 +82,7 @@ class FormDataBase { set( name: string, value: string | blob.DenoBlob | domFile.DomFileImpl, - filename?: string + filename?: string, ): void { requiredArguments("FormData.set", arguments.length, 2); name = String(name); @@ -102,7 +102,7 @@ class FormDataBase { filename || "blob", { type: value.type, - } + }, ); } else { this[dataSymbol][i][1] = String(value); diff --git a/cli/js/web/headers.ts b/cli/js/web/headers.ts index 5fd6abc44..d75f87adc 100644 --- a/cli/js/web/headers.ts +++ b/cli/js/web/headers.ts @@ -55,7 +55,7 @@ function validateValue(value: string): void { function dataAppend( data: Array<[string, string]>, key: string, - value: string + value: string, ): void { for (let i = 0; i < data.length; i++) { const [dataKey] = data[i]; @@ -85,7 +85,7 @@ function dataAppend( * entry in the headers list. */ function dataGet( data: Array<[string, string]>, - key: string + key: string, ): string | undefined { const setCookieValues = []; for (const [dataKey, value] of data) { @@ -118,7 +118,7 @@ function dataGet( function dataSet( data: Array<[string, string]>, key: string, - value: string + value: string, ): void { for (let i = 0; i < data.length; i++) { const [dataKey] = data[i]; @@ -169,7 +169,7 @@ class HeadersBase { constructor(init?: HeadersInit) { if (init === null) { throw new TypeError( - "Failed to construct 'Headers'; The provided value was not valid" + "Failed to construct 'Headers'; The provided value was not valid", ); } else if (isHeaders(init)) { this[headersData] = [...init]; @@ -183,7 +183,7 @@ class HeadersBase { requiredArguments( "Headers.constructor tuple array argument", tuple.length, - 2 + 2, ); this.append(tuple[0], tuple[1]); diff --git a/cli/js/web/performance.ts b/cli/js/web/performance.ts index eb0479b37..1acff9f75 100644 --- a/cli/js/web/performance.ts +++ b/cli/js/web/performance.ts @@ -8,7 +8,7 @@ let performanceEntries: PerformanceEntryList = []; function findMostRecent( name: string, - type: "mark" | "measure" + type: "mark" | "measure", ): PerformanceEntry | undefined { return performanceEntries .slice() @@ -32,12 +32,12 @@ function convertMarkToTimestamp(mark: string | number): number { function filterByNameType( name?: string, - type?: "mark" | "measure" + type?: "mark" | "measure", ): PerformanceEntryList { return performanceEntries.filter( (entry) => (name ? entry.name === name : true) && - (type ? entry.entryType === type : true) + (type ? entry.entryType === type : true), ); } @@ -72,7 +72,7 @@ export class PerformanceEntryImpl implements PerformanceEntry { name: string, entryType: string, startTime: number, - duration: number + duration: number, ) { this.#name = name; this.#entryType = entryType; @@ -111,7 +111,7 @@ export class PerformanceMarkImpl extends PerformanceEntryImpl constructor( name: string, - { detail = null, startTime = now() }: PerformanceMarkOptions = {} + { detail = null, startTime = now() }: PerformanceMarkOptions = {}, ) { super(name, "mark", startTime, 0); if (startTime < 0) { @@ -133,11 +133,9 @@ export class PerformanceMarkImpl extends PerformanceEntryImpl [customInspect](): string { return this.detail - ? `${this.constructor.name} {\n detail: ${inspect(this.detail, { - depth: 3, - })},\n name: "${this.name}",\n entryType: "${ - this.entryType - }",\n startTime: ${this.startTime},\n duration: ${this.duration}\n}` + ? `${this.constructor.name} {\n detail: ${ + inspect(this.detail, { depth: 3 }) + },\n name: "${this.name}",\n entryType: "${this.entryType}",\n startTime: ${this.startTime},\n duration: ${this.duration}\n}` : `${this.constructor.name} { detail: ${this.detail}, name: "${this.name}", entryType: "${this.entryType}", startTime: ${this.startTime}, duration: ${this.duration} }`; } } @@ -161,7 +159,7 @@ export class PerformanceMeasureImpl extends PerformanceEntryImpl startTime: number, duration: number, // eslint-disable-next-line @typescript-eslint/no-explicit-any - detail: any = null + detail: any = null, ) { super(name, "measure", startTime, duration); this.#detail = cloneValue(detail); @@ -180,11 +178,9 @@ export class PerformanceMeasureImpl extends PerformanceEntryImpl [customInspect](): string { return this.detail - ? `${this.constructor.name} {\n detail: ${inspect(this.detail, { - depth: 3, - })},\n name: "${this.name}",\n entryType: "${ - this.entryType - }",\n startTime: ${this.startTime},\n duration: ${this.duration}\n}` + ? `${this.constructor.name} {\n detail: ${ + inspect(this.detail, { depth: 3 }) + },\n name: "${this.name}",\n entryType: "${this.entryType}",\n startTime: ${this.startTime},\n duration: ${this.duration}\n}` : `${this.constructor.name} { detail: ${this.detail}, name: "${this.name}", entryType: "${this.entryType}", startTime: ${this.startTime}, duration: ${this.duration} }`; } } @@ -193,11 +189,11 @@ export class PerformanceImpl implements Performance { clearMarks(markName?: string): void { if (markName == null) { performanceEntries = performanceEntries.filter( - (entry) => entry.entryType !== "mark" + (entry) => entry.entryType !== "mark", ); } else { performanceEntries = performanceEntries.filter( - (entry) => !(entry.name === markName && entry.entryType === "mark") + (entry) => !(entry.name === markName && entry.entryType === "mark"), ); } } @@ -205,12 +201,12 @@ export class PerformanceImpl implements Performance { clearMeasures(measureName?: string): void { if (measureName == null) { performanceEntries = performanceEntries.filter( - (entry) => entry.entryType !== "measure" + (entry) => entry.entryType !== "measure", ); } else { performanceEntries = performanceEntries.filter( (entry) => - !(entry.name === measureName && entry.entryType === "measure") + !(entry.name === measureName && entry.entryType === "measure"), ); } } @@ -220,7 +216,7 @@ export class PerformanceImpl implements Performance { } getEntriesByName( name: string, - type?: "mark" | "measure" + type?: "mark" | "measure", ): PerformanceEntryList { return filterByNameType(name, type); } @@ -230,7 +226,7 @@ export class PerformanceImpl implements Performance { mark( markName: string, - options: PerformanceMarkOptions = {} + options: PerformanceMarkOptions = {}, ): PerformanceMark { // 3.1.1.1 If the global object is a Window object and markName uses the // same name as a read only attribute in the PerformanceTiming interface, @@ -243,17 +239,17 @@ export class PerformanceImpl implements Performance { measure( measureName: string, - options?: PerformanceMeasureOptions + options?: PerformanceMeasureOptions, ): PerformanceMeasure; measure( measureName: string, startMark?: string, - endMark?: string + endMark?: string, ): PerformanceMeasure; measure( measureName: string, startOrMeasureOptions: string | PerformanceMeasureOptions = {}, - endMark?: string + endMark?: string, ): PerformanceMeasure { if (startOrMeasureOptions && typeof startOrMeasureOptions === "object") { if (endMark) { @@ -271,7 +267,7 @@ export class PerformanceImpl implements Performance { "end" in startOrMeasureOptions ) { throw new TypeError( - "Cannot specify start, end, and duration together in options." + "Cannot specify start, end, and duration together in options.", ); } } @@ -319,7 +315,7 @@ export class PerformanceImpl implements Performance { endTime - startTime, typeof startOrMeasureOptions === "object" ? startOrMeasureOptions.detail ?? null - : null + : null, ); performanceEntries.push(entry); return entry; diff --git a/cli/js/web/streams/internals.ts b/cli/js/web/streams/internals.ts index 58a62e3cb..06c5e304d 100644 --- a/cli/js/web/streams/internals.ts +++ b/cli/js/web/streams/internals.ts @@ -66,7 +66,7 @@ export interface ReadableStreamAsyncIterator<T = any> extends AsyncIterator<T> { export function acquireReadableStreamDefaultReader<T>( stream: ReadableStreamImpl<T>, - forAuthorCode = false + forAuthorCode = false, ): ReadableStreamDefaultReaderImpl<T> { const reader = new ReadableStreamDefaultReaderImpl(stream); reader[sym.forAuthorCode] = forAuthorCode; @@ -74,7 +74,7 @@ export function acquireReadableStreamDefaultReader<T>( } export function acquireWritableStreamDefaultWriter<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): WritableStreamDefaultWriterImpl<W> { return new WritableStreamDefaultWriterImpl(stream); } @@ -82,14 +82,14 @@ export function acquireWritableStreamDefaultWriter<W>( export function call<F extends (...args: any[]) => any>( fn: F, v: ThisType<F>, - args: Parameters<F> + args: Parameters<F>, ): ReturnType<F> { return Function.prototype.apply.call(fn, v, args); } function createAlgorithmFromUnderlyingMethod< O extends UnderlyingByteSource | UnderlyingSource | Transformer, - P extends keyof O + P extends keyof O, >( underlyingObject: O, methodName: P, @@ -99,7 +99,7 @@ function createAlgorithmFromUnderlyingMethod< function createAlgorithmFromUnderlyingMethod< O extends UnderlyingByteSource | UnderlyingSource | Transformer, - P extends keyof O + P extends keyof O, >( underlyingObject: O, methodName: P, @@ -108,7 +108,7 @@ function createAlgorithmFromUnderlyingMethod< ): (arg: any) => Promise<void>; function createAlgorithmFromUnderlyingMethod< O extends UnderlyingByteSource | UnderlyingSource | Transformer, - P extends keyof O + P extends keyof O, >( underlyingObject: O, methodName: P, @@ -138,15 +138,15 @@ function createReadableStream<T>( pullAlgorithm: PullAlgorithm, cancelAlgorithm: CancelAlgorithm, highWaterMark = 1, - sizeAlgorithm: SizeAlgorithm<T> = (): number => 1 + sizeAlgorithm: SizeAlgorithm<T> = (): number => 1, ): ReadableStreamImpl<T> { highWaterMark = validateAndNormalizeHighWaterMark(highWaterMark); const stream: ReadableStreamImpl<T> = Object.create( - ReadableStreamImpl.prototype + ReadableStreamImpl.prototype, ); initializeReadableStream(stream); const controller: ReadableStreamDefaultControllerImpl<T> = Object.create( - ReadableStreamDefaultControllerImpl.prototype + ReadableStreamDefaultControllerImpl.prototype, ); setUpReadableStreamDefaultController( stream, @@ -155,7 +155,7 @@ function createReadableStream<T>( pullAlgorithm, cancelAlgorithm, highWaterMark, - sizeAlgorithm + sizeAlgorithm, ); return stream; } @@ -166,13 +166,13 @@ function createWritableStream<W>( closeAlgorithm: CloseAlgorithm, abortAlgorithm: AbortAlgorithm, highWaterMark = 1, - sizeAlgorithm: SizeAlgorithm<W> = (): number => 1 + sizeAlgorithm: SizeAlgorithm<W> = (): number => 1, ): WritableStreamImpl<W> { highWaterMark = validateAndNormalizeHighWaterMark(highWaterMark); const stream = Object.create(WritableStreamImpl.prototype); initializeWritableStream(stream); const controller = Object.create( - WritableStreamDefaultControllerImpl.prototype + WritableStreamDefaultControllerImpl.prototype, ); setUpWritableStreamDefaultController( stream, @@ -182,7 +182,7 @@ function createWritableStream<W>( closeAlgorithm, abortAlgorithm, highWaterMark, - sizeAlgorithm + sizeAlgorithm, ); return stream; } @@ -201,7 +201,7 @@ export function dequeueValue<R>(container: Container<R>): R { function enqueueValueWithSize<R>( container: Container<R>, value: R, - size: number + size: number, ): void { assert(sym.queue in container && sym.queueTotalSize in container); size = Number(size); @@ -225,7 +225,7 @@ export function getDeferred<T>(): Required<Deferred<T>> { } export function initializeReadableStream<R>( - stream: ReadableStreamImpl<R> + stream: ReadableStreamImpl<R>, ): void { stream[sym.state] = "readable"; stream[sym.reader] = stream[sym.storedError] = undefined; @@ -238,7 +238,7 @@ export function initializeTransformStream<I, O>( writableHighWaterMark: number, writableSizeAlgorithm: SizeAlgorithm<I>, readableHighWaterMark: number, - readableSizeAlgorithm: SizeAlgorithm<O> + readableSizeAlgorithm: SizeAlgorithm<O>, ): void { const startAlgorithm = (): Promise<void> => startPromise; const writeAlgorithm = (chunk: any): Promise<void> => @@ -253,7 +253,7 @@ export function initializeTransformStream<I, O>( closeAlgorithm, abortAlgorithm, writableHighWaterMark, - writableSizeAlgorithm + writableSizeAlgorithm, ); const pullAlgorithm = (): PromiseLike<void> => transformStreamDefaultSourcePullAlgorithm(stream); @@ -266,7 +266,7 @@ export function initializeTransformStream<I, O>( pullAlgorithm, cancelAlgorithm, readableHighWaterMark, - readableSizeAlgorithm + readableSizeAlgorithm, ); stream[sym.backpressure] = stream[sym.backpressureChangePromise] = undefined; transformStreamSetBackpressure(stream, true); @@ -277,7 +277,7 @@ export function initializeTransformStream<I, O>( } export function initializeWritableStream<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): void { stream[sym.state] = "writable"; stream[sym.storedError] = stream[sym.writer] = stream[ @@ -315,7 +315,7 @@ function isFiniteNonNegativeNumber(v: unknown): v is number { } export function isReadableByteStreamController( - x: unknown + x: unknown, ): x is ReadableByteStreamControllerImpl { return !( typeof x !== "object" || @@ -333,7 +333,7 @@ export function isReadableStream(x: unknown): x is ReadableStreamImpl { } export function isReadableStreamAsyncIterator( - x: unknown + x: unknown, ): x is ReadableStreamAsyncIterator { if (typeof x !== "object" || x === null) { return false; @@ -342,7 +342,7 @@ export function isReadableStreamAsyncIterator( } export function isReadableStreamDefaultController( - x: unknown + x: unknown, ): x is ReadableStreamDefaultControllerImpl { return !( typeof x !== "object" || @@ -352,7 +352,7 @@ export function isReadableStreamDefaultController( } export function isReadableStreamDefaultReader<T>( - x: unknown + x: unknown, ): x is ReadableStreamDefaultReaderImpl<T> { return !(typeof x !== "object" || x === null || !(sym.readRequests in x)); } @@ -376,7 +376,7 @@ export function isTransformStream(x: unknown): x is TransformStreamImpl { } export function isTransformStreamDefaultController( - x: unknown + x: unknown, ): x is TransformStreamDefaultControllerImpl { return !( typeof x !== "object" || @@ -386,7 +386,7 @@ export function isTransformStreamDefaultController( } export function isUnderlyingByteSource( - underlyingSource: UnderlyingByteSource | UnderlyingSource + underlyingSource: UnderlyingByteSource | UnderlyingSource, ): underlyingSource is UnderlyingByteSource { const { type } = underlyingSource; const typeString = String(type); @@ -402,7 +402,7 @@ export function isWritableStream(x: unknown): x is WritableStreamImpl { } export function isWritableStreamDefaultController( - x: unknown + x: unknown, ): x is WritableStreamDefaultControllerImpl<any> { return !( typeof x !== "object" || @@ -412,7 +412,7 @@ export function isWritableStreamDefaultController( } export function isWritableStreamDefaultWriter( - x: unknown + x: unknown, ): x is WritableStreamDefaultWriterImpl<any> { return !( typeof x !== "object" || @@ -427,7 +427,7 @@ export function isWritableStreamLocked(stream: WritableStreamImpl): boolean { } export function makeSizeAlgorithmFromSizeFunction<T>( - size: QueuingStrategySizeCallback<T> | undefined + size: QueuingStrategySizeCallback<T> | undefined, ): SizeAlgorithm<T> { if (size === undefined) { return (): number => 1; @@ -448,7 +448,7 @@ function peekQueueValue<T>(container: Container<T>): T | "close" { } function readableByteStreamControllerShouldCallPull( - controller: ReadableByteStreamControllerImpl + controller: ReadableByteStreamControllerImpl, ): boolean { const stream = controller[sym.controlledReadableByteStream]; if ( @@ -472,7 +472,7 @@ function readableByteStreamControllerShouldCallPull( } export function readableByteStreamControllerCallPullIfNeeded( - controller: ReadableByteStreamControllerImpl + controller: ReadableByteStreamControllerImpl, ): void { const shouldPull = readableByteStreamControllerShouldCallPull(controller); if (!shouldPull) { @@ -496,20 +496,20 @@ export function readableByteStreamControllerCallPullIfNeeded( }, (e) => { readableByteStreamControllerError(controller, e); - } - ) + }, + ), ); } export function readableByteStreamControllerClearAlgorithms( - controller: ReadableByteStreamControllerImpl + controller: ReadableByteStreamControllerImpl, ): void { (controller as any)[sym.pullAlgorithm] = undefined; (controller as any)[sym.cancelAlgorithm] = undefined; } export function readableByteStreamControllerClose( - controller: ReadableByteStreamControllerImpl + controller: ReadableByteStreamControllerImpl, ): void { const stream = controller[sym.controlledReadableByteStream]; if (controller[sym.closeRequested] || stream[sym.state] !== "readable") { @@ -526,7 +526,7 @@ export function readableByteStreamControllerClose( export function readableByteStreamControllerEnqueue( controller: ReadableByteStreamControllerImpl, - chunk: ArrayBufferView + chunk: ArrayBufferView, ): void { const stream = controller[sym.controlledReadableByteStream]; if (controller[sym.closeRequested] || stream[sym.state] !== "readable") { @@ -540,14 +540,14 @@ export function readableByteStreamControllerEnqueue( controller, transferredBuffer, byteOffset, - byteLength + byteLength, ); } else { assert(controller[sym.queue].length === 0); const transferredView = new Uint8Array( transferredBuffer, byteOffset, - byteLength + byteLength, ); readableStreamFulfillReadRequest(stream, transferredView, false); } @@ -558,7 +558,7 @@ export function readableByteStreamControllerEnqueue( controller, transferredBuffer, byteOffset, - byteLength + byteLength, ); } readableByteStreamControllerCallPullIfNeeded(controller); @@ -568,7 +568,7 @@ function readableByteStreamControllerEnqueueChunkToQueue( controller: ReadableByteStreamControllerImpl, buffer: ArrayBuffer | SharedArrayBuffer, byteOffset: number, - byteLength: number + byteLength: number, ): void { controller[sym.queue].push({ value: buffer, @@ -580,7 +580,7 @@ function readableByteStreamControllerEnqueueChunkToQueue( export function readableByteStreamControllerError( controller: ReadableByteStreamControllerImpl, - e: any + e: any, ): void { const stream = controller[sym.controlledReadableByteStream]; if (stream[sym.state] !== "readable") { @@ -593,7 +593,7 @@ export function readableByteStreamControllerError( } export function readableByteStreamControllerGetDesiredSize( - controller: ReadableByteStreamControllerImpl + controller: ReadableByteStreamControllerImpl, ): number | null { const stream = controller[sym.controlledReadableByteStream]; const state = stream[sym.state]; @@ -607,10 +607,10 @@ export function readableByteStreamControllerGetDesiredSize( } export function readableByteStreamControllerHandleQueueDrain( - controller: ReadableByteStreamControllerImpl + controller: ReadableByteStreamControllerImpl, ): void { assert( - controller[sym.controlledReadableByteStream][sym.state] === "readable" + controller[sym.controlledReadableByteStream][sym.state] === "readable", ); if (controller[sym.queueTotalSize] === 0 && controller[sym.closeRequested]) { readableByteStreamControllerClearAlgorithms(controller); @@ -621,7 +621,7 @@ export function readableByteStreamControllerHandleQueueDrain( } export function readableStreamAddReadRequest<R>( - stream: ReadableStreamImpl<R> + stream: ReadableStreamImpl<R>, ): Promise<ReadableStreamReadResult<R>> { assert(isReadableStreamDefaultReader(stream[sym.reader])); assert(stream[sym.state] === "readable"); @@ -632,7 +632,7 @@ export function readableStreamAddReadRequest<R>( export function readableStreamCancel<T>( stream: ReadableStreamImpl<T>, - reason: any + reason: any, ): Promise<void> { stream[sym.disturbed] = true; if (stream[sym.state] === "closed") { @@ -643,7 +643,7 @@ export function readableStreamCancel<T>( } readableStreamClose(stream); return stream[sym.readableStreamController].then( - () => undefined + () => undefined, ) as Promise<void>; } @@ -661,8 +661,8 @@ export function readableStreamClose<T>(stream: ReadableStreamImpl<T>): void { readableStreamCreateReadResult<T>( undefined, true, - reader[sym.forAuthorCode] - ) + reader[sym.forAuthorCode], + ), ); } reader[sym.readRequests] = []; @@ -675,7 +675,7 @@ export function readableStreamClose<T>(stream: ReadableStreamImpl<T>): void { export function readableStreamCreateReadResult<T>( value: T | undefined, done: boolean, - forAuthorCode: boolean + forAuthorCode: boolean, ): ReadableStreamReadResult<T> { const prototype = forAuthorCode ? Object.prototype : null; assert(typeof done === "boolean"); @@ -688,7 +688,7 @@ export function readableStreamCreateReadResult<T>( } export function readableStreamDefaultControllerCallPullIfNeeded<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): void { const shouldPull = readableStreamDefaultControllerShouldCallPull(controller); if (!shouldPull) { @@ -711,19 +711,19 @@ export function readableStreamDefaultControllerCallPullIfNeeded<T>( }, (e) => { readableStreamDefaultControllerError(controller, e); - } + }, ); } export function readableStreamDefaultControllerCanCloseOrEnqueue<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): boolean { const state = controller[sym.controlledReadableStream][sym.state]; return !controller[sym.closeRequested] && state === "readable"; } export function readableStreamDefaultControllerClearAlgorithms<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): void { (controller as any)[sym.pullAlgorithm] = undefined; (controller as any)[sym.cancelAlgorithm] = undefined; @@ -731,7 +731,7 @@ export function readableStreamDefaultControllerClearAlgorithms<T>( } export function readableStreamDefaultControllerClose<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): void { if (!readableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; @@ -746,7 +746,7 @@ export function readableStreamDefaultControllerClose<T>( export function readableStreamDefaultControllerEnqueue<T>( controller: ReadableStreamDefaultControllerImpl<T>, - chunk: T + chunk: T, ): void { if (!readableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; @@ -770,7 +770,7 @@ export function readableStreamDefaultControllerEnqueue<T>( } export function readableStreamDefaultControllerGetDesiredSize<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): number | null { const stream = controller[sym.controlledReadableStream]; const state = stream[sym.state]; @@ -785,7 +785,7 @@ export function readableStreamDefaultControllerGetDesiredSize<T>( export function readableStreamDefaultControllerError<T>( controller: ReadableStreamDefaultControllerImpl<T>, - e: any + e: any, ): void { const stream = controller[sym.controlledReadableStream]; if (stream[sym.state] !== "readable") { @@ -797,13 +797,13 @@ export function readableStreamDefaultControllerError<T>( } function readableStreamDefaultControllerHasBackpressure<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): boolean { return readableStreamDefaultControllerShouldCallPull(controller); } function readableStreamDefaultControllerShouldCallPull<T>( - controller: ReadableStreamDefaultControllerImpl<T> + controller: ReadableStreamDefaultControllerImpl<T>, ): boolean { const stream = controller[sym.controlledReadableStream]; if ( @@ -824,7 +824,7 @@ function readableStreamDefaultControllerShouldCallPull<T>( } export function readableStreamDefaultReaderRead<R>( - reader: ReadableStreamDefaultReaderImpl<R> + reader: ReadableStreamDefaultReaderImpl<R>, ): Promise<ReadableStreamReadResult<R>> { const stream = reader[sym.ownerReadableStream]; assert(stream); @@ -834,8 +834,8 @@ export function readableStreamDefaultReaderRead<R>( readableStreamCreateReadResult<R>( undefined, true, - reader[sym.forAuthorCode] - ) + reader[sym.forAuthorCode], + ), ); } if (stream[sym.state] === "errored") { @@ -875,24 +875,24 @@ export function readableStreamError(stream: ReadableStreamImpl, e: any): void { export function readableStreamFulfillReadRequest<R>( stream: ReadableStreamImpl<R>, chunk: R, - done: boolean + done: boolean, ): void { const reader = stream[sym.reader]!; const readRequest = reader[sym.readRequests].shift()!; assert(readRequest.resolve); readRequest.resolve( - readableStreamCreateReadResult(chunk, done, reader[sym.forAuthorCode]) + readableStreamCreateReadResult(chunk, done, reader[sym.forAuthorCode]), ); } export function readableStreamGetNumReadRequests( - stream: ReadableStreamImpl + stream: ReadableStreamImpl, ): number { return stream[sym.reader]?.[sym.readRequests].length ?? 0; } export function readableStreamHasDefaultReader( - stream: ReadableStreamImpl + stream: ReadableStreamImpl, ): boolean { const reader = stream[sym.reader]; return !(reader === undefined || !isReadableStreamDefaultReader(reader)); @@ -904,14 +904,14 @@ export function readableStreamPipeTo<T>( preventClose: boolean, preventAbort: boolean, preventCancel: boolean, - signal: AbortSignalImpl | undefined + signal: AbortSignalImpl | undefined, ): Promise<void> { assert(isReadableStream(source)); assert(isWritableStream(dest)); assert( typeof preventClose === "boolean" && typeof preventAbort === "boolean" && - typeof preventCancel === "boolean" + typeof preventCancel === "boolean", ); assert(signal === undefined || signal instanceof AbortSignalImpl); assert(!isReadableStreamLocked(source)); @@ -947,7 +947,7 @@ export function readableStreamPipeTo<T>( shutdownWithAction( () => Promise.all(actions.map((action) => action())), true, - error + error, ); }; if (signal.aborted) { @@ -967,7 +967,7 @@ export function readableStreamPipeTo<T>( function isOrBecomesClosed( stream: ReadableStreamImpl | WritableStreamImpl, promise: Promise<void>, - action: () => void + action: () => void, ): void { if (stream[sym.state] === "closed") { action(); @@ -979,7 +979,7 @@ export function readableStreamPipeTo<T>( function isOrBecomesErrored( stream: ReadableStreamImpl | WritableStreamImpl, promise: Promise<void>, - action: (error: any) => void + action: (error: any) => void, ): void { if (stream[sym.state] === "errored") { action(stream[sym.storedError]); @@ -1012,14 +1012,14 @@ export function readableStreamPipeTo<T>( function shutdownWithAction( action: () => Promise<any>, originalIsError?: boolean, - originalError?: any + originalError?: any, ): void { function doTheRest(): void { setPromiseIsHandledToTrue( action().then( () => finalize(originalIsError, originalError), - (newError) => finalize(true, newError) - ) + (newError) => finalize(true, newError), + ), ); } @@ -1049,7 +1049,7 @@ export function readableStreamPipeTo<T>( !writableStreamCloseQueuedOrInFlight(dest) ) { setPromiseIsHandledToTrue( - waitForWritesToFinish().then(() => finalize(isError, error)) + waitForWritesToFinish().then(() => finalize(isError, error)), ); } finalize(isError, error); @@ -1066,7 +1066,7 @@ export function readableStreamPipeTo<T>( } currentWrite = writableStreamDefaultWriterWrite( writer, - value! + value!, ).then(undefined, () => {}); return false; }); @@ -1094,12 +1094,12 @@ export function readableStreamPipeTo<T>( shutdownWithAction( () => writableStreamAbort(dest, storedError), true, - storedError + storedError, ); } else { shutdown(true, storedError); } - } + }, ); isOrBecomesErrored(dest, writer[sym.closedPromise].promise, (storedError) => { @@ -1107,7 +1107,7 @@ export function readableStreamPipeTo<T>( shutdownWithAction( () => readableStreamCancel(source, storedError), true, - storedError + storedError, ); } else { shutdown(true, storedError); @@ -1127,13 +1127,13 @@ export function readableStreamPipeTo<T>( dest[sym.state] === "closed" ) { const destClosed = new TypeError( - "The destination writable stream closed before all data could be piped to it." + "The destination writable stream closed before all data could be piped to it.", ); if (!preventCancel) { shutdownWithAction( () => readableStreamCancel(source, destClosed), true, - destClosed + destClosed, ); } else { shutdown(true, destClosed); @@ -1146,7 +1146,7 @@ export function readableStreamPipeTo<T>( export function readableStreamReaderGenericCancel<R = any>( reader: ReadableStreamGenericReader<R>, - reason: any + reason: any, ): Promise<void> { const stream = reader[sym.ownerReadableStream]; assert(stream); @@ -1155,7 +1155,7 @@ export function readableStreamReaderGenericCancel<R = any>( export function readableStreamReaderGenericInitialize<R = any>( reader: ReadableStreamGenericReader<R>, - stream: ReadableStreamImpl<R> + stream: ReadableStreamImpl<R>, ): void { reader[sym.forAuthorCode] = true; reader[sym.ownerReadableStream] = stream; @@ -1174,7 +1174,7 @@ export function readableStreamReaderGenericInitialize<R = any>( } export function readableStreamReaderGenericRelease<R = any>( - reader: ReadableStreamGenericReader<R> + reader: ReadableStreamGenericReader<R>, ): void { assert(reader[sym.ownerReadableStream]); assert(reader[sym.ownerReadableStream][sym.reader] === reader); @@ -1194,7 +1194,7 @@ export function readableStreamReaderGenericRelease<R = any>( export function readableStreamTee<T>( stream: ReadableStreamImpl<T>, - cloneForBranch2: boolean + cloneForBranch2: boolean, ): [ReadableStreamImpl<T>, ReadableStreamImpl<T>] { assert(isReadableStream(stream)); assert(typeof cloneForBranch2 === "boolean"); @@ -1225,14 +1225,14 @@ export function readableStreamTee<T>( readableStreamDefaultControllerClose( branch1[ sym.readableStreamController - ] as ReadableStreamDefaultControllerImpl + ] as ReadableStreamDefaultControllerImpl, ); } if (!canceled2) { readableStreamDefaultControllerClose( branch2[ sym.readableStreamController - ] as ReadableStreamDefaultControllerImpl + ] as ReadableStreamDefaultControllerImpl, ); } return; @@ -1248,7 +1248,7 @@ export function readableStreamTee<T>( branch1[ sym.readableStreamController ] as ReadableStreamDefaultControllerImpl, - value1 + value1, ); } if (!canceled2) { @@ -1256,10 +1256,10 @@ export function readableStreamTee<T>( branch2[ sym.readableStreamController ] as ReadableStreamDefaultControllerImpl, - value2 + value2, ); } - } + }, ); setPromiseIsHandledToTrue(readPromise); return Promise.resolve(); @@ -1288,12 +1288,12 @@ export function readableStreamTee<T>( branch1 = createReadableStream( startAlgorithm, pullAlgorithm, - cancel1Algorithm + cancel1Algorithm, ); branch2 = createReadableStream( startAlgorithm, pullAlgorithm, - cancel2Algorithm + cancel2Algorithm, ); setPromiseIsHandledToTrue( reader[sym.closedPromise].promise.catch((r) => { @@ -1301,15 +1301,15 @@ export function readableStreamTee<T>( branch1[ sym.readableStreamController ] as ReadableStreamDefaultControllerImpl, - r + r, ); readableStreamDefaultControllerError( branch2[ sym.readableStreamController ] as ReadableStreamDefaultControllerImpl, - r + r, ); - }) + }), ); return [branch1, branch2]; } @@ -1340,7 +1340,7 @@ function setUpReadableByteStreamController( pullAlgorithm: PullAlgorithm, cancelAlgorithm: CancelAlgorithm, highWaterMark: number, - autoAllocateChunkSize: number | undefined + autoAllocateChunkSize: number | undefined, ): void { assert(stream[sym.readableStreamController] === undefined); if (autoAllocateChunkSize !== undefined) { @@ -1354,7 +1354,7 @@ function setUpReadableByteStreamController( controller[sym.queueTotalSize] = 0; controller[sym.closeRequested] = controller[sym.started] = false; controller[sym.strategyHWM] = validateAndNormalizeHighWaterMark( - highWaterMark + highWaterMark, ); controller[sym.pullAlgorithm] = pullAlgorithm; controller[sym.cancelAlgorithm] = cancelAlgorithm; @@ -1373,19 +1373,19 @@ function setUpReadableByteStreamController( }, (r) => { readableByteStreamControllerError(controller, r); - } - ) + }, + ), ); } export function setUpReadableByteStreamControllerFromUnderlyingSource( stream: ReadableStreamImpl, underlyingByteSource: UnderlyingByteSource, - highWaterMark: number + highWaterMark: number, ): void { assert(underlyingByteSource); const controller: ReadableByteStreamControllerImpl = Object.create( - ReadableByteStreamControllerImpl.prototype + ReadableByteStreamControllerImpl.prototype, ); const startAlgorithm: StartAlgorithm = () => { return invokeOrNoop(underlyingByteSource, "start", controller); @@ -1394,13 +1394,13 @@ export function setUpReadableByteStreamControllerFromUnderlyingSource( underlyingByteSource, "pull", 0, - controller + controller, ); setFunctionName(pullAlgorithm, "[[pullAlgorithm]]"); const cancelAlgorithm = createAlgorithmFromUnderlyingMethod( underlyingByteSource, "cancel", - 1 + 1, ); setFunctionName(cancelAlgorithm, "[[cancelAlgorithm]]"); // 3.13.27.6 Let autoAllocateChunkSize be ? GetV(underlyingByteSource, "autoAllocateChunkSize"). @@ -1412,7 +1412,7 @@ export function setUpReadableByteStreamControllerFromUnderlyingSource( pullAlgorithm, cancelAlgorithm, highWaterMark, - autoAllocateChunkSize + autoAllocateChunkSize, ); } @@ -1423,7 +1423,7 @@ function setUpReadableStreamDefaultController<T>( pullAlgorithm: PullAlgorithm, cancelAlgorithm: CancelAlgorithm, highWaterMark: number, - sizeAlgorithm: SizeAlgorithm<T> + sizeAlgorithm: SizeAlgorithm<T>, ): void { assert(stream[sym.readableStreamController] === undefined); controller[sym.controlledReadableStream] = stream; @@ -1449,8 +1449,8 @@ function setUpReadableStreamDefaultController<T>( }, (r) => { readableStreamDefaultControllerError(controller, r); - } - ) + }, + ), ); } @@ -1458,11 +1458,11 @@ export function setUpReadableStreamDefaultControllerFromUnderlyingSource<T>( stream: ReadableStreamImpl<T>, underlyingSource: UnderlyingSource<T>, highWaterMark: number, - sizeAlgorithm: SizeAlgorithm<T> + sizeAlgorithm: SizeAlgorithm<T>, ): void { assert(underlyingSource); const controller: ReadableStreamDefaultControllerImpl<T> = Object.create( - ReadableStreamDefaultControllerImpl.prototype + ReadableStreamDefaultControllerImpl.prototype, ); const startAlgorithm: StartAlgorithm = (): void | PromiseLike<void> => invokeOrNoop(underlyingSource, "start", controller); @@ -1470,13 +1470,13 @@ export function setUpReadableStreamDefaultControllerFromUnderlyingSource<T>( underlyingSource, "pull", 0, - controller + controller, ); setFunctionName(pullAlgorithm, "[[pullAlgorithm]]"); const cancelAlgorithm: CancelAlgorithm = createAlgorithmFromUnderlyingMethod( underlyingSource, "cancel", - 1 + 1, ); setFunctionName(cancelAlgorithm, "[[cancelAlgorithm]]"); setUpReadableStreamDefaultController( @@ -1486,7 +1486,7 @@ export function setUpReadableStreamDefaultControllerFromUnderlyingSource<T>( pullAlgorithm, cancelAlgorithm, highWaterMark, - sizeAlgorithm + sizeAlgorithm, ); } @@ -1494,7 +1494,7 @@ function setUpTransformStreamDefaultController<I, O>( stream: TransformStreamImpl<I, O>, controller: TransformStreamDefaultControllerImpl<I, O>, transformAlgorithm: TransformAlgorithm<I>, - flushAlgorithm: FlushAlgorithm + flushAlgorithm: FlushAlgorithm, ): void { assert(isTransformStream(stream)); assert(stream[sym.transformStreamController] === undefined); @@ -1506,18 +1506,18 @@ function setUpTransformStreamDefaultController<I, O>( export function setUpTransformStreamDefaultControllerFromTransformer<I, O>( stream: TransformStreamImpl<I, O>, - transformer: Transformer<I, O> + transformer: Transformer<I, O>, ): void { assert(transformer); const controller = Object.create( - TransformStreamDefaultControllerImpl.prototype + TransformStreamDefaultControllerImpl.prototype, ) as TransformStreamDefaultControllerImpl<I, O>; let transformAlgorithm: TransformAlgorithm<I> = (chunk) => { try { transformStreamDefaultControllerEnqueue( controller, // it defaults to no tranformation, so I is assumed to be O - (chunk as unknown) as O + (chunk as unknown) as O, ); } catch (e) { return Promise.reject(e); @@ -1536,13 +1536,13 @@ export function setUpTransformStreamDefaultControllerFromTransformer<I, O>( transformer, "flush", 0, - controller + controller, ); setUpTransformStreamDefaultController( stream, controller, transformAlgorithm, - flushAlgorithm + flushAlgorithm, ); } @@ -1554,7 +1554,7 @@ function setUpWritableStreamDefaultController<W>( closeAlgorithm: CloseAlgorithm, abortAlgorithm: AbortAlgorithm, highWaterMark: number, - sizeAlgorithm: SizeAlgorithm<W> + sizeAlgorithm: SizeAlgorithm<W>, ): void { assert(isWritableStream(stream)); assert(stream[sym.writableStreamController] === undefined); @@ -1569,7 +1569,7 @@ function setUpWritableStreamDefaultController<W>( controller[sym.closeAlgorithm] = closeAlgorithm; controller[sym.abortAlgorithm] = abortAlgorithm; const backpressure = writableStreamDefaultControllerGetBackpressure( - controller + controller, ); writableStreamUpdateBackpressure(stream, backpressure); const startResult = startAlgorithm(); @@ -1578,19 +1578,19 @@ function setUpWritableStreamDefaultController<W>( startPromise.then( () => { assert( - stream[sym.state] === "writable" || stream[sym.state] === "erroring" + stream[sym.state] === "writable" || stream[sym.state] === "erroring", ); controller[sym.started] = true; writableStreamDefaultControllerAdvanceQueueIfNeeded(controller); }, (r) => { assert( - stream[sym.state] === "writable" || stream[sym.state] === "erroring" + stream[sym.state] === "writable" || stream[sym.state] === "erroring", ); controller[sym.started] = true; writableStreamDealWithRejection(stream, r); - } - ) + }, + ), ); } @@ -1598,11 +1598,11 @@ export function setUpWritableStreamDefaultControllerFromUnderlyingSink<W>( stream: WritableStreamImpl<W>, underlyingSink: UnderlyingSink<W>, highWaterMark: number, - sizeAlgorithm: SizeAlgorithm<W> + sizeAlgorithm: SizeAlgorithm<W>, ): void { assert(underlyingSink); const controller = Object.create( - WritableStreamDefaultControllerImpl.prototype + WritableStreamDefaultControllerImpl.prototype, ); const startAlgorithm = (): void | PromiseLike<void> => { return invokeOrNoop(underlyingSink, "start", controller); @@ -1611,19 +1611,19 @@ export function setUpWritableStreamDefaultControllerFromUnderlyingSink<W>( underlyingSink, "write", 1, - controller + controller, ); setFunctionName(writeAlgorithm, "[[writeAlgorithm]]"); const closeAlgorithm = createAlgorithmFromUnderlyingMethod( underlyingSink, "close", - 0 + 0, ); setFunctionName(closeAlgorithm, "[[closeAlgorithm]]"); const abortAlgorithm = createAlgorithmFromUnderlyingMethod( underlyingSink, "abort", - 1 + 1, ); setFunctionName(abortAlgorithm, "[[abortAlgorithm]]"); setUpWritableStreamDefaultController( @@ -1634,12 +1634,12 @@ export function setUpWritableStreamDefaultControllerFromUnderlyingSink<W>( closeAlgorithm, abortAlgorithm, highWaterMark, - sizeAlgorithm + sizeAlgorithm, ); } function transformStreamDefaultControllerClearAlgorithms<I, O>( - controller: TransformStreamDefaultControllerImpl<I, O> + controller: TransformStreamDefaultControllerImpl<I, O>, ): void { (controller as any)[sym.transformAlgorithm] = undefined; (controller as any)[sym.flushAlgorithm] = undefined; @@ -1647,7 +1647,7 @@ function transformStreamDefaultControllerClearAlgorithms<I, O>( export function transformStreamDefaultControllerEnqueue<I, O>( controller: TransformStreamDefaultControllerImpl<I, O>, - chunk: O + chunk: O, ): void { const stream = controller[sym.controlledTransformStream]; const readableController = stream[sym.readable][ @@ -1655,7 +1655,7 @@ export function transformStreamDefaultControllerEnqueue<I, O>( ] as ReadableStreamDefaultControllerImpl<O>; if (!readableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { throw new TypeError( - "TransformStream's readable controller cannot be closed or enqueued." + "TransformStream's readable controller cannot be closed or enqueued.", ); } try { @@ -1665,7 +1665,7 @@ export function transformStreamDefaultControllerEnqueue<I, O>( throw stream[sym.readable][sym.storedError]; } const backpressure = readableStreamDefaultControllerHasBackpressure( - readableController + readableController, ); if (backpressure) { transformStreamSetBackpressure(stream, true); @@ -1674,14 +1674,14 @@ export function transformStreamDefaultControllerEnqueue<I, O>( export function transformStreamDefaultControllerError<I, O>( controller: TransformStreamDefaultControllerImpl<I, O>, - e: any + e: any, ): void { transformStreamError(controller[sym.controlledTransformStream], e); } function transformStreamDefaultControllerPerformTransform<I, O>( controller: TransformStreamDefaultControllerImpl<I, O>, - chunk: I + chunk: I, ): Promise<void> { const transformPromise = controller[sym.transformAlgorithm](chunk); return transformPromise.then(undefined, (r) => { @@ -1692,14 +1692,14 @@ function transformStreamDefaultControllerPerformTransform<I, O>( function transformStreamDefaultSinkAbortAlgorithm<I, O>( stream: TransformStreamImpl<I, O>, - reason: any + reason: any, ): Promise<void> { transformStreamError(stream, reason); return Promise.resolve(undefined); } function transformStreamDefaultSinkCloseAlgorithm<I, O>( - stream: TransformStreamImpl<I, O> + stream: TransformStreamImpl<I, O>, ): Promise<void> { const readable = stream[sym.readable]; const controller = stream[sym.transformStreamController]; @@ -1722,13 +1722,13 @@ function transformStreamDefaultSinkCloseAlgorithm<I, O>( (r) => { transformStreamError(stream, r); throw readable[sym.storedError]; - } + }, ); } function transformStreamDefaultSinkWriteAlgorithm<I, O>( stream: TransformStreamImpl<I, O>, - chunk: I + chunk: I, ): Promise<void> { assert(stream[sym.writable][sym.state] === "writable"); const controller = stream[sym.transformStreamController]; @@ -1744,7 +1744,7 @@ function transformStreamDefaultSinkWriteAlgorithm<I, O>( assert(state === "writable"); return transformStreamDefaultControllerPerformTransform( controller, - chunk + chunk, ); }); } @@ -1752,7 +1752,7 @@ function transformStreamDefaultSinkWriteAlgorithm<I, O>( } function transformStreamDefaultSourcePullAlgorithm<I, O>( - stream: TransformStreamImpl<I, O> + stream: TransformStreamImpl<I, O>, ): Promise<void> { assert(stream[sym.backpressure] === true); assert(stream[sym.backpressureChangePromise] !== undefined); @@ -1762,19 +1762,19 @@ function transformStreamDefaultSourcePullAlgorithm<I, O>( function transformStreamError<I, O>( stream: TransformStreamImpl<I, O>, - e: any + e: any, ): void { readableStreamDefaultControllerError( stream[sym.readable][ sym.readableStreamController ] as ReadableStreamDefaultControllerImpl<O>, - e + e, ); transformStreamErrorWritableAndUnblockWrite(stream, e); } export function transformStreamDefaultControllerTerminate<I, O>( - controller: TransformStreamDefaultControllerImpl<I, O> + controller: TransformStreamDefaultControllerImpl<I, O>, ): void { const stream = controller[sym.controlledTransformStream]; const readableController = stream[sym.readable][ @@ -1787,14 +1787,14 @@ export function transformStreamDefaultControllerTerminate<I, O>( function transformStreamErrorWritableAndUnblockWrite<I, O>( stream: TransformStreamImpl<I, O>, - e: any + e: any, ): void { transformStreamDefaultControllerClearAlgorithms( - stream[sym.transformStreamController] + stream[sym.transformStreamController], ); writableStreamDefaultControllerErrorIfNeeded( stream[sym.writable][sym.writableStreamController]!, - e + e, ); if (stream[sym.backpressure]) { transformStreamSetBackpressure(stream, false); @@ -1803,7 +1803,7 @@ function transformStreamErrorWritableAndUnblockWrite<I, O>( function transformStreamSetBackpressure<I, O>( stream: TransformStreamImpl<I, O>, - backpressure: boolean + backpressure: boolean, ): void { assert(stream[sym.backpressure] !== backpressure); if (stream[sym.backpressureChangePromise] !== undefined) { @@ -1828,12 +1828,12 @@ function transferArrayBuffer(buffer: ArrayBuffer): ArrayBuffer { } export function validateAndNormalizeHighWaterMark( - highWaterMark: number + highWaterMark: number, ): number { highWaterMark = Number(highWaterMark); if (Number.isNaN(highWaterMark) || highWaterMark < 0) { throw new RangeError( - `highWaterMark must be a positive number or Infinity. Received: ${highWaterMark}.` + `highWaterMark must be a positive number or Infinity. Received: ${highWaterMark}.`, ); } return highWaterMark; @@ -1841,7 +1841,7 @@ export function validateAndNormalizeHighWaterMark( export function writableStreamAbort<W>( stream: WritableStreamImpl<W>, - reason: any + reason: any, ): Promise<void> { const state = stream[sym.state]; if (state === "closed" || state === "errored") { @@ -1866,7 +1866,7 @@ export function writableStreamAbort<W>( } function writableStreamAddWriteRequest<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): Promise<void> { assert(isWritableStream(stream)); assert(stream[sym.state] === "writable"); @@ -1876,12 +1876,14 @@ function writableStreamAddWriteRequest<W>( } export function writableStreamClose<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): Promise<void> { const state = stream[sym.state]; if (state === "closed" || state === "errored") { return Promise.reject( - new TypeError("Cannot close an already closed or errored WritableStream.") + new TypeError( + "Cannot close an already closed or errored WritableStream.", + ), ); } assert(!writableStreamCloseQueuedOrInFlight(stream)); @@ -1898,7 +1900,7 @@ export function writableStreamClose<W>( } export function writableStreamCloseQueuedOrInFlight<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): boolean { return !( stream[sym.closeRequest] === undefined && @@ -1908,7 +1910,7 @@ export function writableStreamCloseQueuedOrInFlight<W>( function writableStreamDealWithRejection<W>( stream: WritableStreamImpl<W>, - error: any + error: any, ): void { const state = stream[sym.state]; if (state === "writable") { @@ -1920,7 +1922,7 @@ function writableStreamDealWithRejection<W>( } function writableStreamDefaultControllerAdvanceQueueIfNeeded<W>( - controller: WritableStreamDefaultControllerImpl<W> + controller: WritableStreamDefaultControllerImpl<W>, ): void { const stream = controller[sym.controlledWritableStream]; if (!controller[sym.started]) { @@ -1947,7 +1949,7 @@ function writableStreamDefaultControllerAdvanceQueueIfNeeded<W>( } export function writableStreamDefaultControllerClearAlgorithms<W>( - controller: WritableStreamDefaultControllerImpl<W> + controller: WritableStreamDefaultControllerImpl<W>, ): void { (controller as any)[sym.writeAlgorithm] = undefined; (controller as any)[sym.closeAlgorithm] = undefined; @@ -1956,7 +1958,7 @@ export function writableStreamDefaultControllerClearAlgorithms<W>( } function writableStreamDefaultControllerClose<W>( - controller: WritableStreamDefaultControllerImpl<W> + controller: WritableStreamDefaultControllerImpl<W>, ): void { enqueueValueWithSize(controller, "close", 0); writableStreamDefaultControllerAdvanceQueueIfNeeded(controller); @@ -1964,7 +1966,7 @@ function writableStreamDefaultControllerClose<W>( export function writableStreamDefaultControllerError<W>( controller: WritableStreamDefaultControllerImpl<W>, - error: any + error: any, ): void { const stream = controller[sym.controlledWritableStream]; assert(stream[sym.state] === "writable"); @@ -1974,7 +1976,7 @@ export function writableStreamDefaultControllerError<W>( function writableStreamDefaultControllerErrorIfNeeded<W>( controller: WritableStreamDefaultControllerImpl<W>, - error: any + error: any, ): void { if (controller[sym.controlledWritableStream][sym.state] === "writable") { writableStreamDefaultControllerError(controller, error); @@ -1982,7 +1984,7 @@ function writableStreamDefaultControllerErrorIfNeeded<W>( } function writableStreamDefaultControllerGetBackpressure<W>( - controller: WritableStreamDefaultControllerImpl<W> + controller: WritableStreamDefaultControllerImpl<W>, ): boolean { const desiredSize = writableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; @@ -1990,7 +1992,7 @@ function writableStreamDefaultControllerGetBackpressure<W>( function writableStreamDefaultControllerGetChunkSize<W>( controller: WritableStreamDefaultControllerImpl<W>, - chunk: W + chunk: W, ): number { let returnValue: number; try { @@ -2003,13 +2005,13 @@ function writableStreamDefaultControllerGetChunkSize<W>( } function writableStreamDefaultControllerGetDesiredSize<W>( - controller: WritableStreamDefaultControllerImpl<W> + controller: WritableStreamDefaultControllerImpl<W>, ): number { return controller[sym.strategyHWM] - controller[sym.queueTotalSize]; } function writableStreamDefaultControllerProcessClose<W>( - controller: WritableStreamDefaultControllerImpl<W> + controller: WritableStreamDefaultControllerImpl<W>, ): void { const stream = controller[sym.controlledWritableStream]; writableStreamMarkCloseRequestInFlight(stream); @@ -2024,14 +2026,14 @@ function writableStreamDefaultControllerProcessClose<W>( }, (reason) => { writableStreamFinishInFlightCloseWithError(stream, reason); - } - ) + }, + ), ); } function writableStreamDefaultControllerProcessWrite<W>( controller: WritableStreamDefaultControllerImpl<W>, - chunk: W + chunk: W, ): void { const stream = controller[sym.controlledWritableStream]; writableStreamMarkFirstWriteRequestInFlight(stream); @@ -2048,7 +2050,7 @@ function writableStreamDefaultControllerProcessWrite<W>( state === "writable" ) { const backpressure = writableStreamDefaultControllerGetBackpressure( - controller + controller, ); writableStreamUpdateBackpressure(stream, backpressure); } @@ -2059,15 +2061,15 @@ function writableStreamDefaultControllerProcessWrite<W>( writableStreamDefaultControllerClearAlgorithms(controller); } writableStreamFinishInFlightWriteWithError(stream, reason); - } - ) + }, + ), ); } function writableStreamDefaultControllerWrite<W>( controller: WritableStreamDefaultControllerImpl<W>, chunk: W, - chunkSize: number + chunkSize: number, ): void { const writeRecord = { chunk }; try { @@ -2082,7 +2084,7 @@ function writableStreamDefaultControllerWrite<W>( stream[sym.state] === "writable" ) { const backpressure = writableStreamDefaultControllerGetBackpressure( - controller + controller, ); writableStreamUpdateBackpressure(stream, backpressure); } @@ -2091,7 +2093,7 @@ function writableStreamDefaultControllerWrite<W>( export function writableStreamDefaultWriterAbort<W>( writer: WritableStreamDefaultWriterImpl<W>, - reason: any + reason: any, ): Promise<void> { const stream = writer[sym.ownerWritableStream]; assert(stream); @@ -2099,7 +2101,7 @@ export function writableStreamDefaultWriterAbort<W>( } export function writableStreamDefaultWriterClose<W>( - writer: WritableStreamDefaultWriterImpl<W> + writer: WritableStreamDefaultWriterImpl<W>, ): Promise<void> { const stream = writer[sym.ownerWritableStream]; assert(stream); @@ -2107,7 +2109,7 @@ export function writableStreamDefaultWriterClose<W>( } function writableStreamDefaultWriterCloseWithErrorPropagation<W>( - writer: WritableStreamDefaultWriterImpl<W> + writer: WritableStreamDefaultWriterImpl<W>, ): Promise<void> { const stream = writer[sym.ownerWritableStream]; assert(stream); @@ -2124,7 +2126,7 @@ function writableStreamDefaultWriterCloseWithErrorPropagation<W>( function writableStreamDefaultWriterEnsureClosePromiseRejected<W>( writer: WritableStreamDefaultWriterImpl<W>, - error: any + error: any, ): void { if (writer[sym.closedPromise].reject) { writer[sym.closedPromise].reject!(error); @@ -2138,7 +2140,7 @@ function writableStreamDefaultWriterEnsureClosePromiseRejected<W>( function writableStreamDefaultWriterEnsureReadyPromiseRejected<W>( writer: WritableStreamDefaultWriterImpl<W>, - error: any + error: any, ): void { if (writer[sym.readyPromise].reject) { writer[sym.readyPromise].reject!(error); @@ -2154,7 +2156,7 @@ function writableStreamDefaultWriterEnsureReadyPromiseRejected<W>( export function writableStreamDefaultWriterWrite<W>( writer: WritableStreamDefaultWriterImpl<W>, - chunk: W + chunk: W, ): Promise<void> { const stream = writer[sym.ownerWritableStream]; assert(stream); @@ -2162,7 +2164,7 @@ export function writableStreamDefaultWriterWrite<W>( assert(controller); const chunkSize = writableStreamDefaultControllerGetChunkSize( controller, - chunk + chunk, ); if (stream !== writer[sym.ownerWritableStream]) { return Promise.reject("Writer has incorrect WritableStream."); @@ -2184,7 +2186,7 @@ export function writableStreamDefaultWriterWrite<W>( } export function writableStreamDefaultWriterGetDesiredSize<W>( - writer: WritableStreamDefaultWriterImpl<W> + writer: WritableStreamDefaultWriterImpl<W>, ): number | null { const stream = writer[sym.ownerWritableStream]; const state = stream[sym.state]; @@ -2195,18 +2197,18 @@ export function writableStreamDefaultWriterGetDesiredSize<W>( return 0; } return writableStreamDefaultControllerGetDesiredSize( - stream[sym.writableStreamController]! + stream[sym.writableStreamController]!, ); } export function writableStreamDefaultWriterRelease<W>( - writer: WritableStreamDefaultWriterImpl<W> + writer: WritableStreamDefaultWriterImpl<W>, ): void { const stream = writer[sym.ownerWritableStream]; assert(stream); assert(stream[sym.writer] === writer); const releasedError = new TypeError( - "Writer was released and can no longer be used to monitor the stream's closedness." + "Writer was released and can no longer be used to monitor the stream's closedness.", ); writableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); writableStreamDefaultWriterEnsureClosePromiseRejected(writer, releasedError); @@ -2239,7 +2241,7 @@ function writableStreamFinishErroring<W>(stream: WritableStreamImpl<W>): void { return; } const promise = stream[sym.writableStreamController]; setPromiseIsHandledToTrue( promise.then( @@ -2252,13 +2254,13 @@ function writableStreamFinishErroring<W>(stream: WritableStreamImpl<W>): void { assert(abortRequest.promise.reject); abortRequest.promise.reject(reason); writableStreamRejectCloseAndClosedPromiseIfNeeded(stream); - } - ) + }, + ), ); } function writableStreamFinishInFlightClose<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): void { assert(stream[sym.inFlightCloseRequest]); stream[sym.inFlightCloseRequest]?.resolve!(); @@ -2283,7 +2285,7 @@ function writableStreamFinishInFlightClose<W>( function writableStreamFinishInFlightCloseWithError<W>( stream: WritableStreamImpl<W>, - error: any + error: any, ): void { assert(stream[sym.inFlightCloseRequest]); stream[sym.inFlightCloseRequest]?.reject!(error); @@ -2297,7 +2299,7 @@ function writableStreamFinishInFlightCloseWithError<W>( } function writableStreamFinishInFlightWrite<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): void { assert(stream[sym.inFlightWriteRequest]); stream[sym.inFlightWriteRequest]!.resolve(); @@ -2306,7 +2308,7 @@ function writableStreamFinishInFlightWrite<W>( function writableStreamFinishInFlightWriteWithError<W>( stream: WritableStreamImpl<W>, - error: any + error: any, ): void { assert(stream[sym.inFlightWriteRequest]); stream[sym.inFlightWriteRequest]!.reject!(error); @@ -2316,7 +2318,7 @@ function writableStreamFinishInFlightWriteWithError<W>( } function writableStreamHasOperationMarkedInFlight<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): boolean { return !( stream[sym.inFlightWriteRequest] === undefined && @@ -2325,7 +2327,7 @@ function writableStreamHasOperationMarkedInFlight<W>( } function writableStreamMarkCloseRequestInFlight<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): void { assert(stream[sym.inFlightCloseRequest] === undefined); assert(stream[sym.closeRequest] !== undefined); @@ -2334,7 +2336,7 @@ function writableStreamMarkCloseRequestInFlight<W>( } function writableStreamMarkFirstWriteRequestInFlight<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): void { assert(stream[sym.inFlightWriteRequest] === undefined); assert(stream[sym.writeRequests].length); @@ -2343,7 +2345,7 @@ function writableStreamMarkFirstWriteRequestInFlight<W>( } function writableStreamRejectCloseAndClosedPromiseIfNeeded<W>( - stream: WritableStreamImpl<W> + stream: WritableStreamImpl<W>, ): void { assert(stream[sym.state] === "errored"); if (stream[sym.closeRequest]) { @@ -2360,7 +2362,7 @@ function writableStreamRejectCloseAndClosedPromiseIfNeeded<W>( function writableStreamStartErroring<W>( stream: WritableStreamImpl<W>, - reason: any + reason: any, ): void { assert(stream[sym.storedError] === undefined); assert(stream[sym.state] === "writable"); @@ -2382,7 +2384,7 @@ function writableStreamStartErroring<W>( function writableStreamUpdateBackpressure<W>( stream: WritableStreamImpl<W>, - backpressure: boolean + backpressure: boolean, ): void { assert(stream[sym.state] === "writable"); assert(!writableStreamCloseQueuedOrInFlight(stream)); diff --git a/cli/js/web/streams/queuing_strategy.ts b/cli/js/web/streams/queuing_strategy.ts index 8aa30e142..818f0d51b 100644 --- a/cli/js/web/streams/queuing_strategy.ts +++ b/cli/js/web/streams/queuing_strategy.ts @@ -15,9 +15,9 @@ export class CountQueuingStrategyImpl implements CountQueuingStrategy { } [customInspect](): string { - return `${this.constructor.name} { highWaterMark: ${String( - this.highWaterMark - )}, size: f }`; + return `${this.constructor.name} { highWaterMark: ${ + String(this.highWaterMark) + }, size: f }`; } } @@ -40,9 +40,9 @@ export class ByteLengthQueuingStrategyImpl } [customInspect](): string { - return `${this.constructor.name} { highWaterMark: ${String( - this.highWaterMark - )}, size: f }`; + return `${this.constructor.name} { highWaterMark: ${ + String(this.highWaterMark) + }, size: f }`; } } diff --git a/cli/js/web/streams/readable_byte_stream_controller.ts b/cli/js/web/streams/readable_byte_stream_controller.ts index 4a7ffae12..eb4374604 100644 --- a/cli/js/web/streams/readable_byte_stream_controller.ts +++ b/cli/js/web/streams/readable_byte_stream_controller.ts @@ -42,7 +42,7 @@ export class ReadableByteStreamControllerImpl private constructor() { throw new TypeError( - "ReadableByteStreamController's constructor cannot be called." + "ReadableByteStreamController's constructor cannot be called.", ); } @@ -66,7 +66,7 @@ export class ReadableByteStreamControllerImpl } if (this[sym.controlledReadableByteStream][sym.state] !== "readable") { throw new TypeError( - "ReadableByteStreamController's stream is not in a readable state." + "ReadableByteStreamController's stream is not in a readable state.", ); } readableByteStreamControllerClose(this); @@ -81,12 +81,12 @@ export class ReadableByteStreamControllerImpl } if (this[sym.controlledReadableByteStream][sym.state] !== "readable") { throw new TypeError( - "ReadableByteStreamController's stream is not in a readable state." + "ReadableByteStreamController's stream is not in a readable state.", ); } if (!ArrayBuffer.isView(chunk)) { throw new TypeError( - "You can only enqueue array buffer views when using a ReadableByteStreamController" + "You can only enqueue array buffer views when using a ReadableByteStreamController", ); } if (isDetachedBuffer(chunk.buffer)) { @@ -126,8 +126,8 @@ export class ReadableByteStreamControllerImpl readableStreamCreateReadResult( view, false, - stream[sym.reader]![sym.forAuthorCode] - ) + stream[sym.reader]![sym.forAuthorCode], + ), ); } // 3.11.5.2.5 If autoAllocateChunkSize is not undefined, @@ -137,13 +137,13 @@ export class ReadableByteStreamControllerImpl } [customInspect](): string { - return `${this.constructor.name} { byobRequest: ${String( - this.byobRequest - )}, desiredSize: ${String(this.desiredSize)} }`; + return `${this.constructor.name} { byobRequest: ${ + String(this.byobRequest) + }, desiredSize: ${String(this.desiredSize)} }`; } } setFunctionName( ReadableByteStreamControllerImpl, - "ReadableByteStreamController" + "ReadableByteStreamController", ); diff --git a/cli/js/web/streams/readable_stream.ts b/cli/js/web/streams/readable_stream.ts index cf730d23a..086535bd2 100644 --- a/cli/js/web/streams/readable_stream.ts +++ b/cli/js/web/streams/readable_stream.ts @@ -41,10 +41,10 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { underlyingSource: UnderlyingByteSource | UnderlyingSource<R> = {}, strategy: | { - highWaterMark?: number; - size?: undefined; - } - | QueuingStrategy<R> = {} + highWaterMark?: number; + size?: undefined; + } + | QueuingStrategy<R> = {}, ) { initializeReadableStream(this); const { size } = strategy; @@ -54,14 +54,14 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { if (isUnderlyingByteSource(underlyingSource)) { if (size !== undefined) { throw new RangeError( - `When underlying source is "bytes", strategy.size must be undefined.` + `When underlying source is "bytes", strategy.size must be undefined.`, ); } highWaterMark = validateAndNormalizeHighWaterMark(highWaterMark ?? 0); setUpReadableByteStreamControllerFromUnderlyingSource( this, underlyingSource, - highWaterMark + highWaterMark, ); } else if (type === undefined) { const sizeAlgorithm = makeSizeAlgorithmFromSizeFunction(size); @@ -70,11 +70,11 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { this, underlyingSource, highWaterMark, - sizeAlgorithm + sizeAlgorithm, ); } else { throw new RangeError( - `Valid values for underlyingSource are "bytes" or undefined. Received: "${type}".` + `Valid values for underlyingSource are "bytes" or undefined. Received: "${type}".`, ); } } @@ -93,7 +93,7 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { } if (isReadableStreamLocked(this)) { return Promise.reject( - new TypeError("Cannot cancel a locked ReadableStream.") + new TypeError("Cannot cancel a locked ReadableStream."), ); } return readableStreamCancel(this, reason); @@ -132,7 +132,7 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { writable: WritableStream<R>; readable: ReadableStream<T>; }, - { preventClose, preventAbort, preventCancel, signal }: PipeOptions = {} + { preventClose, preventAbort, preventCancel, signal }: PipeOptions = {}, ): ReadableStream<T> { if (!isReadableStream(this)) { throw new TypeError("Invalid ReadableStream."); @@ -161,7 +161,7 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { preventClose, preventAbort, preventCancel, - signal + signal, ); setPromiseIsHandledToTrue(promise); return readable; @@ -169,14 +169,14 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { pipeTo( dest: WritableStream<R>, - { preventClose, preventAbort, preventCancel, signal }: PipeOptions = {} + { preventClose, preventAbort, preventCancel, signal }: PipeOptions = {}, ): Promise<void> { if (!isReadableStream(this)) { return Promise.reject(new TypeError("Invalid ReadableStream.")); } if (!isWritableStream(dest)) { return Promise.reject( - new TypeError("dest is not a valid WritableStream.") + new TypeError("dest is not a valid WritableStream."), ); } preventClose = Boolean(preventClose); @@ -197,7 +197,7 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { preventClose, preventAbort, preventCancel, - signal + signal, ); } @@ -215,7 +215,7 @@ export class ReadableStreamImpl<R = any> implements ReadableStream<R> { [Symbol.asyncIterator]( options: { preventCancel?: boolean; - } = {} + } = {}, ): AsyncIterableIterator<R> { return this.getIterator(options); } diff --git a/cli/js/web/streams/readable_stream_async_iterator.ts b/cli/js/web/streams/readable_stream_async_iterator.ts index cd656e73d..c6b9759a5 100644 --- a/cli/js/web/streams/readable_stream_async_iterator.ts +++ b/cli/js/web/streams/readable_stream_async_iterator.ts @@ -12,25 +12,24 @@ import { import { assert } from "../../util.ts"; // eslint-disable-next-line @typescript-eslint/no-explicit-any -const AsyncIteratorPrototype: AsyncIterableIterator<any> = Object.getPrototypeOf( - Object.getPrototypeOf(async function* () {}).prototype -); +const AsyncIteratorPrototype: AsyncIterableIterator<any> = Object + .getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); -export const ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIterator = Object.setPrototypeOf( - { +export const ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIterator = + Object.setPrototypeOf({ next( - this: ReadableStreamAsyncIterator + this: ReadableStreamAsyncIterator, // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Promise<ReadableStreamReadResult<any>> { if (!isReadableStreamAsyncIterator(this)) { return Promise.reject( - new TypeError("invalid ReadableStreamAsyncIterator.") + new TypeError("invalid ReadableStreamAsyncIterator."), ); } const reader = this[sym.asyncIteratorReader]; if (!reader[sym.ownerReadableStream]) { return Promise.reject( - new TypeError("reader owner ReadableStream is undefined.") + new TypeError("reader owner ReadableStream is undefined."), ); } return readableStreamDefaultReaderRead(reader).then((result) => { @@ -47,23 +46,23 @@ export const ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIterator = return( this: ReadableStreamAsyncIterator, // eslint-disable-next-line @typescript-eslint/no-explicit-any - value?: any | PromiseLike<any> + value?: any | PromiseLike<any>, // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Promise<ReadableStreamReadResult<any>> { if (!isReadableStreamAsyncIterator(this)) { return Promise.reject( - new TypeError("invalid ReadableStreamAsyncIterator.") + new TypeError("invalid ReadableStreamAsyncIterator."), ); } const reader = this[sym.asyncIteratorReader]; if (!reader[sym.ownerReadableStream]) { return Promise.reject( - new TypeError("reader owner ReadableStream is undefined.") + new TypeError("reader owner ReadableStream is undefined."), ); } if (reader[sym.readRequests].length) { return Promise.reject( - new TypeError("reader has outstanding read requests.") + new TypeError("reader has outstanding read requests."), ); } if (!this[sym.preventCancel]) { @@ -74,8 +73,8 @@ export const ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIterator = ); } readableStreamReaderGenericRelease(reader); - return Promise.resolve(readableStreamCreateReadResult(value, true, true)); + return Promise.resolve( + readableStreamCreateReadResult(value, true, true), + ); }, - }, - AsyncIteratorPrototype -); + }, AsyncIteratorPrototype); diff --git a/cli/js/web/streams/readable_stream_default_controller.ts b/cli/js/web/streams/readable_stream_default_controller.ts index 066bc8a8f..8536712b9 100644 --- a/cli/js/web/streams/readable_stream_default_controller.ts +++ b/cli/js/web/streams/readable_stream_default_controller.ts @@ -41,7 +41,7 @@ export class ReadableStreamDefaultControllerImpl<R = any> private constructor() { throw new TypeError( - "ReadableStreamDefaultController's constructor cannot be called." + "ReadableStreamDefaultController's constructor cannot be called.", ); } @@ -58,7 +58,7 @@ export class ReadableStreamDefaultControllerImpl<R = any> } if (!readableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError( - "ReadableStreamDefaultController cannot close or enqueue." + "ReadableStreamDefaultController cannot close or enqueue.", ); } readableStreamDefaultControllerClose(this); @@ -104,8 +104,8 @@ export class ReadableStreamDefaultControllerImpl<R = any> readableStreamCreateReadResult( chunk, false, - stream[sym.reader]![sym.forAuthorCode] - ) + stream[sym.reader]![sym.forAuthorCode], + ), ); } const pendingPromise = readableStreamAddReadRequest(stream); @@ -114,13 +114,13 @@ export class ReadableStreamDefaultControllerImpl<R = any> } [customInspect](): string { - return `${this.constructor.name} { desiredSize: ${String( - this.desiredSize - )} }`; + return `${this.constructor.name} { desiredSize: ${ + String(this.desiredSize) + } }`; } } setFunctionName( ReadableStreamDefaultControllerImpl, - "ReadableStreamDefaultController" + "ReadableStreamDefaultController", ); diff --git a/cli/js/web/streams/readable_stream_default_reader.ts b/cli/js/web/streams/readable_stream_default_reader.ts index 4ed0a5c7c..88260effb 100644 --- a/cli/js/web/streams/readable_stream_default_reader.ts +++ b/cli/js/web/streams/readable_stream_default_reader.ts @@ -37,12 +37,12 @@ export class ReadableStreamDefaultReaderImpl<R = any> get closed(): Promise<void> { if (!isReadableStreamDefaultReader(this)) { return Promise.reject( - new TypeError("Invalid ReadableStreamDefaultReader.") + new TypeError("Invalid ReadableStreamDefaultReader."), ); } return ( this[sym.closedPromise].promise ?? - Promise.reject(new TypeError("Invalid reader.")) + Promise.reject(new TypeError("Invalid reader.")) ); } @@ -50,7 +50,7 @@ export class ReadableStreamDefaultReaderImpl<R = any> cancel(reason?: any): Promise<void> { if (!isReadableStreamDefaultReader(this)) { return Promise.reject( - new TypeError("Invalid ReadableStreamDefaultReader.") + new TypeError("Invalid ReadableStreamDefaultReader."), ); } if (!this[sym.ownerReadableStream]) { @@ -62,7 +62,7 @@ export class ReadableStreamDefaultReaderImpl<R = any> read(): Promise<ReadableStreamReadResult<R>> { if (!isReadableStreamDefaultReader(this)) { return Promise.reject( - new TypeError("Invalid ReadableStreamDefaultReader.") + new TypeError("Invalid ReadableStreamDefaultReader."), ); } if (!this[sym.ownerReadableStream]) { diff --git a/cli/js/web/streams/symbols.ts b/cli/js/web/streams/symbols.ts index 9c0a336e5..82d668598 100644 --- a/cli/js/web/streams/symbols.ts +++ b/cli/js/web/streams/symbols.ts @@ -20,7 +20,7 @@ export const closedPromise = Symbol("closedPromise"); export const closeRequest = Symbol("closeRequest"); export const closeRequested = Symbol("closeRequested"); export const controlledReadableByteStream = Symbol( - "controlledReadableByteStream" + "controlledReadableByteStream", ); export const controlledReadableStream = Symbol("controlledReadableStream"); export const controlledTransformStream = Symbol("controlledTransformStream"); diff --git a/cli/js/web/streams/transform_stream.ts b/cli/js/web/streams/transform_stream.ts index 1c63a553b..f6924aead 100644 --- a/cli/js/web/streams/transform_stream.ts +++ b/cli/js/web/streams/transform_stream.ts @@ -29,7 +29,7 @@ export class TransformStreamImpl<I = any, O = any> constructor( transformer: Transformer<I, O> = {}, writableStrategy: QueuingStrategy<I> = {}, - readableStrategy: QueuingStrategy<O> = {} + readableStrategy: QueuingStrategy<O> = {}, ) { const writableSizeFunction = writableStrategy.size; let writableHighWaterMark = writableStrategy.highWaterMark; @@ -38,36 +38,36 @@ export class TransformStreamImpl<I = any, O = any> const writableType = transformer.writableType; if (writableType !== undefined) { throw new RangeError( - `Expected transformer writableType to be undefined, received "${String( - writableType - )}"` + `Expected transformer writableType to be undefined, received "${ + String(writableType) + }"`, ); } const writableSizeAlgorithm = makeSizeAlgorithmFromSizeFunction( - writableSizeFunction + writableSizeFunction, ); if (writableHighWaterMark === undefined) { writableHighWaterMark = 1; } writableHighWaterMark = validateAndNormalizeHighWaterMark( - writableHighWaterMark + writableHighWaterMark, ); const readableType = transformer.readableType; if (readableType !== undefined) { throw new RangeError( - `Expected transformer readableType to be undefined, received "${String( - readableType - )}"` + `Expected transformer readableType to be undefined, received "${ + String(readableType) + }"`, ); } const readableSizeAlgorithm = makeSizeAlgorithmFromSizeFunction( - readableSizeFunction + readableSizeFunction, ); if (readableHighWaterMark === undefined) { readableHighWaterMark = 1; } readableHighWaterMark = validateAndNormalizeHighWaterMark( - readableHighWaterMark + readableHighWaterMark, ); const startPromise = getDeferred<void>(); initializeTransformStream( @@ -76,7 +76,7 @@ export class TransformStreamImpl<I = any, O = any> writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, - readableSizeAlgorithm + readableSizeAlgorithm, ); // the brand check expects this, and the brand check occurs in the following // but the property hasn't been defined. @@ -89,7 +89,7 @@ export class TransformStreamImpl<I = any, O = any> const startResult: void | PromiseLike<void> = invokeOrNoop( transformer, "start", - this[sym.transformStreamController] + this[sym.transformStreamController], ); startPromise.resolve(startResult); } @@ -109,9 +109,9 @@ export class TransformStreamImpl<I = any, O = any> } [customInspect](): string { - return `${this.constructor.name} {\n readable: ${inspect( - this.readable - )}\n writable: ${inspect(this.writable)}\n}`; + return `${this.constructor.name} {\n readable: ${ + inspect(this.readable) + }\n writable: ${inspect(this.writable)}\n}`; } } diff --git a/cli/js/web/streams/transform_stream_default_controller.ts b/cli/js/web/streams/transform_stream_default_controller.ts index 22087fb0b..54f1e9f2d 100644 --- a/cli/js/web/streams/transform_stream_default_controller.ts +++ b/cli/js/web/streams/transform_stream_default_controller.ts @@ -24,7 +24,7 @@ export class TransformStreamDefaultControllerImpl<I = any, O = any> private constructor() { throw new TypeError( - "TransformStreamDefaultController's constructor cannot be called." + "TransformStreamDefaultController's constructor cannot be called.", ); } @@ -36,7 +36,7 @@ export class TransformStreamDefaultControllerImpl<I = any, O = any> sym.readable ][sym.readableStreamController]; return readableStreamDefaultControllerGetDesiredSize( - readableController as ReadableStreamDefaultControllerImpl<O> + readableController as ReadableStreamDefaultControllerImpl<O>, ); } @@ -63,13 +63,13 @@ export class TransformStreamDefaultControllerImpl<I = any, O = any> } [customInspect](): string { - return `${this.constructor.name} { desiredSize: ${String( - this.desiredSize - )} }`; + return `${this.constructor.name} { desiredSize: ${ + String(this.desiredSize) + } }`; } } setFunctionName( TransformStreamDefaultControllerImpl, - "TransformStreamDefaultController" + "TransformStreamDefaultController", ); diff --git a/cli/js/web/streams/writable_stream.ts b/cli/js/web/streams/writable_stream.ts index 2dea5311b..94bedb941 100644 --- a/cli/js/web/streams/writable_stream.ts +++ b/cli/js/web/streams/writable_stream.ts @@ -36,7 +36,7 @@ export class WritableStreamImpl<W = any> implements WritableStream<W> { constructor( underlyingSink: UnderlyingSink = {}, - strategy: QueuingStrategy = {} + strategy: QueuingStrategy = {}, ) { initializeWritableStream(this); const size = strategy.size; @@ -51,7 +51,7 @@ export class WritableStreamImpl<W = any> implements WritableStream<W> { this, underlyingSink, highWaterMark, - sizeAlgorithm + sizeAlgorithm, ); } @@ -69,7 +69,7 @@ export class WritableStreamImpl<W = any> implements WritableStream<W> { } if (isWritableStreamLocked(this)) { return Promise.reject( - new TypeError("Cannot abort a locked WritableStream.") + new TypeError("Cannot abort a locked WritableStream."), ); } return writableStreamAbort(this, reason); @@ -81,12 +81,12 @@ export class WritableStreamImpl<W = any> implements WritableStream<W> { } if (isWritableStreamLocked(this)) { return Promise.reject( - new TypeError("Cannot abort a locked WritableStream.") + new TypeError("Cannot abort a locked WritableStream."), ); } if (writableStreamCloseQueuedOrInFlight(this)) { return Promise.reject( - new TypeError("Cannot close an already closing WritableStream.") + new TypeError("Cannot close an already closing WritableStream."), ); } return writableStreamClose(this); diff --git a/cli/js/web/streams/writable_stream_default_controller.ts b/cli/js/web/streams/writable_stream_default_controller.ts index 0fe5f7ef9..960060b8f 100644 --- a/cli/js/web/streams/writable_stream_default_controller.ts +++ b/cli/js/web/streams/writable_stream_default_controller.ts @@ -30,7 +30,7 @@ export class WritableStreamDefaultControllerImpl<W> private constructor() { throw new TypeError( - "WritableStreamDefaultController's constructor cannot be called." + "WritableStreamDefaultController's constructor cannot be called.", ); } @@ -64,5 +64,5 @@ export class WritableStreamDefaultControllerImpl<W> setFunctionName( WritableStreamDefaultControllerImpl, - "WritableStreamDefaultController" + "WritableStreamDefaultController", ); diff --git a/cli/js/web/streams/writable_stream_default_writer.ts b/cli/js/web/streams/writable_stream_default_writer.ts index 2e19af923..34e664e95 100644 --- a/cli/js/web/streams/writable_stream_default_writer.ts +++ b/cli/js/web/streams/writable_stream_default_writer.ts @@ -68,7 +68,7 @@ export class WritableStreamDefaultWriterImpl<W> get closed(): Promise<void> { if (!isWritableStreamDefaultWriter(this)) { return Promise.reject( - new TypeError("Invalid WritableStreamDefaultWriter.") + new TypeError("Invalid WritableStreamDefaultWriter."), ); } return this[sym.closedPromise].promise; @@ -87,7 +87,7 @@ export class WritableStreamDefaultWriterImpl<W> get ready(): Promise<void> { if (!isWritableStreamDefaultWriter(this)) { return Promise.reject( - new TypeError("Invalid WritableStreamDefaultWriter.") + new TypeError("Invalid WritableStreamDefaultWriter."), ); } return this[sym.readyPromise].promise; @@ -97,12 +97,12 @@ export class WritableStreamDefaultWriterImpl<W> abort(reason: any): Promise<void> { if (!isWritableStreamDefaultWriter(this)) { return Promise.reject( - new TypeError("Invalid WritableStreamDefaultWriter.") + new TypeError("Invalid WritableStreamDefaultWriter."), ); } if (!this[sym.ownerWritableStream]) { Promise.reject( - new TypeError("WritableStreamDefaultWriter has no owner.") + new TypeError("WritableStreamDefaultWriter has no owner."), ); } return writableStreamDefaultWriterAbort(this, reason); @@ -111,18 +111,18 @@ export class WritableStreamDefaultWriterImpl<W> close(): Promise<void> { if (!isWritableStreamDefaultWriter(this)) { return Promise.reject( - new TypeError("Invalid WritableStreamDefaultWriter.") + new TypeError("Invalid WritableStreamDefaultWriter."), ); } const stream = this[sym.ownerWritableStream]; if (!stream) { Promise.reject( - new TypeError("WritableStreamDefaultWriter has no owner.") + new TypeError("WritableStreamDefaultWriter has no owner."), ); } if (writableStreamCloseQueuedOrInFlight(stream)) { Promise.reject( - new TypeError("Stream is in an invalid state to be closed.") + new TypeError("Stream is in an invalid state to be closed."), ); } return writableStreamDefaultWriterClose(this); @@ -143,21 +143,21 @@ export class WritableStreamDefaultWriterImpl<W> write(chunk: W): Promise<void> { if (!isWritableStreamDefaultWriter(this)) { return Promise.reject( - new TypeError("Invalid WritableStreamDefaultWriter.") + new TypeError("Invalid WritableStreamDefaultWriter."), ); } if (!this[sym.ownerWritableStream]) { Promise.reject( - new TypeError("WritableStreamDefaultWriter has no owner.") + new TypeError("WritableStreamDefaultWriter has no owner."), ); } return writableStreamDefaultWriterWrite(this, chunk); } [customInspect](): string { - return `${this.constructor.name} { closed: Promise, desiredSize: ${String( - this.desiredSize - )}, ready: Promise }`; + return `${this.constructor.name} { closed: Promise, desiredSize: ${ + String(this.desiredSize) + }, ready: Promise }`; } } diff --git a/cli/js/web/text_encoding.ts b/cli/js/web/text_encoding.ts index d225c6928..97848cb77 100644 --- a/cli/js/web/text_encoding.ts +++ b/cli/js/web/text_encoding.ts @@ -105,7 +105,7 @@ export function atob(s: string): string { if (rem === 1 || /[^+/0-9A-Za-z]/.test(s)) { throw new DOMException( "The string to be decoded is not correctly encoded", - "DataDecodeError" + "DataDecodeError", ); } @@ -129,7 +129,7 @@ export function btoa(s: string): string { if (charCode > 0xff) { throw new TypeError( "The string to be encoded contains characters " + - "outside of the Latin1 range." + "outside of the Latin1 range.", ); } byteArray.push(charCode); @@ -157,7 +157,7 @@ class SingleByteDecoder implements Decoder { constructor( index: number[], - { ignoreBOM = false, fatal = false }: DecoderOptions = {} + { ignoreBOM = false, fatal = false }: DecoderOptions = {}, ) { if (ignoreBOM) { throw new TypeError("Ignoring the BOM is available only with utf-8."); @@ -222,7 +222,7 @@ const decoders = new Map<string, (options: DecoderOptions) => Decoder>(); // Single byte decoders are an array of code point lookups const encodingIndexes = new Map<string, number[]>(); -// prettier-ignore +// deno-fmt-ignore encodingIndexes.set("windows-1252", [ 8364, 129, @@ -358,7 +358,7 @@ for (const [key, index] of encodingIndexes) { key, (options: DecoderOptions): SingleByteDecoder => { return new SingleByteDecoder(index, options); - } + }, ); } @@ -442,7 +442,7 @@ export class TextDecoder { const encoding = encodings.get(label); if (!encoding) { throw new RangeError( - `The encoding label provided ('${label}') is invalid.` + `The encoding label provided ('${label}') is invalid.`, ); } if (!decoders.has(encoding) && encoding !== "utf-8") { @@ -453,7 +453,7 @@ export class TextDecoder { decode( input?: BufferSource, - options: TextDecodeOptions = { stream: false } + options: TextDecodeOptions = { stream: false }, ): string { if (options.stream) { throw new TypeError("Stream not supported."); diff --git a/cli/js/web/timers.ts b/cli/js/web/timers.ts index e8eacb402..71aef5f85 100644 --- a/cli/js/web/timers.ts +++ b/cli/js/web/timers.ts @@ -149,7 +149,7 @@ function unschedule(timer: Timer): void { const nextDueNode: DueNode | null = dueTree.min(); setOrClearGlobalTimeout( nextDueNode && nextDueNode.due, - OriginalDate.now() + OriginalDate.now(), ); } } else { @@ -203,7 +203,7 @@ function setTimer( cb: (...args: Args) => void, delay: number, args: Args, - repeat: boolean + repeat: boolean, ): number { // Bind `args` to the callback and bind `this` to globalThis(global). const callback: () => void = cb.bind(globalThis, ...args); @@ -215,7 +215,7 @@ function setTimer( console.warn( `${delay} does not fit into` + " a 32-bit signed integer." + - "\nTimeout duration was set to 1." + "\nTimeout duration was set to 1.", ); delay = 1; } diff --git a/cli/js/web/url.ts b/cli/js/web/url.ts index 544168d80..f466f9583 100644 --- a/cli/js/web/url.ts +++ b/cli/js/web/url.ts @@ -86,14 +86,14 @@ function parse(url: string, isBase = true): URLParts | undefined { [restAuthentication, restAuthority] = takePattern(restAuthority, /^(.*)@/); [parts.username, restAuthentication] = takePattern( restAuthentication, - /^([^:]*)/ + /^([^:]*)/, ); parts.username = encodeUserinfo(parts.username); [parts.password] = takePattern(restAuthentication, /^:(.*)/); parts.password = encodeUserinfo(parts.password); [parts.hostname, restAuthority] = takePattern( restAuthority, - /^(\[[0-9a-fA-F.:]{2,}\]|[^:]+)/ + /^(\[[0-9a-fA-F.:]{2,}\]|[^:]+)/, ); [parts.port] = takePattern(restAuthority, /^:(.*)/); if (!isValidPort(parts.port)) { @@ -122,8 +122,7 @@ function parse(url: string, isBase = true): URLParts | undefined { function generateUUID(): string { return "00000000-0000-4000-8000-000000000000".replace(/[0]/g, (): string => // random integer from 0 to 15 as a hex digit. - (getRandomValues(new Uint8Array(1))[0] % 16).toString(16) - ); + (getRandomValues(new Uint8Array(1))[0] % 16).toString(16)); } // Keep it outside of URL to avoid any attempts of access. @@ -174,7 +173,7 @@ function normalizePath(path: string, isFilePath = false): string { function resolvePathFromBase( path: string, basePath: string, - isFilePath = false + isFilePath = false, ): string { let normalizedPath = normalizePath(path, isFilePath); let normalizedBasePath = normalizePath(basePath, isFilePath); @@ -185,11 +184,11 @@ function resolvePathFromBase( let baseDriveLetter: string; [driveLetter, normalizedPath] = takePattern( normalizedPath, - /^(\/[A-Za-z]:)(?=\/)/ + /^(\/[A-Za-z]:)(?=\/)/, ); [baseDriveLetter, normalizedBasePath] = takePattern( normalizedBasePath, - /^(\/[A-Za-z]:)(?=\/)/ + /^(\/[A-Za-z]:)(?=\/)/, ); driveLetterPrefix = driveLetter || baseDriveLetter; } @@ -306,10 +305,9 @@ export class URLImpl implements URL { } get href(): string { - const authentication = - this.username || this.password - ? `${this.username}${this.password ? ":" + this.password : ""}@` - : ""; + const authentication = this.username || this.password + ? `${this.username}${this.password ? ":" + this.password : ""}@` + : ""; const host = this.host; const slashes = host ? "//" : parts.get(this)!.slashes; let pathname = this.pathname; @@ -421,8 +419,9 @@ export class URLImpl implements URL { } } - const urlParts = - typeof url === "string" ? parse(url, !baseParts) : parts.get(url); + const urlParts = typeof url === "string" + ? parse(url, !baseParts) + : parts.get(url); if (urlParts == undefined) { throw new TypeError("Invalid URL."); } @@ -441,7 +440,7 @@ export class URLImpl implements URL { path: resolvePathFromBase( urlParts.path, baseParts.path || "/", - baseParts.protocol == "file" + baseParts.protocol == "file", ), query: urlParts.query, hash: urlParts.hash, @@ -522,28 +521,28 @@ function charInC0ControlSet(c: string): boolean { } function charInSearchSet(c: string): boolean { - // prettier-ignore + // deno-fmt-ignore return charInC0ControlSet(c) || ["\u0020", "\u0022", "\u0023", "\u0027", "\u003C", "\u003E"].includes(c) || c > "\u007E"; } function charInFragmentSet(c: string): boolean { - // prettier-ignore + // deno-fmt-ignore return charInC0ControlSet(c) || ["\u0020", "\u0022", "\u003C", "\u003E", "\u0060"].includes(c); } function charInPathSet(c: string): boolean { - // prettier-ignore + // deno-fmt-ignore return charInFragmentSet(c) || ["\u0023", "\u003F", "\u007B", "\u007D"].includes(c); } function charInUserinfoSet(c: string): boolean { // "\u0027" ("'") seemingly isn't in the spec, but matches Chrome and Firefox. - // prettier-ignore + // deno-fmt-ignore return charInPathSet(c) || ["\u0027", "\u002F", "\u003A", "\u003B", "\u003D", "\u0040", "\u005B", "\u005C", "\u005D", "\u005E", "\u007C"].includes(c); } function charIsForbiddenInHost(c: string): boolean { - // prettier-ignore + // deno-fmt-ignore return ["\u0000", "\u0009", "\u000A", "\u000D", "\u0020", "\u0023", "\u0025", "\u002F", "\u003A", "\u003C", "\u003E", "\u003F", "\u0040", "\u005B", "\u005C", "\u005D", "\u005E"].includes(c); } @@ -591,8 +590,9 @@ function encodeHostname(s: string, isSpecial = true): string { if (result.match(/%(?![0-9A-Fa-f]{2})/) != null) { throw new TypeError("Invalid hostname."); } - result = result.replace(/%(.{2})/g, (_, hex) => - String.fromCodePoint(Number(`0x${hex}`)) + result = result.replace( + /%(.{2})/g, + (_, hex) => String.fromCodePoint(Number(`0x${hex}`)), ); // IDNA domain to ASCII. diff --git a/cli/js/web/url_search_params.ts b/cli/js/web/url_search_params.ts index b4d199fbc..f3e247522 100644 --- a/cli/js/web/url_search_params.ts +++ b/cli/js/web/url_search_params.ts @@ -57,14 +57,14 @@ export class URLSearchParamsImpl implements URLSearchParams { }; #handleArrayInitialization = ( - init: string[][] | Iterable<[string, string]> + init: string[][] | Iterable<[string, string]>, ): void => { // Overload: sequence<sequence<USVString>> for (const tuple of init) { // If pair does not contain exactly two items, then throw a TypeError. if (tuple.length !== 2) { throw new TypeError( - "URLSearchParams.constructor tuple array argument must only contain pair elements" + "URLSearchParams.constructor tuple array argument must only contain pair elements", ); } this.#append(tuple[0], tuple[1]); @@ -175,7 +175,7 @@ export class URLSearchParamsImpl implements URLSearchParams { forEach( callbackfn: (value: string, key: string, parent: this) => void, // eslint-disable-next-line @typescript-eslint/no-explicit-any - thisArg?: any + thisArg?: any, ): void { requiredArguments("URLSearchParams.forEach", arguments.length, 1); @@ -212,7 +212,7 @@ export class URLSearchParamsImpl implements URLSearchParams { return this.#params .map( (tuple) => - `${encodeURIComponent(tuple[0])}=${encodeURIComponent(tuple[1])}` + `${encodeURIComponent(tuple[0])}=${encodeURIComponent(tuple[1])}`, ) .join("&"); } diff --git a/cli/js/web/util.ts b/cli/js/web/util.ts index 281048cd8..3165c37a7 100644 --- a/cli/js/web/util.ts +++ b/cli/js/web/util.ts @@ -27,7 +27,7 @@ export function isInvalidDate(x: Date): boolean { export function requiredArguments( name: string, length: number, - required: number + required: number, ): void { if (length < required) { const errMsg = `${name} requires at least ${required} argument${ @@ -43,7 +43,7 @@ export function immutableDefine( o: any, p: string | number | symbol, // eslint-disable-next-line @typescript-eslint/no-explicit-any - value: any + value: any, ): void { Object.defineProperty(o, p, { value, @@ -64,7 +64,7 @@ export function hasOwnProperty(obj: unknown, v: PropertyKey): boolean { * * @internal */ export function isIterable<T, P extends keyof T, K extends T[P]>( - o: T + o: T, ): o is T & Iterable<[P, K]> { // checks for null and undefined if (o == null) { @@ -81,12 +81,12 @@ function cloneArrayBuffer( srcBuffer: ArrayBufferLike, srcByteOffset: number, srcLength: number, - cloneConstructor: ArrayBufferConstructor | SharedArrayBufferConstructor + cloneConstructor: ArrayBufferConstructor | SharedArrayBufferConstructor, ): InstanceType<typeof cloneConstructor> { // this function fudges the return type but SharedArrayBuffer is disabled for a while anyway return srcBuffer.slice( srcByteOffset, - srcByteOffset + srcLength + srcByteOffset + srcLength, ) as InstanceType<typeof cloneConstructor>; } @@ -122,7 +122,7 @@ export function cloneValue(value: any): any { value, 0, value.byteLength, - ArrayBuffer + ArrayBuffer, ); objectCloneMemo.set(value, cloned); return cloned; @@ -142,7 +142,7 @@ export function cloneValue(value: any): any { return new (value.constructor as DataViewConstructor)( clonedBuffer, value.byteOffset, - length + length, ); } if (value instanceof Map) { @@ -183,7 +183,7 @@ interface GenericConstructor<T = any> { * are not. */ export function defineEnumerableProps( Ctor: GenericConstructor, - props: string[] + props: string[], ): void { for (const prop of props) { Reflect.defineProperty(Ctor.prototype, prop, { enumerable: true }); diff --git a/cli/js/web/workers.ts b/cli/js/web/workers.ts index cc40f104c..5fd63477a 100644 --- a/cli/js/web/workers.ts +++ b/cli/js/web/workers.ts @@ -94,7 +94,7 @@ export class WorkerImpl extends EventTarget implements Worker { if (type !== "module") { throw new Error( - 'Not yet implemented: only "module" type workers are supported' + 'Not yet implemented: only "module" type workers are supported', ); } @@ -125,7 +125,7 @@ export class WorkerImpl extends EventTarget implements Worker { hasSourceCode, sourceCode, useDenoNamespace, - options?.name + options?.name, ); this.#id = id; this.#poll(); @@ -225,7 +225,7 @@ export class WorkerImpl extends EventTarget implements Worker { postMessage(message: any, transferOrOptions?: any): void { if (transferOrOptions) { throw new Error( - "Not yet implemented: `transfer` and `options` are not supported." + "Not yet implemented: `transfer` and `options` are not supported.", ); } diff --git a/cli/js/write_file.ts b/cli/js/write_file.ts index 6b64bc09d..db5f20238 100644 --- a/cli/js/write_file.ts +++ b/cli/js/write_file.ts @@ -15,7 +15,7 @@ export interface WriteFileOptions { export function writeFileSync( path: string | URL, data: Uint8Array, - options: WriteFileOptions = {} + options: WriteFileOptions = {}, ): void { if (options.create !== undefined) { const create = !!options.create; @@ -45,7 +45,7 @@ export function writeFileSync( export async function writeFile( path: string | URL, data: Uint8Array, - options: WriteFileOptions = {} + options: WriteFileOptions = {}, ): Promise<void> { if (options.create !== undefined) { const create = !!options.create; diff --git a/cli/js/write_text_file.ts b/cli/js/write_text_file.ts index ca7646c75..97148c411 100644 --- a/cli/js/write_text_file.ts +++ b/cli/js/write_text_file.ts @@ -4,7 +4,7 @@ import { writeFileSync, writeFile, WriteFileOptions } from "./write_file.ts"; export function writeTextFileSync( path: string | URL, data: string, - options: WriteFileOptions = {} + options: WriteFileOptions = {}, ): void { const encoder = new TextEncoder(); return writeFileSync(path, encoder.encode(data), options); @@ -13,7 +13,7 @@ export function writeTextFileSync( export function writeTextFile( path: string | URL, data: string, - options: WriteFileOptions = {} + options: WriteFileOptions = {}, ): Promise<void> { const encoder = new TextEncoder(); return writeFile(path, encoder.encode(data), options); diff --git a/cli/tests/019_media_types.ts b/cli/tests/019_media_types.ts index cc99be83b..523639be4 100644 --- a/cli/tests/019_media_types.ts +++ b/cli/tests/019_media_types.ts @@ -20,5 +20,5 @@ console.log( loadedJs1, loadedJs2, loadedJs3, - loadedJs4 + loadedJs4, ); diff --git a/cli/tests/042_dyn_import_evalcontext.ts b/cli/tests/042_dyn_import_evalcontext.ts index e1cc485d1..f31fffee9 100644 --- a/cli/tests/042_dyn_import_evalcontext.ts +++ b/cli/tests/042_dyn_import_evalcontext.ts @@ -1,4 +1,4 @@ // @ts-expect-error Deno.core.evalContext( - "(async () => console.log(await import('./subdir/mod4.js')))()" + "(async () => console.log(await import('./subdir/mod4.js')))()", ); diff --git a/cli/tests/046_jsx_test.tsx b/cli/tests/046_jsx_test.tsx index a3df2aad7..857d24d36 100644 --- a/cli/tests/046_jsx_test.tsx +++ b/cli/tests/046_jsx_test.tsx @@ -5,10 +5,10 @@ declare namespace JSX { } const React = { createElement(factory: any, props: any, ...children: any[]) { - return {factory, props, children} - } -} + return { factory, props, children }; + }, +}; const View = () => ( <div class="deno">land</div> -) -console.log(<View />) +); +console.log(<View />); diff --git a/cli/tests/047_jsx_test.jsx b/cli/tests/047_jsx_test.jsx index 553c4c5a5..61bd7e36c 100644 --- a/cli/tests/047_jsx_test.jsx +++ b/cli/tests/047_jsx_test.jsx @@ -1,9 +1,9 @@ const React = { createElement(factory, props, ...children) { - return {factory, props, children} - } -} + return { factory, props, children }; + }, +}; const View = () => ( <div class="deno">land</div> -) -console.log(<View />) +); +console.log(<View />); diff --git a/cli/tests/048_media_types_jsx.ts b/cli/tests/048_media_types_jsx.ts index f6a498fdf..54ed28e17 100644 --- a/cli/tests/048_media_types_jsx.ts +++ b/cli/tests/048_media_types_jsx.ts @@ -29,5 +29,5 @@ console.log( loadedJsx1, loadedJsx2, loadedJsx3, - loadedJsx4 + loadedJsx4, ); diff --git a/cli/tests/053_import_compression/main.ts b/cli/tests/053_import_compression/main.ts index d18363b7d..5b2199483 100644 --- a/cli/tests/053_import_compression/main.ts +++ b/cli/tests/053_import_compression/main.ts @@ -3,11 +3,11 @@ import "http://127.0.0.1:4545/cli/tests/053_import_compression/brotli"; console.log( await fetch( - "http://127.0.0.1:4545/cli/tests/053_import_compression/gziped" - ).then((res) => res.text()) + "http://127.0.0.1:4545/cli/tests/053_import_compression/gziped", + ).then((res) => res.text()), ); console.log( await fetch( - "http://127.0.0.1:4545/cli/tests/053_import_compression/brotli" - ).then((res) => res.text()) + "http://127.0.0.1:4545/cli/tests/053_import_compression/brotli", + ).then((res) => res.text()), ); diff --git a/cli/tests/Component.tsx b/cli/tests/Component.tsx index 34208329b..81dfd6957 100644 --- a/cli/tests/Component.tsx +++ b/cli/tests/Component.tsx @@ -1 +1 @@ -import "./046_jsx_test.tsx";
\ No newline at end of file +import "./046_jsx_test.tsx"; diff --git a/cli/tests/badly_formatted.js b/cli/tests/badly_formatted.js deleted file mode 100644 index b646a95a3..000000000 --- a/cli/tests/badly_formatted.js +++ /dev/null @@ -1,4 +0,0 @@ - -console.log("Hello World" - -) diff --git a/cli/tests/badly_formatted.mjs b/cli/tests/badly_formatted.mjs new file mode 100644 index 000000000..bc515a330 --- /dev/null +++ b/cli/tests/badly_formatted.mjs @@ -0,0 +1,4 @@ +// Deliberately using .mjs to avoid triggering dprint +console.log("Hello World" + +) diff --git a/cli/tests/badly_formatted_fixed.js b/cli/tests/badly_formatted_fixed.js index accefceba..e9062ba85 100644 --- a/cli/tests/badly_formatted_fixed.js +++ b/cli/tests/badly_formatted_fixed.js @@ -1 +1,2 @@ +// Deliberately using .mjs to avoid triggering dprint console.log("Hello World"); diff --git a/cli/tests/cafile_info.ts b/cli/tests/cafile_info.ts index e11d106e6..cd92a42f6 100644 --- a/cli/tests/cafile_info.ts +++ b/cli/tests/cafile_info.ts @@ -20,5 +20,5 @@ console.log( loadedJs1, loadedJs2, loadedJs3, - loadedJs4 + loadedJs4, ); diff --git a/cli/tests/compiler_api_test.ts b/cli/tests/compiler_api_test.ts index 274f1b98d..7ff9ebc2b 100644 --- a/cli/tests/compiler_api_test.ts +++ b/cli/tests/compiler_api_test.ts @@ -43,7 +43,7 @@ Deno.test({ { module: "amd", sourceMap: false, - } + }, ); assert(diagnostics == null); assert(actual); @@ -63,7 +63,7 @@ Deno.test({ }, { lib: ["dom", "es2018", "deno.ns"], - } + }, ); assert(diagnostics == null); assert(actual); @@ -81,7 +81,7 @@ Deno.test({ }, { types: ["./subdir/foo_types.d.ts"], - } + }, ); assert(diagnostics == null); assert(actual); @@ -112,7 +112,7 @@ Deno.test({ { sourceMap: false, module: "amd", - } + }, ); assert(actual); assertEquals(Object.keys(actual), ["foo.ts"]); @@ -155,7 +155,7 @@ Deno.test({ }, { removeComments: true, - } + }, ); assert(diagnostics == null); assert(!actual.includes(`random`)); @@ -182,7 +182,7 @@ Deno.test({ { "/foo.ts": `console.log("hello world!")\n`, }, - { target: "es2015" } + { target: "es2015" }, ); assert(diagnostics == null); assert(actual.includes(`var __awaiter = `)); diff --git a/cli/tests/echo_server.ts b/cli/tests/echo_server.ts index deab17397..053bdf5c1 100644 --- a/cli/tests/echo_server.ts +++ b/cli/tests/echo_server.ts @@ -7,5 +7,5 @@ listener.accept().then( await Deno.copy(conn, conn); conn.close(); listener.close(); - } + }, ); diff --git a/cli/tests/error_014_catch_dynamic_import_error.js b/cli/tests/error_014_catch_dynamic_import_error.js index ad3735fc3..483be7b1a 100644 --- a/cli/tests/error_014_catch_dynamic_import_error.js +++ b/cli/tests/error_014_catch_dynamic_import_error.js @@ -24,7 +24,7 @@ await import("./subdir/indirect_throws.js"); } catch (err) { console.log( - "Caught error thrown indirectly by dynamically imported module." + "Caught error thrown indirectly by dynamically imported module.", ); console.log(err); } diff --git a/cli/tests/error_017_hide_long_source_ts.ts b/cli/tests/error_017_hide_long_source_ts.ts index a4c30670f..d61cb1277 100644 --- a/cli/tests/error_017_hide_long_source_ts.ts +++ b/cli/tests/error_017_hide_long_source_ts.ts @@ -1,2 +1,3 @@ +// deno-fmt-ignore-file const LONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONG = undefined; LONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONG.a; diff --git a/cli/tests/error_017_hide_long_source_ts.ts.out b/cli/tests/error_017_hide_long_source_ts.ts.out index 6799a94cc..52c2f7cc2 100644 --- a/cli/tests/error_017_hide_long_source_ts.ts.out +++ b/cli/tests/error_017_hide_long_source_ts.ts.out @@ -1,3 +1,3 @@ [WILDCARD] error: TS2532 [ERROR]: Object is possibly 'undefined'. - at [WILDCARD]tests/error_017_hide_long_source_ts.ts:2:1 + at [WILDCARD]tests/error_017_hide_long_source_ts.ts:3:1 diff --git a/cli/tests/error_018_hide_long_source_js.js b/cli/tests/error_018_hide_long_source_js.js index a4c30670f..d61cb1277 100644 --- a/cli/tests/error_018_hide_long_source_js.js +++ b/cli/tests/error_018_hide_long_source_js.js @@ -1,2 +1,3 @@ +// deno-fmt-ignore-file const LONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONG = undefined; LONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONGLONG.a; diff --git a/cli/tests/error_018_hide_long_source_js.js.out b/cli/tests/error_018_hide_long_source_js.js.out index 37265d659..750ddec4e 100644 --- a/cli/tests/error_018_hide_long_source_js.js.out +++ b/cli/tests/error_018_hide_long_source_js.js.out @@ -1,2 +1,2 @@ error: Uncaught TypeError: Cannot read property 'a' of undefined - at file:///[WILDCARD]cli/tests/error_018_hide_long_source_js.js:2:206 + at file:///[WILDCARD]cli/tests/error_018_hide_long_source_js.js:3:206 diff --git a/cli/tests/error_syntax.js b/cli/tests/error_syntax.js index 0c0c09855..c0414c356 100644 --- a/cli/tests/error_syntax.js +++ b/cli/tests/error_syntax.js @@ -1,3 +1,3 @@ -// prettier-ignore +// deno-fmt-ignore-file (the following is a syntax error ^^ ! ) diff --git a/cli/tests/error_syntax_empty_trailing_line.mjs b/cli/tests/error_syntax_empty_trailing_line.mjs index 5bc6b1c23..864dfb0c7 100644 --- a/cli/tests/error_syntax_empty_trailing_line.mjs +++ b/cli/tests/error_syntax_empty_trailing_line.mjs @@ -1,2 +1,2 @@ -// Deliberately using .mjs to avoid triggering prettier +// Deliberately using .mjs to avoid triggering dprint setTimeout(() => {}), diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs index e93edc79f..4df7a8268 100644 --- a/cli/tests/integration_tests.rs +++ b/cli/tests/integration_tests.rs @@ -347,7 +347,7 @@ fn fmt_test() { let t = TempDir::new().expect("tempdir fail"); let fixed = util::root_path().join("cli/tests/badly_formatted_fixed.js"); let badly_formatted_original = - util::root_path().join("cli/tests/badly_formatted.js"); + util::root_path().join("cli/tests/badly_formatted.mjs"); let badly_formatted = t.path().join("badly_formatted.js"); let badly_formatted_str = badly_formatted.to_str().unwrap(); std::fs::copy(&badly_formatted_original, &badly_formatted) diff --git a/cli/tests/jsx_import_from_ts.App.jsx b/cli/tests/jsx_import_from_ts.App.jsx index 6ea58436b..649230613 100644 --- a/cli/tests/jsx_import_from_ts.App.jsx +++ b/cli/tests/jsx_import_from_ts.App.jsx @@ -1,11 +1,11 @@ const React = { - createElement() {} -} + createElement() {}, +}; export default function app() { - return ( - <div> - <h2>asdf</h2> - </div> - ); -}
\ No newline at end of file + return ( + <div> + <h2>asdf</h2> + </div> + ); +} diff --git a/cli/tests/lib_ref.ts b/cli/tests/lib_ref.ts index 1b9f243c8..0a4ce3fc7 100644 --- a/cli/tests/lib_ref.ts +++ b/cli/tests/lib_ref.ts @@ -1,12 +1,13 @@ const [errors, program] = await Deno.compile( "main.ts", { - "main.ts": `/// <reference lib="dom" />\n\ndocument.getElementById("foo");\nDeno.args;`, + "main.ts": + `/// <reference lib="dom" />\n\ndocument.getElementById("foo");\nDeno.args;`, }, { target: "es2018", lib: ["es2018", "deno.ns"], - } + }, ); console.log(errors); diff --git a/cli/tests/lib_runtime_api.ts b/cli/tests/lib_runtime_api.ts index 5d76ea1c5..788288f72 100644 --- a/cli/tests/lib_runtime_api.ts +++ b/cli/tests/lib_runtime_api.ts @@ -5,7 +5,7 @@ const [errors, program] = await Deno.compile( }, { lib: ["dom", "esnext"], - } + }, ); console.log(errors); diff --git a/cli/tests/subdir/fetching_worker.js b/cli/tests/subdir/fetching_worker.js index a4237a97a..3e33d1c9e 100644 --- a/cli/tests/subdir/fetching_worker.js +++ b/cli/tests/subdir/fetching_worker.js @@ -1,5 +1,5 @@ const r = await fetch( - "http://localhost:4545/cli/tests/subdir/fetching_worker.js" + "http://localhost:4545/cli/tests/subdir/fetching_worker.js", ); await r.text(); postMessage("Done!"); diff --git a/cli/tests/subdir/mt_application_ecmascript_jsx.j2.jsx b/cli/tests/subdir/mt_application_ecmascript_jsx.j2.jsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_application_ecmascript_jsx.j2.jsx +++ b/cli/tests/subdir/mt_application_ecmascript_jsx.j2.jsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_application_x_javascript_jsx.j4.jsx b/cli/tests/subdir/mt_application_x_javascript_jsx.j4.jsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_application_x_javascript_jsx.j4.jsx +++ b/cli/tests/subdir/mt_application_x_javascript_jsx.j4.jsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_application_x_typescript_tsx.t4.tsx b/cli/tests/subdir/mt_application_x_typescript_tsx.t4.tsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_application_x_typescript_tsx.t4.tsx +++ b/cli/tests/subdir/mt_application_x_typescript_tsx.t4.tsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_javascript_jsx.jsx b/cli/tests/subdir/mt_javascript_jsx.jsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_javascript_jsx.jsx +++ b/cli/tests/subdir/mt_javascript_jsx.jsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_text_ecmascript_jsx.j3.jsx b/cli/tests/subdir/mt_text_ecmascript_jsx.j3.jsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_text_ecmascript_jsx.j3.jsx +++ b/cli/tests/subdir/mt_text_ecmascript_jsx.j3.jsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_text_javascript_jsx.j1.jsx b/cli/tests/subdir/mt_text_javascript_jsx.j1.jsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_text_javascript_jsx.j1.jsx +++ b/cli/tests/subdir/mt_text_javascript_jsx.j1.jsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_text_typescript_tsx.t1.tsx b/cli/tests/subdir/mt_text_typescript_tsx.t1.tsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_text_typescript_tsx.t1.tsx +++ b/cli/tests/subdir/mt_text_typescript_tsx.t1.tsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_video_mp2t_tsx.t3.tsx b/cli/tests/subdir/mt_video_mp2t_tsx.t3.tsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_video_mp2t_tsx.t3.tsx +++ b/cli/tests/subdir/mt_video_mp2t_tsx.t3.tsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/mt_video_vdn_tsx.t2.tsx b/cli/tests/subdir/mt_video_vdn_tsx.t2.tsx index 2c7a15491..c5c27f9f9 100644 --- a/cli/tests/subdir/mt_video_vdn_tsx.t2.tsx +++ b/cli/tests/subdir/mt_video_vdn_tsx.t2.tsx @@ -1,5 +1,5 @@ const React = { - createElement() {} -} + createElement() {}, +}; const temp = <div></div>; export const loaded = true; diff --git a/cli/tests/subdir/nested_worker.js b/cli/tests/subdir/nested_worker.js index d3801b8c5..4b51b8763 100644 --- a/cli/tests/subdir/nested_worker.js +++ b/cli/tests/subdir/nested_worker.js @@ -1,7 +1,7 @@ // Specifier should be resolved relative to current file const jsWorker = new Worker( new URL("sibling_worker.js", import.meta.url).href, - { type: "module", name: "sibling" } + { type: "module", name: "sibling" }, ); jsWorker.onerror = (_e) => { diff --git a/cli/tests/swc_syntax_error.ts b/cli/tests/swc_syntax_error.ts index 70e0de97d..991ca9214 100644 --- a/cli/tests/swc_syntax_error.ts +++ b/cli/tests/swc_syntax_error.ts @@ -1,3 +1,4 @@ +// deno-fmt-ignore-file for await (const req of s) { let something: } diff --git a/cli/tests/swc_syntax_error.ts.out b/cli/tests/swc_syntax_error.ts.out index 0896faf68..0cc365e20 100644 --- a/cli/tests/swc_syntax_error.ts.out +++ b/cli/tests/swc_syntax_error.ts.out @@ -1 +1 @@ -error: Unexpected token Some(RBrace) at [WILDCARD]syntax_error.ts:3:0 +error: Unexpected token Some(RBrace) at [WILDCARD]syntax_error.ts:4:0 diff --git a/cli/tests/top_level_for_await.js b/cli/tests/top_level_for_await.js index 54742ce52..a330f6c71 100644 --- a/cli/tests/top_level_for_await.js +++ b/cli/tests/top_level_for_await.js @@ -7,4 +7,4 @@ function* asyncGenerator() { for await (const num of asyncGenerator()) { console.log(num); -}; +} diff --git a/cli/tests/unit/body_test.ts b/cli/tests/unit/body_test.ts index ac65a1312..b7393ad0d 100644 --- a/cli/tests/unit/body_test.ts +++ b/cli/tests/unit/body_test.ts @@ -37,7 +37,7 @@ unitTest( { perms: { net: true } }, async function bodyMultipartFormData(): Promise<void> { const response = await fetch( - "http://localhost:4545/multipart_form_data.txt" + "http://localhost:4545/multipart_form_data.txt", ); const text = await response.text(); @@ -47,14 +47,14 @@ unitTest( assert(formData.has("field_1")); assertEquals(formData.get("field_1")!.toString(), "value_1 \r\n"); assert(formData.has("field_2")); - } + }, ); unitTest( { perms: { net: true } }, async function bodyURLEncodedFormData(): Promise<void> { const response = await fetch( - "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt" + "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt", ); const text = await response.text(); @@ -65,7 +65,7 @@ unitTest( assertEquals(formData.get("field_1")!.toString(), "Hi"); assert(formData.has("field_2")); assertEquals(formData.get("field_2")!.toString(), "<Deno>"); - } + }, ); unitTest({ perms: {} }, async function bodyURLSearchParams(): Promise<void> { diff --git a/cli/tests/unit/buffer_test.ts b/cli/tests/unit/buffer_test.ts index fdbadbfe4..7a628cae5 100644 --- a/cli/tests/unit/buffer_test.ts +++ b/cli/tests/unit/buffer_test.ts @@ -46,7 +46,7 @@ async function fillBytes( buf: Deno.Buffer, s: string, n: number, - fub: Uint8Array + fub: Uint8Array, ): Promise<string> { check(buf, s); for (; n > 0; n--) { @@ -64,7 +64,7 @@ async function fillBytes( async function empty( buf: Deno.Buffer, s: string, - fub: Uint8Array + fub: Uint8Array, ): Promise<void> { check(buf, s); while (true) { @@ -166,7 +166,7 @@ unitTest(async function bufferTooLargeByteWrites(): Promise<void> { buf.grow(growLen); }, Error, - "grown beyond the maximum size" + "grown beyond the maximum size", ); }); @@ -179,8 +179,9 @@ unitTest( let written = 0; const buf = new Deno.Buffer(); const writes = Math.floor(capacity / bufSize); - for (let i = 0; i < writes; i++) + for (let i = 0; i < writes; i++) { written += buf.writeSync(repeat("x", bufSize)); + } if (written < capacity) { written += buf.writeSync(repeat("x", capacity - written)); @@ -188,7 +189,7 @@ unitTest( assertEquals(written, capacity); } - } + }, ); unitTest( @@ -202,9 +203,9 @@ unitTest( await buf.readFrom(reader); }, Error, - "grown beyond the maximum size" + "grown beyond the maximum size", ); - } + }, ); unitTest( @@ -218,9 +219,9 @@ unitTest( buf.readFromSync(reader); }, Error, - "grown beyond the maximum size" + "grown beyond the maximum size", ); - } + }, ); unitTest( @@ -234,7 +235,7 @@ unitTest( assertEquals(buf.length, capacity); } - } + }, ); unitTest( @@ -247,7 +248,7 @@ unitTest( await buf.readFrom(reader); assertEquals(buf.length, capacity); } - } + }, ); unitTest( @@ -261,7 +262,7 @@ unitTest( await buf.readFrom(reader); assertEquals(buf.length, capacity); } - } + }, ); unitTest(async function bufferLargeByteReads(): Promise<void> { @@ -292,7 +293,7 @@ unitTest(async function bufferReadFrom(): Promise<void> { buf, "", 5, - testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) + testBytes.subarray(0, Math.floor(testBytes.byteLength / i)), ); const b = new Deno.Buffer(); await b.readFrom(buf); @@ -314,7 +315,7 @@ unitTest(async function bufferReadFromSync(): Promise<void> { buf, "", 5, - testBytes.subarray(0, Math.floor(testBytes.byteLength / i)) + testBytes.subarray(0, Math.floor(testBytes.byteLength / i)), ); const b = new Deno.Buffer(); b.readFromSync(buf); @@ -340,11 +341,11 @@ unitTest(async function bufferTestGrow(): Promise<void> { // Check that buffer has correct data. assertEquals( buf.bytes().subarray(0, startLen - nread), - xBytes.subarray(nread) + xBytes.subarray(nread), ); assertEquals( buf.bytes().subarray(startLen - nread, startLen - nread + growLen), - yBytes + yBytes, ); } } diff --git a/cli/tests/unit/chmod_test.ts b/cli/tests/unit/chmod_test.ts index 5a2afd507..c53fe8c8b 100644 --- a/cli/tests/unit/chmod_test.ts +++ b/cli/tests/unit/chmod_test.ts @@ -21,7 +21,7 @@ unitTest( const fileInfo = Deno.statSync(filename); assert(fileInfo.mode); assertEquals(fileInfo.mode & 0o777, 0o777); - } + }, ); unitTest( @@ -40,7 +40,7 @@ unitTest( assertEquals(fileInfo.mode & 0o777, 0o777); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); // Check symlink when not on windows @@ -72,7 +72,7 @@ unitTest( symlinkInfo = Deno.lstatSync(symlinkName); assert(symlinkInfo.mode); assertEquals(symlinkInfo.mode & 0o777, symlinkMode); - } + }, ); unitTest({ perms: { write: true } }, function chmodSyncFailure(): void { @@ -102,7 +102,7 @@ unitTest( const fileInfo = Deno.statSync(filename); assert(fileInfo.mode); assertEquals(fileInfo.mode & 0o777, 0o777); - } + }, ); unitTest( @@ -121,7 +121,7 @@ unitTest( assertEquals(fileInfo.mode & 0o777, 0o777); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); // Check symlink when not on windows @@ -154,7 +154,7 @@ unitTest( symlinkInfo = Deno.lstatSync(symlinkName); assert(symlinkInfo.mode); assertEquals(symlinkInfo.mode & 0o777, symlinkMode); - } + }, ); unitTest({ perms: { write: true } }, async function chmodFailure(): Promise< diff --git a/cli/tests/unit/chown_test.ts b/cli/tests/unit/chown_test.ts index 163bfa48b..739e355de 100644 --- a/cli/tests/unit/chown_test.ts +++ b/cli/tests/unit/chown_test.ts @@ -33,7 +33,7 @@ unitTest( } catch (e) { assert(e instanceof Deno.errors.PermissionDenied); } - } + }, ); unitTest( @@ -47,7 +47,7 @@ unitTest( } catch (e) { assert(e instanceof Deno.errors.NotFound); } - } + }, ); unitTest( @@ -61,7 +61,7 @@ unitTest( } catch (e) { assert(e instanceof Deno.errors.NotFound); } - } + }, ); unitTest( @@ -78,7 +78,7 @@ unitTest( assert(e instanceof Deno.errors.PermissionDenied); } Deno.removeSync(dirPath, { recursive: true }); - } + }, ); unitTest( @@ -95,7 +95,7 @@ unitTest( assert(e instanceof Deno.errors.PermissionDenied); } await Deno.remove(dirPath, { recursive: true }); - } + }, ); unitTest( @@ -115,7 +115,7 @@ unitTest( Deno.chownSync(filePath, uid, gid); Deno.removeSync(dirPath, { recursive: true }); - } + }, ); unitTest( @@ -127,7 +127,7 @@ unitTest( Deno.writeTextFileSync(fileUrl, "Hello"); Deno.chownSync(fileUrl, uid, gid); Deno.removeSync(dirPath, { recursive: true }); - } + }, ); unitTest( @@ -139,7 +139,7 @@ unitTest( await Deno.writeTextFile(filePath, "Hello"); await Deno.chown(filePath, uid, gid); Deno.removeSync(dirPath, { recursive: true }); - } + }, ); unitTest( @@ -151,7 +151,7 @@ unitTest( await Deno.writeTextFile(filePath, "Foo"); await Deno.chown(filePath, uid, null); Deno.removeSync(dirPath, { recursive: true }); - } + }, ); unitTest( @@ -171,5 +171,5 @@ unitTest( await Deno.chown(fileUrl, uid, gid); Deno.removeSync(dirPath, { recursive: true }); - } + }, ); diff --git a/cli/tests/unit/console_test.ts b/cli/tests/unit/console_test.ts index 7a03cd6b6..bc97107b1 100644 --- a/cli/tests/unit/console_test.ts +++ b/cli/tests/unit/console_test.ts @@ -155,7 +155,7 @@ unitTest(function consoleTestStringifyCircular(): void { assertEquals(stringify(/[0-9]*/), "/[0-9]*/"); assertEquals( stringify(new Date("2018-12-10T02:26:59.002Z")), - "2018-12-10T02:26:59.002Z" + "2018-12-10T02:26:59.002Z", ); assertEquals(stringify(new Set([1, 2, 3])), "Set { 1, 2, 3 }"); assertEquals( @@ -163,9 +163,9 @@ unitTest(function consoleTestStringifyCircular(): void { new Map([ [1, "one"], [2, "two"], - ]) + ]), ), - `Map { 1 => "one", 2 => "two" }` + `Map { 1 => "one", 2 => "two" }`, ); assertEquals(stringify(new WeakSet()), "WeakSet { [items unknown] }"); assertEquals(stringify(new WeakMap()), "WeakMap { [items unknown] }"); @@ -175,28 +175,28 @@ unitTest(function consoleTestStringifyCircular(): void { assertEquals(stringify(new Extended()), "Extended { a: 1, b: 2 }"); assertEquals( stringify(function f(): void {}), - "[Function: f]" + "[Function: f]", ); assertEquals( stringify(async function af(): Promise<void> {}), - "[AsyncFunction: af]" + "[AsyncFunction: af]", ); assertEquals( stringify(function* gf() {}), - "[GeneratorFunction: gf]" + "[GeneratorFunction: gf]", ); assertEquals( stringify(async function* agf() {}), - "[AsyncGeneratorFunction: agf]" + "[AsyncGeneratorFunction: agf]", ); assertEquals( stringify(new Uint8Array([1, 2, 3])), - "Uint8Array(3) [ 1, 2, 3 ]" + "Uint8Array(3) [ 1, 2, 3 ]", ); assertEquals(stringify(Uint8Array.prototype), "TypedArray {}"); assertEquals( stringify({ a: { b: { c: { d: new Set([1]) } } } }), - "{ a: { b: { c: { d: [Set] } } } }" + "{ a: { b: { c: { d: [Set] } } } }", ); assertEquals(stringify(nestedObj), nestedObjExpected); assertEquals(stringify(JSON), 'JSON { Symbol(Symbol.toStringTag): "JSON" }'); @@ -224,11 +224,11 @@ unitTest(function consoleTestStringifyCircular(): void { trace: [Function], indentLevel: 0, Symbol(isConsoleInstance): true -}` +}`, ); assertEquals( stringify({ str: 1, [Symbol.for("sym")]: 2, [Symbol.toStringTag]: "TAG" }), - 'TAG { str: 1, Symbol(sym): 2, Symbol(Symbol.toStringTag): "TAG" }' + 'TAG { str: 1, Symbol(sym): 2, Symbol(Symbol.toStringTag): "TAG" }', ); // test inspect is working the same assertEquals(stripColor(Deno.inspect(nestedObj)), nestedObjExpected); @@ -240,21 +240,21 @@ unitTest(function consoleTestStringifyWithDepth(): void { const nestedObj: any = { a: { b: { c: { d: { e: { f: 42 } } } } } }; assertEquals( stripColor(inspectArgs([nestedObj], { depth: 3 })), - "{ a: { b: { c: [Object] } } }" + "{ a: { b: { c: [Object] } } }", ); assertEquals( stripColor(inspectArgs([nestedObj], { depth: 4 })), - "{ a: { b: { c: { d: [Object] } } } }" + "{ a: { b: { c: { d: [Object] } } } }", ); assertEquals(stripColor(inspectArgs([nestedObj], { depth: 0 })), "[Object]"); assertEquals( stripColor(inspectArgs([nestedObj])), - "{ a: { b: { c: { d: [Object] } } } }" + "{ a: { b: { c: { d: [Object] } } } }", ); // test inspect is working the same way assertEquals( stripColor(Deno.inspect(nestedObj, { depth: 4 })), - "{ a: { b: { c: { d: [Object] } } } }" + "{ a: { b: { c: { d: [Object] } } } }", ); }); @@ -290,7 +290,7 @@ unitTest(function consoleTestStringifyLargeObject(): void { asda: 3, x: { a: "asd", x: 3 } } -}` +}`, ); }); @@ -310,7 +310,7 @@ unitTest(function consoleTestStringifyIterable() { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... 100 more items -]` +]`, ); const obj = { a: "a", longArray }; @@ -328,7 +328,7 @@ unitTest(function consoleTestStringifyIterable() { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... 100 more items ] -}` +}`, ); const shortMap = new Map([ @@ -445,7 +445,7 @@ unitTest(function consoleTestStringifyIterable() { "98" => 98, "99" => 99, ... 100 more items -}` +}`, ); const shortSet = new Set([1, 2, 3]); @@ -558,14 +558,14 @@ unitTest(function consoleTestStringifyIterable() { 98, 99, ... 100 more items -}` +}`, ); const withEmptyEl = Array(10); withEmptyEl.fill(0, 4, 6); assertEquals( stringify(withEmptyEl), - `[ <4 empty items>, 0, 0, <4 empty items> ]` + `[ <4 empty items>, 0, 0, <4 empty items> ]`, ); /* TODO(ry) Fix this test @@ -643,7 +643,7 @@ unitTest(function consoleTestWithCustomInspectorError(): void { assertEquals(stringify(new B({ a: "a" })), "a"); assertEquals( stringify(B.prototype), - "{ Symbol(Deno.customInspect): [Function: [Deno.customInspect]] }" + "{ Symbol(Deno.customInspect): [Function: [Deno.customInspect]] }", ); }); @@ -662,7 +662,7 @@ unitTest(function consoleTestWithIntegerFormatSpecifier(): void { assertEquals(stringify("%d", 12345678901234567890123), "1"); assertEquals( stringify("%i", 12345678901234567890123n), - "12345678901234567890123n" + "12345678901234567890123n", ); }); @@ -701,7 +701,7 @@ unitTest(function consoleTestWithObjectFormatSpecifier(): void { assertEquals(stringify("%o", { a: 42 }), "{ a: 42 }"); assertEquals( stringify("%o", { a: { b: { c: { d: new Set([1]) } } } }), - "{ a: { b: { c: { d: [Set] } } } }" + "{ a: { b: { c: { d: [Set] } } } }", ); }); @@ -749,7 +749,7 @@ unitTest(function consoleTestError(): void { assert( stringify(e) .split("\n")[0] // error has been caught - .includes("MyError: This is an error") + .includes("MyError: This is an error"), ); } }); @@ -816,7 +816,7 @@ type ConsoleExamineFunc = ( csl: any, out: StringBuffer, err?: StringBuffer, - both?: StringBuffer + both?: StringBuffer, ) => void; function mockConsole(f: ConsoleExamineFunc): void { @@ -829,7 +829,7 @@ function mockConsole(f: ConsoleExamineFunc): void { const buf = isErr ? err : out; buf.add(content); both.add(content); - } + }, ); f(csl, out, err, both); } @@ -854,7 +854,7 @@ unitTest(function consoleGroup(): void { 4 5 6 -` +`, ); }); }); @@ -884,7 +884,7 @@ unitTest(function consoleGroupWarn(): void { 5 6 7 -` +`, ); }); }); @@ -901,7 +901,7 @@ unitTest(function consoleTable(): void { │ a │ "test" │ │ b │ 1 │ └───────┴────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -914,7 +914,7 @@ unitTest(function consoleTable(): void { │ a │ │ │ b │ 30 │ └───────┴────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -930,7 +930,7 @@ unitTest(function consoleTable(): void { │ 3 │ 5 │ 6 │ │ │ 4 │ [ 7 ] │ [ 8 ] │ │ └───────┴───────┴───────┴────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -945,7 +945,7 @@ unitTest(function consoleTable(): void { │ 2 │ 3 │ │ 3 │ "test" │ └────────────┴────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -953,7 +953,7 @@ unitTest(function consoleTable(): void { new Map([ [1, "one"], [2, "two"], - ]) + ]), ); assertEquals( stripColor(out.toString()), @@ -963,7 +963,7 @@ unitTest(function consoleTable(): void { │ 0 │ 1 │ "one" │ │ 1 │ 2 │ "two" │ └────────────┴─────┴────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -985,7 +985,7 @@ unitTest(function consoleTable(): void { │ g │ │ │ │ │ h │ │ │ │ └───────┴───────────┴───────────────────┴────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1007,7 +1007,7 @@ unitTest(function consoleTable(): void { │ 3 │ │ │ 10 │ │ │ 4 │ "test" │ { b: 20, c: "test" } │ │ │ └───────┴────────┴──────────────────────┴────┴────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1018,7 +1018,7 @@ unitTest(function consoleTable(): void { │ (idx) │ ├───────┤ └───────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1029,7 +1029,7 @@ unitTest(function consoleTable(): void { │ (idx) │ ├───────┤ └───────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1040,7 +1040,7 @@ unitTest(function consoleTable(): void { │ (iter idx) │ ├────────────┤ └────────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1051,7 +1051,7 @@ unitTest(function consoleTable(): void { │ (iter idx) │ ├────────────┤ └────────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1069,7 +1069,7 @@ unitTest(function consoleTable(): void { │ 1 │ "你好" │ │ 2 │ "Amapá" │ └───────┴─────────┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1085,7 +1085,7 @@ unitTest(function consoleTable(): void { │ 0 │ 1 │ 2 │ │ 1 │ 3 │ 4 │ └───────┴───┴───┘ -` +`, ); }); mockConsole((console, out): void => { @@ -1099,7 +1099,7 @@ unitTest(function consoleTable(): void { │ 2 │ │ │ 3 │ 6 │ └───────┴───┘ -` +`, ); }); }); @@ -1169,11 +1169,11 @@ unitTest(function consoleTrace(): void { unitTest(function inspectSorted(): void { assertEquals( Deno.inspect({ b: 2, a: 1 }, { sorted: true }), - "{ a: 1, b: 2 }" + "{ a: 1, b: 2 }", ); assertEquals( Deno.inspect(new Set(["b", "a"]), { sorted: true }), - `Set { "a", "b" }` + `Set { "a", "b" }`, ); assertEquals( Deno.inspect( @@ -1181,9 +1181,9 @@ unitTest(function inspectSorted(): void { ["b", 2], ["a", 1], ]), - { sorted: true } + { sorted: true }, ), - `Map { "a" => 1, "b" => 2 }` + `Map { "a" => 1, "b" => 2 }`, ); }); @@ -1194,12 +1194,12 @@ unitTest(function inspectTrailingComma(): void { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", ], - { trailingComma: true } + { trailingComma: true }, ), `[ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", -]` +]`, ); assertEquals( Deno.inspect( @@ -1207,12 +1207,12 @@ unitTest(function inspectTrailingComma(): void { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 1, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: 2, }, - { trailingComma: true } + { trailingComma: true }, ), `{ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: 1, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb: 2, -}` +}`, ); assertEquals( Deno.inspect( @@ -1220,12 +1220,12 @@ unitTest(function inspectTrailingComma(): void { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", ]), - { trailingComma: true } + { trailingComma: true }, ), `Set { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", -}` +}`, ); assertEquals( Deno.inspect( @@ -1233,12 +1233,12 @@ unitTest(function inspectTrailingComma(): void { ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1], ["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 2], ]), - { trailingComma: true } + { trailingComma: true }, ), `Map { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" => 1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" => 2, -}` +}`, ); }); @@ -1248,18 +1248,18 @@ unitTest(function inspectCompact(): void { `{ a: 1, b: 2 -}` +}`, ); }); unitTest(function inspectIterableLimit(): void { assertEquals( Deno.inspect(["a", "b", "c"], { iterableLimit: 2 }), - `[ "a", "b", ... 1 more items ]` + `[ "a", "b", ... 1 more items ]`, ); assertEquals( Deno.inspect(new Set(["a", "b", "c"]), { iterableLimit: 2 }), - `Set { "a", "b", ... 1 more items }` + `Set { "a", "b", ... 1 more items }`, ); assertEquals( Deno.inspect( @@ -1268,8 +1268,8 @@ unitTest(function inspectIterableLimit(): void { ["b", 2], ["c", 3], ]), - { iterableLimit: 2 } + { iterableLimit: 2 }, ), - `Map { "a" => 1, "b" => 2, ... 1 more items }` + `Map { "a" => 1, "b" => 2, ... 1 more items }`, ); }); diff --git a/cli/tests/unit/copy_file_test.ts b/cli/tests/unit/copy_file_test.ts index 5abceb797..c45e4977b 100644 --- a/cli/tests/unit/copy_file_test.ts +++ b/cli/tests/unit/copy_file_test.ts @@ -20,7 +20,7 @@ function writeFileString(filename: string | URL, s: string): void { function assertSameContent( filename1: string | URL, - filename2: string | URL + filename2: string | URL, ): void { const data1 = Deno.readFileSync(filename1); const data2 = Deno.readFileSync(filename2); @@ -41,7 +41,7 @@ unitTest( assertSameContent(fromFilename, toFilename); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -49,10 +49,10 @@ unitTest( function copyFileSyncByUrl(): void { const tempDir = Deno.makeTempDirSync(); const fromUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt`, ); const toUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt`, ); writeFileString(fromUrl, "Hello world!"); Deno.copyFileSync(fromUrl, toUrl); @@ -62,7 +62,7 @@ unitTest( assertSameContent(fromUrl, toUrl); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -77,7 +77,7 @@ unitTest( }, Deno.errors.NotFound); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -86,7 +86,7 @@ unitTest( assertThrows(() => { Deno.copyFileSync("/from.txt", "/to.txt"); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -95,7 +95,7 @@ unitTest( assertThrows(() => { Deno.copyFileSync("/from.txt", "/to.txt"); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -114,7 +114,7 @@ unitTest( assertSameContent(fromFilename, toFilename); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -131,7 +131,7 @@ unitTest( assertSameContent(fromFilename, toFilename); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -139,10 +139,10 @@ unitTest( async function copyFileByUrl(): Promise<void> { const tempDir = Deno.makeTempDirSync(); const fromUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/from.txt`, ); const toUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/to.txt`, ); writeFileString(fromUrl, "Hello world!"); await Deno.copyFile(fromUrl, toUrl); @@ -152,7 +152,7 @@ unitTest( assertSameContent(fromUrl, toUrl); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -167,7 +167,7 @@ unitTest( }, Deno.errors.NotFound); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -186,7 +186,7 @@ unitTest( assertSameContent(fromFilename, toFilename); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -195,7 +195,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.copyFile("/from.txt", "/to.txt"); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -204,5 +204,5 @@ unitTest( await assertThrowsAsync(async () => { await Deno.copyFile("/from.txt", "/to.txt"); }, Deno.errors.PermissionDenied); - } + }, ); diff --git a/cli/tests/unit/dir_test.ts b/cli/tests/unit/dir_test.ts index 5b60b3dba..f9f4c9456 100644 --- a/cli/tests/unit/dir_test.ts +++ b/cli/tests/unit/dir_test.ts @@ -18,7 +18,7 @@ unitTest( assertEquals(current, path); } Deno.chdir(initialdir); - } + }, ); unitTest({ perms: { read: true, write: true } }, function dirCwdError(): void { @@ -44,7 +44,7 @@ unitTest({ perms: { read: false } }, function dirCwdPermError(): void { Deno.cwd(); }, Deno.errors.PermissionDenied, - "read access to <CWD>, run again with the --allow-read flag" + "read access to <CWD>, run again with the --allow-read flag", ); }); @@ -55,5 +55,5 @@ unitTest( assertThrows(() => { Deno.chdir(path); }, Deno.errors.NotFound); - } + }, ); diff --git a/cli/tests/unit/dispatch_json_test.ts b/cli/tests/unit/dispatch_json_test.ts index 938f4f6e3..4ba2fbea9 100644 --- a/cli/tests/unit/dispatch_json_test.ts +++ b/cli/tests/unit/dispatch_json_test.ts @@ -5,7 +5,7 @@ const openErrorStackPattern = new RegExp( at unwrapResponse \\(.*dispatch_json\\.ts:.*\\) at Object.sendAsync \\(.*dispatch_json\\.ts:.*\\) at async Object\\.open \\(.*files\\.ts:.*\\).*$`, - "ms" + "ms", ); unitTest( @@ -16,7 +16,7 @@ unitTest( .catch((error): void => { assertMatch(error.stack, openErrorStackPattern); }); - } + }, ); declare global { diff --git a/cli/tests/unit/dispatch_minimal_test.ts b/cli/tests/unit/dispatch_minimal_test.ts index f46c0e575..4af9e00db 100644 --- a/cli/tests/unit/dispatch_minimal_test.ts +++ b/cli/tests/unit/dispatch_minimal_test.ts @@ -11,7 +11,7 @@ const readErrorStackPattern = new RegExp( at unwrapResponse \\(.*dispatch_minimal\\.ts:.*\\) at Object.sendAsyncMinimal \\(.*dispatch_minimal\\.ts:.*\\) at async Object\\.read \\(.*io\\.ts:.*\\).*$`, - "ms" + "ms", ); unitTest(async function sendAsyncStackTrace(): Promise<void> { @@ -40,7 +40,7 @@ unitTest(function malformedMinimalControlBuffer(): void { const buf32 = new Int32Array( header.buffer, header.byteOffset, - header.byteLength / 4 + header.byteLength / 4, ); const arg = buf32[1]; const message = new TextDecoder().decode(res.slice(12)).trim(); diff --git a/cli/tests/unit/dom_iterable_test.ts b/cli/tests/unit/dom_iterable_test.ts index c4e535a25..f4690d5b9 100644 --- a/cli/tests/unit/dom_iterable_test.ts +++ b/cli/tests/unit/dom_iterable_test.ts @@ -8,7 +8,7 @@ function setup() { [dataSymbol] = new Map<string, number>(); constructor( - data: Array<[string, number]> | IterableIterator<[string, number]> + data: Array<[string, number]> | IterableIterator<[string, number]>, ) { for (const [key, value] of data) { this[dataSymbol].set(key, value); @@ -53,7 +53,7 @@ unitTest(function testDomIterable(): void { this: typeof scope, value: number, key: string, - parent: typeof domIterable + parent: typeof domIterable, ): void { assertEquals(parent, domIterable); assert(key != null); diff --git a/cli/tests/unit/error_stack_test.ts b/cli/tests/unit/error_stack_test.ts index 052cb9591..af7467684 100644 --- a/cli/tests/unit/error_stack_test.ts +++ b/cli/tests/unit/error_stack_test.ts @@ -26,7 +26,7 @@ interface CallSite { function getMockCallSite( fileName: string, lineNumber: number | null, - columnNumber: number | null + columnNumber: number | null, ): CallSite { return { getThis(): unknown { @@ -87,7 +87,7 @@ unitTest(function prepareStackTrace(): void { assert(typeof MockError.prepareStackTrace === "function"); const prepareStackTrace: ( error: Error, - structuredStackTrace: CallSite[] + structuredStackTrace: CallSite[], ) => string = MockError.prepareStackTrace; const result = prepareStackTrace(new Error("foo"), [ getMockCallSite("CLI_SNAPSHOT.js", 23, 0), diff --git a/cli/tests/unit/event_target_test.ts b/cli/tests/unit/event_target_test.ts index cfbe5285b..34f9019d3 100644 --- a/cli/tests/unit/event_target_test.ts +++ b/cli/tests/unit/event_target_test.ts @@ -37,7 +37,7 @@ unitTest(function anEventTargetCanBeSubclassed(): void { on( type: string, callback: ((e: Event) => void) | null, - options?: AddEventListenerOptions + options?: AddEventListenerOptions, ): void { this.addEventListener(type, callback, options); } @@ -45,7 +45,7 @@ unitTest(function anEventTargetCanBeSubclassed(): void { off( type: string, callback: ((e: Event) => void) | null, - options?: EventListenerOptions + options?: EventListenerOptions, ): void { this.removeEventListener(type, callback, options); } @@ -221,5 +221,5 @@ unitTest( target.removeEventListener("foo", listener); target.dispatchEvent(event); assertEquals(callCount, 2); - } + }, ); diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts index c93cc0c85..9562c48c7 100644 --- a/cli/tests/unit/fetch_test.ts +++ b/cli/tests/unit/fetch_test.ts @@ -16,7 +16,7 @@ unitTest({ perms: { net: true } }, async function fetchProtocolError(): Promise< await fetch("file:///"); }, TypeError, - "not supported" + "not supported", ); }); @@ -28,9 +28,9 @@ unitTest( await fetch("http://localhost:4000"); }, Deno.errors.Http, - "error trying to connect" + "error trying to connect", ); - } + }, ); unitTest({ perms: { net: true } }, async function fetchJsonSuccess(): Promise< @@ -55,7 +55,7 @@ unitTest({ perms: { net: true } }, async function fetchUrl(): Promise<void> { unitTest({ perms: { net: true } }, async function fetchURL(): Promise<void> { const response = await fetch( - new URL("http://localhost:4545/cli/tests/fixture.json") + new URL("http://localhost:4545/cli/tests/fixture.json"), ); assertEquals(response.url, "http://localhost:4545/cli/tests/fixture.json"); const _json = await response.json(); @@ -95,7 +95,7 @@ unitTest( { perms: { net: true } }, async function fetchBodyUsedReader(): Promise<void> { const response = await fetch( - "http://localhost:4545/cli/tests/fixture.json" + "http://localhost:4545/cli/tests/fixture.json", ); assert(response.body !== null); @@ -106,14 +106,14 @@ unitTest( reader.releaseLock(); await response.json(); assertEquals(response.bodyUsed, true); - } + }, ); unitTest( { perms: { net: true } }, async function fetchBodyUsedCancelStream(): Promise<void> { const response = await fetch( - "http://localhost:4545/cli/tests/fixture.json" + "http://localhost:4545/cli/tests/fixture.json", ); assert(response.body !== null); @@ -121,7 +121,7 @@ unitTest( const promise = response.body.cancel(); assertEquals(response.bodyUsed, true); await promise; - } + }, ); unitTest({ perms: { net: true } }, async function fetchAsyncIterator(): Promise< @@ -176,7 +176,7 @@ unitTest( } assertEquals(total, data.length); - } + }, ); unitTest({ perms: { net: true } }, async function responseClone(): Promise< @@ -206,7 +206,7 @@ unitTest( { perms: { net: true } }, async function fetchMultipartFormDataSuccess(): Promise<void> { const response = await fetch( - "http://localhost:4545/multipart_form_data.txt" + "http://localhost:4545/multipart_form_data.txt", ); const formData = await response.formData(); assert(formData.has("field_1")); @@ -216,28 +216,28 @@ unitTest( assertEquals(file.name, "file.js"); assertEquals(await file.text(), `console.log("Hi")`); - } + }, ); unitTest( { perms: { net: true } }, async function fetchURLEncodedFormDataSuccess(): Promise<void> { const response = await fetch( - "http://localhost:4545/cli/tests/subdir/form_urlencoded.txt" + "http://localhost:4545/cli/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>"); - } + }, ); unitTest( { perms: { net: true } }, async function fetchInitFormDataBinaryFileBody(): Promise<void> { // Some random bytes - // prettier-ignore + // deno-fmt-ignore const binaryFile = new Uint8Array([108,2,0,0,145,22,162,61,157,227,166,77,138,75,180,56,119,188,177,183]); const response = await fetch("http://localhost:4545/echo_multipart_file", { method: "POST", @@ -249,7 +249,7 @@ unitTest( assertEquals(resultFile.type, "application/octet-stream"); assertEquals(resultFile.name, "file.bin"); assertEquals(new Uint8Array(await resultFile.arrayBuffer()), binaryFile); - } + }, ); unitTest( @@ -257,14 +257,14 @@ unitTest( async function fetchInitFormDataMultipleFilesBody(): Promise<void> { const files = [ { - // prettier-ignore + // deno-fmt-ignore content: new Uint8Array([137,80,78,71,13,10,26,10, 137, 1, 25]), type: "image/png", name: "image", fileName: "some-image.png", }, { - // prettier-ignore + // deno-fmt-ignore content: new Uint8Array([108,2,0,0,145,22,162,61,157,227,166,77,138,75,180,56,119,188,177,183]), name: "file", fileName: "file.bin", @@ -283,7 +283,7 @@ unitTest( form.append( file.name, new Blob([file.content], { type: file.type }), - file.fileName + file.fileName, ); } const response = await fetch("http://localhost:4545/echo_server", { @@ -300,10 +300,10 @@ unitTest( assertEquals(file.expectedType || file.type, resultFile.type); assertEquals( new Uint8Array(await resultFile.arrayBuffer()), - file.content + file.content, ); } - } + }, ); unitTest( @@ -317,7 +317,7 @@ unitTest( assertEquals(response.url, "http://localhost:4545/README.md"); const body = await response.text(); assert(body.includes("Deno")); - } + }, ); unitTest( @@ -326,13 +326,13 @@ unitTest( }, async function fetchWithRelativeRedirection(): Promise<void> { const response = await fetch( - "http://localhost:4545/cli/tests/001_hello.js" + "http://localhost:4545/cli/tests/001_hello.js", ); assertEquals(response.status, 200); assertEquals(response.statusText, "OK"); const body = await response.text(); assert(body.includes("Hello")); - } + }, ); unitTest( @@ -353,7 +353,7 @@ unitTest( assertEquals(response.status, 404); assertEquals(await response.text(), ""); } - } + }, ); unitTest( @@ -365,7 +365,7 @@ unitTest( assertEquals(response.status, 0); // network error assertEquals(response.type, "error"); assertEquals(response.ok, false); - } + }, ); unitTest( @@ -379,7 +379,7 @@ unitTest( const text = await response.text(); assertEquals(text, data); assert(response.headers.get("content-type")!.startsWith("text/plain")); - } + }, ); unitTest( @@ -393,7 +393,7 @@ unitTest( const response = await fetch(req); const text = await response.text(); assertEquals(text, data); - } + }, ); unitTest( @@ -406,7 +406,7 @@ unitTest( }); const text = await response.text(); assertEquals(text, data); - } + }, ); unitTest( @@ -419,7 +419,7 @@ unitTest( }); const text = await response.text(); assertEquals(text, data); - } + }, ); unitTest( @@ -436,9 +436,9 @@ unitTest( assert( response.headers .get("content-type")! - .startsWith("application/x-www-form-urlencoded") + .startsWith("application/x-www-form-urlencoded"), ); - } + }, ); unitTest({ perms: { net: true } }, async function fetchInitBlobBody(): Promise< @@ -468,7 +468,7 @@ unitTest( }); const resultForm = await response.formData(); assertEquals(form.get("field"), resultForm.get("field")); - } + }, ); unitTest( @@ -486,7 +486,7 @@ unitTest( const file = resultForm.get("file"); assert(file instanceof File); assertEquals(file.name, "blob"); - } + }, ); unitTest( @@ -500,7 +500,7 @@ unitTest( new Blob([new TextEncoder().encode(fileContent)], { type: "text/plain", }), - "deno.txt" + "deno.txt", ); const response = await fetch("http://localhost:4545/echo_server", { method: "POST", @@ -516,7 +516,7 @@ unitTest( assertEquals(file.name, resultFile.name); assertEquals(file.type, resultFile.type); assertEquals(await file.text(), await resultFile.text()); - } + }, ); unitTest({ perms: { net: true } }, async function fetchUserAgent(): Promise< @@ -561,8 +561,8 @@ function bufferServer(addr: string): Deno.Buffer { const p1 = buf.readFrom(conn); const p2 = conn.write( new TextEncoder().encode( - "HTTP/1.0 404 Not Found\r\nContent-Length: 2\r\n\r\nNF" - ) + "HTTP/1.0 404 Not Found\r\nContent-Length: 2\r\n\r\nNF", + ), ); // Wait for both an EOF on the read side of the socket and for the write to // complete before closing it. Due to keep-alive, the EOF won't be sent @@ -606,7 +606,7 @@ unitTest( `host: ${addr}\r\n\r\n`, ].join(""); assertEquals(actual, expected); - } + }, ); unitTest( @@ -643,7 +643,7 @@ unitTest( body, ].join(""); assertEquals(actual, expected); - } + }, ); unitTest( @@ -680,7 +680,7 @@ unitTest( bodyStr, ].join(""); assertEquals(actual, expected); - } + }, ); unitTest( @@ -698,12 +698,12 @@ unitTest( try { await response.text(); fail( - "Reponse.text() didn't throw on a filtered response without a body (type opaqueredirect)" + "Reponse.text() didn't throw on a filtered response without a body (type opaqueredirect)", ); } catch (e) { return; } - } + }, ); unitTest( @@ -721,12 +721,12 @@ unitTest( try { await response.text(); fail( - "Reponse.text() didn't throw on a filtered response without a body (type error)" + "Reponse.text() didn't throw on a filtered response without a body (type error)", ); } catch (e) { return; } - } + }, ); unitTest(function responseRedirect(): void { @@ -753,7 +753,7 @@ unitTest({ perms: { net: true } }, async function fetchBodyReadTwice(): Promise< try { await response[method](); fail( - "Reading body multiple times should failed, the stream should've been locked." + "Reading body multiple times should failed, the stream should've been locked.", ); } catch { // pass @@ -765,7 +765,7 @@ unitTest( { perms: { net: true } }, async function fetchBodyReaderAfterRead(): Promise<void> { const response = await fetch( - "http://localhost:4545/cli/tests/fixture.json" + "http://localhost:4545/cli/tests/fixture.json", ); assert(response.body !== null); const reader = await response.body.getReader(); @@ -781,7 +781,7 @@ unitTest( } catch { // pass } - } + }, ); unitTest( @@ -809,7 +809,7 @@ unitTest( } assertEquals(total, data.length); - } + }, ); unitTest( @@ -839,7 +839,7 @@ unitTest( total += value.length; } assertEquals(total, data.length); - } + }, ); unitTest( @@ -851,7 +851,7 @@ unitTest( // After ReadableStream.cancel is called, resource handle must be closed // The test should not fail with: Test case is leaking resources await res.body.cancel(); - } + }, ); unitTest( @@ -869,7 +869,7 @@ unitTest( assertEquals(res.body, null); assertEquals(res.status, status); } - } + }, ); unitTest( @@ -888,7 +888,7 @@ unitTest( // Make sure Body content-type is correctly set assertEquals(blob.type, "application/octet-stream"); assertEquals(blob.size, body.byteLength); - } + }, ); unitTest(function fetchResponseConstructorNullBody(): void { @@ -902,7 +902,7 @@ unitTest(function fetchResponseConstructorNullBody(): void { assert(e instanceof TypeError); assertEquals( e.message, - "Response with null body status cannot have body" + "Response with null body status cannot have body", ); } } @@ -921,7 +921,7 @@ unitTest(function fetchResponseConstructorInvalidStatus(): void { assert(e instanceof RangeError); assertEquals( e.message, - `The status provided (${status}) is outside the range [200, 599]` + `The status provided (${status}) is outside the range [200, 599]`, ); } } diff --git a/cli/tests/unit/file_test.ts b/cli/tests/unit/file_test.ts index 4941554ad..f97283b7f 100644 --- a/cli/tests/unit/file_test.ts +++ b/cli/tests/unit/file_test.ts @@ -60,7 +60,7 @@ unitTest(function fileVariousFileBits(): void { new Uint16Array([0x5353]), new Uint32Array([0x53534150]), ], - 16 + 16, ); }); diff --git a/cli/tests/unit/files_test.ts b/cli/tests/unit/files_test.ts index aca63928b..8992fa71c 100644 --- a/cli/tests/unit/files_test.ts +++ b/cli/tests/unit/files_test.ts @@ -54,7 +54,7 @@ unitTest( assertEquals(totalSize, 12); assertEquals(iterations, 2); file.close(); - } + }, ); unitTest({ perms: { read: true } }, function filesIterSync(): void { @@ -86,7 +86,7 @@ unitTest( assertEquals(totalSize, 12); assertEquals(iterations, 2); file.close(); - } + }, ); unitTest(async function readerIter(): Promise<void> { @@ -175,7 +175,7 @@ unitTest( if (Deno.build.os !== "windows") { assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); } - } + }, ); unitTest( @@ -194,7 +194,7 @@ unitTest( if (Deno.build.os !== "windows") { assertEquals(pathInfo.mode! & 0o777, 0o626 & ~Deno.umask()); } - } + }, ); unitTest( @@ -204,7 +204,9 @@ unitTest( function openSyncUrl(): void { const tempDir = Deno.makeTempDirSync(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test_open.txt` + `file://${ + Deno.build.os === "windows" ? "/" : "" + }${tempDir}/test_open.txt`, ); const file = Deno.openSync(fileUrl, { write: true, @@ -218,7 +220,7 @@ unitTest( } Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -228,7 +230,9 @@ unitTest( async function openUrl(): Promise<void> { const tempDir = await Deno.makeTempDir(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test_open.txt` + `file://${ + Deno.build.os === "windows" ? "/" : "" + }${tempDir}/test_open.txt`, ); const file = await Deno.open(fileUrl, { write: true, @@ -242,7 +246,7 @@ unitTest( } Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -255,7 +259,7 @@ unitTest( await Deno.open(filename, options); }, Deno.errors.PermissionDenied); } - } + }, ); unitTest(async function openOptions(): Promise<void> { @@ -265,7 +269,7 @@ unitTest(async function openOptions(): Promise<void> { await Deno.open(filename, { write: false }); }, Error, - "OpenOptions requires at least one option to be true" + "OpenOptions requires at least one option to be true", ); await assertThrowsAsync( @@ -273,7 +277,7 @@ unitTest(async function openOptions(): Promise<void> { await Deno.open(filename, { truncate: true, write: false }); }, Error, - "'truncate' option requires 'write' option" + "'truncate' option requires 'write' option", ); await assertThrowsAsync( @@ -281,7 +285,7 @@ unitTest(async function openOptions(): Promise<void> { await Deno.open(filename, { create: true, write: false }); }, Error, - "'create' or 'createNew' options require 'write' or 'append' option" + "'create' or 'createNew' options require 'write' or 'append' option", ); await assertThrowsAsync( @@ -289,7 +293,7 @@ unitTest(async function openOptions(): Promise<void> { await Deno.open(filename, { createNew: true, append: false }); }, Error, - "'create' or 'createNew' options require 'write' or 'append' option" + "'create' or 'createNew' options require 'write' or 'append' option", ); }); @@ -318,11 +322,11 @@ unitTest( async (): Promise<void> => { // eslint-disable-next-line @typescript-eslint/no-explicit-any await file.write(null as any); - } + }, ); // TODO: Check error kind when dispatch_minimal pipes errors properly file.close(); await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -350,7 +354,7 @@ unitTest( file.close(); await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -360,7 +364,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.open(filename, { read: true }); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -381,7 +385,7 @@ unitTest( // TODO: test different modes await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -389,7 +393,7 @@ unitTest( async function createFileWithUrl(): Promise<void> { const tempDir = await Deno.makeTempDir(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); const f = await Deno.create(fileUrl); let fileInfo = Deno.statSync(fileUrl); @@ -403,7 +407,7 @@ unitTest( f.close(); await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -424,7 +428,7 @@ unitTest( // TODO: test different modes await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -432,7 +436,7 @@ unitTest( async function createSyncFileWithUrl(): Promise<void> { const tempDir = await Deno.makeTempDir(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); const f = Deno.createSync(fileUrl); let fileInfo = Deno.statSync(fileUrl); @@ -446,7 +450,7 @@ unitTest( f.close(); await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -489,7 +493,7 @@ unitTest( const fileSize = Deno.statSync(filename).size; assertEquals(fileSize, 0); await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -525,7 +529,7 @@ unitTest( file.close(); await Deno.remove(tempDir, { recursive: true }); - } + }, ); unitTest({ perms: { read: true } }, async function seekStart(): Promise<void> { @@ -634,7 +638,7 @@ unitTest({ perms: { read: true } }, async function seekMode(): Promise<void> { await file.seek(1, -1); }, TypeError, - "Invalid seek mode" + "Invalid seek mode", ); // We should still be able to read the file diff --git a/cli/tests/unit/form_data_test.ts b/cli/tests/unit/form_data_test.ts index 338fdd089..30e9a8311 100644 --- a/cli/tests/unit/form_data_test.ts +++ b/cli/tests/unit/form_data_test.ts @@ -157,7 +157,7 @@ unitTest(function formDataParamsArgumentsCheck(): void { assertEquals(hasThrown, 2); assertStringContains( errMsg, - `${method} requires at least 1 argument, but only 0 present` + `${method} requires at least 1 argument, but only 0 present`, ); }); @@ -181,7 +181,7 @@ unitTest(function formDataParamsArgumentsCheck(): void { assertEquals(hasThrown, 2); assertStringContains( errMsg, - `${method} requires at least 2 arguments, but only 0 present` + `${method} requires at least 2 arguments, but only 0 present`, ); hasThrown = 0; @@ -201,7 +201,7 @@ unitTest(function formDataParamsArgumentsCheck(): void { assertEquals(hasThrown, 2); assertStringContains( errMsg, - `${method} requires at least 2 arguments, but only 1 present` + `${method} requires at least 2 arguments, but only 1 present`, ); }); }); diff --git a/cli/tests/unit/fs_events_test.ts b/cli/tests/unit/fs_events_test.ts index ec146f185..f2dd59d79 100644 --- a/cli/tests/unit/fs_events_test.ts +++ b/cli/tests/unit/fs_events_test.ts @@ -16,7 +16,7 @@ unitTest({ perms: { read: true } }, function watchFsInvalidPath() { Deno.watchFs("non-existant.file"); }, Error, - "Input watch path is neither a file nor a directory" + "Input watch path is neither a file nor a directory", ); } else { assertThrows(() => { @@ -26,7 +26,7 @@ unitTest({ perms: { read: true } }, function watchFsInvalidPath() { }); async function getTwoEvents( - iter: AsyncIterableIterator<Deno.FsEvent> + iter: AsyncIterableIterator<Deno.FsEvent>, ): Promise<Deno.FsEvent[]> { const events = []; for await (const event of iter) { @@ -58,5 +58,5 @@ unitTest( assert(events[0].paths[0].includes(testDir)); assert(events[1].kind == "create" || events[1].kind == "modify"); assert(events[1].paths[0].includes(testDir)); - } + }, ); diff --git a/cli/tests/unit/headers_test.ts b/cli/tests/unit/headers_test.ts index 2156fb56b..5dc23355c 100644 --- a/cli/tests/unit/headers_test.ts +++ b/cli/tests/unit/headers_test.ts @@ -27,7 +27,7 @@ unitTest(function newHeaderTest(): void { } catch (e) { assertEquals( e.message, - "Failed to construct 'Headers'; The provided value was not valid" + "Failed to construct 'Headers'; The provided value was not valid", ); } }); @@ -91,7 +91,7 @@ unitTest(function headerHasSuccess(): void { assert(headers.has(name), "headers has name " + name); assert( !headers.has("nameNotInHeaders"), - "headers do not have header: nameNotInHeaders" + "headers do not have header: nameNotInHeaders", ); } }); @@ -287,7 +287,7 @@ unitTest(function headerParamsArgumentsCheck(): void { assertEquals(hasThrown, 2); assertStringContains( errMsg, - `${method} requires at least 1 argument, but only 0 present` + `${method} requires at least 1 argument, but only 0 present`, ); }); @@ -311,7 +311,7 @@ unitTest(function headerParamsArgumentsCheck(): void { assertEquals(hasThrown, 2); assertStringContains( errMsg, - `${method} requires at least 2 arguments, but only 0 present` + `${method} requires at least 2 arguments, but only 0 present`, ); hasThrown = 0; @@ -331,7 +331,7 @@ unitTest(function headerParamsArgumentsCheck(): void { assertEquals(hasThrown, 2); assertStringContains( errMsg, - `${method} requires at least 2 arguments, but only 1 present` + `${method} requires at least 2 arguments, but only 1 present`, ); }); }); @@ -411,7 +411,7 @@ unitTest(function customInspectReturnsCorrectHeadersFormat(): void { const singleHeader = new Headers([["Content-Type", "application/json"]]); assertEquals( stringify(singleHeader), - "Headers { content-type: application/json }" + "Headers { content-type: application/json }", ); const multiParamHeader = new Headers([ ["Content-Type", "application/json"], @@ -419,6 +419,6 @@ unitTest(function customInspectReturnsCorrectHeadersFormat(): void { ]); assertEquals( stringify(multiParamHeader), - "Headers { content-type: application/json, content-length: 1337 }" + "Headers { content-type: application/json, content-length: 1337 }", ); }); diff --git a/cli/tests/unit/link_test.ts b/cli/tests/unit/link_test.ts index c84d0f6a3..db910ee7c 100644 --- a/cli/tests/unit/link_test.ts +++ b/cli/tests/unit/link_test.ts @@ -19,14 +19,14 @@ unitTest( Deno.writeFileSync(newName, new TextEncoder().encode(newData2)); assertEquals( newData2, - new TextDecoder().decode(Deno.readFileSync(oldName)) + new TextDecoder().decode(Deno.readFileSync(oldName)), ); // Writing to oldname also affects newname. const newData3 = "ModifiedAgain"; Deno.writeFileSync(oldName, new TextEncoder().encode(newData3)); assertEquals( newData3, - new TextDecoder().decode(Deno.readFileSync(newName)) + new TextDecoder().decode(Deno.readFileSync(newName)), ); // Remove oldname. File still accessible through newname. Deno.removeSync(oldName); @@ -35,9 +35,9 @@ unitTest( assert(!newNameStat.isSymlink); // Not a symlink. assertEquals( newData3, - new TextDecoder().decode(Deno.readFileSync(newName)) + new TextDecoder().decode(Deno.readFileSync(newName)), ); - } + }, ); unitTest( @@ -53,7 +53,7 @@ unitTest( assertThrows(() => { Deno.linkSync(oldName, newName); }, Deno.errors.AlreadyExists); - } + }, ); unitTest( @@ -66,7 +66,7 @@ unitTest( assertThrows(() => { Deno.linkSync(oldName, newName); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -75,7 +75,7 @@ unitTest( assertThrows(() => { Deno.linkSync("oldbaddir", "newbaddir"); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -84,7 +84,7 @@ unitTest( assertThrows(() => { Deno.linkSync("oldbaddir", "newbaddir"); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -105,14 +105,14 @@ unitTest( Deno.writeFileSync(newName, new TextEncoder().encode(newData2)); assertEquals( newData2, - new TextDecoder().decode(Deno.readFileSync(oldName)) + new TextDecoder().decode(Deno.readFileSync(oldName)), ); // Writing to oldname also affects newname. const newData3 = "ModifiedAgain"; Deno.writeFileSync(oldName, new TextEncoder().encode(newData3)); assertEquals( newData3, - new TextDecoder().decode(Deno.readFileSync(newName)) + new TextDecoder().decode(Deno.readFileSync(newName)), ); // Remove oldname. File still accessible through newname. Deno.removeSync(oldName); @@ -121,7 +121,7 @@ unitTest( assert(!newNameStat.isSymlink); // Not a symlink. assertEquals( newData3, - new TextDecoder().decode(Deno.readFileSync(newName)) + new TextDecoder().decode(Deno.readFileSync(newName)), ); - } + }, ); diff --git a/cli/tests/unit/make_temp_test.ts b/cli/tests/unit/make_temp_test.ts index c1498aa64..05a422cfd 100644 --- a/cli/tests/unit/make_temp_test.ts +++ b/cli/tests/unit/make_temp_test.ts @@ -36,7 +36,7 @@ unitTest( if (Deno.build.os !== "windows") { assertEquals(pathInfo.mode! & 0o777, 0o700 & ~Deno.umask()); } - } + }, ); unitTest(function makeTempDirSyncPerm(): void { @@ -67,7 +67,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.makeTempDir({ dir: "/baddir" }); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -78,7 +78,7 @@ unitTest( if (Deno.build.os !== "windows") { assertEquals(pathInfo.mode! & 0o777, 0o700 & ~Deno.umask()); } - } + }, ); unitTest({ perms: { write: true } }, function makeTempFileSyncSuccess(): void { @@ -111,7 +111,7 @@ unitTest( if (Deno.build.os !== "windows") { assertEquals(pathInfo.mode! & 0o777, 0o600 & ~Deno.umask()); } - } + }, ); unitTest(function makeTempFileSyncPerm(): void { @@ -143,7 +143,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.makeTempFile({ dir: "/baddir" }); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -154,5 +154,5 @@ unitTest( if (Deno.build.os !== "windows") { assertEquals(pathInfo.mode! & 0o777, 0o600 & ~Deno.umask()); } - } + }, ); diff --git a/cli/tests/unit/metrics_test.ts b/cli/tests/unit/metrics_test.ts index 9b7d83887..48ddf30d7 100644 --- a/cli/tests/unit/metrics_test.ts +++ b/cli/tests/unit/metrics_test.ts @@ -39,7 +39,7 @@ unitTest( const metrics = Deno.metrics(); assert(metrics.opsDispatched === metrics.opsCompleted); assert(metrics.opsDispatchedSync === metrics.opsCompletedSync); - } + }, ); unitTest( @@ -54,5 +54,5 @@ unitTest( assert(metrics.opsDispatched === metrics.opsCompleted); assert(metrics.opsDispatchedSync === metrics.opsCompletedSync); assert(metrics.opsDispatchedAsync === metrics.opsCompletedAsync); - } + }, ); diff --git a/cli/tests/unit/mkdir_test.ts b/cli/tests/unit/mkdir_test.ts index 32632bfef..449c79747 100644 --- a/cli/tests/unit/mkdir_test.ts +++ b/cli/tests/unit/mkdir_test.ts @@ -21,7 +21,7 @@ unitTest( const path = Deno.makeTempDirSync() + "/dir"; Deno.mkdirSync(path); assertDirectory(path); - } + }, ); unitTest( @@ -30,7 +30,7 @@ unitTest( const path = Deno.makeTempDirSync() + "/dir"; Deno.mkdirSync(path, { mode: 0o737 }); assertDirectory(path, 0o737); - } + }, ); unitTest({ perms: { write: false } }, function mkdirSyncPerm(): void { @@ -45,7 +45,7 @@ unitTest( const path = Deno.makeTempDirSync() + "/dir"; await Deno.mkdir(path); assertDirectory(path); - } + }, ); unitTest( @@ -54,7 +54,7 @@ unitTest( const path = Deno.makeTempDirSync() + "/dir"; await Deno.mkdir(path, { mode: 0o737 }); assertDirectory(path, 0o737); - } + }, ); unitTest({ perms: { write: true } }, function mkdirErrSyncIfExists(): void { @@ -77,7 +77,7 @@ unitTest( const path = Deno.makeTempDirSync() + "/nested/directory"; Deno.mkdirSync(path, { recursive: true }); assertDirectory(path); - } + }, ); unitTest( @@ -86,7 +86,7 @@ unitTest( const path = Deno.makeTempDirSync() + "/nested/directory"; await Deno.mkdir(path, { recursive: true }); assertDirectory(path); - } + }, ); unitTest( @@ -97,7 +97,7 @@ unitTest( Deno.mkdirSync(path, { mode: 0o737, recursive: true }); assertDirectory(path, 0o737); assertDirectory(nested, 0o737); - } + }, ); unitTest( @@ -108,7 +108,7 @@ unitTest( await Deno.mkdir(path, { mode: 0o737, recursive: true }); assertDirectory(path, 0o737); assertDirectory(nested, 0o737); - } + }, ); unitTest( @@ -126,7 +126,7 @@ unitTest( Deno.mkdirSync(pathLink, { recursive: true, mode: 0o731 }); assertDirectory(path, 0o737); } - } + }, ); unitTest( @@ -144,7 +144,7 @@ unitTest( await Deno.mkdir(pathLink, { recursive: true, mode: 0o731 }); assertDirectory(path, 0o737); } - } + }, ); unitTest( @@ -195,5 +195,5 @@ unitTest( Deno.mkdirSync(danglingLink, { recursive: true }); }, Deno.errors.AlreadyExists); } - } + }, ); diff --git a/cli/tests/unit/net_test.ts b/cli/tests/unit/net_test.ts index e970f0360..793082ced 100644 --- a/cli/tests/unit/net_test.ts +++ b/cli/tests/unit/net_test.ts @@ -34,7 +34,7 @@ unitTest( assertEquals(socket.addr.hostname, "127.0.0.1"); assertEquals(socket.addr.port, 3500); socket.close(); - } + }, ); unitTest( @@ -48,7 +48,7 @@ unitTest( assert(socket.addr.transport === "unix"); assertEquals(socket.addr.path, filePath); socket.close(); - } + }, ); unitTest( @@ -62,7 +62,7 @@ unitTest( assert(socket.addr.transport === "unixpacket"); assertEquals(socket.addr.path, filePath); socket.close(); - } + }, ); unitTest( @@ -78,9 +78,9 @@ unitTest( await p; }, Deno.errors.BadResource, - "Listener has been closed" + "Listener has been closed", ); - } + }, ); unitTest( @@ -98,9 +98,9 @@ unitTest( await p; }, Deno.errors.BadResource, - "Listener has been closed" + "Listener has been closed", ); - } + }, ); unitTest( @@ -123,7 +123,7 @@ unitTest( listener.close(); await Promise.all([p, p1]); assertEquals(acceptErrCount, 1); - } + }, ); // TODO(jsouto): Enable when tokio updates mio to v0.7! @@ -148,7 +148,7 @@ unitTest( listener.close(); await [p, p1]; assertEquals(acceptErrCount, 1); - } + }, ); unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise< @@ -163,7 +163,7 @@ unitTest({ perms: { net: true } }, async function netTcpDialListen(): Promise< assertEquals(conn.localAddr.port, 3500); await conn.write(new Uint8Array([1, 2, 3])); conn.close(); - } + }, ); const conn = await Deno.connect({ hostname: "127.0.0.1", port: 3500 }); @@ -200,7 +200,7 @@ unitTest( assertEquals(conn.localAddr.path, filePath); await conn.write(new Uint8Array([1, 2, 3])); conn.close(); - } + }, ); const conn = await Deno.connect({ path: filePath, transport: "unix" }); assert(conn.remoteAddr.transport === "unix"); @@ -221,7 +221,7 @@ unitTest( listener.close(); conn.close(); - } + }, ); unitTest( @@ -251,7 +251,7 @@ unitTest( assertEquals(3, recvd[2]); alice.close(); bob.close(); - } + }, ); unitTest( @@ -266,7 +266,7 @@ unitTest( const b = socket.send(new Uint8Array(), socket.addr); await Promise.all([a, b]); socket.close(); - } + }, ); unitTest( @@ -300,7 +300,7 @@ unitTest( assertEquals(3, recvd[2]); alice.close(); bob.close(); - } + }, ); unitTest( @@ -336,7 +336,7 @@ unitTest( conn2.close(); await promise; - } + }, ); unitTest( @@ -349,7 +349,7 @@ unitTest( const nextAfterClosing = listener[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); - } + }, ); unitTest( @@ -362,7 +362,7 @@ unitTest( const nextAfterClosing = socket[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); - } + }, ); unitTest( @@ -376,7 +376,7 @@ unitTest( const nextAfterClosing = socket[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); - } + }, ); unitTest( @@ -393,7 +393,7 @@ unitTest( const nextAfterClosing = socket[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); - } + }, ); unitTest( @@ -428,7 +428,7 @@ unitTest( listener.close(); conn.close(); - } + }, ); unitTest( @@ -462,7 +462,7 @@ unitTest( closeDeferred.resolve(); listener.close(); conn.close(); - } + }, ); unitTest( @@ -488,7 +488,7 @@ unitTest( closeDeferred.resolve(); listener.close(); conn.close(); - } + }, ); unitTest( @@ -531,5 +531,5 @@ unitTest( acceptedConn!.close(); listener.close(); await resolvable; - } + }, ); diff --git a/cli/tests/unit/os_test.ts b/cli/tests/unit/os_test.ts index e969464e5..79f70afac 100644 --- a/cli/tests/unit/os_test.ts +++ b/cli/tests/unit/os_test.ts @@ -54,7 +54,7 @@ unitTest( // It is then verified that these match with the values of `expectedEnv`. const checkChildEnv = async ( inputEnv: Record<string, string>, - expectedEnv: Record<string, string> + expectedEnv: Record<string, string>, ): Promise<void> => { const src = ` console.log( @@ -69,7 +69,7 @@ unitTest( assertEquals(status.success, true); const expectedValues = Object.values(expectedEnv); const actualValues = JSON.parse( - new TextDecoder().decode(await proc.output()) + new TextDecoder().decode(await proc.output()), ); assertEquals(actualValues, expectedValues); proc.close(); @@ -87,7 +87,7 @@ unitTest( assertNotEquals(lc1, uc1); await checkChildEnv( { [lc1]: "mu", [uc1]: "MU" }, - { [lc1]: "mu", [uc1]: "MU" } + { [lc1]: "mu", [uc1]: "MU" }, ); // Check that 'dž' and 'DŽ' are folded, but 'Dž' is preserved. @@ -98,13 +98,13 @@ unitTest( assertNotEquals(c2, uc2); await checkChildEnv( { [c2]: "Dz", [lc2]: "dz" }, - { [c2]: "Dz", [lc2]: "dz", [uc2]: "dz" } + { [c2]: "Dz", [lc2]: "dz", [uc2]: "dz" }, ); await checkChildEnv( { [c2]: "Dz", [uc2]: "DZ" }, - { [c2]: "Dz", [uc2]: "DZ", [lc2]: "DZ" } + { [c2]: "Dz", [uc2]: "DZ", [lc2]: "DZ" }, ); - } + }, ); unitTest(function osPid(): void { @@ -130,7 +130,7 @@ unitTest( const expected = Deno.pid; const actual = parseInt(decoder.decode(output)); assertEquals(actual, expected); - } + }, ); unitTest({ perms: { read: true } }, function execPath(): void { @@ -143,7 +143,7 @@ unitTest({ perms: { read: false } }, function execPathPerm(): void { Deno.execPath(); }, Deno.errors.PermissionDenied, - "read access to <exec_path>, run again with the --allow-read flag" + "read access to <exec_path>, run again with the --allow-read flag", ); }); diff --git a/cli/tests/unit/path_from_url_test.ts b/cli/tests/unit/path_from_url_test.ts index d43245c06..047451d48 100644 --- a/cli/tests/unit/path_from_url_test.ts +++ b/cli/tests/unit/path_from_url_test.ts @@ -8,11 +8,11 @@ unitTest( function pathFromURLPosix(): void { assertEquals( pathFromURL(new URL("file:///test/directory")), - "/test/directory" + "/test/directory", ); assertEquals(pathFromURL(new URL("file:///space_ .txt")), "/space_ .txt"); assertThrows(() => pathFromURL(new URL("https://deno.land/welcome.ts"))); - } + }, ); unitTest( @@ -20,11 +20,11 @@ unitTest( function pathFromURLWin32(): void { assertEquals( pathFromURL(new URL("file:///c:/windows/test")), - "c:\\windows\\test" + "c:\\windows\\test", ); assertEquals( pathFromURL(new URL("file:///c:/space_ .txt")), - "c:\\space_ .txt" + "c:\\space_ .txt", ); assertThrows(() => pathFromURL(new URL("https://deno.land/welcome.ts"))); /* TODO(ry) Add tests for these situations @@ -35,5 +35,5 @@ unitTest( * pound_#.txt file:///D:/weird_names/pound_%23.txt * swapped_surrogate_pair_��.txt file:///D:/weird_names/swapped_surrogate_pair_%EF%BF%BD%EF%BF%BD.txt */ - } + }, ); diff --git a/cli/tests/unit/performance_test.ts b/cli/tests/unit/performance_test.ts index cf3c86517..3c98e4e40 100644 --- a/cli/tests/unit/performance_test.ts +++ b/cli/tests/unit/performance_test.ts @@ -47,11 +47,11 @@ unitTest(function performanceMeasure() { assertEquals(mark.startTime, measure.startTime); assert( measure.duration >= 100, - `duration below 100ms: ${measure.duration}` + `duration below 100ms: ${measure.duration}`, ); assert( measure.duration < 500, - `duration exceeds 500ms: ${measure.duration}` + `duration exceeds 500ms: ${measure.duration}`, ); const entries = performance.getEntries(); assert(entries[entries.length - 1] === measure); diff --git a/cli/tests/unit/process_test.ts b/cli/tests/unit/process_test.ts index 7cb9d9ba5..966a9425b 100644 --- a/cli/tests/unit/process_test.ts +++ b/cli/tests/unit/process_test.ts @@ -78,7 +78,7 @@ unitTest( assertEquals(status.code, 42); assertEquals(status.signal, undefined); p.close(); - } + }, ); unitTest( @@ -96,7 +96,7 @@ unitTest( assertEquals(status.code, 128 + 9); assertEquals(status.signal, 9); p.close(); - } + }, ); unitTest({ perms: { run: true } }, function runNotFound(): void { @@ -150,7 +150,7 @@ while True: assertEquals(status.code, code); assertEquals(status.signal, undefined); p.close(); - } + }, ); unitTest({ perms: { run: true } }, async function runStdinPiped(): Promise< @@ -289,7 +289,7 @@ unitTest( assertStringContains(text, "error"); assertStringContains(text, "output"); - } + }, ); unitTest( @@ -310,7 +310,7 @@ unitTest( assertEquals(status.code, 0); p.close(); file.close(); - } + }, ); unitTest({ perms: { run: true } }, async function runEnv(): Promise<void> { diff --git a/cli/tests/unit/read_dir_test.ts b/cli/tests/unit/read_dir_test.ts index de4b217bf..97c45dac3 100644 --- a/cli/tests/unit/read_dir_test.ts +++ b/cli/tests/unit/read_dir_test.ts @@ -63,9 +63,9 @@ unitTest({ perms: { read: true } }, async function readDirWithUrl(): Promise< void > { const files = []; - for await (const dirEntry of Deno.readDir( - pathToAbsoluteFileUrl("cli/tests") - )) { + for await ( + const dirEntry of Deno.readDir(pathToAbsoluteFileUrl("cli/tests")) + ) { files.push(dirEntry); } assertSameContent(files); diff --git a/cli/tests/unit/read_file_test.ts b/cli/tests/unit/read_file_test.ts index 28407cf24..06141002d 100644 --- a/cli/tests/unit/read_file_test.ts +++ b/cli/tests/unit/read_file_test.ts @@ -19,7 +19,7 @@ unitTest({ perms: { read: true } }, function readFileSyncSuccess(): void { unitTest({ perms: { read: true } }, function readFileSyncUrl(): void { const data = Deno.readFileSync( - pathToAbsoluteFileUrl("cli/tests/fixture.json") + pathToAbsoluteFileUrl("cli/tests/fixture.json"), ); assert(data.byteLength > 0); const decoder = new TextDecoder("utf-8"); @@ -44,7 +44,7 @@ unitTest({ perms: { read: true } }, async function readFileUrl(): Promise< void > { const data = await Deno.readFile( - pathToAbsoluteFileUrl("cli/tests/fixture.json") + pathToAbsoluteFileUrl("cli/tests/fixture.json"), ); assert(data.byteLength > 0); const decoder = new TextDecoder("utf-8"); diff --git a/cli/tests/unit/read_link_test.ts b/cli/tests/unit/read_link_test.ts index 597541914..a4baeb792 100644 --- a/cli/tests/unit/read_link_test.ts +++ b/cli/tests/unit/read_link_test.ts @@ -10,15 +10,15 @@ unitTest( { perms: { write: true, read: true } }, function readLinkSyncSuccess(): void { const testDir = Deno.makeTempDirSync(); - const target = - testDir + (Deno.build.os == "windows" ? "\\target" : "/target"); - const symlink = - testDir + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); + const target = testDir + + (Deno.build.os == "windows" ? "\\target" : "/target"); + const symlink = testDir + + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); Deno.mkdirSync(target); Deno.symlinkSync(target, symlink); const targetPath = Deno.readLinkSync(symlink); assertEquals(targetPath, target); - } + }, ); unitTest({ perms: { read: false } }, function readLinkSyncPerm(): void { @@ -37,15 +37,15 @@ unitTest( { perms: { write: true, read: true } }, async function readLinkSuccess(): Promise<void> { const testDir = Deno.makeTempDirSync(); - const target = - testDir + (Deno.build.os == "windows" ? "\\target" : "/target"); - const symlink = - testDir + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); + const target = testDir + + (Deno.build.os == "windows" ? "\\target" : "/target"); + const symlink = testDir + + (Deno.build.os == "windows" ? "\\symlink" : "/symlink"); Deno.mkdirSync(target); Deno.symlinkSync(target, symlink); const targetPath = await Deno.readLink(symlink); assertEquals(targetPath, target); - } + }, ); unitTest({ perms: { read: false } }, async function readLinkPerm(): Promise< diff --git a/cli/tests/unit/read_text_file_test.ts b/cli/tests/unit/read_text_file_test.ts index 4222da5a9..98275f781 100644 --- a/cli/tests/unit/read_text_file_test.ts +++ b/cli/tests/unit/read_text_file_test.ts @@ -16,7 +16,7 @@ unitTest({ perms: { read: true } }, function readTextFileSyncSuccess(): void { unitTest({ perms: { read: true } }, function readTextFileSyncByUrl(): void { const data = Deno.readTextFileSync( - pathToAbsoluteFileUrl("cli/tests/fixture.json") + pathToAbsoluteFileUrl("cli/tests/fixture.json"), ); assert(data.length > 0); const pkg = JSON.parse(data); @@ -42,14 +42,14 @@ unitTest( assert(data.length > 0); const pkg = JSON.parse(data); assertEquals(pkg.name, "deno"); - } + }, ); unitTest({ perms: { read: true } }, async function readTextFileByUrl(): Promise< void > { const data = await Deno.readTextFile( - pathToAbsoluteFileUrl("cli/tests/fixture.json") + pathToAbsoluteFileUrl("cli/tests/fixture.json"), ); assert(data.length > 0); const pkg = JSON.parse(data); diff --git a/cli/tests/unit/real_path_test.ts b/cli/tests/unit/real_path_test.ts index 6e754e3ee..1036f6132 100644 --- a/cli/tests/unit/real_path_test.ts +++ b/cli/tests/unit/real_path_test.ts @@ -34,7 +34,7 @@ unitTest( assert(/^[A-Z]/.test(targetPath)); } assert(targetPath.endsWith("/target")); - } + }, ); unitTest({ perms: { read: false } }, function realPathSyncPerm(): void { @@ -79,7 +79,7 @@ unitTest( assert(/^[A-Z]/.test(targetPath)); } assert(targetPath.endsWith("/target")); - } + }, ); unitTest({ perms: { read: false } }, async function realPathPerm(): Promise< diff --git a/cli/tests/unit/remove_test.ts b/cli/tests/unit/remove_test.ts index 42160af5c..14c960da5 100644 --- a/cli/tests/unit/remove_test.ts +++ b/cli/tests/unit/remove_test.ts @@ -23,7 +23,7 @@ unitTest( Deno.statSync(path); }, Deno.errors.NotFound); } - } + }, ); unitTest( @@ -43,7 +43,7 @@ unitTest( Deno.statSync(filename); }, Deno.errors.NotFound); } - } + }, ); unitTest( @@ -56,7 +56,7 @@ unitTest( const tempDir = Deno.makeTempDirSync(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); Deno.writeFileSync(fileUrl, data, { mode: 0o666 }); @@ -68,7 +68,7 @@ unitTest( Deno.statSync(fileUrl); }, Deno.errors.NotFound); } - } + }, ); unitTest( @@ -95,7 +95,7 @@ unitTest( await Deno[method]("/baddir"); }, Deno.errors.NotFound); } - } + }, ); unitTest( @@ -117,7 +117,7 @@ unitTest( Deno.lstatSync(danglingSymlinkPath); }, Deno.errors.NotFound); } - } + }, ); unitTest( @@ -143,7 +143,7 @@ unitTest( }, Deno.errors.NotFound); await Deno[method](filePath); } - } + }, ); unitTest({ perms: { write: false } }, async function removePerm(): Promise< @@ -171,7 +171,7 @@ unitTest( () => { Deno.statSync(path); }, // Directory is gone - Deno.errors.NotFound + Deno.errors.NotFound, ); // REMOVE NON-EMPTY DIRECTORY @@ -190,7 +190,7 @@ unitTest( }, Deno.errors.NotFound); // Directory is gone } - } + }, ); unitTest( @@ -211,7 +211,7 @@ unitTest( }, Deno.errors.NotFound); // File is gone } - } + }, ); unitTest({ perms: { write: true } }, async function removeAllFail(): Promise< @@ -254,7 +254,7 @@ unitTest( Deno.statSync(path); }, Deno.errors.NotFound); } - } + }, ); if (Deno.build.os === "windows") { @@ -272,7 +272,7 @@ if (Deno.build.os === "windows") { await assertThrowsAsync(async () => { await Deno.lstat("file_link"); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -290,6 +290,6 @@ if (Deno.build.os === "windows") { await assertThrowsAsync(async () => { await Deno.lstat("dir_link"); }, Deno.errors.NotFound); - } + }, ); } diff --git a/cli/tests/unit/rename_test.ts b/cli/tests/unit/rename_test.ts index 38a259782..dfde8dc05 100644 --- a/cli/tests/unit/rename_test.ts +++ b/cli/tests/unit/rename_test.ts @@ -37,7 +37,7 @@ unitTest( Deno.renameSync(oldpath, newpath); assertDirectory(newpath); assertMissing(oldpath); - } + }, ); unitTest( @@ -48,7 +48,7 @@ unitTest( const newpath = "/newbaddir"; Deno.renameSync(oldpath, newpath); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -59,7 +59,7 @@ unitTest( const newpath = "/newbaddir"; Deno.renameSync(oldpath, newpath); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -72,7 +72,7 @@ unitTest( await Deno.rename(oldpath, newpath); assertDirectory(newpath); assertMissing(oldpath); - } + }, ); function readFileString(filename: string): string { @@ -107,21 +107,21 @@ unitTest( Deno.renameSync(oldfile, emptydir); }, Error, - "Is a directory" + "Is a directory", ); assertThrows( (): void => { Deno.renameSync(olddir, fulldir); }, Error, - "Directory not empty" + "Directory not empty", ); assertThrows( (): void => { Deno.renameSync(olddir, file); }, Error, - "Not a directory" + "Not a directory", ); const fileLink = testDir + "/fileLink"; @@ -136,21 +136,21 @@ unitTest( Deno.renameSync(olddir, fileLink); }, Error, - "Not a directory" + "Not a directory", ); assertThrows( (): void => { Deno.renameSync(olddir, dirLink); }, Error, - "Not a directory" + "Not a directory", ); assertThrows( (): void => { Deno.renameSync(olddir, danglingLink); }, Error, - "Not a directory" + "Not a directory", ); // should succeed on Unix @@ -159,7 +159,7 @@ unitTest( Deno.renameSync(dirLink, danglingLink); assertFile(danglingLink); assertEquals("Hello", readFileString(danglingLink)); - } + }, ); unitTest( @@ -182,25 +182,25 @@ unitTest( Deno.renameSync(oldfile, emptydir); }, Deno.errors.PermissionDenied, - "Access is denied" + "Access is denied", ); assertThrows( (): void => { Deno.renameSync(olddir, fulldir); }, Deno.errors.PermissionDenied, - "Access is denied" + "Access is denied", ); assertThrows( (): void => { Deno.renameSync(olddir, emptydir); }, Deno.errors.PermissionDenied, - "Access is denied" + "Access is denied", ); // should succeed on Windows Deno.renameSync(olddir, file); assertDirectory(file); - } + }, ); diff --git a/cli/tests/unit/resources_test.ts b/cli/tests/unit/resources_test.ts index e4d420055..5742fd6a0 100644 --- a/cli/tests/unit/resources_test.ts +++ b/cli/tests/unit/resources_test.ts @@ -25,10 +25,10 @@ unitTest({ perms: { net: true } }, async function resourcesNet(): Promise< const res = Deno.resources(); assertEquals( Object.values(res).filter((r): boolean => r === "tcpListener").length, - 1 + 1, ); const tcpStreams = Object.values(res).filter( - (r): boolean => r === "tcpStream" + (r): boolean => r === "tcpStream", ); assert(tcpStreams.length >= 2); @@ -48,7 +48,7 @@ unitTest({ perms: { read: true } }, async function resourcesFile(): Promise< // check that exactly one new resource (file) was added assertEquals( Object.keys(resourcesAfter).length, - Object.keys(resourcesBefore).length + 1 + Object.keys(resourcesBefore).length + 1, ); const newRid = +Object.keys(resourcesAfter).find((rid): boolean => { return !resourcesBefore.hasOwnProperty(rid); diff --git a/cli/tests/unit/signal_test.ts b/cli/tests/unit/signal_test.ts index 2f117f8d1..98eac6e0b 100644 --- a/cli/tests/unit/signal_test.ts +++ b/cli/tests/unit/signal_test.ts @@ -21,86 +21,86 @@ unitTest( Deno.signal(1); }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.alarm(); // for SIGALRM }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.child(); // for SIGCHLD }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.hungup(); // for SIGHUP }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.interrupt(); // for SIGINT }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.io(); // for SIGIO }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.pipe(); // for SIGPIPE }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.quit(); // for SIGQUIT }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.terminate(); // for SIGTERM }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.userDefined1(); // for SIGUSR1 }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.userDefined2(); // for SIGURS2 }, Error, - "not implemented" + "not implemented", ); assertThrows( () => { Deno.signals.windowChange(); // for SIGWINCH }, Error, - "not implemented" + "not implemented", ); - } + }, ); unitTest( @@ -131,7 +131,7 @@ unitTest( clearInterval(t); await resolvable; - } + }, ); unitTest( @@ -151,7 +151,7 @@ unitTest( clearInterval(t); await resolvable; - } + }, ); unitTest( @@ -191,5 +191,5 @@ unitTest( s = Deno.signals.windowChange(); // for SIGWINCH assert(s instanceof Deno.SignalStream); s.dispose(); - } + }, ); diff --git a/cli/tests/unit/stat_test.ts b/cli/tests/unit/stat_test.ts index 48142bc12..092724395 100644 --- a/cli/tests/unit/stat_test.ts +++ b/cli/tests/unit/stat_test.ts @@ -59,7 +59,7 @@ unitTest( assert(tempInfo.atime !== null && now - tempInfo.atime.valueOf() < 1000); assert(tempInfo.mtime !== null && now - tempInfo.mtime.valueOf() < 1000); assert( - tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000 + tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000, ); const packageInfoByUrl = Deno.statSync(pathToAbsoluteFileUrl("README.md")); @@ -67,7 +67,7 @@ unitTest( assert(!packageInfoByUrl.isSymlink); const modulesInfoByUrl = Deno.statSync( - pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir") + pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), ); assert(modulesInfoByUrl.isDirectory); assert(!modulesInfoByUrl.isSymlink); @@ -79,24 +79,26 @@ unitTest( const tempFileForUrl = Deno.makeTempFileSync(); const tempInfoByUrl = Deno.statSync( new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}` - ) + `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}`, + ), ); now = Date.now(); assert( - tempInfoByUrl.atime !== null && now - tempInfoByUrl.atime.valueOf() < 1000 + tempInfoByUrl.atime !== null && + now - tempInfoByUrl.atime.valueOf() < 1000, ); assert( - tempInfoByUrl.mtime !== null && now - tempInfoByUrl.mtime.valueOf() < 1000 + tempInfoByUrl.mtime !== null && + now - tempInfoByUrl.mtime.valueOf() < 1000, ); assert( tempInfoByUrl.birthtime === null || - now - tempInfoByUrl.birthtime.valueOf() < 1000 + now - tempInfoByUrl.birthtime.valueOf() < 1000, ); Deno.removeSync(tempFile, { recursive: true }); Deno.removeSync(tempFileForUrl, { recursive: true }); - } + }, ); unitTest({ perms: { read: false } }, function statSyncPerm(): void { @@ -125,7 +127,7 @@ unitTest({ perms: { read: true } }, function lstatSyncSuccess(): void { assert(modulesInfo.isSymlink); const modulesInfoByUrl = Deno.lstatSync( - pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir") + pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), ); assert(!modulesInfoByUrl.isDirectory); assert(modulesInfoByUrl.isSymlink); @@ -159,7 +161,7 @@ unitTest( assert(!packageInfo.isSymlink); const packageInfoByUrl = await Deno.stat( - pathToAbsoluteFileUrl("README.md") + pathToAbsoluteFileUrl("README.md"), ); assert(packageInfoByUrl.isFile); assert(!packageInfoByUrl.isSymlink); @@ -169,7 +171,7 @@ unitTest( assert(!modulesInfo.isSymlink); const modulesInfoByUrl = await Deno.stat( - pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir") + pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), ); assert(modulesInfoByUrl.isDirectory); assert(!modulesInfoByUrl.isSymlink); @@ -189,30 +191,32 @@ unitTest( assert(tempInfo.mtime !== null && now - tempInfo.mtime.valueOf() < 1000); assert( - tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000 + tempInfo.birthtime === null || now - tempInfo.birthtime.valueOf() < 1000, ); const tempFileForUrl = await Deno.makeTempFile(); const tempInfoByUrl = await Deno.stat( new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}` - ) + `file://${Deno.build.os === "windows" ? "/" : ""}${tempFileForUrl}`, + ), ); now = Date.now(); assert( - tempInfoByUrl.atime !== null && now - tempInfoByUrl.atime.valueOf() < 1000 + tempInfoByUrl.atime !== null && + now - tempInfoByUrl.atime.valueOf() < 1000, ); assert( - tempInfoByUrl.mtime !== null && now - tempInfoByUrl.mtime.valueOf() < 1000 + tempInfoByUrl.mtime !== null && + now - tempInfoByUrl.mtime.valueOf() < 1000, ); assert( tempInfoByUrl.birthtime === null || - now - tempInfoByUrl.birthtime.valueOf() < 1000 + now - tempInfoByUrl.birthtime.valueOf() < 1000, ); Deno.removeSync(tempFile, { recursive: true }); Deno.removeSync(tempFileForUrl, { recursive: true }); - } + }, ); unitTest({ perms: { read: false } }, async function statPerm(): Promise<void> { @@ -227,7 +231,7 @@ unitTest({ perms: { read: true } }, async function statNotFound(): Promise< await assertThrowsAsync( async (): Promise<void> => { await Deno.stat("bad_file_name"), Deno.errors.NotFound; - } + }, ); }); @@ -247,7 +251,7 @@ unitTest({ perms: { read: true } }, async function lstatSuccess(): Promise< assert(modulesInfo.isSymlink); const modulesInfoByUrl = await Deno.lstat( - pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir") + pathToAbsoluteFileUrl("cli/tests/symlink_to_subdir"), ); assert(!modulesInfoByUrl.isDirectory); assert(modulesInfoByUrl.isSymlink); @@ -293,7 +297,7 @@ unitTest( assert(s.rdev === null); assert(s.blksize === null); assert(s.blocks === null); - } + }, ); unitTest( @@ -317,5 +321,5 @@ unitTest( assert(s.rdev !== null); assert(s.blksize !== null); assert(s.blocks !== null); - } + }, ); diff --git a/cli/tests/unit/streams_internal_test.ts b/cli/tests/unit/streams_internal_test.ts index 346ec27af..caeab431d 100644 --- a/cli/tests/unit/streams_internal_test.ts +++ b/cli/tests/unit/streams_internal_test.ts @@ -10,7 +10,7 @@ unitTest(function streamReadableHwmError() { new ReadableStream<number>(undefined, { highWaterMark }); }, RangeError, - "highWaterMark must be a positive number or Infinity. Received:" + "highWaterMark must be a positive number or Infinity. Received:", ); } @@ -18,7 +18,7 @@ unitTest(function streamReadableHwmError() { new ReadableStream<number>( undefined, // eslint-disable-next-line @typescript-eslint/no-explicit-any - { highWaterMark: Symbol("hwk") as any } + { highWaterMark: Symbol("hwk") as any }, ); }, TypeError); }); @@ -31,11 +31,11 @@ unitTest(function streamWriteableHwmError() { () => { new WritableStream( undefined, - new CountQueuingStrategy({ highWaterMark }) + new CountQueuingStrategy({ highWaterMark }), ); }, RangeError, - "highWaterMark must be a positive number or Infinity. Received:" + "highWaterMark must be a positive number or Infinity. Received:", ); } @@ -43,7 +43,7 @@ unitTest(function streamWriteableHwmError() { new WritableStream( undefined, // eslint-disable-next-line @typescript-eslint/no-explicit-any - new CountQueuingStrategy({ highWaterMark: Symbol("hwmk") as any }) + new CountQueuingStrategy({ highWaterMark: Symbol("hwmk") as any }), ); }, TypeError); }); @@ -57,7 +57,7 @@ unitTest(function streamTransformHwmError() { new TransformStream(undefined, undefined, { highWaterMark }); }, RangeError, - "highWaterMark must be a positive number or Infinity. Received:" + "highWaterMark must be a positive number or Infinity. Received:", ); } @@ -66,7 +66,7 @@ unitTest(function streamTransformHwmError() { undefined, undefined, // eslint-disable-next-line @typescript-eslint/no-explicit-any - { highWaterMark: Symbol("hwmk") as any } + { highWaterMark: Symbol("hwmk") as any }, ); }, TypeError); }); diff --git a/cli/tests/unit/streams_piping_test.ts b/cli/tests/unit/streams_piping_test.ts index a947b3821..0696021cb 100644 --- a/cli/tests/unit/streams_piping_test.ts +++ b/cli/tests/unit/streams_piping_test.ts @@ -72,7 +72,7 @@ unitTest(async function streamPipeLotsOfChunks() { written.push("closed"); }, }, - new CountQueuingStrategy({ highWaterMark: CHUNKS }) + new CountQueuingStrategy({ highWaterMark: CHUNKS }), ); await rs.pipeTo(ws); @@ -101,7 +101,7 @@ for (const preventAbort of [true, false]) { throw new Error("pipeTo promise should be rejected"); }, (value) => - assertEquals(value, undefined, "rejection value should be undefined") + assertEquals(value, undefined, "rejection value should be undefined"), ); }); } @@ -125,7 +125,7 @@ for (const preventCancel of [true, false]) { throw new Error("pipeTo promise should be rejected"); }, (value) => - assertEquals(value, undefined, "rejection value should be undefined") + assertEquals(value, undefined, "rejection value should be undefined"), ); }); } diff --git a/cli/tests/unit/streams_transform_test.ts b/cli/tests/unit/streams_transform_test.ts index c8b4528e8..fa321daf2 100644 --- a/cli/tests/unit/streams_transform_test.ts +++ b/cli/tests/unit/streams_transform_test.ts @@ -17,7 +17,7 @@ function delay(seconds: number): Promise<void> { function readableStreamToArray<R>( readable: { getReader(): ReadableStreamDefaultReader<R> }, - reader?: ReadableStreamDefaultReader<R> + reader?: ReadableStreamDefaultReader<R>, ): Promise<R[]> { if (reader === undefined) { reader = readable.getReader(); @@ -58,21 +58,21 @@ unitTest(function transformStreamIntstancesHaveProperProperties() { assertEquals( typeof writableStream.get, "function", - "writable should have a getter" + "writable should have a getter", ); assertEquals( writableStream.set, undefined, - "writable should not have a setter" + "writable should not have a setter", ); assert(writableStream.configurable, "writable should be configurable"); assert( ts.writable instanceof WritableStream, - "writable is an instance of WritableStream" + "writable is an instance of WritableStream", ); assert( WritableStream.prototype.getWriter.call(ts.writable), - "writable should pass WritableStream brand check" + "writable should pass WritableStream brand check", ); const readableStream = Object.getOwnPropertyDescriptor(proto, "readable"); @@ -81,22 +81,22 @@ unitTest(function transformStreamIntstancesHaveProperProperties() { assertEquals( typeof readableStream.get, "function", - "readable should have a getter" + "readable should have a getter", ); assertEquals( readableStream.set, undefined, - "readable should not have a setter" + "readable should not have a setter", ); assert(readableStream.configurable, "readable should be configurable"); assert( ts.readable instanceof ReadableStream, - "readable is an instance of ReadableStream" + "readable is an instance of ReadableStream", ); assertNotEquals( ReadableStream.prototype.getReader.call(ts.readable), undefined, - "readable should pass ReadableStream brand check" + "readable should pass ReadableStream brand check", ); }); @@ -115,14 +115,14 @@ unitTest(async function transformStreamReadableCanReadOutOfWritable() { assertEquals( writer.desiredSize, 0, - "writer.desiredSize should be 0 after write()" + "writer.desiredSize should be 0 after write()", ); const result = await ts.readable.getReader().read(); assertEquals( result.value, "a", - "result from reading the readable is the same as was written to writable" + "result from reading the readable is the same as was written to writable", ); assert(!result.done, "stream should not be done"); @@ -148,7 +148,7 @@ unitTest(async function transformStreamCanReadWhatIsWritten() { assertEquals( result.value, "A", - "result from reading the readable is the transformation of what was written to writable" + "result from reading the readable is the transformation of what was written to writable", ); assert(!result.done, "stream should not be done"); }); @@ -174,7 +174,7 @@ unitTest(async function transformStreamCanReadBothChunks() { assertEquals( result1.value, "A", - "the first chunk read is the transformation of the single chunk written" + "the first chunk read is the transformation of the single chunk written", ); assert(!result1.done, "stream should not be done"); @@ -182,7 +182,7 @@ unitTest(async function transformStreamCanReadBothChunks() { assertEquals( result2.value, "A", - "the second chunk read is also the transformation of the single chunk written" + "the second chunk read is also the transformation of the single chunk written", ); assert(!result2.done, "stream should not be done"); }); @@ -205,7 +205,7 @@ unitTest(async function transformStreamCanReadWhatIsWritten() { assertEquals( result.value, "A", - "result from reading the readable is the transformation of what was written to writable" + "result from reading the readable is the transformation of what was written to writable", ); assert(!result.done, "stream should not be done"); }); @@ -216,7 +216,7 @@ unitTest(async function transformStreamAsyncReadMultipleChunks() { const ts = new TransformStream({ transform( chunk: string, - controller: TransformStreamDefaultController + controller: TransformStreamDefaultController, ): Promise<void> { delay(0).then(() => controller.enqueue(chunk.toUpperCase())); doSecondEnqueue = (): void => controller.enqueue(chunk.toUpperCase()); @@ -235,7 +235,7 @@ unitTest(async function transformStreamAsyncReadMultipleChunks() { assertEquals( result1.value, "A", - "the first chunk read is the transformation of the single chunk written" + "the first chunk read is the transformation of the single chunk written", ); assert(!result1.done, "stream should not be done"); doSecondEnqueue!(); @@ -244,7 +244,7 @@ unitTest(async function transformStreamAsyncReadMultipleChunks() { assertEquals( result2.value, "A", - "the second chunk read is also the transformation of the single chunk written" + "the second chunk read is also the transformation of the single chunk written", ); assert(!result2.done, "stream should not be done"); returnFromTransform!(); @@ -257,7 +257,7 @@ unitTest(function transformStreamClosingWriteClosesRead() { writer.close(); return Promise.all([writer.closed, ts.readable.getReader().closed]).then( - undefined + undefined, ); }); @@ -273,7 +273,7 @@ unitTest(async function transformStreamCloseWaitAwaitsTransforms() { }, }, undefined, - { highWaterMark: 1 } + { highWaterMark: 1 }, ); const writer = ts.writable.getWriter(); @@ -318,7 +318,7 @@ unitTest(async function transformStreamCloseWriteAfterSyncEnqueues() { assertEquals( chunks, ["x", "y"], - "both enqueued chunks can be read from the readable" + "both enqueued chunks can be read from the readable", ); }); @@ -347,7 +347,7 @@ unitTest(async function transformStreamWritableCloseAsyncAfterAsyncEnqueues() { assertEquals( chunks, ["x", "y"], - "both enqueued chunks can be read from the readable" + "both enqueued chunks can be read from the readable", ); }); @@ -382,7 +382,7 @@ unitTest(async function transformStreamTransformerMethodsCalledAsMethods() { assertEquals( chunks, ["start-suffix", "a-suffix", "flushed-suffix"], - "all enqueued chunks have suffixes" + "all enqueued chunks have suffixes", ); }); @@ -415,7 +415,7 @@ unitTest(async function transformStreamCallTransformSync() { }, }, undefined, - { highWaterMark: Infinity } + { highWaterMark: Infinity }, ); // transform() is only called synchronously when there is no backpressure and // all microtasks have run. @@ -432,7 +432,7 @@ unitTest(function transformStreamCloseWriteCloesesReadWithNoChunks() { writer.close(); return Promise.all([writer.closed, ts.readable.getReader().closed]).then( - undefined + undefined, ); }); @@ -459,7 +459,7 @@ unitTest(function transformStreamEnqueueThrowsAfterReadableCancel() { () => controller.enqueue(undefined), TypeError, undefined, - "enqueue should throw" + "enqueue should throw", ); return cancelPromise; }); @@ -510,7 +510,7 @@ unitTest(function transformStreamReadableTypeThrows() { () => new TransformStream({ readableType: "bytes" as any }), RangeError, undefined, - "constructor should throw" + "constructor should throw", ); }); @@ -520,7 +520,7 @@ unitTest(function transformStreamWirtableTypeThrows() { () => new TransformStream({ writableType: "bytes" as any }), RangeError, undefined, - "constructor should throw" + "constructor should throw", ); }); @@ -532,31 +532,31 @@ unitTest(function transformStreamSubclassable() { } assert( Object.getPrototypeOf(Subclass.prototype) === TransformStream.prototype, - "Subclass.prototype's prototype should be TransformStream.prototype" + "Subclass.prototype's prototype should be TransformStream.prototype", ); assert( Object.getPrototypeOf(Subclass) === TransformStream, - "Subclass's prototype should be TransformStream" + "Subclass's prototype should be TransformStream", ); const sub = new Subclass(); assert( sub instanceof TransformStream, - "Subclass object should be an instance of TransformStream" + "Subclass object should be an instance of TransformStream", ); assert( sub instanceof Subclass, - "Subclass object should be an instance of Subclass" + "Subclass object should be an instance of Subclass", ); const readableGetter = Object.getOwnPropertyDescriptor( TransformStream.prototype, - "readable" + "readable", )!.get; assert( readableGetter!.call(sub) === sub.readable, - "Subclass object should pass brand check" + "Subclass object should pass brand check", ); assert( sub.extraFunction(), - "extraFunction() should be present on Subclass object" + "extraFunction() should be present on Subclass object", ); }); diff --git a/cli/tests/unit/streams_writable_test.ts b/cli/tests/unit/streams_writable_test.ts index 54c1624af..a06b15c7e 100644 --- a/cli/tests/unit/streams_writable_test.ts +++ b/cli/tests/unit/streams_writable_test.ts @@ -79,7 +79,7 @@ unitTest(function getWriterOnErroredStream() { () => { writer.releaseLock(); ws.getWriter(); - } + }, ); }); @@ -97,7 +97,7 @@ unitTest(function closedAndReadyOnReleasedWriter() { assertEquals( closedRejection.name, "TypeError", - "closed promise should reject with a TypeError" + "closed promise should reject with a TypeError", ); return writer.ready.then( (v) => { @@ -107,10 +107,10 @@ unitTest(function closedAndReadyOnReleasedWriter() { assertEquals( readyRejection, closedRejection, - "ready promise should reject with the same error" - ) + "ready promise should reject with the same error", + ), ); - } + }, ); }); @@ -173,13 +173,13 @@ unitTest(function redundantReleaseLockIsNoOp() { assertEquals( undefined, writer1.releaseLock(), - "releaseLock() should return undefined" + "releaseLock() should return undefined", ); const writer2 = ws.getWriter(); assertEquals( undefined, writer1.releaseLock(), - "no-op releaseLock() should return undefined" + "no-op releaseLock() should return undefined", ); // Calling releaseLock() on writer1 should not interfere with writer2. If it did, then the ready promise would be // rejected. @@ -200,7 +200,7 @@ unitTest(function readyPromiseShouldFireBeforeReleaseLock() { assertEquals( events, ["ready", "closed"], - "ready promise should fire before closed promise" + "ready promise should fire before closed promise", ); // Stop the writer promise hanging around after the test has finished. return Promise.all([writerPromise, ws.abort()]).then(undefined); @@ -216,32 +216,32 @@ unitTest(function subclassingWritableStream() { } assert( Object.getPrototypeOf(Subclass.prototype) === WritableStream.prototype, - "Subclass.prototype's prototype should be WritableStream.prototype" + "Subclass.prototype's prototype should be WritableStream.prototype", ); assert( Object.getPrototypeOf(Subclass) === WritableStream, - "Subclass's prototype should be WritableStream" + "Subclass's prototype should be WritableStream", ); const sub = new Subclass(); assert( sub instanceof WritableStream, - "Subclass object should be an instance of WritableStream" + "Subclass object should be an instance of WritableStream", ); assert( sub instanceof Subclass, - "Subclass object should be an instance of Subclass" + "Subclass object should be an instance of Subclass", ); const lockedGetter = Object.getOwnPropertyDescriptor( WritableStream.prototype, - "locked" + "locked", )!.get!; assert( lockedGetter.call(sub) === sub.locked, - "Subclass object should pass brand check" + "Subclass object should pass brand check", ); assert( sub.extraFunction(), - "extraFunction() should be present on Subclass object" + "extraFunction() should be present on Subclass object", ); }); diff --git a/cli/tests/unit/symlink_test.ts b/cli/tests/unit/symlink_test.ts index 8949faa0c..b7babc88a 100644 --- a/cli/tests/unit/symlink_test.ts +++ b/cli/tests/unit/symlink_test.ts @@ -13,7 +13,7 @@ unitTest( const newNameInfoStat = Deno.statSync(newname); assert(newNameInfoLStat.isSymlink); assert(newNameInfoStat.isDirectory); - } + }, ); unitTest(function symlinkSyncPerm(): void { @@ -34,5 +34,5 @@ unitTest( const newNameInfoStat = Deno.statSync(newname); assert(newNameInfoLStat.isSymlink, "NOT SYMLINK"); assert(newNameInfoStat.isDirectory, "NOT DIRECTORY"); - } + }, ); diff --git a/cli/tests/unit/sync_test.ts b/cli/tests/unit/sync_test.ts index fd6acd858..d16ab60d4 100644 --- a/cli/tests/unit/sync_test.ts +++ b/cli/tests/unit/sync_test.ts @@ -16,7 +16,7 @@ unitTest( assertEquals(Deno.readFileSync(filename), data); Deno.close(file.rid); Deno.removeSync(filename); - } + }, ); unitTest( @@ -34,7 +34,7 @@ unitTest( assertEquals(await Deno.readFile(filename), data); Deno.close(file.rid); await Deno.remove(filename); - } + }, ); unitTest( @@ -52,7 +52,7 @@ unitTest( assertEquals(Deno.statSync(filename).size, size); Deno.close(file.rid); Deno.removeSync(filename); - } + }, ); unitTest( @@ -70,5 +70,5 @@ unitTest( assertEquals((await Deno.stat(filename)).size, size); Deno.close(file.rid); await Deno.remove(filename); - } + }, ); diff --git a/cli/tests/unit/test_util.ts b/cli/tests/unit/test_util.ts index 25da7a638..865b6e061 100644 --- a/cli/tests/unit/test_util.ts +++ b/cli/tests/unit/test_util.ts @@ -58,12 +58,12 @@ export async function getProcessPermissions(): Promise<Permissions> { export function permissionsMatch( processPerms: Permissions, - requiredPerms: Permissions + requiredPerms: Permissions, ): boolean { for (const permName in processPerms) { if ( processPerms[permName as keyof Permissions] !== - requiredPerms[permName as keyof Permissions] + requiredPerms[permName as keyof Permissions] ) { return false; } @@ -148,7 +148,7 @@ export function unitTest(fn: TestFunction): void; export function unitTest(options: UnitTestOptions, fn: TestFunction): void; export function unitTest( optionsOrFn: UnitTestOptions | TestFunction, - maybeFn?: TestFunction + maybeFn?: TestFunction, ): void { assert(optionsOrFn, "At least one argument is required"); @@ -166,7 +166,7 @@ export function unitTest( assert(maybeFn, "Missing test function definition"); assert( typeof maybeFn === "function", - "Second argument should be test function definition" + "Second argument should be test function definition", ); fn = maybeFn; name = fn.name; @@ -237,7 +237,7 @@ function serializeTestMessage(message: any): string { export async function reportToConn( conn: Deno.Conn, // eslint-disable-next-line @typescript-eslint/no-explicit-any - message: any + message: any, ): Promise<void> { const line = serializeTestMessage(message); const encodedMsg = encoder.encode(line + (message.end == null ? "\n" : "")); @@ -259,8 +259,8 @@ unitTest(function permissionsMatches(): void { plugin: false, hrtime: false, }, - normalizeTestPermissions({ read: true }) - ) + normalizeTestPermissions({ read: true }), + ), ); assert( @@ -274,8 +274,8 @@ unitTest(function permissionsMatches(): void { plugin: false, hrtime: false, }, - normalizeTestPermissions({}) - ) + normalizeTestPermissions({}), + ), ); assertEquals( @@ -289,9 +289,9 @@ unitTest(function permissionsMatches(): void { plugin: true, hrtime: true, }, - normalizeTestPermissions({ read: true }) + normalizeTestPermissions({ read: true }), ), - false + false, ); assertEquals( @@ -305,9 +305,9 @@ unitTest(function permissionsMatches(): void { plugin: false, hrtime: false, }, - normalizeTestPermissions({ read: true }) + normalizeTestPermissions({ read: true }), ), - false + false, ); assert( @@ -329,8 +329,8 @@ unitTest(function permissionsMatches(): void { run: true, plugin: true, hrtime: true, - } - ) + }, + ), ); }); @@ -348,28 +348,28 @@ unitTest( file!.endsWith(".ts") && !file!.endsWith("unit_tests.ts") && !file!.endsWith("test_util.ts") && - !file!.endsWith("unit_test_runner.ts") + !file!.endsWith("unit_test_runner.ts"), ); const unitTestsFile: Uint8Array = Deno.readFileSync( - "./cli/tests/unit/unit_tests.ts" + "./cli/tests/unit/unit_tests.ts", ); const importLines = new TextDecoder("utf-8") .decode(unitTestsFile) .split("\n") .filter((line) => line.startsWith("import")); const importedTestFiles = importLines.map( - (relativeFilePath) => relativeFilePath.match(/\/([^\/]+)";/)![1] + (relativeFilePath) => relativeFilePath.match(/\/([^\/]+)";/)![1], ); directoryTestFiles.forEach((dirFile) => { if (!importedTestFiles.includes(dirFile!)) { throw new Error( "cil/tests/unit/unit_tests.ts is missing import of test file: cli/js/" + - dirFile + dirFile, ); } }); - } + }, ); export function pathToAbsoluteFileUrl(path: string): URL { diff --git a/cli/tests/unit/testing_test.ts b/cli/tests/unit/testing_test.ts index 854e7161c..9ae547fb8 100644 --- a/cli/tests/unit/testing_test.ts +++ b/cli/tests/unit/testing_test.ts @@ -12,7 +12,7 @@ unitTest(function nameOfTestCaseCantBeEmpty(): void { Deno.test("", () => {}); }, TypeError, - "The test name can't be empty" + "The test name can't be empty", ); assertThrows( () => { @@ -22,6 +22,6 @@ unitTest(function nameOfTestCaseCantBeEmpty(): void { }); }, TypeError, - "The test name can't be empty" + "The test name can't be empty", ); }); diff --git a/cli/tests/unit/text_encoding_test.ts b/cli/tests/unit/text_encoding_test.ts index c87fc705d..e990f1284 100644 --- a/cli/tests/unit/text_encoding_test.ts +++ b/cli/tests/unit/text_encoding_test.ts @@ -58,7 +58,7 @@ unitTest(function btoaFailed(): void { }); unitTest(function textDecoder2(): void { - // prettier-ignore + // deno-fmt-ignore const fixture = new Uint8Array([ 0xf0, 0x9d, 0x93, 0xbd, 0xf0, 0x9d, 0x93, 0xae, @@ -70,7 +70,7 @@ unitTest(function textDecoder2(): void { }); unitTest(function textDecoderIgnoreBOM(): void { - // prettier-ignore + // deno-fmt-ignore const fixture = new Uint8Array([ 0xef, 0xbb, 0xbf, 0xf0, 0x9d, 0x93, 0xbd, @@ -83,7 +83,7 @@ unitTest(function textDecoderIgnoreBOM(): void { }); unitTest(function textDecoderNotBOM(): void { - // prettier-ignore + // deno-fmt-ignore const fixture = new Uint8Array([ 0xef, 0xbb, 0x89, 0xf0, 0x9d, 0x93, 0xbd, @@ -115,7 +115,7 @@ unitTest(function textDecoderErrorEncoding(): void { unitTest(function textEncoder(): void { const fixture = "𝓽𝓮𝔁𝓽"; const encoder = new TextEncoder(); - // prettier-ignore + // deno-fmt-ignore assertEquals(Array.from(encoder.encode(fixture)), [ 0xf0, 0x9d, 0x93, 0xbd, 0xf0, 0x9d, 0x93, 0xae, @@ -131,7 +131,7 @@ unitTest(function textEncodeInto(): void { const result = encoder.encodeInto(fixture, bytes); assertEquals(result.read, 4); assertEquals(result.written, 4); - // prettier-ignore + // deno-fmt-ignore assertEquals(Array.from(bytes), [ 0x74, 0x65, 0x78, 0x74, 0x00, ]); @@ -144,7 +144,7 @@ unitTest(function textEncodeInto2(): void { const result = encoder.encodeInto(fixture, bytes); assertEquals(result.read, 8); assertEquals(result.written, 16); - // prettier-ignore + // deno-fmt-ignore assertEquals(Array.from(bytes), [ 0xf0, 0x9d, 0x93, 0xbd, 0xf0, 0x9d, 0x93, 0xae, @@ -160,7 +160,7 @@ unitTest(function textEncodeInto3(): void { const result = encoder.encodeInto(fixture, bytes); assertEquals(result.read, 2); assertEquals(result.written, 4); - // prettier-ignore + // deno-fmt-ignore assertEquals(Array.from(bytes), [ 0xf0, 0x9d, 0x93, 0xbd, 0x00, ]); diff --git a/cli/tests/unit/timers_test.ts b/cli/tests/unit/timers_test.ts index 8a22173de..b7f6dd520 100644 --- a/cli/tests/unit/timers_test.ts +++ b/cli/tests/unit/timers_test.ts @@ -56,7 +56,7 @@ unitTest(async function timeoutArgs(): Promise<void> { 10, arg, arg.toString(), - [arg] + [arg], ); await promise; }); diff --git a/cli/tests/unit/tls_test.ts b/cli/tests/unit/tls_test.ts index 5a7391e78..ed7466a2c 100644 --- a/cli/tests/unit/tls_test.ts +++ b/cli/tests/unit/tls_test.ts @@ -52,7 +52,7 @@ unitTest( keyFile: "./non/existent/file", }); }, Deno.errors.NotFound); - } + }, ); unitTest({ perms: { net: true } }, function listenTLSNoReadPerm(): void { @@ -90,7 +90,7 @@ unitTest( keyFile: keyFilename, }); }, Error); - } + }, ); unitTest( @@ -115,7 +115,7 @@ unitTest( certFile: certFilename, }); }, Error); - } + }, ); unitTest( @@ -133,7 +133,7 @@ unitTest( }); const response = encoder.encode( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n", ); listener.accept().then( @@ -146,7 +146,7 @@ unitTest( conn.close(); resolvable.resolve(); }, 0); - } + }, ); const conn = await Deno.connectTls({ @@ -179,7 +179,7 @@ unitTest( conn.close(); listener.close(); await resolvable; - } + }, ); unitTest( @@ -230,5 +230,5 @@ unitTest( } conn.close(); - } + }, ); diff --git a/cli/tests/unit/truncate_test.ts b/cli/tests/unit/truncate_test.ts index 0a7e20ab1..db2cdc4be 100644 --- a/cli/tests/unit/truncate_test.ts +++ b/cli/tests/unit/truncate_test.ts @@ -25,7 +25,7 @@ unitTest( Deno.close(file.rid); Deno.removeSync(filename); - } + }, ); unitTest( @@ -47,7 +47,7 @@ unitTest( Deno.close(file.rid); await Deno.remove(filename); - } + }, ); unitTest( @@ -62,7 +62,7 @@ unitTest( Deno.truncateSync(filename, -5); assertEquals(Deno.readFileSync(filename).byteLength, 0); Deno.removeSync(filename); - } + }, ); unitTest( @@ -77,7 +77,7 @@ unitTest( await Deno.truncate(filename, -5); assertEquals((await Deno.readFile(filename)).byteLength, 0); await Deno.remove(filename); - } + }, ); unitTest({ perms: { write: false } }, function truncateSyncPerm(): void { diff --git a/cli/tests/unit/umask_test.ts b/cli/tests/unit/umask_test.ts index bfac65d52..6fe51254d 100644 --- a/cli/tests/unit/umask_test.ts +++ b/cli/tests/unit/umask_test.ts @@ -11,5 +11,5 @@ unitTest( const finalMask = Deno.umask(); assertEquals(newMask, 0o020); assertEquals(finalMask, prevMask); - } + }, ); diff --git a/cli/tests/unit/unit_test_runner.ts b/cli/tests/unit/unit_test_runner.ts index b2e872200..815a501f2 100755 --- a/cli/tests/unit/unit_test_runner.ts +++ b/cli/tests/unit/unit_test_runner.ts @@ -42,7 +42,7 @@ const PERMISSIONS: Deno.PermissionName[] = [ * Take a list of permissions and revoke missing permissions. */ async function dropWorkerPermissions( - requiredPermissions: Deno.PermissionName[] + requiredPermissions: Deno.PermissionName[], ): Promise<void> { const permsToDrop = PERMISSIONS.filter((p): boolean => { return !requiredPermissions.includes(p); @@ -56,7 +56,7 @@ async function dropWorkerPermissions( async function workerRunnerMain( addrStr: string, permsStr: string, - filter?: string + filter?: string, ): Promise<void> { const [hostname, port] = addrStr.split(":"); const addr = { hostname, port: Number(port) }; @@ -84,7 +84,7 @@ function spawnWorkerRunner( verbose: boolean, addr: string, perms: Permissions, - filter?: string + filter?: string, ): Deno.Process { // run subsequent tests using same deno executable const permStr = Object.keys(perms) @@ -126,7 +126,7 @@ async function runTestsForPermissionSet( addrStr: string, verbose: boolean, perms: Permissions, - filter?: string + filter?: string, ): Promise<PermissionSetTestResult> { const permsFmt = fmtPerms(perms); console.log(`Running tests for: ${permsFmt}`); @@ -165,7 +165,7 @@ async function runTestsForPermissionSet( const workerStatus = await workerProcess.status(); if (!workerStatus.success) { throw new Error( - `Worker runner exited with status code: ${workerStatus.code}` + `Worker runner exited with status code: ${workerStatus.code}`, ); } @@ -183,11 +183,11 @@ async function runTestsForPermissionSet( async function masterRunnerMain( verbose: boolean, - filter?: string + filter?: string, ): Promise<void> { console.log( "Discovered permission combinations for tests:", - permissionCombinations.size + permissionCombinations.size, ); for (const perms of permissionCombinations.values()) { @@ -205,7 +205,7 @@ async function masterRunnerMain( addrStr, verbose, perms, - filter + filter, ); testResults.add(result); } @@ -230,7 +230,7 @@ async function masterRunnerMain( if (REGISTERED_UNIT_TESTS.find(({ only }) => only)) { console.error( - `\n${colors.red("FAILED")} because the "only" option was used` + `\n${colors.red("FAILED")} because the "only" option was used`, ); Deno.exit(1); } diff --git a/cli/tests/unit/url_search_params_test.ts b/cli/tests/unit/url_search_params_test.ts index 227deeda7..6965fe128 100644 --- a/cli/tests/unit/url_search_params_test.ts +++ b/cli/tests/unit/url_search_params_test.ts @@ -6,7 +6,7 @@ unitTest(function urlSearchParamsInitString(): void { const searchParams = new URLSearchParams(init); assert( init === searchParams.toString(), - "The init query string does not match" + "The init query string does not match", ); }); @@ -243,7 +243,7 @@ unitTest( }; const params1 = new URLSearchParams((params as unknown) as string[][]); assertEquals(params1.get("1"), "2"); - } + }, ); // If a class extends URLSearchParams, override one method should not change another's behavior. @@ -261,7 +261,7 @@ unitTest( new CustomSearchParams(new CustomSearchParams({ foo: "bar" })); new CustomSearchParams().set("foo", "bar"); assertEquals(overridedAppendCalled, 0); - } + }, ); unitTest(function urlSearchParamsOverridingEntriesNotChangeForEach(): void { diff --git a/cli/tests/unit/url_test.ts b/cli/tests/unit/url_test.ts index 37d92089b..15833633a 100644 --- a/cli/tests/unit/url_test.ts +++ b/cli/tests/unit/url_test.ts @@ -3,14 +3,14 @@ import { unitTest, assert, assertEquals, assertThrows } from "./test_util.ts"; unitTest(function urlParsing(): void { const url = new URL( - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); assertEquals(url.hash, "#qat"); assertEquals(url.host, "baz.qat:8000"); assertEquals(url.hostname, "baz.qat"); assertEquals( url.href, - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); assertEquals(url.origin, "https://baz.qat:8000"); assertEquals(url.password, "bar"); @@ -23,7 +23,7 @@ unitTest(function urlParsing(): void { assertEquals(url.username, "foo"); assertEquals( String(url), - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); }); @@ -90,32 +90,32 @@ unitTest(function urlPortParsing(): void { unitTest(function urlModifications(): void { const url = new URL( - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); url.hash = ""; assertEquals( url.href, - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12", ); url.host = "qat.baz:8080"; assertEquals( url.href, - "https://foo:bar@qat.baz:8080/qux/quux?foo=bar&baz=12" + "https://foo:bar@qat.baz:8080/qux/quux?foo=bar&baz=12", ); url.hostname = "foo.bar"; assertEquals( url.href, - "https://foo:bar@foo.bar:8080/qux/quux?foo=bar&baz=12" + "https://foo:bar@foo.bar:8080/qux/quux?foo=bar&baz=12", ); url.password = "qux"; assertEquals( url.href, - "https://foo:qux@foo.bar:8080/qux/quux?foo=bar&baz=12" + "https://foo:qux@foo.bar:8080/qux/quux?foo=bar&baz=12", ); url.pathname = "/foo/bar%qat"; assertEquals( url.href, - "https://foo:qux@foo.bar:8080/foo/bar%qat?foo=bar&baz=12" + "https://foo:qux@foo.bar:8080/foo/bar%qat?foo=bar&baz=12", ); url.port = ""; assertEquals(url.href, "https://foo:qux@foo.bar/foo/bar%qat?foo=bar&baz=12"); @@ -127,19 +127,19 @@ unitTest(function urlModifications(): void { url.username = "foo@bar"; assertEquals( url.href, - "http://foo%40bar:qux@foo.bar/foo/bar%qat?foo=bar&foo=baz" + "http://foo%40bar:qux@foo.bar/foo/bar%qat?foo=bar&foo=baz", ); url.searchParams.set("bar", "qat"); assertEquals( url.href, - "http://foo%40bar:qux@foo.bar/foo/bar%qat?foo=bar&foo=baz&bar=qat" + "http://foo%40bar:qux@foo.bar/foo/bar%qat?foo=bar&foo=baz&bar=qat", ); url.searchParams.delete("foo"); assertEquals(url.href, "http://foo%40bar:qux@foo.bar/foo/bar%qat?bar=qat"); url.searchParams.append("foo", "bar"); assertEquals( url.href, - "http://foo%40bar:qux@foo.bar/foo/bar%qat?bar=qat&foo=bar" + "http://foo%40bar:qux@foo.bar/foo/bar%qat?bar=qat&foo=bar", ); }); @@ -182,7 +182,7 @@ unitTest(function urlModifyHash(): void { unitTest(function urlSearchParamsReuse(): void { const url = new URL( - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); const sp = url.searchParams; url.host = "baz.qat"; @@ -191,11 +191,11 @@ unitTest(function urlSearchParamsReuse(): void { unitTest(function urlBackSlashes(): void { const url = new URL( - "https:\\\\foo:bar@baz.qat:8000\\qux\\quux?foo=bar&baz=12#qat" + "https:\\\\foo:bar@baz.qat:8000\\qux\\quux?foo=bar&baz=12#qat", ); assertEquals( url.href, - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); }); @@ -221,7 +221,7 @@ unitTest(function urlRequireHost(): void { unitTest(function urlDriveLetter() { assertEquals( new URL("file:///C:").href, - Deno.build.os == "windows" ? "file:///C:/" : "file:///C:" + Deno.build.os == "windows" ? "file:///C:/" : "file:///C:", ); assertEquals(new URL("http://example.com/C:").href, "http://example.com/C:"); }); @@ -229,15 +229,15 @@ unitTest(function urlDriveLetter() { unitTest(function urlUncHostname() { assertEquals( new URL("file:////").href, - Deno.build.os == "windows" ? "file:///" : "file:////" + Deno.build.os == "windows" ? "file:///" : "file:////", ); assertEquals( new URL("file:////server").href, - Deno.build.os == "windows" ? "file://server/" : "file:////server" + Deno.build.os == "windows" ? "file://server/" : "file:////server", ); assertEquals( new URL("file:////server/file").href, - Deno.build.os == "windows" ? "file://server/file" : "file:////server/file" + Deno.build.os == "windows" ? "file://server/file" : "file:////server/file", ); }); @@ -259,39 +259,39 @@ unitTest(function urlTrim() { unitTest(function urlEncoding() { assertEquals( new URL("https://a !$&*()=,;+'\"@example.com").username, - "a%20!$&*()%3D,%3B+%27%22" + "a%20!$&*()%3D,%3B+%27%22", ); assertEquals( new URL("https://:a !$&*()=,;+'\"@example.com").password, - "a%20!$&*()%3D,%3B+%27%22" + "a%20!$&*()%3D,%3B+%27%22", ); assertEquals(new URL("abcde://mañana/c?d#e").hostname, "ma%C3%B1ana"); // https://url.spec.whatwg.org/#idna assertEquals(new URL("https://mañana/c?d#e").hostname, "xn--maana-pta"); assertEquals( new URL("https://example.com/a ~!@$&*()=:/,;+'\"\\").pathname, - "/a%20~!@$&*()=:/,;+'%22/" + "/a%20~!@$&*()=:/,;+'%22/", ); assertEquals( new URL("https://example.com?a ~!@$&*()=:/,;?+'\"\\").search, - "?a%20~!@$&*()=:/,;?+%27%22\\" + "?a%20~!@$&*()=:/,;?+%27%22\\", ); assertEquals( new URL("https://example.com#a ~!@#$&*()=:/,;?+'\"\\").hash, - "#a%20~!@#$&*()=:/,;?+'%22\\" + "#a%20~!@#$&*()=:/,;?+'%22\\", ); }); unitTest(function urlBaseURL(): void { const base = new URL( - "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); const url = new URL("/foo/bar?baz=foo#qux", base); assertEquals(url.href, "https://foo:bar@baz.qat:8000/foo/bar?baz=foo#qux"); assertEquals( new URL("D", "https://foo.bar/path/a/b/c/d").href, - "https://foo.bar/path/a/b/c/D" + "https://foo.bar/path/a/b/c/D", ); assertEquals(new URL("D", "https://foo.bar").href, "https://foo.bar/D"); @@ -299,14 +299,14 @@ unitTest(function urlBaseURL(): void { assertEquals( new URL("/d", "https://foo.bar/path/a/b/c/d").href, - "https://foo.bar/d" + "https://foo.bar/d", ); }); unitTest(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" + "https://foo:bar@baz.qat:8000/qux/quux?foo=bar&baz=12#qat", ); assertEquals(url.href, "https://foo:bar@baz.qat:8000/foo/bar?baz=foo#qux"); }); @@ -324,19 +324,19 @@ unitTest(function urlRelativeWithBase(): void { unitTest(function urlDriveLetterBase() { assertEquals( new URL("/b", "file:///C:/a/b").href, - Deno.build.os == "windows" ? "file:///C:/b" : "file:///b" + Deno.build.os == "windows" ? "file:///C:/b" : "file:///b", ); assertEquals( new URL("D:", "file:///C:/a/b").href, - Deno.build.os == "windows" ? "file:///D:/" : "file:///C:/a/D:" + Deno.build.os == "windows" ? "file:///D:/" : "file:///C:/a/D:", ); assertEquals( new URL("/D:", "file:///C:/a/b").href, - Deno.build.os == "windows" ? "file:///D:/" : "file:///D:" + Deno.build.os == "windows" ? "file:///D:/" : "file:///D:", ); assertEquals( new URL("D:/b", "file:///C:/a/b").href, - Deno.build.os == "windows" ? "file:///D:/b" : "file:///C:/a/D:/b" + Deno.build.os == "windows" ? "file:///D:/b" : "file:///C:/a/D:/b", ); }); @@ -377,9 +377,9 @@ unitTest( const url = new URL("http://example.com/?"); assertEquals( Deno.inspect(url), - 'URL { href: "http://example.com/?", origin: "http://example.com", protocol: "http:", username: "", password: "", host: "example.com", hostname: "example.com", port: "", pathname: "/", hash: "", search: "?" }' + 'URL { href: "http://example.com/?", origin: "http://example.com", protocol: "http:", username: "", password: "", host: "example.com", hostname: "example.com", port: "", pathname: "/", hash: "", search: "?" }', ); - } + }, ); unitTest(function protocolNotHttpOrFile() { @@ -418,7 +418,7 @@ unitTest(function throwForInvalidSchemeConstructor(): void { assertThrows( () => new URL("invalid_scheme://baz.qat"), TypeError, - "Invalid URL." + "Invalid URL.", ); }); diff --git a/cli/tests/unit/utime_test.ts b/cli/tests/unit/utime_test.ts index 7f54349e0..cc68e90cd 100644 --- a/cli/tests/unit/utime_test.ts +++ b/cli/tests/unit/utime_test.ts @@ -29,7 +29,7 @@ unitTest( const fileInfo = Deno.statSync(filename); assertFuzzyTimestampEquals(fileInfo.atime, new Date(atime * 1000)); assertFuzzyTimestampEquals(fileInfo.mtime, new Date(mtime * 1000)); - } + }, ); unitTest( @@ -44,7 +44,7 @@ unitTest( const dirInfo = Deno.statSync(testDir); assertFuzzyTimestampEquals(dirInfo.atime, new Date(atime * 1000)); assertFuzzyTimestampEquals(dirInfo.mtime, new Date(mtime * 1000)); - } + }, ); unitTest( @@ -59,7 +59,7 @@ unitTest( const dirInfo = Deno.statSync(testDir); assertFuzzyTimestampEquals(dirInfo.atime, atime); assertFuzzyTimestampEquals(dirInfo.mtime, mtime); - } + }, ); unitTest( @@ -77,7 +77,7 @@ unitTest( const fileInfo = Deno.statSync(filename); assertFuzzyTimestampEquals(fileInfo.atime, atime); assertFuzzyTimestampEquals(fileInfo.mtime, mtime); - } + }, ); unitTest( @@ -94,7 +94,7 @@ unitTest( const dirInfo = Deno.statSync(testDir); assertFuzzyTimestampEquals(dirInfo.atime, new Date(atime * 1000)); assertFuzzyTimestampEquals(dirInfo.mtime, new Date(mtime * 1000)); - } + }, ); unitTest( @@ -106,7 +106,7 @@ unitTest( assertThrows(() => { Deno.utimeSync("/baddir", atime, mtime); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -118,7 +118,7 @@ unitTest( assertThrows(() => { Deno.utimeSync("/some_dir", atime, mtime); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -137,7 +137,7 @@ unitTest( const fileInfo = Deno.statSync(filename); assertFuzzyTimestampEquals(fileInfo.atime, new Date(atime * 1000)); assertFuzzyTimestampEquals(fileInfo.mtime, new Date(mtime * 1000)); - } + }, ); unitTest( @@ -152,7 +152,7 @@ unitTest( const dirInfo = Deno.statSync(testDir); assertFuzzyTimestampEquals(dirInfo.atime, new Date(atime * 1000)); assertFuzzyTimestampEquals(dirInfo.mtime, new Date(mtime * 1000)); - } + }, ); unitTest( @@ -167,7 +167,7 @@ unitTest( const dirInfo = Deno.statSync(testDir); assertFuzzyTimestampEquals(dirInfo.atime, atime); assertFuzzyTimestampEquals(dirInfo.mtime, mtime); - } + }, ); unitTest( @@ -186,7 +186,7 @@ unitTest( const fileInfo = Deno.statSync(filename); assertFuzzyTimestampEquals(fileInfo.atime, atime); assertFuzzyTimestampEquals(fileInfo.mtime, mtime); - } + }, ); unitTest( @@ -198,7 +198,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.utime("/baddir", atime, mtime); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -210,5 +210,5 @@ unitTest( await assertThrowsAsync(async () => { await Deno.utime("/some_dir", atime, mtime); }, Deno.errors.PermissionDenied); - } + }, ); diff --git a/cli/tests/unit/write_file_test.ts b/cli/tests/unit/write_file_test.ts index bbe1daf38..a48333b9d 100644 --- a/cli/tests/unit/write_file_test.ts +++ b/cli/tests/unit/write_file_test.ts @@ -17,7 +17,7 @@ unitTest( const dec = new TextDecoder("utf-8"); const actual = dec.decode(dataRead); assertEquals("Hello", actual); - } + }, ); unitTest( @@ -27,7 +27,7 @@ unitTest( const data = enc.encode("Hello"); const tempDir = Deno.makeTempDirSync(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); Deno.writeFileSync(fileUrl, data); const dataRead = Deno.readFileSync(fileUrl); @@ -36,7 +36,7 @@ unitTest( assertEquals("Hello", actual); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest({ perms: { write: true } }, function writeFileSyncFail(): void { @@ -71,7 +71,7 @@ unitTest( Deno.writeFileSync(filename, data, { mode: 0o666 }); assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); } - } + }, ); unitTest( @@ -92,7 +92,7 @@ unitTest( const dec = new TextDecoder("utf-8"); const actual = dec.decode(dataRead); assertEquals("Hello", actual); - } + }, ); unitTest( @@ -117,7 +117,7 @@ unitTest( dataRead = Deno.readFileSync(filename); actual = dec.decode(dataRead); assertEquals("Hello", actual); - } + }, ); unitTest( @@ -131,7 +131,7 @@ unitTest( const dec = new TextDecoder("utf-8"); const actual = dec.decode(dataRead); assertEquals("Hello", actual); - } + }, ); unitTest( @@ -141,7 +141,7 @@ unitTest( const data = enc.encode("Hello"); const tempDir = await Deno.makeTempDir(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); await Deno.writeFile(fileUrl, data); const dataRead = Deno.readFileSync(fileUrl); @@ -150,7 +150,7 @@ unitTest( assertEquals("Hello", actual); Deno.removeSync(tempDir, { recursive: true }); - } + }, ); unitTest( @@ -163,7 +163,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.writeFile(filename, data); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -176,7 +176,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.writeFile(filename, data); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -191,7 +191,7 @@ unitTest( await Deno.writeFile(filename, data, { mode: 0o666 }); assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); } - } + }, ); unitTest( @@ -212,7 +212,7 @@ unitTest( const dec = new TextDecoder("utf-8"); const actual = dec.decode(dataRead); assertEquals("Hello", actual); - } + }, ); unitTest( @@ -237,5 +237,5 @@ unitTest( dataRead = Deno.readFileSync(filename); actual = dec.decode(dataRead); assertEquals("Hello", actual); - } + }, ); diff --git a/cli/tests/unit/write_text_file_test.ts b/cli/tests/unit/write_text_file_test.ts index 57e78b860..42c72de7a 100644 --- a/cli/tests/unit/write_text_file_test.ts +++ b/cli/tests/unit/write_text_file_test.ts @@ -13,7 +13,7 @@ unitTest( Deno.writeTextFileSync(filename, "Hello"); const dataRead = Deno.readTextFileSync(filename); assertEquals("Hello", dataRead); - } + }, ); unitTest( @@ -21,14 +21,14 @@ unitTest( function writeTextFileSyncByUrl(): void { const tempDir = Deno.makeTempDirSync(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); Deno.writeTextFileSync(fileUrl, "Hello"); const dataRead = Deno.readTextFileSync(fileUrl); assertEquals("Hello", dataRead); Deno.removeSync(fileUrl, { recursive: true }); - } + }, ); unitTest({ perms: { write: true } }, function writeTextFileSyncFail(): void { @@ -58,7 +58,7 @@ unitTest( Deno.writeTextFileSync(filename, data, { mode: 0o666 }); assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); } - } + }, ); unitTest( @@ -80,7 +80,7 @@ unitTest( Deno.writeTextFileSync(filename, data, { create: true }); Deno.writeTextFileSync(filename, data, { create: false }); assertEquals("Hello", Deno.readTextFileSync(filename)); - } + }, ); unitTest( @@ -97,7 +97,7 @@ unitTest( // append not set should also overwrite Deno.writeTextFileSync(filename, data); assertEquals("Hello", Deno.readTextFileSync(filename)); - } + }, ); unitTest( @@ -107,7 +107,7 @@ unitTest( await Deno.writeTextFile(filename, "Hello"); const dataRead = Deno.readTextFileSync(filename); assertEquals("Hello", dataRead); - } + }, ); unitTest( @@ -115,14 +115,14 @@ unitTest( async function writeTextFileByUrl(): Promise<void> { const tempDir = Deno.makeTempDirSync(); const fileUrl = new URL( - `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt` + `file://${Deno.build.os === "windows" ? "/" : ""}${tempDir}/test.txt`, ); await Deno.writeTextFile(fileUrl, "Hello"); const dataRead = Deno.readTextFileSync(fileUrl); assertEquals("Hello", dataRead); Deno.removeSync(fileUrl, { recursive: true }); - } + }, ); unitTest( @@ -133,7 +133,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.writeTextFile(filename, "Hello"); }, Deno.errors.NotFound); - } + }, ); unitTest( @@ -144,7 +144,7 @@ unitTest( await assertThrowsAsync(async () => { await Deno.writeTextFile(filename, "Hello"); }, Deno.errors.PermissionDenied); - } + }, ); unitTest( @@ -158,7 +158,7 @@ unitTest( await Deno.writeTextFile(filename, data, { mode: 0o666 }); assertEquals(Deno.statSync(filename).mode! & 0o777, 0o666); } - } + }, ); unitTest( @@ -180,7 +180,7 @@ unitTest( await Deno.writeTextFile(filename, data, { create: true }); await Deno.writeTextFile(filename, data, { create: false }); assertEquals("Hello", Deno.readTextFileSync(filename)); - } + }, ); unitTest( @@ -197,5 +197,5 @@ unitTest( // append not set should also overwrite await Deno.writeTextFile(filename, data); assertEquals("Hello", Deno.readTextFileSync(filename)); - } + }, ); diff --git a/cli/tests/wasm.ts b/cli/tests/wasm.ts index 26ad7ba28..98da19d26 100644 --- a/cli/tests/wasm.ts +++ b/cli/tests/wasm.ts @@ -1,4 +1,4 @@ -// prettier-ignore +// deno-fmt-ignore const wasmCode = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 133, 128, 128, 128, 0, 1, 96, 0, 1, 127, 3, 130, 128, 128, 128, 0, 1, 0, 4, 132, 128, 128, 128, 0, 1, 112, 0, 0, diff --git a/cli/tests/wasm_async.js b/cli/tests/wasm_async.js index 98a178aad..837460ae9 100644 --- a/cli/tests/wasm_async.js +++ b/cli/tests/wasm_async.js @@ -7,7 +7,7 @@ // i32.add) // (export "add" (func $add)) // ) -// prettier-ignore +// deno-fmt-ignore const bytes = new Uint8Array([ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, diff --git a/cli/tests/workers_round_robin_bench.ts b/cli/tests/workers_round_robin_bench.ts index d7224b41d..90ebb0364 100644 --- a/cli/tests/workers_round_robin_bench.ts +++ b/cli/tests/workers_round_robin_bench.ts @@ -25,7 +25,7 @@ export function createResolvable<T>(): Resolvable<T> { function handleAsyncMsgFromWorker( promiseTable: Map<number, Resolvable<string>>, - msg: { cmdId: number; data: string } + msg: { cmdId: number; data: string }, ): void { const promise = promiseTable.get(msg.cmdId); if (promise === null) { @@ -39,7 +39,7 @@ async function main(): Promise<void> { for (let i = 1; i <= workerCount; ++i) { const worker = new Worker( new URL("subdir/bench_worker.ts", import.meta.url).href, - { type: "module" } + { type: "module" }, ); const promise = createResolvable<void>(); worker.onmessage = (e): void => { diff --git a/cli/tests/workers_startup_bench.ts b/cli/tests/workers_startup_bench.ts index a25dc8ff7..5213e24cd 100644 --- a/cli/tests/workers_startup_bench.ts +++ b/cli/tests/workers_startup_bench.ts @@ -6,7 +6,7 @@ async function bench(): Promise<void> { for (let i = 1; i <= workerCount; ++i) { const worker = new Worker( new URL("subdir/bench_worker.ts", import.meta.url).href, - { type: "module" } + { type: "module" }, ); const promise = new Promise((resolve): void => { worker.onmessage = (e): void => { diff --git a/cli/tests/workers_test.ts b/cli/tests/workers_test.ts index feab0f9c2..395b1da24 100644 --- a/cli/tests/workers_test.ts +++ b/cli/tests/workers_test.ts @@ -34,11 +34,11 @@ Deno.test({ const jsWorker = new Worker( new URL("subdir/test_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); const tsWorker = new Worker( new URL("subdir/test_worker.ts", import.meta.url).href, - { type: "module", name: "tsWorker" } + { type: "module", name: "tsWorker" }, ); tsWorker.onmessage = (e): void => { @@ -70,7 +70,7 @@ Deno.test({ const nestedWorker = new Worker( new URL("subdir/nested_worker.js", import.meta.url).href, - { type: "module", name: "nested" } + { type: "module", name: "nested" }, ); nestedWorker.onmessage = (e): void => { @@ -90,7 +90,7 @@ Deno.test({ const promise = createResolvable(); const throwingWorker = new Worker( new URL("subdir/throwing_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -112,7 +112,7 @@ Deno.test({ const fetchingWorker = new Worker( new URL("subdir/fetching_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -139,7 +139,7 @@ Deno.test({ const busyWorker = new Worker( new URL("subdir/busy_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); let testResult = 0; @@ -172,7 +172,7 @@ Deno.test({ const racyWorker = new Worker( new URL("subdir/racy_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); racyWorker.onmessage = (e): void => { @@ -200,7 +200,7 @@ Deno.test({ const worker = new Worker( new URL("subdir/event_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); worker.onmessage = (_e: Event): void => { @@ -244,7 +244,7 @@ Deno.test({ const worker = new Worker( new URL("subdir/event_worker_scope.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); worker.onmessage = (e: MessageEvent): void => { @@ -273,11 +273,11 @@ Deno.test({ const regularWorker = new Worker( new URL("subdir/non_deno_worker.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); const denoWorker = new Worker( new URL("subdir/deno_worker.ts", import.meta.url).href, - { type: "module", deno: true } + { type: "module", deno: true }, ); regularWorker.onmessage = (e): void => { @@ -305,7 +305,7 @@ Deno.test({ const promise = createResolvable(); const w = new Worker( new URL("subdir/worker_crypto.js", import.meta.url).href, - { type: "module" } + { type: "module" }, ); w.onmessage = (e): void => { assertEquals(e.data, true); diff --git a/core/encode_decode_test.js b/core/encode_decode_test.js index 294144593..69e6e053b 100644 --- a/core/encode_decode_test.js +++ b/core/encode_decode_test.js @@ -11,20 +11,20 @@ function assertArrayEquals(a1, a2) { } function main() { - // prettier-ignore + // deno-fmt-ignore const fixture1 = [ 0xf0, 0x9d, 0x93, 0xbd, 0xf0, 0x9d, 0x93, 0xae, 0xf0, 0x9d, 0x94, 0x81, 0xf0, 0x9d, 0x93, 0xbd ]; - // prettier-ignore - const fixture2 = [ - 72, 101, 108, 108, - 111, 32, 239, 191, - 189, 239, 191, 189, - 32, 87, 111, 114, - 108, 100 + // deno-fmt-ignore + const fixture2 = [ + 72, 101, 108, 108, + 111, 32, 239, 191, + 189, 239, 191, 189, + 32, 87, 111, 114, + 108, 100 ]; const empty = Deno.core.encode(""); @@ -33,7 +33,7 @@ function main() { assertArrayEquals(Array.from(Deno.core.encode("𝓽𝓮𝔁𝓽")), fixture1); assertArrayEquals( Array.from(Deno.core.encode("Hello \udc12\ud834 World")), - fixture2 + fixture2, ); const emptyBuf = Deno.core.decode(new Uint8Array(0)); diff --git a/core/examples/http_bench.js b/core/examples/http_bench.js index a893dab40..eba9bb677 100644 --- a/core/examples/http_bench.js +++ b/core/examples/http_bench.js @@ -5,7 +5,7 @@ const requestBuf = new Uint8Array(64 * 1024); const responseBuf = new Uint8Array( "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" .split("") - .map((c) => c.charCodeAt(0)) + .map((c) => c.charCodeAt(0)), ); const promiseMap = new Map(); let nextPromiseId = 1; @@ -32,7 +32,7 @@ const scratch32 = new Int32Array(3); const scratchBytes = new Uint8Array( scratch32.buffer, scratch32.byteOffset, - scratch32.byteLength + scratch32.byteLength, ); assert(scratchBytes.byteLength === 3 * 4); diff --git a/deno_typescript/compiler_main.js b/deno_typescript/compiler_main.js index 847f3435f..a42f96860 100644 --- a/deno_typescript/compiler_main.js +++ b/deno_typescript/compiler_main.js @@ -52,7 +52,7 @@ function main(configText, rootNames) { // TS5009: Cannot find the common subdirectory path for the input files. if (code === 5009) return false; return true; - }) + }), ); const emitResult = program.emit(); @@ -60,7 +60,7 @@ function main(configText, rootNames) { dispatch( "op_set_emit_result", - Object.assign(emitResult, { tsVersion: ts.version }) + Object.assign(emitResult, { tsVersion: ts.version }), ); } @@ -176,7 +176,7 @@ class Host { fileName, languageVersion, _onError, - shouldCreateNewSourceFile + shouldCreateNewSourceFile, ) { assert(!shouldCreateNewSourceFile); // We haven't yet encountered this. @@ -204,7 +204,7 @@ class Host { const sourceFile = ts.createSourceFile( fileName, sourceCode, - languageVersion + languageVersion, ); sourceFile.moduleName = fileName; return sourceFile; @@ -222,7 +222,7 @@ class Host { data, _writeByteOrderMark, _onError = null, - sourceFiles = null + sourceFiles = null, ) { if (sourceFiles == null) { return; @@ -243,7 +243,7 @@ class Host { _path, _languageVersion, _onError, - _shouldCreateNewSourceFile + _shouldCreateNewSourceFile, ) { unreachable(); } @@ -301,14 +301,14 @@ class Host { function configure(configurationText) { const { config, error } = ts.parseConfigFileTextToJson( "tsconfig.json", - configurationText + configurationText, ); if (error) { return { options: {}, diagnostics: [error] }; } const { options, errors } = ts.convertCompilerOptionsFromJson( config.compilerOptions, - "" + "", ); return { options, diff --git a/deno_typescript/system_loader_es5.js b/deno_typescript/system_loader_es5.js index df2da2235..91bae136a 100644 --- a/deno_typescript/system_loader_es5.js +++ b/deno_typescript/system_loader_es5.js @@ -8,7 +8,7 @@ /* eslint-disable */ var System, __instantiate; (function () { - // prettier-ignore + // deno-fmt-ignore var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -18,7 +18,7 @@ var System, __instantiate; step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; - // prettier-ignore + // deno-fmt-ignore var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; @@ -75,11 +75,9 @@ var System, __instantiate; } return [ 2, - id in r - ? gExpA(id) - : Promise.resolve().then(function () { - return require(mid); - }), + id in r ? gExpA(id) : Promise.resolve().then(function () { + return require(mid); + }), ]; }); }); diff --git a/docs/contributing/style_guide.md b/docs/contributing/style_guide.md index 6c0e73b50..a54f29281 100644 --- a/docs/contributing/style_guide.md +++ b/docs/contributing/style_guide.md @@ -85,28 +85,23 @@ When designing function interfaces, stick to the following rules. there is only one, and it seems inconceivable that we would add more optional parameters in the future. -<!-- prettier-ignore-start --> -<!-- see https://github.com/prettier/prettier/issues/3679 --> - 3. The 'options' argument is the only argument that is a regular 'Object'. Other arguments can be objects, but they must be distinguishable from a 'plain' Object runtime, by having either: - - a distinguishing prototype (e.g. `Array`, `Map`, `Date`, `class MyThing`) - - a well-known symbol property (e.g. an iterable with `Symbol.iterator`). + - a distinguishing prototype (e.g. `Array`, `Map`, `Date`, `class MyThing`) + - a well-known symbol property (e.g. an iterable with `Symbol.iterator`). This allows the API to evolve in a backwards compatible way, even when the position of the options object changes. -<!-- prettier-ignore-end --> - ```ts // BAD: optional parameters not part of options object. (#2) export function resolve( hostname: string, family?: "ipv4" | "ipv6", - timeout?: number + timeout?: number, ): IPAddress[] {} // GOOD. @@ -116,7 +111,7 @@ export interface ResolveOptions { } export function resolve( hostname: string, - options: ResolveOptions = {} + options: ResolveOptions = {}, ): IPAddress[] {} ``` @@ -135,7 +130,7 @@ export interface RunShellOptions { } export function runShellWithEnv( cmdline: string, - options: RunShellOptions + options: RunShellOptions, ): string {} ``` @@ -145,7 +140,7 @@ export function renameSync( oldname: string, newname: string, replaceExisting?: boolean, - followLinks?: boolean + followLinks?: boolean, ) {} // GOOD. @@ -156,7 +151,7 @@ interface RenameOptions { export function renameSync( oldname: string, newname: string, - options: RenameOptions = {} + options: RenameOptions = {}, ) {} ``` @@ -167,7 +162,7 @@ export function pwrite( buffer: TypedArray, offset: number, length: number, - position: number + position: number, ) {} // BETTER. diff --git a/docs/getting_started/webassembly.md b/docs/getting_started/webassembly.md index ba8a52f7c..613be2fcd 100644 --- a/docs/getting_started/webassembly.md +++ b/docs/getting_started/webassembly.md @@ -2,7 +2,8 @@ Deno can execute [WebAssembly](https://webassembly.org/) binaries. -<!-- prettier-ignore-start --> +<!-- dprint-ignore --> + ```js const wasmCode = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 133, 128, 128, 128, 0, 1, 96, 0, 1, 127, @@ -16,4 +17,3 @@ const wasmModule = new WebAssembly.Module(wasmCode); const wasmInstance = new WebAssembly.Instance(wasmModule); console.log(wasmInstance.exports.main().toString()); ``` -<!-- prettier-ignore-end --> diff --git a/docs/introduction.md b/docs/introduction.md index cdc8c6cb5..738305885 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -14,8 +14,9 @@ It's built on V8, Rust, and Tokio. - Has built-in utilities like a dependency inspector (`deno info`) and a code formatter (`deno fmt`). - Has - [a set of reviewed (audited) standard modules](https://github.com/denoland/deno/tree/master/std) - that are guaranteed to work with Deno. + [a set of reviewed (audited) standard + modules](https://github.com/denoland/deno/tree/master/std) that are guaranteed + to work with Deno. - Scripts can be bundled into a single JavaScript file. ## Philosophy diff --git a/docs/linking_to_external_code/reloading_modules.md b/docs/linking_to_external_code/reloading_modules.md index 01300a5c3..136107a63 100644 --- a/docs/linking_to_external_code/reloading_modules.md +++ b/docs/linking_to_external_code/reloading_modules.md @@ -10,7 +10,6 @@ usage is described below: ```ts deno cache --reload my_module.ts - ``` ### To reload specific modules diff --git a/docs/runtime/compiler_apis.md b/docs/runtime/compiler_apis.md index c2d234836..31d0af2d1 100644 --- a/docs/runtime/compiler_apis.md +++ b/docs/runtime/compiler_apis.md @@ -48,7 +48,7 @@ could do on the command line. So you could do something like this: ```ts const [diagnostics, emitMap] = await Deno.compile( - "https://deno.land/std/examples/welcome.ts" + "https://deno.land/std/examples/welcome.ts", ); ``` @@ -95,7 +95,7 @@ could do on the command line. So you could do something like this: ```ts const [diagnostics, emit] = await Deno.bundle( - "https://deno.land/std/http/server.ts" + "https://deno.land/std/http/server.ts", ); ``` @@ -151,7 +151,7 @@ const [errors, emitted] = await Deno.compile( }, { lib: ["dom", "esnext"], - } + }, ); ``` @@ -191,7 +191,7 @@ const [errors, emitted] = await Deno.compile( }, { lib: ["dom", "esnext", "deno.ns"], - } + }, ); ``` diff --git a/docs/testing/assertions.md b/docs/testing/assertions.md index 93b73da96..b8874a0e9 100644 --- a/docs/testing/assertions.md +++ b/docs/testing/assertions.md @@ -150,7 +150,7 @@ Deno.test("Test Assert Throws", () => { throw new Error("Panic!"); }, Error, - "Panic!" + "Panic!", ); }); ``` @@ -168,7 +168,7 @@ Deno.test("Test Assert Throws Async", () => { }); }, Error, - "Panic! Threw Error" + "Panic! Threw Error", ); assertThrowsAsync( @@ -176,7 +176,7 @@ Deno.test("Test Assert Throws Async", () => { return Promise.reject(new Error("Panic! Reject Error")); }, Error, - "Panic! Reject Error" + "Panic! Reject Error", ); }); ``` diff --git a/docs/tools.md b/docs/tools.md index 5307a6a89..76f54e6bc 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -3,9 +3,6 @@ Deno provides some built in tooling that is useful when working with JavaScript and TypeScript: -<!-- prettier-ignore-start --> -<!-- prettier incorrectly moves the coming soon links to new lines --> - - [bundler (`deno bundle`)](./tools/bundler.md) - [debugger (`--inspect, --inspect-brk`)](./tools/debugger.md) - [dependency inspector (`deno info`)](./tools/dependency_inspector.md) @@ -13,5 +10,3 @@ and TypeScript: - [formatter (`deno fmt`)](./tools/formatter.md) - [test runner (`deno test`)](./testing.md) - [linter (`deno lint`)](./tools/linter.md) - -<!-- prettier-ignore-end --> diff --git a/docs/tools/formatter.md b/docs/tools/formatter.md index 16a5a9ab4..aedb6bdc9 100644 --- a/docs/tools/formatter.md +++ b/docs/tools/formatter.md @@ -16,8 +16,6 @@ cat file.ts | deno fmt - Ignore formatting code by preceding it with a `// deno-fmt-ignore` comment: -<!-- prettier-ignore-start --> - ```ts // deno-fmt-ignore export const identity = [ @@ -27,7 +25,5 @@ export const identity = [ ]; ``` -<!-- prettier-ignore-end --> - Or ignore an entire file by adding a `// deno-fmt-ignore-file` comment at the top of the file. diff --git a/docs/tools/script_installer.md b/docs/tools/script_installer.md index 5f388fc6d..68db10d61 100644 --- a/docs/tools/script_installer.md +++ b/docs/tools/script_installer.md @@ -66,6 +66,8 @@ idiom to specify the entry point in an executable script. Example: +<!-- dprint-ignore --> + ```ts // https://example.com/awesome/cli.ts async function myAwesomeCli(): Promise<void> { diff --git a/std/_util/assert_test.ts b/std/_util/assert_test.ts index 2c94f8bca..3509619c3 100644 --- a/std/_util/assert_test.ts +++ b/std/_util/assert_test.ts @@ -24,7 +24,7 @@ Deno.test({ assert(false, "Oops! Should be true"); }, DenoStdInternalError, - "Oops! Should be true" + "Oops! Should be true", ); }, }); diff --git a/std/archive/tar.ts b/std/archive/tar.ts index 8ec240764..5fcfedc0f 100644 --- a/std/archive/tar.ts +++ b/std/archive/tar.ts @@ -42,7 +42,7 @@ const initialChecksum = 8 * 32; async function readBlock( reader: Deno.Reader, - p: Uint8Array + p: Uint8Array, ): Promise<number | null> { let bytesRead = 0; while (bytesRead < p.length) { @@ -354,21 +354,21 @@ export class Tar { info = await Deno.stat(opts.filePath); } - const mode = - opts.fileMode || (info && info.mode) || parseInt("777", 8) & 0xfff, + const mode = opts.fileMode || (info && info.mode) || + parseInt("777", 8) & 0xfff, mtime = Math.floor( - opts.mtime ?? (info?.mtime ?? new Date()).valueOf() / 1000 + opts.mtime ?? (info?.mtime ?? new Date()).valueOf() / 1000, ), uid = opts.uid || 0, gid = opts.gid || 0; if (typeof opts.owner === "string" && opts.owner.length >= 32) { throw new Error( - "ustar format does not allow owner name length >= 32 bytes" + "ustar format does not allow owner name length >= 32 bytes", ); } if (typeof opts.group === "string" && opts.group.length >= 32) { throw new Error( - "ustar format does not allow group name length >= 32 bytes" + "ustar format does not allow group name length >= 32 bytes", ); } @@ -428,9 +428,9 @@ export class Tar { new Deno.Buffer( clean( recordSize - - (parseInt(tarData.fileSize, 8) % recordSize || recordSize) - ) - ) + (parseInt(tarData.fileSize, 8) % recordSize || recordSize), + ), + ), ); }); @@ -450,7 +450,7 @@ class TarEntry implements Reader { constructor( meta: TarMeta, header: TarHeader, - reader: Reader | (Reader & Deno.Seeker) + reader: Reader | (Reader & Deno.Seeker), ) { Object.assign(this, meta); this.#header = header; @@ -473,7 +473,7 @@ class TarEntry implements Reader { const bufSize = Math.min( // bufSize can't be greater than p.length nor bytes left in the entry p.length, - entryBytesLeft + entryBytesLeft, ); if (entryBytesLeft <= 0) return null; @@ -503,7 +503,7 @@ class TarEntry implements Reader { if (typeof (this.#reader as Seeker).seek === "function") { await (this.#reader as Seeker).seek( this.#entrySize - this.#read, - Deno.SeekMode.Current + Deno.SeekMode.Current, ); this.#read = this.#entrySize; } else { @@ -576,7 +576,7 @@ export class Untar { "fileMode", "mtime", "uid", - "gid" + "gid", ]).forEach((key): void => { const arr = trim(header[key]); if (arr.byteLength > 0) { @@ -589,7 +589,7 @@ export class Untar { if (arr.byteLength > 0) { meta[key] = decoder.decode(arr); } - } + }, ); meta.fileSize = parseInt(decoder.decode(header.fileSize), 8); diff --git a/std/archive/tar_test.ts b/std/archive/tar_test.ts index 69f1ec3f3..17dfe7745 100644 --- a/std/archive/tar_test.ts +++ b/std/archive/tar_test.ts @@ -212,7 +212,7 @@ Deno.test( reader.close(); await Deno.remove(outputFile); assertEquals(entries.length, 0); - } + }, ); Deno.test("untarAsyncIteratorFromFileReader", async function (): Promise<void> { @@ -299,7 +299,7 @@ Deno.test( assertEquals(entries.length, 0); } - } + }, ); Deno.test("untarLinuxGeneratedTar", async function (): Promise<void> { diff --git a/std/async/mux_async_iterator.ts b/std/async/mux_async_iterator.ts index ba6f22775..f9f110e5a 100644 --- a/std/async/mux_async_iterator.ts +++ b/std/async/mux_async_iterator.ts @@ -24,7 +24,7 @@ export class MuxAsyncIterator<T> implements AsyncIterable<T> { } private async callIteratorNext( - iterator: AsyncIterableIterator<T> + iterator: AsyncIterableIterator<T>, ): Promise<void> { try { const { value, done } = await iterator.next(); diff --git a/std/async/mux_async_iterator_test.ts b/std/async/mux_async_iterator_test.ts index 5ca28903b..7977e4f56 100644 --- a/std/async/mux_async_iterator_test.ts +++ b/std/async/mux_async_iterator_test.ts @@ -47,7 +47,7 @@ Deno.test({ } }, Error, - "something went wrong" + "something went wrong", ); }, }); diff --git a/std/bytes/README.md b/std/bytes/README.md index 77f3fdfc8..b1edac1e6 100644 --- a/std/bytes/README.md +++ b/std/bytes/README.md @@ -15,7 +15,7 @@ import { findIndex } from "https://deno.land/std/bytes/mod.ts"; findIndex( new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]), - new Uint8Array([0, 1, 2]) + new Uint8Array([0, 1, 2]), ); // => returns 2 @@ -30,7 +30,7 @@ import { findLastIndex } from "https://deno.land/std/bytes/mod.ts"; findLastIndex( new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]), - new Uint8Array([0, 1, 2]) + new Uint8Array([0, 1, 2]), ); // => returns 3 diff --git a/std/bytes/test.ts b/std/bytes/test.ts index 25af2a35b..6dffad17f 100644 --- a/std/bytes/test.ts +++ b/std/bytes/test.ts @@ -17,7 +17,7 @@ import { encode, decode } from "../encoding/utf8.ts"; Deno.test("[bytes] findIndex1", () => { const i = findIndex( new Uint8Array([1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 3]), - new Uint8Array([0, 1, 2]) + new Uint8Array([0, 1, 2]), ); assertEquals(i, 2); }); @@ -35,7 +35,7 @@ Deno.test("[bytes] findIndex3", () => { Deno.test("[bytes] findLastIndex1", () => { const i = findLastIndex( new Uint8Array([0, 1, 2, 0, 1, 2, 0, 1, 3]), - new Uint8Array([0, 1, 2]) + new Uint8Array([0, 1, 2]), ); assertEquals(i, 3); }); @@ -80,12 +80,12 @@ Deno.test("[bytes] repeat", () => { repeat(new TextEncoder().encode(input as string), count as number); }, Error, - errMsg as string + errMsg as string, ); } else { const newBytes = repeat( new TextEncoder().encode(input as string), - count as number + count as number, ); assertEquals(new TextDecoder().decode(newBytes), output); diff --git a/std/datetime/mod.ts b/std/datetime/mod.ts index 9665a92b2..fe6fe6b3c 100644 --- a/std/datetime/mod.ts +++ b/std/datetime/mod.ts @@ -71,7 +71,7 @@ export type DateTimeFormat = */ export function parseDateTime( datetimeStr: string, - format: DateTimeFormat + format: DateTimeFormat, ): Date { let m, d, y, ho, mi: string; let datePattern: RegExp; @@ -114,8 +114,7 @@ export function parseDateTime( */ export function dayOfYear(date: Date): number { const yearStart = new Date(date.getFullYear(), 0, 0); - const diff = - date.getTime() - + const diff = date.getTime() - yearStart.getTime() + (yearStart.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000; return Math.floor(diff / DAY); @@ -135,13 +134,12 @@ export function currentDayOfYear(): number { */ export function weekOfYear(date: Date): number { const workingDate = new Date( - Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) + Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()), ); const day = workingDate.getUTCDay(); - const nearestThursday = - workingDate.getUTCDate() + + const nearestThursday = workingDate.getUTCDate() + Day.Thu - (day === Day.Sun ? DAYS_PER_WEEK : day); @@ -236,21 +234,19 @@ export type DifferenceOptions = { export function difference( from: Date, to: Date, - options?: DifferenceOptions + options?: DifferenceOptions, ): DifferenceFormat { - const uniqueUnits = options?.units - ? [...new Set(options?.units)] - : [ - "miliseconds", - "seconds", - "minutes", - "hours", - "days", - "weeks", - "months", - "quarters", - "years", - ]; + const uniqueUnits = options?.units ? [...new Set(options?.units)] : [ + "miliseconds", + "seconds", + "minutes", + "hours", + "days", + "weeks", + "months", + "quarters", + "years", + ]; const bigger = Math.max(from.getTime(), to.getTime()); const smaller = Math.min(from.getTime(), to.getTime()); @@ -285,14 +281,14 @@ export function difference( differences.quarters = Math.floor( (typeof differences.months !== "undefined" && differences.months / 4) || - calculateMonthsDifference(bigger, smaller) / 4 + calculateMonthsDifference(bigger, smaller) / 4, ); break; case "years": differences.years = Math.floor( (typeof differences.months !== "undefined" && differences.months / 12) || - calculateMonthsDifference(bigger, smaller) / 12 + calculateMonthsDifference(bigger, smaller) / 12, ); break; } @@ -309,10 +305,13 @@ function calculateMonthsDifference(bigger: number, smaller: number): number { const calendarDiffrences = Math.abs(yearsDiff * 12 + monthsDiff); const compareResult = biggerDate > smallerDate ? 1 : -1; biggerDate.setMonth( - biggerDate.getMonth() - compareResult * calendarDiffrences + biggerDate.getMonth() - compareResult * calendarDiffrences, ); - const isLastMonthNotFull = - biggerDate > smallerDate ? 1 : -1 === -compareResult ? 1 : 0; + const isLastMonthNotFull = biggerDate > smallerDate + ? 1 + : -1 === -compareResult + ? 1 + : 0; const months = compareResult * (calendarDiffrences - isLastMonthNotFull); return months === 0 ? 0 : months; } diff --git a/std/datetime/test.ts b/std/datetime/test.ts index a223abce2..d5dccee73 100644 --- a/std/datetime/test.ts +++ b/std/datetime/test.ts @@ -7,27 +7,27 @@ Deno.test({ fn: () => { assertEquals( datetime.parseDateTime("01-03-2019 16:30", "mm-dd-yyyy hh:mm"), - new Date(2019, 0, 3, 16, 30) + new Date(2019, 0, 3, 16, 30), ); assertEquals( datetime.parseDateTime("03-01-2019 16:31", "dd-mm-yyyy hh:mm"), - new Date(2019, 0, 3, 16, 31) + new Date(2019, 0, 3, 16, 31), ); assertEquals( datetime.parseDateTime("2019-01-03 16:32", "yyyy-mm-dd hh:mm"), - new Date(2019, 0, 3, 16, 32) + new Date(2019, 0, 3, 16, 32), ); assertEquals( datetime.parseDateTime("16:33 01-03-2019", "hh:mm mm-dd-yyyy"), - new Date(2019, 0, 3, 16, 33) + new Date(2019, 0, 3, 16, 33), ); assertEquals( datetime.parseDateTime("16:34 03-01-2019", "hh:mm dd-mm-yyyy"), - new Date(2019, 0, 3, 16, 34) + new Date(2019, 0, 3, 16, 34), ); assertEquals( datetime.parseDateTime("16:35 2019-01-03", "hh:mm yyyy-mm-dd"), - new Date(2019, 0, 3, 16, 35) + new Date(2019, 0, 3, 16, 35), ); }, }); @@ -41,7 +41,7 @@ Deno.test({ (datetime as any).parseDateTime("2019-01-01 00:00", "x-y-z"); }, Error, - "Invalid datetime format!" + "Invalid datetime format!", ); }, }); @@ -51,15 +51,15 @@ Deno.test({ fn: () => { assertEquals( datetime.parseDate("01-03-2019", "mm-dd-yyyy"), - new Date(2019, 0, 3) + new Date(2019, 0, 3), ); assertEquals( datetime.parseDate("03-01-2019", "dd-mm-yyyy"), - new Date(2019, 0, 3) + new Date(2019, 0, 3), ); assertEquals( datetime.parseDate("2019-01-03", "yyyy-mm-dd"), - new Date(2019, 0, 3) + new Date(2019, 0, 3), ); }, }); @@ -73,7 +73,7 @@ Deno.test({ (datetime as any).parseDate("2019-01-01", "x-y-z"); }, Error, - "Invalid date format!" + "Invalid date format!", ); }, }); diff --git a/std/encoding/README.md b/std/encoding/README.md index 588661269..0ec5f4e72 100644 --- a/std/encoding/README.md +++ b/std/encoding/README.md @@ -84,7 +84,7 @@ const string = "a,b,c\nd,e,f"; console.log( await parse(string, { header: false, - }) + }), ); // output: // [["a", "b", "c"], ["d", "e", "f"]] diff --git a/std/encoding/_yaml/dumper/dumper.ts b/std/encoding/_yaml/dumper/dumper.ts index 2b23d4758..e1f1a142a 100644 --- a/std/encoding/_yaml/dumper/dumper.ts +++ b/std/encoding/_yaml/dumper/dumper.ts @@ -92,7 +92,7 @@ function encodeHex(character: number): string { length = 8; } else { throw new YAMLError( - "code point within a string may not be greater than 0xFFFFFFFF" + "code point within a string may not be greater than 0xFFFFFFFF", ); } @@ -242,14 +242,13 @@ function chooseScalarStyle( singleLineOnly: boolean, indentPerLevel: number, lineWidth: number, - testAmbiguousType: (...args: Any[]) => Any + testAmbiguousType: (...args: Any[]) => Any, ): number { const shouldTrackWidth = lineWidth !== -1; let hasLineBreak = false, hasFoldableLine = false, // only checked if shouldTrackWidth previousLineBreak = -1, // count the first line correctly - plain = - isPlainSafeFirst(string.charCodeAt(0)) && + plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1)); let char: number, i: number; @@ -271,8 +270,7 @@ function chooseScalarStyle( hasLineBreak = true; // Check if any line can be folded. if (shouldTrackWidth) { - hasFoldableLine = - hasFoldableLine || + hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " "); @@ -284,8 +282,7 @@ function chooseScalarStyle( plain = plain && isPlainSafe(char); } // in case the end is missing a \n - hasFoldableLine = - hasFoldableLine || + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " "); @@ -387,8 +384,7 @@ function foldString(string: string, width: number): string { const prefix = match[1], line = match[2]; moreIndented = line[0] === " "; - result += - prefix + + result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + // eslint-disable-next-line @typescript-eslint/no-use-before-define foldLine(line, width); @@ -412,7 +408,7 @@ function escapeString(string: string): string { if (nextChar >= 0xdc00 && nextChar <= 0xdfff /* low surrogate */) { // Combine the surrogate pair and store it escaped. result += encodeHex( - (char - 0xd800) * 0x400 + nextChar - 0xdc00 + 0x10000 + (char - 0xd800) * 0x400 + nextChar - 0xdc00 + 0x10000, ); // Advance index one extra since we already used that char here. i++; @@ -420,10 +416,9 @@ function escapeString(string: string): string { } } escapeSeq = ESCAPE_SEQUENCES[char]; - result += - !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); } return result; @@ -453,7 +448,7 @@ function writeScalar( state: DumperState, string: string, level: number, - iskey: boolean + iskey: boolean, ): void { state.dump = ((): string => { if (string.length === 0) { @@ -476,15 +471,13 @@ function writeScalar( // This behaves better than a constant minimum width which disallows // narrower options, or an indent threshold which causes the width // to suddenly increase. - const lineWidth = - state.lineWidth === -1 - ? -1 - : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + const lineWidth = state.lineWidth === -1 + ? -1 + : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); // Without knowing if keys are implicit/explicit, // assume implicit for safety. - const singleLineOnly = - iskey || + const singleLineOnly = iskey || // No block styles in flow mode. (state.flowLevel > -1 && level >= state.flowLevel); function testAmbiguity(str: string): boolean { @@ -497,7 +490,7 @@ function writeScalar( singleLineOnly, state.indent, lineWidth, - testAmbiguity + testAmbiguity, ) ) { case STYLE_PLAIN: @@ -505,13 +498,15 @@ function writeScalar( case STYLE_SINGLE: return `'${string.replace(/'/g, "''")}'`; case STYLE_LITERAL: - return `|${blockHeader(string, state.indent)}${dropEndingNewline( - indentString(string, indent) - )}`; + return `|${blockHeader(string, state.indent)}${ + dropEndingNewline(indentString(string, indent)) + }`; case STYLE_FOLDED: - return `>${blockHeader(string, state.indent)}${dropEndingNewline( - indentString(foldString(string, lineWidth), indent) - )}`; + return `>${blockHeader(string, state.indent)}${ + dropEndingNewline( + indentString(foldString(string, lineWidth), indent), + ) + }`; case STYLE_DOUBLE: return `"${escapeString(string)}"`; default: @@ -523,7 +518,7 @@ function writeScalar( function writeFlowSequence( state: DumperState, level: number, - object: Any + object: Any, ): void { let _result = ""; const _tag = state.tag; @@ -545,7 +540,7 @@ function writeBlockSequence( state: DumperState, level: number, object: Any, - compact = false + compact = false, ): void { let _result = ""; const _tag = state.tag; @@ -575,7 +570,7 @@ function writeBlockSequence( function writeFlowMapping( state: DumperState, level: number, - object: Any + object: Any, ): void { let _result = ""; const _tag = state.tag, @@ -624,7 +619,7 @@ function writeBlockMapping( state: DumperState, level: number, object: Any, - compact = false + compact = false, ): void { const _tag = state.tag, objectKeyList = Object.keys(object); @@ -665,8 +660,7 @@ function writeBlockMapping( continue; // Skip this pair because of invalid key. } - explicitPair = - (state.tag !== null && state.tag !== "?") || + explicitPair = (state.tag !== null && state.tag !== "?") || (state.dump && state.dump.length > 1024); if (explicitPair) { @@ -707,7 +701,7 @@ function writeBlockMapping( function detectType( state: DumperState, object: Any, - explicit = false + explicit = false, ): boolean { const typeList = explicit ? state.explicitTypes : state.implicitTypes; @@ -733,11 +727,11 @@ function detectType( } else if (_hasOwnProperty.call(type.represent, style)) { _result = (type.represent as ArrayObject<RepresentFn>)[style]( object, - style + style, ); } else { throw new YAMLError( - `!<${type.tag}> tag resolver accepts not "${style}" style` + `!<${type.tag}> tag resolver accepts not "${style}" style`, ); } @@ -760,7 +754,7 @@ function writeNode( object: Any, block: boolean, compact: boolean, - iskey = false + iskey = false, ): boolean { state.tag = null; state.dump = object; @@ -843,7 +837,7 @@ function writeNode( function inspectNode( object: Any, objects: Any[], - duplicatesIndexes: number[] + duplicatesIndexes: number[], ): void { if (object !== null && typeof object === "object") { const index = objects.indexOf(object); diff --git a/std/encoding/_yaml/dumper/dumper_state.ts b/std/encoding/_yaml/dumper/dumper_state.ts index 2124ecb98..63b04983e 100644 --- a/std/encoding/_yaml/dumper/dumper_state.ts +++ b/std/encoding/_yaml/dumper/dumper_state.ts @@ -12,7 +12,7 @@ const _hasOwnProperty = Object.prototype.hasOwnProperty; function compileStyleMap( schema: Schema, - map?: ArrayObject<StyleVariant> | null + map?: ArrayObject<StyleVariant> | null, ): ArrayObject<StyleVariant> { if (typeof map === "undefined" || map === null) return {}; diff --git a/std/encoding/_yaml/error.ts b/std/encoding/_yaml/error.ts index a96ab11d6..77473fbd8 100644 --- a/std/encoding/_yaml/error.ts +++ b/std/encoding/_yaml/error.ts @@ -8,7 +8,7 @@ import type { Mark } from "./mark.ts"; export class YAMLError extends Error { constructor( message = "(unknown reason)", - protected mark: Mark | string = "" + protected mark: Mark | string = "", ) { super(`${message} ${mark}`); this.name = this.constructor.name; diff --git a/std/encoding/_yaml/example/dump.ts b/std/encoding/_yaml/example/dump.ts index db3647274..bc4684dfe 100644 --- a/std/encoding/_yaml/example/dump.ts +++ b/std/encoding/_yaml/example/dump.ts @@ -18,5 +18,5 @@ console.log( ], }, test: "foobar", - }) + }), ); diff --git a/std/encoding/_yaml/loader/loader.ts b/std/encoding/_yaml/loader/loader.ts index 4ab3e9adc..216e315f2 100644 --- a/std/encoding/_yaml/loader/loader.ts +++ b/std/encoding/_yaml/loader/loader.ts @@ -25,12 +25,14 @@ const CHOMPING_CLIP = 1; const CHOMPING_STRIP = 2; const CHOMPING_KEEP = 3; -const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +const PATTERN_NON_PRINTABLE = + /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; const PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; const PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; /* eslint-disable-next-line max-len */ -const PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; +const PATTERN_TAG_URI = + /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj: unknown): string { return Object.prototype.toString.call(obj); @@ -148,7 +150,7 @@ function charFromCodepoint(c: number): string { // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF return String.fromCharCode( ((c - 0x010000) >> 10) + 0xd800, - ((c - 0x010000) & 0x03ff) + 0xdc00 + ((c - 0x010000) & 0x03ff) + 0xdc00, ); } @@ -167,8 +169,8 @@ function generateError(state: LoaderState, message: string): YAMLError { state.input, state.position, state.line, - state.position - state.lineStart - ) + state.position - state.lineStart, + ), ); } @@ -229,21 +231,21 @@ const directiveHandlers: DirectiveHandlers = { if (!PATTERN_TAG_HANDLE.test(handle)) { return throwError( state, - "ill-formed tag handle (first argument) of the TAG directive" + "ill-formed tag handle (first argument) of the TAG directive", ); } if (_hasOwnProperty.call(state.tagMap, handle)) { return throwError( state, - `there is a previously declared suffix for "${handle}" tag handle` + `there is a previously declared suffix for "${handle}" tag handle`, ); } if (!PATTERN_TAG_URI.test(prefix)) { return throwError( state, - "ill-formed tag prefix (second argument) of the TAG directive" + "ill-formed tag prefix (second argument) of the TAG directive", ); } @@ -258,7 +260,7 @@ function captureSegment( state: LoaderState, start: number, end: number, - checkJson: boolean + checkJson: boolean, ): void { let result: string; if (start < end) { @@ -289,12 +291,12 @@ function mergeMappings( state: LoaderState, destination: ArrayObject, source: ArrayObject, - overridableKeys: ArrayObject<boolean> + overridableKeys: ArrayObject<boolean>, ): void { if (!common.isObject(source)) { return throwError( state, - "cannot merge mappings; the provided source object is unacceptable" + "cannot merge mappings; the provided source object is unacceptable", ); } @@ -316,7 +318,7 @@ function storeMappingPair( keyNode: Any, valueNode: unknown, startLine?: number, - startPos?: number + startPos?: number, ): ArrayObject { // The output is a plain object here, so keys can only be strings. // We need to convert keyNode to a string, but doing so can hang the process @@ -401,7 +403,7 @@ function readLineBreak(state: LoaderState): void { function skipSeparationSpace( state: LoaderState, allowComments: boolean, - checkIndent: number + checkIndent: number, ): number { let lineBreaks = 0, ch = state.input.charCodeAt(state.position); @@ -478,7 +480,7 @@ function writeFoldedLines(state: LoaderState, count: number): void { function readPlainScalar( state: LoaderState, nodeIndent: number, - withinFlowCollection: boolean + withinFlowCollection: boolean, ): boolean { const kind = state.kind; const result = state.result; @@ -587,7 +589,7 @@ function readPlainScalar( function readSingleQuotedScalar( state: LoaderState, - nodeIndent: number + nodeIndent: number, ): boolean { let ch, captureStart, captureEnd; @@ -624,7 +626,7 @@ function readSingleQuotedScalar( ) { return throwError( state, - "unexpected end of the document within a single quoted scalar" + "unexpected end of the document within a single quoted scalar", ); } else { state.position++; @@ -634,13 +636,13 @@ function readSingleQuotedScalar( return throwError( state, - "unexpected end of the stream within a single quoted scalar" + "unexpected end of the stream within a single quoted scalar", ); } function readDoubleQuotedScalar( state: LoaderState, - nodeIndent: number + nodeIndent: number, ): boolean { let ch = state.input.charCodeAt(state.position); @@ -703,7 +705,7 @@ function readDoubleQuotedScalar( ) { return throwError( state, - "unexpected end of the document within a double quoted scalar" + "unexpected end of the document within a double quoted scalar", ); } else { state.position++; @@ -713,7 +715,7 @@ function readDoubleQuotedScalar( return throwError( state, - "unexpected end of the stream within a double quoted scalar" + "unexpected end of the stream within a double quoted scalar", ); } @@ -808,7 +810,7 @@ function readFlowCollection(state: LoaderState, nodeIndent: number): boolean { overridableKeys, keyTag, keyNode, - valueNode + valueNode, ); } else if (isPair) { (result as Array<{}>).push( @@ -818,8 +820,8 @@ function readFlowCollection(state: LoaderState, nodeIndent: number): boolean { overridableKeys, keyTag, keyNode, - valueNode - ) + valueNode, + ), ); } else { (result as ResultType[]).push(keyNode as ResultType); @@ -839,7 +841,7 @@ function readFlowCollection(state: LoaderState, nodeIndent: number): boolean { return throwError( state, - "unexpected end of the stream within a flow collection" + "unexpected end of the stream within a flow collection", ); } @@ -879,7 +881,7 @@ function readBlockScalar(state: LoaderState, nodeIndent: number): boolean { if (tmp === 0) { return throwError( state, - "bad explicit indentation width of a block scalar; it cannot be less than one" + "bad explicit indentation width of a block scalar; it cannot be less than one", ); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; @@ -933,7 +935,7 @@ function readBlockScalar(state: LoaderState, nodeIndent: number): boolean { if (chomping === CHOMPING_KEEP) { state.result += common.repeat( "\n", - didReadContent ? 1 + emptyLines : emptyLines + didReadContent ? 1 + emptyLines : emptyLines, ); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { @@ -954,7 +956,7 @@ function readBlockScalar(state: LoaderState, nodeIndent: number): boolean { // except for the first content line (cf. Example 8.1) state.result += common.repeat( "\n", - didReadContent ? 1 + emptyLines : emptyLines + didReadContent ? 1 + emptyLines : emptyLines, ); // End of more-indented block. @@ -979,7 +981,7 @@ function readBlockScalar(state: LoaderState, nodeIndent: number): boolean { // Keep all line breaks except the header line break. state.result += common.repeat( "\n", - didReadContent ? 1 + emptyLines : emptyLines + didReadContent ? 1 + emptyLines : emptyLines, ); } @@ -1067,7 +1069,7 @@ function readBlockSequence(state: LoaderState, nodeIndent: number): boolean { function readBlockMapping( state: LoaderState, nodeIndent: number, - flowIndent: number + flowIndent: number, ): boolean { const tag = state.tag, anchor = state.anchor, @@ -1112,7 +1114,7 @@ function readBlockMapping( overridableKeys, keyTag as string, keyNode, - null + null, ); keyTag = keyNode = valueNode = null; } @@ -1127,7 +1129,7 @@ function readBlockMapping( } else { return throwError( state, - "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line" + "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line", ); } @@ -1152,7 +1154,7 @@ function readBlockMapping( if (!isWsOrEol(ch)) { return throwError( state, - "a whitespace character is expected after the key-value separator within a block mapping" + "a whitespace character is expected after the key-value separator within a block mapping", ); } @@ -1163,7 +1165,7 @@ function readBlockMapping( overridableKeys, keyTag as string, keyNode, - null + null, ); keyTag = keyNode = valueNode = null; } @@ -1176,7 +1178,7 @@ function readBlockMapping( } else if (detected) { return throwError( state, - "can not read an implicit mapping pair; a colon is missed" + "can not read an implicit mapping pair; a colon is missed", ); } else { state.tag = tag; @@ -1186,7 +1188,7 @@ function readBlockMapping( } else if (detected) { return throwError( state, - "can not read a block mapping entry; a multiline key may not be an implicit key" + "can not read a block mapping entry; a multiline key may not be an implicit key", ); } else { state.tag = tag; @@ -1221,7 +1223,7 @@ function readBlockMapping( keyNode, valueNode, line, - pos + pos, ); keyTag = keyNode = valueNode = null; } @@ -1249,7 +1251,7 @@ function readBlockMapping( overridableKeys, keyTag as string, keyNode, - null + null, ); } @@ -1306,7 +1308,7 @@ function readTagProperty(state: LoaderState): boolean { } else { return throwError( state, - "unexpected end of the stream within a verbatim tag" + "unexpected end of the stream within a verbatim tag", ); } } else { @@ -1318,7 +1320,7 @@ function readTagProperty(state: LoaderState): boolean { if (!PATTERN_TAG_HANDLE.test(tagHandle)) { return throwError( state, - "named tag handle cannot contain such characters" + "named tag handle cannot contain such characters", ); } @@ -1327,7 +1329,7 @@ function readTagProperty(state: LoaderState): boolean { } else { return throwError( state, - "tag suffix cannot contain exclamation marks" + "tag suffix cannot contain exclamation marks", ); } } @@ -1340,7 +1342,7 @@ function readTagProperty(state: LoaderState): boolean { if (PATTERN_FLOW_INDICATORS.test(tagName)) { return throwError( state, - "tag suffix cannot contain flow indicator characters" + "tag suffix cannot contain flow indicator characters", ); } } @@ -1348,7 +1350,7 @@ function readTagProperty(state: LoaderState): boolean { if (tagName && !PATTERN_TAG_URI.test(tagName)) { return throwError( state, - `tag name cannot contain such characters: ${tagName}` + `tag name cannot contain such characters: ${tagName}`, ); } @@ -1387,7 +1389,7 @@ function readAnchorProperty(state: LoaderState): boolean { if (state.position === position) { return throwError( state, - "name of an anchor node must contain at least one character" + "name of an anchor node must contain at least one character", ); } @@ -1410,7 +1412,7 @@ function readAlias(state: LoaderState): boolean { if (state.position === _position) { return throwError( state, - "name of an alias node must contain at least one character" + "name of an alias node must contain at least one character", ); } @@ -1434,7 +1436,7 @@ function composeNode( parentIndent: number, nodeContext: number, allowToSeek: boolean, - allowCompact: boolean + allowCompact: boolean, ): boolean { let allowBlockScalars: boolean, allowBlockCollections: boolean, @@ -1454,8 +1456,9 @@ function composeNode( state.kind = null; state.result = null; - const allowBlockStyles = (allowBlockScalars = allowBlockCollections = - CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext); + const allowBlockStyles = + (allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext); if (allowToSeek) { if (skipSeparationSpace(state, true, -1)) { @@ -1495,8 +1498,8 @@ function composeNode( } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - const cond = - CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext; + const cond = CONTEXT_FLOW_IN === nodeContext || + CONTEXT_FLOW_OUT === nodeContext; flowIndent = cond ? parentIndent : parentIndent + 1; blockIndent = state.position - state.lineStart; @@ -1522,7 +1525,7 @@ function composeNode( if (state.tag !== null || state.anchor !== null) { return throwError( state, - "alias node should not have Any properties" + "alias node should not have Any properties", ); } } else if ( @@ -1542,8 +1545,8 @@ function composeNode( } else if (indentStatus === 0) { // Special case: block sequences are allowed to have same indentation level as the parent. // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = - allowBlockCollections && readBlockSequence(state, blockIndent); + hasContent = allowBlockCollections && + readBlockSequence(state, blockIndent); } } @@ -1578,7 +1581,7 @@ function composeNode( if (state.result !== null && type.kind !== state.kind) { return throwError( state, - `unacceptable node kind for !<${state.tag}> tag; it should be "${type.kind}", not "${state.kind}"` + `unacceptable node kind for !<${state.tag}> tag; it should be "${type.kind}", not "${state.kind}"`, ); } @@ -1586,7 +1589,7 @@ function composeNode( // `state.result` updated in resolver if matched return throwError( state, - `cannot resolve a node with !<${state.tag}> explicit tag` + `cannot resolve a node with !<${state.tag}> explicit tag`, ); } else { state.result = type.construct(state.result); @@ -1641,7 +1644,7 @@ function readDocument(state: LoaderState): void { if (directiveName.length < 1) { return throwError( state, - "directive name must not be less than one character in length" + "directive name must not be less than one character in length", ); } @@ -1697,7 +1700,7 @@ function readDocument(state: LoaderState): void { if ( state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test( - state.input.slice(documentStart, state.position) + state.input.slice(documentStart, state.position), ) ) { throwWarning(state, "non-ASCII line breaks are interpreted as content"); @@ -1716,7 +1719,7 @@ function readDocument(state: LoaderState): void { if (state.position < state.length - 1) { return throwError( state, - "end of the stream or a document separator is expected" + "end of the stream or a document separator is expected", ); } else { return; @@ -1767,7 +1770,7 @@ function isCbFunction(fn: unknown): fn is CbFunction { export function loadAll<T extends CbFunction | LoaderStateOptions>( input: string, iteratorOrOption?: T, - options?: LoaderStateOptions + options?: LoaderStateOptions, ): T extends CbFunction ? void : unknown[] { if (!isCbFunction(iteratorOrOption)) { return loadDocuments(input, iteratorOrOption as LoaderStateOptions) as Any; @@ -1792,6 +1795,6 @@ export function load(input: string, options?: LoaderStateOptions): unknown { return documents[0]; } throw new YAMLError( - "expected a single document in the stream, but found more" + "expected a single document in the stream, but found more", ); } diff --git a/std/encoding/_yaml/loader/loader_state.ts b/std/encoding/_yaml/loader/loader_state.ts index 781a4a086..60a7ccabc 100644 --- a/std/encoding/_yaml/loader/loader_state.ts +++ b/std/encoding/_yaml/loader/loader_state.ts @@ -57,7 +57,7 @@ export class LoaderState extends State { legacy = false, json = false, listener = null, - }: LoaderStateOptions + }: LoaderStateOptions, ) { super(schema); this.filename = filename; diff --git a/std/encoding/_yaml/mark.ts b/std/encoding/_yaml/mark.ts index 44cf175a0..35e986cce 100644 --- a/std/encoding/_yaml/mark.ts +++ b/std/encoding/_yaml/mark.ts @@ -11,7 +11,7 @@ export class Mark { public buffer: string, public position: number, public line: number, - public column: number + public column: number, ) {} public getSnippet(indent = 4, maxLength = 75): string | null { @@ -48,10 +48,12 @@ export class Mark { } const snippet = this.buffer.slice(start, end); - return `${repeat(" ", indent)}${head}${snippet}${tail}\n${repeat( - " ", - indent + this.position - start + head.length - )}^`; + return `${repeat(" ", indent)}${head}${snippet}${tail}\n${ + repeat( + " ", + indent + this.position - start + head.length, + ) + }^`; } public toString(compact?: boolean): string { diff --git a/std/encoding/_yaml/parse.ts b/std/encoding/_yaml/parse.ts index 9a6f325f2..05a9b48ac 100644 --- a/std/encoding/_yaml/parse.ts +++ b/std/encoding/_yaml/parse.ts @@ -26,7 +26,7 @@ export function parse(content: string, options?: ParseOptions): unknown { export function parseAll( content: string, iterator?: CbFunction, - options?: ParseOptions + options?: ParseOptions, ): unknown { return loadAll(content, iterator, options); } diff --git a/std/encoding/_yaml/schema.ts b/std/encoding/_yaml/schema.ts index 98b49203c..b955e5df8 100644 --- a/std/encoding/_yaml/schema.ts +++ b/std/encoding/_yaml/schema.ts @@ -10,7 +10,7 @@ import type { ArrayObject, Any } from "./utils.ts"; function compileList( schema: Schema, name: "implicit" | "explicit", - result: Type[] + result: Type[], ): Type[] { const exclude: number[] = []; @@ -78,7 +78,7 @@ export class Schema implements SchemaDefinition { if (type.loadKind && type.loadKind !== "scalar") { throw new YAMLError( // eslint-disable-next-line max-len - "There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported." + "There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.", ); } } @@ -87,7 +87,7 @@ export class Schema implements SchemaDefinition { this.compiledExplicit = compileList(this, "explicit", []); this.compiledTypeMap = compileMap( this.compiledImplicit, - this.compiledExplicit + this.compiledExplicit, ); } diff --git a/std/encoding/_yaml/type/float.ts b/std/encoding/_yaml/type/float.ts index 5ae0689b2..6d59ed9ed 100644 --- a/std/encoding/_yaml/type/float.ts +++ b/std/encoding/_yaml/type/float.ts @@ -17,7 +17,7 @@ const YAML_FLOAT_PATTERN = new RegExp( // .inf "|[-+]?\\.(?:inf|Inf|INF)" + // .nan - "|\\.(?:nan|NaN|NAN))$" + "|\\.(?:nan|NaN|NAN))$", ); function resolveYamlFloat(data: string): boolean { diff --git a/std/encoding/_yaml/type/timestamp.ts b/std/encoding/_yaml/type/timestamp.ts index eb03b3825..231908231 100644 --- a/std/encoding/_yaml/type/timestamp.ts +++ b/std/encoding/_yaml/type/timestamp.ts @@ -7,21 +7,21 @@ import { Type } from "../type.ts"; const YAML_DATE_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])" + // [1] year - "-([0-9][0-9])" + // [2] month - "-([0-9][0-9])$" // [3] day + "-([0-9][0-9])" + // [2] month + "-([0-9][0-9])$", // [3] day ); const YAML_TIMESTAMP_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])" + // [1] year - "-([0-9][0-9]?)" + // [2] month - "-([0-9][0-9]?)" + // [3] day - "(?:[Tt]|[ \\t]+)" + // ... - "([0-9][0-9]?)" + // [4] hour - ":([0-9][0-9])" + // [5] minute - ":([0-9][0-9])" + // [6] second - "(?:\\.([0-9]*))?" + // [7] fraction - "(?:[ \\t]*(Z|([-+])([0-9][0-9]?)" + // [8] tz [9] tz_sign [10] tz_hour - "(?::([0-9][0-9]))?))?$" // [11] tz_minute + "-([0-9][0-9]?)" + // [2] month + "-([0-9][0-9]?)" + // [3] day + "(?:[Tt]|[ \\t]+)" + // ... + "([0-9][0-9]?)" + // [4] hour + ":([0-9][0-9])" + // [5] minute + ":([0-9][0-9])" + // [6] second + "(?:\\.([0-9]*))?" + // [7] fraction + "(?:[ \\t]*(Z|([-+])([0-9][0-9]?)" + // [8] tz [9] tz_sign [10] tz_hour + "(?::([0-9][0-9]))?))?$", // [11] tz_minute ); function resolveYamlTimestamp(data: string): boolean { @@ -75,7 +75,7 @@ function constructYamlTimestamp(data: string): Date { } const date = new Date( - Date.UTC(year, month, day, hour, minute, second, fraction) + Date.UTC(year, month, day, hour, minute, second, fraction), ); if (delta) date.setTime(date.getTime() - delta); diff --git a/std/encoding/ascii85.ts b/std/encoding/ascii85.ts index b7a2e2065..6a303ebda 100644 --- a/std/encoding/ascii85.ts +++ b/std/encoding/ascii85.ts @@ -65,9 +65,11 @@ export function encode(uint8: Uint8Array, options?: Ascii85Options): string { break; case "btoa": if (options?.delimiter) { - return `xbtoa Begin\n${output - .slice(0, output.length - difference) - .join("")}\nxbtoa End`; + return `xbtoa Begin\n${ + output + .slice(0, output.length - difference) + .join("") + }\nxbtoa End`; } break; case "RFC 1924": @@ -99,13 +101,15 @@ export function decode(ascii85: string, options?: Ascii85Options): Uint8Array { .replaceAll("y", "+<VdL"); break; case "RFC 1924": - ascii85 = ascii85.replaceAll(/./g, (match) => - String.fromCharCode(rfc1924.indexOf(match) + 33) + ascii85 = ascii85.replaceAll( + /./g, + (match) => String.fromCharCode(rfc1924.indexOf(match) + 33), ); break; case "Z85": - ascii85 = ascii85.replaceAll(/./g, (match) => - String.fromCharCode(Z85.indexOf(match) + 33) + ascii85 = ascii85.replaceAll( + /./g, + (match) => String.fromCharCode(Z85.indexOf(match) + 33), ); break; } @@ -117,7 +121,7 @@ export function decode(ascii85: string, options?: Ascii85Options): Uint8Array { let v = 0, n = 0, max = 0; - for (let i = 0; i < len; ) { + for (let i = 0; i < len;) { for (max += 5; i < max; i++) { v = v * 85 + (i < len ? ascii85.charCodeAt(i) : 117) - 33; } diff --git a/std/encoding/ascii85_test.ts b/std/encoding/ascii85_test.ts index d068c0bf6..02af70964 100644 --- a/std/encoding/ascii85_test.ts +++ b/std/encoding/ascii85_test.ts @@ -126,7 +126,7 @@ for (const [standard, tests] of Object.entries(testCasesNoDelimeter)) { encode(utf8encoder.encode(bin), { standard: standard as Ascii85Standard, }), - b85 + b85, ); } }, @@ -138,7 +138,7 @@ for (const [standard, tests] of Object.entries(testCasesNoDelimeter)) { for (const [bin, b85] of tests) { assertEquals( decode(b85, { standard: standard as Ascii85Standard }), - utf8encoder.encode(bin) + utf8encoder.encode(bin), ); } }, @@ -155,7 +155,7 @@ for (const [standard, tests] of Object.entries(testCasesDelimeter)) { standard: standard as Ascii85Standard, delimiter: true, }), - b85 + b85, ); } }, @@ -170,7 +170,7 @@ for (const [standard, tests] of Object.entries(testCasesDelimeter)) { standard: standard as Ascii85Standard, delimiter: true, }), - utf8encoder.encode(bin) + utf8encoder.encode(bin), ); } }, diff --git a/std/encoding/base32.ts b/std/encoding/base32.ts index e7d3332fd..7d0ec81f3 100644 --- a/std/encoding/base32.ts +++ b/std/encoding/base32.ts @@ -65,8 +65,7 @@ export function decode(b32: string): Uint8Array { let i: number; for (i = 0; i < len; i += 8) { - tmp = - (revLookup[b32.charCodeAt(i)] << 20) | + tmp = (revLookup[b32.charCodeAt(i)] << 20) | (revLookup[b32.charCodeAt(i + 1)] << 15) | (revLookup[b32.charCodeAt(i + 2)] << 10) | (revLookup[b32.charCodeAt(i + 3)] << 5) | @@ -75,8 +74,7 @@ export function decode(b32: string): Uint8Array { arr[curByte++] = (tmp >> 9) & 0xff; arr[curByte++] = (tmp >> 1) & 0xff; - tmp = - ((tmp & 1) << 15) | + tmp = ((tmp & 1) << 15) | (revLookup[b32.charCodeAt(i + 5)] << 10) | (revLookup[b32.charCodeAt(i + 6)] << 5) | revLookup[b32.charCodeAt(i + 7)]; @@ -85,8 +83,7 @@ export function decode(b32: string): Uint8Array { } if (placeHoldersLen === 1) { - tmp = - (revLookup[b32.charCodeAt(i)] << 20) | + tmp = (revLookup[b32.charCodeAt(i)] << 20) | (revLookup[b32.charCodeAt(i + 1)] << 15) | (revLookup[b32.charCodeAt(i + 2)] << 10) | (revLookup[b32.charCodeAt(i + 3)] << 5) | @@ -94,14 +91,12 @@ export function decode(b32: string): Uint8Array { arr[curByte++] = (tmp >> 17) & 0xff; arr[curByte++] = (tmp >> 9) & 0xff; arr[curByte++] = (tmp >> 1) & 0xff; - tmp = - ((tmp & 1) << 7) | + tmp = ((tmp & 1) << 7) | (revLookup[b32.charCodeAt(i + 5)] << 2) | (revLookup[b32.charCodeAt(i + 6)] >> 3); arr[curByte++] = tmp & 0xff; } else if (placeHoldersLen === 3) { - tmp = - (revLookup[b32.charCodeAt(i)] << 19) | + tmp = (revLookup[b32.charCodeAt(i)] << 19) | (revLookup[b32.charCodeAt(i + 1)] << 14) | (revLookup[b32.charCodeAt(i + 2)] << 9) | (revLookup[b32.charCodeAt(i + 3)] << 4) | @@ -110,16 +105,14 @@ export function decode(b32: string): Uint8Array { arr[curByte++] = (tmp >> 8) & 0xff; arr[curByte++] = tmp & 0xff; } else if (placeHoldersLen === 4) { - tmp = - (revLookup[b32.charCodeAt(i)] << 11) | + tmp = (revLookup[b32.charCodeAt(i)] << 11) | (revLookup[b32.charCodeAt(i + 1)] << 6) | (revLookup[b32.charCodeAt(i + 2)] << 1) | (revLookup[b32.charCodeAt(i + 3)] >> 4); arr[curByte++] = (tmp >> 8) & 0xff; arr[curByte++] = tmp & 0xff; } else if (placeHoldersLen === 6) { - tmp = - (revLookup[b32.charCodeAt(i)] << 3) | + tmp = (revLookup[b32.charCodeAt(i)] << 3) | (revLookup[b32.charCodeAt(i + 1)] >> 2); arr[curByte++] = tmp & 0xff; } @@ -131,16 +124,14 @@ function encodeChunk(uint8: Uint8Array, start: number, end: number): string { let tmp: number; const output = []; for (let i = start; i < end; i += 5) { - tmp = - ((uint8[i] << 16) & 0xff0000) | + tmp = ((uint8[i] << 16) & 0xff0000) | ((uint8[i + 1] << 8) & 0xff00) | (uint8[i + 2] & 0xff); output.push(lookup[(tmp >> 19) & 0x1f]); output.push(lookup[(tmp >> 14) & 0x1f]); output.push(lookup[(tmp >> 9) & 0x1f]); output.push(lookup[(tmp >> 4) & 0x1f]); - tmp = - ((tmp & 0xf) << 16) | + tmp = ((tmp & 0xf) << 16) | ((uint8[i + 3] << 8) & 0xff00) | (uint8[i + 4] & 0xff); output.push(lookup[(tmp >> 15) & 0x1f]); @@ -169,15 +160,14 @@ export function encode(uint8: Uint8Array): string { encodeChunk( uint8, i, - i + maxChunkLength > len2 ? len2 : i + maxChunkLength - ) + i + maxChunkLength > len2 ? len2 : i + maxChunkLength, + ), ); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 4) { - tmp = - ((uint8[len2] & 0xff) << 16) | + tmp = ((uint8[len2] & 0xff) << 16) | ((uint8[len2 + 1] & 0xff) << 8) | (uint8[len2 + 2] & 0xff); parts.push(lookup[(tmp >> 19) & 0x1f]); @@ -190,8 +180,7 @@ export function encode(uint8: Uint8Array): string { parts.push(lookup[tmp & 0x1f]); parts.push("="); } else if (extraBytes === 3) { - tmp = - ((uint8[len2] & 0xff) << 17) | + tmp = ((uint8[len2] & 0xff) << 17) | ((uint8[len2 + 1] & 0xff) << 9) | ((uint8[len2 + 2] & 0xff) << 1); parts.push(lookup[(tmp >> 20) & 0x1f]); diff --git a/std/encoding/base32_test.ts b/std/encoding/base32_test.ts index 2bd7acea1..cfefe54d7 100644 --- a/std/encoding/base32_test.ts +++ b/std/encoding/base32_test.ts @@ -112,7 +112,7 @@ Deno.test({ decode("OOOO=="); } catch (e) { assert( - e.message.includes("Invalid string. Length must be a multiple of 8") + e.message.includes("Invalid string. Length must be a multiple of 8"), ); errorCaught = true; } diff --git a/std/encoding/base64url.ts b/std/encoding/base64url.ts index 726ea2eb8..b20878554 100644 --- a/std/encoding/base64url.ts +++ b/std/encoding/base64url.ts @@ -12,8 +12,9 @@ import { export function addPaddingToBase64url(base64url: string): string { if (base64url.length % 4 === 2) return base64url + "=="; if (base64url.length % 4 === 3) return base64url + "="; - if (base64url.length % 4 === 1) + if (base64url.length % 4 === 1) { throw new TypeError("Illegal base64url string!"); + } return base64url; } diff --git a/std/encoding/binary.ts b/std/encoding/binary.ts index aed9343b9..f4918e750 100644 --- a/std/encoding/binary.ts +++ b/std/encoding/binary.ts @@ -47,7 +47,7 @@ export function sizeof(dataType: DataType): number { * Resolves it in a `Uint8Array`, or throws `Deno.errors.UnexpectedEof` if `n` bytes cannot be read. */ export async function getNBytes( r: Deno.Reader, - n: number + n: number, ): Promise<Uint8Array> { const scratch = new Uint8Array(n); const nRead = await r.read(scratch); @@ -117,7 +117,7 @@ export function varbig(b: Uint8Array, o: VarbigOptions = {}): bigint | null { export function putVarnum( b: Uint8Array, x: number, - o: VarnumOptions = {} + o: VarnumOptions = {}, ): number { o.dataType = o.dataType ?? "int32"; const littleEndian = (o.endian ?? "big") === "little" ? true : false; @@ -158,7 +158,7 @@ export function putVarnum( export function putVarbig( b: Uint8Array, x: bigint, - o: VarbigOptions = {} + o: VarbigOptions = {}, ): number { o.dataType = o.dataType ?? "int64"; const littleEndian = (o.endian ?? "big") === "little" ? true : false; @@ -198,7 +198,7 @@ export function putVarbig( * `o.dataType` defaults to `"int32"`. */ export async function readVarnum( r: Deno.Reader, - o: VarnumOptions = {} + o: VarnumOptions = {}, ): Promise<number> { o.dataType = o.dataType ?? "int32"; const scratch = await getNBytes(r, sizeof(o.dataType)); @@ -210,7 +210,7 @@ export async function readVarnum( * `o.dataType` defaults to `"int64"`. */ export async function readVarbig( r: Deno.Reader, - o: VarbigOptions = {} + o: VarbigOptions = {}, ): Promise<bigint> { o.dataType = o.dataType ?? "int64"; const scratch = await getNBytes(r, sizeof(o.dataType)); @@ -223,7 +223,7 @@ export async function readVarbig( export function writeVarnum( w: Deno.Writer, x: number, - o: VarnumOptions = {} + o: VarnumOptions = {}, ): Promise<number> { o.dataType = o.dataType ?? "int32"; const scratch = new Uint8Array(sizeof(o.dataType)); @@ -237,7 +237,7 @@ export function writeVarnum( export function writeVarbig( w: Deno.Writer, x: bigint, - o: VarbigOptions = {} + o: VarbigOptions = {}, ): Promise<number> { o.dataType = o.dataType ?? "int64"; const scratch = new Uint8Array(sizeof(o.dataType)); diff --git a/std/encoding/binary_test.ts b/std/encoding/binary_test.ts index 6213bc2e3..89a5b8c8e 100644 --- a/std/encoding/binary_test.ts +++ b/std/encoding/binary_test.ts @@ -36,7 +36,7 @@ Deno.test("testPutVarbig", function (): void { putVarbig(buff, 0xffeeddccbbaa9988n); assertEquals( buff, - new Uint8Array([0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88]) + new Uint8Array([0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88]), ); }); @@ -45,7 +45,7 @@ Deno.test("testPutVarbigLittleEndian", function (): void { putVarbig(buff, 0x8899aabbccddeeffn, { endian: "little" }); assertEquals( buff, - new Uint8Array([0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88]) + new Uint8Array([0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88]), ); }); @@ -132,7 +132,7 @@ Deno.test("testWriteVarbig", async function (): Promise<void> { await buff.read(data); assertEquals( data, - new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) + new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]), ); }); @@ -143,7 +143,7 @@ Deno.test("testWriteVarbigLittleEndian", async function (): Promise<void> { await buff.read(data); assertEquals( data, - new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) + new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]), ); }); @@ -167,7 +167,7 @@ Deno.test("testVarbigBytes", function (): void { const rslt = varbigBytes(0x0102030405060708n); assertEquals( rslt, - new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) + new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]), ); }); @@ -175,7 +175,7 @@ Deno.test("testVarbigBytesLittleEndian", function (): void { const rslt = varbigBytes(0x0807060504030201n, { endian: "little" }); assertEquals( rslt, - new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) + new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]), ); }); diff --git a/std/encoding/csv.ts b/std/encoding/csv.ts index 5af054530..27b40c566 100644 --- a/std/encoding/csv.ts +++ b/std/encoding/csv.ts @@ -63,7 +63,7 @@ function chkOptions(opt: ReadOptions): void { async function readRecord( Startline: number, reader: BufReader, - opt: ReadOptions = { comma: ",", trimLeadingSpace: false } + opt: ReadOptions = { comma: ",", trimLeadingSpace: false }, ): Promise<string[] | null> { const tp = new TextProtoReader(reader); const lineIndex = Startline; @@ -86,7 +86,8 @@ async function readRecord( const commaLen = opt.comma.length; let recordBuffer = ""; const fieldIndexes = [] as number[]; - parseField: for (;;) { + parseField: + for (;;) { if (opt.trimLeadingSpace) { line = line.trimLeft(); } @@ -221,7 +222,7 @@ export async function readMatrix( comma: ",", trimLeadingSpace: false, lazyQuotes: false, - } + }, ): Promise<string[][]> { const result: string[][] = []; let _nbFields: number | undefined; @@ -315,7 +316,7 @@ export async function parse( input: string | BufReader, opt: ParseOptions = { header: false, - } + }, ): Promise<unknown[]> { let r: string[][]; if (input instanceof BufReader) { @@ -336,7 +337,7 @@ export async function parse( return { name: e, }; - } + }, ); } } else { @@ -347,7 +348,7 @@ export async function parse( return { name: e, }; - } + }, ); i++; } diff --git a/std/encoding/csv_test.ts b/std/encoding/csv_test.ts index 60d43e35e..07a8e0965 100644 --- a/std/encoding/csv_test.ts +++ b/std/encoding/csv_test.ts @@ -381,8 +381,8 @@ x,,, */ { Name: "HugeLines", - Input: - "#ignore\n".repeat(10000) + "@".repeat(5000) + "," + "*".repeat(5000), + Input: "#ignore\n".repeat(10000) + "@".repeat(5000) + "," + + "*".repeat(5000), Output: [["@".repeat(5000), "*".repeat(5000)]], Comment: "#", }, @@ -488,7 +488,7 @@ for (const t of testCases) { trimLeadingSpace: trim, fieldsPerRecord: fieldsPerRec, lazyQuotes: lazyquote, - } + }, ); } catch (e) { err = e; @@ -504,7 +504,7 @@ for (const t of testCases) { trimLeadingSpace: trim, fieldsPerRecord: fieldsPerRec, lazyQuotes: lazyquote, - } + }, ); const expected = t.Output; assertEquals(actual, expected); diff --git a/std/encoding/hex.ts b/std/encoding/hex.ts index 729df6c49..5b09422a9 100644 --- a/std/encoding/hex.ts +++ b/std/encoding/hex.ts @@ -10,7 +10,7 @@ const hextable = new TextEncoder().encode("0123456789abcdef"); export function errInvalidByte(byte: number): Error { return new Error( "encoding/hex: invalid byte: " + - new TextDecoder().decode(new Uint8Array([byte])) + new TextDecoder().decode(new Uint8Array([byte])), ); } diff --git a/std/encoding/hex_test.ts b/std/encoding/hex_test.ts index a42238e53..0cf39ad2e 100644 --- a/std/encoding/hex_test.ts +++ b/std/encoding/hex_test.ts @@ -132,7 +132,7 @@ Deno.test({ assertThrows( () => decode(new TextEncoder().encode(input as string)), Error, - (expectedErr as Error).message + (expectedErr as Error).message, ); } }, @@ -147,7 +147,7 @@ Deno.test({ decodeString(input as string); }, Error, - (expectedErr as Error).message + (expectedErr as Error).message, ); } }, diff --git a/std/encoding/toml.ts b/std/encoding/toml.ts index 8a0715ab6..7d340c8e8 100644 --- a/std/encoding/toml.ts +++ b/std/encoding/toml.ts @@ -110,7 +110,7 @@ class Parser { .join("\n") .replace(/"""/g, '"') .replace(/'''/g, `'`) - .replace(/\n/g, "\\n") + .replace(/\n/g, "\\n"), ); isLiteral = false; } else { @@ -321,7 +321,7 @@ class Parser { this.context.currentGroup.type === "array" ) { this.context.currentGroup.arrValues.push( - this.context.currentGroup.objValues + this.context.currentGroup.objValues, ); this.context.currentGroup.objValues = {}; } @@ -350,7 +350,7 @@ class Parser { if (this.context.currentGroup) { if (this.context.currentGroup.type === "array") { this.context.currentGroup.arrValues.push( - this.context.currentGroup.objValues + this.context.currentGroup.objValues, ); } this._groupToOutput(); diff --git a/std/encoding/toml_test.ts b/std/encoding/toml_test.ts index d272a29ff..5c4c63b5a 100644 --- a/std/encoding/toml_test.ts +++ b/std/encoding/toml_test.ts @@ -27,8 +27,7 @@ Deno.test({ str4: 'this is a "quote"', str5: "The quick brown\nfox jumps over\nthe lazy dog.", str6: "The quick brown\nfox jumps over\nthe lazy dog.", - lines: - "The first newline is\ntrimmed in raw strings.\n All other " + + lines: "The first newline is\ntrimmed in raw strings.\n All other " + "whitespace\n is preserved.", }, }; diff --git a/std/examples/catj.ts b/std/examples/catj.ts index 93fc68a1d..6013a8ac6 100644 --- a/std/examples/catj.ts +++ b/std/examples/catj.ts @@ -19,9 +19,8 @@ function isObject(arg: any): arg is object { function isValidIdentifier(value: string): boolean { // eslint-disable-next-line max-len - return /^(?!(?:do|if|in|for|let|new|try|var|case|else|enum|eval|null|this|true|void|with|break|catch|class|const|false|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$)[\x24A-Z\x5Fa-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC][\x240-9A-Z\x5Fa-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]*$/.test( - value - ); + return /^(?!(?:do|if|in|for|let|new|try|var|case|else|enum|eval|null|this|true|void|with|break|catch|class|const|false|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$)[\x24A-Z\x5Fa-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC][\x240-9A-Z\x5Fa-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]*$/ + .test(value); } function printValue(value: unknown, path: string): void { @@ -59,8 +58,8 @@ function printObject(obj: { [key: string]: any }, path: string): void { function printArray(array: unknown[], path: string): void { for (const index in array) { const value = array[index]; - const nodePath = - (path ? path : colors.cyan(".")) + "[" + colors.cyan(index) + "]"; + const nodePath = (path ? path : colors.cyan(".")) + "[" + + colors.cyan(index) + "]"; if (Array.isArray(value)) { printArray(value, nodePath); diff --git a/std/examples/gist.ts b/std/examples/gist.ts index 555ec8056..31a22d750 100755 --- a/std/examples/gist.ts +++ b/std/examples/gist.ts @@ -21,7 +21,7 @@ const parsedArgs = parse(Deno.args); if (parsedArgs._.length === 0) { console.error( "Usage: gist.ts --allow-env --allow-net [-t|--title Example] some_file " + - "[next_file]" + "[next_file]", ); Deno.exit(1); } diff --git a/std/examples/tests/catj_test.ts b/std/examples/tests/catj_test.ts index 58533ab60..99320fd1d 100644 --- a/std/examples/tests/catj_test.ts +++ b/std/examples/tests/catj_test.ts @@ -45,7 +45,7 @@ Deno.test("[examples/catj] print multiple files", async () => { const decoder = new TextDecoder(); const process = catj( "testdata/catj/simple-object.json", - "testdata/catj/simple-array.json" + "testdata/catj/simple-array.json", ); try { const output = await process.output(); diff --git a/std/examples/tests/echo_server_test.ts b/std/examples/tests/echo_server_test.ts index 2cf52e466..61afb9756 100644 --- a/std/examples/tests/echo_server_test.ts +++ b/std/examples/tests/echo_server_test.ts @@ -19,7 +19,7 @@ Deno.test("[examples/echo_server]", async () => { assertNotEquals(message, null); assertStrictEquals( decoder.decode((message as ReadLineResult).line).trim(), - "Listening on 0.0.0.0:8080" + "Listening on 0.0.0.0:8080", ); conn = await Deno.connect({ hostname: "127.0.0.1", port: 8080 }); diff --git a/std/examples/tests/xeval_test.ts b/std/examples/tests/xeval_test.ts index 9f7c5db9e..cc74c5226 100644 --- a/std/examples/tests/xeval_test.ts +++ b/std/examples/tests/xeval_test.ts @@ -21,7 +21,7 @@ Deno.test("xevalDelimiter", async function (): Promise<void> { ($): number => chunks.push($), { delimiter: "MADAM", - } + }, ); assertEquals(chunks, ["!MAD", "ADAM!"]); }); diff --git a/std/examples/xeval.ts b/std/examples/xeval.ts index 814d306cd..be326a4ad 100644 --- a/std/examples/xeval.ts +++ b/std/examples/xeval.ts @@ -40,7 +40,7 @@ const DEFAULT_DELIMITER = "\n"; export async function xeval( reader: Deno.Reader, xevalFunc: XevalFunc, - { delimiter = DEFAULT_DELIMITER }: XevalOptions = {} + { delimiter = DEFAULT_DELIMITER }: XevalOptions = {}, ): Promise<void> { for await (const chunk of readStringDelim(reader, delimiter)) { // Ignore empty chunks. diff --git a/std/flags/dash_test.ts b/std/flags/dash_test.ts index 896305cc4..7a4f7dd1e 100755 --- a/std/flags/dash_test.ts +++ b/std/flags/dash_test.ts @@ -23,6 +23,6 @@ Deno.test("moveArgsAfterDoubleDashIntoOwnArray", function (): void { name: "John", _: ["before"], "--": ["after"], - } + }, ); }); diff --git a/std/flags/mod.ts b/std/flags/mod.ts index a961e6c68..09b5afa8a 100644 --- a/std/flags/mod.ts +++ b/std/flags/mod.ts @@ -104,7 +104,7 @@ export function parse( stopEarly = false, string = [], unknown = (i: string): unknown => i, - }: ArgParsingOptions = {} + }: ArgParsingOptions = {}, ): Args { const flags: Flags = { bools: {}, @@ -191,7 +191,7 @@ export function parse( function setArg( key: string, val: unknown, - arg: string | undefined = undefined + arg: string | undefined = undefined, ): void { if (arg && flags.unknownFn && !argDefined(key, arg)) { if (flags.unknownFn(arg, key, val) === false) return; @@ -210,7 +210,7 @@ export function parse( function aliasIsBoolean(key: string): boolean { return getForce(aliases, key).some( - (x) => typeof get(flags.bools, x) === "boolean" + (x) => typeof get(flags.bools, x) === "boolean", ); } diff --git a/std/flags/parse_test.ts b/std/flags/parse_test.ts index c6a40d1ee..9a19e5634 100755 --- a/std/flags/parse_test.ts +++ b/std/flags/parse_test.ts @@ -43,7 +43,7 @@ Deno.test("comprehensive", function (): void { meep: false, name: "meowmers", _: ["bare", "--not-a-flag", "eek"], - } + }, ); }); diff --git a/std/flags/unknown_test.ts b/std/flags/unknown_test.ts index d6db78371..d17fb8111 100755 --- a/std/flags/unknown_test.ts +++ b/std/flags/unknown_test.ts @@ -45,7 +45,7 @@ Deno.test( honk: true, _: [], }); - } + }, ); Deno.test("stringAndAliasIsNotUnkown", function (): void { diff --git a/std/fmt/colors.ts b/std/fmt/colors.ts index a020657d9..7a12b2883 100644 --- a/std/fmt/colors.ts +++ b/std/fmt/colors.ts @@ -186,7 +186,10 @@ export function rgb24(str: string, color: number | Rgb): string { if (typeof color === "number") { return run( str, - code([38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 39) + code( + [38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], + 39, + ), ); } return run( @@ -199,8 +202,8 @@ export function rgb24(str: string, color: number | Rgb): string { clampAndTruncate(color.g), clampAndTruncate(color.b), ], - 39 - ) + 39, + ), ); } @@ -217,7 +220,10 @@ export function bgRgb24(str: string, color: number | Rgb): string { if (typeof color === "number") { return run( str, - code([48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], 49) + code( + [48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], + 49, + ), ); } return run( @@ -230,8 +236,8 @@ export function bgRgb24(str: string, color: number | Rgb): string { clampAndTruncate(color.g), clampAndTruncate(color.b), ], - 49 - ) + 49, + ), ); } @@ -241,7 +247,7 @@ const ANSI_PATTERN = new RegExp( "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", ].join("|"), - "g" + "g", ); export function stripColor(string: string): string { diff --git a/std/fmt/colors_test.ts b/std/fmt/colors_test.ts index 7a312202a..dea27f84e 100644 --- a/std/fmt/colors_test.ts +++ b/std/fmt/colors_test.ts @@ -142,7 +142,7 @@ Deno.test("test_rgb24", function (): void { g: 42, b: 43, }), - "[38;2;41;42;43mfoo bar[39m" + "[38;2;41;42;43mfoo bar[39m", ); }); @@ -157,7 +157,7 @@ Deno.test("test_bgRgb24", function (): void { g: 42, b: 43, }), - "[48;2;41;42;43mfoo bar[49m" + "[48;2;41;42;43mfoo bar[49m", ); }); diff --git a/std/fmt/printf.ts b/std/fmt/printf.ts index bf5feaaed..36b6dddb0 100644 --- a/std/fmt/printf.ts +++ b/std/fmt/printf.ts @@ -153,8 +153,9 @@ class Printf { break; case State.POSITIONAL: // either a verb or * only verb for now, TODO if (c === "*") { - const worp = - this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION; + const worp = this.flags.precision === -1 + ? WorP.WIDTH + : WorP.PRECISION; this.handleWidthOrPrecisionRef(worp); this.state = State.PERCENT; break; @@ -503,8 +504,9 @@ class Printf { } let fractional = m[F.fractional]; - const precision = - this.flags.precision !== -1 ? this.flags.precision : DEFAULT_PRECISION; + const precision = this.flags.precision !== -1 + ? this.flags.precision + : DEFAULT_PRECISION; fractional = this.roundFractionToPrecision(fractional, precision); let e = m[F.exponent]; @@ -553,8 +555,9 @@ class Printf { const dig = arr[0]; let fractional = arr[1]; - const precision = - this.flags.precision !== -1 ? this.flags.precision : DEFAULT_PRECISION; + const precision = this.flags.precision !== -1 + ? this.flags.precision + : DEFAULT_PRECISION; fractional = this.roundFractionToPrecision(fractional, precision); return this.padNum(`${dig}.${fractional}`, n < 0); @@ -589,8 +592,9 @@ class Printf { // converted in the style of an f or F conversion specifier. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html - let P = - this.flags.precision !== -1 ? this.flags.precision : DEFAULT_PRECISION; + let P = this.flags.precision !== -1 + ? this.flags.precision + : DEFAULT_PRECISION; P = P === 0 ? 1 : P; const m = n.toExponential().match(FLOAT_REGEXP); @@ -650,15 +654,16 @@ class Printf { } default: throw new Error( - "currently only number and string are implemented for hex" + "currently only number and string are implemented for hex", ); } } fmtV(val: object): string { if (this.flags.sharp) { - const options = - this.flags.precision !== -1 ? { depth: this.flags.precision } : {}; + const options = this.flags.precision !== -1 + ? { depth: this.flags.precision } + : {}; return this.pad(Deno.inspect(val, options)); } else { const p = this.flags.precision; diff --git a/std/fmt/printf_test.ts b/std/fmt/printf_test.ts index a10fdf516..54adc8b55 100644 --- a/std/fmt/printf_test.ts +++ b/std/fmt/printf_test.ts @@ -35,19 +35,19 @@ Deno.test("testIntegerB", function (): void { assertEquals(S("%b", -4), "-100"); assertEquals( S("%b", 4.1), - "100.0001100110011001100110011001100110011001100110011" + "100.0001100110011001100110011001100110011001100110011", ); assertEquals( S("%b", -4.1), - "-100.0001100110011001100110011001100110011001100110011" + "-100.0001100110011001100110011001100110011001100110011", ); assertEquals( S("%b", Number.MAX_SAFE_INTEGER), - "11111111111111111111111111111111111111111111111111111" + "11111111111111111111111111111111111111111111111111111", ); assertEquals( S("%b", Number.MIN_SAFE_INTEGER), - "-11111111111111111111111111111111111111111111111111111" + "-11111111111111111111111111111111111111111111111111111", ); // width @@ -137,18 +137,18 @@ Deno.test("testFloatfF", function (): void { assertEquals( S("%.324f", Number.MIN_VALUE), // eslint-disable-next-line max-len - "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005" + "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005", ); assertEquals(S("%F", Number.MIN_VALUE), "0.000000"); assertEquals( S("%f", Number.MAX_VALUE), // eslint-disable-next-line max-len - "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000" + "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000", ); assertEquals( S("%F", Number.MAX_VALUE), // eslint-disable-next-line max-len - "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000" + "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000", ); }); @@ -190,7 +190,7 @@ Deno.test("testWidthAndPrecision", function (): void { assertEquals( S("%9.99d", 9), // eslint-disable-next-line max-len - "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009" + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009", ); assertEquals(S("%1.12d", 9), "000000000009"); assertEquals(S("%2s", "a"), " a"); @@ -200,12 +200,12 @@ Deno.test("testWidthAndPrecision", function (): void { assertEquals( S("%*.99d", 9, 9), // eslint-disable-next-line max-len - "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009" + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009", ); assertEquals( S("%9.*d", 99, 9), // eslint-disable-next-line max-len - "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009" + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009", ); assertEquals(S("%*s", 2, "a"), " a"); assertEquals(S("%*d", 2, 1), " 1"); @@ -591,7 +591,7 @@ Deno.test("testThorough", function (): void { assertEquals( is, should, - `failed case[${i}] : is >${is}< should >${should}<` + `failed case[${i}] : is >${is}< should >${should}<`, ); }); }); @@ -600,7 +600,7 @@ Deno.test("testWeirdos", function (): void { assertEquals(S("%.d", 9), "9"); assertEquals( S("dec[%d]=%d hex[%[1]d]=%#x oct[%[1]d]=%#o %s", 1, 255, "Third"), - "dec[1]=255 hex[1]=0xff oct[1]=0377 Third" + "dec[1]=255 hex[1]=0xff oct[1]=0377 Third", ); }); @@ -610,7 +610,7 @@ Deno.test("formatV", function (): void { assertEquals(S("%#v", a), `{ a: { a: { a: { a: ${cyan("[Object]")} } } } }`); assertEquals( S("%#.8v", a), - "{ a: { a: { a: { a: { a: { a: { a: {} } } } } } } }" + "{ a: { a: { a: { a: { a: { a: { a: {} } } } } } } }", ); assertEquals(S("%#.1v", a), `{ a: ${cyan("[Object]")} }`); }); @@ -625,9 +625,9 @@ Deno.test("flagLessThan", function (): void { const aArray = [a, a, a]; assertEquals( S("%<#.1v", aArray), - `[ { a: ${cyan("[Object]")} }, { a: ${cyan("[Object]")} }, { a: ${cyan( - "[Object]" - )} } ]` + `[ { a: ${cyan("[Object]")} }, { a: ${cyan("[Object]")} }, { a: ${ + cyan("[Object]") + } } ]`, ); const fArray = [1.2345, 0.98765, 123456789.5678]; assertEquals(S("%<.2f", fArray), "[ 1.23, 0.99, 123456789.57 ]"); @@ -649,7 +649,7 @@ Deno.test("testErrors", function (): void { assertEquals(S("%.*f", "a", 1.1), "%!(BAD PREC 'a')"); assertEquals( S("%.[2]*f", 1.23, "p"), - `%!(BAD PREC 'p')%!(EXTRA '${yellow("1.23")}')` + `%!(BAD PREC 'p')%!(EXTRA '${yellow("1.23")}')`, ); assertEquals(S("%.[2]*[1]f Yippie!", 1.23, "p"), "%!(BAD PREC 'p') Yippie!"); @@ -663,7 +663,7 @@ Deno.test("testErrors", function (): void { assertEquals(S("%[hallo]s %d %d %d", 1, 2, 3, 4), "%!(BAD INDEX) 2 3 4"); assertEquals( S("%[5]s", 1, 2, 3, 4), - `%!(BAD INDEX)%!(EXTRA '${yellow("2")}' '${yellow("3")}' '${yellow("4")}')` + `%!(BAD INDEX)%!(EXTRA '${yellow("2")}' '${yellow("3")}' '${yellow("4")}')`, ); assertEquals(S("%[5]f"), "%!(BAD INDEX)"); assertEquals(S("%.[5]f"), "%!(BAD INDEX)"); diff --git a/std/fs/_util.ts b/std/fs/_util.ts index bae48c970..6866526cd 100644 --- a/std/fs/_util.ts +++ b/std/fs/_util.ts @@ -9,7 +9,7 @@ import * as path from "../path/mod.ts"; export function isSubdir( src: string, dest: string, - sep: string = path.sep + sep: string = path.sep, ): boolean { if (src === dest) { return false; diff --git a/std/fs/_util_test.ts b/std/fs/_util_test.ts index 48fc33ecd..a05f2cb2d 100644 --- a/std/fs/_util_test.ts +++ b/std/fs/_util_test.ts @@ -28,7 +28,7 @@ Deno.test("_isSubdir", function (): void { assertEquals( isSubdir(src, dest, sep), expected, - `'${src}' should ${expected ? "" : "not"} be parent dir of '${dest}'` + `'${src}' should ${expected ? "" : "not"} be parent dir of '${dest}'`, ); }); }); diff --git a/std/fs/copy.ts b/std/fs/copy.ts index 269340e85..b1b340354 100644 --- a/std/fs/copy.ts +++ b/std/fs/copy.ts @@ -24,7 +24,7 @@ async function ensureValidCopy( src: string, dest: string, options: CopyOptions, - isCopyFolder = false + isCopyFolder = false, ): Promise<Deno.FileInfo | undefined> { let destStat: Deno.FileInfo; @@ -39,7 +39,7 @@ async function ensureValidCopy( if (isCopyFolder && !destStat.isDirectory) { throw new Error( - `Cannot overwrite non-directory '${dest}' with directory '${src}'.` + `Cannot overwrite non-directory '${dest}' with directory '${src}'.`, ); } if (!options.overwrite) { @@ -53,7 +53,7 @@ function ensureValidCopySync( src: string, dest: string, options: CopyOptions, - isCopyFolder = false + isCopyFolder = false, ): Deno.FileInfo | undefined { let destStat: Deno.FileInfo; try { @@ -67,7 +67,7 @@ function ensureValidCopySync( if (isCopyFolder && !destStat.isDirectory) { throw new Error( - `Cannot overwrite non-directory '${dest}' with directory '${src}'.` + `Cannot overwrite non-directory '${dest}' with directory '${src}'.`, ); } if (!options.overwrite) { @@ -81,7 +81,7 @@ function ensureValidCopySync( async function copyFile( src: string, dest: string, - options: CopyOptions + options: CopyOptions, ): Promise<void> { await ensureValidCopy(src, dest, options); await Deno.copyFile(src, dest); @@ -108,7 +108,7 @@ function copyFileSync(src: string, dest: string, options: CopyOptions): void { async function copySymLink( src: string, dest: string, - options: CopyOptions + options: CopyOptions, ): Promise<void> { await ensureValidCopy(src, dest, options); const originSrcFilePath = await Deno.readLink(src); @@ -132,7 +132,7 @@ async function copySymLink( function copySymlinkSync( src: string, dest: string, - options: CopyOptions + options: CopyOptions, ): void { ensureValidCopySync(src, dest, options); const originSrcFilePath = Deno.readLinkSync(src); @@ -157,7 +157,7 @@ function copySymlinkSync( async function copyDir( src: string, dest: string, - options: CopyOptions + options: CopyOptions, ): Promise<void> { const destStat = await ensureValidCopy(src, dest, options, true); @@ -227,7 +227,7 @@ function copyDirSync(src: string, dest: string, options: CopyOptions): void { export async function copy( src: string, dest: string, - options: CopyOptions = {} + options: CopyOptions = {}, ): Promise<void> { src = path.resolve(src); dest = path.resolve(dest); @@ -240,7 +240,7 @@ export async function copy( if (srcStat.isDirectory && isSubdir(src, dest)) { throw new Error( - `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.` + `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`, ); } @@ -266,7 +266,7 @@ export async function copy( export function copySync( src: string, dest: string, - options: CopyOptions = {} + options: CopyOptions = {}, ): void { src = path.resolve(src); dest = path.resolve(dest); @@ -279,7 +279,7 @@ export function copySync( if (srcStat.isDirectory && isSubdir(src, dest)) { throw new Error( - `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.` + `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`, ); } diff --git a/std/fs/copy_test.ts b/std/fs/copy_test.ts index dd9b90ff6..75efd7cc0 100644 --- a/std/fs/copy_test.ts +++ b/std/fs/copy_test.ts @@ -17,7 +17,7 @@ const testdataDir = path.resolve("fs", "testdata"); function testCopy( name: string, cb: (tempDir: string) => Promise<void>, - ignore = false + ignore = false, ): void { Deno.test({ name, @@ -34,7 +34,7 @@ function testCopy( function testCopyIgnore( name: string, - cb: (tempDir: string) => Promise<void> + cb: (tempDir: string) => Promise<void>, ): void { testCopy(name, cb, true); } @@ -60,9 +60,9 @@ testCopy( await assertThrowsAsync( async (): Promise<void> => { await copy(srcFile, destFile); - } + }, ); - } + }, ); testCopy( @@ -75,9 +75,9 @@ testCopy( await copy(srcFile, destFile); }, Error, - "Source and destination cannot be the same." + "Source and destination cannot be the same.", ); - } + }, ); testCopy( @@ -91,12 +91,12 @@ testCopy( assertEquals( await exists(srcFile), true, - `source should exist before copy` + `source should exist before copy`, ); assertEquals( await exists(destFile), false, - "destination should not exist before copy" + "destination should not exist before copy", ); await copy(srcFile, destFile); @@ -105,7 +105,7 @@ testCopy( assertEquals( await exists(destFile), true, - "destination should exist before copy" + "destination should exist before copy", ); const destContent = new TextDecoder().decode(await Deno.readFile(destFile)); @@ -113,7 +113,7 @@ testCopy( assertEquals( srcContent, destContent, - "source and destination should have the same content" + "source and destination should have the same content", ); // Copy again and it should throw an error. @@ -122,7 +122,7 @@ testCopy( await copy(srcFile, destFile); }, Error, - `'${destFile}' already exists.` + `'${destFile}' already exists.`, ); // Modify destination file. @@ -130,7 +130,7 @@ testCopy( assertEquals( new TextDecoder().decode(await Deno.readFile(destFile)), - "txt copy" + "txt copy", ); // Copy again with overwrite option. @@ -139,9 +139,9 @@ testCopy( // Make sure the file has been overwritten. assertEquals( new TextDecoder().decode(await Deno.readFile(destFile)), - "txt" + "txt", ); - } + }, ); // TODO(#6644) This case is ignored because of the issue #5065. @@ -168,7 +168,7 @@ testCopyIgnore( assert(destStatInfo.mtime instanceof Date); assertEquals(destStatInfo.atime, srcStatInfo.atime); assertEquals(destStatInfo.mtime, srcStatInfo.mtime); - } + }, ); testCopy( @@ -184,9 +184,9 @@ testCopy( await copy(srcDir, destDir); }, Error, - `Cannot copy '${srcDir}' to a subdirectory of itself, '${destDir}'.` + `Cannot copy '${srcDir}' to a subdirectory of itself, '${destDir}'.`, ); - } + }, ); testCopy( @@ -203,9 +203,9 @@ testCopy( await copy(srcDir, destDir); }, Error, - `Cannot overwrite non-directory '${destDir}' with directory '${srcDir}'.` + `Cannot overwrite non-directory '${destDir}' with directory '${srcDir}'.`, ); - } + }, ); testCopy( @@ -226,11 +226,11 @@ testCopy( // After copy. The source and destination should have the same content. assertEquals( new TextDecoder().decode(await Deno.readFile(srcFile)), - new TextDecoder().decode(await Deno.readFile(destFile)) + new TextDecoder().decode(await Deno.readFile(destFile)), ); assertEquals( new TextDecoder().decode(await Deno.readFile(srcNestFile)), - new TextDecoder().decode(await Deno.readFile(destNestFile)) + new TextDecoder().decode(await Deno.readFile(destNestFile)), ); // Copy again without overwrite option and it should throw an error. @@ -239,14 +239,14 @@ testCopy( await copy(srcDir, destDir); }, Error, - `'${destDir}' already exists.` + `'${destDir}' already exists.`, ); // Modify the file in the destination directory. await Deno.writeFile(destNestFile, new TextEncoder().encode("nest copy")); assertEquals( new TextDecoder().decode(await Deno.readFile(destNestFile)), - "nest copy" + "nest copy", ); // Copy again with overwrite option. @@ -255,9 +255,9 @@ testCopy( // Make sure the file has been overwritten. assertEquals( new TextDecoder().decode(await Deno.readFile(destNestFile)), - "nest" + "nest", ); - } + }, ); testCopy( @@ -269,7 +269,7 @@ testCopy( assert( (await Deno.lstat(srcLink)).isSymlink, - `'${srcLink}' should be symlink type` + `'${srcLink}' should be symlink type`, ); await copy(srcLink, destLink); @@ -277,7 +277,7 @@ testCopy( const statInfo = await Deno.lstat(destLink); assert(statInfo.isSymlink, `'${destLink}' should be symlink type`); - } + }, ); testCopy( @@ -291,7 +291,7 @@ testCopy( assert( (await Deno.lstat(srcLink)).isSymlink, - `'${srcLink}' should be symlink type` + `'${srcLink}' should be symlink type`, ); await copy(srcLink, destLink); @@ -299,7 +299,7 @@ testCopy( const statInfo = await Deno.lstat(destLink); assert(statInfo.isSymlink); - } + }, ); testCopySync( @@ -310,7 +310,7 @@ testCopySync( assertThrows((): void => { copySync(srcFile, destFile); }); - } + }, ); testCopySync( @@ -338,7 +338,7 @@ testCopySync( // is fixed // assertEquals(destStatInfo.atime, srcStatInfo.atime); // assertEquals(destStatInfo.mtime, srcStatInfo.mtime); - } + }, ); testCopySync( @@ -350,9 +350,9 @@ testCopySync( copySync(srcFile, srcFile); }, Error, - "Source and destination cannot be the same." + "Source and destination cannot be the same.", ); - } + }, ); testCopySync("[fs] copy file synchronously", (tempDir: string): void => { @@ -379,7 +379,7 @@ testCopySync("[fs] copy file synchronously", (tempDir: string): void => { copySync(srcFile, destFile); }, Error, - `'${destFile}' already exists.` + `'${destFile}' already exists.`, ); // Modify destination file. @@ -387,7 +387,7 @@ testCopySync("[fs] copy file synchronously", (tempDir: string): void => { assertEquals( new TextDecoder().decode(Deno.readFileSync(destFile)), - "txt copy" + "txt copy", ); // Copy again with overwrite option. @@ -410,9 +410,9 @@ testCopySync( copySync(srcDir, destDir); }, Error, - `Cannot copy '${srcDir}' to a subdirectory of itself, '${destDir}'.` + `Cannot copy '${srcDir}' to a subdirectory of itself, '${destDir}'.`, ); - } + }, ); testCopySync( @@ -430,9 +430,9 @@ testCopySync( copySync(srcDir, destDir); }, Error, - `Cannot overwrite non-directory '${destDir}' with directory '${srcDir}'.` + `Cannot overwrite non-directory '${destDir}' with directory '${srcDir}'.`, ); - } + }, ); testCopySync("[fs] copy directory synchronously", (tempDir: string): void => { @@ -451,11 +451,11 @@ testCopySync("[fs] copy directory synchronously", (tempDir: string): void => { // After copy. The source and destination should have the same content. assertEquals( new TextDecoder().decode(Deno.readFileSync(srcFile)), - new TextDecoder().decode(Deno.readFileSync(destFile)) + new TextDecoder().decode(Deno.readFileSync(destFile)), ); assertEquals( new TextDecoder().decode(Deno.readFileSync(srcNestFile)), - new TextDecoder().decode(Deno.readFileSync(destNestFile)) + new TextDecoder().decode(Deno.readFileSync(destNestFile)), ); // Copy again without overwrite option and it should throw an error. @@ -464,14 +464,14 @@ testCopySync("[fs] copy directory synchronously", (tempDir: string): void => { copySync(srcDir, destDir); }, Error, - `'${destDir}' already exists.` + `'${destDir}' already exists.`, ); // Modify the file in the destination directory. Deno.writeFileSync(destNestFile, new TextEncoder().encode("nest copy")); assertEquals( new TextDecoder().decode(Deno.readFileSync(destNestFile)), - "nest copy" + "nest copy", ); // Copy again with overwrite option. @@ -480,7 +480,7 @@ testCopySync("[fs] copy directory synchronously", (tempDir: string): void => { // Make sure the file has been overwritten. assertEquals( new TextDecoder().decode(Deno.readFileSync(destNestFile)), - "nest" + "nest", ); }); @@ -493,7 +493,7 @@ testCopySync( assert( Deno.lstatSync(srcLink).isSymlink, - `'${srcLink}' should be symlink type` + `'${srcLink}' should be symlink type`, ); copySync(srcLink, destLink); @@ -501,7 +501,7 @@ testCopySync( const statInfo = Deno.lstatSync(destLink); assert(statInfo.isSymlink, `'${destLink}' should be symlink type`); - } + }, ); testCopySync( @@ -515,7 +515,7 @@ testCopySync( assert( Deno.lstatSync(srcLink).isSymlink, - `'${srcLink}' should be symlink type` + `'${srcLink}' should be symlink type`, ); copySync(srcLink, destLink); @@ -523,5 +523,5 @@ testCopySync( const statInfo = Deno.lstatSync(destLink); assert(statInfo.isSymlink); - } + }, ); diff --git a/std/fs/empty_dir_test.ts b/std/fs/empty_dir_test.ts index e0e4c58fa..6c06c9d52 100644 --- a/std/fs/empty_dir_test.ts +++ b/std/fs/empty_dir_test.ts @@ -71,14 +71,14 @@ Deno.test("emptyDirIfItExist", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await Deno.stat(testNestDir); - } + }, ); // test file have been removed await assertThrowsAsync( async (): Promise<void> => { await Deno.stat(testDirFile); - } + }, ); } finally { // remote test dir @@ -199,7 +199,7 @@ for (const s of scenes) { await Deno.writeFile( path.join(testfolder, "child.txt"), - new TextEncoder().encode("hello world") + new TextEncoder().encode("hello world"), ); try { @@ -215,7 +215,10 @@ for (const s of scenes) { } args.push( - path.join(testdataDir, s.async ? "empty_dir.ts" : "empty_dir_sync.ts") + path.join( + testdataDir, + s.async ? "empty_dir.ts" : "empty_dir_sync.ts", + ), ); args.push("testfolder"); diff --git a/std/fs/ensure_dir.ts b/std/fs/ensure_dir.ts index 961476028..f5b5cd309 100644 --- a/std/fs/ensure_dir.ts +++ b/std/fs/ensure_dir.ts @@ -11,7 +11,9 @@ export async function ensureDir(dir: string): Promise<void> { const fileInfo = await Deno.lstat(dir); if (!fileInfo.isDirectory) { throw new Error( - `Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'` + `Ensure path exists, expected 'dir', got '${ + getFileInfoType(fileInfo) + }'`, ); } } catch (err) { @@ -34,7 +36,9 @@ export function ensureDirSync(dir: string): void { const fileInfo = Deno.lstatSync(dir); if (!fileInfo.isDirectory) { throw new Error( - `Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'` + `Ensure path exists, expected 'dir', got '${ + getFileInfoType(fileInfo) + }'`, ); } } catch (err) { diff --git a/std/fs/ensure_dir_test.ts b/std/fs/ensure_dir_test.ts index d70f5eb1a..c24e14d1a 100644 --- a/std/fs/ensure_dir_test.ts +++ b/std/fs/ensure_dir_test.ts @@ -17,7 +17,7 @@ Deno.test("ensureDirIfItNotExist", async function (): Promise<void> { await Deno.stat(testDir).then((): void => { throw new Error("test dir should exists."); }); - } + }, ); await Deno.remove(baseDir, { recursive: true }); @@ -48,7 +48,7 @@ Deno.test("ensureDirIfItExist", async function (): Promise<void> { await Deno.stat(testDir).then((): void => { throw new Error("test dir should still exists."); }); - } + }, ); await Deno.remove(baseDir, { recursive: true }); @@ -82,7 +82,7 @@ Deno.test("ensureDirIfItAsFile", async function (): Promise<void> { await ensureDir(testFile); }, Error, - `Ensure path exists, expected 'dir', got 'file'` + `Ensure path exists, expected 'dir', got 'file'`, ); await Deno.remove(baseDir, { recursive: true }); @@ -99,7 +99,7 @@ Deno.test("ensureDirSyncIfItAsFile", function (): void { ensureDirSync(testFile); }, Error, - `Ensure path exists, expected 'dir', got 'file'` + `Ensure path exists, expected 'dir', got 'file'`, ); Deno.removeSync(baseDir, { recursive: true }); diff --git a/std/fs/ensure_file.ts b/std/fs/ensure_file.ts index b36379b3d..41565795c 100644 --- a/std/fs/ensure_file.ts +++ b/std/fs/ensure_file.ts @@ -17,7 +17,7 @@ export async function ensureFile(filePath: string): Promise<void> { const stat = await Deno.lstat(filePath); if (!stat.isFile) { throw new Error( - `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'` + `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`, ); } } catch (err) { @@ -48,7 +48,7 @@ export function ensureFileSync(filePath: string): void { const stat = Deno.lstatSync(filePath); if (!stat.isFile) { throw new Error( - `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'` + `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`, ); } } catch (err) { diff --git a/std/fs/ensure_file_test.ts b/std/fs/ensure_file_test.ts index 1e51db451..d87de0051 100644 --- a/std/fs/ensure_file_test.ts +++ b/std/fs/ensure_file_test.ts @@ -16,7 +16,7 @@ Deno.test("ensureFileIfItNotExist", async function (): Promise<void> { await Deno.stat(testFile).then((): void => { throw new Error("test file should exists."); }); - } + }, ); await Deno.remove(testDir, { recursive: true }); @@ -50,7 +50,7 @@ Deno.test("ensureFileIfItExist", async function (): Promise<void> { await Deno.stat(testFile).then((): void => { throw new Error("test file should exists."); }); - } + }, ); await Deno.remove(testDir, { recursive: true }); @@ -83,7 +83,7 @@ Deno.test("ensureFileIfItExistAsDir", async function (): Promise<void> { await ensureFile(testDir); }, Error, - `Ensure path exists, expected 'file', got 'dir'` + `Ensure path exists, expected 'file', got 'dir'`, ); await Deno.remove(testDir, { recursive: true }); @@ -99,7 +99,7 @@ Deno.test("ensureFileSyncIfItExistAsDir", function (): void { ensureFileSync(testDir); }, Error, - `Ensure path exists, expected 'file', got 'dir'` + `Ensure path exists, expected 'file', got 'dir'`, ); Deno.removeSync(testDir, { recursive: true }); diff --git a/std/fs/ensure_link.ts b/std/fs/ensure_link.ts index f446df781..ea8501b03 100644 --- a/std/fs/ensure_link.ts +++ b/std/fs/ensure_link.ts @@ -17,7 +17,7 @@ export async function ensureLink(src: string, dest: string): Promise<void> { const destFilePathType = getFileInfoType(destStatInfo); if (destFilePathType !== "file") { throw new Error( - `Ensure path exists, expected 'file', got '${destFilePathType}'` + `Ensure path exists, expected 'file', got '${destFilePathType}'`, ); } return; @@ -41,7 +41,7 @@ export function ensureLinkSync(src: string, dest: string): void { const destFilePathType = getFileInfoType(destStatInfo); if (destFilePathType !== "file") { throw new Error( - `Ensure path exists, expected 'file', got '${destFilePathType}'` + `Ensure path exists, expected 'file', got '${destFilePathType}'`, ); } return; diff --git a/std/fs/ensure_link_test.ts b/std/fs/ensure_link_test.ts index e05d3a648..d4f2f30c2 100644 --- a/std/fs/ensure_link_test.ts +++ b/std/fs/ensure_link_test.ts @@ -19,7 +19,7 @@ Deno.test("ensureLinkIfItNotExist", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await ensureLink(testFile, linkFile); - } + }, ); await Deno.remove(destDir, { recursive: true }); @@ -59,10 +59,10 @@ Deno.test("ensureLinkIfItExist", async function (): Promise<void> { await Deno.writeFile(testFile, new TextEncoder().encode("123")); const testFileContent1 = new TextDecoder().decode( - await Deno.readFile(testFile) + await Deno.readFile(testFile), ); const linkFileContent1 = new TextDecoder().decode( - await Deno.readFile(testFile) + await Deno.readFile(testFile), ); assertEquals(testFileContent1, "123"); @@ -72,10 +72,10 @@ Deno.test("ensureLinkIfItExist", async function (): Promise<void> { await Deno.writeFile(testFile, new TextEncoder().encode("abc")); const testFileContent2 = new TextDecoder().decode( - await Deno.readFile(testFile) + await Deno.readFile(testFile), ); const linkFileContent2 = new TextDecoder().decode( - await Deno.readFile(testFile) + await Deno.readFile(testFile), ); assertEquals(testFileContent2, "abc"); @@ -107,10 +107,10 @@ Deno.test("ensureLinkSyncIfItExist", function (): void { Deno.writeFileSync(testFile, new TextEncoder().encode("123")); const testFileContent1 = new TextDecoder().decode( - Deno.readFileSync(testFile) + Deno.readFileSync(testFile), ); const linkFileContent1 = new TextDecoder().decode( - Deno.readFileSync(testFile) + Deno.readFileSync(testFile), ); assertEquals(testFileContent1, "123"); @@ -120,10 +120,10 @@ Deno.test("ensureLinkSyncIfItExist", function (): void { Deno.writeFileSync(testFile, new TextEncoder().encode("abc")); const testFileContent2 = new TextDecoder().decode( - Deno.readFileSync(testFile) + Deno.readFileSync(testFile), ); const linkFileContent2 = new TextDecoder().decode( - Deno.readFileSync(testFile) + Deno.readFileSync(testFile), ); assertEquals(testFileContent2, "abc"); @@ -143,7 +143,7 @@ Deno.test("ensureLinkDirectoryIfItExist", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await ensureLink(testDir, linkDir); - } + }, // "Operation not permitted (os error 1)" // throw an local matching test // "Access is denied. (os error 5)" // throw in CI ); @@ -162,7 +162,7 @@ Deno.test("ensureLinkSyncDirectoryIfItExist", function (): void { assertThrows( (): void => { ensureLinkSync(testDir, linkDir); - } + }, // "Operation not permitted (os error 1)" // throw an local matching test // "Access is denied. (os error 5)" // throw in CI ); diff --git a/std/fs/ensure_symlink.ts b/std/fs/ensure_symlink.ts index be96d5b13..03a8db930 100644 --- a/std/fs/ensure_symlink.ts +++ b/std/fs/ensure_symlink.ts @@ -20,7 +20,7 @@ export async function ensureSymlink(src: string, dest: string): Promise<void> { const destFilePathType = getFileInfoType(destStatInfo); if (destFilePathType !== "symlink") { throw new Error( - `Ensure path exists, expected 'symlink', got '${destFilePathType}'` + `Ensure path exists, expected 'symlink', got '${destFilePathType}'`, ); } return; @@ -53,7 +53,7 @@ export function ensureSymlinkSync(src: string, dest: string): void { const destFilePathType = getFileInfoType(destStatInfo); if (destFilePathType !== "symlink") { throw new Error( - `Ensure path exists, expected 'symlink', got '${destFilePathType}'` + `Ensure path exists, expected 'symlink', got '${destFilePathType}'`, ); } return; diff --git a/std/fs/ensure_symlink_test.ts b/std/fs/ensure_symlink_test.ts index d90495cbf..bc0741fed 100644 --- a/std/fs/ensure_symlink_test.ts +++ b/std/fs/ensure_symlink_test.ts @@ -17,7 +17,7 @@ Deno.test("ensureSymlinkIfItNotExist", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await ensureSymlink(testFile, path.join(testDir, "test1.txt")); - } + }, ); await assertThrowsAsync( @@ -25,7 +25,7 @@ Deno.test("ensureSymlinkIfItNotExist", async function (): Promise<void> { await Deno.stat(testFile).then((): void => { throw new Error("test file should exists."); }); - } + }, ); }); diff --git a/std/fs/exists_test.ts b/std/fs/exists_test.ts index 8b584d861..3c280f4c4 100644 --- a/std/fs/exists_test.ts +++ b/std/fs/exists_test.ts @@ -8,7 +8,7 @@ const testdataDir = path.resolve("fs", "testdata"); Deno.test("[fs] existsFile", async function (): Promise<void> { assertEquals( await exists(path.join(testdataDir, "not_exist_file.ts")), - false + false, ); assertEquals(await existsSync(path.join(testdataDir, "0.ts")), true); }); @@ -21,7 +21,7 @@ Deno.test("[fs] existsFileSync", function (): void { Deno.test("[fs] existsDirectory", async function (): Promise<void> { assertEquals( await exists(path.join(testdataDir, "not_exist_directory")), - false + false, ); assertEquals(existsSync(testdataDir), true); }); @@ -29,7 +29,7 @@ Deno.test("[fs] existsDirectory", async function (): Promise<void> { Deno.test("[fs] existsDirectorySync", function (): void { assertEquals( existsSync(path.join(testdataDir, "not_exist_directory")), - false + false, ); assertEquals(existsSync(testdataDir), true); }); diff --git a/std/fs/expand_glob.ts b/std/fs/expand_glob.ts index 8a4b0ed03..6d1f883b5 100644 --- a/std/fs/expand_glob.ts +++ b/std/fs/expand_glob.ts @@ -77,7 +77,7 @@ export async function* expandGlob( includeDirs = true, extended = false, globstar = false, - }: ExpandGlobOptions = {} + }: ExpandGlobOptions = {}, ): AsyncIterableIterator<WalkEntry> { const globOptions: GlobOptions = { extended, globstar }; const absRoot = isAbsolute(root) @@ -110,7 +110,7 @@ export async function* expandGlob( async function* advanceMatch( walkInfo: WalkEntry, - globSegment: string + globSegment: string, ): AsyncIterableIterator<WalkEntry> { if (!walkInfo.isDirectory) { return; @@ -135,7 +135,7 @@ export async function* expandGlob( match: [ globToRegExp( joinGlobs([walkInfo.path, globSegment], globOptions), - globOptions + globOptions, ), ], skip: excludePatterns, @@ -156,12 +156,12 @@ export async function* expandGlob( } if (hasTrailingSep) { currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => entry.isDirectory + (entry: WalkEntry): boolean => entry.isDirectory, ); } if (!includeDirs) { currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => !entry.isDirectory + (entry: WalkEntry): boolean => !entry.isDirectory, ); } yield* currentMatches; @@ -184,7 +184,7 @@ export function* expandGlobSync( includeDirs = true, extended = false, globstar = false, - }: ExpandGlobOptions = {} + }: ExpandGlobOptions = {}, ): IterableIterator<WalkEntry> { const globOptions: GlobOptions = { extended, globstar }; const absRoot = isAbsolute(root) @@ -217,7 +217,7 @@ export function* expandGlobSync( function* advanceMatch( walkInfo: WalkEntry, - globSegment: string + globSegment: string, ): IterableIterator<WalkEntry> { if (!walkInfo.isDirectory) { return; @@ -242,7 +242,7 @@ export function* expandGlobSync( match: [ globToRegExp( joinGlobs([walkInfo.path, globSegment], globOptions), - globOptions + globOptions, ), ], skip: excludePatterns, @@ -263,12 +263,12 @@ export function* expandGlobSync( } if (hasTrailingSep) { currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => entry.isDirectory + (entry: WalkEntry): boolean => entry.isDirectory, ); } if (!includeDirs) { currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => !entry.isDirectory + (entry: WalkEntry): boolean => !entry.isDirectory, ); } yield* currentMatches; diff --git a/std/fs/expand_glob_test.ts b/std/fs/expand_glob_test.ts index 1eec4df42..8b4a90754 100644 --- a/std/fs/expand_glob_test.ts +++ b/std/fs/expand_glob_test.ts @@ -19,7 +19,7 @@ import { async function expandGlobArray( globString: string, - options: ExpandGlobOptions + options: ExpandGlobOptions, ): Promise<string[]> { const paths: string[] = []; for await (const { path } of expandGlob(globString, options)) { @@ -27,7 +27,7 @@ async function expandGlobArray( } paths.sort(); const pathsSync = [...expandGlobSync(globString, options)].map( - ({ path }): string => path + ({ path }): string => path, ); pathsSync.sort(); assertEquals(paths, pathsSync); @@ -36,7 +36,7 @@ async function expandGlobArray( assert(path.startsWith(root)); } const relativePaths = paths.map( - (path: string): string => relative(root, path) || "." + (path: string): string => relative(root, path) || ".", ); relativePaths.sort(); return relativePaths; @@ -98,7 +98,7 @@ Deno.test("expandGlobGlobstar", async function (): Promise<void> { const options = { ...EG_OPTIONS, globstar: true }; assertEquals( await expandGlobArray(joinGlobs(["**", "abc"], options), options), - ["abc", join("subdir", "abc")] + ["abc", join("subdir", "abc")], ); }); @@ -106,7 +106,7 @@ Deno.test("expandGlobGlobstarParent", async function (): Promise<void> { const options = { ...EG_OPTIONS, globstar: true }; assertEquals( await expandGlobArray(joinGlobs(["subdir", "**", ".."], options), options), - ["."] + ["."], ); }); @@ -127,7 +127,7 @@ Deno.test("expandGlobPermError", async function (): Promise<void> { assertEquals(decode(await p.output()), ""); assertStringContains( decode(await p.stderrOutput()), - "Uncaught PermissionDenied" + "Uncaught PermissionDenied", ); p.close(); }); diff --git a/std/fs/move.ts b/std/fs/move.ts index 6aeca29ea..421ca0771 100644 --- a/std/fs/move.ts +++ b/std/fs/move.ts @@ -10,13 +10,13 @@ interface MoveOptions { export async function move( src: string, dest: string, - { overwrite = false }: MoveOptions = {} + { overwrite = false }: MoveOptions = {}, ): Promise<void> { const srcStat = await Deno.stat(src); if (srcStat.isDirectory && isSubdir(src, dest)) { throw new Error( - `Cannot move '${src}' to a subdirectory of itself, '${dest}'.` + `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`, ); } @@ -39,13 +39,13 @@ export async function move( export function moveSync( src: string, dest: string, - { overwrite = false }: MoveOptions = {} + { overwrite = false }: MoveOptions = {}, ): void { const srcStat = Deno.statSync(src); if (srcStat.isDirectory && isSubdir(src, dest)) { throw new Error( - `Cannot move '${src}' to a subdirectory of itself, '${dest}'.` + `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`, ); } diff --git a/std/fs/move_test.ts b/std/fs/move_test.ts index fdf451125..73a96ce46 100644 --- a/std/fs/move_test.ts +++ b/std/fs/move_test.ts @@ -19,7 +19,7 @@ Deno.test("moveDirectoryIfSrcNotExists", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await move(srcDir, destDir); - } + }, ); }); @@ -36,7 +36,7 @@ Deno.test("moveDirectoryIfDestNotExists", async function (): Promise<void> { throw new Error("should not throw error"); }, Error, - "should not throw error" + "should not throw error", ); await Deno.remove(destDir); @@ -57,11 +57,11 @@ Deno.test( throw new Error("should not throw error"); }, Error, - "should not throw error" + "should not throw error", ); await Deno.remove(destDir); - } + }, ); Deno.test("moveFileIfSrcNotExists", async function (): Promise<void> { @@ -72,7 +72,7 @@ Deno.test("moveFileIfSrcNotExists", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await move(srcFile, destFile); - } + }, ); }); @@ -103,7 +103,7 @@ Deno.test("moveFileIfDestExists", async function (): Promise<void> { await move(srcFile, destFile); }, Error, - "dest already exists" + "dest already exists", ); // move again with overwrite @@ -113,7 +113,7 @@ Deno.test("moveFileIfDestExists", async function (): Promise<void> { throw new Error("should not throw error"); }, Error, - "should not throw error" + "should not throw error", ); assertEquals(await exists(srcFile), false); @@ -144,7 +144,7 @@ Deno.test("moveDirectory", async function (): Promise<void> { assertEquals(await exists(destFile), true); const destFileContent = new TextDecoder().decode( - await Deno.readFile(destFile) + await Deno.readFile(destFile), ); assertEquals(destFileContent, "src"); @@ -179,12 +179,12 @@ Deno.test( assertEquals(await exists(destFile), true); const destFileContent = new TextDecoder().decode( - await Deno.readFile(destFile) + await Deno.readFile(destFile), ); assertEquals(destFileContent, "src"); await Deno.remove(destDir, { recursive: true }); - } + }, ); Deno.test("moveIntoSubDir", async function (): Promise<void> { @@ -198,7 +198,7 @@ Deno.test("moveIntoSubDir", async function (): Promise<void> { await move(srcDir, destDir); }, Error, - `Cannot move '${srcDir}' to a subdirectory of itself, '${destDir}'.` + `Cannot move '${srcDir}' to a subdirectory of itself, '${destDir}'.`, ); await Deno.remove(srcDir, { recursive: true }); }); @@ -225,7 +225,7 @@ Deno.test("moveSyncDirectoryIfDestNotExists", function (): void { throw new Error("should not throw error"); }, Error, - "should not throw error" + "should not throw error", ); Deno.removeSync(destDir); @@ -244,7 +244,7 @@ Deno.test("moveSyncDirectoryIfDestNotExistsAndOverwrite", function (): void { throw new Error("should not throw error"); }, Error, - "should not throw error" + "should not throw error", ); Deno.removeSync(destDir); @@ -286,7 +286,7 @@ Deno.test("moveSyncFileIfDestExists", function (): void { moveSync(srcFile, destFile); }, Error, - "dest already exists" + "dest already exists", ); // move again with overwrite @@ -296,7 +296,7 @@ Deno.test("moveSyncFileIfDestExists", function (): void { throw new Error("should not throw error"); }, Error, - "should not throw error" + "should not throw error", ); assertEquals(existsSync(srcFile), false); @@ -368,7 +368,7 @@ Deno.test("moveSyncIntoSubDir", function (): void { moveSync(srcDir, destDir); }, Error, - `Cannot move '${srcDir}' to a subdirectory of itself, '${destDir}'.` + `Cannot move '${srcDir}' to a subdirectory of itself, '${destDir}'.`, ); Deno.removeSync(srcDir, { recursive: true }); }); diff --git a/std/fs/read_file_str.ts b/std/fs/read_file_str.ts index 7420183e2..9aa50f15a 100644 --- a/std/fs/read_file_str.ts +++ b/std/fs/read_file_str.ts @@ -12,7 +12,7 @@ export interface ReadOptions { */ export function readFileStrSync( filename: string, - opts: ReadOptions = {} + opts: ReadOptions = {}, ): string { const decoder = new TextDecoder(opts.encoding); return decoder.decode(Deno.readFileSync(filename)); @@ -26,7 +26,7 @@ export function readFileStrSync( */ export async function readFileStr( filename: string, - opts: ReadOptions = {} + opts: ReadOptions = {}, ): Promise<string> { const decoder = new TextDecoder(opts.encoding); return decoder.decode(await Deno.readFile(filename)); diff --git a/std/fs/read_json_test.ts b/std/fs/read_json_test.ts index edc5d8800..c910c6334 100644 --- a/std/fs/read_json_test.ts +++ b/std/fs/read_json_test.ts @@ -15,7 +15,7 @@ Deno.test("readJsonFileNotExists", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await readJson(emptyJsonFile); - } + }, ); }); @@ -25,7 +25,7 @@ Deno.test("readEmptyJsonFile", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await readJson(emptyJsonFile); - } + }, ); }); @@ -35,7 +35,7 @@ Deno.test("readInvalidJsonFile", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { await readJson(invalidJsonFile); - } + }, ); }); diff --git a/std/fs/walk.ts b/std/fs/walk.ts index 0292b77ef..8f2196833 100644 --- a/std/fs/walk.ts +++ b/std/fs/walk.ts @@ -44,7 +44,7 @@ function include( path: string, exts?: string[], match?: RegExp[], - skip?: RegExp[] + skip?: RegExp[], ): boolean { if (exts && !exts.some((ext): boolean => path.endsWith(ext))) { return false; @@ -91,7 +91,7 @@ export async function* walk( exts = undefined, match = undefined, skip = undefined, - }: WalkOptions = {} + }: WalkOptions = {}, ): AsyncIterableIterator<WalkEntry> { if (maxDepth < 0) { return; @@ -144,7 +144,7 @@ export function* walkSync( exts = undefined, match = undefined, skip = undefined, - }: WalkOptions = {} + }: WalkOptions = {}, ): IterableIterator<WalkEntry> { if (maxDepth < 0) { return; diff --git a/std/fs/walk_test.ts b/std/fs/walk_test.ts index 52fd4ff57..df4525b95 100644 --- a/std/fs/walk_test.ts +++ b/std/fs/walk_test.ts @@ -4,7 +4,7 @@ import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts"; export function testWalk( setup: (arg0: string) => void | Promise<void>, t: () => void | Promise<void>, - ignore = false + ignore = false, ): void { const name = t.name; async function fn(): Promise<void> { @@ -28,7 +28,7 @@ function normalize({ path }: WalkEntry): string { export async function walkArray( root: string, - options: WalkOptions = {} + options: WalkOptions = {}, ): Promise<string[]> { const arr: string[] = []; for await (const w of walk(root, { ...options })) { @@ -59,7 +59,7 @@ testWalk( async function emptyDir(): Promise<void> { const arr = await walkArray("."); assertEquals(arr, [".", "empty"]); - } + }, ); testWalk( @@ -69,7 +69,7 @@ testWalk( async function singleFile(): Promise<void> { const arr = await walkArray("."); assertEquals(arr, [".", "x"]); - } + }, ); testWalk( @@ -86,7 +86,7 @@ testWalk( count += 1; } assertEquals(count, 4); - } + }, ); testWalk( @@ -97,7 +97,7 @@ testWalk( async function nestedSingleFile(): Promise<void> { const arr = await walkArray("."); assertEquals(arr, [".", "a", "a/x"]); - } + }, ); testWalk( @@ -111,7 +111,7 @@ testWalk( assertEquals(arr3, [".", "a", "a/b", "a/b/c"]); const arr5 = await walkArray(".", { maxDepth: 5 }); assertEquals(arr5, [".", "a", "a/b", "a/b/c", "a/b/c/d", "a/b/c/d/x"]); - } + }, ); testWalk( @@ -124,7 +124,7 @@ testWalk( assertReady(4); const arr = await walkArray(".", { includeDirs: false }); assertEquals(arr, ["a", "b/c"]); - } + }, ); testWalk( @@ -137,7 +137,7 @@ testWalk( assertReady(4); const arr = await walkArray(".", { includeFiles: false }); assertEquals(arr, [".", "b"]); - } + }, ); testWalk( @@ -149,7 +149,7 @@ testWalk( assertReady(3); const arr = await walkArray(".", { exts: [".ts"] }); assertEquals(arr, ["x.ts"]); - } + }, ); testWalk( @@ -162,7 +162,7 @@ testWalk( assertReady(4); const arr = await walkArray(".", { exts: [".rs", ".ts"] }); assertEquals(arr, ["x.ts", "y.rs"]); - } + }, ); testWalk( @@ -174,7 +174,7 @@ testWalk( assertReady(3); const arr = await walkArray(".", { match: [/x/] }); assertEquals(arr, ["x"]); - } + }, ); testWalk( @@ -187,7 +187,7 @@ testWalk( assertReady(4); const arr = await walkArray(".", { match: [/x/, /y/] }); assertEquals(arr, ["x", "y"]); - } + }, ); testWalk( @@ -199,7 +199,7 @@ testWalk( assertReady(3); const arr = await walkArray(".", { skip: [/x/] }); assertEquals(arr, [".", "y"]); - } + }, ); testWalk( @@ -212,7 +212,7 @@ testWalk( assertReady(4); const arr = await walkArray(".", { skip: [/x/, /y/] }); assertEquals(arr, [".", "z"]); - } + }, ); testWalk( @@ -227,7 +227,7 @@ testWalk( assertReady(6); const arr = await walkArray("b"); assertEquals(arr, ["b", "b/z"]); - } + }, ); testWalk( @@ -236,7 +236,7 @@ testWalk( await assertThrowsAsync(async () => { await walkArray("nonexistent"); }, Deno.errors.NotFound); - } + }, ); testWalk( @@ -258,5 +258,5 @@ testWalk( assertEquals(arr.length, 3); assert(arr.some((f): boolean => f.endsWith("/b/z"))); }, - true + true, ); diff --git a/std/fs/write_file_str.ts b/std/fs/write_file_str.ts index 670399dcc..bf972f204 100644 --- a/std/fs/write_file_str.ts +++ b/std/fs/write_file_str.ts @@ -21,7 +21,7 @@ export function writeFileStrSync(filename: string, content: string): void { */ export async function writeFileStr( filename: string, - content: string + content: string, ): Promise<void> { const encoder = new TextEncoder(); await Deno.writeFile(filename, encoder.encode(content)); diff --git a/std/fs/write_json.ts b/std/fs/write_json.ts index 28eb80d44..015957bba 100644 --- a/std/fs/write_json.ts +++ b/std/fs/write_json.ts @@ -12,7 +12,7 @@ export async function writeJson( filePath: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any object: any, - options: WriteJsonOptions = {} + options: WriteJsonOptions = {}, ): Promise<void> { let contentRaw = ""; @@ -20,7 +20,7 @@ export async function writeJson( contentRaw = JSON.stringify( object, options.replacer as string[], - options.spaces + options.spaces, ); } catch (err) { err.message = `${filePath}: ${err.message}`; @@ -35,7 +35,7 @@ export function writeJsonSync( filePath: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any object: any, - options: WriteJsonOptions = {} + options: WriteJsonOptions = {}, ): void { let contentRaw = ""; @@ -43,7 +43,7 @@ export function writeJsonSync( contentRaw = JSON.stringify( object, options.replacer as string[], - options.spaces + options.spaces, ); } catch (err) { err.message = `${filePath}: ${err.message}`; diff --git a/std/fs/write_json_test.ts b/std/fs/write_json_test.ts index 45d27c4f1..c22bd7bf1 100644 --- a/std/fs/write_json_test.ts +++ b/std/fs/write_json_test.ts @@ -18,7 +18,7 @@ Deno.test("writeJsonIfNotExists", async function (): Promise<void> { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = await Deno.readFile(notExistsJsonFile); @@ -39,7 +39,7 @@ Deno.test("writeJsonIfExists", async function (): Promise<void> { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = await Deno.readFile(existsJsonFile); @@ -52,7 +52,7 @@ Deno.test("writeJsonIfExists", async function (): Promise<void> { Deno.test("writeJsonIfExistsAnInvalidJson", async function (): Promise<void> { const existsInvalidJsonFile = path.join( testdataDir, - "file_write_invalid.json" + "file_write_invalid.json", ); const invalidJsonContent = new TextEncoder().encode("[123}"); @@ -64,7 +64,7 @@ Deno.test("writeJsonIfExistsAnInvalidJson", async function (): Promise<void> { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = await Deno.readFile(existsInvalidJsonFile); @@ -86,7 +86,7 @@ Deno.test("writeJsonWithSpaces", async function (): Promise<void> { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = await Deno.readFile(existsJsonFile); @@ -109,12 +109,12 @@ Deno.test("writeJsonWithReplacer", async function (): Promise<void> { { a: "1", b: "2", c: "3" }, { replacer: ["a"], - } + }, ); throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = await Deno.readFile(existsJsonFile); @@ -133,7 +133,7 @@ Deno.test("writeJsonSyncIfNotExists", function (): void { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = Deno.readFileSync(notExistsJsonFile); @@ -154,7 +154,7 @@ Deno.test("writeJsonSyncIfExists", function (): void { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = Deno.readFileSync(existsJsonFile); @@ -167,7 +167,7 @@ Deno.test("writeJsonSyncIfExists", function (): void { Deno.test("writeJsonSyncIfExistsAnInvalidJson", function (): void { const existsInvalidJsonFile = path.join( testdataDir, - "file_write_invalid_sync.json" + "file_write_invalid_sync.json", ); const invalidJsonContent = new TextEncoder().encode("[123}"); @@ -179,7 +179,7 @@ Deno.test("writeJsonSyncIfExistsAnInvalidJson", function (): void { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = Deno.readFileSync(existsInvalidJsonFile); @@ -201,7 +201,7 @@ Deno.test("writeJsonWithSpaces", function (): void { throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = Deno.readFileSync(existsJsonFile); @@ -214,7 +214,7 @@ Deno.test("writeJsonWithSpaces", function (): void { Deno.test("writeJsonWithReplacer", function (): void { const existsJsonFile = path.join( testdataDir, - "file_write_replacer_sync.json" + "file_write_replacer_sync.json", ); const invalidJsonContent = new TextEncoder().encode(); @@ -227,12 +227,12 @@ Deno.test("writeJsonWithReplacer", function (): void { { a: "1", b: "2", c: "3" }, { replacer: ["a"], - } + }, ); throw new Error("should write success"); }, Error, - "should write success" + "should write success", ); const content = Deno.readFileSync(existsJsonFile); diff --git a/std/hash/_fnv/util.ts b/std/hash/_fnv/util.ts index 3d1cb5bac..096b70815 100644 --- a/std/hash/_fnv/util.ts +++ b/std/hash/_fnv/util.ts @@ -45,7 +45,7 @@ export function mul32(a: number, b: number): number { */ export function mul64( [ah, al]: [number, number], - [bh, bl]: [number, number] + [bh, bl]: [number, number], ): [number, number] { const [n, c] = mul32WithCarry(al, bl); return [n32(mul32(al, bh) + mul32(ah, bl) + c), n]; diff --git a/std/hash/hash_test.ts b/std/hash/hash_test.ts index 5169c2107..4d7d7465d 100644 --- a/std/hash/hash_test.ts +++ b/std/hash/hash_test.ts @@ -311,6 +311,6 @@ Deno.test("[hash/double_digest] testDoubleDigest", () => { assertEquals(h1, h2); }, Error, - "hash: already digested" + "hash: already digested", ); }); diff --git a/std/hash/sha1.ts b/std/hash/sha1.ts index e55b5e8d3..6a79db27b 100644 --- a/std/hash/sha1.ts +++ b/std/hash/sha1.ts @@ -33,6 +33,7 @@ export class Sha1 { constructor(sharedMemory = false) { if (sharedMemory) { + // deno-fmt-ignore blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; this.#blocks = blocks; } else { @@ -70,6 +71,7 @@ export class Sha1 { if (this.#hashed) { this.#hashed = false; blocks[0] = this.#block; + // deno-fmt-ignore blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } @@ -90,8 +92,7 @@ export class Sha1 { blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { - code = - 0x10000 + + code = 0x10000 + (((code & 0x3ff) << 10) | (msg.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; @@ -134,6 +135,7 @@ export class Sha1 { this.hash(); } blocks[0] = this.#block; + // deno-fmt-ignore blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } blocks[14] = (this.#hBytes << 3) | (this.#bytes >>> 29); diff --git a/std/hash/sha1_test.ts b/std/hash/sha1_test.ts index 2c78bb1c8..25571947f 100644 --- a/std/hash/sha1_test.ts +++ b/std/hash/sha1_test.ts @@ -16,7 +16,6 @@ function toHexString(value: number[] | ArrayBuffer): string { return hex; } -// prettier-ignore // deno-fmt-ignore const fixtures: { sha1: Record<string, Record<string, Message>>; @@ -74,10 +73,9 @@ for (const method of methods) { fn() { const algorithm = new Sha1(); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -94,10 +92,9 @@ for (const method of methods) { fn() { const algorithm = new Sha1(true); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); diff --git a/std/hash/sha256.ts b/std/hash/sha256.ts index 61da5a578..e2456d7a1 100644 --- a/std/hash/sha256.ts +++ b/std/hash/sha256.ts @@ -14,7 +14,6 @@ export type Message = string | number[] | ArrayBuffer; const HEX_CHARS = "0123456789abcdef".split(""); const EXTRA = [-2147483648, 8388608, 32768, 128] as const; const SHIFT = [24, 16, 8, 0] as const; -// prettier-ignore // deno-fmt-ignore const K = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, @@ -58,6 +57,7 @@ export class Sha256 { protected init(is224: boolean, sharedMemory: boolean): void { if (sharedMemory) { + // deno-fmt-ignore blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; this.#blocks = blocks; } else { @@ -116,6 +116,7 @@ export class Sha256 { if (this.#hashed) { this.#hashed = false; blocks[0] = this.#block; + // deno-fmt-ignore blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } @@ -136,8 +137,7 @@ export class Sha256 { blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { - code = - 0x10000 + + code = 0x10000 + (((code & 0x3ff) << 10) | (msg.charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; @@ -180,6 +180,7 @@ export class Sha256 { this.hash(); } blocks[0] = this.#block; + // deno-fmt-ignore blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } blocks[14] = (this.#hBytes << 3) | (this.#bytes >>> 29); @@ -213,8 +214,8 @@ export class Sha256 { t1 = blocks[j - 15]; s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3); t1 = blocks[j - 2]; - s1 = - ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); + s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ + (t1 >>> 10); blocks[j] = (blocks[j - 16] + s0 + blocks[j - 7] + s1) << 0; } @@ -234,12 +235,10 @@ export class Sha256 { } this.#first = false; } else { - s0 = - ((a >>> 2) | (a << 30)) ^ + s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); - s1 = - ((e >>> 6) | (e << 26)) ^ + s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); ab = a & b; @@ -250,12 +249,10 @@ export class Sha256 { h = (d + t1) << 0; d = (t1 + t2) << 0; } - s0 = - ((d >>> 2) | (d << 30)) ^ + s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10)); - s1 = - ((h >>> 6) | (h << 26)) ^ + s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7)); da = d & a; @@ -265,12 +262,10 @@ export class Sha256 { t2 = s0 + maj; g = (c + t1) << 0; c = (t1 + t2) << 0; - s0 = - ((c >>> 2) | (c << 30)) ^ + s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10)); - s1 = - ((g >>> 6) | (g << 26)) ^ + s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7)); cd = c & d; @@ -280,12 +275,10 @@ export class Sha256 { t2 = s0 + maj; f = (b + t1) << 0; b = (t1 + t2) << 0; - s0 = - ((b >>> 2) | (b << 30)) ^ + s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10)); - s1 = - ((f >>> 6) | (f << 26)) ^ + s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7)); bc = b & c; @@ -320,8 +313,7 @@ export class Sha256 { const h6 = this.#h6; const h7 = this.#h7; - let hex = - HEX_CHARS[(h0 >> 28) & 0x0f] + + let hex = HEX_CHARS[(h0 >> 28) & 0x0f] + HEX_CHARS[(h0 >> 24) & 0x0f] + HEX_CHARS[(h0 >> 20) & 0x0f] + HEX_CHARS[(h0 >> 16) & 0x0f] + @@ -378,8 +370,7 @@ export class Sha256 { HEX_CHARS[(h6 >> 4) & 0x0f] + HEX_CHARS[h6 & 0x0f]; if (!this.#is224) { - hex += - HEX_CHARS[(h7 >> 28) & 0x0f] + + hex += HEX_CHARS[(h7 >> 28) & 0x0f] + HEX_CHARS[(h7 >> 24) & 0x0f] + HEX_CHARS[(h7 >> 20) & 0x0f] + HEX_CHARS[(h7 >> 16) & 0x0f] + @@ -444,7 +435,7 @@ export class Sha256 { (h7 >> 24) & 0xff, (h7 >> 16) & 0xff, (h7 >> 8) & 0xff, - h7 & 0xff + h7 & 0xff, ); } return arr; @@ -501,8 +492,7 @@ export class HmacSha256 extends Sha256 { bytes[index++] = 0x80 | ((code >> 6) & 0x3f); bytes[index++] = 0x80 | (code & 0x3f); } else { - code = - 0x10000 + + code = 0x10000 + (((code & 0x3ff) << 10) | (secretKey.charCodeAt(++i) & 0x3ff)); bytes[index++] = 0xf0 | (code >> 18); bytes[index++] = 0x80 | ((code >> 12) & 0x3f); diff --git a/std/hash/sha256_test.ts b/std/hash/sha256_test.ts index 3cf4cbdf2..ba7efe4d1 100644 --- a/std/hash/sha256_test.ts +++ b/std/hash/sha256_test.ts @@ -16,7 +16,6 @@ function toHexString(value: number[] | ArrayBuffer): string { return hex; } -// prettier-ignore // deno-fmt-ignore const fixtures: { sha256: Record<string, Record<string, Message>>; @@ -155,35 +154,29 @@ const fixtures: { }, }; -// prettier-ignore // deno-fmt-ignore fixtures.sha256.Uint8Array = { '182889f925ae4e5cc37118ded6ed87f7bdc7cab5ec5e78faef2e50048999473f': new Uint8Array([211, 212]), 'd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592': new Uint8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103]) }; -// prettier-ignore // deno-fmt-ignore fixtures.sha256.Int8Array = { 'd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592': new Int8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103]) }; -// prettier-ignore // deno-fmt-ignore fixtures.sha256.ArrayBuffer = { 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855': new ArrayBuffer(0), '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d': new ArrayBuffer(1) }; -// prettier-ignore // deno-fmt-ignore fixtures.sha224.Uint8Array = { 'e17541396a3ecd1cd5a2b968b84e597e8eae3b0ea3127963bf48dd3b': new Uint8Array([211, 212]), '730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525': new Uint8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103]) }; -// prettier-ignore // deno-fmt-ignore fixtures.sha224.Int8Array = { '730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525': new Int8Array([84, 104, 101, 32, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 32, 106, 117, 109, 112, 115, 32, 111, 118, 101, 114, 32, 116, 104, 101, 32, 108, 97, 122, 121, 32, 100, 111, 103]) }; -// prettier-ignore // deno-fmt-ignore fixtures.sha224.ArrayBuffer = { 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f': new ArrayBuffer(0), @@ -225,10 +218,9 @@ for (const method of methods) { fn() { const algorithm = new Sha256(); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -245,10 +237,9 @@ for (const method of methods) { fn() { const algorithm = new Sha256(true); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -265,10 +256,9 @@ for (const method of methods) { fn() { const algorithm = new HmacSha256(key); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -285,10 +275,9 @@ for (const method of methods) { fn() { const algorithm = new HmacSha256(key, true); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -302,6 +291,6 @@ Deno.test("[hash/sha256] test Uint8Array from Reader", async () => { const hash = new Sha256().update(data).hex(); assertEquals( hash, - "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" + "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", ); }); diff --git a/std/hash/sha3_test.ts b/std/hash/sha3_test.ts index 64e426385..b5936f960 100644 --- a/std/hash/sha3_test.ts +++ b/std/hash/sha3_test.ts @@ -554,7 +554,7 @@ Deno.test("[hash/sha3] testSha3-256Chain", () => { assertEquals( output, - "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532" + "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", ); }); @@ -567,6 +567,6 @@ Deno.test("[hash/sha3] testSha3UpdateFinalized", () => { assertEquals(hash, hash2); }, Error, - "sha3: cannot update already finalized hash" + "sha3: cannot update already finalized hash", ); }); diff --git a/std/hash/sha512.ts b/std/hash/sha512.ts index b55069f4d..1eef85a47 100644 --- a/std/hash/sha512.ts +++ b/std/hash/sha512.ts @@ -9,11 +9,11 @@ export type Message = string | number[] | ArrayBuffer; -// prettier-ignore +// deno-fmt-ignore const HEX_CHARS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"] as const; const EXTRA = [-2147483648, 8388608, 32768, 128] as const; const SHIFT = [24, 16, 8, 0] as const; -// prettier-ignore +// deno-fmt-ignore const K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, @@ -37,7 +37,7 @@ const K = [ const blocks: number[] = []; -// prettier-ignore +// deno-fmt-ignore export class Sha512 { #blocks!: number[]; #block!: number; @@ -564,7 +564,7 @@ export class Sha512 { h0h = this.#h0h, h0l = this.#h0l, h1h = this.#h1h, h1l = this.#h1l, h2h = this.#h2h, h2l = this.#h2l, h3h = this.#h3h, h3l = this.#h3l, h4h = this.#h4h, h4l = this.#h4l, h5h = this.#h5h, h5l = this.#h5l, h6h = this.#h6h, h6l = this.#h6l, h7h = this.#h7h, h7l = this.#h7l, bits = this.#bits; - let hex = + let hex = HEX_CHARS[(h0h >> 28) & 0x0f] + HEX_CHARS[(h0h >> 24) & 0x0f] + HEX_CHARS[(h0h >> 20) & 0x0f] + HEX_CHARS[(h0h >> 16) & 0x0f] + HEX_CHARS[(h0h >> 12) & 0x0f] + HEX_CHARS[(h0h >> 8) & 0x0f] + @@ -747,8 +747,7 @@ export class HmacSha512 extends Sha512 { bytes[index++] = 0x80 | ((code >> 6) & 0x3f); bytes[index++] = 0x80 | (code & 0x3f); } else { - code = - 0x10000 + + code = 0x10000 + (((code & 0x3ff) << 10) | (secretKey.charCodeAt(++i) & 0x3ff)); bytes[index++] = 0xf0 | (code >> 18); bytes[index++] = 0x80 | ((code >> 12) & 0x3f); diff --git a/std/hash/sha512_test.ts b/std/hash/sha512_test.ts index c656731a3..d8d69a923 100644 --- a/std/hash/sha512_test.ts +++ b/std/hash/sha512_test.ts @@ -16,7 +16,6 @@ function toHexString(value: number[] | ArrayBuffer): string { return hex; } -// prettier-ignore // deno-fmt-ignore const fixtures: { sha512bits224: Record<string, Record<string, Message>>, @@ -285,10 +284,9 @@ for (const method of methods) { fn() { const algorithm = new Sha512(224); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -305,10 +303,9 @@ for (const method of methods) { fn() { const algorithm = new Sha512(256); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -325,10 +322,9 @@ for (const method of methods) { fn() { const algorithm = new Sha512(); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -345,10 +341,9 @@ for (const method of methods) { fn() { const algorithm = new HmacSha512(key, 224); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -365,10 +360,9 @@ for (const method of methods) { fn() { const algorithm = new HmacSha512(key, 256); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -385,10 +379,9 @@ for (const method of methods) { fn() { const algorithm = new HmacSha512(key); algorithm.update(message); - const actual = - method === "hex" - ? algorithm[method]() - : toHexString(algorithm[method]()); + const actual = method === "hex" + ? algorithm[method]() + : toHexString(algorithm[method]()); assertEquals(actual, expected); }, }); @@ -401,6 +394,6 @@ Deno.test("[hash/sha512] test Uint8Array from Reader", async () => { const hash = new Sha512().update(data).hex(); assertEquals( hash, - "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff" + "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff", ); }); diff --git a/std/http/_io.ts b/std/http/_io.ts index 1db0fc292..743f52556 100644 --- a/std/http/_io.ts +++ b/std/http/_io.ts @@ -122,7 +122,7 @@ function isProhibidedForTrailer(key: string): boolean { * field will be deleted. */ export async function readTrailers( headers: Headers, - r: BufReader + r: BufReader, ): Promise<void> { const trailers = parseTrailer(headers.get("trailer")); if (trailers == null) return; @@ -133,11 +133,11 @@ export async function readTrailers( throw new Deno.errors.InvalidData("Missing trailer header."); } const undeclared = [...result.keys()].filter( - (k) => !trailerNames.includes(k) + (k) => !trailerNames.includes(k), ); if (undeclared.length > 0) { throw new Deno.errors.InvalidData( - `Undeclared trailers: ${Deno.inspect(undeclared)}.` + `Undeclared trailers: ${Deno.inspect(undeclared)}.`, ); } for (const [k, v] of result) { @@ -146,7 +146,7 @@ export async function readTrailers( const missingTrailers = trailerNames.filter((k) => !result.has(k)); if (missingTrailers.length > 0) { throw new Deno.errors.InvalidData( - `Missing trailers: ${Deno.inspect(missingTrailers)}.` + `Missing trailers: ${Deno.inspect(missingTrailers)}.`, ); } headers.delete("trailer"); @@ -163,7 +163,7 @@ function parseTrailer(field: string | null): Headers | undefined { const prohibited = trailerNames.filter((k) => isProhibidedForTrailer(k)); if (prohibited.length > 0) { throw new Deno.errors.InvalidData( - `Prohibited trailer names: ${Deno.inspect(prohibited)}.` + `Prohibited trailer names: ${Deno.inspect(prohibited)}.`, ); } return new Headers(trailerNames.map((key) => [key, ""])); @@ -171,7 +171,7 @@ function parseTrailer(field: string | null): Headers | undefined { export async function writeChunkedBody( w: Deno.Writer, - r: Deno.Reader + r: Deno.Reader, ): Promise<void> { const writer = BufWriter.create(w); for await (const chunk of Deno.iter(r)) { @@ -192,7 +192,7 @@ export async function writeChunkedBody( export async function writeTrailers( w: Deno.Writer, headers: Headers, - trailers: Headers + trailers: Headers, ): Promise<void> { const trailer = headers.get("trailer"); if (trailer === null) { @@ -201,7 +201,7 @@ export async function writeTrailers( const transferEncoding = headers.get("transfer-encoding"); if (transferEncoding === null || !transferEncoding.match(/^chunked/)) { throw new TypeError( - `Trailers are only allowed for "transfer-encoding: chunked", got "transfer-encoding: ${transferEncoding}".` + `Trailers are only allowed for "transfer-encoding: chunked", got "transfer-encoding: ${transferEncoding}".`, ); } const writer = BufWriter.create(w); @@ -211,11 +211,11 @@ export async function writeTrailers( ); if (prohibitedTrailers.length > 0) { throw new TypeError( - `Prohibited trailer names: ${Deno.inspect(prohibitedTrailers)}.` + `Prohibited trailer names: ${Deno.inspect(prohibitedTrailers)}.`, ); } const undeclared = [...trailers.keys()].filter( - (k) => !trailerNames.includes(k) + (k) => !trailerNames.includes(k), ); if (undeclared.length > 0) { throw new TypeError(`Undeclared trailers: ${Deno.inspect(undeclared)}.`); @@ -229,7 +229,7 @@ export async function writeTrailers( export async function writeResponse( w: Deno.Writer, - r: Response + r: Response, ): Promise<void> { const protoMajor = 1; const protoMinor = 1; @@ -333,7 +333,7 @@ export function parseHTTPVersion(vers: string): [number, number] { export async function readRequest( conn: Deno.Conn, - bufr: BufReader + bufr: BufReader, ): Promise<ServerRequest | null> { const tp = new TextProtoReader(bufr); const firstLine = await tp.readLine(); // e.g. GET /index.html HTTP/1.0 @@ -372,7 +372,7 @@ function fixLength(req: ServerRequest): void { // that contains a Transfer-Encoding header field. // rfc: https://tools.ietf.org/html/rfc7230#section-3.3.2 throw new Error( - "http: Transfer-Encoding and Content-Length cannot be send together" + "http: Transfer-Encoding and Content-Length cannot be send together", ); } } diff --git a/std/http/_io_test.ts b/std/http/_io_test.ts index 473c40637..77d8288f2 100644 --- a/std/http/_io_test.ts +++ b/std/http/_io_test.ts @@ -23,7 +23,7 @@ Deno.test("bodyReader", async () => { const text = "Hello, Deno"; const r = bodyReader( text.length, - new BufReader(new Deno.Buffer(encode(text))) + new BufReader(new Deno.Buffer(encode(text))), ); assertEquals(decode(await Deno.readAll(r)), text); }); @@ -108,14 +108,14 @@ Deno.test( async () => { await readTrailers( h, - new BufReader(new Deno.Buffer(encode(trailer))) + new BufReader(new Deno.Buffer(encode(trailer))), ); }, Deno.errors.InvalidData, - `Undeclared trailers: [ "` + `Undeclared trailers: [ "`, ); } - } + }, ); Deno.test( @@ -130,10 +130,10 @@ Deno.test( await readTrailers(h, new BufReader(new Deno.Buffer())); }, Deno.errors.InvalidData, - `Prohibited trailer names: [ "` + `Prohibited trailer names: [ "`, ); } - } + }, ); Deno.test("writeTrailer", async () => { @@ -141,11 +141,11 @@ Deno.test("writeTrailer", async () => { await writeTrailers( w, new Headers({ "transfer-encoding": "chunked", trailer: "deno,node" }), - new Headers({ deno: "land", node: "js" }) + new Headers({ deno: "land", node: "js" }), ); assertEquals( new TextDecoder().decode(w.bytes()), - "deno: land\r\nnode: js\r\n\r\n" + "deno: land\r\nnode: js\r\n\r\n", ); }); @@ -156,14 +156,14 @@ Deno.test("writeTrailer should throw", async () => { return writeTrailers(w, new Headers(), new Headers()); }, TypeError, - "Missing trailer header." + "Missing trailer header.", ); await assertThrowsAsync( () => { return writeTrailers(w, new Headers({ trailer: "deno" }), new Headers()); }, TypeError, - `Trailers are only allowed for "transfer-encoding: chunked", got "transfer-encoding: null".` + `Trailers are only allowed for "transfer-encoding: chunked", got "transfer-encoding: null".`, ); for (const f of ["content-length", "trailer", "transfer-encoding"]) { await assertThrowsAsync( @@ -171,11 +171,11 @@ Deno.test("writeTrailer should throw", async () => { return writeTrailers( w, new Headers({ "transfer-encoding": "chunked", trailer: f }), - new Headers({ [f]: "1" }) + new Headers({ [f]: "1" }), ); }, TypeError, - `Prohibited trailer names: [ "` + `Prohibited trailer names: [ "`, ); } await assertThrowsAsync( @@ -183,11 +183,11 @@ Deno.test("writeTrailer should throw", async () => { return writeTrailers( w, new Headers({ "transfer-encoding": "chunked", trailer: "deno" }), - new Headers({ node: "js" }) + new Headers({ node: "js" }), ); }, TypeError, - `Undeclared trailers: [ "node" ].` + `Undeclared trailers: [ "node" ].`, ); }); @@ -419,20 +419,17 @@ Deno.test("testReadRequestError", async function (): Promise<void> { // deduplicated if same or reject otherwise // See Issue 16490. { - in: - "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 0\r\n\r\n" + + in: "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 0\r\n\r\n" + "Gopher hey\r\n", err: "cannot contain multiple Content-Length headers", }, { - in: - "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 6\r\n\r\n" + + in: "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 6\r\n\r\n" + "Gopher\r\n", err: "cannot contain multiple Content-Length headers", }, { - in: - "PUT / HTTP/1.1\r\nContent-Length: 6 \r\nContent-Length: 6\r\n" + + in: "PUT / HTTP/1.1\r\nContent-Length: 6 \r\nContent-Length: 6\r\n" + "Content-Length:6\r\n\r\nGopher\r\n", headers: [{ key: "Content-Length", value: "6" }], }, @@ -451,8 +448,7 @@ Deno.test("testReadRequestError", async function (): Promise<void> { headers: [{ key: "Content-Length", value: "0" }], }, { - in: - "POST / HTTP/1.1\r\nContent-Length:0\r\ntransfer-encoding: " + + in: "POST / HTTP/1.1\r\nContent-Length:0\r\ntransfer-encoding: " + "chunked\r\n\r\n", headers: [], err: "http: Transfer-Encoding and Content-Length cannot be send together", diff --git a/std/http/cookie_test.ts b/std/http/cookie_test.ts index 0b412d8e4..f34f5acae 100644 --- a/std/http/cookie_test.ts +++ b/std/http/cookie_test.ts @@ -38,7 +38,7 @@ Deno.test({ deleteCookie(res, "deno"); assertEquals( res.headers?.get("Set-Cookie"), - "deno=; Expires=Thu, 01 Jan 1970 00:00:00 GMT" + "deno=; Expires=Thu, 01 Jan 1970 00:00:00 GMT", ); }, }); @@ -79,7 +79,7 @@ Deno.test({ }); assertEquals( res.headers.get("Set-Cookie"), - "Space=Cat; Secure; HttpOnly; Max-Age=2" + "Space=Cat; Secure; HttpOnly; Max-Age=2", ); let error = false; @@ -108,7 +108,7 @@ Deno.test({ }); assertEquals( res.headers.get("Set-Cookie"), - "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land" + "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land", ); res.headers = new Headers(); @@ -124,7 +124,7 @@ Deno.test({ assertEquals( res.headers.get("Set-Cookie"), "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; " + - "SameSite=Strict" + "SameSite=Strict", ); res.headers = new Headers(); @@ -139,7 +139,7 @@ Deno.test({ }); assertEquals( res.headers.get("Set-Cookie"), - "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; SameSite=Lax" + "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; SameSite=Lax", ); res.headers = new Headers(); @@ -154,7 +154,7 @@ Deno.test({ }); assertEquals( res.headers.get("Set-Cookie"), - "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; Path=/" + "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; Path=/", ); res.headers = new Headers(); @@ -171,7 +171,7 @@ Deno.test({ assertEquals( res.headers.get("Set-Cookie"), "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; Path=/; " + - "unparsed=keyvalue; batman=Bruce" + "unparsed=keyvalue; batman=Bruce", ); res.headers = new Headers(); @@ -188,7 +188,7 @@ Deno.test({ assertEquals( res.headers.get("Set-Cookie"), "Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; Path=/; " + - "Expires=Fri, 07 Jan 1983 15:32:00 GMT" + "Expires=Fri, 07 Jan 1983 15:32:00 GMT", ); res.headers = new Headers(); @@ -203,7 +203,7 @@ Deno.test({ }); assertEquals( res.headers.get("Set-Cookie"), - "__Host-Kitty=Meow; Secure; Path=/" + "__Host-Kitty=Meow; Secure; Path=/", ); res.headers = new Headers(); @@ -211,7 +211,7 @@ Deno.test({ setCookie(res, { name: "cookie-2", value: "value-2", maxAge: 3600 }); assertEquals( res.headers.get("Set-Cookie"), - "cookie-1=value-1; Secure, cookie-2=value-2; Max-Age=3600" + "cookie-1=value-1; Secure, cookie-2=value-2; Max-Age=3600", ); res.headers = new Headers(); diff --git a/std/http/file_server.ts b/std/http/file_server.ts index a66118e74..ffcf31e54 100755 --- a/std/http/file_server.ts +++ b/std/http/file_server.ts @@ -97,7 +97,7 @@ function fileLenToString(len: number): string { export async function serveFile( req: ServerRequest, - filePath: string + filePath: string, ): Promise<Response> { const [file, fileInfo] = await Promise.all([ Deno.open(filePath), @@ -122,7 +122,7 @@ export async function serveFile( // TODO: simplify this after deno.stat and deno.readDir are fixed async function serveDir( req: ServerRequest, - dirPath: string + dirPath: string, ): Promise<Response> { const dirUrl = `/${posix.relative(target, dirPath)}`; const listEntry: EntryInfo[] = []; @@ -192,7 +192,7 @@ function setCORS(res: Response): void { res.headers.append("access-control-allow-origin", "*"); res.headers.append( "access-control-allow-headers", - "Origin, X-Requested-With, Content-Type, Accept, Range" + "Origin, X-Requested-With, Content-Type, Accept, Range", ); } @@ -263,9 +263,10 @@ function dirViewerTemplate(dirname: string, entries: EntryInfo[]): string { <th>Size</th> <th>Name</th> </tr> - ${entries.map( - (entry) => - html` + ${ + entries.map( + (entry) => + html` <tr> <td class="mode"> ${entry.mode} @@ -277,8 +278,9 @@ function dirViewerTemplate(dirname: string, entries: EntryInfo[]): string { <a href="${entry.url}">${entry.name}</a> </td> </tr> - ` - )} + `, + ) + } </table> </main> </body> @@ -359,7 +361,7 @@ function main(): void { console.error(e.message); } } - } + }, ); console.log(`HTTP server listening on http://${addr}/`); diff --git a/std/http/file_server_test.ts b/std/http/file_server_test.ts index 66c1d7d04..486bc514c 100644 --- a/std/http/file_server_test.ts +++ b/std/http/file_server_test.ts @@ -78,13 +78,13 @@ Deno.test( assertEquals(res.headers.get("content-type"), "text/markdown"); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( - await Deno.readFile("README.md") + await Deno.readFile("README.md"), ); assertEquals(downloadedFile, localFile); } finally { await killFileServer(); } - } + }, ); Deno.test( @@ -98,14 +98,14 @@ Deno.test( assertEquals(res.headers.get("content-type"), "text/markdown"); const downloadedFile = await res.text(); const localFile = new TextDecoder().decode( - await Deno.readFile("./http/README.md") + await Deno.readFile("./http/README.md"), ); console.log(downloadedFile, localFile); assertEquals(downloadedFile, localFile); } finally { await killFileServer(); } - } + }, ); Deno.test("serveDirectory", async function (): Promise<void> { diff --git a/std/http/racing_server.ts b/std/http/racing_server.ts index 67db029e0..1770443af 100644 --- a/std/http/racing_server.ts +++ b/std/http/racing_server.ts @@ -10,7 +10,7 @@ function body(i: number): string { } async function delayedRespond( request: ServerRequest, - step: number + step: number, ): Promise<void> { await delay(3000); await request.respond({ status: 200, body: body(step) }); @@ -24,7 +24,7 @@ async function largeRespond(request: ServerRequest, c: string): Promise<void> { async function ignoreToConsume( request: ServerRequest, - step: number + step: number, ): Promise<void> { await request.respond({ status: 200, body: body(step) }); } diff --git a/std/http/server.ts b/std/http/server.ts index b1ffed96b..93f116fff 100644 --- a/std/http/server.ts +++ b/std/http/server.ts @@ -65,7 +65,7 @@ export class ServerRequest { .map((e): string => e.trim().toLowerCase()); assert( parts.includes("chunked"), - 'transfer-encoding must include "chunked" if content-length is not set' + 'transfer-encoding must include "chunked" if content-length is not set', ); this._body = chunkedBodyReader(this.headers, this.r); } else { @@ -136,7 +136,7 @@ export class Server implements AsyncIterable<ServerRequest> { // Yields all HTTP requests on a single TCP connection. private async *iterateHttpRequests( - conn: Deno.Conn + conn: Deno.Conn, ): AsyncIterableIterator<ServerRequest> { const reader = new BufReader(conn); const writer = new BufWriter(conn); @@ -203,7 +203,7 @@ export class Server implements AsyncIterable<ServerRequest> { // same kind and adds it to the request multiplexer so that another TCP // connection can be accepted. private async *acceptConnAndIterateHttpRequests( - mux: MuxAsyncIterator<ServerRequest> + mux: MuxAsyncIterator<ServerRequest>, ): AsyncIterableIterator<ServerRequest> { if (this.closing) return; // Wait for a new connection. @@ -302,7 +302,7 @@ export function serve(addr: string | HTTPOptions): Server { */ export async function listenAndServe( addr: string | HTTPOptions, - handler: (req: ServerRequest) => void + handler: (req: ServerRequest) => void, ): Promise<void> { const server = serve(addr); @@ -359,7 +359,7 @@ export function serveTLS(options: HTTPSOptions): Server { */ export async function listenAndServeTLS( options: HTTPSOptions, - handler: (req: ServerRequest) => void + handler: (req: ServerRequest) => void, ): Promise<void> { const server = serveTLS(options); diff --git a/std/http/server_test.ts b/std/http/server_test.ts index f6bff1c5f..bc9b52341 100644 --- a/std/http/server_test.ts +++ b/std/http/server_test.ts @@ -51,8 +51,7 @@ const responseTests: ResponseTest[] = [ body: new Deno.Buffer(new TextEncoder().encode("abcdef")), }, - raw: - "HTTP/1.1 200 OK\r\n" + + raw: "HTTP/1.1 200 OK\r\n" + "transfer-encoding: chunked\r\n\r\n" + "6\r\nabcdef\r\n0\r\n\r\n", }, @@ -94,10 +93,9 @@ Deno.test("requestContentLength", function (): void { const maxChunkSize = 70; while (chunkOffset < shortText.length) { const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( - chunkOffset, - chunkSize - )}\r\n`; + chunksData += `${chunkSize.toString(16)}\r\n${ + shortText.substr(chunkOffset, chunkSize) + }\r\n`; chunkOffset += chunkSize; } chunksData += "0\r\n\r\n"; @@ -164,7 +162,7 @@ Deno.test( assertEquals(tr.total, 0); await req.finalize(); assertEquals(tr.total, text.length); - } + }, ); Deno.test( "ServerRequest.finalize() should consume unread body / chunked, trailers", @@ -199,7 +197,7 @@ Deno.test( assertEquals(req.headers.has("trailer"), false); assertEquals(req.headers.get("deno"), "land"); assertEquals(req.headers.get("node"), "js"); - } + }, ); Deno.test("requestBodyWithTransferEncoding", async function (): Promise<void> { { @@ -212,10 +210,9 @@ Deno.test("requestBodyWithTransferEncoding", async function (): Promise<void> { const maxChunkSize = 70; while (chunkOffset < shortText.length) { const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( - chunkOffset, - chunkSize - )}\r\n`; + chunksData += `${chunkSize.toString(16)}\r\n${ + shortText.substr(chunkOffset, chunkSize) + }\r\n`; chunkOffset += chunkSize; } chunksData += "0\r\n\r\n"; @@ -236,10 +233,9 @@ Deno.test("requestBodyWithTransferEncoding", async function (): Promise<void> { const maxChunkSize = 70; while (chunkOffset < longText.length) { const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( - chunkOffset, - chunkSize - )}\r\n`; + chunksData += `${chunkSize.toString(16)}\r\n${ + longText.substr(chunkOffset, chunkSize) + }\r\n`; chunkOffset += chunkSize; } chunksData += "0\r\n\r\n"; @@ -308,10 +304,9 @@ Deno.test("requestBodyReaderWithTransferEncoding", async function (): Promise< const maxChunkSize = 70; while (chunkOffset < shortText.length) { const chunkSize = Math.min(maxChunkSize, shortText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${shortText.substr( - chunkOffset, - chunkSize - )}\r\n`; + chunksData += `${chunkSize.toString(16)}\r\n${ + shortText.substr(chunkOffset, chunkSize) + }\r\n`; chunkOffset += chunkSize; } chunksData += "0\r\n\r\n"; @@ -341,10 +336,9 @@ Deno.test("requestBodyReaderWithTransferEncoding", async function (): Promise< const maxChunkSize = 70; while (chunkOffset < longText.length) { const chunkSize = Math.min(maxChunkSize, longText.length - chunkOffset); - chunksData += `${chunkSize.toString(16)}\r\n${longText.substr( - chunkOffset, - chunkSize - )}\r\n`; + chunksData += `${chunkSize.toString(16)}\r\n${ + longText.substr(chunkOffset, chunkSize) + }\r\n`; chunkOffset += chunkSize; } chunksData += "0\r\n\r\n"; @@ -436,7 +430,7 @@ Deno.test({ const s = await r.readLine(); assert( s !== null && s.includes("server listening"), - "server must be started" + "server must be started", ); // Requests to the server and immediately closes the connection const conn = await Deno.connectTls({ @@ -446,7 +440,7 @@ Deno.test({ }); await Deno.writeAll( conn, - new TextEncoder().encode("GET / HTTP/1.0\r\n\r\n") + new TextEncoder().encode("GET / HTTP/1.0\r\n\r\n"), ); const res = new Uint8Array(100); const nread = await conn.read(res); @@ -475,7 +469,7 @@ Deno.test( const nextAfterClosing = server[Symbol.asyncIterator]().next(); assertEquals(await nextAfterClosing, { value: undefined, done: true }); - } + }, ); Deno.test({ @@ -492,7 +486,7 @@ Deno.test({ const conn = await Deno.connect({ hostname: "127.0.0.1", port: 8123 }); await Deno.writeAll( conn, - new TextEncoder().encode("GET /hello HTTP/1.1\r\n\r\n") + new TextEncoder().encode("GET /hello HTTP/1.1\r\n\r\n"), ); const res = new Uint8Array(100); const nread = await conn.read(res); @@ -533,7 +527,7 @@ Deno.test({ }); await Deno.writeAll( conn, - new TextEncoder().encode("GET / HTTP/1.1\r\n\r\n") + new TextEncoder().encode("GET / HTTP/1.1\r\n\r\n"), ); conn.close(); await p; @@ -551,12 +545,12 @@ Deno.test({ }); await Deno.writeAll( conn, - encode("GET / HTTP/1.1\r\nmalformedHeader\r\n\r\n\r\n\r\n") + encode("GET / HTTP/1.1\r\nmalformedHeader\r\n\r\n\r\n\r\n"), ); const responseString = decode(await Deno.readAll(conn)); assertMatch( responseString, - /^HTTP\/1\.1 400 Bad Request\r\ncontent-length: \d+\r\n\r\n.*\r\n\r\n$/ms + /^HTTP\/1\.1 400 Bad Request\r\ncontent-length: \d+\r\n\r\n.*\r\n\r\n$/ms, ); conn.close(); server.close(); @@ -592,7 +586,7 @@ Deno.test({ port, // certFile }), - Deno.errors.InvalidData + Deno.errors.InvalidData, ); // Valid request after invalid @@ -604,7 +598,7 @@ Deno.test({ await Deno.writeAll( conn, - new TextEncoder().encode("GET / HTTP/1.0\r\n\r\n") + new TextEncoder().encode("GET / HTTP/1.0\r\n\r\n"), ); const res = new Uint8Array(100); const nread = await conn.read(res); diff --git a/std/io/bufio.ts b/std/io/bufio.ts index a1e6f67aa..682f96499 100644 --- a/std/io/bufio.ts +++ b/std/io/bufio.ts @@ -95,7 +95,7 @@ export class BufReader implements Reader { } throw new Error( - `No progress after ${MAX_CONSECUTIVE_EMPTY_READS} read() calls` + `No progress after ${MAX_CONSECUTIVE_EMPTY_READS} read() calls`, ); } @@ -252,7 +252,7 @@ export class BufReader implements Reader { let { partial } = err; assert( partial instanceof Uint8Array, - "bufio: caught error from `readSlice()` without `partial` property" + "bufio: caught error from `readSlice()` without `partial` property", ); // Don't throw if `readSlice()` failed with `BufferFullError`, instead we @@ -466,7 +466,7 @@ export class BufWriter extends AbstractBufBase implements Writer { try { await Deno.writeAll( this.writer, - this.buf.subarray(0, this.usedBufferBytes) + this.buf.subarray(0, this.usedBufferBytes), ); } catch (e) { this.err = e; @@ -527,7 +527,7 @@ export class BufWriterSync extends AbstractBufBase implements WriterSync { /** return new BufWriterSync unless writer is BufWriterSync */ static create( writer: WriterSync, - size: number = DEFAULT_BUF_SIZE + size: number = DEFAULT_BUF_SIZE, ): BufWriterSync { return writer instanceof BufWriterSync ? writer @@ -559,7 +559,7 @@ export class BufWriterSync extends AbstractBufBase implements WriterSync { try { Deno.writeAllSync( this.writer, - this.buf.subarray(0, this.usedBufferBytes) + this.buf.subarray(0, this.usedBufferBytes), ); } catch (e) { this.err = e; @@ -633,7 +633,7 @@ function createLPS(pat: Uint8Array): Uint8Array { /** Read delimited bytes from a Reader. */ export async function* readDelim( reader: Reader, - delim: Uint8Array + delim: Uint8Array, ): AsyncIterableIterator<Uint8Array> { // Avoid unicode problems const delimLen = delim.length; @@ -692,7 +692,7 @@ export async function* readDelim( /** Read delimited strings from a Reader. */ export async function* readStringDelim( reader: Reader, - delim: string + delim: string, ): AsyncIterableIterator<string> { const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -704,7 +704,7 @@ export async function* readStringDelim( /** Read strings line-by-line from a Reader. */ // eslint-disable-next-line require-await export async function* readLines( - reader: Reader + reader: Reader, ): AsyncIterableIterator<string> { yield* readStringDelim(reader, "\n"); } diff --git a/std/io/bufio_test.ts b/std/io/bufio_test.ts index ad02703de..1ad6c7ac6 100644 --- a/std/io/bufio_test.ts +++ b/std/io/bufio_test.ts @@ -122,8 +122,7 @@ Deno.test("bufioBufReader", async function (): Promise<void> { const read = readmaker.fn(new StringReader(text)); const buf = new BufReader(read, bufsize); const s = await bufreader.fn(buf); - const debugStr = - `reader=${readmaker.name} ` + + const debugStr = `reader=${readmaker.name} ` + `fn=${bufreader.name} bufsize=${bufsize} want=${text} got=${s}`; assertEquals(s, text, debugStr); } @@ -179,11 +178,11 @@ Deno.test("bufioReadString", async function (): Promise<void> { }); const testInput = encoder.encode( - "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy" + "012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy", ); const testInputrn = encoder.encode( "012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\n" + - "uvw\r\nxy\r\n\n\r\n" + "uvw\r\nxy\r\n\n\r\n", ); const testOutput = encoder.encode("0123456789abcdefghijklmnopqrstuvwxy"); @@ -225,7 +224,7 @@ async function testReadLine(input: Uint8Array): Promise<void> { assertEquals( line, want, - `Bad line at stride ${stride}: want: ${want} got: ${line}` + `Bad line at stride ${stride}: want: ${want} got: ${line}`, ); done += line.byteLength; } @@ -233,7 +232,7 @@ async function testReadLine(input: Uint8Array): Promise<void> { done, testOutput.byteLength, `readLine didn't return everything: got: ${done}, ` + - `want: ${testOutput} (stride: ${stride})` + `want: ${testOutput} (stride: ${stride})`, ); } } @@ -249,7 +248,7 @@ Deno.test("bufioPeek", async function (): Promise<void> { // string is 16 (minReadBufferSize) long. const buf = new BufReader( new StringReader("abcdefghijklmnop"), - MIN_READ_BUFFER_SIZE + MIN_READ_BUFFER_SIZE, ); let actual = await buf.peek(1); @@ -425,7 +424,7 @@ Deno.test("bufReaderReadFull", async function (): Promise<void> { Deno.test("readStringDelimAndLines", async function (): Promise<void> { const enc = new TextEncoder(); const data = new Deno.Buffer( - enc.encode("Hello World\tHello World 2\tHello World 3") + enc.encode("Hello World\tHello World 2\tHello World 3"), ); const chunks_ = []; @@ -464,9 +463,9 @@ Deno.test( assertEquals(decoder.decode(r2.line), "z"); assert( r1.line.buffer !== r2.line.buffer, - "array buffer should not be shared across reads" + "array buffer should not be shared across reads", ); - } + }, ); Deno.test({ diff --git a/std/io/ioutil.ts b/std/io/ioutil.ts index ac6d103a3..da48e95ab 100644 --- a/std/io/ioutil.ts +++ b/std/io/ioutil.ts @@ -12,7 +12,7 @@ const DEFAULT_BUFFER_SIZE = 32 * 1024; export async function copyN( r: Reader, dest: Writer, - size: number + size: number, ): Promise<number> { let bytesRead = 0; let buf = new Uint8Array(DEFAULT_BUFFER_SIZE); @@ -67,7 +67,7 @@ export async function readLong(buf: BufReader): Promise<number | null> { // We probably should provide a similar API that returns BigInt values. if (big > MAX_SAFE_INTEGER) { throw new RangeError( - "Long value too big to be represented as a JavaScript number." + "Long value too big to be represented as a JavaScript number.", ); } return Number(big); diff --git a/std/io/ioutil_test.ts b/std/io/ioutil_test.ts index dfdda23fb..69f76f691 100644 --- a/std/io/ioutil_test.ts +++ b/std/io/ioutil_test.ts @@ -38,7 +38,7 @@ Deno.test("testReadInt", async function (): Promise<void> { Deno.test("testReadLong", async function (): Promise<void> { const r = new BinaryReader( - new Uint8Array([0x00, 0x00, 0x00, 0x78, 0x12, 0x34, 0x56, 0x78]) + new Uint8Array([0x00, 0x00, 0x00, 0x78, 0x12, 0x34, 0x56, 0x78]), ); const long = await readLong(new BufReader(r)); assertEquals(long, 0x7812345678); @@ -46,7 +46,7 @@ Deno.test("testReadLong", async function (): Promise<void> { Deno.test("testReadLong2", async function (): Promise<void> { const r = new BinaryReader( - new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]) + new Uint8Array([0, 0, 0, 0, 0x12, 0x34, 0x56, 0x78]), ); const long = await readLong(new BufReader(r)); assertEquals(long, 0x12345678); @@ -58,9 +58,9 @@ Deno.test("testSliceLongToBytes", function (): void { const expected = readLong( new BufReader( new BinaryReader( - new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]) - ) - ) + new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef]), + ), + ), ); assertEquals(actual, expected); }); diff --git a/std/io/streams.ts b/std/io/streams.ts index 3969746ef..89cc6bd45 100644 --- a/std/io/streams.ts +++ b/std/io/streams.ts @@ -1,7 +1,7 @@ // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. export function fromStreamWriter( - streamWriter: WritableStreamDefaultWriter<Uint8Array> + streamWriter: WritableStreamDefaultWriter<Uint8Array>, ): Deno.Writer { return { async write(p: Uint8Array): Promise<number> { @@ -13,7 +13,7 @@ export function fromStreamWriter( } export function fromStreamReader( - streamReader: ReadableStreamDefaultReader<Uint8Array> + streamReader: ReadableStreamDefaultReader<Uint8Array>, ): Deno.Reader { const buffer = new Deno.Buffer(); diff --git a/std/io/streams_test.ts b/std/io/streams_test.ts index 00d056e2f..4579e3668 100644 --- a/std/io/streams_test.ts +++ b/std/io/streams_test.ts @@ -64,7 +64,7 @@ Deno.test("toReaderCheck", async function (): Promise<void> { assertEquals( expected, - readChunks.map((chunk) => decoder.decode(chunk)) + readChunks.map((chunk) => decoder.decode(chunk)), ); }); @@ -115,7 +115,7 @@ Deno.test("toReaderBigIrregularChunksCheck", async function (): Promise<void> { chunks .slice() .map((chunk) => [...chunk]) - .flat() + .flat(), ); const readableStream = new ReadableStream({ pull(controller): void { diff --git a/std/io/util.ts b/std/io/util.ts index f4b7bf8bb..0055d7094 100644 --- a/std/io/util.ts +++ b/std/io/util.ts @@ -13,11 +13,11 @@ export async function tempFile( opts: { prefix?: string; postfix?: string; - } = { prefix: "", postfix: "" } + } = { prefix: "", postfix: "" }, ): Promise<{ file: Deno.File; filepath: string }> { const r = Math.floor(Math.random() * 1000000); const filepath = path.resolve( - `${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}` + `${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}`, ); await Deno.mkdir(path.dirname(filepath), { recursive: true }); const file = await Deno.open(filepath, { diff --git a/std/log/handlers.ts b/std/log/handlers.ts index e09dc648c..21c25a816 100644 --- a/std/log/handlers.ts +++ b/std/log/handlers.ts @@ -195,7 +195,7 @@ export class RotatingFileHandler extends FileHandler { if (await exists(this._filename + "." + i)) { this.destroy(); throw new Deno.errors.AlreadyExists( - "Backup log file " + this._filename + "." + i + " already exists" + "Backup log file " + this._filename + "." + i + " already exists", ); } } diff --git a/std/log/handlers_test.ts b/std/log/handlers_test.ts index ef4b69000..8921dd542 100644 --- a/std/log/handlers_test.ts +++ b/std/log/handlers_test.ts @@ -67,7 +67,7 @@ Deno.test("simpleHandler", function (): void { args: [], level: level, loggerName: "default", - }) + }), ); } @@ -88,7 +88,7 @@ Deno.test("testFormatterAsString", function (): void { args: [], level: LogLevels.DEBUG, loggerName: "default", - }) + }), ); assertEquals(handler.messages, ["test DEBUG Hello, world!"]); @@ -105,7 +105,7 @@ Deno.test("testFormatterWithEmptyMsg", function () { args: [], level: LogLevels.DEBUG, loggerName: "default", - }) + }), ); assertEquals(handler.messages, ["test DEBUG "]); @@ -123,7 +123,7 @@ Deno.test("testFormatterAsFunction", function (): void { args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); assertEquals(handler.messages, ["fn formatter ERROR Hello, world!"]); @@ -144,7 +144,7 @@ Deno.test({ args: [], level: LogLevels.WARNING, loggerName: "default", - }) + }), ); await fileHandler.destroy(); const firstFileSize = (await Deno.stat(LOG_FILE)).size; @@ -156,7 +156,7 @@ Deno.test({ args: [], level: LogLevels.WARNING, loggerName: "default", - }) + }), ); await fileHandler.destroy(); const secondFileSize = (await Deno.stat(LOG_FILE)).size; @@ -192,15 +192,15 @@ Deno.test({ Deno.writeFileSync(LOG_FILE, new TextEncoder().encode("hello world")); Deno.writeFileSync( LOG_FILE + ".1", - new TextEncoder().encode("hello world") + new TextEncoder().encode("hello world"), ); Deno.writeFileSync( LOG_FILE + ".2", - new TextEncoder().encode("hello world") + new TextEncoder().encode("hello world"), ); Deno.writeFileSync( LOG_FILE + ".3", - new TextEncoder().encode("hello world") + new TextEncoder().encode("hello world"), ); const fileHandler = new RotatingFileHandler("WARNING", { @@ -227,7 +227,7 @@ Deno.test({ async fn() { Deno.writeFileSync( LOG_FILE + ".3", - new TextEncoder().encode("hello world") + new TextEncoder().encode("hello world"), ); const fileHandler = new RotatingFileHandler("WARNING", { filename: LOG_FILE, @@ -240,7 +240,7 @@ Deno.test({ await fileHandler.setup(); }, Deno.errors.AlreadyExists, - "Backup log file " + LOG_FILE + ".3 already exists" + "Backup log file " + LOG_FILE + ".3 already exists", ); fileHandler.destroy(); @@ -266,7 +266,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); // 'ERROR AAA\n' = 10 bytes fileHandler.flush(); assertEquals((await Deno.stat(LOG_FILE)).size, 10); @@ -276,7 +276,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); fileHandler.flush(); assertEquals((await Deno.stat(LOG_FILE)).size, 20); @@ -286,7 +286,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); fileHandler.flush(); // Rollover occurred. Log file now has 1 record, rollover file has the original 2 @@ -316,7 +316,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); // 'ERROR AAA\n' = 10 bytes fileHandler.handle( new LogRecord({ @@ -324,7 +324,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); fileHandler.handle( new LogRecord({ @@ -332,7 +332,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); await fileHandler.destroy(); @@ -351,15 +351,15 @@ Deno.test({ Deno.writeFileSync(LOG_FILE, new TextEncoder().encode("original log file")); Deno.writeFileSync( LOG_FILE + ".1", - new TextEncoder().encode("original log.1 file") + new TextEncoder().encode("original log.1 file"), ); Deno.writeFileSync( LOG_FILE + ".2", - new TextEncoder().encode("original log.2 file") + new TextEncoder().encode("original log.2 file"), ); Deno.writeFileSync( LOG_FILE + ".3", - new TextEncoder().encode("original log.3 file") + new TextEncoder().encode("original log.3 file"), ); const fileHandler = new RotatingFileHandler("WARNING", { @@ -375,7 +375,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); // 'ERROR AAA\n' = 10 bytes await fileHandler.destroy(); @@ -383,15 +383,15 @@ Deno.test({ assertEquals(decoder.decode(Deno.readFileSync(LOG_FILE)), "ERROR AAA\n"); assertEquals( decoder.decode(Deno.readFileSync(LOG_FILE + ".1")), - "original log file" + "original log file", ); assertEquals( decoder.decode(Deno.readFileSync(LOG_FILE + ".2")), - "original log.1 file" + "original log.1 file", ); assertEquals( decoder.decode(Deno.readFileSync(LOG_FILE + ".3")), - "original log.2 file" + "original log.2 file", ); assert(!existsSync(LOG_FILE + ".4")); @@ -416,7 +416,7 @@ Deno.test({ await fileHandler.setup(); }, Error, - "maxBytes cannot be less than 1" + "maxBytes cannot be less than 1", ); }, }); @@ -435,7 +435,7 @@ Deno.test({ await fileHandler.setup(); }, Error, - "maxBackupCount cannot be less than 1" + "maxBackupCount cannot be less than 1", ); }, }); @@ -454,7 +454,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); // 'ERROR AAA\n' = 10 bytes assertEquals((await Deno.stat(LOG_FILE)).size, 0); @@ -514,7 +514,7 @@ Deno.test({ args: [], level: LogLevels.ERROR, loggerName: "default", - }) + }), ); // ERROR won't trigger immediate flush @@ -527,7 +527,7 @@ Deno.test({ args: [], level: LogLevels.CRITICAL, loggerName: "default", - }) + }), ); // CRITICAL will trigger immediate flush diff --git a/std/log/logger.ts b/std/log/logger.ts index 482047f2a..ef4bfd58f 100644 --- a/std/log/logger.ts +++ b/std/log/logger.ts @@ -50,7 +50,7 @@ export class Logger { constructor( loggerName: string, levelName: LevelName, - options: LoggerOptions = {} + options: LoggerOptions = {}, ) { this.#loggerName = loggerName; this.#level = getLevelByName(levelName); diff --git a/std/log/logger_test.ts b/std/log/logger_test.ts index f7b438cba..08080356b 100644 --- a/std/log/logger_test.ts +++ b/std/log/logger_test.ts @@ -129,11 +129,11 @@ Deno.test( const inlineData: string | undefined = logger.debug( expensiveFunction, 1, - 2 + 2, ); assert(!called); assertEquals(inlineData, undefined); - } + }, ); Deno.test("String resolver fn resolves as expected", function (): void { @@ -235,7 +235,7 @@ Deno.test( }); const data18: { payload: string; other: number } = logger.error( { payload: "data", other: 123 }, - 1 + 1, ); assertEquals(data18, { payload: "data", @@ -243,5 +243,5 @@ Deno.test( }); assertEquals(handler.messages[16], 'ERROR {"payload":"data","other":123}'); assertEquals(handler.messages[17], 'ERROR {"payload":"data","other":123}'); - } + }, ); diff --git a/std/log/mod.ts b/std/log/mod.ts index 9565749aa..3960a65a3 100644 --- a/std/log/mod.ts +++ b/std/log/mod.ts @@ -60,7 +60,7 @@ export function getLogger(name?: string): Logger { const d = state.loggers.get("default"); assert( d != null, - `"default" logger must be set for getting logger without name` + `"default" logger must be set for getting logger without name`, ); return d; } diff --git a/std/mime/multipart.ts b/std/mime/multipart.ts index 0d60fd00b..6597a1bea 100644 --- a/std/mime/multipart.ts +++ b/std/mime/multipart.ts @@ -59,7 +59,7 @@ function randomBoundary(): string { export function matchAfterPrefix( buf: Uint8Array, prefix: Uint8Array, - eof: boolean + eof: boolean, ): -1 | 0 | 1 { if (buf.length === prefix.length) { return eof ? 1 : 0; @@ -98,7 +98,7 @@ export function scanUntilBoundary( dashBoundary: Uint8Array, newLineDashBoundary: Uint8Array, total: number, - eof: boolean + eof: boolean, ): number | null { if (total === 0) { // At beginning of body, allow dashBoundary. @@ -168,7 +168,7 @@ class PartReader implements Deno.Reader, Deno.Closer { this.mr.dashBoundary, this.mr.newLineDashBoundary, this.total, - eof + eof, ); if (this.n === 0) { // Force buffered I/O to read more into buffer. @@ -417,7 +417,7 @@ export class MultipartReader { function multipatFormData( fileMap: Map<string, FormFile | FormFile[]>, - valueMap: Map<string, string> + valueMap: Map<string, string>, ): MultipartFormData { function file(key: string): FormFile | FormFile[] | undefined { return fileMap.get(key); @@ -468,7 +468,7 @@ class PartWriter implements Deno.Writer { private writer: Deno.Writer, readonly boundary: string, public headers: Headers, - isFirstBoundary: boolean + isFirstBoundary: boolean, ) { let buf = ""; if (isFirstBoundary) { @@ -549,7 +549,7 @@ export class MultipartWriter { this.writer, this.boundary, headers, - !this.lastPart + !this.lastPart, ); this.lastPart = part; return part; @@ -559,7 +559,7 @@ export class MultipartWriter { const h = new Headers(); h.set( "Content-Disposition", - `form-data; name="${field}"; filename="${filename}"` + `form-data; name="${field}"; filename="${filename}"`, ); h.set("Content-Type", "application/octet-stream"); return this.createPart(h); @@ -580,7 +580,7 @@ export class MultipartWriter { async writeFile( field: string, filename: string, - file: Deno.Reader + file: Deno.Reader, ): Promise<void> { const f = await this.createFormFile(field, filename); await Deno.copy(file, f); diff --git a/std/mime/multipart_test.ts b/std/mime/multipart_test.ts index c0282ee3b..d2cfb2ee5 100644 --- a/std/mime/multipart_test.ts +++ b/std/mime/multipart_test.ts @@ -28,7 +28,7 @@ Deno.test("multipartScanUntilBoundary1", function (): void { dashBoundary, nlDashBoundary, 0, - true + true, ); assertEquals(n, null); }); @@ -40,7 +40,7 @@ Deno.test("multipartScanUntilBoundary2", function (): void { dashBoundary, nlDashBoundary, 0, - true + true, ); assertEquals(n, 3); }); @@ -52,7 +52,7 @@ Deno.test("multipartScanUntilBoundary3", function (): void { dashBoundary, nlDashBoundary, 0, - false + false, ); assertEquals(n, data.length); }); @@ -64,7 +64,7 @@ Deno.test("multipartScanUntilBoundary4", function (): void { dashBoundary, nlDashBoundary, 0, - false + false, ); assertEquals(n, 3); }); @@ -105,27 +105,27 @@ Deno.test("multipartMultipartWriter2", function (): void { assertThrows( (): MultipartWriter => new MultipartWriter(w, ""), Error, - "invalid boundary length" + "invalid boundary length", ); assertThrows( (): MultipartWriter => new MultipartWriter( w, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + - "aaaaaaaa" + "aaaaaaaa", ), Error, - "invalid boundary length" + "invalid boundary length", ); assertThrows( (): MultipartWriter => new MultipartWriter(w, "aaa aaa"), Error, - "invalid boundary character" + "invalid boundary character", ); assertThrows( (): MultipartWriter => new MultipartWriter(w, "boundary¥¥"), Error, - "invalid boundary character" + "invalid boundary character", ); }); @@ -139,7 +139,7 @@ Deno.test("multipartMultipartWriter3", async function (): Promise<void> { await mw.close(); }, Error, - "closed" + "closed", ); await assertThrowsAsync( async (): Promise<void> => { @@ -147,28 +147,28 @@ Deno.test("multipartMultipartWriter3", async function (): Promise<void> { await mw.writeFile("bar", "file", null as any); }, Error, - "closed" + "closed", ); await assertThrowsAsync( async (): Promise<void> => { await mw.writeField("bar", "bar"); }, Error, - "closed" + "closed", ); assertThrows( (): void => { mw.createFormField("bar"); }, Error, - "closed" + "closed", ); assertThrows( (): void => { mw.createFormFile("bar", "file"); }, Error, - "closed" + "closed", ); }); @@ -178,7 +178,7 @@ Deno.test({ const o = await Deno.open(path.resolve("./mime/testdata/sample.txt")); const mr = new MultipartReader( o, - "--------------------------434049563556637648550474" + "--------------------------434049563556637648550474", ); const form = await mr.readForm(); assertEquals(form.value("foo"), "foo"); @@ -250,7 +250,7 @@ Deno.test({ const o = await Deno.open(path.resolve("./mime/testdata/sample.txt")); const mr = new MultipartReader( o, - "--------------------------434049563556637648550474" + "--------------------------434049563556637648550474", ); const form = await mr.readForm(20); let file = form.file("file"); @@ -277,7 +277,7 @@ Deno.test({ const o = await Deno.open(path.resolve("./mime/testdata/sample.txt")); const mr = new MultipartReader( o, - "--------------------------434049563556637648550474" + "--------------------------434049563556637648550474", ); const form = await mr.readForm(); const map = new Map(form.entries()); diff --git a/std/node/_fs/_fs_access.ts b/std/node/_fs/_fs_access.ts index 79e4ca96d..df84eac9c 100644 --- a/std/node/_fs/_fs_access.ts +++ b/std/node/_fs/_fs_access.ts @@ -10,7 +10,7 @@ import { notImplemented } from "../_utils.ts"; export function access( path: string | URL, // eslint-disable-line @typescript-eslint/no-unused-vars modeOrCallback: number | Function, // eslint-disable-line @typescript-eslint/no-unused-vars - callback?: CallbackWithError // eslint-disable-line @typescript-eslint/no-unused-vars + callback?: CallbackWithError, // eslint-disable-line @typescript-eslint/no-unused-vars ): void { notImplemented("Not yet available"); } diff --git a/std/node/_fs/_fs_appendFile.ts b/std/node/_fs/_fs_appendFile.ts index c057c1f65..bc30de609 100644 --- a/std/node/_fs/_fs_appendFile.ts +++ b/std/node/_fs/_fs_appendFile.ts @@ -17,7 +17,7 @@ export function appendFile( pathOrRid: string | number | URL, data: string, optionsOrCallback: Encodings | WriteFileOptions | CallbackWithError, - callback?: CallbackWithError + callback?: CallbackWithError, ): void { pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid; const callbackFn: CallbackWithError | undefined = @@ -80,7 +80,7 @@ function closeRidIfNecessary(isPathString: boolean, rid: number): void { export function appendFileSync( pathOrRid: string | number | URL, data: string, - options?: Encodings | WriteFileOptions + options?: Encodings | WriteFileOptions, ): void { let rid = -1; @@ -116,7 +116,7 @@ export function appendFileSync( } function validateEncoding( - encodingOption: Encodings | WriteFileOptions | undefined + encodingOption: Encodings | WriteFileOptions | undefined, ): void { if (!encodingOption) return; diff --git a/std/node/_fs/_fs_appendFile_test.ts b/std/node/_fs/_fs_appendFile_test.ts index 9c0ccb666..d41065205 100644 --- a/std/node/_fs/_fs_appendFile_test.ts +++ b/std/node/_fs/_fs_appendFile_test.ts @@ -13,7 +13,7 @@ Deno.test({ appendFile("some/path", "some data", "utf8"); }, Error, - "No callback function supplied" + "No callback function supplied", ); }, }); @@ -27,7 +27,7 @@ Deno.test({ appendFile("some/path", "some data", "made-up-encoding", () => {}); }, Error, - "Only 'utf8' encoding is currently supported" + "Only 'utf8' encoding is currently supported", ); assertThrows( () => { @@ -36,17 +36,17 @@ Deno.test({ "some data", // @ts-expect-error Type '"made-up-encoding"' is not assignable to type { encoding: "made-up-encoding" }, - () => {} + () => {}, ); }, Error, - "Only 'utf8' encoding is currently supported" + "Only 'utf8' encoding is currently supported", ); assertThrows( // @ts-expect-error Type '"made-up-encoding"' is not assignable to type () => appendFileSync("some/path", "some data", "made-up-encoding"), Error, - "Only 'utf8' encoding is currently supported" + "Only 'utf8' encoding is currently supported", ); assertThrows( () => @@ -55,7 +55,7 @@ Deno.test({ encoding: "made-up-encoding", }), Error, - "Only 'utf8' encoding is currently supported" + "Only 'utf8' encoding is currently supported", ); }, }); @@ -200,7 +200,7 @@ Deno.test({ assertThrows( () => appendFileSync(tempFile, "hello world", { flag: "ax" }), Deno.errors.AlreadyExists, - "" + "", ); assertEquals(Deno.resources(), openResourcesBeforeAppend); Deno.removeSync(tempFile); diff --git a/std/node/_fs/_fs_chmod.ts b/std/node/_fs/_fs_chmod.ts index 844afd21d..9a8277b45 100644 --- a/std/node/_fs/_fs_chmod.ts +++ b/std/node/_fs/_fs_chmod.ts @@ -12,7 +12,7 @@ const allowedModes = /^[0-7]{3}/; export function chmod( path: string | URL, mode: string | number, - callback: CallbackWithError + callback: CallbackWithError, ): void { path = path instanceof URL ? fromFileUrl(path) : path; diff --git a/std/node/_fs/_fs_chown.ts b/std/node/_fs/_fs_chown.ts index 56068ef73..ae3af0121 100644 --- a/std/node/_fs/_fs_chown.ts +++ b/std/node/_fs/_fs_chown.ts @@ -11,7 +11,7 @@ export function chown( path: string | URL, uid: number, gid: number, - callback: CallbackWithError + callback: CallbackWithError, ): void { path = path instanceof URL ? fromFileUrl(path) : path; diff --git a/std/node/_fs/_fs_common.ts b/std/node/_fs/_fs_common.ts index 3c20ca73e..165b9aeca 100644 --- a/std/node/_fs/_fs_common.ts +++ b/std/node/_fs/_fs_common.ts @@ -35,7 +35,7 @@ export interface WriteFileOptions extends FileOptions { } export function isFileOptions( - fileOptions: string | WriteFileOptions | undefined + fileOptions: string | WriteFileOptions | undefined, ): fileOptions is FileOptions { if (!fileOptions) return false; @@ -47,14 +47,15 @@ export function isFileOptions( } export function getEncoding( - optOrCallback?: FileOptions | WriteFileOptions | Function | Encodings | null + optOrCallback?: FileOptions | WriteFileOptions | Function | Encodings | null, ): Encodings | null { if (!optOrCallback || typeof optOrCallback === "function") { return null; } - const encoding = - typeof optOrCallback === "string" ? optOrCallback : optOrCallback.encoding; + const encoding = typeof optOrCallback === "string" + ? optOrCallback + : optOrCallback.encoding; if (!encoding) return null; return encoding; } diff --git a/std/node/_fs/_fs_copy.ts b/std/node/_fs/_fs_copy.ts index 72f43d18f..ba530a85c 100644 --- a/std/node/_fs/_fs_copy.ts +++ b/std/node/_fs/_fs_copy.ts @@ -6,7 +6,7 @@ import { fromFileUrl } from "../path.ts"; export function copyFile( source: string | URL, destination: string, - callback: CallbackWithError + callback: CallbackWithError, ): void { source = source instanceof URL ? fromFileUrl(source) : source; diff --git a/std/node/_fs/_fs_dir_test.ts b/std/node/_fs/_fs_dir_test.ts index 2d2d5f585..4c2806389 100644 --- a/std/node/_fs/_fs_dir_test.ts +++ b/std/node/_fs/_fs_dir_test.ts @@ -49,7 +49,7 @@ Deno.test({ let calledBack = false; const fileFromCallback: Dirent | null = await new Dir( - testDir + testDir, // eslint-disable-next-line @typescript-eslint/no-explicit-any ).read((err: any, res: Dirent) => { assert(res === null); @@ -83,10 +83,11 @@ Deno.test({ // eslint-disable-next-line @typescript-eslint/no-explicit-any (err: any, secondResult: Dirent) => { assert( - secondResult.name === "bar.txt" || secondResult.name === "foo.txt" + secondResult.name === "bar.txt" || + secondResult.name === "foo.txt", ); secondCallback = true; - } + }, ); const thirdRead: Dirent | null = await dir.read(); const fourthRead: Dirent | null = await dir.read(); diff --git a/std/node/_fs/_fs_dirent.ts b/std/node/_fs/_fs_dirent.ts index 3ea1def42..24e43145c 100644 --- a/std/node/_fs/_fs_dirent.ts +++ b/std/node/_fs/_fs_dirent.ts @@ -10,7 +10,7 @@ export default class Dirent { isCharacterDevice(): boolean { notImplemented( - "Deno does not yet support identification of character devices" + "Deno does not yet support identification of character devices", ); return false; } @@ -21,7 +21,7 @@ export default class Dirent { isFIFO(): boolean { notImplemented( - "Deno does not yet support identification of FIFO named pipes" + "Deno does not yet support identification of FIFO named pipes", ); return false; } diff --git a/std/node/_fs/_fs_dirent_test.ts b/std/node/_fs/_fs_dirent_test.ts index 8c4b98214..aeb20f1d5 100644 --- a/std/node/_fs/_fs_dirent_test.ts +++ b/std/node/_fs/_fs_dirent_test.ts @@ -65,14 +65,14 @@ Deno.test({ new Dirent(entry).isFIFO(); }, Error, - "does not yet support" + "does not yet support", ); assertThrows( () => { new Dirent(entry).isSocket(); }, Error, - "does not yet support" + "does not yet support", ); }, }); diff --git a/std/node/_fs/_fs_link.ts b/std/node/_fs/_fs_link.ts index df08e13b1..42ca3de89 100644 --- a/std/node/_fs/_fs_link.ts +++ b/std/node/_fs/_fs_link.ts @@ -10,10 +10,11 @@ import { fromFileUrl } from "../path.ts"; export function link( existingPath: string | URL, newPath: string | URL, - callback: CallbackWithError + callback: CallbackWithError, ): void { - existingPath = - existingPath instanceof URL ? fromFileUrl(existingPath) : existingPath; + existingPath = existingPath instanceof URL + ? fromFileUrl(existingPath) + : existingPath; newPath = newPath instanceof URL ? fromFileUrl(newPath) : newPath; Deno.link(existingPath, newPath) @@ -27,10 +28,11 @@ export function link( */ export function linkSync( existingPath: string | URL, - newPath: string | URL + newPath: string | URL, ): void { - existingPath = - existingPath instanceof URL ? fromFileUrl(existingPath) : existingPath; + existingPath = existingPath instanceof URL + ? fromFileUrl(existingPath) + : existingPath; newPath = newPath instanceof URL ? fromFileUrl(newPath) : newPath; Deno.linkSync(existingPath, newPath); diff --git a/std/node/_fs/_fs_mkdir.ts b/std/node/_fs/_fs_mkdir.ts index 8578f4653..63aabd010 100644 --- a/std/node/_fs/_fs_mkdir.ts +++ b/std/node/_fs/_fs_mkdir.ts @@ -14,7 +14,7 @@ type MkdirOptions = export function mkdir( path: string | URL, options?: MkdirOptions | CallbackWithError, - callback?: CallbackWithError + callback?: CallbackWithError, ): void { path = path instanceof URL ? fromFileUrl(path) : path; @@ -33,7 +33,7 @@ export function mkdir( } if (typeof recursive !== "boolean") { throw new Deno.errors.InvalidData( - "invalid recursive option , must be a boolean" + "invalid recursive option , must be a boolean", ); } Deno.mkdir(path, { recursive, mode }) @@ -64,7 +64,7 @@ export function mkdirSync(path: string | URL, options?: MkdirOptions): void { } if (typeof recursive !== "boolean") { throw new Deno.errors.InvalidData( - "invalid recursive option , must be a boolean" + "invalid recursive option , must be a boolean", ); } diff --git a/std/node/_fs/_fs_readFile.ts b/std/node/_fs/_fs_readFile.ts index 39c3d8393..2aef28290 100644 --- a/std/node/_fs/_fs_readFile.ts +++ b/std/node/_fs/_fs_readFile.ts @@ -14,11 +14,11 @@ import { fromFileUrl } from "../path.ts"; function maybeDecode(data: Uint8Array, encoding: TextEncodings): string; function maybeDecode( data: Uint8Array, - encoding: BinaryEncodings | null + encoding: BinaryEncodings | null, ): Buffer; function maybeDecode( data: Uint8Array, - encoding: Encodings | null + encoding: Encodings | null, ): string | Buffer { const buffer = new Buffer(data.buffer, data.byteOffset, data.byteLength); if (encoding && encoding !== "binary") return buffer.toString(encoding); @@ -33,23 +33,23 @@ type Callback = TextCallback | BinaryCallback | GenericCallback; export function readFile( path: string | URL, options: TextOptionsArgument, - callback: TextCallback + callback: TextCallback, ): void; export function readFile( path: string | URL, options: BinaryOptionsArgument, - callback: BinaryCallback + callback: BinaryCallback, ): void; export function readFile( path: string | URL, options: null | undefined | FileOptionsArgument, - callback: BinaryCallback + callback: BinaryCallback, ): void; export function readFile(path: string | URL, callback: BinaryCallback): void; export function readFile( path: string | URL, optOrCallback?: FileOptionsArgument | Callback | null | undefined, - callback?: Callback + callback?: Callback, ): void { path = path instanceof URL ? fromFileUrl(path) : path; let cb: Callback | undefined; @@ -77,15 +77,15 @@ export function readFile( export function readFileSync( path: string | URL, - opt: TextOptionsArgument + opt: TextOptionsArgument, ): string; export function readFileSync( path: string | URL, - opt?: BinaryOptionsArgument + opt?: BinaryOptionsArgument, ): Buffer; export function readFileSync( path: string | URL, - opt?: FileOptionsArgument + opt?: FileOptionsArgument, ): string | Buffer { path = path instanceof URL ? fromFileUrl(path) : path; const data = Deno.readFileSync(path); diff --git a/std/node/_fs/_fs_readFile_test.ts b/std/node/_fs/_fs_readFile_test.ts index 076c4b276..ff449dbb2 100644 --- a/std/node/_fs/_fs_readFile_test.ts +++ b/std/node/_fs/_fs_readFile_test.ts @@ -3,7 +3,7 @@ import * as path from "../../path/mod.ts"; import { assertEquals, assert } from "../../testing/asserts.ts"; const testData = path.resolve( - path.join("node", "_fs", "testdata", "hello.txt") + path.join("node", "_fs", "testdata", "hello.txt"), ); Deno.test("readFileSuccess", async function () { diff --git a/std/node/_fs/_fs_readlink.ts b/std/node/_fs/_fs_readlink.ts index 11ce43f55..866ea187b 100644 --- a/std/node/_fs/_fs_readlink.ts +++ b/std/node/_fs/_fs_readlink.ts @@ -8,7 +8,7 @@ import { fromFileUrl } from "../path.ts"; type ReadlinkCallback = ( err: MaybeEmpty<Error>, - linkString: MaybeEmpty<string | Uint8Array> + linkString: MaybeEmpty<string | Uint8Array>, ) => void; interface ReadlinkOptions { @@ -17,7 +17,7 @@ interface ReadlinkOptions { function maybeEncode( data: string, - encoding: string | null + encoding: string | null, ): string | Uint8Array { if (encoding === "buffer") { return new TextEncoder().encode(data); @@ -26,7 +26,7 @@ function maybeEncode( } function getEncoding( - optOrCallback?: ReadlinkOptions | ReadlinkCallback + optOrCallback?: ReadlinkOptions | ReadlinkCallback, ): string | null { if (!optOrCallback || typeof optOrCallback === "function") { return null; @@ -50,7 +50,7 @@ function getEncoding( export function readlink( path: string | URL, optOrCallback: ReadlinkCallback | ReadlinkOptions, - callback?: ReadlinkCallback + callback?: ReadlinkCallback, ): void { path = path instanceof URL ? fromFileUrl(path) : path; @@ -67,13 +67,13 @@ export function readlink( Deno.readLink, (data: string): string | Uint8Array => maybeEncode(data, encoding), cb, - path + path, ); } export function readlinkSync( path: string | URL, - opt?: ReadlinkOptions + opt?: ReadlinkOptions, ): string | Uint8Array { path = path instanceof URL ? fromFileUrl(path) : path; diff --git a/std/node/_fs/_fs_writeFile.ts b/std/node/_fs/_fs_writeFile.ts index 8a66f3f3d..a8ae1f586 100644 --- a/std/node/_fs/_fs_writeFile.ts +++ b/std/node/_fs/_fs_writeFile.ts @@ -17,7 +17,7 @@ export function writeFile( pathOrRid: string | number | URL, data: string | Uint8Array, optOrCallback: Encodings | CallbackWithError | WriteFileOptions | undefined, - callback?: CallbackWithError + callback?: CallbackWithError, ): void { const callbackFn: CallbackWithError | undefined = optOrCallback instanceof Function ? optOrCallback : callback; @@ -72,7 +72,7 @@ export function writeFile( export function writeFileSync( pathOrRid: string | number | URL, data: string | Uint8Array, - options?: Encodings | WriteFileOptions + options?: Encodings | WriteFileOptions, ): void { pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid; diff --git a/std/node/_fs/_fs_writeFile_test.ts b/std/node/_fs/_fs_writeFile_test.ts index 015ed6553..a11e0fb67 100644 --- a/std/node/_fs/_fs_writeFile_test.ts +++ b/std/node/_fs/_fs_writeFile_test.ts @@ -18,7 +18,7 @@ Deno.test("Callback must be a function error", function fn() { writeFile("some/path", "some data", "utf8"); }, TypeError, - "Callback must be a function." + "Callback must be a function.", ); }); @@ -29,7 +29,7 @@ Deno.test("Invalid encoding results in error()", function testEncodingErrors() { writeFile("some/path", "some data", "made-up-encoding", () => {}); }, Error, - `The value "made-up-encoding" is invalid for option "encoding"` + `The value "made-up-encoding" is invalid for option "encoding"`, ); assertThrows( @@ -38,7 +38,7 @@ Deno.test("Invalid encoding results in error()", function testEncodingErrors() { writeFileSync("some/path", "some data", "made-up-encoding"); }, Error, - `The value "made-up-encoding" is invalid for option "encoding"` + `The value "made-up-encoding" is invalid for option "encoding"`, ); assertThrows( @@ -50,11 +50,11 @@ Deno.test("Invalid encoding results in error()", function testEncodingErrors() { // @ts-expect-error Type '"made-up-encoding"' is not assignable to type encoding: "made-up-encoding", }, - () => {} + () => {}, ); }, Error, - `The value "made-up-encoding" is invalid for option "encoding"` + `The value "made-up-encoding" is invalid for option "encoding"`, ); assertThrows( @@ -65,7 +65,7 @@ Deno.test("Invalid encoding results in error()", function testEncodingErrors() { }); }, Error, - `The value "made-up-encoding" is invalid for option "encoding"` + `The value "made-up-encoding" is invalid for option "encoding"`, ); }); @@ -77,7 +77,7 @@ Deno.test( writeFile("some/path", "some data", "utf16le", () => {}); }, Error, - `Not implemented: "utf16le" encoding` + `Not implemented: "utf16le" encoding`, ); assertThrows( @@ -85,9 +85,9 @@ Deno.test( writeFileSync("some/path", "some data", "utf16le"); }, Error, - `Not implemented: "utf16le" encoding` + `Not implemented: "utf16le" encoding`, ); - } + }, ); Deno.test( @@ -111,7 +111,7 @@ Deno.test( const data = await Deno.readFile(tempFile); await Deno.remove(tempFile); assertEquals(decoder.decode(data), "hello world"); - } + }, ); Deno.test( @@ -125,7 +125,7 @@ Deno.test( await Deno.remove("_fs_writeFile_test_file.txt"); assertEquals(res, null); assertEquals(decoder.decode(data), "hello world"); - } + }, ); Deno.test( @@ -146,7 +146,7 @@ Deno.test( "_fs_writeFile_test_file.txt", value, encoding as TextEncodings, - resolve + resolve, ); }); @@ -155,7 +155,7 @@ Deno.test( assertEquals(res, null); assertEquals(decoder.decode(data), "hello world"); } - } + }, ); Deno.test("Path can be an URL", async function testCorrectWriteUsingURL() { @@ -165,7 +165,7 @@ Deno.test("Path can be an URL", async function testCorrectWriteUsingURL() { path .join(testDataDir, "_fs_writeFile_test_file_url.txt") .replace(/\\/g, "/") - : "file://" + path.join(testDataDir, "_fs_writeFile_test_file_url.txt") + : "file://" + path.join(testDataDir, "_fs_writeFile_test_file_url.txt"), ); const filePath = path.fromFileUrl(url); const res = await new Promise((resolve) => { @@ -218,7 +218,7 @@ Deno.test( await Deno.remove(filename); assert(fileInfo.mode); assertNotEquals(fileInfo.mode & 0o777, 0o777); - } + }, ); Deno.test( @@ -237,7 +237,7 @@ Deno.test( const data = Deno.readFileSync(tempFile); Deno.removeSync(tempFile); assertEquals(decoder.decode(data), "hello world"); - } + }, ); Deno.test( @@ -260,7 +260,7 @@ Deno.test( Deno.removeSync(file); assertEquals(decoder.decode(data), "hello world"); } - } + }, ); Deno.test( @@ -273,18 +273,18 @@ Deno.test( const data = Deno.readFileSync(file); Deno.removeSync(file); assertEquals(decoder.decode(data), "hello world"); - } + }, ); Deno.test("sync: Path can be an URL", function testCorrectWriteSyncUsingURL() { const filePath = path.join( testDataDir, - "_fs_writeFileSync_test_file_url.txt" + "_fs_writeFileSync_test_file_url.txt", ); const url = new URL( Deno.build.os === "windows" ? "file:///" + filePath.replace(/\\/g, "/") - : "file://" + filePath + : "file://" + filePath, ); writeFileSync(url, "hello world"); @@ -305,5 +305,5 @@ Deno.test( Deno.removeSync(filename); assert(fileInfo && fileInfo.mode); assertEquals(fileInfo.mode & 0o777, 0o777); - } + }, ); diff --git a/std/node/_fs/promises/_fs_readFile.ts b/std/node/_fs/promises/_fs_readFile.ts index 8677e05cd..446c48625 100644 --- a/std/node/_fs/promises/_fs_readFile.ts +++ b/std/node/_fs/promises/_fs_readFile.ts @@ -8,15 +8,15 @@ import { readFile as readFileCallback } from "../_fs_readFile.ts"; export function readFile( path: string | URL, - options: TextOptionsArgument + options: TextOptionsArgument, ): Promise<string>; export function readFile( path: string | URL, - options?: BinaryOptionsArgument + options?: BinaryOptionsArgument, ): Promise<Uint8Array>; export function readFile( path: string | URL, - options?: FileOptionsArgument + options?: FileOptionsArgument, ): Promise<string | Uint8Array> { return new Promise((resolve, reject) => { readFileCallback(path, options, (err, data): void => { diff --git a/std/node/_fs/promises/_fs_readFile_test.ts b/std/node/_fs/promises/_fs_readFile_test.ts index 1d2097881..a5f5a1327 100644 --- a/std/node/_fs/promises/_fs_readFile_test.ts +++ b/std/node/_fs/promises/_fs_readFile_test.ts @@ -3,7 +3,7 @@ import * as path from "../../../path/mod.ts"; import { assertEquals, assert } from "../../../testing/asserts.ts"; const testData = path.resolve( - path.join("node", "_fs", "testdata", "hello.txt") + path.join("node", "_fs", "testdata", "hello.txt"), ); Deno.test("readFileSuccess", async function () { diff --git a/std/node/_fs/promises/_fs_writeFile.ts b/std/node/_fs/promises/_fs_writeFile.ts index 48b9bf0ea..1c9ea5032 100644 --- a/std/node/_fs/promises/_fs_writeFile.ts +++ b/std/node/_fs/promises/_fs_writeFile.ts @@ -6,7 +6,7 @@ import { writeFile as writeFileCallback } from "../_fs_writeFile.ts"; export function writeFile( pathOrRid: string | number | URL, data: string | Uint8Array, - options?: Encodings | WriteFileOptions + options?: Encodings | WriteFileOptions, ): Promise<void> { return new Promise((resolve, reject) => { writeFileCallback(pathOrRid, data, options, (err?: Error | null) => { diff --git a/std/node/_fs/promises/_fs_writeFile_test.ts b/std/node/_fs/promises/_fs_writeFile_test.ts index 6901fff22..698284057 100644 --- a/std/node/_fs/promises/_fs_writeFile_test.ts +++ b/std/node/_fs/promises/_fs_writeFile_test.ts @@ -17,7 +17,7 @@ Deno.test("Invalid encoding results in error()", function testEncodingErrors() { await writeFile("some/path", "some data", "made-up-encoding"); }, Error, - `The value "made-up-encoding" is invalid for option "encoding"` + `The value "made-up-encoding" is invalid for option "encoding"`, ); assertThrowsAsync( async () => { @@ -27,7 +27,7 @@ Deno.test("Invalid encoding results in error()", function testEncodingErrors() { }); }, Error, - `The value "made-up-encoding" is invalid for option "encoding"` + `The value "made-up-encoding" is invalid for option "encoding"`, ); }); @@ -39,9 +39,9 @@ Deno.test( await writeFile("some/path", "some data", "utf16le"); }, Error, - `Not implemented: "utf16le" encoding` + `Not implemented: "utf16le" encoding`, ); - } + }, ); Deno.test( @@ -60,7 +60,7 @@ Deno.test( const data = await Deno.readFile(tempFile); await Deno.remove(tempFile); assertEquals(decoder.decode(data), "hello world"); - } + }, ); Deno.test( @@ -74,7 +74,7 @@ Deno.test( const data = await Deno.readFile("_fs_writeFile_test_file.txt"); await Deno.remove("_fs_writeFile_test_file.txt"); assertEquals(decoder.decode(data), "hello world"); - } + }, ); Deno.test( @@ -93,14 +93,14 @@ Deno.test( await writeFile( "_fs_writeFile_test_file.txt", value, - encoding as TextEncodings + encoding as TextEncodings, ); const data = await Deno.readFile("_fs_writeFile_test_file.txt"); await Deno.remove("_fs_writeFile_test_file.txt"); assertEquals(decoder.decode(data), "hello world"); } - } + }, ); Deno.test("Mode is correctly set", async function testCorrectFileMode() { @@ -133,5 +133,5 @@ Deno.test( await Deno.remove(filename); assert(fileInfo.mode); assertNotEquals(fileInfo.mode & 0o777, 0o777); - } + }, ); diff --git a/std/node/_util/_util_callbackify.ts b/std/node/_util/_util_callbackify.ts index 4c752e7ef..b37bf829a 100644 --- a/std/node/_util/_util_callbackify.ts +++ b/std/node/_util/_util_callbackify.ts @@ -42,30 +42,30 @@ type Callback<ResultT> = | ((err: null, result: ResultT) => void); function callbackify<ResultT>( - fn: () => PromiseLike<ResultT> + fn: () => PromiseLike<ResultT>, ): (callback: Callback<ResultT>) => void; function callbackify<ArgT, ResultT>( - fn: (arg: ArgT) => PromiseLike<ResultT> + fn: (arg: ArgT) => PromiseLike<ResultT>, ): (arg: ArgT, callback: Callback<ResultT>) => void; function callbackify<Arg1T, Arg2T, ResultT>( - fn: (arg1: Arg1T, arg2: Arg2T) => PromiseLike<ResultT> + fn: (arg1: Arg1T, arg2: Arg2T) => PromiseLike<ResultT>, ): (arg1: Arg1T, arg2: Arg2T, callback: Callback<ResultT>) => void; function callbackify<Arg1T, Arg2T, Arg3T, ResultT>( - fn: (arg1: Arg1T, arg2: Arg2T, arg3: Arg3T) => PromiseLike<ResultT> + fn: (arg1: Arg1T, arg2: Arg2T, arg3: Arg3T) => PromiseLike<ResultT>, ): (arg1: Arg1T, arg2: Arg2T, arg3: Arg3T, callback: Callback<ResultT>) => void; function callbackify<Arg1T, Arg2T, Arg3T, Arg4T, ResultT>( fn: ( arg1: Arg1T, arg2: Arg2T, arg3: Arg3T, - arg4: Arg4T - ) => PromiseLike<ResultT> + arg4: Arg4T, + ) => PromiseLike<ResultT>, ): ( arg1: Arg1T, arg2: Arg2T, arg3: Arg3T, arg4: Arg4T, - callback: Callback<ResultT> + callback: Callback<ResultT>, ) => void; function callbackify<Arg1T, Arg2T, Arg3T, Arg4T, Arg5T, ResultT>( fn: ( @@ -73,15 +73,15 @@ function callbackify<Arg1T, Arg2T, Arg3T, Arg4T, Arg5T, ResultT>( arg2: Arg2T, arg3: Arg3T, arg4: Arg4T, - arg5: Arg5T - ) => PromiseLike<ResultT> + arg5: Arg5T, + ) => PromiseLike<ResultT>, ): ( arg1: Arg1T, arg2: Arg2T, arg3: Arg3T, arg4: Arg4T, arg5: Arg5T, - callback: Callback<ResultT> + callback: Callback<ResultT>, ) => void; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -105,7 +105,7 @@ function callbackify(original: any): any { (rej: unknown) => { rej = rej || new NodeFalsyValueRejectionError(rej); queueMicrotask(cb.bind(this, rej)); - } + }, ); }; diff --git a/std/node/_util/_util_callbackify_test.ts b/std/node/_util/_util_callbackify_test.ts index e8a313905..d585f0551 100644 --- a/std/node/_util/_util_callbackify_test.ts +++ b/std/node/_util/_util_callbackify_test.ts @@ -58,7 +58,7 @@ class TestQueue { if (this.#queueSize === 0) { assert( this.#resolve, - "Test setup error; async queue is missing #resolve" + "Test setup error; async queue is missing #resolve", ); this.#resolve(); } @@ -127,7 +127,7 @@ Deno.test( } await testQueue.waitForCompletion(); - } + }, ); Deno.test( @@ -152,7 +152,7 @@ Deno.test( assertStrictEquals( // eslint-disable-next-line @typescript-eslint/no-explicit-any (err as any).code, - "ERR_FALSY_VALUE_REJECTION" + "ERR_FALSY_VALUE_REJECTION", ); // eslint-disable-next-line @typescript-eslint/no-explicit-any assertStrictEquals((err as any).reason, value); @@ -188,7 +188,7 @@ Deno.test( assertStrictEquals( // eslint-disable-next-line @typescript-eslint/no-explicit-any (err as any).code, - "ERR_FALSY_VALUE_REJECTION" + "ERR_FALSY_VALUE_REJECTION", ); // eslint-disable-next-line @typescript-eslint/no-explicit-any assertStrictEquals((err as any).reason, value); @@ -222,7 +222,7 @@ Deno.test( assertStrictEquals( // eslint-disable-next-line @typescript-eslint/no-explicit-any (err as any).code, - "ERR_FALSY_VALUE_REJECTION" + "ERR_FALSY_VALUE_REJECTION", ); // eslint-disable-next-line @typescript-eslint/no-explicit-any assertStrictEquals((err as any).reason, value); @@ -238,7 +238,7 @@ Deno.test( } await testQueue.waitForCompletion(); - } + }, ); Deno.test("callbackify passes arguments to the original", async () => { @@ -304,7 +304,7 @@ Deno.test("callbackify preserves the `this` binding", async () => { cbSyncFunction.call(objectWithSyncFunction, value, function ( this: unknown, err: unknown, - ret: unknown + ret: unknown, ) { assertStrictEquals(err, null); assertStrictEquals(ret, value); @@ -325,7 +325,7 @@ Deno.test("callbackify preserves the `this` binding", async () => { cbAsyncFunction.call(objectWithAsyncFunction, value, function ( this: unknown, err: unknown, - ret: unknown + ret: unknown, ) { assertStrictEquals(err, null); assertStrictEquals(ret, value); @@ -351,7 +351,7 @@ Deno.test("callbackify throws with non-function inputs", () => { assertStrictEquals(err.name, "TypeError"); assertStrictEquals( err.message, - 'The "original" argument must be of type function.' + 'The "original" argument must be of type function.', ); } }); @@ -382,9 +382,9 @@ Deno.test( assertStrictEquals(err.name, "TypeError"); assertStrictEquals( err.message, - "The last argument must be of type function." + "The last argument must be of type function.", ); } }); - } + }, ); diff --git a/std/node/_util/_util_promisify.ts b/std/node/_util/_util_promisify.ts index ea2fb6a5e..9e86b5a09 100644 --- a/std/node/_util/_util_promisify.ts +++ b/std/node/_util/_util_promisify.ts @@ -32,7 +32,7 @@ declare let Symbol: SymbolConstructor; interface SymbolConstructor { for(key: "nodejs.util.promisify.custom"): typeof _CustomPromisifiedSymbol; for( - key: "nodejs.util.promisify.customArgs" + key: "nodejs.util.promisify.customArgs", ): typeof _CustomPromisifyArgsSymbol; } // End hack. @@ -44,21 +44,22 @@ const kCustomPromisifiedSymbol = Symbol.for("nodejs.util.promisify.custom"); // This is an internal Node symbol used by functions returning multiple // arguments, e.g. ['bytesRead', 'buffer'] for fs.read(). const kCustomPromisifyArgsSymbol = Symbol.for( - "nodejs.util.promisify.customArgs" + "nodejs.util.promisify.customArgs", ); class NodeInvalidArgTypeError extends TypeError { public code = "ERR_INVALID_ARG_TYPE"; constructor(argumentName: string, type: string, received: unknown) { super( - `The "${argumentName}" argument must be of type ${type}. Received ${typeof received}` + `The "${argumentName}" argument must be of type ${type}. Received ${typeof received}`, ); } } export function promisify(original: Function): Function { - if (typeof original !== "function") + if (typeof original !== "function") { throw new NodeInvalidArgTypeError("original", "Function", original); + } // @ts-ignore TypeScript (as of 3.7) does not support indexing namespaces by symbol if (original[kCustomPromisifiedSymbol]) { @@ -68,7 +69,7 @@ export function promisify(original: Function): Function { throw new NodeInvalidArgTypeError( "util.promisify.custom", "Function", - fn + fn, ); } return Object.defineProperty(fn, kCustomPromisifiedSymbol, { @@ -115,7 +116,7 @@ export function promisify(original: Function): Function { }); return Object.defineProperties( fn, - Object.getOwnPropertyDescriptors(original) + Object.getOwnPropertyDescriptors(original), ); } diff --git a/std/node/_util/_util_promisify_test.ts b/std/node/_util/_util_promisify_test.ts index 4369a0132..5148bc609 100644 --- a/std/node/_util/_util_promisify_test.ts +++ b/std/node/_util/_util_promisify_test.ts @@ -36,7 +36,7 @@ Deno.test( "Errors should reject the promise", async function testPromiseRejection() { await assertThrowsAsync(() => readFile("/dontexist"), Deno.errors.NotFound); - } + }, ); Deno.test("Promisify.custom", async function testPromisifyCustom() { @@ -106,7 +106,7 @@ Deno.test( } const value = await promisify(fn)(); assertStrictEquals(value, "foo"); - } + }, ); Deno.test( @@ -117,7 +117,7 @@ Deno.test( } const value = await promisify(fn)(); assertStrictEquals(value, undefined); - } + }, ); Deno.test( @@ -128,7 +128,7 @@ Deno.test( } const value = await promisify(fn)(); assertStrictEquals(value, undefined); - } + }, ); Deno.test( @@ -139,7 +139,7 @@ Deno.test( } const value = await promisify(fn)(null, 42); assertStrictEquals(value, 42); - } + }, ); Deno.test( @@ -151,9 +151,9 @@ Deno.test( await assertThrowsAsync( () => promisify(fn)(new Error("oops"), null), Error, - "oops" + "oops", ); - } + }, ); Deno.test("Rejected value", async function testPromisifyWithAsObjectMethod() { @@ -173,7 +173,7 @@ Deno.test( "Multiple callback", async function testPromisifyWithMultipleCallback() { const err = new Error( - "Should not have called the callback with the error." + "Should not have called the callback with the error.", ); const stack = err.stack; @@ -185,7 +185,7 @@ Deno.test( await fn(); await Promise.resolve(); return assertStrictEquals(stack, err.stack); - } + }, ); Deno.test("Promisify a promise", function testPromisifyPromise() { @@ -203,7 +203,7 @@ Deno.test("Test error", async function testInvalidArguments() { a: number, b: number, c: number, - cb: Function + cb: Function, ): void { errToThrow = new Error(`${a}-${b}-${c}-${cb}`); throw errToThrow; @@ -227,7 +227,7 @@ Deno.test("Test invalid arguments", function testInvalidArguments() { assert(e instanceof TypeError); assertEquals( e.message, - `The "original" argument must be of type Function. Received ${typeof input}` + `The "original" argument must be of type Function. Received ${typeof input}`, ); } }); diff --git a/std/node/_util/_util_types.ts b/std/node/_util/_util_types.ts index df8ccbb05..eaf955b35 100644 --- a/std/node/_util/_util_types.ts +++ b/std/node/_util/_util_types.ts @@ -194,7 +194,8 @@ export function isSymbolObject(value: unknown): boolean { // Adapted from Lodash export function isTypedArray(value: unknown): boolean { /** Used to match `toStringTag` values of typed arrays. */ - const reTypedTag = /^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)Array\]$/; + const reTypedTag = + /^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)Array\]$/; return _isObjectLike(value) && reTypedTag.test(_toString.call(value)); } diff --git a/std/node/_util/_util_types_test.ts b/std/node/_util/_util_types_test.ts index f6dfcfe89..fff0dad0c 100644 --- a/std/node/_util/_util_types_test.ts +++ b/std/node/_util/_util_types_test.ts @@ -229,14 +229,14 @@ Deno.test("Should return false for invalid Float64Array types", () => { Deno.test("Should return true for valid generator functions", () => { assertStrictEquals( isGeneratorFunction(function* foo() {}), - true + true, ); }); Deno.test("Should return false for invalid generator functions", () => { assertStrictEquals( isGeneratorFunction(function foo() {}), - false + false, ); }); @@ -249,7 +249,7 @@ Deno.test("Should return true for valid generator object types", () => { Deno.test("Should return false for invalid generation object types", () => { assertStrictEquals( isGeneratorObject(function* foo() {}), - false + false, ); }); diff --git a/std/node/_utils.ts b/std/node/_utils.ts index 66b7b10d9..0e8b26fb5 100644 --- a/std/node/_utils.ts +++ b/std/node/_utils.ts @@ -65,8 +65,9 @@ function slowCases(enc: string): string | undefined { if (enc === "ucs2") return "utf16le"; break; case 3: - if (enc === "hex" || enc === "HEX" || `${enc}`.toLowerCase() === "hex") + if (enc === "hex" || enc === "HEX" || `${enc}`.toLowerCase() === "hex") { return "hex"; + } break; case 5: if (enc === "ascii") return "ascii"; @@ -93,16 +94,18 @@ function slowCases(enc: string): string | undefined { enc === "utf16le" || enc === "UTF16LE" || `${enc}`.toLowerCase() === "utf16le" - ) + ) { return "utf16le"; + } break; case 8: if ( enc === "utf-16le" || enc === "UTF-16LE" || `${enc}`.toLowerCase() === "utf-16le" - ) + ) { return "utf16le"; + } break; default: if (enc === "") return "utf8"; diff --git a/std/node/buffer.ts b/std/node/buffer.ts index 9c8d8784c..7656803d9 100644 --- a/std/node/buffer.ts +++ b/std/node/buffer.ts @@ -18,8 +18,9 @@ function checkEncoding(encoding = "utf8", strict = true): string { const normalized = normalizeEncoding(encoding); - if (normalized === undefined) + if (normalized === undefined) { throw new TypeError(`Unkown encoding: ${encoding}`); + } if (notImplementedEncodings.includes(encoding)) { notImplemented(`"${encoding}" encoding`); @@ -78,11 +79,11 @@ export default class Buffer extends Uint8Array { static alloc( size: number, fill?: number | string | Uint8Array | Buffer, - encoding = "utf8" + encoding = "utf8", ): Buffer { if (typeof size !== "number") { throw new TypeError( - `The "size" argument must be of type number. Received type ${typeof size}` + `The "size" argument must be of type number. Received type ${typeof size}`, ); } @@ -92,15 +93,17 @@ export default class Buffer extends Uint8Array { let bufFill; if (typeof fill === "string") { encoding = checkEncoding(encoding); - if (typeof fill === "string" && fill.length === 1 && encoding === "utf8") + if ( + typeof fill === "string" && fill.length === 1 && encoding === "utf8" + ) { buf.fill(fill.charCodeAt(0)); - else bufFill = Buffer.from(fill, encoding); + } else bufFill = Buffer.from(fill, encoding); } else if (typeof fill === "number") { buf.fill(fill); } else if (fill instanceof Uint8Array) { if (fill.length === 0) { throw new TypeError( - `The argument "value" is invalid. Received ${fill.constructor.name} []` + `The argument "value" is invalid. Received ${fill.constructor.name} []`, ); } @@ -108,8 +111,9 @@ export default class Buffer extends Uint8Array { } if (bufFill) { - if (bufFill.length > buf.length) + if (bufFill.length > buf.length) { bufFill = bufFill.subarray(0, buf.length); + } let offset = 0; while (offset < size) { @@ -136,7 +140,7 @@ export default class Buffer extends Uint8Array { */ static byteLength( string: string | Buffer | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding = "utf8" + encoding = "utf8", ): number { if (typeof string != "string") return string.byteLength; @@ -180,7 +184,7 @@ export default class Buffer extends Uint8Array { static from( arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, - length?: number + length?: number, ): Buffer; /** * Copies the passed buffer data onto a new Buffer instance. @@ -194,12 +198,14 @@ export default class Buffer extends Uint8Array { // eslint-disable-next-line @typescript-eslint/no-explicit-any value: any, offsetOrEncoding?: number | string, - length?: number + length?: number, ): Buffer { - const offset = - typeof offsetOrEncoding === "string" ? undefined : offsetOrEncoding; - let encoding = - typeof offsetOrEncoding === "string" ? offsetOrEncoding : undefined; + const offset = typeof offsetOrEncoding === "string" + ? undefined + : offsetOrEncoding; + let encoding = typeof offsetOrEncoding === "string" + ? offsetOrEncoding + : undefined; if (typeof value == "string") { encoding = checkEncoding(encoding, false); @@ -236,7 +242,7 @@ export default class Buffer extends Uint8Array { targetBuffer: Buffer | Uint8Array, targetStart = 0, sourceStart = 0, - sourceEnd = this.length + sourceEnd = this.length, ): number { const sourceBuffer = this.subarray(sourceStart, sourceEnd); targetBuffer.set(sourceBuffer, targetStart); @@ -249,7 +255,7 @@ export default class Buffer extends Uint8Array { equals(otherBuffer: Uint8Array | Buffer): boolean { if (!(otherBuffer instanceof Uint8Array)) { throw new TypeError( - `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type ${typeof otherBuffer}` + `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type ${typeof otherBuffer}`, ); } @@ -267,14 +273,14 @@ export default class Buffer extends Uint8Array { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getBigInt64(offset); } readBigInt64LE(offset = 0): bigint { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getBigInt64(offset, true); } @@ -282,14 +288,14 @@ export default class Buffer extends Uint8Array { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getBigUint64(offset); } readBigUInt64LE(offset = 0): bigint { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getBigUint64(offset, true); } @@ -297,14 +303,14 @@ export default class Buffer extends Uint8Array { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getFloat64(offset); } readDoubleLE(offset = 0): number { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getFloat64(offset, true); } @@ -312,50 +318,50 @@ export default class Buffer extends Uint8Array { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getFloat32(offset); } readFloatLE(offset = 0): number { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getFloat32(offset, true); } readInt8(offset = 0): number { return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt8( - offset + offset, ); } readInt16BE(offset = 0): number { return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt16( - offset + offset, ); } readInt16LE(offset = 0): number { return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt16( offset, - true + true, ); } readInt32BE(offset = 0): number { return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt32( - offset + offset, ); } readInt32LE(offset = 0): number { return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt32( offset, - true + true, ); } readUInt8(offset = 0): number { return new DataView(this.buffer, this.byteOffset, this.byteLength).getUint8( - offset + offset, ); } @@ -363,14 +369,14 @@ export default class Buffer extends Uint8Array { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getUint16(offset); } readUInt16LE(offset = 0): number { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getUint16(offset, true); } @@ -378,14 +384,14 @@ export default class Buffer extends Uint8Array { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getUint32(offset); } readUInt32LE(offset = 0): number { return new DataView( this.buffer, this.byteOffset, - this.byteLength + this.byteLength, ).getUint32(offset, true); } @@ -429,14 +435,14 @@ export default class Buffer extends Uint8Array { write(string: string, offset = 0, length = this.length): number { return new TextEncoder().encodeInto( string, - this.subarray(offset, offset + length) + this.subarray(offset, offset + length), ).written; } writeBigInt64BE(value: bigint, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setBigInt64( offset, - value + value, ); return offset + 4; } @@ -444,7 +450,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setBigInt64( offset, value, - true + true, ); return offset + 4; } @@ -452,7 +458,7 @@ export default class Buffer extends Uint8Array { writeBigUInt64BE(value: bigint, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setBigUint64( offset, - value + value, ); return offset + 4; } @@ -460,7 +466,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setBigUint64( offset, value, - true + true, ); return offset + 4; } @@ -468,7 +474,7 @@ export default class Buffer extends Uint8Array { writeDoubleBE(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat64( offset, - value + value, ); return offset + 8; } @@ -476,7 +482,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat64( offset, value, - true + true, ); return offset + 8; } @@ -484,7 +490,7 @@ export default class Buffer extends Uint8Array { writeFloatBE(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat32( offset, - value + value, ); return offset + 4; } @@ -492,7 +498,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat32( offset, value, - true + true, ); return offset + 4; } @@ -500,7 +506,7 @@ export default class Buffer extends Uint8Array { writeInt8(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setInt8( offset, - value + value, ); return offset + 1; } @@ -508,7 +514,7 @@ export default class Buffer extends Uint8Array { writeInt16BE(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setInt16( offset, - value + value, ); return offset + 2; } @@ -516,7 +522,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setInt16( offset, value, - true + true, ); return offset + 2; } @@ -524,7 +530,7 @@ export default class Buffer extends Uint8Array { writeInt32BE(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setUint32( offset, - value + value, ); return offset + 4; } @@ -532,7 +538,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setInt32( offset, value, - true + true, ); return offset + 4; } @@ -540,7 +546,7 @@ export default class Buffer extends Uint8Array { writeUInt8(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setUint8( offset, - value + value, ); return offset + 1; } @@ -548,7 +554,7 @@ export default class Buffer extends Uint8Array { writeUInt16BE(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setUint16( offset, - value + value, ); return offset + 2; } @@ -556,7 +562,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setUint16( offset, value, - true + true, ); return offset + 2; } @@ -564,7 +570,7 @@ export default class Buffer extends Uint8Array { writeUInt32BE(value: number, offset = 0): number { new DataView(this.buffer, this.byteOffset, this.byteLength).setUint32( offset, - value + value, ); return offset + 4; } @@ -572,7 +578,7 @@ export default class Buffer extends Uint8Array { new DataView(this.buffer, this.byteOffset, this.byteLength).setUint32( offset, value, - true + true, ); return offset + 4; } diff --git a/std/node/buffer_test.ts b/std/node/buffer_test.ts index f96fa8e4b..5d01a4b67 100644 --- a/std/node/buffer_test.ts +++ b/std/node/buffer_test.ts @@ -22,7 +22,7 @@ Deno.test({ }, RangeError, "Invalid typed array length: -1", - "should throw on negative numbers" + "should throw on negative numbers", ); }, }); @@ -41,7 +41,7 @@ Deno.test({ }, TypeError, `The "size" argument must be of type number. Received type ${typeof size}`, - "should throw on non-number size" + "should throw on non-number size", ); } }, @@ -62,7 +62,7 @@ Deno.test({ }, TypeError, `The argument "value" is invalid. Received ${value.constructor.name} []`, - "should throw for empty Buffer/Uint8Array" + "should throw for empty Buffer/Uint8Array", ); } }, @@ -132,7 +132,7 @@ Deno.test({ fn() { assertEquals( Buffer.alloc(11, "aGVsbG8gd29ybGQ=", "base64"), - new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]) + new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), ); }, }); @@ -142,7 +142,7 @@ Deno.test({ fn() { assertEquals( Buffer.alloc(4, "64656e6f", "hex"), - new Uint8Array([100, 101, 110, 111]) + new Uint8Array([100, 101, 110, 111]), ); }, }); @@ -152,7 +152,7 @@ Deno.test({ fn() { assertEquals( Buffer.alloc(13, "64656e6f", "hex").toString(), - "denodenodenod" + "denodenodenod", ); }, }); @@ -162,11 +162,11 @@ Deno.test({ fn() { assertEquals( Buffer.alloc(7, new Uint8Array([100, 101])), - new Uint8Array([100, 101, 100, 101, 100, 101, 100]) + new Uint8Array([100, 101, 100, 101, 100, 101, 100]), ); assertEquals( Buffer.alloc(6, new Uint8Array([100, 101])), - new Uint8Array([100, 101, 100, 101, 100, 101]) + new Uint8Array([100, 101, 100, 101, 100, 101]), ); }, }); @@ -176,7 +176,7 @@ Deno.test({ fn() { assertEquals( Buffer.alloc(1, new Uint8Array([100, 101])), - new Uint8Array([100]) + new Uint8Array([100]), ); }, }); @@ -186,11 +186,11 @@ Deno.test({ fn() { assertEquals( Buffer.alloc(6, new Buffer([100, 101])), - new Uint8Array([100, 101, 100, 101, 100, 101]) + new Uint8Array([100, 101, 100, 101, 100, 101]), ); assertEquals( Buffer.alloc(7, new Buffer([100, 101])), - new Uint8Array([100, 101, 100, 101, 100, 101, 100]) + new Uint8Array([100, 101, 100, 101, 100, 101, 100]), ); }, }); @@ -224,7 +224,7 @@ Deno.test({ assertEquals(Buffer.byteLength("aGkk", "base64"), 3); assertEquals( Buffer.byteLength("bHNrZGZsa3NqZmtsc2xrZmFqc2RsZmtqcw==", "base64"), - 25 + 25, ); // special padding assertEquals(Buffer.byteLength("aaa=", "base64"), 2); @@ -253,7 +253,7 @@ Deno.test({ assertEquals( Buffer.byteLength(Buffer.alloc(0)), Buffer.alloc(0).byteLength, - "Byte lenght differs on buffers" + "Byte lenght differs on buffers", ); }, }); @@ -306,7 +306,7 @@ Deno.test({ }, RangeError, "offset is out of bounds", - "should throw on negative numbers" + "should throw on negative numbers", ); }, }); @@ -319,7 +319,7 @@ Deno.test({ assertEquals( buffer.toString(), "test", - "Buffer to string should recover the string" + "Buffer to string should recover the string", ); }, }); @@ -330,13 +330,13 @@ Deno.test({ for (const encoding of ["hex", "HEX"]) { const buffer: Buffer = Buffer.from( "7468697320697320612074c3a97374", - encoding + encoding, ); assertEquals(buffer.length, 15, "Buffer length should be 15"); assertEquals( buffer.toString(), "this is a tést", - "Buffer to string should recover the string" + "Buffer to string should recover the string", ); } }, @@ -351,7 +351,7 @@ Deno.test({ assertEquals( buffer.toString(), "this is a tést", - "Buffer to string should recover the string" + "Buffer to string should recover the string", ); } }, @@ -365,7 +365,7 @@ Deno.test({ assertEquals( buffer.toString(encoding), "ZGVubyBsYW5k", - "Buffer to string should recover the string in base64" + "Buffer to string should recover the string in base64", ); } const b64 = "dGhpcyBpcyBhIHTDqXN0"; @@ -381,7 +381,7 @@ Deno.test({ assertEquals( buffer.toString(encoding), "64656e6f206c616e64", - "Buffer to string should recover the string" + "Buffer to string should recover the string", ); } const hex = "64656e6f206c616e64"; @@ -404,7 +404,7 @@ Deno.test({ }, TypeError, `Unkown encoding: ${encoding}`, - "Should throw on invalid encoding" + "Should throw on invalid encoding", ); } }, @@ -430,7 +430,7 @@ Deno.test({ Buffer.from("yes", encoding); }, TypeError, - `Unkown encoding: ${encoding}` + `Unkown encoding: ${encoding}`, ); } }, @@ -451,7 +451,7 @@ Deno.test({ }, Error, `"${encoding}" encoding`, - "Should throw on invalid encoding" + "Should throw on invalid encoding", ); assertThrows( @@ -462,7 +462,7 @@ Deno.test({ }, Error, `"${encoding}" encoding`, - "Should throw on invalid encoding" + "Should throw on invalid encoding", ); } }, @@ -476,7 +476,7 @@ Deno.test({ assertEquals( buffer.toString(), "test", - "Buffer to string should recover the string" + "Buffer to string should recover the string", ); }, }); @@ -501,7 +501,7 @@ Deno.test({ fn() { assertEquals( JSON.stringify(Buffer.from("deno")), - '{"type":"Buffer","data":[100,101,110,111]}' + '{"type":"Buffer","data":[100,101,110,111]}', ); }, }); @@ -578,7 +578,7 @@ Deno.test({ assertEquals(d.equals(d), true); assertEquals( d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65])), - true + true, ); assertEquals(c.equals(d), false); @@ -589,7 +589,7 @@ Deno.test({ // @ts-ignore () => Buffer.alloc(1).equals("abc"), TypeError, - `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type string` + `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type string`, ); }, }); diff --git a/std/node/events.ts b/std/node/events.ts index ef547cc37..b267852aa 100644 --- a/std/node/events.ts +++ b/std/node/events.ts @@ -44,7 +44,7 @@ export default class EventEmitter { private _addListener( eventName: string | symbol, listener: Function | WrappedFunction, - prepend: boolean + prepend: boolean, ): this { this.emit("newListener", eventName, listener); if (this._events.has(eventName)) { @@ -64,7 +64,7 @@ export default class EventEmitter { const warning = new Error( `Possible EventEmitter memory leak detected. ${this.listenerCount(eventName)} ${eventName.toString()} listeners. - Use emitter.setMaxListeners() to increase limit` + Use emitter.setMaxListeners() to increase limit`, ); warning.name = "MaxListenersExceededWarning"; console.warn(warning); @@ -76,7 +76,7 @@ export default class EventEmitter { /** Alias for emitter.on(eventName, listener). */ public addListener( eventName: string | symbol, - listener: Function | WrappedFunction + listener: Function | WrappedFunction, ): this { return this._addListener(eventName, listener, false); } @@ -147,13 +147,13 @@ export default class EventEmitter { private _listeners( target: EventEmitter, eventName: string | symbol, - unwrap: boolean + unwrap: boolean, ): Function[] { if (!target._events.has(eventName)) { return []; } const eventListeners: Function[] = target._events.get( - eventName + eventName, ) as Function[]; return unwrap @@ -180,7 +180,7 @@ export default class EventEmitter { * including any wrappers (such as those created by .once()). */ public rawListeners( - eventName: string | symbol + eventName: string | symbol, ): Array<Function | WrappedFunction> { return this._listeners(this, eventName, false); } @@ -199,7 +199,7 @@ export default class EventEmitter { */ public on( eventName: string | symbol, - listener: Function | WrappedFunction + listener: Function | WrappedFunction, ): this { return this.addListener(eventName, listener); } @@ -217,7 +217,7 @@ export default class EventEmitter { // Wrapped function that calls EventEmitter.removeListener(eventName, self) on execution. private onceWrap( eventName: string | symbol, - listener: Function + listener: Function, ): WrappedFunction { const wrapper = function ( this: { @@ -239,7 +239,7 @@ export default class EventEmitter { context: this, }; const wrapped = (wrapper.bind( - wrapperContext + wrapperContext, ) as unknown) as WrappedFunction; wrapperContext.rawListener = wrapped; wrapped.listener = listener; @@ -255,7 +255,7 @@ export default class EventEmitter { */ public prependListener( eventName: string | symbol, - listener: Function | WrappedFunction + listener: Function | WrappedFunction, ): this { return this._addListener(eventName, listener, true); } @@ -267,7 +267,7 @@ export default class EventEmitter { */ public prependOnceListener( eventName: string | symbol, - listener: Function + listener: Function, ): this { const wrapped: WrappedFunction = this.onceWrap(eventName, listener); this.prependListener(eventName, wrapped); @@ -359,7 +359,7 @@ export { EventEmitter }; */ export function once( emitter: EventEmitter | EventTarget, - name: string + name: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Promise<any[]> { return new Promise((resolve, reject) => { @@ -371,7 +371,7 @@ export function once( (...args) => { resolve(args); }, - { once: true, passive: false, capture: false } + { once: true, passive: false, capture: false }, ); return; } else if (emitter instanceof EventEmitter) { @@ -429,7 +429,7 @@ interface AsyncInterable { */ export function on( emitter: EventEmitter, - event: string | symbol + event: string | symbol, ): AsyncInterable { // eslint-disable-next-line @typescript-eslint/no-explicit-any const unconsumedEventValues: any[] = []; diff --git a/std/node/events_test.ts b/std/node/events_test.ts index 58025ce84..62b20594c 100644 --- a/std/node/events_test.ts +++ b/std/node/events_test.ts @@ -93,9 +93,9 @@ Deno.test({ "event", (oneArg: string, twoArg: string, threeArg: string) => { eventsFired.push( - "event(" + oneArg + ", " + twoArg + ", " + threeArg + ")" + "event(" + oneArg + ", " + twoArg + ", " + threeArg + ")", ); - } + }, ); testEmitter.emit("event", 1, 2, 3); assertEquals(eventsFired, ["event(1)", "event(1, 2)", "event(1, 2, 3)"]); @@ -346,7 +346,7 @@ Deno.test({ assertEquals(rawListenersForEvent[0], listenerA); assertEquals( (rawListenersForOnceEvent[0] as WrappedFunction).listener, - listenerB + listenerB, ); }, }); @@ -361,7 +361,8 @@ Deno.test({ testEmitter.once("once-event", listenerA); const rawListenersForOnceEvent = testEmitter.rawListeners("once-event"); - const wrappedFn: WrappedFunction = rawListenersForOnceEvent[0] as WrappedFunction; + const wrappedFn: WrappedFunction = + rawListenersForOnceEvent[0] as WrappedFunction; wrappedFn.listener(); wrappedFn.listener(); wrappedFn.listener(); @@ -411,14 +412,14 @@ Deno.test({ ee.setMaxListeners(-1); }, Error, - "must be >= 0" + "must be >= 0", ); assertThrows( () => { ee.setMaxListeners(3.45); }, Error, - "must be 'an integer'" + "must be 'an integer'", ); }, }); @@ -434,7 +435,7 @@ Deno.test({ ee.emit("error"); }, Error, - "Unhandled error" + "Unhandled error", ); ee.on(EventEmitter.errorMonitor, () => { @@ -447,7 +448,7 @@ Deno.test({ ee.emit("error"); }, Error, - "Unhandled error" + "Unhandled error", ); assertEquals(events, ["errorMonitor event"]); diff --git a/std/node/module.ts b/std/node/module.ts index 8d13ff366..534fe88e4 100644 --- a/std/node/module.ts +++ b/std/node/module.ts @@ -71,7 +71,7 @@ function stat(filename: string): StatResult { function updateChildren( parent: Module | null, child: Module, - scan: boolean + scan: boolean, ): void { const children = parent && parent.children; if (children && !(scan && children.includes(child))) { @@ -164,7 +164,7 @@ class Module { require, this, filename, - dirname + dirname, ); if (requireDepth === 0) { statCache = null; @@ -177,7 +177,7 @@ class Module { * */ static _resolveLookupPaths( request: string, - parent: Module | null + parent: Module | null, ): string[] | null { if ( request.charAt(0) !== "." || @@ -208,7 +208,7 @@ class Module { request: string, parent: Module, isMain: boolean, - options?: { paths: string[] } + options?: { paths: string[] }, ): string { // Polyfills. if (nativeModuleCanBeRequiredByUsers(request)) { @@ -219,8 +219,7 @@ class Module { if (typeof options === "object" && options !== null) { if (Array.isArray(options.paths)) { - const isRelative = - request.startsWith("./") || + const isRelative = request.startsWith("./") || request.startsWith("../") || (isWindows && request.startsWith(".\\")) || request.startsWith("..\\"); @@ -278,7 +277,7 @@ class Module { static _findPath( request: string, paths: string[], - isMain: boolean + isMain: boolean, ): string | boolean { const absoluteRequest = path.isAbsolute(request); if (absoluteRequest) { @@ -287,16 +286,15 @@ class Module { return false; } - const cacheKey = - request + "\x00" + (paths.length === 1 ? paths[0] : paths.join("\x00")); + const cacheKey = request + "\x00" + + (paths.length === 1 ? paths[0] : paths.join("\x00")); const entry = Module._pathCache[cacheKey]; if (entry) { return entry; } let exts; - let trailingSlash = - request.length > 0 && + let trailingSlash = request.length > 0 && request.charCodeAt(request.length - 1) === CHAR_FORWARD_SLASH; if (!trailingSlash) { trailingSlash = /(?:^|\/)\.?\.$/.test(request); @@ -604,18 +602,18 @@ nativeModulePolyfill.set("os", createNativeModule("os", nodeOs)); nativeModulePolyfill.set("path", createNativeModule("path", nodePath)); nativeModulePolyfill.set( "querystring", - createNativeModule("querystring", nodeQueryString) + createNativeModule("querystring", nodeQueryString), ); nativeModulePolyfill.set( "string_decoder", - createNativeModule("string_decoder", nodeStringDecoder) + createNativeModule("string_decoder", nodeStringDecoder), ); nativeModulePolyfill.set("timers", createNativeModule("timers", nodeTimers)); nativeModulePolyfill.set("util", createNativeModule("util", nodeUtil)); function loadNativeModule( _filename: string, - request: string + request: string, ): Module | undefined { return nativeModulePolyfill.get(request); } @@ -662,7 +660,7 @@ function readPackage(requestPath: string): PackageInfo | null { let json: string | undefined; try { json = new TextDecoder().decode( - Deno.readFileSync(path.toNamespacedPath(jsonPath)) + Deno.readFileSync(path.toNamespacedPath(jsonPath)), ); } catch { // pass @@ -691,7 +689,7 @@ function readPackage(requestPath: string): PackageInfo | null { } function readPackageScope( - checkPath: string + checkPath: string, ): { path: string; data: PackageInfo } | false { const rootSeparatorIndex = checkPath.indexOf(path.sep); let separatorIndex; @@ -726,7 +724,7 @@ function tryPackage( requestPath: string, exts: string[], isMain: boolean, - _originalPath: string + _originalPath: string, ): string | false { const pkg = readPackageMain(requestPath); @@ -735,8 +733,7 @@ function tryPackage( } const filename = path.resolve(requestPath, pkg); - let actual = - tryFile(filename, isMain) || + let actual = tryFile(filename, isMain) || tryExtensions(filename, exts, isMain) || tryExtensions(path.resolve(filename, "index"), exts, isMain); if (actual === false) { @@ -744,7 +741,7 @@ function tryPackage( if (!actual) { const err = new Error( `Cannot find module '${filename}'. ` + - 'Please verify that the package.json has a valid "main" entry' + 'Please verify that the package.json has a valid "main" entry', ) as Error & { code: string }; err.code = "MODULE_NOT_FOUND"; throw err; @@ -779,7 +776,7 @@ function toRealPath(requestPath: string): string { function tryExtensions( p: string, exts: string[], - isMain: boolean + isMain: boolean, ): string | false { for (let i = 0; i < exts.length; i++) { const filename = tryFile(p + exts[i], isMain); @@ -826,7 +823,7 @@ function isConditionalDotExportSugar(exports: any, _basePath: string): boolean { '"exports" cannot ' + "contain some keys starting with '.' and some not. The exports " + "object must either be an object of package subpath keys or an " + - "object of main entry condition name keys only." + "object of main entry condition name keys only.", ); } } @@ -853,7 +850,7 @@ function applyExports(basePath: string, expansion: string): string { mapping, "", basePath, - mappingKey + mappingKey, ); } @@ -879,7 +876,7 @@ function applyExports(basePath: string, expansion: string): string { mapping, subpath, basePath, - mappingKey + mappingKey, ); } } @@ -888,7 +885,7 @@ function applyExports(basePath: string, expansion: string): string { const e = new Error( `Package exports for '${basePath}' do not define ` + - `a '${mappingKey}' subpath` + `a '${mappingKey}' subpath`, ) as Error & { code?: string }; e.code = "MODULE_NOT_FOUND"; throw e; @@ -901,7 +898,7 @@ const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/; function resolveExports( nmPath: string, request: string, - absoluteRequest: boolean + absoluteRequest: boolean, ): string { // The implementation's behavior is meant to mirror resolution in ESM. if (!absoluteRequest) { @@ -923,7 +920,7 @@ function resolveExportsTarget( target: any, subpath: string, basePath: string, - mappingKey: string + mappingKey: string, ): string { if (typeof target === "string") { if ( @@ -957,7 +954,7 @@ function resolveExportsTarget( targetValue, subpath, basePath, - mappingKey + mappingKey, ); } catch (e) { if (e.code !== "MODULE_NOT_FOUND") throw e; @@ -972,7 +969,7 @@ function resolveExportsTarget( target.default, subpath, basePath, - mappingKey + mappingKey, ); } catch (e) { if (e.code !== "MODULE_NOT_FOUND") throw e; @@ -983,7 +980,7 @@ function resolveExportsTarget( if (mappingKey !== ".") { e = new Error( `Package exports for '${basePath}' do not define a ` + - `valid '${mappingKey}' target${subpath ? " for " + subpath : ""}` + `valid '${mappingKey}' target${subpath ? " for " + subpath : ""}`, ); } else { e = new Error(`No valid exports main found for '${basePath}'`); @@ -999,9 +996,9 @@ const nmLen = nmChars.length; // eslint-disable-next-line @typescript-eslint/no-explicit-any function emitCircularRequireWarning(prop: any): void { console.error( - `Accessing non-existent property '${String( - prop - )}' of module exports inside circular dependency` + `Accessing non-existent property '${ + String(prop) + }' of module exports inside circular dependency`, ); } @@ -1024,7 +1021,7 @@ const CircularRequirePrototypeWarningProxy = new Proxy( emitCircularRequireWarning(prop); return undefined; }, - } + }, ); // Object.prototype and ObjectProtoype refer to our 'primordials' versions @@ -1056,7 +1053,7 @@ type RequireWrapper = ( require: any, module: Module, __filename: string, - __dirname: string + __dirname: string, ) => void; function wrapSafe(filename: string, content: string): RequireWrapper { @@ -1099,8 +1096,8 @@ Module._extensions[".json"] = (module: Module, filename: string): void => { function createRequireFromPath(filename: string): RequireFunction { // Allow a directory to be passed as the filename - const trailingSlash = - filename.endsWith("/") || (isWindows && filename.endsWith("\\")); + const trailingSlash = filename.endsWith("/") || + (isWindows && filename.endsWith("\\")); const proxyPath = trailingSlash ? path.join(filename, "noop.js") : filename; diff --git a/std/node/module_test.ts b/std/node/module_test.ts index 30441a58d..bdc2f39d3 100644 --- a/std/node/module_test.ts +++ b/std/node/module_test.ts @@ -34,7 +34,7 @@ Deno.test("requireBuiltin", function () { const { readFileSync, isNull, extname } = require("./tests/cjs/cjs_builtin"); assertEquals( readFileSync("./node/_fs/testdata/hello.txt", { encoding: "utf8" }), - "hello world" + "hello world", ); assert(isNull(null)); assertEquals(extname("index.html"), ".html"); diff --git a/std/node/os.ts b/std/node/os.ts index afb472629..c312ffe0c 100644 --- a/std/node/os.ts +++ b/std/node/os.ts @@ -203,7 +203,7 @@ export function uptime(): number { /** Not yet implemented */ export function userInfo( /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ - options: UserInfoOptions = { encoding: "utf-8" } + options: UserInfoOptions = { encoding: "utf-8" }, ): UserInfo { notImplemented(SEE_GITHUB_ISSUE); } diff --git a/std/node/os_test.ts b/std/node/os_test.ts index c5f39f635..34f8d0f87 100644 --- a/std/node/os_test.ts +++ b/std/node/os_test.ts @@ -54,14 +54,14 @@ Deno.test({ os.getPriority(3.15); }, Error, - "pid must be 'an integer'" + "pid must be 'an integer'", ); assertThrows( () => { os.getPriority(9999999999); }, Error, - "must be >= -2147483648 && <= 2147483647" + "must be >= -2147483648 && <= 2147483647", ); }, }); @@ -74,14 +74,14 @@ Deno.test({ os.setPriority(3.15, 0); }, Error, - "pid must be 'an integer'" + "pid must be 'an integer'", ); assertThrows( () => { os.setPriority(9999999999, 0); }, Error, - "pid must be >= -2147483648 && <= 2147483647" + "pid must be >= -2147483648 && <= 2147483647", ); }, }); @@ -94,28 +94,28 @@ Deno.test({ os.setPriority(0, 3.15); }, Error, - "priority must be 'an integer'" + "priority must be 'an integer'", ); assertThrows( () => { os.setPriority(0, -21); }, Error, - "priority must be >= -20 && <= 19" + "priority must be >= -20 && <= 19", ); assertThrows( () => { os.setPriority(0, 20); }, Error, - "priority must be >= -20 && <= 19" + "priority must be >= -20 && <= 19", ); assertThrows( () => { os.setPriority(0, 9999999999); }, Error, - "priority must be >= -20 && <= 19" + "priority must be >= -20 && <= 19", ); }, }); @@ -129,28 +129,28 @@ Deno.test({ os.setPriority(3.15); }, Error, - "priority must be 'an integer'" + "priority must be 'an integer'", ); assertThrows( () => { os.setPriority(-21); }, Error, - "priority must be >= -20 && <= 19" + "priority must be >= -20 && <= 19", ); assertThrows( () => { os.setPriority(20); }, Error, - "priority must be >= -20 && <= 19" + "priority must be >= -20 && <= 19", ); assertThrows( () => { os.setPriority(9999999999); }, Error, - "priority must be >= -20 && <= 19" + "priority must be >= -20 && <= 19", ); }, }); @@ -207,63 +207,63 @@ Deno.test({ os.cpus(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.freemem(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.getPriority(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.networkInterfaces(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.setPriority(0); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.totalmem(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.type(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.uptime(); }, Error, - "Not implemented" + "Not implemented", ); assertThrows( () => { os.userInfo(); }, Error, - "Not implemented" + "Not implemented", ); }, }); diff --git a/std/node/process_test.ts b/std/node/process_test.ts index c4332af33..2674b725f 100644 --- a/std/node/process_test.ts +++ b/std/node/process_test.ts @@ -44,7 +44,7 @@ Deno.test({ process.chdir("non-existent-directory-name"); }, Deno.errors.NotFound, - "file" + "file", // On every OS Deno returns: "No such file" except for Windows, where it's: // "The system cannot find the file specified. (os error 2)" so "file" is // the only common string here. @@ -95,7 +95,7 @@ Deno.test({ process.on("uncaughtException", (_err: Error) => {}); }, Error, - "implemented" + "implemented", ); }, }); @@ -107,7 +107,7 @@ Deno.test({ assert(Array.isArray(argv)); assert( process.argv[0].match(/[^/\\]*deno[^/\\]*$/), - "deno included in the file name of argv[0]" + "deno included in the file name of argv[0]", ); // we cannot test for anything else (we see test runner arguments here) }, diff --git a/std/node/querystring.ts b/std/node/querystring.ts index bed327337..4e3c728c1 100644 --- a/std/node/querystring.ts +++ b/std/node/querystring.ts @@ -5,14 +5,15 @@ interface ParseOptions { maxKeys?: number; } export const hexTable = new Array(256); -for (let i = 0; i < 256; ++i) +for (let i = 0; i < 256; ++i) { hexTable[i] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(); +} export function parse( str: string, sep = "&", eq = "=", - { decodeURIComponent = unescape, maxKeys = 1000 }: ParseOptions = {} + { decodeURIComponent = unescape, maxKeys = 1000 }: ParseOptions = {}, ): { [key: string]: string[] | string } { const entries = str .split(sep) @@ -49,7 +50,7 @@ interface StringifyOptions { export function encodeStr( str: string, noEscapeTable: number[], - hexTable: string[] + hexTable: string[], ): string { const len = str.length; if (len === 0) return ""; @@ -78,8 +79,7 @@ export function encodeStr( } if (c < 0xd800 || c >= 0xe000) { lastPos = i + 1; - out += - hexTable[0xe0 | (c >> 12)] + + out += hexTable[0xe0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3f)] + hexTable[0x80 | (c & 0x3f)]; continue; @@ -96,8 +96,7 @@ export function encodeStr( lastPos = i + 1; c = 0x10000 + (((c & 0x3ff) << 10) | c2); - out += - hexTable[0xf0 | (c >> 18)] + + out += hexTable[0xf0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3f)] + hexTable[0x80 | ((c >> 6) & 0x3f)] + hexTable[0x80 | (c & 0x3f)]; @@ -111,7 +110,7 @@ export function stringify( obj: object, sep = "&", eq = "=", - { encodeURIComponent = escape }: StringifyOptions = {} + { encodeURIComponent = escape }: StringifyOptions = {}, ): string { const final = []; diff --git a/std/node/querystring_test.ts b/std/node/querystring_test.ts index 63abf471b..6ce681ca5 100644 --- a/std/node/querystring_test.ts +++ b/std/node/querystring_test.ts @@ -11,7 +11,7 @@ Deno.test({ c: true, d: ["foo", "bar"], }), - "a=hello&b=5&c=true&d=foo&d=bar" + "a=hello&b=5&c=true&d=foo&d=bar", ); }, }); diff --git a/std/node/string_decoder.ts b/std/node/string_decoder.ts index 7f167ad3c..ce7c19538 100644 --- a/std/node/string_decoder.ts +++ b/std/node/string_decoder.ts @@ -31,8 +31,9 @@ enum NotImplemented { function normalizeEncoding(enc?: string): string { const encoding = castEncoding(enc ?? null); if (encoding && encoding in NotImplemented) notImplemented(encoding); - if (!encoding && typeof enc === "string" && enc.toLowerCase() !== "raw") + if (!encoding && typeof enc === "string" && enc.toLowerCase() !== "raw") { throw new Error(`Unknown encoding: ${enc}`); + } return String(encoding); } /* @@ -55,7 +56,7 @@ function utf8CheckByte(byte: number): number { function utf8CheckIncomplete( self: StringDecoderBase, buf: Buffer, - i: number + i: number, ): number { let j = buf.length - 1; if (j < i) return 0; @@ -94,7 +95,7 @@ function utf8CheckIncomplete( * */ function utf8CheckExtraBytes( self: StringDecoderBase, - buf: Buffer + buf: Buffer, ): string | undefined { if ((buf[0] & 0xc0) !== 0x80) { self.lastNeed = 0; @@ -119,7 +120,7 @@ function utf8CheckExtraBytes( * */ function utf8FillLastComplete( this: StringDecoderBase, - buf: Buffer + buf: Buffer, ): string | undefined { const p = this.lastTotal - this.lastNeed; const r = utf8CheckExtraBytes(this, buf); @@ -137,7 +138,7 @@ function utf8FillLastComplete( * */ function utf8FillLastIncomplete( this: StringDecoderBase, - buf: Buffer + buf: Buffer, ): string | undefined { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); @@ -203,8 +204,9 @@ function base64Text(this: StringDecoderBase, buf: Buffer, i: number): string { function base64End(this: Base64Decoder, buf?: Buffer): string { const r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) + if (this.lastNeed) { return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + } return r; } diff --git a/std/node/string_decoder_test.ts b/std/node/string_decoder_test.ts index 69bb8402a..de32b6815 100644 --- a/std/node/string_decoder_test.ts +++ b/std/node/string_decoder_test.ts @@ -22,7 +22,7 @@ Deno.test({ decoder = new StringDecoder("utf8"); assertEquals( decoder.write(Buffer.from("\ufffd\ufffd\ufffd")), - "\ufffd\ufffd\ufffd" + "\ufffd\ufffd\ufffd", ); assertEquals(decoder.end(), ""); @@ -60,7 +60,7 @@ Deno.test({ decoder = new StringDecoder("base64"); assertEquals( decoder.write(Buffer.from("\ufffd\ufffd\ufffd")), - "77+977+977+9" + "77+977+977+9", ); assertEquals(decoder.end(), ""); @@ -98,7 +98,7 @@ Deno.test({ decoder = new StringDecoder("hex"); assertEquals( decoder.write(Buffer.from("\ufffd\ufffd\ufffd")), - "efbfbdefbfbdefbfbd" + "efbfbdefbfbdefbfbd", ); assertEquals(decoder.end(), ""); diff --git a/std/node/url.ts b/std/node/url.ts index b0034d02d..826a274f8 100644 --- a/std/node/url.ts +++ b/std/node/url.ts @@ -38,12 +38,14 @@ const tabRegEx = /\t/g; export function fileURLToPath(path: string | URL): string { if (typeof path === "string") path = new URL(path); - else if (!(path instanceof URL)) + else if (!(path instanceof URL)) { throw new Deno.errors.InvalidData( - "invalid argument path , must be a string or URL" + "invalid argument path , must be a string or URL", ); - if (path.protocol !== "file:") + } + if (path.protocol !== "file:") { throw new Deno.errors.InvalidData("invalid url scheme"); + } return isWindows ? getPathFromURLWin(path) : getPathFromURLPosix(path); } @@ -59,7 +61,7 @@ function getPathFromURLWin(url: URL): string { ) { // 5c 5C \ throw new Deno.errors.InvalidData( - "must not include encoded \\ or / characters" + "must not include encoded \\ or / characters", ); } } @@ -95,7 +97,7 @@ function getPathFromURLPosix(url: URL): string { const third = pathname.codePointAt(n + 2) || 0x20; if (pathname[n + 1] === "2" && third === 102) { throw new Deno.errors.InvalidData( - "must not include encoded / characters" + "must not include encoded / characters", ); } } @@ -111,16 +113,19 @@ export function pathToFileURL(filepath: string): URL { (filePathLast === CHAR_FORWARD_SLASH || (isWindows && filePathLast === CHAR_BACKWARD_SLASH)) && resolved[resolved.length - 1] !== path.sep - ) + ) { resolved += "/"; + } const outURL = new URL("file://"); if (resolved.includes("%")) resolved = resolved.replace(percentRegEx, "%25"); // In posix, "/" is a valid character in paths - if (!isWindows && resolved.includes("\\")) + if (!isWindows && resolved.includes("\\")) { resolved = resolved.replace(backslashRegEx, "%5C"); + } if (resolved.includes("\n")) resolved = resolved.replace(newlineRegEx, "%0A"); - if (resolved.includes("\r")) + if (resolved.includes("\r")) { resolved = resolved.replace(carriageReturnRegEx, "%0D"); + } if (resolved.includes("\t")) resolved = resolved.replace(tabRegEx, "%09"); outURL.pathname = resolved; return outURL; diff --git a/std/node/util.ts b/std/node/util.ts index e046aba9c..8e3c50b87 100644 --- a/std/node/util.ts +++ b/std/node/util.ts @@ -62,7 +62,7 @@ export function validateIntegerRange( value: number, name: string, min = -2147483648, - max = 2147483647 + max = 2147483647, ): void { // The defaults for min and max correspond to the limits of 32-bit integers. if (!Number.isInteger(value)) { @@ -70,7 +70,7 @@ export function validateIntegerRange( } if (value < min || value > max) { throw new Error( - `${name} must be >= ${min} && <= ${max}. Value was ${value}` + `${name} must be >= ${min} && <= ${max}. Value was ${value}`, ); } } diff --git a/std/path/_globrex.ts b/std/path/_globrex.ts index 6ad297d86..0cc5399fa 100644 --- a/std/path/_globrex.ts +++ b/std/path/_globrex.ts @@ -57,7 +57,7 @@ export function globrex( strict = false, filepath = false, flags = "", - }: GlobrexOptions = {} + }: GlobrexOptions = {}, ): GlobrexResult { const sepPattern = new RegExp(`^${SEP}${strict ? "" : "+"}$`); let regex = ""; @@ -82,7 +82,7 @@ export function globrex( // Helper function to build string and segments function add( str: string, - options: AddOptions = { split: false, last: false, only: "" } + options: AddOptions = { split: false, last: false, only: "" }, ): void { const { split, last, only } = options; if (only !== "path") regex += str; @@ -279,8 +279,7 @@ export function globrex( add(".*"); } else { // globstar is enabled, so determine if this is a globstar segment - const isGlobstar = - starCount > 1 && // multiple "*"'s + const isGlobstar = starCount > 1 && // multiple "*"'s // from the start of the segment [SEP_RAW, "/", undefined].includes(prevChar) && // to the end of the segment @@ -320,7 +319,7 @@ export function globrex( segments: pathSegments, globstar: new RegExp( !flags.includes("g") ? `^${GLOBSTAR_SEGMENT}$` : GLOBSTAR_SEGMENT, - flags + flags, ), }; } diff --git a/std/path/_globrex_test.ts b/std/path/_globrex_test.ts index 67a58cc64..19eabc983 100644 --- a/std/path/_globrex_test.ts +++ b/std/path/_globrex_test.ts @@ -11,7 +11,7 @@ function match( glob: string, strUnix: string, strWin?: string | object, - opts: GlobrexOptions = {} + opts: GlobrexOptions = {}, ): boolean { if (typeof strWin === "object") { opts = strWin; @@ -48,19 +48,19 @@ Deno.test({ t.equal( match("u*orn", "unicorn", { flags: "g" }), true, - "match the middle" + "match the middle", ); t.equal(match("ico", "unicorn"), false, "do not match without g"); t.equal( match("ico", "unicorn", { flags: "g" }), true, - 'match anywhere with RegExp "g"' + 'match anywhere with RegExp "g"', ); t.equal(match("u*nicorn", "unicorn"), true, "match zero characters"); t.equal( match("u*nicorn", "unicorn", { flags: "g" }), true, - "match zero characters" + "match zero characters", ); }, }); @@ -73,34 +73,34 @@ Deno.test({ globstar: false, }), true, - "complex match" + "complex match", ); t.equal( match("*.min.*", "http://example.com/jquery.min.js", { globstar: false }), true, - "complex match" + "complex match", ); t.equal( match("*/js/*.js", "http://example.com/js/jquery.min.js", { globstar: false, }), true, - "complex match" + "complex match", ); t.equal( match("*.min.*", "http://example.com/jquery.min.js", { flags: "g" }), true, - "complex match global" + "complex match global", ); t.equal( match("*.min.js", "http://example.com/jquery.min.js", { flags: "g" }), true, - "complex match global" + "complex match global", ); t.equal( match("*/js/*.js", "http://example.com/js/jquery.min.js", { flags: "g" }), true, - "complex match global" + "complex match global", ); const str = "\\/$^+?.()=!|{},[].*"; @@ -108,70 +108,70 @@ Deno.test({ t.equal( match(str, str, { flags: "g" }), true, - "battle test complex string - strict" + "battle test complex string - strict", ); t.equal( match(".min.", "http://example.com/jquery.min.js"), false, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("*.min.*", "http://example.com/jquery.min.js"), true, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match(".min.", "http://example.com/jquery.min.js", { flags: "g" }), true, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("http:", "http://example.com/jquery.min.js"), false, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("http:*", "http://example.com/jquery.min.js"), true, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("http:", "http://example.com/jquery.min.js", { flags: "g" }), true, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("min.js", "http://example.com/jquery.min.js"), false, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("*.min.js", "http://example.com/jquery.min.js"), true, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("min.js", "http://example.com/jquery.min.js", { flags: "g" }), true, - 'matches without/with using RegExp "g"' + 'matches without/with using RegExp "g"', ); t.equal( match("min", "http://example.com/jquery.min.js", { flags: "g" }), true, - 'match anywhere (globally) using RegExp "g"' + 'match anywhere (globally) using RegExp "g"', ); t.equal( match("/js/", "http://example.com/js/jquery.min.js", { flags: "g" }), true, - 'match anywhere (globally) using RegExp "g"' + 'match anywhere (globally) using RegExp "g"', ); t.equal(match("/js*jq*.js", "http://example.com/js/jquery.min.js"), false); t.equal( match("/js*jq*.js", "http://example.com/js/jquery.min.js", { flags: "g", }), - true + true, ); }, }); @@ -186,28 +186,28 @@ Deno.test({ const tester = (globstar: boolean): void => { t.equal( match("f?o", "foo", { extended: true, globstar, flags: "g" }), - true + true, ); t.equal( match("f?o", "fooo", { extended: true, globstar, flags: "g" }), - true + true, ); t.equal( match("f?o?", "fooo", { extended: true, globstar, flags: "g" }), - true + true, ); t.equal( match("?fo", "fooo", { extended: true, globstar, flags: "g" }), - false + false, ); t.equal( match("f?oo", "foo", { extended: true, globstar, flags: "g" }), - false + false, ); t.equal( match("foo?", "foo", { extended: true, globstar, flags: "g" }), - false + false, ); }; @@ -230,15 +230,15 @@ Deno.test({ const tester = (globstar: boolean): void => { t.equal( match("fo[oz]", "foo", { extended: true, globstar, flags: "g" }), - true + true, ); t.equal( match("fo[oz]", "foz", { extended: true, globstar, flags: "g" }), - true + true, ); t.equal( match("fo[oz]", "fog", { extended: true, globstar, flags: "g" }), - false + false, ); }; @@ -252,55 +252,55 @@ Deno.test({ fn(): void { t.equal( match("[[:alnum:]]/bar.txt", "a/bar.txt", { extended: true }), - true + true, ); t.equal( match("@([[:alnum:]abc]|11)/bar.txt", "11/bar.txt", { extended: true }), - true + true, ); t.equal( match("@([[:alnum:]abc]|11)/bar.txt", "a/bar.txt", { extended: true }), - true + true, ); t.equal( match("@([[:alnum:]abc]|11)/bar.txt", "b/bar.txt", { extended: true }), - true + true, ); t.equal( match("@([[:alnum:]abc]|11)/bar.txt", "c/bar.txt", { extended: true }), - true + true, ); t.equal( match("@([[:alnum:]abc]|11)/bar.txt", "abc/bar.txt", { extended: true }), - false + false, ); t.equal( match("@([[:alnum:]abc]|11)/bar.txt", "3/bar.txt", { extended: true }), - true + true, ); t.equal( match("[[:digit:]]/bar.txt", "1/bar.txt", { extended: true }), - true + true, ); t.equal( match("[[:digit:]b]/bar.txt", "b/bar.txt", { extended: true }), - true + true, ); t.equal( match("[![:digit:]b]/bar.txt", "a/bar.txt", { extended: true }), - true + true, ); t.equal( match("[[:alnum:]]/bar.txt", "!/bar.txt", { extended: true }), - false + false, ); t.equal( match("[[:digit:]]/bar.txt", "a/bar.txt", { extended: true }), - false + false, ); t.equal( match("[[:digit:]b]/bar.txt", "a/bar.txt", { extended: true }), - false + false, ); }, }); @@ -320,7 +320,7 @@ Deno.test({ globstar, flag: "g", }), - true + true, ); t.equal( match("foo{bar,baaz}", "foobar", { @@ -328,7 +328,7 @@ Deno.test({ globstar, flag: "g", }), - true + true, ); t.equal( match("foo{bar,baaz}", "foobuzz", { @@ -336,7 +336,7 @@ Deno.test({ globstar, flag: "g", }), - false + false, ); t.equal( match("foo{bar,b*z}", "foobuzz", { @@ -344,7 +344,7 @@ Deno.test({ globstar, flag: "g", }), - true + true, ); }; @@ -360,41 +360,41 @@ Deno.test({ match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://foo.baaz.com/jquery.min.js", - { extended: true } + { extended: true }, ), - true + true, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://moz.buzz.com/index.html", - { extended: true } + { extended: true }, ), - true + true, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://moz.buzz.com/index.htm", - { extended: true } + { extended: true }, ), - false + false, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://moz.bar.com/index.html", - { extended: true } + { extended: true }, ), - false + false, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://flozz.buzz.com/index.html", - { extended: true } + { extended: true }, ), - false + false, ); const tester = (globstar: boolean): void => { @@ -402,41 +402,41 @@ Deno.test({ match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://foo.baaz.com/jquery.min.js", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - true + true, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://moz.buzz.com/index.html", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - true + true, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://moz.buzz.com/index.htm", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - false + false, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://moz.bar.com/index.html", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - false + false, ); t.equal( match( "http://?o[oz].b*z.com/{*.js,*.html}", "http://flozz.buzz.com/index.html", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - false + false, ); }; @@ -453,17 +453,17 @@ Deno.test({ match( "http://foo.com/**/{*.js,*.html}", "http://foo.com/bar/jquery.min.js", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - true + true, ); t.equal( match( "http://foo.com/**/{*.js,*.html}", "http://foo.com/bar/baz/jquery.min.js", - { extended: true, globstar, flags: "g" } + { extended: true, globstar, flags: "g" }, ), - true + true, ); t.equal( match("http://foo.com/**", "http://foo.com/bar/baz/jquery.min.js", { @@ -471,7 +471,7 @@ Deno.test({ globstar, flags: "g", }), - true + true, ); }; @@ -488,7 +488,7 @@ Deno.test({ t.equal(match(testExtStr, testExtStr, { extended: true }), true); t.equal( match(testExtStr, testExtStr, { extended: true, globstar, flags: "g" }), - true + true, ); }; @@ -506,37 +506,37 @@ Deno.test({ t.equal(match("/foo/**", "/foo/bar/baz.txt", { globstar: true }), true); t.equal( match("/foo/*/*.txt", "/foo/bar/baz.txt", { globstar: true }), - true + true, ); t.equal( match("/foo/**/*.txt", "/foo/bar/baz.txt", { globstar: true }), - true + true, ); t.equal( match("/foo/**/*.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - true + true, ); t.equal(match("/foo/**/bar.txt", "/foo/bar.txt", { globstar: true }), true); t.equal( match("/foo/**/**/bar.txt", "/foo/bar.txt", { globstar: true }), - true + true, ); t.equal( match("/foo/**/*/baz.txt", "/foo/bar/baz.txt", { globstar: true }), - true + true, ); t.equal(match("/foo/**/*.txt", "/foo/bar.txt", { globstar: true }), true); t.equal( match("/foo/**/**/*.txt", "/foo/bar.txt", { globstar: true }), - true + true, ); t.equal( match("/foo/**/*/*.txt", "/foo/bar/baz.txt", { globstar: true }), - true + true, ); t.equal( match("**/*.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - true + true, ); t.equal(match("**/foo.txt", "foo.txt", { globstar: true }), true); t.equal(match("**/*.txt", "foo.txt", { globstar: true }), true); @@ -544,29 +544,29 @@ Deno.test({ t.equal(match("/foo/*.txt", "/foo/bar/baz.txt", { globstar: true }), false); t.equal( match("/foo/*/*.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - false + false, ); t.equal(match("/foo/*/bar.txt", "/foo/bar.txt", { globstar: true }), false); t.equal( match("/foo/*/*/baz.txt", "/foo/bar/baz.txt", { globstar: true }), - false + false, ); t.equal( match("/foo/**.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - false + false, ); t.equal( match("/foo/bar**/*.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - false + false, ); t.equal(match("/foo/bar**", "/foo/bar/baz.txt", { globstar: true }), false); t.equal( match("**/.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - false + false, ); t.equal( match("*/*.txt", "/foo/bar/baz/qux.txt", { globstar: true }), - false + false, ); t.equal(match("*/*.txt", "foo.txt", { globstar: true }), false); t.equal( @@ -574,65 +574,65 @@ Deno.test({ extended: true, globstar: true, }), - false + false, ); t.equal( match("http://foo.com/*", "http://foo.com/bar/baz/jquery.min.js", { globstar: true, }), - false + false, ); t.equal( match("http://foo.com/*", "http://foo.com/bar/baz/jquery.min.js", { globstar: false, }), - true + true, ); t.equal( match("http://foo.com/**", "http://foo.com/bar/baz/jquery.min.js", { globstar: true, }), - true + true, ); t.equal( match( "http://foo.com/*/*/jquery.min.js", "http://foo.com/bar/baz/jquery.min.js", - { globstar: true } + { globstar: true }, ), - true + true, ); t.equal( match( "http://foo.com/**/jquery.min.js", "http://foo.com/bar/baz/jquery.min.js", - { globstar: true } + { globstar: true }, ), - true + true, ); t.equal( match( "http://foo.com/*/*/jquery.min.js", "http://foo.com/bar/baz/jquery.min.js", - { globstar: false } + { globstar: false }, ), - true + true, ); t.equal( match( "http://foo.com/*/jquery.min.js", "http://foo.com/bar/baz/jquery.min.js", - { globstar: false } + { globstar: false }, ), - true + true, ); t.equal( match( "http://foo.com/*/jquery.min.js", "http://foo.com/bar/baz/jquery.min.js", - { globstar: true } + { globstar: true }, ), - false + false, ); }, }); @@ -646,46 +646,46 @@ Deno.test({ t.equal(match("?(foo|bar)baz.txt", "foobaz.txt", { extended: true }), true); t.equal( match("?(ba[zr]|qux)baz.txt", "bazbaz.txt", { extended: true }), - true + true, ); t.equal( match("?(ba[zr]|qux)baz.txt", "barbaz.txt", { extended: true }), - true + true, ); t.equal( match("?(ba[zr]|qux)baz.txt", "quxbaz.txt", { extended: true }), - true + true, ); t.equal( match("?(ba[!zr]|qux)baz.txt", "batbaz.txt", { extended: true }), - true + true, ); t.equal(match("?(ba*|qux)baz.txt", "batbaz.txt", { extended: true }), true); t.equal( match("?(ba*|qux)baz.txt", "batttbaz.txt", { extended: true }), - true + true, ); t.equal(match("?(ba*|qux)baz.txt", "quxbaz.txt", { extended: true }), true); t.equal( match("?(ba?(z|r)|qux)baz.txt", "bazbaz.txt", { extended: true }), - true + true, ); t.equal( match("?(ba?(z|?(r))|qux)baz.txt", "bazbaz.txt", { extended: true }), - true + true, ); t.equal(match("?(foo).txt", "foo.txt", { extended: false }), false); t.equal( match("?(foo|bar)baz.txt", "foobarbaz.txt", { extended: true }), - false + false, ); t.equal( match("?(ba[zr]|qux)baz.txt", "bazquxbaz.txt", { extended: true }), - false + false, ); t.equal( match("?(ba[!zr]|qux)baz.txt", "bazbaz.txt", { extended: true }), - false + false, ); }, }); @@ -708,21 +708,21 @@ Deno.test({ t.equal(match("*(foo|b*[rt]).txt", "tlat.txt", { extended: true }), false); t.equal( match("*(*).txt", "whatever.txt", { extended: true, globstar: true }), - true + true, ); t.equal( match("*(foo|bar)/**/*.txt", "foo/hello/world/bar.txt", { extended: true, globstar: true, }), - true + true, ); t.equal( match("*(foo|bar)/**/*.txt", "foo/world/bar.txt", { extended: true, globstar: true, }), - true + true, ); }, }); @@ -745,15 +745,15 @@ Deno.test({ t.equal(match("@(foo|baz)bar.txt", "foobar.txt", { extended: true }), true); t.equal( match("@(foo|baz)bar.txt", "foobazbar.txt", { extended: true }), - false + false, ); t.equal( match("@(foo|baz)bar.txt", "foofoobar.txt", { extended: true }), - false + false, ); t.equal( match("@(foo|baz)bar.txt", "toofoobar.txt", { extended: true }), - false + false, ); }, }); @@ -766,11 +766,11 @@ Deno.test({ t.equal(match("!bar.txt", "!bar.txt", { extended: true }), true); t.equal( match("!({foo,bar})baz.txt", "notbaz.txt", { extended: true }), - true + true, ); t.equal( match("!({foo,bar})baz.txt", "foobaz.txt", { extended: true }), - false + false, ); }, }); @@ -791,35 +791,35 @@ Deno.test({ match("**/*/?yfile.{md,js,txt}", "foo/bar/baz/myfile.md", { extended: true, }), - true + true, ); t.equal( match("**/*/?yfile.{md,js,txt}", "foo/baz/myfile.md", { extended: true }), - true + true, ); t.equal( match("**/*/?yfile.{md,js,txt}", "foo/baz/tyfile.js", { extended: true }), - true + true, ); t.equal( match("[[:digit:]_.]/file.js", "1/file.js", { extended: true }), - true + true, ); t.equal( match("[[:digit:]_.]/file.js", "2/file.js", { extended: true }), - true + true, ); t.equal( match("[[:digit:]_.]/file.js", "_/file.js", { extended: true }), - true + true, ); t.equal( match("[[:digit:]_.]/file.js", "./file.js", { extended: true }), - true + true, ); t.equal( match("[[:digit:]_.]/file.js", "z/file.js", { extended: true }), - false + false, ); }, }); diff --git a/std/path/_util.ts b/std/path/_util.ts index 0c3253045..ead425a0b 100644 --- a/std/path/_util.ts +++ b/std/path/_util.ts @@ -16,7 +16,7 @@ import { export function assertPath(path: string): void { if (typeof path !== "string") { throw new TypeError( - `Path must be a string. Received ${JSON.stringify(path)}` + `Path must be a string. Received ${JSON.stringify(path)}`, ); } } @@ -41,7 +41,7 @@ export function normalizeString( path: string, allowAboveRoot: boolean, separator: string, - isPathSeparator: (code: number) => boolean + isPathSeparator: (code: number) => boolean, ): string { let res = ""; let lastSegmentLength = 0; @@ -106,11 +106,11 @@ export function normalizeString( export function _format( sep: string, - pathObject: FormatInputPathObject + pathObject: FormatInputPathObject, ): string { const dir: string | undefined = pathObject.dir || pathObject.root; - const base: string = - pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); + const base: string = pathObject.base || + (pathObject.name || "") + (pathObject.ext || ""); if (!dir) return base; if (dir === pathObject.root) return dir + base; return dir + sep + base; diff --git a/std/path/basename_test.ts b/std/path/basename_test.ts index b0694de20..9e2265db9 100644 --- a/std/path/basename_test.ts +++ b/std/path/basename_test.ts @@ -32,7 +32,7 @@ Deno.test("basename", function () { // On unix a backslash is just treated as any other character. assertEquals( path.posix.basename("\\dir\\basename.ext"), - "\\dir\\basename.ext" + "\\dir\\basename.ext", ); assertEquals(path.posix.basename("\\basename.ext"), "\\basename.ext"); assertEquals(path.posix.basename("basename.ext"), "basename.ext"); @@ -44,7 +44,7 @@ Deno.test("basename", function () { const controlCharFilename = "Icon" + String.fromCharCode(13); assertEquals( path.posix.basename("/a/b/" + controlCharFilename), - controlCharFilename + controlCharFilename, ); }); diff --git a/std/path/common_test.ts b/std/path/common_test.ts index 921cf1c99..7b7bd2ba3 100644 --- a/std/path/common_test.ts +++ b/std/path/common_test.ts @@ -11,7 +11,7 @@ Deno.test({ "file://deno/std/path/mod.ts", "file://deno/cli/js/main.ts", ], - "/" + "/", ); assertEquals(actual, "file://deno/"); }, @@ -22,7 +22,7 @@ Deno.test({ fn() { const actual = common( ["file://deno/cli/js/deno.ts", "https://deno.land/std/path/mod.ts"], - "/" + "/", ); assertEquals(actual, ""); }, @@ -37,7 +37,7 @@ Deno.test({ "c:\\deno\\std\\path\\mod.ts", "c:\\deno\\cli\\js\\main.ts", ], - "\\" + "\\", ); assertEquals(actual, "c:\\deno\\"); }, diff --git a/std/path/dirname_test.ts b/std/path/dirname_test.ts index bdf3391a9..210d3a9ec 100644 --- a/std/path/dirname_test.ts +++ b/std/path/dirname_test.ts @@ -40,15 +40,15 @@ Deno.test("dirnameWin32", function () { assertEquals(path.win32.dirname("\\\\unc\\share\\foo\\"), "\\\\unc\\share\\"); assertEquals( path.win32.dirname("\\\\unc\\share\\foo\\bar"), - "\\\\unc\\share\\foo" + "\\\\unc\\share\\foo", ); assertEquals( path.win32.dirname("\\\\unc\\share\\foo\\bar\\"), - "\\\\unc\\share\\foo" + "\\\\unc\\share\\foo", ); assertEquals( path.win32.dirname("\\\\unc\\share\\foo\\bar\\baz"), - "\\\\unc\\share\\foo\\bar" + "\\\\unc\\share\\foo\\bar", ); assertEquals(path.win32.dirname("/a/b/"), "/a"); assertEquals(path.win32.dirname("/a/b"), "/a"); diff --git a/std/path/glob.ts b/std/path/glob.ts index 5288efda9..172587626 100644 --- a/std/path/glob.ts +++ b/std/path/glob.ts @@ -41,7 +41,7 @@ export interface GlobToRegExpOptions extends GlobOptions { */ export function globToRegExp( glob: string, - { extended = false, globstar = true }: GlobToRegExpOptions = {} + { extended = false, globstar = true }: GlobToRegExpOptions = {}, ): RegExp { const result = globrex(glob, { extended, @@ -57,7 +57,8 @@ export function globToRegExp( export function isGlob(str: string): boolean { const chars: Record<string, string> = { "{": "}", "(": ")", "[": "]" }; /* eslint-disable-next-line max-len */ - const regex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; + const regex = + /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; if (str === "") { return false; @@ -89,7 +90,7 @@ export function isGlob(str: string): boolean { /** Like normalize(), but doesn't collapse "**\/.." when `globstar` is true. */ export function normalizeGlob( glob: string, - { globstar = false }: GlobOptions = {} + { globstar = false }: GlobOptions = {}, ): string { if (glob.match(/\0/g)) { throw new Error(`Glob contains invalid characters: "${glob}"`); @@ -100,7 +101,7 @@ export function normalizeGlob( const s = SEP_PATTERN.source; const badParentPattern = new RegExp( `(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, - "g" + "g", ); return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, ".."); } @@ -108,7 +109,7 @@ export function normalizeGlob( /** Like join(), but doesn't collapse "**\/.." when `globstar` is true. */ export function joinGlobs( globs: string[], - { extended = false, globstar = false }: GlobOptions = {} + { extended = false, globstar = false }: GlobOptions = {}, ): string { if (!globstar || globs.length == 0) { return join(...globs); diff --git a/std/path/glob_test.ts b/std/path/glob_test.ts index 1c90e765a..dba79c302 100644 --- a/std/path/glob_test.ts +++ b/std/path/glob_test.ts @@ -13,33 +13,33 @@ Deno.test({ assertEquals(globToRegExp("*.ts").test("unicorn.js"), false); assertEquals( globToRegExp(join("unicorn", "**", "cathedral.ts")).test( - join("unicorn", "in", "the", "cathedral.ts") + join("unicorn", "in", "the", "cathedral.ts"), ), - true + true, ); assertEquals( globToRegExp(join("unicorn", "**", "cathedral.ts")).test( - join("unicorn", "in", "the", "kitchen.ts") + join("unicorn", "in", "the", "kitchen.ts"), ), - false + false, ); assertEquals( globToRegExp(join("unicorn", "**", "bathroom.*")).test( - join("unicorn", "sleeping", "in", "bathroom.py") + join("unicorn", "sleeping", "in", "bathroom.py"), ), - true + true, ); assertEquals( globToRegExp(join("unicorn", "!(sleeping)", "bathroom.ts"), { extended: true, }).test(join("unicorn", "flying", "bathroom.ts")), - true + true, ); assertEquals( globToRegExp(join("unicorn", "(!sleeping)", "bathroom.ts"), { extended: true, }).test(join("unicorn", "sleeping", "bathroom.ts")), - false + false, ); }, }); @@ -59,7 +59,7 @@ testWalk( assertEquals(arr.length, 2); assertEquals(arr[0], "a/x.ts"); assertEquals(arr[1], "b/z.ts"); - } + }, ); testWalk( @@ -79,7 +79,7 @@ testWalk( }); assertEquals(arr.length, 1); assertEquals(arr[0], "a/yo/x.ts"); - } + }, ); testWalk( @@ -104,7 +104,7 @@ testWalk( assertEquals(arr.length, 2); assertEquals(arr[0], "a/deno/x.ts"); assertEquals(arr[1], "a/raptor/x.ts"); - } + }, ); testWalk( @@ -120,7 +120,7 @@ testWalk( assertEquals(arr.length, 2); assertEquals(arr[0], "x.js"); assertEquals(arr[1], "x.ts"); - } + }, ); Deno.test({ diff --git a/std/path/posix.ts b/std/path/posix.ts index 351ceb06e..03d07a84a 100644 --- a/std/path/posix.ts +++ b/std/path/posix.ts @@ -50,7 +50,7 @@ export function resolve(...pathSegments: string[]): string { resolvedPath, !resolvedAbsolute, "/", - isPosixPathSeparator + isPosixPathSeparator, ); if (resolvedAbsolute) { @@ -337,7 +337,7 @@ 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}` + `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`, ); } return _format("/", pathObject); diff --git a/std/path/win32.ts b/std/path/win32.ts index 30482e453..66ed1ff14 100644 --- a/std/path/win32.ts +++ b/std/path/win32.ts @@ -167,7 +167,7 @@ export function resolve(...pathSegments: string[]): string { resolvedTail, !resolvedAbsolute, "\\", - isPathSeparator + isPathSeparator, ); return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "."; @@ -259,7 +259,7 @@ export function normalize(path: string): string { path.slice(rootEnd), !isAbsolute, "\\", - isPathSeparator + isPathSeparator, ); } else { tail = ""; @@ -750,7 +750,7 @@ 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}` + `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`, ); } return _format("\\", pathObject); diff --git a/std/permissions/mod.ts b/std/permissions/mod.ts index b7f80117b..71c7e43ff 100644 --- a/std/permissions/mod.ts +++ b/std/permissions/mod.ts @@ -4,7 +4,8 @@ const { PermissionDenied } = Deno.errors; function getPermissionString(descriptors: Deno.PermissionDescriptor[]): string { return descriptors.length - ? ` ${descriptors + ? ` ${ + descriptors .map((pd) => { switch (pd.name) { case "read": @@ -20,7 +21,8 @@ function getPermissionString(descriptors: Deno.PermissionDescriptor[]): string { return `--allow-${pd.name}`; } }) - .join("\n ")}` + .join("\n ") + }` : ""; } @@ -52,7 +54,7 @@ export async function grant( * If one of the permissions requires a prompt, the function will attempt to * prompt for it. The function resolves with all of the granted permissions. */ export async function grant( - descriptors: Deno.PermissionDescriptor[] + descriptors: Deno.PermissionDescriptor[], ): Promise<void | Deno.PermissionDescriptor[]>; export async function grant( descriptor: Deno.PermissionDescriptor[] | Deno.PermissionDescriptor, @@ -94,7 +96,7 @@ export async function grantOrThrow( * the denied permissions. If all permissions are granted, the function will * resolve. */ export async function grantOrThrow( - descriptors: Deno.PermissionDescriptor[] + descriptors: Deno.PermissionDescriptor[], ): Promise<void>; export async function grantOrThrow( descriptor: Deno.PermissionDescriptor[] | Deno.PermissionDescriptor, @@ -112,9 +114,11 @@ export async function grantOrThrow( } if (denied.length) { throw new PermissionDenied( - `The following permissions have not been granted:\n${getPermissionString( - denied - )}` + `The following permissions have not been granted:\n${ + getPermissionString( + denied, + ) + }`, ); } } diff --git a/std/signal/mod.ts b/std/signal/mod.ts index f09f76882..44ed24f13 100644 --- a/std/signal/mod.ts +++ b/std/signal/mod.ts @@ -27,7 +27,7 @@ export function signal( if (signos.length < 1) { throw new Error( - "No signals are given. You need to specify at least one signal to create a signal stream." + "No signals are given. You need to specify at least one signal to create a signal stream.", ); } diff --git a/std/signal/test.ts b/std/signal/test.ts index 4c8aa82e0..a21cc1d64 100644 --- a/std/signal/test.ts +++ b/std/signal/test.ts @@ -12,7 +12,7 @@ Deno.test({ (signal as any)(); }, Error, - "No signals are given. You need to specify at least one signal to create a signal stream." + "No signals are given. You need to specify at least one signal to create a signal stream.", ); }, }); @@ -28,7 +28,7 @@ Deno.test({ const sig = signal( Deno.Signal.SIGUSR1, Deno.Signal.SIGUSR2, - Deno.Signal.SIGINT + Deno.Signal.SIGINT, ); setTimeout(async () => { diff --git a/std/testing/README.md b/std/testing/README.md index 0e0ee14e7..bc9d8af33 100644 --- a/std/testing/README.md +++ b/std/testing/README.md @@ -90,7 +90,7 @@ Deno.test("doesThrow", function (): void { throw new TypeError("hello world!"); }, TypeError, - "hello" + "hello", ); }); @@ -109,7 +109,7 @@ Deno.test("doesThrow", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { throw new TypeError("hello world!"); - } + }, ); await assertThrowsAsync(async (): Promise<void> => { throw new TypeError("hello world!"); @@ -119,12 +119,12 @@ Deno.test("doesThrow", async function (): Promise<void> { throw new TypeError("hello world!"); }, TypeError, - "hello" + "hello", ); await assertThrowsAsync( async (): Promise<void> => { return Promise.reject(new Error()); - } + }, ); }); @@ -133,7 +133,7 @@ Deno.test("fails", async function (): Promise<void> { await assertThrowsAsync( async (): Promise<void> => { console.log("Hello world"); - } + }, ); }); ``` @@ -214,7 +214,7 @@ runBenchmarks({ silent: true }, (p: BenchmarkRunProgress) => { // initial progress data if (p.state === ProgressState.BenchmarkingStart) { console.log( - `Starting benchmarking. Queued: ${p.queued.length}, filtered: ${p.filtered}` + `Starting benchmarking. Queued: ${p.queued.length}, filtered: ${p.filtered}`, ); } // ... diff --git a/std/testing/asserts.ts b/std/testing/asserts.ts index 2a1358143..4b9241e55 100644 --- a/std/testing/asserts.ts +++ b/std/testing/asserts.ts @@ -22,12 +22,12 @@ export class AssertionError extends Error { export function _format(v: unknown): string { let string = globalThis.Deno ? Deno.inspect(v, { - depth: Infinity, - sorted: true, - trailingComma: true, - compact: false, - iterableLimit: Infinity, - }) + depth: Infinity, + sorted: true, + trailingComma: true, + compact: false, + iterableLimit: Infinity, + }) : String(v); if (typeof v == "string") { string = `"${string.replace(/(?=["\\])/g, "\\")}"`; @@ -62,9 +62,9 @@ function buildMessage(diffResult: ReadonlyArray<DiffResult<string>>): string[] { messages.push(""); messages.push(""); messages.push( - ` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${green( - bold("Expected") - )}` + ` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${ + green(bold("Expected")) + }`, ); messages.push(""); messages.push(""); @@ -163,13 +163,13 @@ export function assert(expr: unknown, msg = ""): asserts expr { export function assertEquals( actual: unknown, expected: unknown, - msg?: string + msg?: string, ): void; export function assertEquals<T>(actual: T, expected: T, msg?: string): void; export function assertEquals( actual: unknown, expected: unknown, - msg?: string + msg?: string, ): void { if (equal(actual, expected)) { return; @@ -180,7 +180,7 @@ export function assertEquals( try { const diffResult = diff( actualString.split("\n"), - expectedString.split("\n") + expectedString.split("\n"), ); const diffMsg = buildMessage(diffResult).join("\n"); message = `Values are not equal:\n${diffMsg}`; @@ -206,13 +206,13 @@ export function assertEquals( export function assertNotEquals( actual: unknown, expected: unknown, - msg?: string + msg?: string, ): void; export function assertNotEquals<T>(actual: T, expected: T, msg?: string): void; export function assertNotEquals( actual: unknown, expected: unknown, - msg?: string + msg?: string, ): void { if (!equal(actual, expected)) { return; @@ -245,7 +245,7 @@ export function assertNotEquals( export function assertStrictEquals<T>( actual: T, expected: T, - msg?: string + msg?: string, ): void { if (actual === expected) { return; @@ -264,14 +264,15 @@ export function assertStrictEquals<T>( .split("\n") .map((l) => ` ${l}`) .join("\n"); - message = `Values have the same structure but are not reference-equal:\n\n${red( - withOffset - )}\n`; + message = + `Values have the same structure but are not reference-equal:\n\n${ + red(withOffset) + }\n`; } else { try { const diffResult = diff( actualString.split("\n"), - expectedString.split("\n") + expectedString.split("\n"), ); const diffMsg = buildMessage(diffResult).join("\n"); message = `Values are not strictly equal:\n${diffMsg}`; @@ -291,7 +292,7 @@ export function assertStrictEquals<T>( export function assertStringContains( actual: string, expected: string, - msg?: string + msg?: string, ): void { if (!actual.includes(expected)) { if (!msg) { @@ -314,17 +315,17 @@ export function assertStringContains( export function assertArrayContains( actual: ArrayLike<unknown>, expected: ArrayLike<unknown>, - msg?: string + msg?: string, ): void; export function assertArrayContains<T>( actual: ArrayLike<T>, expected: ArrayLike<T>, - msg?: string + msg?: string, ): void; export function assertArrayContains( actual: ArrayLike<unknown>, expected: ArrayLike<unknown>, - msg?: string + msg?: string, ): void { const missing: unknown[] = []; for (let i = 0; i < expected.length; i++) { @@ -343,9 +344,9 @@ export function assertArrayContains( return; } if (!msg) { - msg = `actual: "${_format(actual)}" expected to contain: "${_format( - expected - )}"\nmissing: ${_format(missing)}`; + msg = `actual: "${_format(actual)}" expected to contain: "${ + _format(expected) + }"\nmissing: ${_format(missing)}`; } throw new AssertionError(msg); } @@ -357,7 +358,7 @@ export function assertArrayContains( export function assertMatch( actual: string, expected: RegExp, - msg?: string + msg?: string, ): void { if (!expected.test(actual)) { if (!msg) { @@ -384,7 +385,7 @@ export function assertThrows<T = void>( fn: () => T, ErrorClass?: Constructor, msgIncludes = "", - msg?: string + msg?: string, ): Error { let doesThrow = false; let error = null; @@ -395,18 +396,20 @@ export function assertThrows<T = void>( throw new AssertionError("A non-Error object was thrown."); } if (ErrorClass && !(e instanceof ErrorClass)) { - msg = `Expected error to be instance of "${ErrorClass.name}", but was "${ - e.constructor.name - }"${msg ? `: ${msg}` : "."}`; + msg = + `Expected error to be instance of "${ErrorClass.name}", but was "${e.constructor.name}"${ + msg ? `: ${msg}` : "." + }`; throw new AssertionError(msg); } if ( msgIncludes && !stripColor(e.message).includes(stripColor(msgIncludes)) ) { - msg = `Expected error message to include "${msgIncludes}", but got "${ - e.message - }"${msg ? `: ${msg}` : "."}`; + msg = + `Expected error message to include "${msgIncludes}", but got "${e.message}"${ + msg ? `: ${msg}` : "." + }`; throw new AssertionError(msg); } doesThrow = true; @@ -428,7 +431,7 @@ export async function assertThrowsAsync<T = void>( fn: () => Promise<T>, ErrorClass?: Constructor, msgIncludes = "", - msg?: string + msg?: string, ): Promise<Error> { let doesThrow = false; let error = null; @@ -439,18 +442,20 @@ export async function assertThrowsAsync<T = void>( throw new AssertionError("A non-Error object was thrown or rejected."); } if (ErrorClass && !(e instanceof ErrorClass)) { - msg = `Expected error to be instance of "${ErrorClass.name}", but got "${ - e.name - }"${msg ? `: ${msg}` : "."}`; + msg = + `Expected error to be instance of "${ErrorClass.name}", but got "${e.name}"${ + msg ? `: ${msg}` : "." + }`; throw new AssertionError(msg); } if ( msgIncludes && !stripColor(e.message).includes(stripColor(msgIncludes)) ) { - msg = `Expected error message to include "${msgIncludes}", but got "${ - e.message - }"${msg ? `: ${msg}` : "."}`; + msg = + `Expected error message to include "${msgIncludes}", but got "${e.message}"${ + msg ? `: ${msg}` : "." + }`; throw new AssertionError(msg); } doesThrow = true; diff --git a/std/testing/asserts_test.ts b/std/testing/asserts_test.ts index c3059ebac..7ea73b5c0 100644 --- a/std/testing/asserts_test.ts +++ b/std/testing/asserts_test.ts @@ -29,14 +29,14 @@ Deno.test("testingEqual", function (): void { assert( equal( { hello: "world", hi: { there: "everyone" } }, - { hello: "world", hi: { there: "everyone" } } - ) + { hello: "world", hi: { there: "everyone" } }, + ), ); assert( !equal( { hello: "world", hi: { there: "everyone" } }, - { hello: "world", hi: { there: "everyone else" } } - ) + { hello: "world", hi: { there: "everyone else" } }, + ), ); assert(equal(/deno/, /deno/)); assert(!equal(/deno/, /node/)); @@ -45,8 +45,8 @@ Deno.test("testingEqual", function (): void { assert( !equal( new Date(2019, 0, 3, 4, 20, 1, 10), - new Date(2019, 0, 3, 4, 20, 1, 20) - ) + new Date(2019, 0, 3, 4, 20, 1, 20), + ), ); assert(equal(new Set([1]), new Set([1]))); assert(!equal(new Set([1]), new Set([2]))); @@ -65,20 +65,20 @@ Deno.test("testingEqual", function (): void { new Map([ ["foo", "bar"], ["baz", "baz"], - ]) - ) + ]), + ), ); assert( equal( new Map([["foo", new Map([["bar", "baz"]])]]), - new Map([["foo", new Map([["bar", "baz"]])]]) - ) + new Map([["foo", new Map([["bar", "baz"]])]]), + ), ); assert( equal( new Map([["foo", { bar: "baz" }]]), - new Map([["foo", { bar: "baz" }]]) - ) + new Map([["foo", { bar: "baz" }]]), + ), ); assert( equal( @@ -89,8 +89,8 @@ Deno.test("testingEqual", function (): void { new Map([ ["baz", "qux"], ["foo", "bar"], - ]) - ) + ]), + ), ); assert(equal(new Map([["foo", ["bar"]]]), new Map([["foo", ["bar"]]]))); assert(!equal(new Map([["foo", "bar"]]), new Map([["bar", "baz"]]))); @@ -100,14 +100,14 @@ Deno.test("testingEqual", function (): void { new Map([ ["foo", "bar"], ["bar", "baz"], - ]) - ) + ]), + ), ); assert( !equal( new Map([["foo", new Map([["bar", "baz"]])]]), - new Map([["foo", new Map([["bar", "qux"]])]]) - ) + new Map([["foo", new Map([["bar", "qux"]])]]), + ), ); assert(equal(new Map([[{ x: 1 }, true]]), new Map([[{ x: 1 }, true]]))); assert(!equal(new Map([[{ x: 1 }, true]]), new Map([[{ x: 1 }, false]]))); @@ -120,13 +120,13 @@ Deno.test("testingEqual", function (): void { assert(equal(new Uint8Array([1, 2, 3, 4]), new Uint8Array([1, 2, 3, 4]))); assert(!equal(new Uint8Array([1, 2, 3, 4]), new Uint8Array([2, 1, 4, 3]))); assert( - equal(new URL("https://example.test"), new URL("https://example.test")) + equal(new URL("https://example.test"), new URL("https://example.test")), ); assert( !equal( new URL("https://example.test"), - new URL("https://example.test/with-path") - ) + new URL("https://example.test/with-path"), + ), ); }); @@ -137,7 +137,7 @@ Deno.test("testingNotEquals", function (): void { assertNotEquals("Denosaurus", "Tyrannosaurus"); assertNotEquals( new Date(2019, 0, 3, 4, 20, 1, 10), - new Date(2019, 0, 3, 4, 20, 1, 20) + new Date(2019, 0, 3, 4, 20, 1, 20), ); let didThrow; try { @@ -172,7 +172,7 @@ Deno.test("testingArrayContains", function (): void { assertArrayContains(fixtureObject, [{ deno: "luv" }]); assertArrayContains( Uint8Array.from([1, 2, 3, 4]), - Uint8Array.from([1, 2, 3]) + Uint8Array.from([1, 2, 3]), ); assertThrows( (): void => assertArrayContains(fixtureObject, [{ deno: "node" }]), @@ -193,7 +193,7 @@ missing: [ { deno: "node", }, -]` +]`, ); }); @@ -204,7 +204,7 @@ Deno.test("testingAssertStringContainsThrow", function (): void { } catch (e) { assert( e.message === - `actual: "Denosaurus from Jurassic" expected to contain: "Raptor"` + `actual: "Denosaurus from Jurassic" expected to contain: "Raptor"`, ); assert(e instanceof AssertionError); didThrow = true; @@ -223,7 +223,7 @@ Deno.test("testingAssertStringMatchingThrows", function (): void { } catch (e) { assert( e.message === - `actual: "Denosaurus from Jurassic" expected to match: "/Raptor/"` + `actual: "Denosaurus from Jurassic" expected to match: "/Raptor/"`, ); assert(e instanceof AssertionError); didThrow = true; @@ -262,7 +262,7 @@ Deno.test("testingAssertFail", function (): void { fail("foo"); }, AssertionError, - "Failed assertion: foo" + "Failed assertion: foo", ); }); @@ -276,11 +276,11 @@ Deno.test("testingAssertFailWithWrongErrorClass", function (): void { fail("foo"); }, TypeError, - "Failed assertion: foo" + "Failed assertion: foo", ); }, AssertionError, - `Expected error to be instance of "TypeError", but was "AssertionError"` + `Expected error to be instance of "TypeError", but was "AssertionError"`, ); }); @@ -299,9 +299,9 @@ Deno.test("testingAssertThrowsAsyncWithReturnType", () => { const createHeader = (): string[] => [ "", "", - ` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${green( - bold("Expected") - )}`, + ` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${ + green(bold("Expected")) + }`, "", "", ]; @@ -332,7 +332,7 @@ Deno.test({ removed(`- ${yellow("1")}`), added(`+ ${yellow("2")}`), "", - ].join("\n") + ].join("\n"), ); }, }); @@ -348,7 +348,7 @@ Deno.test({ ...createHeader(), removed(`- ${yellow("1")}`), added(`+ "1"`), - ].join("\n") + ].join("\n"), ); }, }); @@ -365,7 +365,7 @@ Deno.test({ + "1", "2", 3, - ]` + ]`, ); }, }); @@ -385,7 +385,7 @@ Deno.test({ + ], - b: "2", - c: 3, - }` + }`, ); }, }); @@ -397,7 +397,7 @@ Deno.test({ (): void => assertEquals( new Date(2019, 0, 3, 4, 20, 1, 10), - new Date(2019, 0, 3, 4, 20, 1, 20) + new Date(2019, 0, 3, 4, 20, 1, 20), ), AssertionError, [ @@ -406,7 +406,7 @@ Deno.test({ removed(`- ${new Date(2019, 0, 3, 4, 20, 1, 10).toISOString()}`), added(`+ ${new Date(2019, 0, 3, 4, 20, 1, 20).toISOString()}`), "", - ].join("\n") + ].join("\n"), ); }, }); @@ -441,7 +441,7 @@ Deno.test({ + 3, + ], - b: 2, - }` + }`, ); }, }); @@ -457,7 +457,7 @@ Deno.test({ { a: 1, b: 2, - }` + }`, ); }, }); @@ -481,11 +481,11 @@ Deno.test("Assert Throws Non-Error Fail", () => { throw "Panic!"; }, String, - "Panic!" + "Panic!", ); }, AssertionError, - "A non-Error object was thrown." + "A non-Error object was thrown.", ); assertThrows( @@ -495,7 +495,7 @@ Deno.test("Assert Throws Non-Error Fail", () => { }); }, AssertionError, - "A non-Error object was thrown." + "A non-Error object was thrown.", ); assertThrows( @@ -505,7 +505,7 @@ Deno.test("Assert Throws Non-Error Fail", () => { }); }, AssertionError, - "A non-Error object was thrown." + "A non-Error object was thrown.", ); }); @@ -517,11 +517,11 @@ Deno.test("Assert Throws Async Non-Error Fail", () => { return Promise.reject("Panic!"); }, String, - "Panic!" + "Panic!", ); }, AssertionError, - "A non-Error object was thrown or rejected." + "A non-Error object was thrown or rejected.", ); assertThrowsAsync( @@ -531,7 +531,7 @@ Deno.test("Assert Throws Async Non-Error Fail", () => { }); }, AssertionError, - "A non-Error object was thrown or rejected." + "A non-Error object was thrown or rejected.", ); assertThrowsAsync( @@ -541,7 +541,7 @@ Deno.test("Assert Throws Async Non-Error Fail", () => { }); }, AssertionError, - "A non-Error object was thrown or rejected." + "A non-Error object was thrown or rejected.", ); assertThrowsAsync( @@ -551,7 +551,7 @@ Deno.test("Assert Throws Async Non-Error Fail", () => { }); }, AssertionError, - "A non-Error object was thrown or rejected." + "A non-Error object was thrown or rejected.", ); }); @@ -568,7 +568,7 @@ Deno.test("assertEquals diff for differently ordered objects", () => { ccccccccccccccccccccccc: 1, aaaaaaaaaaaaaaaaaaaaaaaa: 0, bbbbbbbbbbbbbbbbbbbbbbbb: 0, - } + }, ); }, AssertionError, @@ -578,7 +578,7 @@ Deno.test("assertEquals diff for differently ordered objects", () => { bbbbbbbbbbbbbbbbbbbbbbbb: 0, - ccccccccccccccccccccccc: 0, + ccccccccccccccccccccccc: 1, - }` + }`, ); }); @@ -592,7 +592,7 @@ Deno.test("assert diff formatting", () => { `{ a: 1, b: 2, -}` +}`, ); // Same for nested small objects. @@ -609,7 +609,7 @@ Deno.test("assert diff formatting", () => { "b", ], }, -]` +]`, ); // Grouping is disabled. @@ -623,7 +623,7 @@ Deno.test("assert diff formatting", () => { "i", "i", "i", -]` +]`, ); }); @@ -633,7 +633,7 @@ Deno.test("Assert Throws Parent Error", () => { throw new AssertionError("Fail!"); }, Error, - "Fail!" + "Fail!", ); }); @@ -643,6 +643,6 @@ Deno.test("Assert Throws Async Parent Error", () => { throw new AssertionError("Fail!"); }, Error, - "Fail!" + "Fail!", ); }); diff --git a/std/testing/bench.ts b/std/testing/bench.ts index e6f4582b9..b8bf40a9b 100644 --- a/std/testing/bench.ts +++ b/std/testing/bench.ts @@ -112,17 +112,17 @@ function assertTiming(clock: BenchmarkClock): void { if (!clock.stop) { throw new BenchmarkRunError( `Running benchmarks FAILED during benchmark named [${clock.for}]. The benchmark timer's stop method must be called`, - clock.for + clock.for, ); } else if (!clock.start) { throw new BenchmarkRunError( `Running benchmarks FAILED during benchmark named [${clock.for}]. The benchmark timer's start method must be called`, - clock.for + clock.for, ); } else if (clock.start > clock.stop) { throw new BenchmarkRunError( `Running benchmarks FAILED during benchmark named [${clock.for}]. The benchmark timer's start method must be called before its stop method`, - clock.for + clock.for, ); } } @@ -136,7 +136,7 @@ function createBenchmarkTimer(clock: BenchmarkClock): BenchmarkTimer { if (isNaN(clock.start)) { throw new BenchmarkRunError( `Running benchmarks FAILED during benchmark named [${clock.for}]. The benchmark timer's start method must be called before its stop method`, - clock.for + clock.for, ); } clock.stop = performance.now(); @@ -148,7 +148,7 @@ const candidates: BenchmarkDefinition[] = []; /** Registers a benchmark as a candidate for the runBenchmarks executor. */ export function bench( - benchmark: BenchmarkDefinition | BenchmarkFunction + benchmark: BenchmarkDefinition | BenchmarkFunction, ): void { if (!benchmark.name) { throw new Error("The benchmark function must not be anonymous"); @@ -171,7 +171,7 @@ export function clearBenchmarks({ skip = /$^/, }: BenchmarkClearOptions = {}): void { const keep = candidates.filter( - ({ name }): boolean => !only.test(name) || skip.test(name) + ({ name }): boolean => !only.test(name) || skip.test(name), ); candidates.splice(0, candidates.length); candidates.push(...keep); @@ -185,11 +185,11 @@ export function clearBenchmarks({ */ export async function runBenchmarks( { only = /[^\s]/, skip = /^\s*$/, silent }: BenchmarkRunOptions = {}, - progressCb?: (progress: BenchmarkRunProgress) => void | Promise<void> + progressCb?: (progress: BenchmarkRunProgress) => void | Promise<void>, ): Promise<BenchmarkRunResult> { // Filtering candidates by the "only" and "skip" constraint const benchmarks: BenchmarkDefinition[] = candidates.filter( - ({ name }): boolean => only.test(name) && !skip.test(name) + ({ name }): boolean => only.test(name) && !skip.test(name), ); // Init main counters and error flag const filtered = candidates.length - benchmarks.length; @@ -217,7 +217,7 @@ export async function runBenchmarks( console.log( "running", benchmarks.length, - `benchmark${benchmarks.length === 1 ? " ..." : "s ..."}` + `benchmark${benchmarks.length === 1 ? " ..." : "s ..."}`, ); } @@ -233,7 +233,7 @@ export async function runBenchmarks( // Remove benchmark from queued const queueIndex = progress.queued.findIndex( - (queued) => queued.name === name && queued.runsCount === runs + (queued) => queued.name === name && queued.runsCount === runs, ); if (queueIndex != -1) { progress.queued.splice(queueIndex, 1); @@ -268,17 +268,16 @@ export async function runBenchmarks( await publishProgress( progress, ProgressState.BenchPartialResult, - progressCb + progressCb, ); // Resetting the benchmark clock clock.start = clock.stop = NaN; // Once all ran if (!--pendingRuns) { - result = - runs == 1 - ? `${totalMs}ms` - : `${runs} runs avg: ${totalMs / runs}ms`; + result = runs == 1 + ? `${totalMs}ms` + : `${runs} runs avg: ${totalMs / runs}ms`; // Adding results progress.results.push({ name, @@ -293,7 +292,7 @@ export async function runBenchmarks( await publishProgress( progress, ProgressState.BenchResult, - progressCb + progressCb, ); break; } @@ -329,7 +328,7 @@ export async function runBenchmarks( // Closing results console.log( `benchmark result: ${failError ? red("FAIL") : blue("DONE")}. ` + - `${progress.results.length} measured; ${filtered} filtered` + `${progress.results.length} measured; ${filtered} filtered`, ); } @@ -349,14 +348,14 @@ export async function runBenchmarks( async function publishProgress( progress: BenchmarkRunProgress, state: ProgressState, - progressCb?: (progress: BenchmarkRunProgress) => void | Promise<void> + progressCb?: (progress: BenchmarkRunProgress) => void | Promise<void>, ): Promise<void> { progressCb && (await progressCb(cloneProgressWithState(progress, state))); } function cloneProgressWithState( progress: BenchmarkRunProgress, - state: ProgressState + state: ProgressState, ): BenchmarkRunProgress { return deepAssign({}, progress, { state }) as BenchmarkRunProgress; } diff --git a/std/testing/bench_test.ts b/std/testing/bench_test.ts index b6d64ab89..97a923ac2 100644 --- a/std/testing/bench_test.ts +++ b/std/testing/bench_test.ts @@ -46,8 +46,8 @@ Deno.test({ async (denoland: string): Promise<void> => { const r = await fetch(denoland); await r.text(); - } - ) + }, + ), ); b.stop(); }); @@ -73,7 +73,7 @@ Deno.test({ assertEquals(benchResult.results.length, 5); const resultWithSingleRunsFiltered = benchResult.results.filter( - ({ name }) => name === "forDecrementX1e9" + ({ name }) => name === "forDecrementX1e9", ); assertEquals(resultWithSingleRunsFiltered.length, 1); @@ -85,7 +85,7 @@ Deno.test({ assertEquals(resultWithSingleRuns.measuredRunsMs.length, 1); const resultWithMultipleRunsFiltered = benchResult.results.filter( - ({ name }) => name === "runs100ForIncrementX1e6" + ({ name }) => name === "runs100ForIncrementX1e6", ); assertEquals(resultWithMultipleRunsFiltered.length, 1); @@ -108,7 +108,7 @@ Deno.test({ bench(() => {}); }, Error, - "The benchmark function must not be anonymous" + "The benchmark function must not be anonymous", ); }, }); @@ -125,7 +125,7 @@ Deno.test({ await runBenchmarks({ only: /benchWithoutStop/, silent: true }); }, BenchmarkRunError, - "The benchmark timer's stop method must be called" + "The benchmark timer's stop method must be called", ); }, }); @@ -142,7 +142,7 @@ Deno.test({ await runBenchmarks({ only: /benchWithoutStart/, silent: true }); }, BenchmarkRunError, - "The benchmark timer's start method must be called" + "The benchmark timer's start method must be called", ); }, }); @@ -160,7 +160,7 @@ Deno.test({ await runBenchmarks({ only: /benchStopBeforeStart/, silent: true }); }, BenchmarkRunError, - "The benchmark timer's start method must be called before its stop method" + "The benchmark timer's start method must be called before its stop method", ); }, }); @@ -249,7 +249,7 @@ Deno.test({ { skip: /skip/, silent: true }, (progress) => { progressCallbacks.push(progress); - } + }, ); let pc = 0; @@ -322,7 +322,7 @@ Deno.test({ assertEquals(progress.results.length, 2); assert(!!progress.results.find(({ name }) => name == "single")); const resultOfMultiple = progress.results.filter( - ({ name }) => name == "multiple" + ({ name }) => name == "multiple", ); assertEquals(resultOfMultiple.length, 1); assert(!!resultOfMultiple[0].measuredRunsMs); diff --git a/std/testing/diff.ts b/std/testing/diff.ts index da1e827ac..3a9eca4bb 100644 --- a/std/testing/diff.ts +++ b/std/testing/diff.ts @@ -41,7 +41,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { const suffixCommon = createCommon( A.slice(prefixCommon.length), B.slice(prefixCommon.length), - true + true, ).reverse(); A = suffixCommon.length ? A.slice(prefixCommon.length, -suffixCommon.length) @@ -57,16 +57,16 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { if (!N) { return [ ...prefixCommon.map( - (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }) + (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }), ), ...A.map( (a): DiffResult<typeof a> => ({ type: swapped ? DiffType.added : DiffType.removed, value: a, - }) + }), ), ...suffixCommon.map( - (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }) + (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }), ), ]; } @@ -91,7 +91,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { A: T[], B: T[], current: FarthestPoint, - swapped: boolean + swapped: boolean, ): Array<{ type: DiffType; value: T; @@ -133,7 +133,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { slide: FarthestPoint, down: FarthestPoint, k: number, - M: number + M: number, ): FarthestPoint { if (slide && slide.y === -1 && down && down.y === -1) { return { y: 0, id: 0 }; @@ -163,7 +163,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { down: FarthestPoint, _offset: number, A: T[], - B: T[] + B: T[], ): FarthestPoint { const M = A.length; const N = B.length; @@ -189,7 +189,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { fp[k + 1 + offset], offset, A, - B + B, ); } for (let k = delta + p; k > delta; --k) { @@ -199,7 +199,7 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { fp[k + 1 + offset], offset, A, - B + B, ); } fp[delta + offset] = snake( @@ -208,16 +208,16 @@ export default function diff<T>(A: T[], B: T[]): Array<DiffResult<T>> { fp[delta + 1 + offset], offset, A, - B + B, ); } return [ ...prefixCommon.map( - (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }) + (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }), ), ...backTrace(A, B, fp[delta + offset], swapped), ...suffixCommon.map( - (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }) + (c): DiffResult<typeof c> => ({ type: DiffType.common, value: c }), ), ]; } diff --git a/std/textproto/mod.ts b/std/textproto/mod.ts index 1d0d22715..b23ccee19 100644 --- a/std/textproto/mod.ts +++ b/std/textproto/mod.ts @@ -71,7 +71,7 @@ export class TextProtoReader { throw new Deno.errors.UnexpectedEof(); } else if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { throw new Deno.errors.InvalidData( - `malformed MIME header initial line: ${str(line)}` + `malformed MIME header initial line: ${str(line)}`, ); } @@ -84,7 +84,7 @@ export class TextProtoReader { let i = kv.indexOf(charCode(":")); if (i < 0) { throw new Deno.errors.InvalidData( - `malformed MIME header line: ${str(kv)}` + `malformed MIME header line: ${str(kv)}`, ); } @@ -110,7 +110,7 @@ export class TextProtoReader { } const value = str(kv.subarray(i)).replace( invalidHeaderCharRegex, - encodeURI + encodeURI, ); // In case of invalid header we swallow the error diff --git a/std/textproto/test.ts b/std/textproto/test.ts index a7109410b..1d4bed50b 100644 --- a/std/textproto/test.ts +++ b/std/textproto/test.ts @@ -96,8 +96,7 @@ Deno.test({ Deno.test({ name: "[textproto] Reader : MIME Header Non compliant", async fn(): Promise<void> { - const input = - "Foo: bar\r\n" + + const input = "Foo: bar\r\n" + "Content-Language: en\r\n" + "SID : 0\r\n" + "Audio Mode : None\r\n" + @@ -143,9 +142,7 @@ Deno.test({ Deno.test({ name: "[textproto] Reader : MIME Header Trim Continued", async fn(): Promise<void> { - const input = - "" + // for code formatting purpose. - "a:\n" + + const input = "a:\n" + " 0 \r\n" + "b:1 \t\r\n" + "c: 2\r\n" + @@ -185,7 +182,7 @@ Deno.test({ const input = "abcdefghijklmnopqrstuvwxyz"; const bufSize = 25; const tp = new TextProtoReader( - new BufReader(new StringReader(input), bufSize) + new BufReader(new StringReader(input), bufSize), ); const line = await tp.readLine(); assertEquals(line, input); diff --git a/std/uuid/v1.ts b/std/uuid/v1.ts index cbfce576a..6e48fa55f 100644 --- a/std/uuid/v1.ts +++ b/std/uuid/v1.ts @@ -4,7 +4,7 @@ import { bytesToUuid } from "./_common.ts"; const UUID_RE = new RegExp( "^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", - "i" + "i", ); export function validate(id: string): boolean { @@ -29,7 +29,7 @@ type V1Options = { export function generate( options?: V1Options | null, buf?: number[], - offset?: number + offset?: number, ): string | number[] { let i = (buf && offset) || 0; const b = buf || []; @@ -40,8 +40,7 @@ export function generate( if (node == null || clockseq == null) { // eslint-disable-next-line @typescript-eslint/no-explicit-any - const seedBytes: any = - options.random || + const seedBytes: any = options.random || options.rng || crypto.getRandomValues(new Uint8Array(16)); if (node == null) { @@ -58,8 +57,9 @@ export function generate( clockseq = _clockseq = ((seedBytes[6] << 8) | seedBytes[7]) & 0x3fff; } } - let msecs = - options.msecs !== undefined ? options.msecs : new Date().getTime(); + let msecs = options.msecs !== undefined + ? options.msecs + : new Date().getTime(); let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; diff --git a/std/uuid/v4.ts b/std/uuid/v4.ts index 83fc6d86e..53fbc92e3 100644 --- a/std/uuid/v4.ts +++ b/std/uuid/v4.ts @@ -4,7 +4,7 @@ import { bytesToUuid } from "./_common.ts"; const UUID_RE = new RegExp( "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", - "i" + "i", ); export function validate(id: string): boolean { diff --git a/std/uuid/v5.ts b/std/uuid/v5.ts index f982d9745..6375e7bab 100644 --- a/std/uuid/v5.ts +++ b/std/uuid/v5.ts @@ -10,7 +10,8 @@ import { Sha1 } from "../hash/sha1.ts"; import { isString } from "../node/util.ts"; import { assert } from "../_util/assert.ts"; -const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const UUID_RE = + /^[0-9a-f]{8}-[0-9a-f]{4}-[5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; export function validate(id: string): boolean { return UUID_RE.test(id); @@ -24,7 +25,7 @@ interface V5Options { export function generate( options: V5Options, buf?: number[], - offset?: number + offset?: number, ): string | number[] { const i = (buf && offset) || 0; @@ -33,7 +34,7 @@ export function generate( if (isString(namespace)) namespace = uuidToBytes(namespace as string); assert( namespace.length === 16, - "namespace must be uuid string or an Array of 16 byte values" + "namespace must be uuid string or an Array of 16 byte values", ); const content = (namespace as number[]).concat(value as number[]); diff --git a/std/wasi/snapshot_preview1.ts b/std/wasi/snapshot_preview1.ts index 5a526d408..37f8216ff 100644 --- a/std/wasi/snapshot_preview1.ts +++ b/std/wasi/snapshot_preview1.ts @@ -361,7 +361,7 @@ export default class Module { args.reduce(function (acc, arg) { return acc + text.encode(`${arg}\0`).length; }, 0), - true + true, ); return ERRNO_SUCCESS; @@ -387,7 +387,7 @@ export default class Module { environ_sizes_get: ( environc_out: number, - environ_buf_size_out: number + environ_buf_size_out: number, ): number => { const entries = Object.entries(this.env); const text = new TextEncoder(); @@ -399,7 +399,7 @@ export default class Module { entries.reduce(function (acc, [key, value]) { return acc + text.encode(`${key}=${value}\0`).length; }, 0), - true + true, ); return ERRNO_SUCCESS; @@ -435,7 +435,7 @@ export default class Module { clock_time_get: ( id: number, precision: bigint, - time_out: number + time_out: number, ): number => { const view = new DataView(this.memory.buffer); @@ -467,7 +467,7 @@ export default class Module { fd: number, offset: bigint, len: bigint, - advice: number + advice: number, ): number => { return ERRNO_NOSYS; }, @@ -528,7 +528,7 @@ export default class Module { fd_fdstat_set_rights: ( fd: number, fs_rights_base: bigint, - fs_rights_inheriting: bigint + fs_rights_inheriting: bigint, ): number => { return ERRNO_NOSYS; }, @@ -582,21 +582,21 @@ export default class Module { view.setBigUint64( buf_out, BigInt(info.atime ? info.atime.getTime() * 1e6 : 0), - true + true, ); buf_out += 8; view.setBigUint64( buf_out, BigInt(info.mtime ? info.mtime.getTime() * 1e6 : 0), - true + true, ); buf_out += 8; view.setBigUint64( buf_out, BigInt(info.birthtime ? info.birthtime.getTime() * 1e6 : 0), - true + true, ); buf_out += 8; } catch (err) { @@ -625,7 +625,7 @@ export default class Module { fd: number, atim: bigint, mtim: bigint, - fst_flags: number + fst_flags: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -658,7 +658,7 @@ export default class Module { iovs_ptr: number, iovs_len: number, offset: bigint, - nread_out: number + nread_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -701,7 +701,7 @@ export default class Module { view.setUint32( buf_out + 4, new TextEncoder().encode(entry.vpath).byteLength, - true + true, ); return ERRNO_SUCCESS; @@ -710,7 +710,7 @@ export default class Module { fd_prestat_dir_name: ( fd: number, path_ptr: number, - path_len: number + path_len: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -732,7 +732,7 @@ export default class Module { iovs_ptr: number, iovs_len: number, offset: bigint, - nwritten_out: number + nwritten_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -764,7 +764,7 @@ export default class Module { fd: number, iovs_ptr: number, iovs_len: number, - nread_out: number + nread_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -795,7 +795,7 @@ export default class Module { buf_ptr: number, buf_len: number, cookie: bigint, - bufused_out: number + bufused_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -813,7 +813,7 @@ export default class Module { const name_data = new TextEncoder().encode(entries[i].name); const entry_info = Deno.statSync( - resolve(entry.path, entries[i].name) + resolve(entry.path, entries[i].name), ); const entry_data = new Uint8Array(24 + name_data.byteLength); const entry_view = new DataView(entry_data.buffer); @@ -822,7 +822,7 @@ export default class Module { entry_view.setBigUint64( 8, BigInt(entry_info.ino ? entry_info.ino : 0), - true + true, ); entry_view.setUint32(16, name_data.byteLength, true); @@ -849,7 +849,7 @@ export default class Module { const data = entry_data.slice( 0, - Math.min(entry_data.length, buf_len - bufused) + Math.min(entry_data.length, buf_len - bufused), ); heap.set(data, buf_ptr + bufused); bufused += data.byteLength; @@ -883,7 +883,7 @@ export default class Module { fd: number, offset: bigint, whence: number, - newoffset_out: number + newoffset_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -941,7 +941,7 @@ export default class Module { fd: number, iovs_ptr: number, iovs_len: number, - nwritten_out: number + nwritten_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -959,7 +959,7 @@ export default class Module { iovs_ptr += 4; nwritten += entry.handle.writeSync( - new Uint8Array(this.memory.buffer, data_ptr, data_len) + new Uint8Array(this.memory.buffer, data_ptr, data_len), ); } @@ -971,7 +971,7 @@ export default class Module { path_create_directory: ( fd: number, path_ptr: number, - path_len: number + path_len: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1000,7 +1000,7 @@ export default class Module { flags: number, path_ptr: number, path_len: number, - buf_out: number + buf_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1018,10 +1018,9 @@ export default class Module { const view = new DataView(this.memory.buffer); try { - const info = - (flags & LOOKUPFLAGS_SYMLINK_FOLLOW) != 0 - ? Deno.statSync(path) - : Deno.lstatSync(path); + const info = (flags & LOOKUPFLAGS_SYMLINK_FOLLOW) != 0 + ? Deno.statSync(path) + : Deno.lstatSync(path); view.setBigUint64(buf_out, BigInt(info.dev ? info.dev : 0), true); buf_out += 8; @@ -1060,21 +1059,21 @@ export default class Module { view.setBigUint64( buf_out, BigInt(info.atime ? info.atime.getTime() * 1e6 : 0), - true + true, ); buf_out += 8; view.setBigUint64( buf_out, BigInt(info.mtime ? info.mtime.getTime() * 1e6 : 0), - true + true, ); buf_out += 8; view.setBigUint64( buf_out, BigInt(info.birthtime ? info.birthtime.getTime() * 1e6 : 0), - true + true, ); buf_out += 8; } catch (err) { @@ -1091,7 +1090,7 @@ export default class Module { path_len: number, atim: bigint, mtim: bigint, - fst_flags: number + fst_flags: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1130,7 +1129,7 @@ export default class Module { old_path_len: number, new_fd: number, new_path_ptr: number, - new_path_len: number + new_path_len: number, ): number => { const old_entry = this.fds[old_fd]; const new_entry = this.fds[new_fd]; @@ -1146,13 +1145,13 @@ export default class Module { const old_data = new Uint8Array( this.memory.buffer, old_path_ptr, - old_path_len + old_path_len, ); const old_path = resolve(old_entry.path, text.decode(old_data)); const new_data = new Uint8Array( this.memory.buffer, new_path_ptr, - new_path_len + new_path_len, ); const new_path = resolve(new_entry.path, text.decode(new_data)); @@ -1174,7 +1173,7 @@ export default class Module { fs_rights_base: number | bigint, fs_rights_inherting: number | bigint, fdflags: number, - opened_fd_out: number + opened_fd_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1196,11 +1195,10 @@ export default class Module { // around it for now. try { const entries = Array.from(Deno.readDirSync(path)); - const opened_fd = - this.fds.push({ - entries, - path, - }) - 1; + const opened_fd = this.fds.push({ + entries, + path, + }) - 1; const view = new DataView(this.memory.buffer); view.setUint32(opened_fd_out, opened_fd, true); @@ -1237,7 +1235,7 @@ export default class Module { if ( (BigInt(fs_rights_base) & BigInt(RIGHTS_FD_READ | RIGHTS_FD_READDIR)) != - 0n + 0n ) { options.read = true; } @@ -1248,9 +1246,9 @@ export default class Module { RIGHTS_FD_DATASYNC | RIGHTS_FD_WRITE | RIGHTS_FD_ALLOCATE | - RIGHTS_FD_FILESTAT_SET_SIZE + RIGHTS_FD_FILESTAT_SET_SIZE, )) != - 0n + 0n ) { options.write = true; } @@ -1281,11 +1279,10 @@ export default class Module { try { const handle = Deno.openSync(path, options); - const opened_fd = - this.fds.push({ - handle, - path, - }) - 1; + const opened_fd = this.fds.push({ + handle, + path, + }) - 1; const view = new DataView(this.memory.buffer); view.setUint32(opened_fd_out, opened_fd, true); @@ -1302,7 +1299,7 @@ export default class Module { path_len: number, buf_ptr: number, buf_len: number, - bufused_out: number + bufused_out: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1336,7 +1333,7 @@ export default class Module { path_remove_directory: ( fd: number, path_ptr: number, - path_len: number + path_len: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1370,7 +1367,7 @@ export default class Module { old_path_len: number, new_fd: number, new_path_ptr: number, - new_path_len: number + new_path_len: number, ): number => { const old_entry = this.fds[fd]; const new_entry = this.fds[new_fd]; @@ -1386,13 +1383,13 @@ export default class Module { const old_data = new Uint8Array( this.memory.buffer, old_path_ptr, - old_path_len + old_path_len, ); const old_path = resolve(old_entry.path, text.decode(old_data)); const new_data = new Uint8Array( this.memory.buffer, new_path_ptr, - new_path_len + new_path_len, ); const new_path = resolve(new_entry.path, text.decode(new_data)); @@ -1410,7 +1407,7 @@ export default class Module { old_path_len: number, fd: number, new_path_ptr: number, - new_path_len: number + new_path_len: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1425,13 +1422,13 @@ export default class Module { const old_data = new Uint8Array( this.memory.buffer, old_path_ptr, - old_path_len + old_path_len, ); const old_path = text.decode(old_data); const new_data = new Uint8Array( this.memory.buffer, new_path_ptr, - new_path_len + new_path_len, ); const new_path = resolve(entry.path, text.decode(new_data)); @@ -1447,7 +1444,7 @@ export default class Module { path_unlink_file: ( fd: number, path_ptr: number, - path_len: number + path_len: number, ): number => { const entry = this.fds[fd]; if (!entry) { @@ -1475,7 +1472,7 @@ export default class Module { in_ptr: number, out_ptr: number, nsubscriptions: number, - nevents_out: number + nevents_out: number, ): number => { return ERRNO_NOSYS; }, @@ -1505,7 +1502,7 @@ export default class Module { ri_data_len: number, ri_flags: number, ro_datalen_out: number, - ro_flags_out: number + ro_flags_out: number, ): number => { return ERRNO_NOSYS; }, @@ -1515,7 +1512,7 @@ export default class Module { si_data_ptr: number, si_data_len: number, si_flags: number, - so_datalen_out: number + so_datalen_out: number, ): number => { return ERRNO_NOSYS; }, diff --git a/std/wasi/snapshot_preview1_test.ts b/std/wasi/snapshot_preview1_test.ts index 262aa7f95..748ba7772 100644 --- a/std/wasi/snapshot_preview1_test.ts +++ b/std/wasi/snapshot_preview1_test.ts @@ -57,7 +57,7 @@ if (import.meta.main) { const basename = entry.name.replace(/.rs$/, ".json"); await Deno.writeTextFile( path.join(outdir, basename), - prelude[0].slice(2) + prelude[0].slice(2), ); } } diff --git a/std/ws/mod.ts b/std/ws/mod.ts index e2151a53e..5f0219cfc 100644 --- a/std/ws/mod.ts +++ b/std/ws/mod.ts @@ -32,7 +32,7 @@ export interface WebSocketCloseEvent { } export function isWebSocketCloseEvent( - a: WebSocketEvent + a: WebSocketEvent, ): a is WebSocketCloseEvent { return hasOwnProperty(a, "code"); } @@ -40,7 +40,7 @@ export function isWebSocketCloseEvent( export type WebSocketPingEvent = ["ping", Uint8Array]; export function isWebSocketPingEvent( - a: WebSocketEvent + a: WebSocketEvent, ): a is WebSocketPingEvent { return Array.isArray(a) && a[0] === "ping" && a[1] instanceof Uint8Array; } @@ -48,7 +48,7 @@ export function isWebSocketPingEvent( export type WebSocketPongEvent = ["pong", Uint8Array]; export function isWebSocketPongEvent( - a: WebSocketEvent + a: WebSocketEvent, ): a is WebSocketPongEvent { return Array.isArray(a) && a[0] === "pong" && a[1] instanceof Uint8Array; } @@ -105,14 +105,14 @@ export function unmask(payload: Uint8Array, mask?: Uint8Array): void { /** Write websocket frame to given writer */ export async function writeFrame( frame: WebSocketFrame, - writer: Deno.Writer + writer: Deno.Writer, ): Promise<void> { const payloadLength = frame.payload.byteLength; let header: Uint8Array; const hasMask = frame.mask ? 0x80 : 0; if (frame.mask && frame.mask.byteLength !== 4) { throw new Error( - "invalid mask. mask must be 4 bytes: length=" + frame.mask.byteLength + "invalid mask. mask must be 4 bytes: length=" + frame.mask.byteLength, ); } if (payloadLength < 126) { @@ -263,7 +263,7 @@ class WebSocketImpl implements WebSocket { // [0x12, 0x34] -> 0x1234 const code = (frame.payload[0] << 8) | frame.payload[1]; const reason = decode( - frame.payload.subarray(2, frame.payload.length) + frame.payload.subarray(2, frame.payload.length), ); await this.close(code, reason); yield { code, reason }; @@ -312,8 +312,9 @@ class WebSocketImpl implements WebSocket { } send(data: WebSocketMessage): Promise<void> { - const opcode = - typeof data === "string" ? OpCode.TextFrame : OpCode.BinaryFrame; + const opcode = typeof data === "string" + ? OpCode.TextFrame + : OpCode.BinaryFrame; const payload = typeof data === "string" ? encode(data) : data; const isLastFrame = true; const frame = { @@ -382,7 +383,7 @@ class WebSocketImpl implements WebSocket { this.sendQueue = []; rest.forEach((e) => e.d.reject( - new Deno.errors.ConnectionReset("Socket has already been closed") + new Deno.errors.ConnectionReset("Socket has already been closed"), ) ); } @@ -457,7 +458,7 @@ export async function handshake( url: URL, headers: Headers, bufReader: BufReader, - bufWriter: BufWriter + bufWriter: BufWriter, ): Promise<void> { const { hostname, pathname, search } = url; const key = createSecKey(); @@ -494,7 +495,7 @@ export async function handshake( if (version !== "HTTP/1.1" || statusCode !== "101") { throw new Error( `ws: server didn't accept handshake: ` + - `version=${version}, statusCode=${statusCode}` + `version=${version}, statusCode=${statusCode}`, ); } @@ -508,7 +509,7 @@ export async function handshake( if (secAccept !== expectedSecAccept) { throw new Error( `ws: unexpected sec-websocket-accept header: ` + - `expected=${expectedSecAccept}, actual=${secAccept}` + `expected=${expectedSecAccept}, actual=${secAccept}`, ); } } @@ -519,7 +520,7 @@ export async function handshake( */ export async function connectWebSocket( endpoint: string, - headers: Headers = new Headers() + headers: Headers = new Headers(), ): Promise<WebSocket> { const url = new URL(endpoint); const { hostname } = url; diff --git a/std/ws/test.ts b/std/ws/test.ts index ad6b6256c..87cf549ec 100644 --- a/std/ws/test.ts +++ b/std/ws/test.ts @@ -21,13 +21,13 @@ import { delay } from "../async/delay.ts"; Deno.test("[ws] read unmasked text frame", async () => { // unmasked single text frame with payload "Hello" const buf = new BufReader( - new Deno.Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) + new Deno.Buffer(new Uint8Array([0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])), ); const frame = await readFrame(buf); assertEquals(frame.opcode, OpCode.TextFrame); assertEquals(frame.mask, undefined); const actual = new TextDecoder().decode( - new Deno.Buffer(frame.payload).bytes() + new Deno.Buffer(frame.payload).bytes(), ); assertEquals(actual, "Hello"); assertEquals(frame.isLastFrame, true); @@ -49,14 +49,14 @@ Deno.test("[ws] read masked text frame", async () => { 0x4d, 0x51, 0x58, - ]) - ) + ]), + ), ); const frame = await readFrame(buf); assertEquals(frame.opcode, OpCode.TextFrame); unmask(frame.payload, frame.mask); const actual = new TextDecoder().decode( - new Deno.Buffer(frame.payload).bytes() + new Deno.Buffer(frame.payload).bytes(), ); assertEquals(actual, "Hello"); assertEquals(frame.isLastFrame, true); @@ -64,10 +64,10 @@ Deno.test("[ws] read masked text frame", async () => { Deno.test("[ws] read unmasked split text frames", async () => { const buf1 = new BufReader( - new Deno.Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])) + new Deno.Buffer(new Uint8Array([0x01, 0x03, 0x48, 0x65, 0x6c])), ); const buf2 = new BufReader( - new Deno.Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f])) + new Deno.Buffer(new Uint8Array([0x80, 0x02, 0x6c, 0x6f])), ); const [f1, f2] = await Promise.all([readFrame(buf1), readFrame(buf2)]); assertEquals(f1.isLastFrame, false); @@ -86,15 +86,15 @@ Deno.test("[ws] read unmasked split text frames", async () => { Deno.test("[ws] read unmasked ping / pong frame", async () => { // unmasked ping with payload "Hello" const buf = new BufReader( - new Deno.Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])) + new Deno.Buffer(new Uint8Array([0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f])), ); const ping = await readFrame(buf); assertEquals(ping.opcode, OpCode.Ping); const actual1 = new TextDecoder().decode( - new Deno.Buffer(ping.payload).bytes() + new Deno.Buffer(ping.payload).bytes(), ); assertEquals(actual1, "Hello"); - // prettier-ignore + // deno-fmt-ignore const pongFrame= [0x8a, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58] const buf2 = new BufReader(new Deno.Buffer(new Uint8Array(pongFrame))); const pong = await readFrame(buf2); @@ -102,7 +102,7 @@ Deno.test("[ws] read unmasked ping / pong frame", async () => { assert(pong.mask !== undefined); unmask(pong.payload, pong.mask); const actual2 = new TextDecoder().decode( - new Deno.Buffer(pong.payload).bytes() + new Deno.Buffer(pong.payload).bytes(), ); assertEquals(actual2, "Hello"); }); @@ -163,7 +163,7 @@ Deno.test("[ws] acceptable", () => { ["sec-websocket-version", "13"], ["upgrade", "WebSocket"], ]), - }) + }), ); }); @@ -172,25 +172,25 @@ Deno.test("[ws] acceptable should return false when headers invalid", () => { acceptable({ headers: new Headers({ "sec-websocket-key": "aaa" }), }), - false + false, ); assertEquals( acceptable({ headers: new Headers({ upgrade: "websocket" }), }), - false + false, ); assertEquals( acceptable({ headers: new Headers({ upgrade: "invalid", "sec-websocket-key": "aaa" }), }), - false + false, ); assertEquals( acceptable({ headers: new Headers({ upgrade: "websocket", "sec-websocket-ky": "" }), }), - false + false, ); }); @@ -200,9 +200,9 @@ Deno.test( await assertThrowsAsync( async (): Promise<void> => { await connectWebSocket("file://hoge/hoge"); - } + }, ); - } + }, ); Deno.test("[ws] write and read masked frame", async () => { @@ -217,7 +217,7 @@ Deno.test("[ws] write and read masked frame", async () => { opcode: OpCode.TextFrame, payload: encode(msg), }, - buf + buf, ); const frame = await readFrame(r); assertEquals(frame.opcode, OpCode.TextFrame); @@ -237,9 +237,9 @@ Deno.test("[ws] handshake should not send search when it's empty", async () => { new URL("ws://example.com"), new Headers(), new BufReader(reader), - new BufWriter(writer) + new BufWriter(writer), ); - } + }, ); const tpReader = new TextProtoReader(new BufReader(writer)); @@ -260,16 +260,16 @@ Deno.test( new URL("ws://example.com?a=1"), new Headers(), new BufReader(reader), - new BufWriter(writer) + new BufWriter(writer), ); - } + }, ); const tpReader = new TextProtoReader(new BufReader(writer)); const statusLine = await tpReader.readLine(); assertEquals(statusLine, "GET /?a=1 HTTP/1.1"); - } + }, ); Deno.test("[ws] ws.close() should use 1000 as close code", async () => { @@ -356,11 +356,11 @@ Deno.test( sock.closeForce(); await assertThrowsAsync( () => sock.send("hello"), - Deno.errors.ConnectionReset + Deno.errors.ConnectionReset, ); await assertThrowsAsync(() => sock.ping(), Deno.errors.ConnectionReset); await assertThrowsAsync(() => sock.close(0), Deno.errors.ConnectionReset); - } + }, ); Deno.test( @@ -378,7 +378,7 @@ Deno.test( const { value, done } = await it.next(); assertEquals(value, undefined); assertEquals(done, true); - } + }, ); Deno.test({ diff --git a/test_plugin/tests/test.js b/test_plugin/tests/test.js index d48394b4b..2c1913f92 100644 --- a/test_plugin/tests/test.js +++ b/test_plugin/tests/test.js @@ -11,7 +11,9 @@ if (Deno.build.os === "darwin") { filenameSuffix = ".dylib"; } -const filename = `../target/${Deno.args[0]}/${filenamePrefix}${filenameBase}${filenameSuffix}`; +const filename = `../target/${ + Deno.args[0] +}/${filenamePrefix}${filenameBase}${filenameSuffix}`; // This will be checked against open resources after Plugin.close() // in runTestClose() below. @@ -34,7 +36,7 @@ function runTestSync() { testSync, new Uint8Array([116, 101, 115, 116]), new Uint8Array([49, 50, 51]), - new Uint8Array([99, 98, 97]) + new Uint8Array([99, 98, 97]), ); console.log(`Plugin Sync Response: ${textDecoder.decode(response)}`); @@ -48,7 +50,7 @@ function runTestAsync() { const response = Deno.core.dispatch( testAsync, new Uint8Array([116, 101, 115, 116]), - new Uint8Array([49, 50, 51]) + new Uint8Array([49, 50, 51]), ); if (response != null || response != undefined) { @@ -84,7 +86,7 @@ function runTestPluginClose() { throw new Error( `Difference in open resources before openPlugin and after Plugin.close(): Before: ${preStr} -After: ${postStr}` +After: ${postStr}`, ); } } diff --git a/third_party b/third_party -Subproject 9ad53352a9bc7cd179d9e06663a097352514d38 +Subproject c886054af3b475d530d6bb2e04519a4cd85bf82 diff --git a/tools/README.md b/tools/README.md index cec1e39e8..5f3a8c476 100644 --- a/tools/README.md +++ b/tools/README.md @@ -4,8 +4,8 @@ Documentation for various tooling in support of Deno development ## format.py -This script will format the code (currently using prettier, yapf and rustfmt). -It is a prerequisite to run this before code check in. +This script will format the code (currently using dprint, yapf and rustfmt). It +is a prerequisite to run this before code check in. To run formatting: diff --git a/tools/deno_tcp.ts b/tools/deno_tcp.ts index 06907db90..898869768 100644 --- a/tools/deno_tcp.ts +++ b/tools/deno_tcp.ts @@ -6,7 +6,7 @@ const addr = Deno.args[0] || "127.0.0.1:4500"; const [hostname, port] = addr.split(":"); const listener = Deno.listen({ hostname, port: Number(port) }); const response = new TextEncoder().encode( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n", ); async function handle(conn: Deno.Conn): Promise<void> { const buffer = new Uint8Array(1024); diff --git a/tools/format.py b/tools/format.py index 2f3faf0dd..4ff17af43 100755 --- a/tools/format.py +++ b/tools/format.py @@ -3,7 +3,7 @@ import os import sys import argparse -from third_party import python_env +from third_party import python_env, get_prebuilt_tool_path from util import git_ls_files, git_staged, third_party_path, root_path from util import print_command, run @@ -17,7 +17,7 @@ def get_cmd_args(): return cmd_args parser = argparse.ArgumentParser() - parser.add_argument("--js", help="run prettier", action="store_true") + parser.add_argument("--js", help="run dprint", action="store_true") parser.add_argument("--py", help="run yapf", action="store_true") parser.add_argument("--rs", help="run rustfmt", action="store_true") parser.add_argument( @@ -38,7 +38,7 @@ def main(): did_fmt = False if args.js: - prettier() + dprint() did_fmt = True if args.py: yapf() @@ -48,24 +48,15 @@ def main(): did_fmt = True if not did_fmt: - prettier() + dprint() yapf() rustfmt() -def prettier(): - script = os.path.join(third_party_path, "node_modules", "prettier", - "bin-prettier.js") - source_files = get_sources(root_path, ["*.js", "*.json", "*.ts", "*.md"]) - if source_files: - max_command_length = 24000 - while len(source_files) > 0: - command = ["node", script, "--write", "--loglevel=error", "--"] - while len(source_files) > 0: - command.append(source_files.pop()) - if len(" ".join(command)) > max_command_length: - break - run(command, shell=False, quiet=True) +def dprint(): + executable_path = get_prebuilt_tool_path("dprint") + command = [executable_path, "fmt"] + run(command, shell=False, quiet=True) def yapf(): diff --git a/tools/node_tcp.js b/tools/node_tcp.js index 7c6147dbf..22e2a5161 100644 --- a/tools/node_tcp.js +++ b/tools/node_tcp.js @@ -5,7 +5,7 @@ const port = process.argv[2] || "4544"; console.log("port", port); const response = Buffer.from( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n", ); Server((socket) => { diff --git a/tools/node_tcp_promise.js b/tools/node_tcp_promise.js index c59a9a7b4..36709d2b9 100644 --- a/tools/node_tcp_promise.js +++ b/tools/node_tcp_promise.js @@ -5,7 +5,7 @@ const port = process.argv[2] || "4544"; console.log("port", port); const response = Buffer.from( - "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n", ); function write(socket, buffer) { diff --git a/tools/node_tcp_proxy.js b/tools/node_tcp_proxy.js index 304ed0407..d693dc5c8 100644 --- a/tools/node_tcp_proxy.js +++ b/tools/node_tcp_proxy.js @@ -64,5 +64,5 @@ console.log( "redirecting connections from 127.0.0.1:%d to %s:%d", localport, remotehost, - remoteport + remoteport, ); diff --git a/tools/package.json b/tools/package.json index 56e056b6a..bd619fa56 100644 --- a/tools/package.json +++ b/tools/package.json @@ -2,13 +2,11 @@ "name": "deno", "private": true, "devDependencies": { - "@types/prettier": "1.16.1", "@typescript-eslint/eslint-plugin": "2.5.0", "@typescript-eslint/parser": "2.5.0", "eslint": "5.15.1", "eslint-config-prettier": "4.1.0", "magic-string": "0.25.2", - "prettier": "1.17.1", "typescript": "3.6.3" } } |