From c03b1fe6e996373d60036d20328715527646d861 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 12 Nov 2024 13:56:37 +0100 Subject: [PATCH] make work with dnt --- command/upgrade/_check_version.ts | 5 +- command/upgrade/get_runtime.ts | 2 +- command/upgrade/runtime/bun_runtime.ts | 11 +-- command/upgrade/spinner.ts | 4 +- flags/flags.ts | 78 ++++++++-------- flags/types.ts | 10 +- internal/runtime/delete_env.ts | 2 +- internal/runtime/exit.ts | 2 +- internal/runtime/get_args.ts | 2 +- internal/runtime/get_columns.ts | 2 +- internal/runtime/get_env.ts | 2 +- internal/runtime/get_os.ts | 2 +- internal/runtime/inspect.ts | 10 +- internal/runtime/is_terminal.ts | 2 +- internal/runtime/no_color.ts | 7 +- internal/runtime/read.ts | 2 +- internal/runtime/read_dir.ts | 8 +- internal/runtime/read_sync.ts | 4 +- internal/runtime/set_env.ts | 2 +- internal/runtime/set_raw.ts | 4 +- internal/runtime/stat.ts | 2 +- internal/runtime/write_sync.ts | 2 +- prompt/_generic_prompt.ts | 85 ++++++++--------- prompt/_generic_suggestions.ts | 115 +++++++++++------------ prompt/_utils.ts | 11 ++- prompt/checkbox.ts | 121 +++++++++++++------------ prompt/select.ts | 51 ++++++----- 27 files changed, 276 insertions(+), 272 deletions(-) diff --git a/command/upgrade/_check_version.ts b/command/upgrade/_check_version.ts index 4d4934d0..b7d3a0cf 100644 --- a/command/upgrade/_check_version.ts +++ b/command/upgrade/_check_version.ts @@ -2,7 +2,7 @@ import { bold, yellow } from "@std/fmt/colors"; import { Command } from "../command.ts"; /** Check if new version is available and add hint to version. */ -// deno-lint-ignore no-explicit-any +// dnt-shim-ignore deno-lint-ignore no-explicit-any export async function checkVersion(cmd: Command): Promise { const mainCommand = cmd.getMainCommand(); const upgradeCommand = mainCommand.getCommand("upgrade"); @@ -16,8 +16,7 @@ export async function checkVersion(cmd: Command): Promise { if (!currentVersion || currentVersion === latestVersion) { return; } - const versionHelpText = - `(New version available: ${latestVersion}. Run '${mainCommand.getName()} upgrade' to upgrade to the latest version!)`; + const versionHelpText = `(New version available: ${latestVersion}. Run '${mainCommand.getName()} upgrade' to upgrade to the latest version!)`; mainCommand.version(`${currentVersion} ${bold(yellow(versionHelpText))}`); } diff --git a/command/upgrade/get_runtime.ts b/command/upgrade/get_runtime.ts index 31cd925b..5fa1d250 100644 --- a/command/upgrade/get_runtime.ts +++ b/command/upgrade/get_runtime.ts @@ -9,7 +9,7 @@ export interface GetRuntimeResult { /** Get runtime handler for current runtime. */ export async function getRuntime(): Promise { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno?.version?.deno) { diff --git a/command/upgrade/runtime/bun_runtime.ts b/command/upgrade/runtime/bun_runtime.ts index 3160476b..de1d993b 100644 --- a/command/upgrade/runtime/bun_runtime.ts +++ b/command/upgrade/runtime/bun_runtime.ts @@ -6,21 +6,18 @@ export class BunRuntime extends NodeRuntime { protected override async execute( cmdArgs: string[], isJsr: boolean, - logger?: Logger, + logger?: Logger ): Promise { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const Bun = (globalThis as any).Bun; - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const process = (globalThis as any).process; cmdArgs = isJsr ? [`${process.execPath}x`, "jsr", ...cmdArgs] : [process.execPath, ...cmdArgs]; - logger?.log( - dim("$ %s"), - cmdArgs.join(" "), - ); + logger?.log(dim("$ %s"), cmdArgs.join(" ")); const proc = Bun.spawn(cmdArgs, { stdout: "pipe", stderr: "pipe" }); await proc.exited; diff --git a/command/upgrade/spinner.ts b/command/upgrade/spinner.ts index a80aa928..12353256 100644 --- a/command/upgrade/spinner.ts +++ b/command/upgrade/spinner.ts @@ -197,7 +197,7 @@ export class Spinner { * ``` */ start() { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any if (this.#active || (globalThis as any).Deno?.stdout.writable.locked) { return; } @@ -212,7 +212,7 @@ export class Spinner { const frame = encoder.encode( noColor ? this.#spinner[i] + " " + this.message - : color + this.#spinner[i] + COLOR_RESET + " " + this.message, + : color + this.#spinner[i] + COLOR_RESET + " " + this.message ); // call writeSync once to reduce flickering const writeData = new Uint8Array(LINE_CLEAR.length + frame.length); diff --git a/flags/flags.ts b/flags/flags.ts index a7f16a80..4739d8ee 100644 --- a/flags/flags.ts +++ b/flags/flags.ts @@ -74,10 +74,10 @@ const DefaultTypes: Record = { export function parseFlags< TFlags extends Record, TFlagOptions extends FlagOptions, - TFlagsResult extends ParseFlagsContext, + TFlagsResult extends ParseFlagsContext >( argsOrCtx: string[] | TFlagsResult, - opts: ParseFlagsOptions = {}, + opts: ParseFlagsOptions = {} ): TFlagsResult & ParseFlagsContext { let args: Array; let ctx: ParseFlagsContext>; @@ -113,7 +113,7 @@ export function parseFlags< } function validateOptions( - opts: ParseFlagsOptions, + opts: ParseFlagsOptions ) { opts.flags?.forEach((opt) => { opt.depends?.forEach((flag) => { @@ -132,17 +132,13 @@ function validateOptions( function parseArgs( ctx: ParseFlagsContext>, args: Array, - opts: ParseFlagsOptions, + opts: ParseFlagsOptions ): Map { /** Option name mapping: propertyName -> option.name */ const optionsMap: Map = new Map(); let inLiteral = false; - for ( - let argsIndex = 0; - argsIndex < args.length; - argsIndex++ - ) { + for (let argsIndex = 0; argsIndex < args.length; argsIndex++) { let option: FlagOptions | undefined; let current: string = args[argsIndex]; let currentValue: string | undefined; @@ -233,17 +229,20 @@ function parseArgs( } if (option.type && !option.args?.length) { - option.args = [{ - type: option.type, - optional: option.optionalValue, - variadic: option.variadic, - list: option.list, - separator: option.separator, - }]; + option.args = [ + { + type: option.type, + optional: option.optionalValue, + variadic: option.variadic, + list: option.list, + separator: option.separator, + }, + ]; } if ( - opts.flags?.length && !option.args?.length && + opts.flags?.length && + !option.args?.length && typeof currentValue !== "undefined" ) { throw new UnexpectedOptionValueError(option.name, currentValue); @@ -273,9 +272,12 @@ function parseArgs( const value = option.value(ctx.flags[propName], previous); setFlagValue(value); } else if (option.collect) { - const value: unknown[] = typeof previous !== "undefined" - ? (Array.isArray(previous) ? previous : [previous]) - : []; + const value: unknown[] = + typeof previous !== "undefined" + ? Array.isArray(previous) + ? previous + : [previous] + : []; value.push(ctx.flags[propName]); setFlagValue(value); @@ -333,7 +335,7 @@ function parseArgs( throw new InvalidOptionValueError( option.name, arg.type ?? "?", - nextValue, + nextValue ); } return value; @@ -393,15 +395,19 @@ function parseArgs( } // require optional values to be called with an equal sign: foo=bar if ( - option.equalsSign && arg.optional && !arg.variadic && + option.equalsSign && + arg.optional && + !arg.variadic && typeof currentValue === "undefined" ) { return false; } if (arg.optional || arg.variadic) { - return nextValue[0] !== "-" || + return ( + nextValue[0] !== "-" || typeof currentValue !== "undefined" || - (arg.type === OptionType.NUMBER && !isNaN(Number(nextValue))); + (arg.type === OptionType.NUMBER && !isNaN(Number(nextValue))) + ); } return false; @@ -411,15 +417,15 @@ function parseArgs( function parseValue( option: FlagOptions, arg: ArgumentOptions, - value: string, + value: string ): unknown { const result: unknown = opts.parse ? opts.parse({ - label: "Option", - type: arg.type || OptionType.STRING, - name: `--${option.name}`, - value, - }) + label: "Option", + type: arg.type || OptionType.STRING, + name: `--${option.name}`, + value, + }) : parseDefaultType(option, arg, value); if (typeof result !== "undefined") { @@ -449,11 +455,11 @@ function parseDottedOptions(ctx: ParseFlagsContext): void { if (~key.indexOf(".")) { key.split(".").reduce( ( - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any result: Record, subKey: string, index: number, - parts: string[], + parts: string[] ) => { if (index === parts.length - 1) { result[subKey] = ctx.flags[key]; @@ -462,14 +468,14 @@ function parseDottedOptions(ctx: ParseFlagsContext): void { } return result[subKey]; }, - result, + result ); } else { result[key] = ctx.flags[key]; } return result; }, - {}, + {} ); } @@ -498,9 +504,9 @@ function splitFlags(flag: string): Array { function parseDefaultType( option: FlagOptions, arg: ArgumentOptions, - value: string, + value: string ): unknown { - const type: ArgumentType = arg.type as ArgumentType || OptionType.STRING; + const type: ArgumentType = (arg.type as ArgumentType) || OptionType.STRING; const parseType = DefaultTypes[type]; if (!parseType) { diff --git a/flags/types.ts b/flags/types.ts index 36082d98..0b4dac9a 100644 --- a/flags/types.ts +++ b/flags/types.ts @@ -1,6 +1,6 @@ /** Parser options. */ export interface ParseFlagsOptions< - TFlagOptions extends FlagOptions = FlagOptions, + TFlagOptions extends FlagOptions = FlagOptions > { /** An array of flag options. */ flags?: Array; @@ -107,10 +107,10 @@ export type DefaultValue = export type DefaultValueHandler = () => TValue; /** A callback method for custom processing or mapping of flag values. */ -// deno-lint-ignore no-explicit-any +// dnt-shim-ignore deno-lint-ignore no-explicit-any export type ValueHandler = ( val: TValue, - previous?: TReturn, + previous?: TReturn ) => TReturn; /** @@ -118,9 +118,9 @@ export type ValueHandler = ( * and can be also passed as first argument to the `parseFlags` method. */ export interface ParseFlagsContext< - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any TFlags extends Record = Record, - TStandaloneOption extends FlagOptions = FlagOptions, + TStandaloneOption extends FlagOptions = FlagOptions > { /** An object of parsed flags. */ flags: TFlags; diff --git a/internal/runtime/delete_env.ts b/internal/runtime/delete_env.ts index b5165154..7d1deb0f 100644 --- a/internal/runtime/delete_env.ts +++ b/internal/runtime/delete_env.ts @@ -5,7 +5,7 @@ * @param name The name of the environment variable. */ export function deleteEnv(name: string): string | undefined { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/exit.ts b/internal/runtime/exit.ts index ed5e8579..fb34258f 100644 --- a/internal/runtime/exit.ts +++ b/internal/runtime/exit.ts @@ -5,7 +5,7 @@ * @param code The exit code. */ export function exit(code: number): never { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; const exit: (code: number) => never = Deno?.exit ?? process?.exit; diff --git a/internal/runtime/get_args.ts b/internal/runtime/get_args.ts index 6f81d7ab..460df100 100644 --- a/internal/runtime/get_args.ts +++ b/internal/runtime/get_args.ts @@ -4,7 +4,7 @@ * @internal */ export function getArgs(): Array { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; return Deno?.args ?? process?.argv.slice(2) ?? []; diff --git a/internal/runtime/get_columns.ts b/internal/runtime/get_columns.ts index ad9c15f6..0dd48b4c 100644 --- a/internal/runtime/get_columns.ts +++ b/internal/runtime/get_columns.ts @@ -5,7 +5,7 @@ */ export function getColumns(): number | null { try { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; // Catch error in none tty mode: Inappropriate ioctl for device (os error 25) diff --git a/internal/runtime/get_env.ts b/internal/runtime/get_env.ts index 03af34e1..53dbc3f4 100644 --- a/internal/runtime/get_env.ts +++ b/internal/runtime/get_env.ts @@ -5,7 +5,7 @@ * @param name The name of the environment variable. */ export function getEnv(name: string): string | undefined { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/get_os.ts b/internal/runtime/get_os.ts index d2481fbf..1d6676ee 100644 --- a/internal/runtime/get_os.ts +++ b/internal/runtime/get_os.ts @@ -16,7 +16,7 @@ export function getOs(): | "openbsd" | "sunos" | "win32" { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/inspect.ts b/internal/runtime/inspect.ts index ea9996d7..4ef33174 100644 --- a/internal/runtime/inspect.ts +++ b/internal/runtime/inspect.ts @@ -4,11 +4,11 @@ * @internal */ export function inspect(value: unknown, colors: boolean): string { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno } = globalThis as any; - return Deno?.inspect( - value, - { depth: 1, colors, trailingComma: false }, - ) ?? JSON.stringify(value, null, 2); + return ( + Deno?.inspect(value, { depth: 1, colors, trailingComma: false }) ?? + JSON.stringify(value, null, 2) + ); } diff --git a/internal/runtime/is_terminal.ts b/internal/runtime/is_terminal.ts index db4981be..176e3eac 100644 --- a/internal/runtime/is_terminal.ts +++ b/internal/runtime/is_terminal.ts @@ -4,7 +4,7 @@ * @internal */ export function isTerminal(): boolean { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/no_color.ts b/internal/runtime/no_color.ts index bb860138..ca227550 100644 --- a/internal/runtime/no_color.ts +++ b/internal/runtime/no_color.ts @@ -4,14 +4,15 @@ * @internal */ export function getNoColor(): boolean { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { return Deno.noColor; } else if (process) { - return process?.env.NO_COLOR === "1" || - process?.env.NODE_DISABLE_COLORS === "1"; + return ( + process?.env.NO_COLOR === "1" || process?.env.NODE_DISABLE_COLORS === "1" + ); } throw new Error("unsupported runtime"); diff --git a/internal/runtime/read.ts b/internal/runtime/read.ts index 14bd4b15..c4e61ef9 100644 --- a/internal/runtime/read.ts +++ b/internal/runtime/read.ts @@ -5,7 +5,7 @@ * @param data Uint8Array to store the data. */ export async function read(data: Uint8Array): Promise { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, Bun, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/read_dir.ts b/internal/runtime/read_dir.ts index bb00cf29..066dd9f7 100644 --- a/internal/runtime/read_dir.ts +++ b/internal/runtime/read_dir.ts @@ -5,7 +5,7 @@ * @param path Path to the directory. */ export async function readDir(path: string): Promise> { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno } = globalThis as any; path ||= "."; @@ -20,10 +20,8 @@ export async function readDir(path: string): Promise> { const fs = await import("node:fs"); return new Promise((resolve, reject) => { - fs.readdir( - path, - (err: unknown, files: Array) => - err ? reject(err) : resolve(files.map((name) => ({ name }))), + fs.readdir(path, (err: unknown, files: Array) => + err ? reject(err) : resolve(files.map((name) => ({ name }))) ); }); } diff --git a/internal/runtime/read_sync.ts b/internal/runtime/read_sync.ts index 82aeb92f..cd9976ab 100644 --- a/internal/runtime/read_sync.ts +++ b/internal/runtime/read_sync.ts @@ -1,4 +1,4 @@ -// deno-lint-ignore no-explicit-any +// dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process, Buffer } = globalThis as any; const { readSync: readSyncNode } = process ? await import("node:fs") @@ -19,7 +19,7 @@ export function readSync(data: Uint8Array): number { buffer, 0, buffer.length, - null, + null ); for (let i = 0; i < bytesRead; i++) { diff --git a/internal/runtime/set_env.ts b/internal/runtime/set_env.ts index 1b672aad..6e264b92 100644 --- a/internal/runtime/set_env.ts +++ b/internal/runtime/set_env.ts @@ -6,7 +6,7 @@ * @param value The value of the environment variable. */ export function setEnv(name: string, value: string): void { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/set_raw.ts b/internal/runtime/set_raw.ts index ffd48ffb..dcd14b1a 100644 --- a/internal/runtime/set_raw.ts +++ b/internal/runtime/set_raw.ts @@ -7,9 +7,9 @@ */ export function setRaw( mode: boolean, - { cbreak }: { cbreak?: boolean } = {}, + { cbreak }: { cbreak?: boolean } = {} ): void { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/internal/runtime/stat.ts b/internal/runtime/stat.ts index 2fa60f34..5e6fedd8 100644 --- a/internal/runtime/stat.ts +++ b/internal/runtime/stat.ts @@ -5,7 +5,7 @@ * @param input Path to the file. */ export async function stat(input: string): Promise<{ isDirectory: boolean }> { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno } = globalThis as any; if (Deno) { diff --git a/internal/runtime/write_sync.ts b/internal/runtime/write_sync.ts index 1b5623cd..25e320a8 100644 --- a/internal/runtime/write_sync.ts +++ b/internal/runtime/write_sync.ts @@ -5,7 +5,7 @@ * @param data Data to write to stdout. */ export function writeSync(data: Uint8Array): number { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const { Deno, process } = globalThis as any; if (Deno) { diff --git a/prompt/_generic_prompt.ts b/prompt/_generic_prompt.ts index 4e84631b..5208998e 100644 --- a/prompt/_generic_prompt.ts +++ b/prompt/_generic_prompt.ts @@ -41,17 +41,13 @@ export interface StaticGenericPrompt { prompt(options: TOptions): Promise; } -// deno-lint-ignore no-explicit-any +// dnt-shim-ignore deno-lint-ignore no-explicit-any export type InferPromptOptions> = - Parameters< - TPrompt["getDefaultSettings"] - >[0]; + Parameters[0]; -// deno-lint-ignore no-explicit-any +// dnt-shim-ignore deno-lint-ignore no-explicit-any export type InferPromptValue> = Awaited< - ReturnType< - TPrompt["prompt"] - > + ReturnType >; /** Generic prompt options. */ @@ -112,10 +108,7 @@ export interface GenericPromptKeys { } /** Generic prompt representation. */ -export abstract class GenericPrompt< - TValue, - TRawValue, -> { +export abstract class GenericPrompt { protected static injectedValue: unknown | undefined; protected abstract readonly settings: GenericPromptSettings< TValue, @@ -142,7 +135,7 @@ export abstract class GenericPrompt< } public getDefaultSettings( - options: GenericPromptOptions, + options: GenericPromptOptions ): GenericPromptSettings { return { ...options, @@ -188,7 +181,7 @@ export abstract class GenericPrompt< await this.render(); this.#lastError = undefined; - if (!await this.read()) { + if (!(await this.read())) { return this.#execute(); } @@ -201,7 +194,7 @@ export abstract class GenericPrompt< if (successMessage) { this.settings.writer.writeSync( - this.#encoder.encode(successMessage + "\n"), + this.#encoder.encode(successMessage + "\n") ); } @@ -214,11 +207,7 @@ export abstract class GenericPrompt< /** Render prompt. */ protected async render(): Promise { const result: [string, string | undefined, string | undefined] = - await Promise.all([ - this.message(), - this.body?.(), - this.footer(), - ]); + await Promise.all([this.message(), this.body?.(), this.footer()]); const content: string = result.filter(Boolean).join("\n"); const lines = content.split("\n"); @@ -226,9 +215,9 @@ export abstract class GenericPrompt< const columns = getColumns(); const linesCount: number = columns ? lines.reduce((prev, next) => { - const length = stripAnsiCode(next).length; - return prev + (length > columns ? Math.ceil(length / columns) : 1); - }, 0) + const length = stripAnsiCode(next).length; + return prev + (length > columns ? Math.ceil(length / columns) : 1); + }, 0) : content.split("\n").length; const y: number = linesCount - this.cursor.y - 1; @@ -270,14 +259,18 @@ export abstract class GenericPrompt< } protected message(): string { - return `${this.settings.indent}${this.settings.prefix}` + - bold(this.settings.message) + this.defaults(); + return ( + `${this.settings.indent}${this.settings.prefix}` + + bold(this.settings.message) + + this.defaults() + ); } protected defaults(): string { let defaultMessage = ""; if ( - typeof this.settings.default !== "undefined" && !this.settings.hideDefault + typeof this.settings.default !== "undefined" && + !this.settings.hideDefault ) { defaultMessage += dim(` (${this.format(this.settings.default)})`); } @@ -286,10 +279,15 @@ export abstract class GenericPrompt< /** Get prompt success message. */ protected success(value: TValue): string | undefined { - return `${this.settings.indent}${this.settings.prefix}` + - bold(this.settings.message) + this.defaults() + - " " + this.settings.pointer + - " " + green(this.format(value)); + return ( + `${this.settings.indent}${this.settings.prefix}` + + bold(this.settings.message) + + this.defaults() + + " " + + this.settings.pointer + + " " + + green(this.format(value)) + ); } protected body?(): string | undefined | Promise; @@ -307,7 +305,7 @@ export abstract class GenericPrompt< protected hint(): string | undefined { return this.settings.hint ? this.settings.indent + - italic(brightBlue(dim(`${Figures.POINTER} `) + this.settings.hint)) + italic(brightBlue(dim(`${Figures.POINTER} `) + this.settings.hint)) : undefined; } @@ -368,10 +366,7 @@ export abstract class GenericPrompt< const isTty = this.settings.reader.isTerminal(); if (isTty) { - this.settings.reader.setRaw( - true, - { cbreak: this.settings.cbreak }, - ); + this.settings.reader.setRaw(true, { cbreak: this.settings.cbreak }); } const nread: number | null = await this.settings.reader.read(buffer); @@ -417,10 +412,9 @@ export abstract class GenericPrompt< this.#value = undefined; this.#lastError = undefined; - const validation = - await (this.settings.validate - ? this.settings.validate(value) - : this.validate(value)); + const validation = await (this.settings.validate + ? this.settings.validate(value) + : this.validate(value)); if (validation === false) { this.#lastError = `Invalid answer.`; @@ -440,15 +434,16 @@ export abstract class GenericPrompt< protected isKey( keys: TKey | undefined, name: TName, - event: KeyCode, + event: KeyCode ): boolean { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const keyNames: Array | undefined = keys?.[name] as any; - return typeof keyNames !== "undefined" && ( - (typeof event.name !== "undefined" && + return ( + typeof keyNames !== "undefined" && + ((typeof event.name !== "undefined" && keyNames.indexOf(event.name) !== -1) || - (typeof event.sequence !== "undefined" && - keyNames.indexOf(event.sequence) !== -1) + (typeof event.sequence !== "undefined" && + keyNames.indexOf(event.sequence) !== -1)) ); } } diff --git a/prompt/_generic_suggestions.ts b/prompt/_generic_suggestions.ts index b3dae0f9..9a25b59a 100644 --- a/prompt/_generic_suggestions.ts +++ b/prompt/_generic_suggestions.ts @@ -82,13 +82,13 @@ export interface GenericSuggestionsKeys extends GenericInputKeys { /** Auto-suggestions handler. */ export type SuggestionHandler = ( - input: string, + input: string ) => Array | Promise>; /** Auto-suggestions complete handler. */ export type CompleteHandler = ( input: string, - suggestion?: string, + suggestion?: string ) => Promise | string; interface LocalStorage { @@ -100,8 +100,10 @@ interface LocalStorage { const sep = getOs() === "windows" ? "\\" : "/"; /** Generic input prompt representation. */ -export abstract class GenericSuggestions - extends GenericInput { +export abstract class GenericSuggestions< + TValue, + TRawValue +> extends GenericInput { // @ts-ignore ignore jsr publish error protected abstract override readonly settings: GenericSuggestionsSettings< TValue, @@ -114,7 +116,7 @@ export abstract class GenericSuggestions #hasReadPermissions?: boolean; public override getDefaultSettings( - options: GenericSuggestionsOptions, + options: GenericSuggestionsOptions ): GenericSuggestionsSettings { const settings = super.getDefaultSettings(options); return { @@ -136,7 +138,7 @@ export abstract class GenericSuggestions // Keep support for deno < 1.10. if (this.settings.id && "localStorage" in window) { try { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any return (window as any).localStorage; } catch (_) { // Ignore error if --location is not set. @@ -161,17 +163,16 @@ export abstract class GenericSuggestions if (this.settings.id) { this.localStorage?.setItem( this.settings.id, - JSON.stringify([ - ...suggestions, - ...this.loadSuggestions(), - ].filter(uniqueSuggestions)), + JSON.stringify( + [...suggestions, ...this.loadSuggestions()].filter(uniqueSuggestions) + ) ); } } protected override async render(): Promise { if (this.settings.files && this.#hasReadPermissions === undefined) { - // deno-lint-ignore no-explicit-any + // dnt-shim-ignore deno-lint-ignore no-explicit-any const status = await (globalThis as any).Deno?.permissions.request({ name: "read", }); @@ -189,14 +190,14 @@ export abstract class GenericSuggestions this.suggestions = await this.getSuggestions(); this.suggestionsIndex = Math.max( this.getCurrentInputValue().trim().length === 0 ? -1 : 0, - Math.min(this.suggestions.length - 1, this.suggestionsIndex), + Math.min(this.suggestions.length - 1, this.suggestionsIndex) ); this.suggestionsOffset = Math.max( 0, Math.min( this.suggestions.length - this.getListHeight(), - this.suggestionsOffset, - ), + this.suggestionsOffset + ) ); } @@ -205,14 +206,15 @@ export abstract class GenericSuggestions } protected getSuggestion(): string { - return this.suggestions[this.suggestionsIndex]?.toString() - .substr( - this.getCurrentInputValue().length, - ) ?? ""; + return ( + this.suggestions[this.suggestionsIndex] + ?.toString() + .substr(this.getCurrentInputValue().length) ?? "" + ); } protected async getUserSuggestions( - input: string, + input: string ): Promise> { return typeof this.settings.suggestions === "function" ? await this.settings.suggestions(input) @@ -224,14 +226,14 @@ export abstract class GenericSuggestions } protected async getFileSuggestions( - input: string, + input: string ): Promise> { if (!this.#isFileModeEnabled()) { return []; } const path = await stat(input) - .then((file) => file.isDirectory ? input : dirname(input)) + .then((file) => (file.isDirectory ? input : dirname(input))) .catch(() => dirname(input)); return await listDir(path, this.settings.files); @@ -241,8 +243,8 @@ export abstract class GenericSuggestions const input = this.getCurrentInputValue(); const suggestions = [ ...this.loadSuggestions(), - ...await this.getUserSuggestions(input), - ...await this.getFileSuggestions(input), + ...(await this.getUserSuggestions(input)), + ...(await this.getFileSuggestions(input)), ].filter(uniqueSuggestions); if (!input.length) { @@ -255,9 +257,10 @@ export abstract class GenericSuggestions .toLowerCase() .startsWith(input.toLowerCase()) ) - .sort((a: string | number, b: string | number) => - levenshteinDistance((a || a).toString(), input) - - levenshteinDistance((b || b).toString(), input) + .sort( + (a: string | number, b: string | number) => + levenshteinDistance((a || a).toString(), input) - + levenshteinDistance((b || b).toString(), input) ); } @@ -282,21 +285,23 @@ export abstract class GenericSuggestions [ "Previous Page", getFiguresByKeys(this.settings.keys?.previousPage ?? []), - ], + ] ); } else { actions.push( ["Next", getFiguresByKeys(this.settings.keys?.next ?? [])], - ["Previous", getFiguresByKeys(this.settings.keys?.previous ?? [])], + ["Previous", getFiguresByKeys(this.settings.keys?.previous ?? [])] ); } - actions.push( - ["Complete", getFiguresByKeys(this.settings.keys?.complete ?? [])], - ); + actions.push([ + "Complete", + getFiguresByKeys(this.settings.keys?.complete ?? []), + ]); } - actions.push( - ["Submit", getFiguresByKeys(this.settings.keys?.submit ?? [])], - ); + actions.push([ + "Submit", + getFiguresByKeys(this.settings.keys?.submit ?? []), + ]); let info = this.settings.indent; if (this.suggestions.length) { @@ -321,10 +326,7 @@ export abstract class GenericSuggestions i++ ) { list.push( - this.getListItem( - this.suggestions[i], - this.suggestionsIndex === i, - ), + this.getListItem(this.suggestions[i], this.suggestionsIndex === i) ); } if (list.length && this.settings.info) { @@ -338,10 +340,7 @@ export abstract class GenericSuggestions * @param value Option. * @param isSelected Set to true if option is selected. */ - protected getListItem( - value: string | number, - isSelected?: boolean, - ): string { + protected getListItem(value: string | number, isSelected?: boolean): string { let line = this.settings.indent ?? ""; line += isSelected ? `${this.settings.listPointer} ` : " "; if (isSelected) { @@ -354,11 +353,11 @@ export abstract class GenericSuggestions /** Get suggestions row height. */ protected getListHeight( - suggestions: Array = this.suggestions, + suggestions: Array = this.suggestions ): number { return Math.min( suggestions.length, - this.settings.maxRows || suggestions.length, + this.settings.maxRows || suggestions.length ); } @@ -436,19 +435,17 @@ export abstract class GenericSuggestions protected async complete(): Promise { let input: string = this.getCurrentInputValue(); - const suggestion: string | undefined = this - .suggestions[this.suggestionsIndex]?.toString(); + const suggestion: string | undefined = + this.suggestions[this.suggestionsIndex]?.toString(); if (this.settings.complete) { input = await this.settings.complete(input, suggestion); } else if ( this.#isFileModeEnabled() && input.at(-1) !== sep && - await isDirectory(input) && - ( - this.getCurrentInputValue().at(-1) !== "." || - this.getCurrentInputValue().endsWith("..") - ) + (await isDirectory(input)) && + (this.getCurrentInputValue().at(-1) !== "." || + this.getCurrentInputValue().endsWith("..")) ) { input += sep; } else if (suggestion) { @@ -477,7 +474,7 @@ export abstract class GenericSuggestions this.suggestionsIndex++; if ( this.suggestionsIndex >= - this.suggestionsOffset + this.getListHeight() + this.suggestionsOffset + this.getListHeight() ) { this.suggestionsOffset++; } @@ -556,21 +553,25 @@ export abstract class GenericSuggestions function uniqueSuggestions( value: unknown, index: number, - self: Array, + self: Array ) { - return typeof value !== "undefined" && value !== "" && - self.indexOf(value) === index; + return ( + typeof value !== "undefined" && + value !== "" && + self.indexOf(value) === index + ); } async function listDir( path: string, - mode?: boolean | RegExp, + mode?: boolean | RegExp ): Promise> { const fileNames: string[] = []; for (const file of await readDir(path)) { if ( - mode === true && (file.name.startsWith(".") || file.name.endsWith("~")) + mode === true && + (file.name.startsWith(".") || file.name.endsWith("~")) ) { continue; } diff --git a/prompt/_utils.ts b/prompt/_utils.ts index c54f7f8d..5e037add 100644 --- a/prompt/_utils.ts +++ b/prompt/_utils.ts @@ -1,10 +1,13 @@ /** Alias method for Number constructor. */ -// deno-lint-ignore no-explicit-any +// dnt-shim-ignore deno-lint-ignore no-explicit-any export function parseNumber(value: any): number { return Number(value); } -export type WidenType = T extends string ? string - : T extends number ? number - : T extends boolean ? boolean +export type WidenType = T extends string + ? string + : T extends number + ? number + : T extends boolean + ? boolean : T; diff --git a/prompt/checkbox.ts b/prompt/checkbox.ts index 90ed0c27..d2b89724 100644 --- a/prompt/checkbox.ts +++ b/prompt/checkbox.ts @@ -46,8 +46,8 @@ export interface CheckboxOptions } /** Checkbox prompt settings. */ -interface CheckboxSettings extends - GenericListSettings< +interface CheckboxSettings + extends GenericListSettings< TValue, Array, Array, @@ -87,8 +87,10 @@ export interface CheckboxOptionSettings /** Checkbox option group settings. */ export interface CheckboxOptionGroupSettings - extends - GenericListOptionGroupSettings> { + extends GenericListOptionGroupSettings< + TValue, + CheckboxOptionSettings + > { readonly checked: boolean; icon: boolean; } @@ -187,7 +189,7 @@ export class Checkbox extends GenericList< * @param options Checkbox options. */ public static prompt( - options: CheckboxOptions, + options: CheckboxOptions ): Promise>> { return new this(options).prompt() as Promise>>; } @@ -218,7 +220,7 @@ export class Checkbox extends GenericList< } public override getDefaultSettings( - options: CheckboxOptions, + options: CheckboxOptions ): CheckboxSettings { const settings = super.getDefaultSettings(options); return { @@ -249,16 +251,13 @@ export class Checkbox extends GenericList< | CheckboxOption | CheckboxOptionGroup | GenericListSeparatorOption - >, + > ): Array< CheckboxOptionSettings | CheckboxOptionGroupSettings > { return options.map((option) => typeof option === "string" || typeof option === "number" - ? this.mapOption( - promptOptions, - { value: option as TValue }, - ) + ? this.mapOption(promptOptions, { value: option as TValue }) : isCheckboxOptionGroup(option) ? this.mapOptionGroup(promptOptions, option) : this.mapOption(promptOptions, option) @@ -267,15 +266,17 @@ export class Checkbox extends GenericList< protected override mapOption( options: CheckboxOptions, - option: CheckboxOption | GenericListSeparatorOption, + option: CheckboxOption | GenericListSeparatorOption ): CheckboxOptionSettings { if (isOption(option)) { return { ...super.mapOption(options, option), - checked: typeof option.checked === "undefined" && options.default && - options.default.indexOf(option.value) !== -1 - ? true - : !!option.checked, + checked: + typeof option.checked === "undefined" && + options.default && + options.default.indexOf(option.value) !== -1 + ? true + : !!option.checked, icon: typeof option.icon === "undefined" ? true : option.icon, }; } else { @@ -289,7 +290,7 @@ export class Checkbox extends GenericList< protected override mapOptionGroup( promptOptions: CheckboxOptions, - option: CheckboxOptionGroup, + option: CheckboxOptionGroup ): CheckboxOptionGroupSettings { const options = this.mapOptions(promptOptions, option.options); return { @@ -310,17 +311,13 @@ export class Checkbox extends GenericList< } protected override getListItemIcon( - option: - | CheckboxOptionSettings - | CheckboxOptionGroupSettings, + option: CheckboxOptionSettings | CheckboxOptionGroupSettings ): string { return this.getCheckboxIcon(option) + super.getListItemIcon(option); } private getCheckboxIcon( - option: - | CheckboxOptionSettings - | CheckboxOptionGroupSettings, + option: CheckboxOptionSettings | CheckboxOptionGroupSettings ): string { if (!option.icon) { return ""; @@ -340,9 +337,7 @@ export class Checkbox extends GenericList< TValue, CheckboxOptionSettings, CheckboxOptionGroupSettings - >( - this.settings.options, - ) + >(this.settings.options) .filter((option) => option.checked) .map((option) => option.value); } @@ -375,23 +370,25 @@ export class Checkbox extends GenericList< protected override hint(): string | undefined { if (this.confirmSubmit) { const info = this.isBackButton(this.selectedOption) - ? ` To leave the current group press ${ - getFiguresByKeys(this.settings.keys.back ?? []).join(", ") - }.` + ? ` To leave the current group press ${getFiguresByKeys( + this.settings.keys.back ?? [] + ).join(", ")}.` : isOptionGroup(this.selectedOption) - ? ` To open the selected group press ${ - getFiguresByKeys(this.settings.keys.open ?? []).join(", ") - }.` - : ` To check or uncheck the selected option press ${ - getFiguresByKeys(this.settings.keys.check ?? []).join(", ") - }.`; - - return this.settings.indent + + ? ` To open the selected group press ${getFiguresByKeys( + this.settings.keys.open ?? [] + ).join(", ")}.` + : ` To check or uncheck the selected option press ${getFiguresByKeys( + this.settings.keys.check ?? [] + ).join(", ")}.`; + + return ( + this.settings.indent + brightBlue( - `Press ${ - getFiguresByKeys(this.settings.keys.submit ?? []) - } again to submit.${info}`, - ); + `Press ${getFiguresByKeys( + this.settings.keys.submit ?? [] + )} again to submit.${info}` + ) + ); } return super.hint(); @@ -427,7 +424,7 @@ export class Checkbox extends GenericList< option: | CheckboxOptionSettings | CheckboxOptionGroupSettings, - checked: boolean, + checked: boolean ) { if (isOption(option)) { option.checked = checked; @@ -458,11 +455,13 @@ export class Checkbox extends GenericList< CheckboxOptionGroupSettings >(this.settings.options); - const isValidValue = Array.isArray(value) && - value.every((val) => - options.findIndex((option: CheckboxOptionSettings) => - equal(option.value, val) - ) !== -1 + const isValidValue = + Array.isArray(value) && + value.every( + (val) => + options.findIndex((option: CheckboxOptionSettings) => + equal(option.value, val) + ) !== -1 ); if (!isValidValue) { @@ -493,17 +492,21 @@ export class Checkbox extends GenericList< * @param value Output value. */ protected format(value: Array): string { - return value.map((val) => - this.settings.format?.(val) ?? this.getOptionByValue(val)?.name ?? - String(val) - ).join(", "); + return value + .map( + (val) => + this.settings.format?.(val) ?? + this.getOptionByValue(val)?.name ?? + String(val) + ) + .join(", "); } } function areSomeChecked( options: Array< CheckboxOptionSettings | CheckboxOptionGroupSettings - >, + > ): boolean { return options.some((option) => isOptionGroup(option) ? areSomeChecked(option.options) : option.checked @@ -513,7 +516,7 @@ function areSomeChecked( function areAllChecked( options: Array< CheckboxOptionSettings | CheckboxOptionGroupSettings - >, + > ): boolean { return options.every((option) => isOptionGroup(option) ? areAllChecked(option.options) : option.checked @@ -523,16 +526,14 @@ function areAllChecked( function flatOptions< TValue, TOption extends GenericListOptionSettings, - TGroup extends GenericListOptionGroupSettings, ->( - options: Array, -): Array { + TGroup extends GenericListOptionGroupSettings +>(options: Array): Array { return flat(options); function flat( options: Array, indentLevel = 0, - opts: Array = [], + opts: Array = [] ): Array { for (const option of options) { option.indentLevel = indentLevel; @@ -549,8 +550,8 @@ function flatOptions< } export function isCheckboxOptionGroup( - option: unknown, - // deno-lint-ignore no-explicit-any + option: unknown + // dnt-shim-ignore deno-lint-ignore no-explicit-any ): option is CheckboxOptionGroup { return isOptionGroup(option); } diff --git a/prompt/select.ts b/prompt/select.ts index 52b2543b..3b80d501 100644 --- a/prompt/select.ts +++ b/prompt/select.ts @@ -33,8 +33,8 @@ export interface SelectOptions } /** Select prompt settings. */ -export interface SelectSettings extends - GenericListSettings< +export interface SelectSettings + extends GenericListSettings< TValue, TValue, TValue, @@ -147,7 +147,7 @@ export class Select extends GenericList< /** Execute the prompt with provided options. */ public static prompt( - options: SelectOptions, + options: SelectOptions ): Promise> { return new this(options).prompt() as Promise>; } @@ -172,7 +172,7 @@ export class Select extends GenericList< } public override getDefaultSettings( - options: SelectOptions, + options: SelectOptions ): SelectSettings { return { ...super.getDefaultSettings(options), @@ -189,16 +189,13 @@ export class Select extends GenericList< | SelectOption | SelectOptionGroup | GenericListSeparatorOption - >, + > ): Array | SelectOptionGroupSettings> { return options.map((option) => isSelectOptionGroup(option) ? this.mapOptionGroup(promptOptions, option) : typeof option === "string" || typeof option === "number" - ? this.mapOption( - promptOptions, - { value: option as TValue }, - ) + ? this.mapOption(promptOptions, { value: option as TValue }) : this.mapOption(promptOptions, option) ); } @@ -213,9 +210,9 @@ export class Select extends GenericList< isOptionGroup(this.selectedOption) ) { const info = isOptionGroup(this.selectedOption) - ? ` To select a group use ${ - getFiguresByKeys(this.settings.keys.open ?? []).join(", ") - }.` + ? ` To select a group use ${getFiguresByKeys( + this.settings.keys.open ?? [] + ).join(", ")}.` : ""; this.setErrorMessage(`No option selected.${info}`); return; @@ -237,9 +234,15 @@ export class Select extends GenericList< * @return True on success, false or error message on error. */ protected validate(value: TValue): boolean | string { - return this.options.findIndex(( - option: SelectOptionSettings | SelectOptionGroupSettings, - ) => isOption(option) && equal(option.value, value)) !== -1; + return ( + this.options.findIndex( + ( + option: + | SelectOptionSettings + | SelectOptionGroupSettings + ) => isOption(option) && equal(option.value, value) + ) !== -1 + ); } /** @@ -256,16 +259,16 @@ export class Select extends GenericList< * @param value Output value. */ protected format(value: TValue): string { - return this.settings.format?.(value) ?? - this.getOptionByValue(value)?.name ?? String(value); + return ( + this.settings.format?.(value) ?? + this.getOptionByValue(value)?.name ?? + String(value) + ); } } -function assertIsOption< - TValue, - TOption extends GenericListOption, ->( - option: TOption | GenericListOptionGroup>, +function assertIsOption>( + option: TOption | GenericListOptionGroup> ): asserts option is TOption { if (!isOption(option)) { throw new Error("Expected an option but got an option group."); @@ -273,8 +276,8 @@ function assertIsOption< } export function isSelectOptionGroup( - option: unknown, - // deno-lint-ignore no-explicit-any + option: unknown + // dnt-shim-ignore deno-lint-ignore no-explicit-any ): option is SelectOptionGroup { return isOptionGroup(option); }