diff --git a/flush.d.ts b/flush.d.ts deleted file mode 100644 index 5ca9b097b..000000000 --- a/flush.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare const flush: () => Promise - -export = flush diff --git a/flush.js b/flush.js deleted file mode 100644 index 080811026..000000000 --- a/flush.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/cli-ux/flush').flush diff --git a/handle.js b/handle.js deleted file mode 100644 index aff2c83fc..000000000 --- a/handle.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = async error => require('./lib/errors/handle').handle(error) diff --git a/package.json b/package.json index 6143b123d..2fd69920c 100644 --- a/package.json +++ b/package.json @@ -66,10 +66,7 @@ "node": ">=18.0.0" }, "files": [ - "/lib", - "/flush.js", - "/flush.d.ts", - "/handle.js" + "/lib" ], "homepage": "https://github.com/oclif/core", "keywords": [ @@ -82,7 +79,26 @@ "argv" ], "license": "MIT", - "main": "./lib/index.js", + "exports": { + ".": "./lib/index.js", + "./args": "./lib/args.js", + "./command": "./lib/command.js", + "./config": "./lib/config/index.js", + "./errors": "./lib/errors/index.js", + "./execute": "./lib/execute.js", + "./flags": "./lib/flags.js", + "./flush": "./lib/flush.js", + "./handle": "./lib/errors/handle.js", + "./help": "./lib/help/index.js", + "./hooks": "./lib/interfaces/hooks.js", + "./interfaces": "./lib/interfaces/index.js", + "./logger": "./lib/logger.js", + "./performance": "./lib/performance.js", + "./run": "./lib/main.js", + "./settings": "./lib/settings.js", + "./util/ids": "./lib/util/ids.js", + "./ux": "./lib/ux/index.js" + }, "repository": "oclif/core", "oclif": { "bin": "oclif", diff --git a/src/cache.ts b/src/cache.ts index d9649129c..75330bdcc 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -2,14 +2,14 @@ import {readFileSync} from 'node:fs' import {join} from 'node:path' import {Config} from './config/config' -import {PJSON, Plugin} from './interfaces' +import {Configuration, Plugin} from './interfaces' type OclifCoreInfo = {name: string; version: string} type CacheContents = { rootPlugin: Plugin config: Config - exitCodes: PJSON.Plugin['oclif']['exitCodes'] + exitCodes: Configuration['exitCodes'] '@oclif/core': OclifCoreInfo } @@ -36,7 +36,7 @@ export default class Cache extends Map | undefined { return super.get(key) } diff --git a/src/command.ts b/src/command.ts index f898b173d..8408f695a 100644 --- a/src/command.ts +++ b/src/command.ts @@ -29,7 +29,7 @@ import * as Parser from './parser' import {aggregateFlags} from './util/aggregate-flags' import {toConfiguredId} from './util/ids' import {uniq} from './util/util' -import ux from './ux' +import {ux} from './ux' const pjson = Cache.getInstance().get('@oclif/core') @@ -406,36 +406,36 @@ export namespace Command { */ export type Cached = { [key: string]: unknown - aliasPermutations?: string[] + aliasPermutations?: string[] | undefined aliases: string[] args: {[name: string]: Arg.Cached} - deprecateAliases?: boolean - deprecationOptions?: Deprecation - description?: string - examples?: Example[] + deprecateAliases?: boolean | undefined + deprecationOptions?: Deprecation | undefined + description?: string | undefined + examples?: Example[] | undefined flags: {[name: string]: Flag.Cached} hasDynamicHelp?: boolean hidden: boolean hiddenAliases: string[] id: string - isESM?: boolean - permutations?: string[] - pluginAlias?: string - pluginName?: string - pluginType?: string - relativePath?: string[] - state?: 'beta' | 'deprecated' | string - strict?: boolean - summary?: string - type?: string - usage?: string | string[] + isESM?: boolean | undefined + permutations?: string[] | undefined + pluginAlias?: string | undefined + pluginName?: string | undefined + pluginType?: string | undefined + relativePath?: string[] | undefined + state?: 'beta' | 'deprecated' | string | undefined + strict?: boolean | undefined + summary?: string | undefined + type?: string | undefined + usage?: string | string[] | undefined } export type Flag = IFlag export namespace Flag { export type Cached = Omit & - (BooleanFlagProps | OptionFlagProps) & {hasDynamicHelp?: boolean} + (BooleanFlagProps | OptionFlagProps) & {hasDynamicHelp?: boolean | undefined} export type Any = Cached | Flag } diff --git a/src/config/config.ts b/src/config/config.ts index 7f8a28676..79fc7a324 100644 --- a/src/config/config.ts +++ b/src/config/config.ts @@ -8,7 +8,7 @@ import Cache from '../cache' import {Command} from '../command' import {CLIError, error, exit, warn} from '../errors' import {getHelpFlagAdditions} from '../help/util' -import {Hook, Hooks, PJSON, Topic} from '../interfaces' +import {Configuration, Hook, Hooks, PJSON, S3Templates, Topic, UserPJSON} from '../interfaces' import {ArchTypes, Config as IConfig, LoadOptions, PlatformTypes, VersionDetails} from '../interfaces/config' import {Plugin as IPlugin, Options} from '../interfaces/plugin' import {Theme} from '../interfaces/theme' @@ -19,7 +19,7 @@ import {settings} from '../settings' import {safeReadJson} from '../util/fs' import {getHomeDir, getPlatform} from '../util/os' import {compact, isProd} from '../util/util' -import ux from '../ux' +import {ux} from '../ux' import {parseTheme} from '../ux/theme' import PluginLoader from './plugin-loader' import {tsPath} from './ts-path' @@ -83,8 +83,8 @@ export class Config implements IConfig { public arch!: ArchTypes public bin!: string - public binAliases?: string[] - public binPath?: string + public binAliases?: string[] | undefined + public binPath?: string | undefined public cacheDir!: string public channel!: string public configDir!: string @@ -94,18 +94,18 @@ export class Config implements IConfig { public home!: string public isSingleCommandCLI = false public name!: string - public npmRegistry?: string - public nsisCustomization?: string - public pjson!: PJSON.CLI + public npmRegistry?: string | undefined + public nsisCustomization?: string | undefined + public pjson!: PJSON public platform!: PlatformTypes public plugins: Map = new Map() public root!: string public shell!: string - public theme?: Theme + public theme?: Theme | undefined public topicSeparator: ' ' | ':' = ':' - public updateConfig!: NonNullable + public updateConfig!: NonNullable public userAgent!: string - public userPJSON?: PJSON.User + public userPJSON?: UserPJSON | undefined public valid!: boolean public version!: string protected warned = false @@ -348,10 +348,9 @@ export class Config implements IConfig { } this.isSingleCommandCLI = Boolean( - this.pjson.oclif.default || - (typeof this.pjson.oclif.commands !== 'string' && - this.pjson.oclif.commands?.strategy === 'single' && - this.pjson.oclif.commands?.target), + typeof this.pjson.oclif.commands !== 'string' && + this.pjson.oclif.commands?.strategy === 'single' && + this.pjson.oclif.commands?.target, ) this.maybeAdjustDebugSetting() @@ -396,13 +395,19 @@ export class Config implements IConfig { public async loadTheme(): Promise { if (this.scopedEnvVarTrue('DISABLE_THEME')) return - const defaultThemeFile = this.pjson.oclif.theme - ? resolve(this.root, this.pjson.oclif.theme) - : this.pjson.oclif.theme + const userThemeFile = resolve(this.configDir, 'theme.json') + const getDefaultTheme = async () => { + if (!this.pjson.oclif.theme) return + if (typeof this.pjson.oclif.theme === 'string') { + return safeReadJson>(resolve(this.root, this.pjson.oclif.theme)) + } + + return this.pjson.oclif.theme + } const [defaultTheme, userTheme] = await Promise.all([ - defaultThemeFile ? await safeReadJson>(defaultThemeFile) : undefined, + await getDefaultTheme(), await safeReadJson>(userThemeFile), ]) @@ -589,13 +594,13 @@ export class Config implements IConfig { } public s3Key( - type: keyof PJSON.S3.Templates, + type: keyof S3Templates, ext?: '.tar.gz' | '.tar.xz' | IConfig.s3Key.Options, options: IConfig.s3Key.Options = {}, ): string { if (typeof ext === 'object') options = ext else if (ext) options.ext = ext - const template = this.updateConfig.s3.templates[options.platform ? 'target' : 'vanilla'][type] ?? '' + const template = this.updateConfig.s3.templates?.[options.platform ? 'target' : 'vanilla'][type] ?? '' return ejs.render(template, {...(this as any), ...options}) } diff --git a/src/config/plugin-loader.ts b/src/config/plugin-loader.ts index 27088dcdf..463b93c6b 100644 --- a/src/config/plugin-loader.ts +++ b/src/config/plugin-loader.ts @@ -12,21 +12,23 @@ import {makeDebug} from './util' const debug = makeDebug() type PluginLoaderOptions = { - plugins?: IPlugin[] | PluginsMap + plugins?: IPlugin[] | PluginsMap | undefined root: string } type LoadOpts = { dataDir: string - devPlugins?: boolean - force?: boolean + devPlugins?: boolean | undefined + force?: boolean | undefined rootPlugin: IPlugin - userPlugins?: boolean - pluginAdditions?: { - core?: string[] - dev?: string[] - path?: string - } + userPlugins?: boolean | undefined + pluginAdditions?: + | { + core?: string[] + dev?: string[] + path?: string + } + | undefined } type PluginsMap = Map @@ -57,7 +59,7 @@ export default class PluginLoader { return {errors: this.errors, plugins: this.plugins} } - public async loadRoot({pjson}: {pjson?: PJSON.Plugin}): Promise { + public async loadRoot({pjson}: {pjson?: PJSON | undefined}): Promise { let rootPlugin: IPlugin if (this.pluginsProvided) { const plugins = [...this.plugins.values()] diff --git a/src/config/plugin.ts b/src/config/plugin.ts index b5b304705..c269a3f5f 100644 --- a/src/config/plugin.ts +++ b/src/config/plugin.ts @@ -65,14 +65,9 @@ function processCommandIds(files: string[]): string[] { function determineCommandDiscoveryOptions( commandDiscovery: string | CommandDiscovery | undefined, - defaultCmdId?: string | undefined, ): CommandDiscovery | undefined { if (!commandDiscovery) return - if (typeof commandDiscovery === 'string' && defaultCmdId) { - return {strategy: 'single', target: commandDiscovery} - } - if (typeof commandDiscovery === 'string') { return {globPatterns: GLOB_PATTERNS, strategy: 'pattern', target: commandDiscovery} } @@ -127,13 +122,13 @@ export class Plugin implements IPlugin { name!: string - parent: Plugin | undefined + parent?: Plugin | undefined - pjson!: PJSON.Plugin + pjson!: PJSON root!: string - tag?: string + tag?: string | undefined type!: string @@ -247,7 +242,7 @@ export class Plugin implements IPlugin { ]), ) - this.commandDiscoveryOpts = determineCommandDiscoveryOptions(this.pjson.oclif?.commands, this.pjson.oclif?.default) + this.commandDiscoveryOpts = determineCommandDiscoveryOptions(this.pjson.oclif?.commands) this._debug('command discovery options', this.commandDiscoveryOpts) diff --git a/src/config/ts-path.ts b/src/config/ts-path.ts index a28bad4cd..39d4c422c 100644 --- a/src/config/ts-path.ts +++ b/src/config/ts-path.ts @@ -246,8 +246,16 @@ async function determinePath(root: string, orig: string): Promise { * if there is a tsconfig and the original sources exist, it attempts to require ts-node */ export async function tsPath(root: string, orig: string, plugin: Plugin): Promise -export async function tsPath(root: string, orig: string | undefined, plugin?: Plugin): Promise -export async function tsPath(root: string, orig: string | undefined, plugin?: Plugin): Promise { +export async function tsPath( + root: string, + orig: string | undefined, + plugin?: Plugin | undefined, +): Promise +export async function tsPath( + root: string, + orig: string | undefined, + plugin?: Plugin | undefined, +): Promise { const rootPlugin = plugin?.options.isRoot ? plugin : Cache.getInstance().get('rootPlugin') if (!orig) return orig diff --git a/src/errors/errors/cli.ts b/src/errors/errors/cli.ts index bda115db7..0de8c1849 100644 --- a/src/errors/errors/cli.ts +++ b/src/errors/errors/cli.ts @@ -12,7 +12,10 @@ import {settings} from '../../settings' * properties specific to internal oclif error handling */ -export function addOclifExitCode(error: Record, options?: {exit?: false | number}): OclifError { +export function addOclifExitCode( + error: Record, + options?: {exit?: false | number | undefined}, +): OclifError { if (!('oclif' in error)) { ;(error as unknown as OclifError).oclif = {} } @@ -22,12 +25,12 @@ export function addOclifExitCode(error: Record, options?: {exit?: f } export class CLIError extends Error implements OclifError { - code?: string + code?: string | undefined oclif: OclifError['oclif'] = {} - skipOclifErrorHandling?: boolean - suggestions?: string[] + skipOclifErrorHandling?: boolean | undefined + suggestions?: string[] | undefined - constructor(error: Error | string, options: {exit?: false | number} & PrettyPrintableError = {}) { + constructor(error: Error | string, options: {exit?: false | number | undefined} & PrettyPrintableError = {}) { super(error instanceof Error ? error.message : error) addOclifExitCode(this, options) this.code = options.code diff --git a/src/errors/errors/pretty-print.ts b/src/errors/errors/pretty-print.ts index b908e3d66..838e622bf 100644 --- a/src/errors/errors/pretty-print.ts +++ b/src/errors/errors/pretty-print.ts @@ -6,7 +6,7 @@ import {errtermwidth} from '../../screen' import {settings} from '../../settings' // These exist for backwards compatibility with CLIError -type CLIErrorDisplayOptions = {bang?: string; name?: string} +type CLIErrorDisplayOptions = {bang?: string | undefined; name?: string | undefined} export function applyPrettyPrintOptions(error: Error, options: PrettyPrintableError): PrettyPrintableError { const prettyErrorKeys: (keyof PrettyPrintableError)[] = ['message', 'code', 'ref', 'suggestions'] diff --git a/src/flush.ts b/src/flush.ts index b09d260ee..c3b813292 100644 --- a/src/flush.ts +++ b/src/flush.ts @@ -1,4 +1,4 @@ -import {error} from './errors' +import {error} from './errors/error' function timeout(p: Promise, ms: number) { function wait(ms: number, unref = false) { diff --git a/src/help/formatter.ts b/src/help/formatter.ts index c9e6ad5c5..5a96fb693 100644 --- a/src/help/formatter.ts +++ b/src/help/formatter.ts @@ -77,7 +77,12 @@ export class HelpFormatter { public renderList( input: (string | undefined)[][], - opts: {indentation: number; multiline?: boolean; spacer?: string; stripAnsi?: boolean}, + opts: { + indentation: number + multiline?: boolean | undefined + spacer?: string | undefined + stripAnsi?: boolean | undefined + }, ): string { if (input.length === 0) { return '' diff --git a/src/help/index.ts b/src/help/index.ts index 2baca5d0d..75402631f 100644 --- a/src/help/index.ts +++ b/src/help/index.ts @@ -4,18 +4,20 @@ import {Command} from '../command' import {tsPath} from '../config/ts-path' import {error} from '../errors/error' import * as Interfaces from '../interfaces' +import {HelpLocationOptions} from '../interfaces/pjson' import {load} from '../module-loader' import {SINGLE_COMMAND_CLI_SYMBOL} from '../symbols' import {cacheDefaultValue} from '../util/cache-default-value' import {toConfiguredId} from '../util/ids' import {compact, sortBy, uniqBy} from '../util/util' -import ux from '../ux' +import {ux} from '../ux' import {colorize} from '../ux/theme' import {CommandHelp} from './command' import {HelpFormatter} from './formatter' import RootHelp from './root' import {formatCommandDeprecationWarning, getHelpFlagAdditions, standardizeIDFromArgv} from './util' export {CommandHelp} from './command' +export {HelpFormatter, type HelpSection, type HelpSectionKeyValueTable, type HelpSectionRenderer} from './formatter' export {getHelpFlagAdditions, normalizeArgv, standardizeIDFromArgv} from './util' function getHelpSubject(args: string[], config: Interfaces.Config): string | undefined { @@ -385,19 +387,22 @@ function extractClass(exported: any): HelpBaseDerived { return exported && exported.default ? exported.default : exported } -export async function loadHelpClass(config: Interfaces.Config): Promise { - const {pjson} = config - const configuredClass = pjson.oclif?.helpClass +function determineLocation(helpClass: string | HelpLocationOptions): HelpLocationOptions { + if (typeof helpClass === 'string') return {identifier: 'default', target: helpClass} + if (!helpClass.identifier) return {...helpClass, identifier: 'default'} + return helpClass +} - if (configuredClass) { +export async function loadHelpClass(config: Interfaces.Config): Promise { + if (config.pjson.oclif?.helpClass) { + const {identifier, target} = determineLocation(config.pjson.oclif?.helpClass) try { - const path = (await tsPath(config.root, configuredClass)) ?? configuredClass - const exported = await load(config, path) - return extractClass(exported) + const path = (await tsPath(config.root, target)) ?? target + const module = await load(config, path) + const helpClass = module[identifier] ?? (identifier === 'default' ? extractClass(module) : undefined) + return extractClass(helpClass) } catch (error: any) { - throw new Error( - `Unable to load configured help class "${configuredClass}", failed with message:\n${error.message}`, - ) + throw new Error(`Unable to load configured help class "${target}", failed with message:\n${error.message}`) } } diff --git a/src/index.ts b/src/index.ts index 13cbcd1b7..417f337ed 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,15 +18,22 @@ export {handle} from './errors/handle' export {execute} from './execute' export * as Flags from './flags' export {flush} from './flush' -export {CommandHelp, Help, HelpBase, loadHelpClass} from './help' -export {HelpSection, HelpSectionKeyValueTable, HelpSectionRenderer} from './help/formatter' +export { + CommandHelp, + Help, + HelpBase, + type HelpSection, + type HelpSectionKeyValueTable, + type HelpSectionRenderer, + loadHelpClass, +} from './help' export * as Interfaces from './interfaces' -export {Hook} from './interfaces/hooks' +export {type Hook} from './interfaces/hooks' export {getLogger} from './logger' export {run} from './main' export * as ModuleLoader from './module-loader' export * as Parser from './parser' export {Performance} from './performance' -export {Settings, settings} from './settings' +export {type Settings, settings} from './settings' export {toConfiguredId, toStandardizedId} from './util/ids' -export {methods as ux} from './ux' +export {ux} from './ux' diff --git a/src/interfaces/config.ts b/src/interfaces/config.ts index 930305fbd..48e06a98a 100644 --- a/src/interfaces/config.ts +++ b/src/interfaces/config.ts @@ -1,6 +1,6 @@ import {Command} from '../command' import {Hook, Hooks} from './hooks' -import {PJSON} from './pjson' +import {Configuration, PJSON, S3Templates} from './pjson' import {Options, Plugin} from './plugin' import {Theme} from './theme' import {Topic} from './topic' @@ -37,8 +37,8 @@ export interface Config { /** * name of any bin aliases that will execute the cli */ - readonly binAliases?: string[] - readonly binPath?: string + readonly binAliases?: string[] | undefined + readonly binPath?: string | undefined /** * cache directory to use for CLI * @@ -84,9 +84,9 @@ export interface Config { /** * npm registry to use for installing plugins */ - readonly npmRegistry?: string - readonly nsisCustomization?: string - readonly pjson: PJSON.CLI + readonly npmRegistry?: string | undefined + readonly nsisCustomization?: string | undefined + readonly pjson: PJSON /** * process.platform */ @@ -102,7 +102,7 @@ export interface Config { captureErrors?: boolean, ): Promise> s3Key(type: 'unversioned' | 'versioned', ext: '.tar.gz' | '.tar.xz', options?: Config.s3Key.Options): string - s3Key(type: keyof PJSON.S3.Templates, options?: Config.s3Key.Options): string + s3Key(type: keyof S3Templates, options?: Config.s3Key.Options): string s3Url(key: string): string scopedEnvVar(key: string): string | undefined scopedEnvVarKey(key: string): string @@ -112,10 +112,10 @@ export interface Config { * active shell */ readonly shell: string - readonly theme?: Theme + readonly theme?: Theme | undefined topicSeparator: ' ' | ':' readonly topics: Topic[] - readonly updateConfig: NonNullable + readonly updateConfig: NonNullable /** * user agent to use for http calls * diff --git a/src/interfaces/errors.ts b/src/interfaces/errors.ts index d6262903e..4da74c06d 100644 --- a/src/interfaces/errors.ts +++ b/src/interfaces/errors.ts @@ -2,7 +2,7 @@ export type CommandError = Error & {exitCode?: number} export interface OclifError { oclif: { - exit?: number + exit?: number | undefined } } @@ -10,21 +10,21 @@ export interface PrettyPrintableError { /** * a unique error code for this error class */ - code?: string + code?: string | undefined /** * message to display related to the error */ - message?: string + message?: string | undefined /** * a url to find out more information related to this error * or fixing the error */ - ref?: string + ref?: string | undefined /** * a suggestion that may be useful or provide additional context */ - suggestions?: string[] + suggestions?: string[] | undefined } diff --git a/src/interfaces/index.ts b/src/interfaces/index.ts index e033e95c8..9657ce800 100644 --- a/src/interfaces/index.ts +++ b/src/interfaces/index.ts @@ -8,7 +8,7 @@ export type {Hook, Hooks} from './hooks' export type {Logger} from './logger' export type {Manifest} from './manifest' export type {Arg, BooleanFlag, CustomOptions, Deprecation, Flag, FlagDefinition, OptionFlag} from './parser' -export type {PJSON} from './pjson' +export type {Configuration, PJSON, S3, S3Templates, UserPJSON} from './pjson' export type {Options, Plugin, PluginOptions} from './plugin' export type {S3Manifest} from './s3-manifest' export type {Theme} from './theme' diff --git a/src/interfaces/parser.ts b/src/interfaces/parser.ts index a1b00abb8..a8e9f52cd 100644 --- a/src/interfaces/parser.ts +++ b/src/interfaces/parser.ts @@ -6,10 +6,10 @@ export type ArgOutput = {[name: string]: any} export type CLIParseErrorOptions = { parse: { - input?: ParserInput - output?: ParserOutput + input?: ParserInput | undefined + output?: ParserOutput | undefined } - exit?: number + exit?: number | undefined } export type OutputArgs = {[P in keyof T]: any} @@ -295,10 +295,10 @@ type FlagReturnType = R['requiredOrDefaulted'] : T[] : T : R['multiple'] extends true - ? [T] extends [Array] - ? T | undefined - : T[] | undefined - : T | undefined + ? [T] extends [Array] + ? T | undefined + : T[] | undefined + : T | undefined /** * FlagDefinition types a function that takes `options` and returns an OptionFlag. @@ -421,7 +421,7 @@ export type Input enableJsonFlag?: true | false args?: ArgInput - strict?: boolean + strict?: boolean | undefined context?: ParserContext '--'?: boolean } @@ -432,11 +432,11 @@ export type ParserInput = { args: ArgInput strict: boolean context: ParserContext | undefined - '--'?: boolean + '--'?: boolean | undefined } export type ParserContext = Command & { - token?: FlagToken | ArgToken + token?: FlagToken | ArgToken | undefined } export type FlagInput = {[P in keyof T]: Flag} diff --git a/src/interfaces/pjson.ts b/src/interfaces/pjson.ts index 657876920..c4430facf 100644 --- a/src/interfaces/pjson.ts +++ b/src/interfaces/pjson.ts @@ -1,18 +1,5 @@ import {HelpOptions} from './help' - -export interface PJSON { - [k: string]: any - dependencies?: {[name: string]: string} - devDependencies?: {[name: string]: string} - oclif: { - bin?: string - dirname?: string - hooks?: Record - plugins?: string[] - schema?: number - } - version: string -} +import {Theme} from './theme' export type CommandDiscovery = { /** @@ -96,140 +83,222 @@ export type HookOptions = { identifier: string } -export namespace PJSON { - export interface Plugin extends PJSON { - name: string - oclif: PJSON['oclif'] & { - additionalHelpFlags?: string[] - additionalVersionFlags?: string[] - aliases?: {[name: string]: null | string} - commands?: string | CommandDiscovery - /** - * Default command id when no command is found. This is used to support single command CLIs. - * Only supported value is "." - * - * @deprecated Use `commands.strategy: 'single'` instead. - */ - default?: string - description?: string - devPlugins?: string[] - exitCodes?: { - default?: number - failedFlagParsing?: number - failedFlagValidation?: number - invalidArgsSpec?: number - nonExistentFlag?: number - requiredArgs?: number - unexpectedArgs?: number - } - flexibleTaxonomy?: boolean - helpClass?: string - helpOptions?: HelpOptions - hooks?: {[name: string]: string | string[] | HookOptions | HookOptions[]} - jitPlugins?: Record - macos?: { - identifier?: string - sign?: string - } - plugins?: string[] - repositoryPrefix?: string - schema?: number - state?: 'beta' | 'deprecated' | string - theme?: string - topicSeparator?: ' ' | ':' - topics?: { - [k: string]: { - description?: string - hidden?: boolean - subtopics?: Plugin['oclif']['topics'] - } - } - update?: { - autoupdate?: { - debounce?: number - rollout?: number - } - disableNpmLookup?: boolean - node: { - targets?: string[] - version?: string - options?: string | string[] - } - s3: S3 - } - windows?: { - homepage?: string - keypath?: string - name?: string +export type HelpLocationOptions = { + /** + * The file path containing help class. + */ + target: string + /** + * The name of the export to use when loading the help class from the `target` file. Defaults to `default`. + */ + identifier: string +} + +export type S3Templates = { + baseDir?: string + manifest?: string + unversioned?: string + versioned?: string +} + +export type S3 = { + acl?: string | undefined + bucket?: string | undefined + folder?: string | undefined + gz?: boolean | undefined + host?: string | undefined + templates?: + | { + target: S3Templates + vanilla: S3Templates } - } - version: string - } + | undefined + xz?: boolean | undefined +} - export interface S3 { - acl?: string - bucket?: string - folder?: string - gz?: boolean - host?: string - templates: { - target: S3.Templates - vanilla: S3.Templates - } - xz?: boolean +export type Configuration = { + /** + * Flags in addition to --help that should trigger help output. + */ + additionalHelpFlags?: string[] + /** + * Flags in addition to --version that should trigger version output. + */ + additionalVersionFlags?: string[] + /** + * Plugin aliases. + */ + aliases?: {[name: string]: null | string} + /** + * The name of the executable. + */ + bin?: string + /** + * Aliases for the executable. + */ + binAliases?: string[] + commands?: string | CommandDiscovery + /** + * Your CLI's description. Overrides the description in the package.json. + */ + description?: string | undefined + /** + * Plugins to load when in development mode. + */ + devPlugins?: string[] + /** + * The directory name to use when determining the cache, config, and data directories. + */ + dirname?: string + /** + * Example plugin to use in @oclif/plugin-plugin's help output. + */ + examplePlugin?: string + /** + * Customize the exit codes for the CLI. + */ + exitCodes?: { + default?: number + failedFlagParsing?: number + failedFlagValidation?: number + invalidArgsSpec?: number + nonExistentFlag?: number + requiredArgs?: number + unexpectedArgs?: number } - - export namespace S3 { - export interface Templates { - baseDir?: string - manifest?: string - unversioned?: string - versioned?: string - } + /** + * Enable flexible taxonomy for commands. + */ + flexibleTaxonomy?: boolean + /** + * The location of your custom help class. + */ + helpClass?: string | HelpLocationOptions + /** + * Options for the help output. + */ + helpOptions?: HelpOptions + /** + * Register hooks to run at various points in the CLI lifecycle. + */ + hooks?: {[name: string]: string | string[] | HookOptions | HookOptions[]} + /** + * Plugins that can be installed just-in-time. + */ + jitPlugins?: Record + macos?: { + identifier?: string + sign?: string } - - export interface CLI extends Plugin { - oclif: Plugin['oclif'] & { - bin?: string - binAliases?: string[] - dirname?: string - flexibleTaxonomy?: boolean - jitPlugins?: Record - npmRegistry?: string - nsisCustomization?: string - schema?: number - scope?: string - pluginPrefix?: string - 'warn-if-update-available'?: { - authorization: string - message: string - registry: string - timeoutInDays: number - frequency: number - frequencyUnit: 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' - } + /** + * Use a private or alternate npm registry. + */ + npmRegistry?: string + /** + * Script to run during postinstall on windows. + */ + nsisCustomization?: string + /** + * Plugin prefix to use when working with plugins with @oclif/plugin-plugins. + * + * Defaults to `plugin-`. + */ + pluginPrefix?: string + /** + * Plugins to load. + */ + plugins?: string[] + /** + * Template string used to build links to source code in CLI's README (when using `oclif readme`). + */ + repositoryPrefix?: string + schema?: number + /** + * The namespace to be used for plugins of your CLI, e.g. `@salesforce`. + */ + scope?: string + /** + * State of your CLI + * + * - `beta` - will show message to user that command or CLI is in beta + * - `deprecated` - will show message to user that command or CLI is deprecated + */ + state?: 'beta' | 'deprecated' | string + /** + * The theme to ship with the CLI. + * + * Can be a path to a JSON file or a Theme object. + */ + theme?: string | Theme + /** + * Separator to use for your CLI. Can be `:` or ` `. + */ + topicSeparator?: ' ' | ':' + /** + * Customize the topics in the CLI. + */ + topics?: { + [k: string]: { + description?: string + hidden?: boolean + subtopics?: Configuration['topics'] } } - - export interface User extends PJSON { - oclif: PJSON['oclif'] & { - plugins?: (PluginTypes.Link | PluginTypes.User | string)[] + update?: { + autoupdate?: { + debounce?: number + rollout?: number + } + disableNpmLookup?: boolean + node: { + targets?: string[] + version?: string + options?: string | string[] } - private?: boolean + s3: S3 + } + 'warn-if-update-available'?: { + authorization?: string + message?: string + registry?: string + timeoutInDays?: number + frequency?: number + frequencyUnit?: 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' } + windows?: { + homepage?: string + keypath?: string + name?: string + } +} - export type PluginTypes = {root: string} | PluginTypes.Link | PluginTypes.User - export namespace PluginTypes { - export interface User { - name: string - tag?: string - type: 'user' - url?: string - } - export interface Link { - name: string - root: string - type: 'link' - } +export type UserPlugin = { + name: string + tag?: string + type: 'user' + url?: string +} + +export type LinkedPlugin = { + name: string + root: string + type: 'link' +} + +export type PluginTypes = {root: string} | UserPlugin | LinkedPlugin + +export type UserPJSON = { + oclif: { + plugins?: PluginTypes[] } + private?: boolean +} + +export type PJSON = { + [k: string]: any + dependencies?: {[name: string]: string} + devDependencies?: {[name: string]: string} + name: string + oclif: Configuration + version: string } diff --git a/src/interfaces/plugin.ts b/src/interfaces/plugin.ts index 6d23ae741..65fa7d1ad 100644 --- a/src/interfaces/plugin.ts +++ b/src/interfaces/plugin.ts @@ -4,36 +4,38 @@ import {HookOptions, PJSON} from './pjson' import {Topic} from './topic' export interface PluginOptions { - children?: Plugin[] - errorOnManifestCreate?: boolean - flexibleTaxonomy?: boolean - ignoreManifest?: boolean - isRoot?: boolean - name?: string - parent?: Plugin - pjson?: PJSON.Plugin - respectNoCacheDefault?: boolean + children?: Plugin[] | undefined + errorOnManifestCreate?: boolean | undefined + flexibleTaxonomy?: boolean | undefined + ignoreManifest?: boolean | undefined + isRoot?: boolean | undefined + name?: string | undefined + parent?: Plugin | undefined + pjson?: PJSON | undefined + respectNoCacheDefault?: boolean | undefined root: string - tag?: string - type?: string - url?: string + tag?: string | undefined + type?: string | undefined + url?: string | undefined } export interface Options extends PluginOptions { - channel?: string - devPlugins?: boolean - enablePerf?: boolean - jitPlugins?: boolean - logger?: Logger - pjson?: PJSON.Plugin - pluginAdditions?: { - core?: string[] - dev?: string[] - path?: string - } - plugins?: Map - userPlugins?: boolean - version?: string + channel?: string | undefined + devPlugins?: boolean | undefined + enablePerf?: boolean | undefined + jitPlugins?: boolean | undefined + logger?: Logger | undefined + pjson?: PJSON | undefined + pluginAdditions?: + | { + core?: string[] + dev?: string[] + path?: string + } + | undefined + plugins?: Map | undefined + userPlugins?: boolean | undefined + version?: string | undefined } export interface Plugin { @@ -68,13 +70,13 @@ export interface Plugin { */ name: string readonly options: Options - parent?: Plugin + parent?: Plugin | undefined /** * full package.json * * parsed with read-pkg */ - pjson: PJSON.CLI | PJSON.Plugin + pjson: PJSON /** * base path of plugin */ @@ -83,7 +85,7 @@ export interface Plugin { * npm dist-tag of plugin * only used for user plugins */ - tag?: string + tag?: string | undefined readonly topics: Topic[] /** diff --git a/src/interfaces/topic.ts b/src/interfaces/topic.ts index 13ecb05ec..887f4847d 100644 --- a/src/interfaces/topic.ts +++ b/src/interfaces/topic.ts @@ -1,5 +1,5 @@ export interface Topic { - description?: string - hidden?: boolean + description?: string | undefined + hidden?: boolean | undefined name: string } diff --git a/src/main.ts b/src/main.ts index 9b41b1530..ba2d312f1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -7,7 +7,7 @@ import * as Interfaces from './interfaces' import {getLogger, setLogger} from './logger' import {OCLIF_MARKER_OWNER, Performance} from './performance' import {SINGLE_COMMAND_CLI_SYMBOL} from './symbols' -import ux from './ux' +import {ux} from './ux' export const helpAddition = (argv: string[], config: Interfaces.Config): boolean => { if (argv.length === 0 && !config.isSingleCommandCLI) return true diff --git a/src/parser/errors.ts b/src/parser/errors.ts index 65b01339b..08aaf56fa 100644 --- a/src/parser/errors.ts +++ b/src/parser/errors.ts @@ -10,7 +10,7 @@ export {CLIError} from '../errors' export type Validation = { name: string - reason?: string + reason?: string | undefined status: 'failed' | 'success' validationFn: string } diff --git a/src/parser/parse.ts b/src/parser/parse.ts index 72d79028f..7ee8c195c 100644 --- a/src/parser/parse.ts +++ b/src/parser/parse.ts @@ -560,15 +560,19 @@ export class Parser< ) as TFlags & BFlags & {json: boolean | undefined} type FlagWithStrategy = { - helpFunction?: (fws: FlagWithStrategy, flags: Record, ...args: any) => Promise + helpFunction?: ( + fws: FlagWithStrategy, + flags: Record, + ...args: any + ) => Promise | undefined inputFlag: { flag: Flag name: string } - metadata?: MetadataFlag - tokens?: FlagToken[] - value?: any - valueFunction?: ValueFunction + metadata?: MetadataFlag | undefined + tokens?: FlagToken[] | undefined + value?: any | undefined + valueFunction?: ValueFunction | undefined } const flagTokenMap = this.mapAndValidateFlags() @@ -624,7 +628,7 @@ export class Parser< } } - private findFlag(arg: string): {isLong: boolean; name?: string} { + private findFlag(arg: string): {isLong: boolean; name?: string | undefined} { const isLong = arg.startsWith('--') const short = isLong ? false : arg.startsWith('-') const name = isLong ? this.findLongFlag(arg) : short ? this.findShortFlag(arg) : undefined diff --git a/src/settings.ts b/src/settings.ts index 2e98bc2a3..0a497439e 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -5,19 +5,19 @@ export type Settings = { * Environment Variable: * OCLIF_COLUMNS=80 */ - columns?: number + columns?: number | undefined /** * Show additional debug output without DEBUG. Mainly shows stackstraces. * * Useful to set in the ./bin/dev.js script. * oclif.settings.debug = true; */ - debug?: boolean + debug?: boolean | undefined /** * Enable performance tracking. Resulting data is available in the `perf` property of the `Config` class. * This will be overridden by the `enablePerf` property passed into Config constructor. */ - performanceEnabled?: boolean + performanceEnabled?: boolean | undefined /** * Try to use ts-node to load typescript source files instead of javascript files. * Defaults to true in development and test environments (e.g. using bin/dev.js or @@ -25,13 +25,13 @@ export type Settings = { * * @deprecated use enableAutoTranspile instead. */ - tsnodeEnabled?: boolean + tsnodeEnabled?: boolean | undefined /** * Enable automatic transpilation of TypeScript files to JavaScript. * * Defaults to true in development and test environments (e.g. using bin/dev.js or NODE_ENV=development or NODE_ENV=test). */ - enableAutoTranspile?: boolean + enableAutoTranspile?: boolean | undefined } // Set global.oclif to the new object if it wasn't set before diff --git a/src/util/ids.ts b/src/util/ids.ts index 9af35c1d1..5a9ce406a 100644 --- a/src/util/ids.ts +++ b/src/util/ids.ts @@ -1,4 +1,4 @@ -import {Config} from '../interfaces' +import {type Config} from '../interfaces/config' export function toStandardizedId(commandID: string, config: Config): string { return commandID.replaceAll(new RegExp(config.topicSeparator, 'g'), ':') diff --git a/src/util/read-pjson.ts b/src/util/read-pjson.ts index 221126d76..a377b4e4c 100644 --- a/src/util/read-pjson.ts +++ b/src/util/read-pjson.ts @@ -12,14 +12,14 @@ const debug = makeDebug('read-pjson') * * We can assume that the package.json file exists because the plugin root has already been loaded at this point. */ -export async function readPjson(path: string): Promise { +export async function readPjson(path: string): Promise { const pjsonPath = join(path, 'package.json') if (process.env.OCLIF_DISABLE_RC) { debug('OCLIF_DISABLE_RC is set, skipping rc search') - return readJson(pjsonPath) + return readJson(pjsonPath) } - const pjson = await readJson(pjsonPath) + const pjson = await readJson(pjsonPath) // don't bother with cosmiconfig if the plugin's package.json already has an oclif config if (pjson.oclif) { diff --git a/src/ux/action/base.ts b/src/ux/action/base.ts index f6c2b85fd..21d9e7411 100644 --- a/src/ux/action/base.ts +++ b/src/ux/action/base.ts @@ -210,7 +210,7 @@ export class ActionBase { } } - private get globals(): {action: {task?: Task}; output: string | undefined} { + private get globals(): {action: {task?: Task | undefined}; output: string | undefined} { ;(global as any).ux = (global as any).ux || {} const globals = (global as any).ux globals.action = globals.action || {} diff --git a/src/ux/colorize-json.ts b/src/ux/colorize-json.ts index 5354f5e14..d509475a0 100644 --- a/src/ux/colorize-json.ts +++ b/src/ux/colorize-json.ts @@ -13,8 +13,8 @@ const tokenTypes = [ ] type Options = { - pretty?: boolean - theme?: Record + pretty?: boolean | undefined + theme?: Record | undefined } function formatInput(json?: unknown, options?: Options) { diff --git a/src/ux/index.ts b/src/ux/index.ts index e3b744fc6..8c394c205 100644 --- a/src/ux/index.ts +++ b/src/ux/index.ts @@ -7,6 +7,13 @@ import colorizeJson from './colorize-json' import {colorize} from './theme' import {stderr, stdout} from './write' +export {error} from '../errors/error' +export {exit} from '../errors/exit' +export {warn} from '../errors/warn' +export {default as colorizeJson} from './colorize-json' +export {colorize} from './theme' +export {stderr, stdout} from './write' + const ACTION_TYPE = (Boolean(process.stderr.isTTY) && !process.env.CI && @@ -14,7 +21,7 @@ const ACTION_TYPE = 'spinner') || 'simple' -export const methods = { +export const ux = { action: ACTION_TYPE === 'spinner' ? new Spinner() : new Simple(), /** * Add color to text. @@ -70,5 +77,3 @@ export const methods = { */ warn, } - -export default methods diff --git a/test/command/fixtures/single-cmd-cli-deprecated/package.json b/test/command/fixtures/single-cmd-cli-deprecated/package.json deleted file mode 100644 index aab6f1da7..000000000 --- a/test/command/fixtures/single-cmd-cli-deprecated/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "single-cmd-cli", - "version": "0.0.0", - "description": "Single Command CLI", - "private": true, - "oclif": { - "default": ".", - "commands": "./dist" - } -} diff --git a/test/command/fixtures/single-cmd-cli-deprecated/src/index.ts b/test/command/fixtures/single-cmd-cli-deprecated/src/index.ts deleted file mode 100644 index d303edff3..000000000 --- a/test/command/fixtures/single-cmd-cli-deprecated/src/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -import {Command} from '../../../../../src/index' - -export default class FooBar extends Command { - public static description = 'Description of single command CLI.' - public async run(): Promise { - this.log('hello world!') - } -} diff --git a/test/command/fixtures/single-cmd-cli-deprecated/tsconfig.json b/test/command/fixtures/single-cmd-cli-deprecated/tsconfig.json deleted file mode 100644 index 968ea6fbe..000000000 --- a/test/command/fixtures/single-cmd-cli-deprecated/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "compilerOptions": { - "outDir": "dist", - "rootDirs": ["./src"] - }, - "include": ["./src/**/*"] -} diff --git a/test/command/single-command-cli.test.ts b/test/command/single-command-cli.test.ts index 1fc6a6b09..432bd20c8 100644 --- a/test/command/single-command-cli.test.ts +++ b/test/command/single-command-cli.test.ts @@ -22,25 +22,3 @@ DESCRIPTION expect(stdout).to.equal('hello world!\n') }) }) - -describe('single command cli (deprecated)', () => { - it('should show help for commands', async () => { - const {stdout} = await runCommand(['--help'], { - root: resolve(__dirname, 'fixtures/single-cmd-cli-deprecated/package.json'), - }) - expect(stdout).to.equal(`Description of single command CLI. - -USAGE - $ single-cmd-cli - -DESCRIPTION - Description of single command CLI. - -`) - }) - - it('should run command', async () => { - const {stdout} = await runCommand([], {root: resolve(__dirname, 'fixtures/single-cmd-cli-deprecated/package.json')}) - expect(stdout).to.equal('hello world!\n') - }) -}) diff --git a/test/config/config.test.ts b/test/config/config.test.ts index e3ec9e816..b10765e66 100644 --- a/test/config/config.test.ts +++ b/test/config/config.test.ts @@ -169,7 +169,7 @@ describe('Config', () => { }) const tests: Array<{ - key: keyof Interfaces.PJSON.S3.Templates + key: keyof Interfaces.S3Templates expected: string extra?: Record & {ext?: '.tar.gz' | '.tar.xz' | Interfaces.Config.s3Key.Options} }> = [ @@ -227,8 +227,8 @@ describe('Config', () => { ...pjson, oclif: { ...pjson.oclif, + // @ts-expect-error - not worth stubbing out every single required prop on s3 update: { - // @ts-expect-error - not worth stubbing out every single required prop on s3 s3: { host: 'https://bar.com/a/', }, diff --git a/test/help/_test-help-class-identifier.ts b/test/help/_test-help-class-identifier.ts new file mode 100644 index 000000000..9dc96a7ac --- /dev/null +++ b/test/help/_test-help-class-identifier.ts @@ -0,0 +1,20 @@ +// `loadHelpClass` tests require an oclif project for testing so +// it is re-using the setup here to be able to do a lookup for +// this sample help class file in tests, although it is not needed +// for ../help itself. + +import {HelpBase} from '../../src' + +export class MyHelp extends HelpBase { + getCommandHelpForReadme(): string { + return 'help for readme' + } + + async showCommandHelp(): Promise { + console.log('command help') + } + + async showHelp(): Promise { + console.log('help') + } +} diff --git a/test/help/util.test.ts b/test/help/util.test.ts index 95dbd8f10..f63b4c5a9 100644 --- a/test/help/util.test.ts +++ b/test/help/util.test.ts @@ -6,6 +6,7 @@ import {Args, Command, Config} from '../../src' import * as util from '../../src/config/util' import {loadHelpClass, standardizeIDFromArgv} from '../../src/help' import configuredHelpClass from './_test-help-class' +import {MyHelp} from './_test-help-class-identifier' describe('util', () => { let config: Config @@ -45,6 +46,29 @@ describe('util', () => { expect(await loadHelpClass(config)).to.deep.equal(configuredHelpClass) }) + it('loads help class defined using target but no identifier', async () => { + config.pjson.oclif.helpClass = { + target: '../test/help/_test-help-class', + // @ts-expect-error for testing purposes + identifier: undefined, + } + config.root = resolve(__dirname, '..') + + expect(configuredHelpClass).to.not.be.undefined + expect(await loadHelpClass(config)).to.deep.equal(configuredHelpClass) + }) + + it('loads help class defined using target and identifier', async () => { + config.pjson.oclif.helpClass = { + target: '../test/help/_test-help-class-identifier', + identifier: 'MyHelp', + } + config.root = resolve(__dirname, '..') + + expect(MyHelp).to.not.be.undefined + expect(await loadHelpClass(config)).to.deep.equal(MyHelp) + }) + describe('error cases', () => { it('throws an error when failing to load the help class defined in pjson.oclif.helpClass', async () => { config.pjson.oclif.helpClass = './lib/does-not-exist-help-class' diff --git a/tsconfig.json b/tsconfig.json index 2d9df030c..0ac529273 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -9,6 +9,7 @@ "strict": true, "target": "ES2022", "allowSyntheticDefaultImports": true, + "exactOptionalPropertyTypes": true, "noErrorTruncation": true, "moduleResolution": "Node16" },