first commit

This commit is contained in:
2025-10-26 23:10:15 +08:00
commit 8f0345b7be
14961 changed files with 2356381 additions and 0 deletions

38
node_modules/@oclif/core/lib/args.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
import { URL } from 'node:url';
import { Arg, ArgDefinition } from './interfaces/parser';
/**
* Create a custom arg.
*
* @example
* type Id = string
* type IdOpts = { startsWith: string; length: number };
*
* export const myArg = custom<Id, IdOpts>({
* parse: async (input, opts) => {
* if (input.startsWith(opts.startsWith) && input.length === opts.length) {
* return input
* }
*
* throw new Error('Invalid id')
* },
* })
*/
export declare function custom<T = string, P = Record<string, unknown>>(_defaults: Partial<Arg<T, P>>): ArgDefinition<T, P>;
export declare const boolean: ArgDefinition<boolean, Record<string, unknown>>;
export declare const integer: ArgDefinition<number, {
max?: number;
min?: number;
}>;
export declare const directory: ArgDefinition<string, {
exists?: boolean;
}>;
export declare const file: ArgDefinition<string, {
exists?: boolean;
}>;
/**
* Initializes a string as a URL. Throws an error
* if the string is not a valid URL.
*/
export declare const url: ArgDefinition<URL, Record<string, unknown>>;
declare const stringArg: ArgDefinition<string, Record<string, unknown>>;
export { stringArg as string };

61
node_modules/@oclif/core/lib/args.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.string = exports.url = exports.file = exports.directory = exports.integer = exports.boolean = void 0;
exports.custom = custom;
const node_url_1 = require("node:url");
const fs_1 = require("./util/fs");
const util_1 = require("./util/util");
function custom(defaults) {
return (options = {}) => ({
parse: async (i, _context, _opts) => i,
...defaults,
...options,
input: [],
type: 'option',
});
}
exports.boolean = custom({
parse: async (b) => Boolean(b) && (0, util_1.isNotFalsy)(b),
});
exports.integer = custom({
async parse(input, _, opts) {
if (!/^-?\d+$/.test(input))
throw new Error(`Expected an integer but received: ${input}`);
const num = Number.parseInt(input, 10);
if (opts.min !== undefined && num < opts.min)
throw new Error(`Expected an integer greater than or equal to ${opts.min} but received: ${input}`);
if (opts.max !== undefined && num > opts.max)
throw new Error(`Expected an integer less than or equal to ${opts.max} but received: ${input}`);
return num;
},
});
exports.directory = custom({
async parse(input, _, opts) {
if (opts.exists)
return (0, fs_1.dirExists)(input);
return input;
},
});
exports.file = custom({
async parse(input, _, opts) {
if (opts.exists)
return (0, fs_1.fileExists)(input);
return input;
},
});
/**
* Initializes a string as a URL. Throws an error
* if the string is not a valid URL.
*/
exports.url = custom({
async parse(input) {
try {
return new node_url_1.URL(input);
}
catch {
throw new Error(`Expected a valid url but received: ${input}`);
}
},
});
const stringArg = custom({});
exports.string = stringArg;

27
node_modules/@oclif/core/lib/cache.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { Config } from './config/config';
import { OclifConfiguration, Plugin } from './interfaces';
type CacheContents = {
rootPlugin: Plugin;
config: Config;
exitCodes: OclifConfiguration['exitCodes'];
'@oclif/core': OclifCoreInfo;
};
type OclifCoreInfo = {
name: string;
version: string;
};
type ValueOf<T> = T[keyof T];
/**
* A simple cache for storing values that need to be accessed globally.
*/
export default class Cache extends Map<keyof CacheContents, ValueOf<CacheContents>> {
static instance: Cache;
constructor();
static getInstance(): Cache;
get(_key: 'config'): Config | undefined;
get(_key: '@oclif/core'): OclifCoreInfo;
get(_key: 'rootPlugin'): Plugin | undefined;
get(_key: 'exitCodes'): OclifConfiguration['exitCodes'] | undefined;
private getOclifCoreMeta;
}
export {};

40
node_modules/@oclif/core/lib/cache.js generated vendored Normal file
View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
/**
* A simple cache for storing values that need to be accessed globally.
*/
class Cache extends Map {
static instance;
constructor() {
super();
this.set('@oclif/core', this.getOclifCoreMeta());
}
static getInstance() {
if (!Cache.instance) {
Cache.instance = new Cache();
}
return Cache.instance;
}
get(key) {
return super.get(key);
}
getOclifCoreMeta() {
try {
return { name: '@oclif/core', version: require('@oclif/core/package.json').version };
}
catch {
try {
return {
name: '@oclif/core',
version: JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, '..', 'package.json'), 'utf8')).version,
};
}
catch {
return { name: '@oclif/core', version: 'unknown' };
}
}
}
}
exports.default = Cache;

191
node_modules/@oclif/core/lib/command.d.ts generated vendored Normal file
View File

@@ -0,0 +1,191 @@
import { Config } from './config';
import { PrettyPrintableError } from './errors';
import { LoadOptions } from './interfaces/config';
import { CommandError } from './interfaces/errors';
import { ArgInput, ArgOutput, ArgProps, BooleanFlagProps, Deprecation, FlagInput, FlagOutput, Arg as IArg, Flag as IFlag, Input, OptionFlagProps, ParserOutput } from './interfaces/parser';
import { Plugin } from './interfaces/plugin';
/**
* An abstract class which acts as the base for each command
* in your project.
*/
export declare abstract class Command {
argv: string[];
config: Config;
private static readonly _base;
/** An array of aliases for this command. */
static aliases: string[];
/** An order-dependent object of arguments for the command */
static args: ArgInput;
static baseFlags: FlagInput;
/**
* Emit deprecation warning when a command alias is used
*/
static deprecateAliases?: boolean;
static deprecationOptions?: Deprecation;
/**
* A full description of how to use the command.
*
* If no summary, the first line of the description will be used as the summary.
*/
static description: string | undefined;
static enableJsonFlag: boolean;
/**
* An array of examples to show at the end of the command's help.
*
* IF only a string is provided, it will try to look for a line that starts
* with the cmd.bin as the example command and the rest as the description.
* If found, the command will be formatted appropriately.
*
* ```
* EXAMPLES:
* A description of a particular use case.
*
* $ <%= config.bin => command flags
* ```
*/
static examples: Command.Example[];
/** A hash of flags for the command */
static flags: FlagInput;
static hasDynamicHelp: boolean;
static help: string | undefined;
/** Hide the command from help */
static hidden: boolean;
/** An array of aliases for this command that are hidden from help. */
static hiddenAliases: string[];
/** A command ID, used mostly in error or verbose reporting. */
static id: string;
static plugin: Plugin | undefined;
static readonly pluginAlias?: string;
static readonly pluginName?: string;
static readonly pluginType?: string;
/** Mark the command as a given state (e.g. beta or deprecated) in help */
static state?: 'beta' | 'deprecated' | string;
/** When set to false, allows a variable amount of arguments */
static strict: boolean;
/**
* The tweet-sized description for your class, used in a parent-commands
* sub-command listing and as the header for the command help.
*/
static summary?: string;
/**
* An override string (or strings) for the default usage documentation.
*/
static usage: string | string[] | undefined;
protected debug: (...args: any[]) => void;
id: string | undefined;
parsed: boolean;
constructor(argv: string[], config: Config);
/**
* instantiate and run the command
*
* @param {Command.Class} this - the command class
* @param {string[]} argv argv
* @param {LoadOptions} opts options
* @returns {Promise<unknown>} result
*/
static run<T extends Command>(this: new (argv: string[], config: Config) => T, argv?: string[], opts?: LoadOptions): Promise<ReturnType<T['run']>>;
protected get ctor(): typeof Command;
protected _run<T>(): Promise<T>;
protected catch(err: CommandError): Promise<any>;
error(input: Error | string, options: {
code?: string;
exit: false;
} & PrettyPrintableError): void;
error(input: Error | string, options?: {
code?: string;
exit?: number;
} & PrettyPrintableError): never;
exit(code?: number): never;
protected finally(_: Error | undefined): Promise<any>;
protected init(): Promise<any>;
/**
* Determine if the command is being run with the --json flag in a command that supports it.
*
* @returns {boolean} true if the command supports json and the --json flag is present
*/
jsonEnabled(): boolean;
log(message?: string, ...args: any[]): void;
protected logJson(json: unknown): void;
logToStderr(message?: string, ...args: any[]): void;
protected parse<F extends FlagOutput, B extends FlagOutput, A extends ArgOutput>(options?: Input<F, B, A>, argv?: string[]): Promise<ParserOutput<F, B, A>>;
/**
* actual command run code goes here
*/
abstract run(): Promise<any>;
protected toErrorJson(err: unknown): any;
protected toSuccessJson(result: unknown): any;
warn(input: Error | string): Error | string;
protected warnIfCommandDeprecated(): void;
protected warnIfFlagDeprecated(flags: Record<string, unknown>): void;
private removeEnvVar;
}
export declare namespace Command {
/**
* The Command class exported by a command file.
*/
type Class = typeof Command & {
id: string;
run(argv?: string[], config?: LoadOptions): Promise<any>;
};
/**
* A cached command that's had a `load` method attached to it.
*
* The `Plugin` class loads the commands from the manifest (if it exists) or requires and caches
* the commands directly from the commands directory inside the plugin. At this point the plugin
* is working with `Command.Cached`. It then appends a `load` method to each one. If the a command
* is executed then the `load` method is used to require the command class.
*/
type Loadable = Cached & {
load(): Promise<Command.Class>;
};
/**
* A cached version of the command. This is created by the cachedCommand utility and
* stored in the oclif.manifest.json.
*/
type Cached = {
[key: string]: unknown;
aliasPermutations?: string[] | undefined;
aliases: string[];
args: {
[name: string]: Arg.Cached;
};
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 | 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;
};
type Flag = IFlag<any>;
namespace Flag {
type Cached = Omit<Flag, 'input' | 'parse'> & (BooleanFlagProps | OptionFlagProps) & {
hasDynamicHelp?: boolean | undefined;
};
type Any = Cached | Flag;
}
type Arg = IArg<any>;
namespace Arg {
type Cached = Omit<Arg, 'input' | 'parse'> & ArgProps;
type Any = Arg | Cached;
}
type Example = {
command: string;
description: string;
} | string;
}

343
node_modules/@oclif/core/lib/command.js generated vendored Normal file
View File

@@ -0,0 +1,343 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Command = void 0;
const node_url_1 = require("node:url");
const node_util_1 = require("node:util");
const cache_1 = __importDefault(require("./cache"));
const config_1 = require("./config");
const Errors = __importStar(require("./errors"));
const util_1 = require("./help/util");
const logger_1 = require("./logger");
const Parser = __importStar(require("./parser"));
const aggregate_flags_1 = require("./util/aggregate-flags");
const ids_1 = require("./util/ids");
const util_2 = require("./util/util");
const ux_1 = require("./ux");
const pjson = cache_1.default.getInstance().get('@oclif/core');
/**
* swallows stdout epipe errors
* this occurs when stdout closes such as when piping to head
*/
process.stdout.on('error', (err) => {
if (err && err.code === 'EPIPE')
return;
throw err;
});
/**
* An abstract class which acts as the base for each command
* in your project.
*/
class Command {
argv;
config;
static _base = `${pjson.name}@${pjson.version}`;
/** An array of aliases for this command. */
static aliases = [];
/** An order-dependent object of arguments for the command */
static args = {};
static baseFlags;
/**
* Emit deprecation warning when a command alias is used
*/
static deprecateAliases;
static deprecationOptions;
/**
* A full description of how to use the command.
*
* If no summary, the first line of the description will be used as the summary.
*/
static description;
static enableJsonFlag = false;
/**
* An array of examples to show at the end of the command's help.
*
* IF only a string is provided, it will try to look for a line that starts
* with the cmd.bin as the example command and the rest as the description.
* If found, the command will be formatted appropriately.
*
* ```
* EXAMPLES:
* A description of a particular use case.
*
* $ <%= config.bin => command flags
* ```
*/
static examples;
/** A hash of flags for the command */
static flags;
static hasDynamicHelp = false;
static help;
/** Hide the command from help */
static hidden;
/** An array of aliases for this command that are hidden from help. */
static hiddenAliases = [];
/** A command ID, used mostly in error or verbose reporting. */
static id;
static plugin;
static pluginAlias;
static pluginName;
static pluginType;
/** Mark the command as a given state (e.g. beta or deprecated) in help */
static state;
/** When set to false, allows a variable amount of arguments */
static strict = true;
/**
* The tweet-sized description for your class, used in a parent-commands
* sub-command listing and as the header for the command help.
*/
static summary;
/**
* An override string (or strings) for the default usage documentation.
*/
static usage;
debug;
id;
parsed = false;
constructor(argv, config) {
this.argv = argv;
this.config = config;
this.id = this.ctor.id;
try {
this.debug = (0, logger_1.makeDebug)(this.id ? `${this.config.bin}:${this.id}` : this.config.bin);
}
catch {
this.debug = () => {
// noop
};
}
}
/**
* instantiate and run the command
*
* @param {Command.Class} this - the command class
* @param {string[]} argv argv
* @param {LoadOptions} opts options
* @returns {Promise<unknown>} result
*/
static async run(argv, opts) {
if (!argv)
argv = process.argv.slice(2);
// Handle the case when a file URL string is passed in such as 'import.meta.url'; covert to file path.
if (typeof opts === 'string' && opts.startsWith('file://')) {
opts = (0, node_url_1.fileURLToPath)(opts);
}
const config = await config_1.Config.load(opts || require.main?.filename || __dirname);
const cache = cache_1.default.getInstance();
if (!cache.has('config'))
cache.set('config', config);
const cmd = new this(argv, config);
if (!cmd.id) {
const id = cmd.constructor.name.toLowerCase();
cmd.id = id;
cmd.ctor.id = id;
}
return cmd._run();
}
get ctor() {
return this.constructor;
}
async _run() {
let err;
let result;
try {
// remove redirected env var to allow subsessions to run autoupdated client
this.removeEnvVar('REDIRECTED');
await this.init();
result = await this.run();
}
catch (error) {
err = error;
await this.catch(error);
}
finally {
await this.finally(err);
}
if (result && this.jsonEnabled())
this.logJson(this.toSuccessJson(result));
if (!this.parsed && !(0, util_2.isProd)()) {
process.emitWarning(`Command ${this.id} did not parse its arguments. Did you forget to call 'this.parse'?`, {
code: 'UnparsedCommand',
});
}
return result;
}
async catch(err) {
process.exitCode = process.exitCode ?? err.exitCode ?? 1;
if (this.jsonEnabled()) {
this.logJson(this.toErrorJson(err));
}
else {
if (!err.message)
throw err;
try {
ux_1.ux.action.stop(ux_1.ux.colorize('bold', ux_1.ux.colorize('red', '!')));
}
catch { }
throw err;
}
}
error(input, options = {}) {
return Errors.error(input, options);
}
exit(code = 0) {
Errors.exit(code);
}
async finally(_) { }
async init() {
this.debug('init version: %s argv: %o', this.ctor._base, this.argv);
const g = globalThis;
g['http-call'] = g['http-call'] || {};
g['http-call'].userAgent = this.config.userAgent;
this.warnIfCommandDeprecated();
}
/**
* Determine if the command is being run with the --json flag in a command that supports it.
*
* @returns {boolean} true if the command supports json and the --json flag is present
*/
jsonEnabled() {
// If the command doesn't support json, return false
if (!this.ctor?.enableJsonFlag)
return false;
// If the CONTENT_TYPE env var is set to json, return true
if (this.config.scopedEnvVar?.('CONTENT_TYPE')?.toLowerCase() === 'json')
return true;
const passThroughIndex = this.argv.indexOf('--');
const jsonIndex = this.argv.indexOf('--json');
return passThroughIndex === -1
? // If '--' is not present, then check for `--json` in this.argv
jsonIndex !== -1
: // If '--' is present, return true only the --json flag exists and is before the '--'
jsonIndex !== -1 && jsonIndex < passThroughIndex;
}
log(message = '', ...args) {
if (!this.jsonEnabled()) {
message = typeof message === 'string' ? message : (0, node_util_1.inspect)(message);
ux_1.ux.stdout(message, ...args);
}
}
logJson(json) {
ux_1.ux.stdout(ux_1.ux.colorizeJson(json, { pretty: true, theme: this.config.theme?.json }));
}
logToStderr(message = '', ...args) {
if (!this.jsonEnabled()) {
message = typeof message === 'string' ? message : (0, node_util_1.inspect)(message);
ux_1.ux.stderr(message, ...args);
}
}
async parse(options, argv = this.argv) {
if (!options)
options = this.ctor;
const opts = {
context: this,
...options,
flags: (0, aggregate_flags_1.aggregateFlags)(options.flags, options.baseFlags, options.enableJsonFlag),
};
const hookResult = await this.config.runHook('preparse', { argv: [...argv], options: opts });
// Since config.runHook will only run the hook for the root plugin, hookResult.successes will always have a length of 0 or 1
// But to be extra safe, we find the result that matches the root plugin.
const argvToParse = hookResult.successes?.length
? (hookResult.successes.find((s) => s.plugin.root === cache_1.default.getInstance().get('rootPlugin')?.root)?.result ??
argv)
: argv;
this.argv = [...argvToParse];
const results = await Parser.parse(argvToParse, opts);
this.warnIfFlagDeprecated(results.flags ?? {});
this.parsed = true;
return results;
}
toErrorJson(err) {
return { error: err };
}
toSuccessJson(result) {
return result;
}
warn(input) {
if (!this.jsonEnabled())
Errors.warn(input);
return input;
}
warnIfCommandDeprecated() {
const [id] = (0, util_1.normalizeArgv)(this.config);
if (this.ctor.deprecateAliases && this.ctor.aliases.includes(id)) {
const cmdName = (0, ids_1.toConfiguredId)(this.ctor.id, this.config);
const aliasName = (0, ids_1.toConfiguredId)(id, this.config);
this.warn((0, util_1.formatCommandDeprecationWarning)(aliasName, { to: cmdName }));
}
if (this.ctor.state === 'deprecated') {
const cmdName = (0, ids_1.toConfiguredId)(this.ctor.id, this.config);
this.warn((0, util_1.formatCommandDeprecationWarning)(cmdName, this.ctor.deprecationOptions));
}
}
warnIfFlagDeprecated(flags) {
const allFlags = (0, aggregate_flags_1.aggregateFlags)(this.ctor.flags, this.ctor.baseFlags, this.ctor.enableJsonFlag);
for (const flag of Object.keys(flags)) {
const flagDef = allFlags[flag];
const deprecated = flagDef?.deprecated;
if (deprecated) {
this.warn((0, util_1.formatFlagDeprecationWarning)(flag, deprecated));
}
const deprecateAliases = flagDef?.deprecateAliases;
if (deprecateAliases) {
const aliases = (0, util_2.uniq)([...(flagDef?.aliases ?? []), ...(flagDef?.charAliases ?? [])]).map((a) => a.length === 1 ? `-${a}` : `--${a}`);
if (aliases.length === 0)
return;
const foundAliases = aliases.filter((alias) => this.argv.includes(alias));
for (const alias of foundAliases) {
let preferredUsage = `--${flagDef?.name}`;
if (flagDef?.char) {
preferredUsage += ` | -${flagDef?.char}`;
}
this.warn((0, util_1.formatFlagDeprecationWarning)(alias, { to: preferredUsage }));
}
}
}
}
removeEnvVar(envVar) {
const keys = [];
try {
keys.push(...this.config.scopedEnvVarKeys(envVar));
}
catch {
keys.push(this.config.scopedEnvVarKey(envVar));
}
keys.map((key) => delete process.env[key]);
}
}
exports.Command = Command;

136
node_modules/@oclif/core/lib/config/config.d.ts generated vendored Normal file
View File

@@ -0,0 +1,136 @@
import { Command } from '../command';
import { Hook, Hooks, OclifConfiguration, 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';
export declare class Config implements IConfig {
options: Options;
arch: ArchTypes;
bin: string;
binAliases?: string[] | undefined;
binPath?: string | undefined;
cacheDir: string;
channel: string;
configDir: string;
dataDir: string;
dirname: string;
flexibleTaxonomy: boolean;
home: string;
isSingleCommandCLI: boolean;
name: string;
npmRegistry?: string | undefined;
nsisCustomization?: string | undefined;
pjson: PJSON;
platform: PlatformTypes;
plugins: Map<string, IPlugin>;
root: string;
shell: string;
theme?: Theme | undefined;
topicSeparator: ' ' | ':';
updateConfig: NonNullable<OclifConfiguration['update']>;
userAgent: string;
userPJSON?: UserPJSON | undefined;
valid: boolean;
version: string;
protected warned: boolean;
windows: boolean;
private _base;
private _commandIDs;
private _commands;
private _topics;
private commandPermutations;
private pluginLoader;
private rootPlugin;
private topicPermutations;
constructor(options: Options);
static load(opts?: LoadOptions): Promise<Config>;
get commandIDs(): string[];
get commands(): Command.Loadable[];
protected get isProd(): boolean;
static get rootPlugin(): IPlugin | undefined;
get topics(): Topic[];
get versionDetails(): VersionDetails;
protected _shell(): string;
protected dir(category: 'cache' | 'config' | 'data'): string;
findCommand(id: string, opts: {
must: true;
}): Command.Loadable;
findCommand(id: string, opts?: {
must: boolean;
}): Command.Loadable | undefined;
/**
* Find all command ids that include the provided command id.
*
* For example, if the command ids are:
* - foo:bar:baz
* - one:two:three
*
* `bar` would return `foo:bar:baz`
*
* @param partialCmdId string
* @param argv string[] process.argv containing the flags and arguments provided by the user
* @returns string[]
*/
findMatches(partialCmdId: string, argv: string[]): Command.Loadable[];
findTopic(id: string, opts: {
must: true;
}): Topic;
findTopic(id: string, opts?: {
must: boolean;
}): Topic | undefined;
/**
* Returns an array of all command ids. If flexible taxonomy is enabled then all permutations will be appended to the array.
* @returns string[]
*/
getAllCommandIDs(): string[];
/**
* Returns an array of all commands. If flexible taxonomy is enabled then all permutations will be appended to the array.
* @returns Command.Loadable[]
*/
getAllCommands(): Command.Loadable[];
getPluginsList(): IPlugin[];
load(): Promise<void>;
loadPluginsAndCommands(opts?: {
force: boolean;
}): Promise<void>;
loadTheme(): Promise<Theme | undefined>;
protected macosCacheDir(): string | undefined;
runCommand<T = unknown>(id: string, argv?: string[], cachedCommand?: Command.Loadable | null): Promise<T>;
runHook<T extends keyof Hooks, P extends Hooks = Hooks>(event: T, opts: P[T]['options'], timeout?: number, captureErrors?: boolean): Promise<Hook.Result<P[T]['return']>>;
s3Key(type: keyof S3Templates, ext?: '.tar.gz' | '.tar.xz' | IConfig.s3Key.Options, options?: IConfig.s3Key.Options): string;
s3Url(key: string): string;
scopedEnvVar(k: string): string | undefined;
/**
* this DOES NOT account for bin aliases, use scopedEnvVarKeys instead which will account for bin aliases
* @param k {string}, the unscoped key you want to get the value for
* @returns {string} returns the env var key
*/
scopedEnvVarKey(k: string): string;
/**
* gets the scoped env var keys for a given key, including bin aliases
* @param k {string}, the env key e.g. 'debug'
* @returns {string[]} e.g. ['SF_DEBUG', 'SFDX_DEBUG']
*/
scopedEnvVarKeys(k: string): string[];
scopedEnvVarTrue(k: string): boolean;
protected windowsHome(): string | undefined;
protected windowsHomedriveHome(): string | undefined;
protected windowsUserprofileHome(): string | undefined;
private buildS3Config;
private getCmdLookupId;
private getTopicLookupId;
/**
* Insert legacy plugins
*
* Replace invalid CLI plugins (cli-engine plugins, mostly Heroku) loaded via `this.loadPlugins`
* with oclif-compatible ones returned by @oclif/plugin-legacy init hook.
*
* @param plugins array of oclif-compatible plugins
*/
private insertLegacyPlugins;
private isJitPluginCommand;
private loadCommands;
private loadTopics;
private maybeAdjustDebugSetting;
private warn;
}

816
node_modules/@oclif/core/lib/config/config.js generated vendored Normal file
View File

@@ -0,0 +1,816 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Config = void 0;
const ejs = __importStar(require("ejs"));
const is_wsl_1 = __importDefault(require("is-wsl"));
const node_os_1 = require("node:os");
const node_path_1 = require("node:path");
const node_url_1 = require("node:url");
const cache_1 = __importDefault(require("../cache"));
const errors_1 = require("../errors");
const util_1 = require("../help/util");
const logger_1 = require("../logger");
const module_loader_1 = require("../module-loader");
const performance_1 = require("../performance");
const settings_1 = require("../settings");
const determine_priority_1 = require("../util/determine-priority");
const fs_1 = require("../util/fs");
const ids_1 = require("../util/ids");
const os_1 = require("../util/os");
const util_2 = require("../util/util");
const ux_1 = require("../ux");
const theme_1 = require("../ux/theme");
const plugin_loader_1 = __importDefault(require("./plugin-loader"));
const ts_path_1 = require("./ts-path");
const util_3 = require("./util");
const debug = (0, util_3.makeDebug)();
const _pjson = cache_1.default.getInstance().get('@oclif/core');
const BASE = `${_pjson.name}@${_pjson.version}`;
const ROOT_ONLY_HOOKS = new Set(['preparse']);
function displayWarnings() {
if (process.listenerCount('warning') > 1)
return;
process.on('warning', (warning) => {
console.error(warning.stack);
if (warning.detail)
console.error(warning.detail);
});
}
function channelFromVersion(version) {
const m = version.match(/[^-]+(?:-([^.]+))?/);
return (m && m[1]) || 'stable';
}
function isConfig(o) {
return o && Boolean(o._base);
}
class Permutations extends Map {
validPermutations = new Map();
add(permutation, commandId) {
this.validPermutations.set(permutation, commandId);
for (const id of (0, util_3.collectUsableIds)([permutation])) {
if (this.has(id)) {
this.set(id, this.get(id).add(commandId));
}
else {
this.set(id, new Set([commandId]));
}
}
}
get(key) {
return super.get(key) ?? new Set();
}
getAllValid() {
return [...this.validPermutations.keys()];
}
getValid(key) {
return this.validPermutations.get(key);
}
hasValid(key) {
return this.validPermutations.has(key);
}
}
class Config {
options;
arch;
bin;
binAliases;
binPath;
cacheDir;
channel;
configDir;
dataDir;
dirname;
flexibleTaxonomy;
home;
isSingleCommandCLI = false;
name;
npmRegistry;
nsisCustomization;
pjson;
platform;
plugins = new Map();
root;
shell;
theme;
topicSeparator = ':';
updateConfig;
userAgent;
userPJSON;
valid;
version;
warned = false;
windows;
_base = BASE;
_commandIDs;
_commands = new Map();
_topics = new Map();
commandPermutations = new Permutations();
pluginLoader;
rootPlugin;
topicPermutations = new Permutations();
constructor(options) {
this.options = options;
}
static async load(opts = module.filename || __dirname) {
(0, logger_1.setLogger)(opts);
// Handle the case when a file URL string is passed in such as 'import.meta.url'; covert to file path.
if (typeof opts === 'string' && opts.startsWith('file://')) {
opts = (0, node_url_1.fileURLToPath)(opts);
}
if (typeof opts === 'string')
opts = { root: opts };
if (isConfig(opts)) {
/**
* Reload the Config based on the version required by the command.
* This is needed because the command is given the Config instantiated
* by the root plugin, which may be a different version than the one
* required by the command.
*
* Doing this ensures that the command can freely use any method on Config that
* exists in the version of Config required by the command but may not exist on the
* root's instance of Config.
*/
if (BASE !== opts._base) {
debug(`reloading config from ${opts._base} to ${BASE}`);
const config = new Config({ ...opts.options, plugins: opts.plugins });
await config.load();
return config;
}
return opts;
}
const config = new Config(opts);
await config.load();
return config;
}
get commandIDs() {
if (this._commandIDs)
return this._commandIDs;
this._commandIDs = this.commands.map((c) => c.id);
return this._commandIDs;
}
get commands() {
return [...this._commands.values()];
}
get isProd() {
return (0, util_2.isProd)();
}
static get rootPlugin() {
return this.rootPlugin;
}
get topics() {
return [...this._topics.values()];
}
get versionDetails() {
const [cliVersion, architecture, nodeVersion] = this.userAgent.split(' ');
return {
architecture,
cliVersion,
nodeVersion,
osVersion: `${(0, node_os_1.type)()} ${(0, node_os_1.release)()}`,
pluginVersions: Object.fromEntries([...this.plugins.values()].map((p) => [p.name, { root: p.root, type: p.type, version: p.version }])),
rootPath: this.root,
shell: this.shell,
};
}
_shell() {
let shellPath;
const { COMSPEC } = process.env;
const SHELL = process.env.SHELL ?? (0, node_os_1.userInfo)().shell?.split(node_path_1.sep)?.pop();
if (SHELL) {
shellPath = SHELL.split('/');
}
else if (this.windows && process.title.toLowerCase().includes('powershell')) {
shellPath = ['powershell'];
}
else if (this.windows && process.title.toLowerCase().includes('command prompt')) {
shellPath = ['cmd.exe'];
}
else if (this.windows && COMSPEC) {
shellPath = COMSPEC.split(/\\|\//);
}
else {
shellPath = ['unknown'];
}
return shellPath.at(-1) ?? 'unknown';
}
dir(category) {
const base = process.env[`XDG_${category.toUpperCase()}_HOME`] ||
(this.windows && process.env.LOCALAPPDATA) ||
(0, node_path_1.join)(this.home, category === 'data' ? '.local/share' : '.' + category);
return (0, node_path_1.join)(base, this.dirname);
}
findCommand(id, opts = {}) {
const lookupId = this.getCmdLookupId(id);
const command = this._commands.get(lookupId);
if (opts.must && !command)
(0, errors_1.error)(`command ${lookupId} not found`);
return command;
}
/**
* Find all command ids that include the provided command id.
*
* For example, if the command ids are:
* - foo:bar:baz
* - one:two:three
*
* `bar` would return `foo:bar:baz`
*
* @param partialCmdId string
* @param argv string[] process.argv containing the flags and arguments provided by the user
* @returns string[]
*/
findMatches(partialCmdId, argv) {
const flags = argv
.filter((arg) => !(0, util_1.getHelpFlagAdditions)(this).includes(arg) && arg.startsWith('-'))
.map((a) => a.replaceAll('-', ''));
const possibleMatches = [...this.commandPermutations.get(partialCmdId)].map((k) => this._commands.get(k));
const matches = possibleMatches.filter((command) => {
const cmdFlags = Object.entries(command.flags).flatMap(([flag, def]) => def.char ? [def.char, flag] : [flag]);
// A command is a match if the provided flags belong to the full command
return flags.every((f) => cmdFlags.includes(f));
});
return matches;
}
findTopic(name, opts = {}) {
const lookupId = this.getTopicLookupId(name);
const topic = this._topics.get(lookupId);
if (topic)
return topic;
if (opts.must)
throw new Error(`topic ${name} not found`);
}
/**
* Returns an array of all command ids. If flexible taxonomy is enabled then all permutations will be appended to the array.
* @returns string[]
*/
getAllCommandIDs() {
return this.getAllCommands().map((c) => c.id);
}
/**
* Returns an array of all commands. If flexible taxonomy is enabled then all permutations will be appended to the array.
* @returns Command.Loadable[]
*/
getAllCommands() {
const commands = [...this._commands.values()];
const validPermutations = [...this.commandPermutations.getAllValid()];
for (const permutation of validPermutations) {
if (!this._commands.has(permutation)) {
const cmd = this._commands.get(this.getCmdLookupId(permutation));
commands.push({ ...cmd, id: permutation });
}
}
return commands;
}
getPluginsList() {
return [...this.plugins.values()];
}
// eslint-disable-next-line complexity
async load() {
settings_1.settings.performanceEnabled =
(settings_1.settings.performanceEnabled === undefined ? this.options.enablePerf : settings_1.settings.performanceEnabled) ?? false;
if (settings_1.settings.debug)
displayWarnings();
(0, logger_1.setLogger)(this.options);
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, 'config.load');
this.pluginLoader = new plugin_loader_1.default({ plugins: this.options.plugins, root: this.options.root });
this.rootPlugin = await this.pluginLoader.loadRoot({ pjson: this.options.pjson });
// Cache the root plugin so that we can reference it later when determining if
// we should skip ts-node registration for an ESM plugin.
const cache = cache_1.default.getInstance();
cache.set('rootPlugin', this.rootPlugin);
cache.set('exitCodes', this.rootPlugin.pjson.oclif.exitCodes ?? {});
this.root = this.rootPlugin.root;
this.pjson = this.rootPlugin.pjson;
this.plugins.set(this.rootPlugin.name, this.rootPlugin);
this.root = this.rootPlugin.root;
this.pjson = this.rootPlugin.pjson;
this.name = this.pjson.name;
this.version = this.options.version || this.pjson.version || '0.0.0';
this.channel = this.options.channel || channelFromVersion(this.version);
this.valid = this.rootPlugin.valid;
this.arch = (0, node_os_1.arch)() === 'ia32' ? 'x86' : (0, node_os_1.arch)();
this.platform = is_wsl_1.default ? 'wsl' : (0, os_1.getPlatform)();
this.windows = this.platform === 'win32';
this.bin = this.pjson.oclif.bin || this.name;
this.binAliases = this.pjson.oclif.binAliases;
this.nsisCustomization = this.pjson.oclif.nsisCustomization;
this.dirname = this.pjson.oclif.dirname || this.name;
this.flexibleTaxonomy = this.pjson.oclif.flexibleTaxonomy || false;
// currently, only colons or spaces are valid separators
if (this.pjson.oclif.topicSeparator && [' ', ':'].includes(this.pjson.oclif.topicSeparator))
this.topicSeparator = this.pjson.oclif.topicSeparator;
if (this.platform === 'win32')
this.dirname = this.dirname.replace('/', '\\');
this.userAgent = `${this.name}/${this.version} ${this.platform}-${this.arch} node-${process.version}`;
this.shell = this._shell();
this.home = process.env.HOME || (this.windows && this.windowsHome()) || (0, os_1.getHomeDir)() || (0, node_os_1.tmpdir)();
this.cacheDir = this.scopedEnvVar('CACHE_DIR') || this.macosCacheDir() || this.dir('cache');
this.configDir = this.scopedEnvVar('CONFIG_DIR') || this.dir('config');
this.dataDir = this.scopedEnvVar('DATA_DIR') || this.dir('data');
this.binPath = this.scopedEnvVar('BINPATH');
this.npmRegistry = this.scopedEnvVar('NPM_REGISTRY') || this.pjson.oclif.npmRegistry;
this.theme = await this.loadTheme();
this.updateConfig = {
...this.pjson.oclif.update,
node: this.pjson.oclif.update?.node ?? {},
s3: this.buildS3Config(),
};
this.isSingleCommandCLI = Boolean(typeof this.pjson.oclif.commands !== 'string' &&
this.pjson.oclif.commands?.strategy === 'single' &&
this.pjson.oclif.commands?.target);
this.maybeAdjustDebugSetting();
await this.loadPluginsAndCommands();
debug('config done');
marker?.addDetails({
commandPermutations: this.commands.length,
commands: [...this.plugins.values()].reduce((acc, p) => acc + p.commands.length, 0),
plugins: this.plugins.size,
topics: this.topics.length,
});
marker?.stop();
}
async loadPluginsAndCommands(opts) {
const pluginsMarker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, 'config.loadAllPlugins');
const { errors, plugins } = await this.pluginLoader.loadChildren({
dataDir: this.dataDir,
devPlugins: this.options.devPlugins,
force: opts?.force ?? false,
pluginAdditions: this.options.pluginAdditions,
rootPlugin: this.rootPlugin,
userPlugins: this.options.userPlugins,
});
this.plugins = plugins;
pluginsMarker?.stop();
const commandsMarker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, 'config.loadAllCommands');
for (const plugin of this.plugins.values()) {
this.loadCommands(plugin);
this.loadTopics(plugin);
}
commandsMarker?.stop();
for (const error of errors) {
this.warn(error);
}
}
async loadTheme() {
if (this.scopedEnvVarTrue('DISABLE_THEME'))
return;
const userThemeFile = (0, node_path_1.resolve)(this.configDir, 'theme.json');
const getDefaultTheme = async () => {
if (!this.pjson.oclif.theme)
return;
if (typeof this.pjson.oclif.theme === 'string') {
return (0, fs_1.safeReadJson)((0, node_path_1.resolve)(this.root, this.pjson.oclif.theme));
}
return this.pjson.oclif.theme;
};
const [defaultTheme, userTheme] = await Promise.all([
getDefaultTheme(),
(0, fs_1.safeReadJson)(userThemeFile),
]);
// Merge the default theme with the user theme, giving the user theme precedence.
const merged = { ...defaultTheme, ...userTheme };
return Object.keys(merged).length > 0 ? (0, theme_1.parseTheme)(merged) : undefined;
}
macosCacheDir() {
return (this.platform === 'darwin' && (0, node_path_1.join)(this.home, 'Library', 'Caches', this.dirname)) || undefined;
}
async runCommand(id, argv = [], cachedCommand = null) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `config.runCommand#${id}`);
debug('runCommand %s %o', id, argv);
let c = cachedCommand ?? this.findCommand(id);
if (!c) {
const matches = this.flexibleTaxonomy ? this.findMatches(id, argv) : [];
const hookResult = this.flexibleTaxonomy && matches.length > 0
? await this.runHook('command_incomplete', { argv, id, matches })
: await this.runHook('command_not_found', { argv, id });
if (hookResult.successes[0])
return hookResult.successes[0].result;
if (hookResult.failures[0])
throw hookResult.failures[0].error;
throw new errors_1.CLIError(`command ${id} not found`);
}
if (this.isJitPluginCommand(c)) {
const pluginName = c.pluginName;
const pluginVersion = this.pjson.oclif.jitPlugins[pluginName];
const jitResult = await this.runHook('jit_plugin_not_installed', {
argv,
command: c,
id,
pluginName,
pluginVersion,
});
if (jitResult.failures[0])
throw jitResult.failures[0].error;
if (jitResult.successes[0]) {
await this.loadPluginsAndCommands({ force: true });
c = this.findCommand(id) ?? c;
}
else {
// this means that no jit_plugin_not_installed hook exists, so we should run the default behavior
const result = await this.runHook('command_not_found', { argv, id });
if (result.successes[0])
return result.successes[0].result;
if (result.failures[0])
throw result.failures[0].error;
throw new errors_1.CLIError(`command ${id} not found`);
}
}
const command = await c.load();
await this.runHook('prerun', { argv, Command: command });
const result = (await command.run(argv, this));
// If plugins:uninstall was run, we need to remove all the uninstalled plugins
// from this.plugins so that the postrun hook doesn't attempt to run any
// hooks that might have existed in the uninstalled plugins.
if (c.id === 'plugins:uninstall') {
for (const arg of argv)
this.plugins.delete(arg);
}
await this.runHook('postrun', { argv, Command: command, result });
marker?.addDetails({ command: id, plugin: c.pluginName });
marker?.stop();
return result;
}
async runHook(event, opts, timeout, captureErrors) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `config.runHook#${event}`);
debug('start %s hook', event);
const search = (m) => {
if (typeof m === 'function')
return m;
if (m.default && typeof m.default === 'function')
return m.default;
return Object.values(m).find((m) => typeof m === 'function');
};
const withTimeout = async (ms, promise) => {
let id;
const timeout = new Promise((_, reject) => {
id = setTimeout(() => {
reject(new Error(`Timed out after ${ms} ms.`));
}, ms).unref();
});
return Promise.race([promise, timeout]).then((result) => {
clearTimeout(id);
return result;
});
};
const final = {
failures: [],
successes: [],
};
const plugins = ROOT_ONLY_HOOKS.has(event) ? [this.rootPlugin] : [...this.plugins.values()];
const promises = plugins.map(async (p) => {
const debug = (0, logger_1.makeDebug)([p.name, 'hooks', event].join(':'));
const context = {
config: this,
debug,
error(message, options = {}) {
(0, errors_1.error)(message, options);
},
exit(code = 0) {
(0, errors_1.exit)(code);
},
log(message, ...args) {
ux_1.ux.stdout(message, ...args);
},
warn(message) {
(0, errors_1.warn)(message);
},
};
const hooks = p.hooks[event] || [];
for (const hook of hooks) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `config.runHook#${p.name}(${hook.target})`);
try {
/* eslint-disable no-await-in-loop */
const { filePath, isESM, module } = await (0, module_loader_1.loadWithData)(p, await (0, ts_path_1.tsPath)(p.root, hook.target, p));
debug('start', isESM ? '(import)' : '(require)', filePath);
// If no hook is found using the identifier, then we should `search` for the hook but only if the hook identifier is 'default'
// A named identifier (e.g. MY_HOOK) that isn't found indicates that the hook isn't implemented in the plugin.
const hookFn = module[hook.identifier] ?? (hook.identifier === 'default' ? search(module) : undefined);
if (!hookFn) {
debug('No hook found for hook definition:', hook);
continue;
}
const result = timeout
? await withTimeout(timeout, hookFn.call(context, { ...opts, config: this, context }))
: await hookFn.call(context, { ...opts, config: this, context });
final.successes.push({ plugin: p, result });
if (p.name === '@oclif/plugin-legacy' && event === 'init') {
this.insertLegacyPlugins(result);
}
debug('done');
}
catch (error) {
final.failures.push({ error: error, plugin: p });
debug(error);
// Do not throw the error if
// captureErrors is set to true
// error.oclif.exit is undefined or 0
// error.code is MODULE_NOT_FOUND
if (!captureErrors &&
error.oclif?.exit !== undefined &&
error.oclif?.exit !== 0 &&
error.code !== 'MODULE_NOT_FOUND')
throw error;
}
marker?.addDetails({
event,
hook: hook.target,
plugin: p.name,
});
marker?.stop();
}
});
await Promise.all(promises);
debug('%s hook done', event);
marker?.stop();
return final;
}
s3Key(type, ext, options = {}) {
if (typeof ext === 'object')
options = ext;
else if (ext)
options.ext = ext;
const template = this.updateConfig.s3?.templates?.[options.platform ? 'target' : 'vanilla'][type] ?? '';
return ejs.render(template, { ...this, ...options });
}
s3Url(key) {
const { host } = this.updateConfig.s3 ?? { host: undefined };
if (!host)
throw new Error('no s3 host is set');
const url = new node_url_1.URL(host);
url.pathname = (0, node_path_1.join)(url.pathname, key);
return url.toString();
}
scopedEnvVar(k) {
return process.env[this.scopedEnvVarKeys(k).find((k) => process.env[k])];
}
/**
* this DOES NOT account for bin aliases, use scopedEnvVarKeys instead which will account for bin aliases
* @param k {string}, the unscoped key you want to get the value for
* @returns {string} returns the env var key
*/
scopedEnvVarKey(k) {
return [this.bin, k]
.map((p) => p.replaceAll('@', '').replaceAll(/[/-]/g, '_'))
.join('_')
.toUpperCase();
}
/**
* gets the scoped env var keys for a given key, including bin aliases
* @param k {string}, the env key e.g. 'debug'
* @returns {string[]} e.g. ['SF_DEBUG', 'SFDX_DEBUG']
*/
scopedEnvVarKeys(k) {
return [this.bin, ...(this.binAliases ?? [])]
.filter(Boolean)
.map((alias) => [alias.replaceAll('@', '').replaceAll(/[/-]/g, '_'), k].join('_').toUpperCase());
}
scopedEnvVarTrue(k) {
const v = this.scopedEnvVar(k);
return v === '1' || v === 'true';
}
windowsHome() {
return this.windowsHomedriveHome() || this.windowsUserprofileHome();
}
windowsHomedriveHome() {
return process.env.HOMEDRIVE && process.env.HOMEPATH && (0, node_path_1.join)(process.env.HOMEDRIVE, process.env.HOMEPATH);
}
windowsUserprofileHome() {
return process.env.USERPROFILE;
}
buildS3Config() {
const s3 = this.pjson.oclif.update?.s3;
const bucket = this.scopedEnvVar('S3_BUCKET') ?? s3?.bucket;
const host = s3?.host ?? (bucket && `https://${bucket}.s3.amazonaws.com`);
const templates = {
...s3?.templates,
target: {
baseDir: '<%- bin %>',
manifest: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- platform %>-<%- arch %>",
unversioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %>-<%- platform %>-<%- arch %><%- ext %>",
versioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %>-v<%- version %>/<%- bin %>-v<%- version %>-<%- platform %>-<%- arch %><%- ext %>",
...(s3?.templates && s3?.templates.target),
},
vanilla: {
baseDir: '<%- bin %>',
manifest: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %>version",
unversioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %><%- ext %>",
versioned: "<%- channel === 'stable' ? '' : 'channels/' + channel + '/' %><%- bin %>-v<%- version %>/<%- bin %>-v<%- version %><%- ext %>",
...(s3?.templates && s3?.templates.vanilla),
},
};
return {
bucket,
host,
templates,
};
}
getCmdLookupId(id) {
if (this._commands.has(id))
return id;
if (this.commandPermutations.hasValid(id))
return this.commandPermutations.getValid(id);
return id;
}
getTopicLookupId(id) {
if (this._topics.has(id))
return id;
if (this.topicPermutations.hasValid(id))
return this.topicPermutations.getValid(id);
return id;
}
/**
* Insert legacy plugins
*
* Replace invalid CLI plugins (cli-engine plugins, mostly Heroku) loaded via `this.loadPlugins`
* with oclif-compatible ones returned by @oclif/plugin-legacy init hook.
*
* @param plugins array of oclif-compatible plugins
*/
insertLegacyPlugins(plugins) {
for (const plugin of plugins) {
this.plugins.set(plugin.name, plugin);
// Delete all commands from the legacy plugin so that we can re-add them.
// This is necessary because determinePriority will pick the initial
// command that was added, which won't have been converted by PluginLegacy yet.
for (const cmd of plugin.commands ?? []) {
this._commands.delete(cmd.id);
for (const alias of [...(cmd.aliases ?? []), ...(cmd.hiddenAliases ?? [])]) {
this._commands.delete(alias);
}
}
this.loadCommands(plugin);
}
}
isJitPluginCommand(c) {
// Return true if the command's plugin is listed under oclif.jitPlugins AND if the plugin hasn't been loaded to this.plugins
return (Object.keys(this.pjson.oclif.jitPlugins ?? {}).includes(c.pluginName ?? '') &&
Boolean(c?.pluginName && !this.plugins.has(c.pluginName)));
}
loadCommands(plugin) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `config.loadCommands#${plugin.name}`, { plugin: plugin.name });
for (const command of plugin.commands) {
// set canonical command id
if (this._commands.has(command.id)) {
const prioritizedCommand = (0, determine_priority_1.determinePriority)(this.pjson.oclif.plugins ?? [], [
this._commands.get(command.id),
command,
]);
this._commands.set(prioritizedCommand.id, prioritizedCommand);
}
else {
this._commands.set(command.id, command);
}
// v3 moved command id permutations to the manifest, but some plugins may not have
// the new manifest yet. For those, we need to calculate the permutations here.
const permutations = this.flexibleTaxonomy && command.permutations === undefined
? (0, util_3.getCommandIdPermutations)(command.id)
: (command.permutations ?? [command.id]);
// set every permutation
for (const permutation of permutations) {
this.commandPermutations.add(permutation, command.id);
}
const handleAlias = (alias, hidden = false) => {
const aliasWithDefaultTopicSeparator = (0, ids_1.toStandardizedId)(alias, this);
if (this._commands.has(aliasWithDefaultTopicSeparator)) {
const prioritizedCommand = (0, determine_priority_1.determinePriority)(this.pjson.oclif.plugins ?? [], [
this._commands.get(aliasWithDefaultTopicSeparator),
command,
]);
this._commands.set(aliasWithDefaultTopicSeparator, {
...prioritizedCommand,
id: aliasWithDefaultTopicSeparator,
});
}
else {
this._commands.set(aliasWithDefaultTopicSeparator, { ...command, hidden, id: aliasWithDefaultTopicSeparator });
}
// set every permutation of the aliases
// v3 moved command alias permutations to the manifest, but some plugins may not have
// the new manifest yet. For those, we need to calculate the permutations here.
const aliasPermutations = this.flexibleTaxonomy && command.aliasPermutations === undefined
? (0, util_3.getCommandIdPermutations)(aliasWithDefaultTopicSeparator)
: (command.permutations ?? [aliasWithDefaultTopicSeparator]);
// set every permutation
for (const permutation of aliasPermutations) {
this.commandPermutations.add(permutation, command.id);
}
};
// set command aliases
for (const alias of command.aliases ?? []) {
handleAlias(alias);
}
// set hidden command aliases
for (const alias of command.hiddenAliases ?? []) {
handleAlias(alias, true);
}
}
marker?.addDetails({ commandCount: plugin.commands.length });
marker?.stop();
}
loadTopics(plugin) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `config.loadTopics#${plugin.name}`, { plugin: plugin.name });
for (const topic of (0, util_2.compact)(plugin.topics)) {
const existing = this._topics.get(topic.name);
if (existing) {
existing.description = topic.description || existing.description;
existing.hidden = existing.hidden || topic.hidden;
}
else {
this._topics.set(topic.name, topic);
}
const permutations = this.flexibleTaxonomy ? (0, util_3.getCommandIdPermutations)(topic.name) : [topic.name];
for (const permutation of permutations) {
this.topicPermutations.add(permutation, topic.name);
}
}
// Add missing topics for displaying help when partial commands are entered.
for (const c of plugin.commands.filter((c) => !c.hidden)) {
const parts = c.id.split(':');
while (parts.length > 0) {
const name = parts.join(':');
if (name && !this._topics.has(name)) {
this._topics.set(name, { description: c.summary || c.description, name });
}
parts.pop();
}
}
marker?.stop();
}
maybeAdjustDebugSetting() {
if (this.scopedEnvVarTrue('DEBUG')) {
settings_1.settings.debug = true;
displayWarnings();
}
}
warn(err, scope) {
if (this.warned)
return;
if (typeof err === 'string') {
process.emitWarning(err);
return;
}
if (err instanceof Error) {
const modifiedErr = err;
modifiedErr.name = `${err.name} Plugin: ${this.name}`;
modifiedErr.detail = (0, util_2.compact)([
err.detail,
`module: ${this._base}`,
scope && `task: ${scope}`,
`plugin: ${this.name}`,
`root: ${this.root}`,
'See more details with DEBUG=*',
]).join('\n');
process.emitWarning(err);
return;
}
// err is an object
process.emitWarning('Config.warn expected either a string or Error, but instead received an object');
err.name = `${err.name} Plugin: ${this.name}`;
err.detail = (0, util_2.compact)([
err.detail,
`module: ${this._base}`,
scope && `task: ${scope}`,
`plugin: ${this.name}`,
`root: ${this.root}`,
'See more details with DEBUG=*',
]).join('\n');
process.emitWarning(JSON.stringify(err));
}
}
exports.Config = Config;

3
node_modules/@oclif/core/lib/config/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export { Config } from './config';
export { Plugin } from './plugin';
export { tsPath } from './ts-path';

9
node_modules/@oclif/core/lib/config/index.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tsPath = exports.Plugin = exports.Config = void 0;
var config_1 = require("./config");
Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return config_1.Config; } });
var plugin_1 = require("./plugin");
Object.defineProperty(exports, "Plugin", { enumerable: true, get: function () { return plugin_1.Plugin; } });
var ts_path_1 = require("./ts-path");
Object.defineProperty(exports, "tsPath", { enumerable: true, get: function () { return ts_path_1.tsPath; } });

38
node_modules/@oclif/core/lib/config/plugin-loader.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
import { PJSON } from '../interfaces';
import { Plugin as IPlugin } from '../interfaces/plugin';
type PluginLoaderOptions = {
plugins?: IPlugin[] | PluginsMap | undefined;
root: string;
};
type LoadOpts = {
dataDir: string;
devPlugins?: boolean | undefined;
force?: boolean | undefined;
rootPlugin: IPlugin;
userPlugins?: boolean | undefined;
pluginAdditions?: {
core?: string[];
dev?: string[];
path?: string;
} | undefined;
};
type PluginsMap = Map<string, IPlugin>;
export default class PluginLoader {
options: PluginLoaderOptions;
errors: (Error | string)[];
plugins: PluginsMap;
private pluginsProvided;
constructor(options: PluginLoaderOptions);
loadChildren(opts: LoadOpts): Promise<{
errors: (Error | string)[];
plugins: PluginsMap;
}>;
loadRoot({ pjson }: {
pjson?: PJSON | undefined;
}): Promise<IPlugin>;
private loadCorePlugins;
private loadDevPlugins;
private loadPlugins;
private loadUserPlugins;
}
export {};

188
node_modules/@oclif/core/lib/config/plugin-loader.js generated vendored Normal file
View File

@@ -0,0 +1,188 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const minimatch_1 = require("minimatch");
const node_path_1 = require("node:path");
const performance_1 = require("../performance");
const fs_1 = require("../util/fs");
const util_1 = require("../util/util");
const plugin_1 = require("./plugin");
const util_2 = require("./util");
const debug = (0, util_2.makeDebug)();
function findMatchingDependencies(dependencies, patterns) {
return Object.keys(dependencies).filter((p) => patterns.some((w) => (0, minimatch_1.minimatch)(p, w)));
}
class PluginLoader {
options;
errors = [];
plugins = new Map();
pluginsProvided = false;
constructor(options) {
this.options = options;
if (options.plugins) {
this.pluginsProvided = true;
this.plugins = Array.isArray(options.plugins) ? new Map(options.plugins.map((p) => [p.name, p])) : options.plugins;
}
}
async loadChildren(opts) {
if (!this.pluginsProvided || opts.force) {
await this.loadUserPlugins(opts);
await this.loadDevPlugins(opts);
await this.loadCorePlugins(opts);
}
return { errors: this.errors, plugins: this.plugins };
}
async loadRoot({ pjson }) {
let rootPlugin;
if (this.pluginsProvided) {
const plugins = [...this.plugins.values()];
rootPlugin = plugins.find((p) => p.root === this.options.root) ?? plugins[0];
}
else {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, 'plugin.load#root');
rootPlugin = new plugin_1.Plugin({ isRoot: true, pjson, root: this.options.root });
await rootPlugin.load();
marker?.addDetails({
commandCount: rootPlugin.commands.length,
hasManifest: rootPlugin.hasManifest ?? false,
name: rootPlugin.name,
topicCount: rootPlugin.topics.length,
type: rootPlugin.type,
usesMain: Boolean(rootPlugin.pjson.main),
});
marker?.stop();
}
this.plugins.set(rootPlugin.name, rootPlugin);
return rootPlugin;
}
async loadCorePlugins(opts) {
const { plugins: corePlugins } = opts.rootPlugin.pjson.oclif;
if (corePlugins) {
const plugins = findMatchingDependencies(opts.rootPlugin.pjson.dependencies ?? {}, corePlugins);
await this.loadPlugins(opts.rootPlugin.root, 'core', plugins);
}
const { core: pluginAdditionsCore, path } = opts.pluginAdditions ?? { core: [] };
if (pluginAdditionsCore) {
if (path) {
// If path is provided, load plugins from the path
const pjson = await (0, fs_1.readJson)((0, node_path_1.join)(path, 'package.json'));
const plugins = findMatchingDependencies(pjson.dependencies ?? {}, pluginAdditionsCore);
await this.loadPlugins(path, 'core', plugins);
}
else {
const plugins = findMatchingDependencies(opts.rootPlugin.pjson.dependencies ?? {}, pluginAdditionsCore);
await this.loadPlugins(opts.rootPlugin.root, 'core', plugins);
}
}
}
async loadDevPlugins(opts) {
if (opts.devPlugins !== false) {
// do not load oclif.devPlugins in production
if ((0, util_1.isProd)())
return;
try {
const { devPlugins } = opts.rootPlugin.pjson.oclif;
if (devPlugins) {
const allDeps = { ...opts.rootPlugin.pjson.dependencies, ...opts.rootPlugin.pjson.devDependencies };
const plugins = findMatchingDependencies(allDeps ?? {}, devPlugins);
await this.loadPlugins(opts.rootPlugin.root, 'dev', plugins);
}
const { dev: pluginAdditionsDev, path } = opts.pluginAdditions ?? { core: [] };
if (pluginAdditionsDev) {
if (path) {
// If path is provided, load plugins from the path
const pjson = await (0, fs_1.readJson)((0, node_path_1.join)(path, 'package.json'));
const allDeps = { ...pjson.dependencies, ...pjson.devDependencies };
const plugins = findMatchingDependencies(allDeps ?? {}, pluginAdditionsDev);
await this.loadPlugins(path, 'dev', plugins);
}
else {
const allDeps = { ...opts.rootPlugin.pjson.dependencies, ...opts.rootPlugin.pjson.devDependencies };
const plugins = findMatchingDependencies(allDeps ?? {}, pluginAdditionsDev);
await this.loadPlugins(opts.rootPlugin.root, 'dev', plugins);
}
}
}
catch (error) {
process.emitWarning(error);
}
}
}
async loadPlugins(root, type, plugins, parent) {
if (!plugins || plugins.length === 0)
return;
const mark = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `config.loadPlugins#${type}`);
debug('loading plugins', plugins);
await Promise.all((plugins || []).map(async (plugin) => {
try {
const name = typeof plugin === 'string' ? plugin : plugin.name;
const opts = {
name,
root,
type,
};
if (typeof plugin !== 'string') {
opts.tag = plugin.tag || opts.tag;
opts.root = plugin.root || opts.root;
opts.url = plugin.url;
}
if (parent) {
opts.parent = parent;
}
if (this.plugins.has(name))
return;
const pluginMarker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `plugin.load#${name}`);
const instance = new plugin_1.Plugin(opts);
await instance.load();
pluginMarker?.addDetails({
commandCount: instance.commands.length,
hasManifest: instance.hasManifest,
name: instance.name,
topicCount: instance.topics.length,
type: instance.type,
usesMain: Boolean(instance.pjson.main),
});
pluginMarker?.stop();
this.plugins.set(instance.name, instance);
if (parent) {
instance.parent = parent;
if (!parent.children)
parent.children = [];
parent.children.push(instance);
}
if (instance.pjson.oclif.plugins) {
const allDeps = type === 'dev'
? { ...instance.pjson.dependencies, ...instance.pjson.devDependencies }
: instance.pjson.dependencies;
const plugins = findMatchingDependencies(allDeps ?? {}, instance.pjson.oclif.plugins);
await this.loadPlugins(instance.root, type, plugins, instance);
}
}
catch (error) {
this.errors.push(error);
}
}));
mark?.addDetails({ pluginCount: plugins.length });
mark?.stop();
}
async loadUserPlugins(opts) {
if (opts.userPlugins !== false) {
try {
const userPJSONPath = (0, node_path_1.join)(opts.dataDir, 'package.json');
debug('reading user plugins pjson %s', userPJSONPath);
// ignore cache because the file might have changed within the same process (e.g. during a JIT plugin install)
const pjson = await (0, fs_1.readJson)(userPJSONPath, false);
if (!pjson.oclif)
pjson.oclif = { schema: 1 };
if (!pjson.oclif.plugins)
pjson.oclif.plugins = [];
await this.loadPlugins(userPJSONPath, 'user', pjson.oclif.plugins.filter((p) => p.type === 'user'));
await this.loadPlugins(userPJSONPath, 'link', pjson.oclif.plugins.filter((p) => p.type === 'link'));
}
catch (error) {
if (error.code !== 'ENOENT')
process.emitWarning(error);
}
}
}
}
exports.default = PluginLoader;

51
node_modules/@oclif/core/lib/config/plugin.d.ts generated vendored Normal file
View File

@@ -0,0 +1,51 @@
import { Command } from '../command';
import { Manifest } from '../interfaces/manifest';
import { HookOptions, PJSON } from '../interfaces/pjson';
import { Plugin as IPlugin, PluginOptions } from '../interfaces/plugin';
import { Topic } from '../interfaces/topic';
export declare class Plugin implements IPlugin {
options: PluginOptions;
_base: string;
protected _debug: (..._: any) => void;
alias: string;
alreadyLoaded: boolean;
children: Plugin[];
commandIDs: string[];
commands: Command.Loadable[];
commandsDir: string | undefined;
hasManifest: boolean;
hooks: {
[key: string]: HookOptions[];
};
isRoot: boolean;
manifest: Manifest;
moduleType: 'commonjs' | 'module';
name: string;
parent?: Plugin | undefined;
pjson: PJSON;
root: string;
tag?: string | undefined;
type: string;
valid: boolean;
version: string;
private commandCache;
private commandDiscoveryOpts;
private flexibleTaxonomy;
constructor(options: PluginOptions);
get topics(): Topic[];
findCommand(id: string, opts: {
must: true;
}): Promise<Command.Class>;
findCommand(id: string, opts?: {
must: boolean;
}): Promise<Command.Class | undefined>;
load(): Promise<void>;
private _manifest;
private addErrorScope;
private getCommandIDs;
private getCommandIdsFromPattern;
private getCommandIdsFromTarget;
private getCommandsDir;
private loadCommandsFromTarget;
private warn;
}

374
node_modules/@oclif/core/lib/config/plugin.js generated vendored Normal file
View File

@@ -0,0 +1,374 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Plugin = void 0;
const node_path_1 = require("node:path");
const node_util_1 = require("node:util");
const tinyglobby_1 = require("tinyglobby");
const cache_1 = __importDefault(require("../cache"));
const errors_1 = require("../errors");
const module_loader_1 = require("../module-loader");
const performance_1 = require("../performance");
const symbols_1 = require("../symbols");
const cache_command_1 = require("../util/cache-command");
const find_root_1 = require("../util/find-root");
const fs_1 = require("../util/fs");
const read_pjson_1 = require("../util/read-pjson");
const util_1 = require("../util/util");
const ts_path_1 = require("./ts-path");
const util_2 = require("./util");
const _pjson = cache_1.default.getInstance().get('@oclif/core');
function topicsToArray(input, base) {
if (!input)
return [];
base = base ? `${base}:` : '';
if (Array.isArray(input)) {
return [...input, input.flatMap((t) => topicsToArray(t.subtopics, `${base}${t.name}`))];
}
return Object.keys(input).flatMap((k) => {
input[k].name = k;
return [{ ...input[k], name: `${base}${k}` }, ...topicsToArray(input[k].subtopics, `${base}${input[k].name}`)];
});
}
const cachedCommandCanBeUsed = (manifest, id) => Boolean(manifest?.commands[id] && 'isESM' in manifest.commands[id] && 'relativePath' in manifest.commands[id]);
const searchForCommandClass = (cmd) => {
if (typeof cmd.run === 'function')
return cmd;
if (cmd.default && cmd.default.run)
return cmd.default;
return Object.values(cmd).find((cmd) => typeof cmd.run === 'function');
};
const ensureCommandClass = (cmd) => {
if (cmd && typeof cmd.run === 'function')
return cmd;
};
const GLOB_PATTERNS = [
'**/*.+(js|cjs|mjs|ts|tsx|mts|cts)',
'!**/*.+(d.ts|test.ts|test.js|spec.ts|spec.js|d.mts|d.cts)?(x)',
];
function processCommandIds(files) {
return files.map((file) => {
const p = (0, node_path_1.parse)(file);
const topics = p.dir.split('/');
const command = p.name !== 'index' && p.name;
const id = [...topics, command].filter(Boolean).join(':');
return id === '' ? symbols_1.SINGLE_COMMAND_CLI_SYMBOL : id;
});
}
function determineCommandDiscoveryOptions(commandDiscovery) {
if (!commandDiscovery)
return;
if (typeof commandDiscovery === 'string') {
return { globPatterns: GLOB_PATTERNS, strategy: 'pattern', target: commandDiscovery };
}
if (!commandDiscovery.target)
throw new errors_1.CLIError('`oclif.commandDiscovery.target` is required.');
if (!commandDiscovery.strategy)
throw new errors_1.CLIError('`oclif.commandDiscovery.strategy` is required.');
if (commandDiscovery.strategy === 'explicit' && !commandDiscovery.identifier) {
commandDiscovery.identifier = 'default';
}
return commandDiscovery;
}
function determineHookOptions(hook) {
if (typeof hook === 'string')
return { identifier: 'default', target: hook };
if (!hook.identifier)
return { ...hook, identifier: 'default' };
return hook;
}
class Plugin {
options;
_base = `${_pjson.name}@${_pjson.version}`;
_debug = (0, util_2.makeDebug)();
alias;
alreadyLoaded = false;
children = [];
commandIDs = [];
// This will be initialized in the _manifest() method, which gets called in the load() method.
commands;
commandsDir;
hasManifest = false;
hooks;
isRoot = false;
manifest;
moduleType;
name;
parent;
pjson;
root;
tag;
type;
valid = false;
version;
commandCache;
commandDiscoveryOpts;
flexibleTaxonomy;
constructor(options) {
this.options = options;
}
get topics() {
return topicsToArray(this.pjson.oclif.topics || {});
}
async findCommand(id, opts = {}) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `plugin.findCommand#${this.name}.${id}`, {
id,
plugin: this.name,
});
const fetch = async () => {
if (this.commandDiscoveryOpts?.strategy === 'pattern') {
const commandsDir = await this.getCommandsDir();
if (!commandsDir)
return;
let module;
let isESM;
let filePath;
try {
;
({ filePath, isESM, module } = cachedCommandCanBeUsed(this.manifest, id)
? await (0, module_loader_1.loadWithDataFromManifest)(this.manifest.commands[id], this.root)
: await (0, module_loader_1.loadWithData)(this, (0, node_path_1.join)(commandsDir ?? this.pjson.oclif.commands, ...id.split(':'))));
this._debug(isESM ? '(import)' : '(require)', filePath);
}
catch (error) {
if (!opts.must && error.code === 'MODULE_NOT_FOUND')
return;
throw error;
}
const cmd = searchForCommandClass(module);
if (!cmd)
return;
cmd.id = id;
cmd.plugin = this;
cmd.isESM = isESM;
cmd.relativePath = (0, node_path_1.relative)(this.root, filePath || '').split(node_path_1.sep);
return cmd;
}
if (this.commandDiscoveryOpts?.strategy === 'single' || this.commandDiscoveryOpts?.strategy === 'explicit') {
const commandCache = await this.loadCommandsFromTarget();
const cmd = ensureCommandClass(commandCache?.[id]);
if (!cmd)
return;
cmd.id = id;
cmd.plugin = this;
return cmd;
}
};
const cmd = await fetch();
if (!cmd && opts.must)
(0, errors_1.error)(`command ${id} not found`);
marker?.stop();
return cmd;
}
// eslint-disable-next-line complexity
async load() {
this.type = this.options.type ?? 'core';
this.tag = this.options.tag;
this.isRoot = this.options.isRoot ?? false;
if (this.options.parent)
this.parent = this.options.parent;
// Linked plugins already have a root so there's no need to search for it.
// However there could be child plugins nested inside the linked plugin, in which
// case we still need to search for the child plugin's root.
const root = this.options.pjson && this.options.isRoot
? this.options.root
: this.type === 'link' && !this.parent
? this.options.root
: await (0, find_root_1.findRoot)(this.options.name, this.options.root);
if (!root)
throw new errors_1.CLIError(`could not find package.json with ${(0, node_util_1.inspect)(this.options)}`);
this.root = root;
this._debug(`loading ${this.type} plugin from ${root}`);
this.pjson = this.options.pjson ?? (await (0, read_pjson_1.readPjson)(root));
this.flexibleTaxonomy = this.options?.flexibleTaxonomy || this.pjson.oclif?.flexibleTaxonomy || false;
this.moduleType = this.pjson.type === 'module' ? 'module' : 'commonjs';
this.name = this.pjson.name;
this.alias = this.options.name ?? this.pjson.name;
if (!this.name)
throw new errors_1.CLIError(`no name in package.json (${root})`);
this._debug = (0, util_2.makeDebug)(this.name);
this.version = this.pjson.version;
if (this.pjson.oclif) {
this.valid = true;
}
else {
this.pjson.oclif = this.pjson['cli-engine'] || {};
}
this.hooks = Object.fromEntries(Object.entries(this.pjson.oclif.hooks ?? {}).map(([k, v]) => [
k,
(0, util_1.castArray)(v).map((v) => determineHookOptions(v)),
]));
this.commandDiscoveryOpts = determineCommandDiscoveryOptions(this.pjson.oclif?.commands);
this._debug('command discovery options', this.commandDiscoveryOpts);
this.manifest = await this._manifest();
this.commands = Object.entries(this.manifest.commands)
.map(([id, c]) => ({
...c,
load: async () => this.findCommand(id, { must: true }),
pluginAlias: this.alias,
pluginType: c.pluginType === 'jit' ? 'jit' : this.type,
}))
.sort((a, b) => a.id.localeCompare(b.id));
}
async _manifest() {
const ignoreManifest = Boolean(this.options.ignoreManifest);
const errorOnManifestCreate = Boolean(this.options.errorOnManifestCreate);
const respectNoCacheDefault = Boolean(this.options.respectNoCacheDefault);
const readManifest = async (dotfile = false) => {
try {
const p = (0, node_path_1.join)(this.root, `${dotfile ? '.' : ''}oclif.manifest.json`);
const manifest = await (0, fs_1.readJson)(p);
if (!process.env.OCLIF_NEXT_VERSION && manifest.version.split('-')[0] !== this.version.split('-')[0]) {
process.emitWarning(`Mismatched version in ${this.name} plugin manifest. Expected: ${this.version} Received: ${manifest.version}\nThis usually means you have an oclif.manifest.json file that should be deleted in development. This file should be automatically generated when publishing.`);
}
else {
this._debug('using manifest from', p);
this.hasManifest = true;
return manifest;
}
}
catch (error) {
if (error.code === 'ENOENT') {
if (!dotfile)
return readManifest(true);
}
else {
this.warn(error, 'readManifest');
}
}
};
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `plugin.manifest#${this.name}`, { plugin: this.name });
if (!ignoreManifest) {
const manifest = await readManifest();
if (manifest) {
marker?.addDetails({ commandCount: Object.keys(manifest.commands).length, fromCache: true });
marker?.stop();
this.commandIDs = Object.keys(manifest.commands);
return manifest;
}
}
this.commandIDs = await this.getCommandIDs();
const manifest = {
commands: (await Promise.all(this.commandIDs.map(async (id) => {
try {
const found = await this.findCommand(id, { must: true });
const cached = await (0, cache_command_1.cacheCommand)(found, this, respectNoCacheDefault);
// Ensure that id is set to the id being processed
// This is necessary because the id is set by findCommand but if there
// are multiple instances of a Command, then the id will be set to the
// last one found.
cached.id = id;
if (this.flexibleTaxonomy) {
const permutations = (0, util_2.getCommandIdPermutations)(id);
const aliasPermutations = cached.aliases.flatMap((a) => (0, util_2.getCommandIdPermutations)(a));
return [id, { ...cached, aliasPermutations, permutations }];
}
return [id, cached];
}
catch (error) {
const scope = `findCommand (${id})`;
if (Boolean(errorOnManifestCreate) === false)
this.warn(error, scope);
else
throw this.addErrorScope(error, scope);
}
})))
// eslint-disable-next-line unicorn/prefer-native-coercion-functions
.filter((f) => Boolean(f))
.reduce((commands, [id, c]) => {
commands[id] = c;
return commands;
}, {}),
version: this.version,
};
marker?.addDetails({ commandCount: Object.keys(manifest.commands).length, fromCache: false });
marker?.stop();
return manifest;
}
addErrorScope(err, scope) {
err.name = err.name ?? (0, node_util_1.inspect)(err).trim();
err.detail = (0, util_1.compact)([
err.detail,
`module: ${this._base}`,
scope && `task: ${scope}`,
`plugin: ${this.name}`,
`root: ${this.root}`,
...(err.code ? [`code: ${err.code}`] : []),
...(err.message ? [`message: ${err.message}`] : []),
'See more details with DEBUG=*',
]).join('\n');
return err;
}
async getCommandIDs() {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, `plugin.getCommandIDs#${this.name}`, { plugin: this.name });
let ids;
switch (this.commandDiscoveryOpts?.strategy) {
case 'explicit': {
ids = (await this.getCommandIdsFromTarget()) ?? [];
break;
}
case 'pattern': {
ids = await this.getCommandIdsFromPattern();
break;
}
case 'single': {
ids = (await this.getCommandIdsFromTarget()) ?? [];
break;
}
default: {
ids = [];
}
}
this._debug('found commands', ids);
marker?.addDetails({ count: ids.length });
marker?.stop();
return ids;
}
async getCommandIdsFromPattern() {
const commandsDir = await this.getCommandsDir();
if (!commandsDir)
return [];
this._debug(`loading IDs from ${commandsDir}`);
const files = await (0, tinyglobby_1.glob)(this.commandDiscoveryOpts?.globPatterns ?? GLOB_PATTERNS, { cwd: commandsDir });
return processCommandIds(files);
}
async getCommandIdsFromTarget() {
const commandsFromExport = await this.loadCommandsFromTarget();
if (commandsFromExport) {
return Object.entries((await this.loadCommandsFromTarget()) ?? [])
.filter(([, cmd]) => ensureCommandClass(cmd))
.map(([id]) => id);
}
}
async getCommandsDir() {
if (this.commandsDir)
return this.commandsDir;
this.commandsDir = await (0, ts_path_1.tsPath)(this.root, this.commandDiscoveryOpts?.target, this);
return this.commandsDir;
}
async loadCommandsFromTarget() {
if (this.commandCache)
return this.commandCache;
if (this.commandDiscoveryOpts?.strategy === 'explicit' && this.commandDiscoveryOpts.target) {
const filePath = await (0, ts_path_1.tsPath)(this.root, this.commandDiscoveryOpts.target, this);
const module = await (0, module_loader_1.load)(this, filePath);
this.commandCache = module[this.commandDiscoveryOpts?.identifier ?? 'default'] ?? {};
return this.commandCache;
}
if (this.commandDiscoveryOpts?.strategy === 'single' && this.commandDiscoveryOpts.target) {
const filePath = await (0, ts_path_1.tsPath)(this.root, this.commandDiscoveryOpts?.target ?? this.root, this);
const module = await (0, module_loader_1.load)(this, filePath);
this.commandCache = { [symbols_1.SINGLE_COMMAND_CLI_SYMBOL]: searchForCommandClass(module) };
return this.commandCache;
}
}
warn(err, scope) {
if (typeof err === 'string')
err = new Error(err);
const warning = this.addErrorScope(err, scope);
process.emitWarning(warning.name, warning);
}
}
exports.Plugin = Plugin;

9
node_modules/@oclif/core/lib/config/ts-path.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { Plugin, TSConfig } from '../interfaces';
export declare const TS_CONFIGS: Record<string, TSConfig | undefined>;
/**
* Convert a path from the compiled ./lib files to the ./src typescript source
* this is for developing typescript plugins/CLIs
* if there is a tsconfig and the original sources exist, it attempts to require ts-node
*/
export declare function tsPath(root: string, orig: string, plugin: Plugin): Promise<string>;
export declare function tsPath(root: string, orig: string | undefined, plugin?: Plugin | undefined): Promise<string | undefined>;

293
node_modules/@oclif/core/lib/config/ts-path.js generated vendored Normal file
View File

@@ -0,0 +1,293 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TS_CONFIGS = void 0;
exports.tsPath = tsPath;
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const node_url_1 = require("node:url");
const cache_1 = __importDefault(require("../cache"));
const warn_1 = require("../errors/warn");
const settings_1 = require("../settings");
const fs_1 = require("../util/fs");
const read_tsconfig_1 = require("../util/read-tsconfig");
const util_1 = require("../util/util");
const util_2 = require("./util");
const debug = (0, util_2.makeDebug)('ts-path');
exports.TS_CONFIGS = {};
const REGISTERED = new Set();
function determineRuntime() {
/**
* Examples:
* #!/usr/bin/env bun
* bun bin/run.js
* bun bin/dev.js
*/
if (process.execPath.split(node_path_1.sep).includes('bun'))
return 'bun';
/**
* Examples:
* #!/usr/bin/env node
* #!/usr/bin/env node --loader ts-node/esm --experimental-specifier-resolution=node --no-warnings
* node bin/run.js
* node bin/dev.js
*/
if (process.execArgv.length === 0)
return 'node';
/**
* Examples:
* #!/usr/bin/env ts-node
* #!/usr/bin/env node_modules/.bin/ts-node
* ts-node bin/run.js
* ts-node bin/dev.js
*/
if (process.execArgv[0] === '--require' && process.execArgv[1].split(node_path_1.sep).includes('ts-node'))
return 'ts-node';
if (process.execArgv[0].split(node_path_1.sep).includes('ts-node'))
return 'ts-node';
/**
* Examples:
* #!/usr/bin/env tsx
* #!/usr/bin/env node_modules/.bin/tsx
* tsx bin/run.js
* tsx bin/dev.js
*/
if (process.execArgv[0] === '--require' && process.execArgv[1].split(node_path_1.sep).includes('tsx'))
return 'tsx';
return 'node';
}
const RUN_TIME = determineRuntime();
function isErrno(error) {
return 'code' in error && error.code === 'ENOENT';
}
async function loadTSConfig(root) {
try {
if (exports.TS_CONFIGS[root])
return exports.TS_CONFIGS[root];
const tsconfig = await (0, read_tsconfig_1.readTSConfig)(root);
if (!tsconfig)
return;
debug('tsconfig: %O', tsconfig);
exports.TS_CONFIGS[root] = tsconfig;
return exports.TS_CONFIGS[root];
}
catch (error) {
if (isErrno(error))
return;
debug(`Could not parse tsconfig.json. Skipping typescript path lookup for ${root}.`);
(0, warn_1.memoizedWarn)(`Could not parse tsconfig.json for ${root}. Falling back to compiled source.`);
}
}
async function registerTsx(root, moduleType) {
if (REGISTERED.has(root))
return;
try {
const apiPath = moduleType === 'module' ? 'tsx/esm/api' : 'tsx/cjs/api';
const tsxPath = require.resolve(apiPath, { paths: [root] });
if (!tsxPath)
return;
debug('registering tsx at', root);
debug('tsx path:', tsxPath);
const { href } = (0, node_url_1.pathToFileURL)(tsxPath);
debug('tsx href:', href);
const { register } = await import(href);
debug('Successfully imported tsx');
register();
REGISTERED.add(root);
}
catch (error) {
debug(`Could not find tsx. Skipping tsx registration for ${root}.`);
debug(error);
}
}
async function registerTSNode(root, tsconfig) {
if (REGISTERED.has(root))
return;
debug('registering ts-node at', root);
const tsNodePath = require.resolve('ts-node', { paths: [root, __dirname] });
debug('ts-node path:', tsNodePath);
let tsNode;
try {
tsNode = require(tsNodePath);
debug('Successfully required ts-node');
}
catch (error) {
debug(`Could not find ts-node at ${tsNodePath}. Skipping ts-node registration for ${root}.`);
debug(error);
(0, warn_1.memoizedWarn)(`Could not find ts-node at ${tsNodePath}. Please ensure that ts-node is a devDependency. Falling back to compiled source.`);
return;
}
const typeRoots = [(0, node_path_1.join)(root, 'node_modules', '@types')];
const rootDirs = [];
if (tsconfig.compilerOptions.rootDirs) {
for (const r of tsconfig.compilerOptions.rootDirs) {
rootDirs.push((0, node_path_1.join)(root, r));
}
}
else if (tsconfig.compilerOptions.rootDir) {
rootDirs.push((0, node_path_1.join)(root, tsconfig.compilerOptions.rootDir));
}
else if (tsconfig.compilerOptions.baseUrl) {
rootDirs.push((0, node_path_1.join)(root, tsconfig.compilerOptions.baseUrl));
}
else {
rootDirs.push((0, node_path_1.join)(root, 'src'));
}
// Because we need to provide a modified `rootDirs` to ts-node, we need to
// remove `baseUrl` and `rootDir` from `compilerOptions` so that they
// don't conflict.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { baseUrl, rootDir, ...rest } = tsconfig.compilerOptions;
const conf = {
compilerOptions: {
...rest,
rootDirs,
typeRoots,
},
...tsconfig['ts-node'],
cwd: root,
esm: tsconfig['ts-node']?.esm ?? true,
experimentalSpecifierResolution: tsconfig['ts-node']?.experimentalSpecifierResolution ?? 'explicit',
scope: true,
scopeDir: root,
skipProject: true,
transpileOnly: true,
};
debug('ts-node options: %O', conf);
tsNode.register(conf);
REGISTERED.add(root);
}
/**
* Skip ts-node registration for ESM plugins in production.
* The node/ts-node ecosystem is not mature enough to support auto-transpiling ESM modules at this time.
* See the following:
* - https://github.com/TypeStrong/ts-node/issues/1791#issuecomment-1149754228
* - https://github.com/nodejs/node/issues/49432
* - https://github.com/nodejs/node/pull/49407
* - https://github.com/nodejs/node/issues/34049
*
* We still register tsx/ts-node for ESM plugins when NODE_ENV is "test" or "development" and root plugin is also ESM
* since that allows plugins to be auto-transpiled when developing locally using `bin/dev.js`.
*/
function cannotTranspileEsm(rootPlugin, plugin, isProduction) {
return ((isProduction || rootPlugin?.moduleType === 'commonjs') &&
plugin?.moduleType === 'module' &&
!plugin?.pjson.devDependencies?.tsx);
}
/**
* If the dev script is run with ts-node for an ESM plugin, skip ts-node registration
* and fall back on compiled source since ts-node executable cannot transpile ESM in Node 20+
*
* See the following:
* https://nodejs.org/en/blog/announcements/v20-release-announce#custom-esm-loader-hooks-nearing-stable
* https://github.com/oclif/core/issues/817
* https://github.com/TypeStrong/ts-node/issues/1997
*/
function cannotUseTsNode(root, plugin, isProduction) {
if (plugin?.moduleType !== 'module' || isProduction)
return false;
const nodeMajor = Number.parseInt(process.version.replace('v', '').split('.')[0], 10);
return RUN_TIME === 'ts-node' && nodeMajor >= 20;
}
/**
* Determine the path to the source file from the compiled ./lib files
*/
async function determinePath(root, orig, plugin) {
const tsconfig = await loadTSConfig(root);
if (!tsconfig)
return orig;
debug(`Determining path for ${orig}`);
if (RUN_TIME === 'bun') {
debug(`Skipping ts-node registration for ${root} because the runtime is: ${RUN_TIME}`);
}
else {
// attempt to register tsx first. If it fails to register, we will fall back to ts-node
await registerTsx(root, plugin?.moduleType);
// if tsx registration succeeded, then this will exit early since the path will be in REGISTERED already
await registerTSNode(root, tsconfig);
}
const { baseUrl, outDir, rootDir, rootDirs } = tsconfig.compilerOptions;
const rootDirPath = rootDir ?? (rootDirs ?? [])[0] ?? baseUrl;
if (!rootDirPath) {
debug(`no rootDir, rootDirs, or baseUrl specified in tsconfig.json. Returning default path ${orig}`);
return orig;
}
if (!outDir) {
debug(`no outDir specified in tsconfig.json. Returning default path ${orig}`);
return orig;
}
// rewrite path from ./lib/foo to ./src/foo
const lib = (0, node_path_1.join)(root, outDir); // ./lib
const src = (0, node_path_1.join)(root, rootDirPath); // ./src
const relative = (0, node_path_1.relative)(lib, orig); // ./commands
// For hooks, it might point to a js file, not a module. Something like "./hooks/myhook.js" which doesn't need the js.
const out = (0, node_path_1.join)(src, relative).replace(/\.js$/, ''); // ./src/commands
// this can be a directory of commands or point to a hook file
// if it's a directory, we check if the path exists. If so, return the path to the directory.
// For hooks, it might point to a module, not a file. Something like "./hooks/myhook"
// That file doesn't exist, and the real file is "./hooks/myhook.ts"
// In that case we attempt to resolve to the filename. If it fails it will revert back to the lib path
debug(`lib dir: ${lib}`);
debug(`src dir: ${src}`);
debug(`src directory to find: ${out}`);
if ((0, fs_1.existsSync)(out)) {
debug(`Found source directory for ${orig} at ${out}`);
return out;
}
const sourceFiles = await Promise.all([
(0, promises_1.access)(`${out}.ts`)
.then(() => `${out}.ts`)
.catch(() => false),
(0, promises_1.access)(`${out}.tsx`)
.then(() => `${out}.tsx`)
.catch(() => false),
]);
if (sourceFiles.some(Boolean)) {
debug(`Found source file for ${orig} at ${out}`);
return out;
}
debug(`No source file found. Returning default path ${orig}`);
if (!(0, util_1.isProd)())
(0, warn_1.memoizedWarn)(`Could not find source for ${orig} based on tsconfig. Defaulting to compiled source.`);
return orig;
}
async function tsPath(root, orig, plugin) {
const rootPlugin = plugin?.options.isRoot ? plugin : cache_1.default.getInstance().get('rootPlugin');
if (!orig)
return orig;
orig = orig.startsWith(root) ? orig : (0, node_path_1.join)(root, orig);
// NOTE: The order of these checks matter!
const enableAutoTranspile = settings_1.settings.enableAutoTranspile ?? settings_1.settings.tsnodeEnabled;
if (enableAutoTranspile === false) {
debug(`Skipping typescript path lookup for ${root} because enableAutoTranspile is explicitly set to false`);
return orig;
}
const isProduction = (0, util_1.isProd)();
// Do not skip ts-node registration if the plugin is linked
if (enableAutoTranspile === undefined && isProduction && plugin?.type !== 'link') {
debug(`Skipping typescript path lookup for ${root} because NODE_ENV is NOT "test" or "development"`);
return orig;
}
if (cannotTranspileEsm(rootPlugin, plugin, isProduction)) {
debug(`Skipping typescript path lookup for ${root} because it's an ESM module (NODE_ENV: ${process.env.NODE_ENV}, root plugin module type: ${rootPlugin?.moduleType})`);
const warningIsDisabled = process.env.OCLIF_DISABLE_LINKED_ESM_WARNING && (0, util_1.isTruthy)(process.env.OCLIF_DISABLE_LINKED_ESM_WARNING);
// Only warn if the plugin is linked AND the warning is not disabled
if (plugin?.type === 'link' && !warningIsDisabled)
(0, warn_1.memoizedWarn)(`${plugin?.name} is a linked ESM module and cannot be auto-transpiled. Existing compiled source will be used instead.`);
return orig;
}
if (cannotUseTsNode(root, plugin, isProduction)) {
debug(`Skipping typescript path lookup for ${root} because ts-node is run in node version ${process.version}"`);
(0, warn_1.memoizedWarn)(`ts-node executable cannot transpile ESM in Node 20. Existing compiled source will be used instead. See https://github.com/oclif/core/issues/817.`);
return orig;
}
try {
return await determinePath(root, orig, plugin);
}
catch (error) {
debug(error);
return orig;
}
}

23
node_modules/@oclif/core/lib/config/util.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
export declare function makeDebug(...scope: string[]): (..._: any) => void;
export declare function getPermutations(arr: string[]): Array<string[]>;
export declare function getCommandIdPermutations(commandId: string): string[];
/**
* Return an array of ids that represent all the usable combinations that a user could enter.
*
* For example, if the command ids are:
* - foo:bar:baz
* - one:two:three
* Then the usable ids would be:
* - foo
* - foo:bar
* - foo:bar:baz
* - one
* - one:two
* - one:two:three
*
* This allows us to determine which parts of the argv array belong to the command id whenever the topicSeparator is a space.
*
* @param commandIds string[]
* @returns string[]
*/
export declare const collectUsableIds: (commandIds: string[]) => Set<string>;

54
node_modules/@oclif/core/lib/config/util.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectUsableIds = void 0;
exports.makeDebug = makeDebug;
exports.getPermutations = getPermutations;
exports.getCommandIdPermutations = getCommandIdPermutations;
const logger_1 = require("../logger");
function makeDebug(...scope) {
return (formatter, ...args) => (0, logger_1.getLogger)(['config', ...scope].join(':')).debug(formatter, ...args);
}
// Adapted from https://github.com/angus-c/just/blob/master/packages/array-permutations/index.js
function getPermutations(arr) {
if (arr.length === 0)
return [];
if (arr.length === 1)
return [arr];
const output = [];
const partialPermutations = getPermutations(arr.slice(1));
const first = arr[0];
for (let i = 0, len = partialPermutations.length; i < len; i++) {
const partial = partialPermutations[i];
for (let j = 0, len2 = partial.length; j <= len2; j++) {
const start = partial.slice(0, j);
const end = partial.slice(j);
const merged = [...start, first, ...end];
output.push(merged);
}
}
return output;
}
function getCommandIdPermutations(commandId) {
return getPermutations(commandId.split(':')).flatMap((c) => c.join(':'));
}
/**
* Return an array of ids that represent all the usable combinations that a user could enter.
*
* For example, if the command ids are:
* - foo:bar:baz
* - one:two:three
* Then the usable ids would be:
* - foo
* - foo:bar
* - foo:bar:baz
* - one
* - one:two
* - one:two:three
*
* This allows us to determine which parts of the argv array belong to the command id whenever the topicSeparator is a space.
*
* @param commandIds string[]
* @returns string[]
*/
const collectUsableIds = (commandIds) => new Set(commandIds.flatMap((id) => id.split(':').map((_, i, a) => a.slice(0, i + 1).join(':'))));
exports.collectUsableIds = collectUsableIds;

8
node_modules/@oclif/core/lib/errors/error.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { PrettyPrintableError } from '../interfaces';
export declare function error(input: Error | string, options: {
exit: false;
} & PrettyPrintableError): void;
export declare function error(input: Error | string, options?: {
exit?: number;
} & PrettyPrintableError): never;
export default error;

63
node_modules/@oclif/core/lib/errors/error.js generated vendored Normal file
View File

@@ -0,0 +1,63 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.error = error;
const logger_1 = require("../logger");
const write_1 = require("../ux/write");
const cli_1 = require("./errors/cli");
const pretty_print_1 = __importStar(require("./errors/pretty-print"));
function error(input, options = {}) {
let err;
if (typeof input === 'string') {
err = new cli_1.CLIError(input, options);
}
else if (input instanceof Error) {
err = (0, cli_1.addOclifExitCode)(input, options);
}
else {
throw new TypeError('first argument must be a string or instance of Error');
}
err = (0, pretty_print_1.applyPrettyPrintOptions)(err, options);
if (options.exit === false) {
const message = (0, pretty_print_1.default)(err);
if (message)
(0, write_1.stderr)(message);
if (err?.stack)
(0, logger_1.getLogger)().error(err.stack);
}
else
throw err;
}
exports.default = error;

29
node_modules/@oclif/core/lib/errors/errors/cli.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import { OclifError, PrettyPrintableError } from '../../interfaces/errors';
/**
* properties specific to internal oclif error handling
*/
export declare function addOclifExitCode(error: Record<string, any>, options?: {
exit?: false | number | undefined;
}): OclifError;
export declare class CLIError extends Error implements OclifError {
code?: string | undefined;
oclif: OclifError['oclif'];
skipOclifErrorHandling?: boolean | undefined;
suggestions?: string[] | undefined;
constructor(error: Error | string, options?: {
exit?: false | number | undefined;
} & PrettyPrintableError);
get bang(): string | undefined;
get stack(): string;
/**
* @deprecated `render` Errors display should be handled by display function, like pretty-print
* @returns {string} returns a string representing the display of the error
*/
render(): string;
}
export declare namespace CLIError {
class Warn extends CLIError {
constructor(err: Error | string);
get bang(): string | undefined;
}
}

79
node_modules/@oclif/core/lib/errors/errors/cli.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLIError = void 0;
exports.addOclifExitCode = addOclifExitCode;
const clean_stack_1 = __importDefault(require("clean-stack"));
const indent_string_1 = __importDefault(require("indent-string"));
const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
const cache_1 = __importDefault(require("../../cache"));
const screen_1 = require("../../screen");
const settings_1 = require("../../settings");
const theme_1 = require("../../ux/theme");
/**
* properties specific to internal oclif error handling
*/
function addOclifExitCode(error, options) {
if (!('oclif' in error)) {
;
error.oclif = {};
}
error.oclif.exit = options?.exit === undefined ? (cache_1.default.getInstance().get('exitCodes')?.default ?? 2) : options.exit;
return error;
}
class CLIError extends Error {
code;
oclif = {};
skipOclifErrorHandling;
suggestions;
constructor(error, options = {}) {
super(error instanceof Error ? error.message : error);
addOclifExitCode(this, options);
this.code = options.code;
this.suggestions = options.suggestions;
}
// eslint-disable-next-line getter-return
get bang() {
try {
return (0, theme_1.colorize)('red', process.platform === 'win32' ? '»' : '');
}
catch { }
}
get stack() {
return (0, clean_stack_1.default)(super.stack, { pretty: true });
}
/**
* @deprecated `render` Errors display should be handled by display function, like pretty-print
* @returns {string} returns a string representing the display of the error
*/
render() {
if (settings_1.settings.debug) {
return this.stack;
}
let output = `${this.name}: ${this.message}`;
output = (0, wrap_ansi_1.default)(output, screen_1.errtermwidth - 6, { hard: true, trim: false });
output = (0, indent_string_1.default)(output, 3);
output = (0, indent_string_1.default)(output, 1, { includeEmptyLines: true, indent: this.bang });
output = (0, indent_string_1.default)(output, 1);
return output;
}
}
exports.CLIError = CLIError;
(function (CLIError) {
class Warn extends CLIError {
constructor(err) {
super(err instanceof Error ? err.message : err);
this.name = 'Warning';
}
// eslint-disable-next-line getter-return
get bang() {
try {
return (0, theme_1.colorize)('yellow', process.platform === 'win32' ? '»' : '');
}
catch { }
}
}
CLIError.Warn = Warn;
})(CLIError || (exports.CLIError = CLIError = {}));

7
node_modules/@oclif/core/lib/errors/errors/exit.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { OclifError } from '../../interfaces';
import { CLIError } from './cli';
export declare class ExitError extends CLIError implements OclifError {
code: string;
constructor(exitCode?: number);
render(): string;
}

14
node_modules/@oclif/core/lib/errors/errors/exit.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExitError = void 0;
const cli_1 = require("./cli");
class ExitError extends cli_1.CLIError {
code = 'EEXIT';
constructor(exitCode = 1) {
super(`EEXIT: ${exitCode}`, { exit: exitCode });
}
render() {
return '';
}
}
exports.ExitError = ExitError;

View File

@@ -0,0 +1,6 @@
import { OclifError } from '../../interfaces';
import { CLIError } from './cli';
export declare class ModuleLoadError extends CLIError implements OclifError {
code: string;
constructor(message: string);
}

View File

@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModuleLoadError = void 0;
const cli_1 = require("./cli");
class ModuleLoadError extends cli_1.CLIError {
code = 'MODULE_NOT_FOUND';
constructor(message) {
super(`[MODULE_NOT_FOUND] ${message}`, { exit: 1 });
this.name = 'ModuleLoadError';
}
}
exports.ModuleLoadError = ModuleLoadError;

View File

@@ -0,0 +1,8 @@
import { PrettyPrintableError } from '../../interfaces/errors';
type CLIErrorDisplayOptions = {
bang?: string | undefined;
name?: string | undefined;
};
export declare function applyPrettyPrintOptions(error: Error, options: PrettyPrintableError): PrettyPrintableError;
export default function prettyPrint(error: Error & PrettyPrintableError & CLIErrorDisplayOptions): string | undefined;
export {};

View File

@@ -0,0 +1,51 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyPrettyPrintOptions = applyPrettyPrintOptions;
exports.default = prettyPrint;
const indent_string_1 = __importDefault(require("indent-string"));
const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
const screen_1 = require("../../screen");
const settings_1 = require("../../settings");
function applyPrettyPrintOptions(error, options) {
const prettyErrorKeys = ['message', 'code', 'ref', 'suggestions'];
for (const key of prettyErrorKeys) {
const applyOptionsKey = !(key in error) && options[key];
if (applyOptionsKey) {
;
error[key] = options[key];
}
}
return error;
}
const formatSuggestions = (suggestions) => {
const label = 'Try this:';
if (!suggestions || suggestions.length === 0)
return undefined;
if (suggestions.length === 1)
return `${label} ${suggestions[0]}`;
const multiple = suggestions.map((suggestion) => `* ${suggestion}`).join('\n');
return `${label}\n${(0, indent_string_1.default)(multiple, 2)}`;
};
function prettyPrint(error) {
if (settings_1.settings.debug) {
return error.stack;
}
const { bang, code, message, name: errorSuffix, ref, suggestions } = error;
// errorSuffix is pulled from the 'name' property on CLIError
// and is like either Error or Warning
const formattedHeader = message ? `${errorSuffix || 'Error'}: ${message}` : undefined;
const formattedCode = code ? `Code: ${code}` : undefined;
const formattedSuggestions = formatSuggestions(suggestions);
const formattedReference = ref ? `Reference: ${ref}` : undefined;
const formatted = [formattedHeader, formattedCode, formattedSuggestions, formattedReference]
.filter(Boolean)
.join('\n');
let output = (0, wrap_ansi_1.default)(formatted, screen_1.errtermwidth - 6, { hard: true, trim: false });
output = (0, indent_string_1.default)(output, 3);
output = (0, indent_string_1.default)(output, 1, { includeEmptyLines: true, indent: bang || '' });
output = (0, indent_string_1.default)(output, 1);
return output;
}

1
node_modules/@oclif/core/lib/errors/exit.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export declare function exit(code?: number): never;

7
node_modules/@oclif/core/lib/errors/exit.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.exit = exit;
const exit_1 = require("./errors/exit");
function exit(code = 0) {
throw new exit_1.ExitError(code);
}

14
node_modules/@oclif/core/lib/errors/handle.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { OclifError, PrettyPrintableError } from '../interfaces';
import { CLIParseError } from '../parser/errors';
import { CLIError } from './errors/cli';
/**
* This is an odd abstraction for process.exit, but it allows us to stub it in tests.
*
* https://github.com/sinonjs/sinon/issues/562
*/
export declare const Exit: {
exit(code?: number): never;
};
type ErrorToHandle = Error & Partial<PrettyPrintableError> & Partial<OclifError> & Partial<CLIError> & Partial<CLIParseError>;
export declare function handle(err: ErrorToHandle): Promise<void>;
export {};

60
node_modules/@oclif/core/lib/errors/handle.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Exit = void 0;
exports.handle = handle;
const clean_stack_1 = __importDefault(require("clean-stack"));
const cache_1 = __importDefault(require("../cache"));
const index_1 = require("../help/index");
const logger_1 = require("../logger");
const cli_1 = require("./errors/cli");
const exit_1 = require("./errors/exit");
const pretty_print_1 = __importDefault(require("./errors/pretty-print"));
/**
* This is an odd abstraction for process.exit, but it allows us to stub it in tests.
*
* https://github.com/sinonjs/sinon/issues/562
*/
exports.Exit = {
exit(code = 0) {
// eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
process.exit(code);
},
};
async function handle(err) {
try {
if (!err)
err = new cli_1.CLIError('no error?');
if (err.message === 'SIGINT')
exports.Exit.exit(1);
const shouldPrint = !(err instanceof exit_1.ExitError) && !err.skipOclifErrorHandling;
const pretty = (0, pretty_print_1.default)(err);
const stack = (0, clean_stack_1.default)(err.stack || '', { pretty: true });
if (shouldPrint) {
console.error(pretty ?? stack);
const config = cache_1.default.getInstance().get('config');
if (err.showHelp && err.parse?.input?.argv && config) {
const options = {
...(config.pjson.oclif.helpOptions ?? config.pjson.helpOptions),
sections: ['flags', 'usage', 'arguments'],
sendToStderr: true,
};
const help = new index_1.Help(config, options);
console.error();
await help.showHelp(process.argv.slice(2));
}
}
const exitCode = err.oclif?.exit ?? 1;
if (err.code !== 'EEXIT' && stack) {
(0, logger_1.getLogger)().error(stack);
}
exports.Exit.exit(exitCode);
}
catch (error) {
console.error(err.stack);
console.error(error.stack);
exports.Exit.exit(1);
}
}

8
node_modules/@oclif/core/lib/errors/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
export { PrettyPrintableError } from '../interfaces';
export { error } from './error';
export { CLIError } from './errors/cli';
export { ExitError } from './errors/exit';
export { ModuleLoadError } from './errors/module-load';
export { exit } from './exit';
export { handle } from './handle';
export { warn } from './warn';

17
node_modules/@oclif/core/lib/errors/index.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.warn = exports.handle = exports.exit = exports.ModuleLoadError = exports.ExitError = exports.CLIError = exports.error = void 0;
var error_1 = require("./error");
Object.defineProperty(exports, "error", { enumerable: true, get: function () { return error_1.error; } });
var cli_1 = require("./errors/cli");
Object.defineProperty(exports, "CLIError", { enumerable: true, get: function () { return cli_1.CLIError; } });
var exit_1 = require("./errors/exit");
Object.defineProperty(exports, "ExitError", { enumerable: true, get: function () { return exit_1.ExitError; } });
var module_load_1 = require("./errors/module-load");
Object.defineProperty(exports, "ModuleLoadError", { enumerable: true, get: function () { return module_load_1.ModuleLoadError; } });
var exit_2 = require("./exit");
Object.defineProperty(exports, "exit", { enumerable: true, get: function () { return exit_2.exit; } });
var handle_1 = require("./handle");
Object.defineProperty(exports, "handle", { enumerable: true, get: function () { return handle_1.handle; } });
var warn_1 = require("./warn");
Object.defineProperty(exports, "warn", { enumerable: true, get: function () { return warn_1.warn; } });

8
node_modules/@oclif/core/lib/errors/warn.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
/**
* Prints a pretty warning message to stderr.
*
* @param input The error or string to print.
*/
export declare function warn(input: Error | string): void;
export declare function memoizedWarn(input: Error | string): void;
export default warn;

40
node_modules/@oclif/core/lib/errors/warn.js generated vendored Normal file
View File

@@ -0,0 +1,40 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.warn = warn;
exports.memoizedWarn = memoizedWarn;
const logger_1 = require("../logger");
const write_1 = require("../ux/write");
const cli_1 = require("./errors/cli");
const pretty_print_1 = __importDefault(require("./errors/pretty-print"));
/**
* Prints a pretty warning message to stderr.
*
* @param input The error or string to print.
*/
function warn(input) {
let err;
if (typeof input === 'string') {
err = new cli_1.CLIError.Warn(input);
}
else if (input instanceof Error) {
err = (0, cli_1.addOclifExitCode)(input);
}
else {
throw new TypeError('first argument must be a string or instance of Error');
}
const message = (0, pretty_print_1.default)(err);
if (message)
(0, write_1.stderr)(message);
if (err?.stack)
(0, logger_1.getLogger)().error(err.stack);
}
const WARNINGS = new Set();
function memoizedWarn(input) {
if (!WARNINGS.has(input))
warn(input);
WARNINGS.add(input);
}
exports.default = warn;

44
node_modules/@oclif/core/lib/execute.d.ts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { LoadOptions } from './interfaces';
/**
* Load and run oclif CLI
*
* @example For ESM dev.js
* ```
* #!/usr/bin/env -S node --loader ts-node/esm --no-warnings=ExperimentalWarning
* import { execute } from '@oclif/core'
*
* await execute({development: true, dir: import.meta.url})
* ```
*
* @example For ESM run.js
* ```
* #!/usr/bin/env node
* import { execute } from '@oclif/core'
*
* await execute({dir: import.meta.url})
* ```
*
* @example For CJS dev.js
* ```
* #!/usr/bin/env ts-node
* void (async () => {
* const oclif = await import('@oclif/core')
* await oclif.execute({development: true, dir: __dirname})
* })()
* ```
*
* @example For CJS run.js
* ```
* #!/usr/bin/env node
* void (async () => {
* const oclif = await import('@oclif/core')
* await oclif.execute({dir: __dirname})
* })()
* ```
*/
export declare function execute(options: {
args?: string[];
development?: boolean;
dir?: string;
loadOptions?: LoadOptions;
}): Promise<unknown>;

61
node_modules/@oclif/core/lib/execute.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.execute = execute;
const errors_1 = require("./errors");
const handle_1 = require("./errors/handle");
const flush_1 = require("./flush");
const main_1 = require("./main");
const settings_1 = require("./settings");
/**
* Load and run oclif CLI
*
* @example For ESM dev.js
* ```
* #!/usr/bin/env -S node --loader ts-node/esm --no-warnings=ExperimentalWarning
* import { execute } from '@oclif/core'
*
* await execute({development: true, dir: import.meta.url})
* ```
*
* @example For ESM run.js
* ```
* #!/usr/bin/env node
* import { execute } from '@oclif/core'
*
* await execute({dir: import.meta.url})
* ```
*
* @example For CJS dev.js
* ```
* #!/usr/bin/env ts-node
* void (async () => {
* const oclif = await import('@oclif/core')
* await oclif.execute({development: true, dir: __dirname})
* })()
* ```
*
* @example For CJS run.js
* ```
* #!/usr/bin/env node
* void (async () => {
* const oclif = await import('@oclif/core')
* await oclif.execute({dir: __dirname})
* })()
* ```
*/
async function execute(options) {
if (!options.dir && !options.loadOptions) {
throw new errors_1.CLIError('dir or loadOptions is required.');
}
if (options.development) {
// In dev mode -> use ts-node and dev plugins
process.env.NODE_ENV = 'development';
settings_1.settings.debug = true;
}
return (0, main_1.run)(options.args ?? process.argv.slice(2), options.loadOptions ?? options.dir)
.then(async (result) => {
(0, flush_1.flush)();
return result;
})
.catch(async (error) => (0, handle_1.handle)(error));
}

181
node_modules/@oclif/core/lib/flags.d.ts generated vendored Normal file
View File

@@ -0,0 +1,181 @@
import { URL } from 'node:url';
import { BooleanFlag, CustomOptions, FlagDefinition, OptionFlag } from './interfaces';
type NotArray<T> = T extends Array<any> ? never : T;
/**
* Create a custom flag.
*
* @example
* type Id = string
* type IdOpts = { startsWith: string; length: number }
*
* export const myFlag = custom<Id, IdOpts>({
* parse: async (input, opts) => {
* if (input.startsWith(opts.startsWith) && input.length === opts.length) {
* return input
* }
*
* throw new Error('Invalid id')
* },
* })
*/
export declare function custom<T = string, P extends CustomOptions = CustomOptions>(defaults: Partial<OptionFlag<T[], P>> & {
multiple: true;
} & ({
default: OptionFlag<T[], P>['default'];
} | {
required: true;
})): FlagDefinition<T, P, {
multiple: true;
requiredOrDefaulted: true;
}>;
export declare function custom<T = string, P extends CustomOptions = CustomOptions>(defaults: Partial<OptionFlag<NotArray<T>, P>> & {
multiple?: false | undefined;
} & ({
default: OptionFlag<NotArray<T>, P>['default'];
} | {
required: true;
})): FlagDefinition<T, P, {
multiple: false;
requiredOrDefaulted: true;
}>;
export declare function custom<T = string, P extends CustomOptions = CustomOptions>(defaults: Partial<OptionFlag<NotArray<T>, P>> & {
default?: OptionFlag<NotArray<T>, P>['default'] | undefined;
multiple?: false | undefined;
required?: false | undefined;
}): FlagDefinition<T, P, {
multiple: false;
requiredOrDefaulted: false;
}>;
export declare function custom<T = string, P extends CustomOptions = CustomOptions>(defaults: Partial<OptionFlag<T[], P>> & {
default?: OptionFlag<T[], P>['default'] | undefined;
multiple: true;
required?: false | undefined;
}): FlagDefinition<T, P, {
multiple: true;
requiredOrDefaulted: false;
}>;
export declare function custom<T = string, P extends CustomOptions = CustomOptions>(): FlagDefinition<T, P, {
multiple: false;
requiredOrDefaulted: false;
}>;
/**
* A boolean flag. Defaults to `false` unless default is set to `true`.
*
* - `allowNo` option allows `--no-` prefix to negate boolean flag.
*/
export declare function boolean<T = boolean>(options?: Partial<BooleanFlag<T>>): BooleanFlag<T>;
/**
* An integer flag. Throws an error if the provided value is not a valid integer.
*
* - `min` option allows to set a minimum value.
* - `max` option allows to set a maximum value.
*/
export declare const integer: FlagDefinition<number, {
max?: number;
min?: number;
}, {
multiple: false;
requiredOrDefaulted: false;
}>;
/**
* A directory flag.
*
* - `exists` option allows you to throw an error if the directory does not exist.
*/
export declare const directory: FlagDefinition<string, {
exists?: boolean;
}, {
multiple: false;
requiredOrDefaulted: false;
}>;
/**
* A file flag.
*
* - `exists` option allows you to throw an error if the file does not exist.
*/
export declare const file: FlagDefinition<string, {
exists?: boolean;
}, {
multiple: false;
requiredOrDefaulted: false;
}>;
/**
* A URL flag that converts the provided value is a string.
*
* Throws an error if the string is not a valid URL.
*/
export declare const url: FlagDefinition<URL, CustomOptions, {
multiple: false;
requiredOrDefaulted: false;
}>;
/**
* A string flag.
*/
export declare const string: FlagDefinition<string, CustomOptions, {
multiple: false;
requiredOrDefaulted: false;
}>;
/**
* Version flag that will print the CLI version and exit.
*/
export declare const version: (opts?: Partial<BooleanFlag<boolean>>) => BooleanFlag<void>;
/**
* A help flag that will print the CLI help and exit.
*/
export declare const help: (opts?: Partial<BooleanFlag<boolean>>) => BooleanFlag<void>;
type ReadonlyElementOf<T extends ReadonlyArray<unknown>> = T[number];
/**
* Create a custom flag that infers the flag type from the provided options.
*
* The provided `options` must be a readonly array in order for type inference to work.
*
* @example
* export default class MyCommand extends Command {
* static flags = {
* name: Flags.option({
* options: ['foo', 'bar'] as const,
* })(),
* }
* }
*/
export declare function option<T extends readonly string[], P extends CustomOptions>(defaults: Partial<OptionFlag<ReadonlyElementOf<T>[], P>> & {
multiple: true;
options: T;
} & ({
default: OptionFlag<ReadonlyElementOf<T>[], P>['default'] | undefined;
} | {
required: true;
})): FlagDefinition<(typeof defaults.options)[number], P, {
multiple: true;
requiredOrDefaulted: true;
}>;
export declare function option<T extends readonly string[], P extends CustomOptions>(defaults: Partial<OptionFlag<ReadonlyElementOf<T>, P>> & {
multiple?: false | undefined;
options: T;
} & ({
default: OptionFlag<ReadonlyElementOf<T>, P>['default'];
} | {
required: true;
})): FlagDefinition<(typeof defaults.options)[number], P, {
multiple: false;
requiredOrDefaulted: true;
}>;
export declare function option<T extends readonly string[], P extends CustomOptions>(defaults: Partial<OptionFlag<ReadonlyElementOf<T>, P>> & {
default?: OptionFlag<ReadonlyElementOf<T>, P>['default'] | undefined;
multiple?: false | undefined;
options: T;
required?: false | undefined;
}): FlagDefinition<(typeof defaults.options)[number], P, {
multiple: false;
requiredOrDefaulted: false;
}>;
export declare function option<T extends readonly string[], P extends CustomOptions>(defaults: Partial<OptionFlag<ReadonlyElementOf<T>[], P>> & {
default?: OptionFlag<ReadonlyElementOf<T>[], P>['default'] | undefined;
multiple: true;
options: T;
required?: false | undefined;
}): FlagDefinition<(typeof defaults.options)[number], P, {
multiple: true;
requiredOrDefaulted: false;
}>;
export {};

129
node_modules/@oclif/core/lib/flags.js generated vendored Normal file
View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.help = exports.version = exports.string = exports.url = exports.file = exports.directory = exports.integer = void 0;
exports.custom = custom;
exports.boolean = boolean;
exports.option = option;
const node_url_1 = require("node:url");
const errors_1 = require("./errors");
const help_1 = require("./help");
const fs_1 = require("./util/fs");
function custom(defaults) {
return (options = {}) => ({
parse: async (input, _ctx, _opts) => input,
...defaults,
...options,
input: [],
multiple: Boolean(options.multiple === undefined ? (defaults?.multiple ?? false) : options.multiple),
type: 'option',
});
}
/**
* A boolean flag. Defaults to `false` unless default is set to `true`.
*
* - `allowNo` option allows `--no-` prefix to negate boolean flag.
*/
function boolean(options = {}) {
return {
parse: async (b, _) => b,
...options,
allowNo: Boolean(options.allowNo),
type: 'boolean',
};
}
/**
* An integer flag. Throws an error if the provided value is not a valid integer.
*
* - `min` option allows to set a minimum value.
* - `max` option allows to set a maximum value.
*/
exports.integer = custom({
async parse(input, _, opts) {
if (!/^-?\d+$/.test(input))
throw new errors_1.CLIError(`Expected an integer but received: ${input}`);
const num = Number.parseInt(input, 10);
if (opts.min !== undefined && num < opts.min)
throw new errors_1.CLIError(`Expected an integer greater than or equal to ${opts.min} but received: ${input}`);
if (opts.max !== undefined && num > opts.max)
throw new errors_1.CLIError(`Expected an integer less than or equal to ${opts.max} but received: ${input}`);
return num;
},
});
/**
* A directory flag.
*
* - `exists` option allows you to throw an error if the directory does not exist.
*/
exports.directory = custom({
async parse(input, _, opts) {
if (opts.exists)
return (0, fs_1.dirExists)(input);
return input;
},
});
/**
* A file flag.
*
* - `exists` option allows you to throw an error if the file does not exist.
*/
exports.file = custom({
async parse(input, _, opts) {
if (opts.exists)
return (0, fs_1.fileExists)(input);
return input;
},
});
/**
* A URL flag that converts the provided value is a string.
*
* Throws an error if the string is not a valid URL.
*/
exports.url = custom({
async parse(input) {
try {
return new node_url_1.URL(input);
}
catch {
throw new errors_1.CLIError(`Expected a valid url but received: ${input}`);
}
},
});
/**
* A string flag.
*/
exports.string = custom();
/**
* Version flag that will print the CLI version and exit.
*/
const version = (opts = {}) => boolean({
description: 'Show CLI version.',
...opts,
async parse(_, ctx) {
ctx.log(ctx.config.userAgent);
ctx.exit(0);
},
});
exports.version = version;
/**
* A help flag that will print the CLI help and exit.
*/
const help = (opts = {}) => boolean({
description: 'Show CLI help.',
...opts,
async parse(_, cmd) {
const Help = await (0, help_1.loadHelpClass)(cmd.config);
await new Help(cmd.config, cmd.config.pjson.oclif.helpOptions ?? cmd.config.pjson.helpOptions).showHelp(cmd.id ? [cmd.id, ...cmd.argv] : cmd.argv);
cmd.exit(0);
},
});
exports.help = help;
function option(defaults) {
return (options = {}) => ({
parse: async (input, _ctx, _opts) => input,
...defaults,
...options,
input: [],
multiple: Boolean(options.multiple === undefined ? defaults.multiple : options.multiple),
type: 'option',
});
}

1
node_modules/@oclif/core/lib/flush.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export declare function flush(ms?: number): Promise<void>;

26
node_modules/@oclif/core/lib/flush.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flush = flush;
const error_1 = require("./errors/error");
function timeout(p, ms) {
function wait(ms, unref = false) {
return new Promise((resolve) => {
const t = setTimeout(() => resolve(null), ms);
if (unref)
t.unref();
});
}
return Promise.race([p, wait(ms, true).then(() => (0, error_1.error)('timed out'))]);
}
async function _flush() {
const p = new Promise((resolve) => {
process.stdout.once('drain', () => resolve(null));
});
const flushed = process.stdout.write('');
if (flushed)
return;
return p;
}
async function flush(ms = 10_000) {
await timeout(_flush(), ms);
}

33
node_modules/@oclif/core/lib/help/command.d.ts generated vendored Normal file
View File

@@ -0,0 +1,33 @@
import { Command } from '../command';
import * as Interfaces from '../interfaces';
import { HelpFormatter, HelpSectionRenderer } from './formatter';
export declare class CommandHelp extends HelpFormatter {
command: Command.Loadable;
config: Interfaces.Config;
opts: Interfaces.HelpOptions;
constructor(command: Command.Loadable, config: Interfaces.Config, opts: Interfaces.HelpOptions);
protected aliases(aliases: string[] | undefined): string | undefined;
protected arg(arg: Command.Arg.Any): string;
protected args(args: Command.Arg.Any[]): [string, string | undefined][] | undefined;
protected defaultUsage(): string;
protected description(): string | undefined;
protected examples(examples: Command.Example[] | string | undefined): string | undefined;
protected flagHelpLabel(flag: Command.Flag.Any, showOptions?: boolean): string;
protected flags(flags: Array<Command.Flag.Any>): [string, string | undefined][] | undefined;
protected flagsDescriptions(flags: Array<Command.Flag.Any>): string | undefined;
generate(): string;
protected groupFlags(flags: Array<Command.Flag.Any>): {
flagGroups: {
[name: string]: Array<Command.Flag.Any>;
};
mainFlags: Array<Command.Flag.Any>;
};
protected sections(): Array<{
generate: HelpSectionRenderer;
header: string;
}>;
protected usage(): string;
private formatIfCommand;
private isCommand;
}
export default CommandHelp;

338
node_modules/@oclif/core/lib/help/command.js generated vendored Normal file
View File

@@ -0,0 +1,338 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandHelp = void 0;
const ansis_1 = __importDefault(require("ansis"));
const ensure_arg_object_1 = require("../util/ensure-arg-object");
const ids_1 = require("../util/ids");
const util_1 = require("../util/util");
const theme_1 = require("../ux/theme");
const docopts_1 = require("./docopts");
const formatter_1 = require("./formatter");
// Don't use os.EOL because we need to ensure that a string
// written on any platform, that may use \r\n or \n, will be
// split on any platform, not just the os specific EOL at runtime.
const POSSIBLE_LINE_FEED = /\r\n|\n/;
/**
* Determines the sort order of flags. Will default to alphabetical if not set or set to an invalid value.
*/
function determineSortOrder(flagSortOrder) {
if (flagSortOrder === 'alphabetical')
return 'alphabetical';
if (flagSortOrder === 'none')
return 'none';
return 'alphabetical';
}
class CommandHelp extends formatter_1.HelpFormatter {
command;
config;
opts;
constructor(command, config, opts) {
super(config, opts);
this.command = command;
this.config = config;
this.opts = opts;
}
aliases(aliases) {
if (!aliases || aliases.length === 0)
return;
const body = aliases
.map((a) => [
(0, theme_1.colorize)(this.config?.theme?.dollarSign, '$'),
(0, theme_1.colorize)(this.config?.theme?.bin, this.config.bin),
(0, theme_1.colorize)(this.config?.theme?.alias, a),
].join(' '))
.join('\n');
return body;
}
arg(arg) {
const name = arg.name.toUpperCase();
if (arg.required)
return `${name}`;
return `[${name}]`;
}
args(args) {
if (args.filter((a) => a.description).length === 0)
return;
return args.map((a) => {
// Add ellipsis to indicate that the argument takes multiple values if strict is false
let name = this.command.strict === false ? `${a.name.toUpperCase()}...` : a.name.toUpperCase();
name = a.required ? `${name}` : `[${name}]`;
let description = a.description || '';
if (a.default)
description = `${(0, theme_1.colorize)(this.config?.theme?.flagDefaultValue, `[default: ${a.default}]`)} ${description}`;
if (a.options)
description = `${(0, theme_1.colorize)(this.config?.theme?.flagOptions, `(${a.options.join('|')})`)} ${description}`;
return [
(0, theme_1.colorize)(this.config?.theme?.flag, name),
description ? (0, theme_1.colorize)(this.config?.theme?.sectionDescription, description) : undefined,
];
});
}
defaultUsage() {
// Docopts by default
if (this.opts.docopts === undefined || this.opts.docopts) {
return docopts_1.DocOpts.generate(this.command);
}
return (0, util_1.compact)([
this.command.id,
Object.values(this.command.args ?? {})
?.filter((a) => !a.hidden)
.map((a) => this.arg(a))
.join(' '),
]).join(' ');
}
description() {
const cmd = this.command;
let description;
if (this.opts.hideCommandSummaryInDescription) {
description = [(cmd.description || '').split(POSSIBLE_LINE_FEED).at(-1) ?? ''];
}
else if (cmd.description) {
const summary = cmd.summary ? `${cmd.summary}\n` : null;
description = summary
? [...summary.split(POSSIBLE_LINE_FEED), ...(cmd.description || '').split(POSSIBLE_LINE_FEED)]
: (cmd.description || '').split(POSSIBLE_LINE_FEED);
}
if (description) {
return this.wrap(description.join('\n'));
}
}
examples(examples) {
if (!examples || examples.length === 0)
return;
const body = (0, util_1.castArray)(examples)
.map((a) => {
let description;
let commands;
if (typeof a === 'string') {
const lines = a.split(POSSIBLE_LINE_FEED).filter(Boolean);
// If the example is <description>\n<command> then format correctly
if (lines.length >= 2 && !this.isCommand(lines[0]) && lines.slice(1).every((i) => this.isCommand(i))) {
description = lines[0];
commands = lines.slice(1);
}
else {
return lines.map((line) => this.formatIfCommand(line)).join('\n');
}
}
else {
description = a.description;
commands = [a.command];
}
const multilineSeparator = this.config.platform === 'win32' ? (this.config.shell.includes('powershell') ? '`' : '^') : '\\';
// The command will be indented in the section, which is also indented
const finalIndentedSpacing = this.indentSpacing * 2;
const multilineCommands = commands
.map((c) =>
// First indent keeping room for escaped newlines
this.indent(this.wrap(this.formatIfCommand(c), finalIndentedSpacing + 4))
// Then add the escaped newline
.split(POSSIBLE_LINE_FEED)
.join(` ${multilineSeparator}\n `))
.join('\n');
return `${this.wrap(description, finalIndentedSpacing)}\n\n${multilineCommands}`;
})
.join('\n\n');
return body;
}
flagHelpLabel(flag, showOptions = false) {
let label = flag.helpLabel;
if (!label) {
const labels = [];
labels.push(flag.char ? `-${flag.char[0]}` : ' ');
if (flag.name) {
if (flag.type === 'boolean' && flag.allowNo) {
labels.push(`--[no-]${flag.name.trim()}`);
}
else {
labels.push(`--${flag.name.trim()}`);
}
}
label = labels.join(flag.char ? (0, theme_1.colorize)(this.config?.theme?.flagSeparator, ', ') : ' ');
}
if (flag.type === 'option') {
let value = docopts_1.DocOpts.formatUsageType(flag, this.opts.showFlagNameInTitle ?? false, this.opts.showFlagOptionsInTitle ?? showOptions);
if (!value.includes('|'))
value = (0, theme_1.colorize)('underline', value);
label += `=${value}`;
}
return (0, theme_1.colorize)(this.config.theme?.flag, label);
}
flags(flags) {
if (flags.length === 0)
return;
const noChar = flags.reduce((previous, current) => previous && current.char === undefined, true);
// eslint-disable-next-line complexity
return flags.map((flag) => {
let left = this.flagHelpLabel(flag);
if (noChar)
left = left.replace(' ', '');
let right = flag.summary || flag.description || '';
const canBeCached = !(this.opts.respectNoCacheDefault === true && flag.noCacheDefault === true);
if (flag.type === 'option' && flag.default && canBeCached) {
right = `${(0, theme_1.colorize)(this.config?.theme?.flagDefaultValue, `[default: ${flag.default}]`)} ${right}`;
}
if (flag.required)
right = `${(0, theme_1.colorize)(this.config?.theme?.flagRequired, '(required)')} ${right}`;
if (flag.type === 'option' && flag.options && !flag.helpValue && !this.opts.showFlagOptionsInTitle) {
right += (0, theme_1.colorize)(this.config?.theme?.flagOptions, `\n<options: ${flag.options.join('|')}>`);
}
return [left, (0, theme_1.colorize)(this.config?.theme?.sectionDescription, right.trim())];
});
}
flagsDescriptions(flags) {
const flagsWithExtendedDescriptions = flags.filter((flag) => flag.summary && flag.description);
if (flagsWithExtendedDescriptions.length === 0)
return;
const body = flagsWithExtendedDescriptions
.map((flag) => {
// Guaranteed to be set because of the filter above, but make ts happy
const summary = flag.summary || '';
let flagHelp = this.flagHelpLabel(flag, true);
if (!flag.char)
flagHelp = flagHelp.replace(' ', '');
flagHelp +=
flagHelp.length + summary.length + 2 < this.opts.maxWidth
? ' ' + summary
: '\n\n' + this.indent(this.wrap(summary, this.indentSpacing * 2));
return `${flagHelp}\n\n${this.indent(this.wrap(flag.description || '', this.indentSpacing * 2))}`;
})
.join('\n\n');
return body;
}
generate() {
const cmd = this.command;
const unsortedFlags = Object.entries(cmd.flags || {})
.filter(([, v]) => !v.hidden)
.map(([k, v]) => {
v.name = k;
return v;
});
const flags = determineSortOrder(this.opts.flagSortOrder) === 'alphabetical'
? (0, util_1.sortBy)(unsortedFlags, (f) => [!f.char, f.char, f.name])
: unsortedFlags;
const args = Object.values((0, ensure_arg_object_1.ensureArgObject)(cmd.args)).filter((a) => !a.hidden);
const output = (0, util_1.compact)(this.sections().map(({ generate, header }) => {
const body = generate({ args, cmd, flags }, header);
// Generate can return a list of sections
if (Array.isArray(body)) {
return body
.map((helpSection) => helpSection && helpSection.body && this.section(helpSection.header, helpSection.body))
.join('\n\n');
}
return body && this.section(header, body);
})).join('\n\n');
return output;
}
groupFlags(flags) {
const mainFlags = [];
const flagGroups = {};
for (const flag of flags) {
const group = flag.helpGroup;
if (group) {
if (!flagGroups[group])
flagGroups[group] = [];
flagGroups[group].push(flag);
}
else {
mainFlags.push(flag);
}
}
return { flagGroups, mainFlags };
}
sections() {
const sections = [
{
generate: () => this.usage(),
header: this.opts.usageHeader || 'USAGE',
},
{
generate: ({ args }, header) => [{ body: this.args(args), header }],
header: 'ARGUMENTS',
},
{
generate: ({ flags }, header) => {
const { flagGroups, mainFlags } = this.groupFlags(flags);
const flagSections = [];
const mainFlagBody = this.flags(mainFlags);
if (mainFlagBody)
flagSections.push({ body: mainFlagBody, header });
for (const [name, flags] of Object.entries(flagGroups)) {
const body = this.flags(flags);
if (body)
flagSections.push({ body, header: `${name.toUpperCase()} ${header}` });
}
return (0, util_1.compact)(flagSections);
},
header: 'FLAGS',
},
{
generate: () => this.description(),
header: 'DESCRIPTION',
},
{
generate: ({ cmd }) => this.aliases(cmd.aliases),
header: 'ALIASES',
},
{
generate: ({ cmd }) => {
const examples = cmd.examples || cmd.example;
return this.examples(examples);
},
header: 'EXAMPLES',
},
{
generate: ({ flags }) => this.flagsDescriptions(flags),
header: 'FLAG DESCRIPTIONS',
},
];
const allowedSections = this.opts.sections?.map((s) => s.toLowerCase());
return sections.filter(({ header }) => !allowedSections || allowedSections.includes(header.toLowerCase()));
}
usage() {
const { id, usage } = this.command;
const standardId = (0, ids_1.toStandardizedId)(id, this.config);
const configuredId = (0, ids_1.toConfiguredId)(id, this.config);
const body = (usage ? (0, util_1.castArray)(usage) : [this.defaultUsage()])
.map((u) => {
const allowedSpacing = this.opts.maxWidth - this.indentSpacing;
const dollarSign = (0, theme_1.colorize)(this.config?.theme?.dollarSign, '$');
const bin = (0, theme_1.colorize)(this.config?.theme?.bin, this.config.bin);
const command = (0, theme_1.colorize)(this.config?.theme?.command, '<%= command.id %>');
const commandDescription = (0, theme_1.colorize)(this.config?.theme?.sectionDescription, u
.replace('<%= command.id %>', '')
.replace(new RegExp(`^${standardId}`), '')
.replace(new RegExp(`^${configuredId}`), '')
.trim());
const line = `${dollarSign} ${bin} ${command} ${commandDescription}`.trim();
if (line.length > allowedSpacing) {
const splitIndex = line.slice(0, Math.max(0, allowedSpacing)).lastIndexOf(' ');
return (line.slice(0, Math.max(0, splitIndex)) +
'\n' +
this.indent(this.wrap(line.slice(Math.max(0, splitIndex)), this.indentSpacing * 2)));
}
return this.wrap(line);
})
.join('\n');
return body;
}
formatIfCommand(example) {
example = this.render(example);
const dollarSign = (0, theme_1.colorize)(this.config?.theme?.dollarSign, '$');
if (example.startsWith(this.config.bin))
return `${dollarSign} ${example}`;
if (example.startsWith(`$ ${this.config.bin}`))
return `${dollarSign}${example.replace(`$`, '')}`;
return example;
}
isCommand(example) {
return ansis_1.default
.strip(this.formatIfCommand(example))
.startsWith(`${(0, theme_1.colorize)(this.config?.theme?.dollarSign, '$')} ${this.config.bin}`);
}
}
exports.CommandHelp = CommandHelp;
exports.default = CommandHelp;

69
node_modules/@oclif/core/lib/help/docopts.d.ts generated vendored Normal file
View File

@@ -0,0 +1,69 @@
import { Command } from '../command';
/**
* DocOpts - See http://docopt.org/.
*
* flag.exclusive: groups elements when one of the mutually exclusive cases is a required flag: (--apple | --orange)
* flag.exclusive: groups elements when none of the mutually exclusive cases is required (optional flags): [--apple | --orange]
* flag.dependsOn: specifies that if one element is present, then another one is required: (--apple --orange)
*
* @example
* {
* name: 'classnames',
* required: true,
* exclusive: ['suitenames']
* ...
* },{
* name: 'suitenames',
* type: 'array'
* required: true
* ...
* }
*
* Results in:
* Usage: <%= command.id %> (-n <string> | -s <array>)
*
* @example
* {
* name: 'classnames',
* ...
* excludes: ['suitenames']
* },{
* name: 'suitenames',
* ...
* }
*
* Results in:
* Usage: <%= command.id %> [-n <string> | -s <string>]
*
* @example
* {
* name: 'classnames',
* ...
* dependsOn: ['suitenames']
* },{
* name: 'suitenames',
* type: 'flag'
* ...
* }
*
* Results in:
* Usage: <%= command.id %> (-n <string> -s)
*
* TODO:
* - Support nesting, eg:
* Usage: my_program (--either-this <and-that> | <or-this>)
* Usage: my_program [(<one-argument> <another-argument>)]
*
*/
export declare class DocOpts {
private cmd;
private flagList;
private flagMap;
constructor(cmd: Command.Loadable);
static formatUsageType(flag: Command.Flag.Any, showFlagName: boolean, showOptions: boolean): string;
static generate(cmd: Command.Loadable): string;
toString(): string;
private combineElementsToFlag;
private generateElements;
private groupFlagElements;
}

197
node_modules/@oclif/core/lib/help/docopts.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DocOpts = void 0;
const ensure_arg_object_1 = require("../util/ensure-arg-object");
/**
* DocOpts - See http://docopt.org/.
*
* flag.exclusive: groups elements when one of the mutually exclusive cases is a required flag: (--apple | --orange)
* flag.exclusive: groups elements when none of the mutually exclusive cases is required (optional flags): [--apple | --orange]
* flag.dependsOn: specifies that if one element is present, then another one is required: (--apple --orange)
*
* @example
* {
* name: 'classnames',
* required: true,
* exclusive: ['suitenames']
* ...
* },{
* name: 'suitenames',
* type: 'array'
* required: true
* ...
* }
*
* Results in:
* Usage: <%= command.id %> (-n <string> | -s <array>)
*
* @example
* {
* name: 'classnames',
* ...
* excludes: ['suitenames']
* },{
* name: 'suitenames',
* ...
* }
*
* Results in:
* Usage: <%= command.id %> [-n <string> | -s <string>]
*
* @example
* {
* name: 'classnames',
* ...
* dependsOn: ['suitenames']
* },{
* name: 'suitenames',
* type: 'flag'
* ...
* }
*
* Results in:
* Usage: <%= command.id %> (-n <string> -s)
*
* TODO:
* - Support nesting, eg:
* Usage: my_program (--either-this <and-that> | <or-this>)
* Usage: my_program [(<one-argument> <another-argument>)]
*
*/
class DocOpts {
cmd;
flagList;
flagMap;
constructor(cmd) {
this.cmd = cmd;
// Create a new map with references to the flags that we can manipulate.
this.flagMap = {};
this.flagList = Object.entries(cmd.flags || {})
.filter(([_, flag]) => !flag.hidden)
.map(([name, flag]) => {
this.flagMap[name] = flag;
return flag;
});
}
static formatUsageType(flag, showFlagName, showOptions) {
if (flag.type !== 'option')
return '';
let helpValues;
if (flag.helpValue) {
// if there is a given helpValue, use it
helpValues = typeof flag.helpValue === 'string' ? [flag.helpValue] : flag.helpValue;
}
else if (flag.options) {
// if there are options, show them if wanted
helpValues = [showOptions ? flag.options.join('|') : '<option>'];
}
else if (showFlagName) {
helpValues = [flag.name];
}
else {
// default to <value>
helpValues = ['<value>'];
}
return helpValues.map((v) => `${v}${flag.multiple ? '...' : ''}`).join(' ');
}
static generate(cmd) {
return new DocOpts(cmd).toString();
}
toString() {
const opts = ['<%= command.id %>'];
if (this.cmd.args) {
// If strict is false, add ellipsis to indicate that the argument takes multiple values
const suffix = this.cmd.strict === false ? '...' : '';
const a = Object.values((0, ensure_arg_object_1.ensureArgObject)(this.cmd.args))
.filter((arg) => !arg.hidden)
.map((arg) => arg.required ? `${arg.name.toUpperCase()}${suffix}` : `[${arg.name.toUpperCase()}${suffix}]`) || [];
opts.push(...a);
}
try {
opts.push(...Object.values(this.groupFlagElements()));
}
catch {
// If there is an error, just return no usage so we don't fail command help.
opts.push(...this.flagList.map((flag) => {
const name = flag.char ? `-${flag.char}` : `--${flag.name}`;
if (flag.type === 'boolean')
return name;
return `${name}=${DocOpts.formatUsageType(flag, false, true)}`;
}));
}
return opts.join(' ');
}
combineElementsToFlag(elementMap, flagName, flagNames, unionString) {
if (!this.flagMap[flagName]) {
return;
}
let isRequired = this.flagMap[flagName]?.required;
if (typeof isRequired !== 'boolean' || !isRequired) {
isRequired = flagNames.reduce((required, toCombine) => required || this.flagMap[toCombine]?.required || false, false);
}
for (const toCombine of flagNames) {
elementMap[flagName] = `${elementMap[flagName] || ''}${unionString}${elementMap[toCombine] || ''}`;
// We handled this flag, don't handle it again
delete elementMap[toCombine];
delete this.flagMap[toCombine];
}
elementMap[flagName] = isRequired ? `(${elementMap[flagName] || ''})` : `[${elementMap[flagName] || ''}]`;
// We handled this flag, don't handle it again
delete this.flagMap[flagName];
}
generateElements(elementMap = {}, flagGroups = []) {
const elementStrs = [];
for (const flag of flagGroups) {
let type = '';
// not all flags have short names
const flagName = flag.char ? `-${flag.char}` : `--${flag.name}`;
if (flag.type === 'option') {
type = ` ${DocOpts.formatUsageType(flag, false, true)}`;
}
const element = `${flagName}${type}`;
elementMap[flag.name] = element;
elementStrs.push(element);
}
return elementStrs;
}
groupFlagElements() {
const elementMap = {};
// Generate all doc opt elements for combining
// Show required flags first
this.generateElements(elementMap, this.flagList.filter((flag) => flag.required));
// Then show optional flags
this.generateElements(elementMap, this.flagList.filter((flag) => !flag.required));
for (const flag of this.flagList) {
if (Array.isArray(flag.dependsOn)) {
this.combineElementsToFlag(elementMap, flag.name, flag.dependsOn, ' ');
}
let exclusive;
if (Array.isArray(flag.exclusive)) {
exclusive = new Set(flag.exclusive);
}
if (Array.isArray(flag.combinable)) {
const combinableFlags = new Set(flag.combinable);
exclusive ??= new Set();
for (const item of this.flagList) {
// each flag not in the "combinable" list, is equivalent to an "exclusive" flag
if (flag !== item && !combinableFlags.has(item.name)) {
exclusive.add(item.name);
}
}
}
if (exclusive !== undefined && exclusive.size > 0) {
this.combineElementsToFlag(elementMap, flag.name, [...exclusive], ' | ');
}
}
// Since combineElementsToFlag deletes the references in this.flags when it combines
// them, this will go through the remaining list of uncombined elements.
for (const remainingFlagName of Object.keys(this.flagMap)) {
const remainingFlag = this.flagMap[remainingFlagName] || {};
if (!remainingFlag.required) {
elementMap[remainingFlag.name] = `[${elementMap[remainingFlag.name] || ''}]`;
}
}
return elementMap;
}
}
exports.DocOpts = DocOpts;

96
node_modules/@oclif/core/lib/help/formatter.d.ts generated vendored Normal file
View File

@@ -0,0 +1,96 @@
import { Command } from '../command';
import * as Interfaces from '../interfaces';
export type HelpSectionKeyValueTable = {
description: string;
name: string;
}[];
export type HelpSection = {
body: [string, string | undefined][] | HelpSectionKeyValueTable | string | undefined;
header: string;
} | undefined;
export type HelpSectionRenderer = (data: {
args: Command.Arg.Any[];
cmd: Command.Loadable;
flags: Command.Flag.Any[];
}, header: string) => HelpSection | HelpSection[] | string | undefined;
export declare class HelpFormatter {
protected config: Interfaces.Config;
indentSpacing: number;
protected opts: Interfaces.HelpOptions;
/**
* Takes a string and replaces `<%= prop =>` with the value of prop, where prop is anything on
* `config=Interfaces.Config` or `opts=Interface.HelpOptions`.
*
* ```javascript
* `<%= config.bin =>` // will resolve to the bin defined in `pjson.oclif`.
* ```
*/
render: (input: string) => string;
constructor(config: Interfaces.Config, opts?: Partial<Interfaces.HelpOptions>);
/**
* Indent by `this.indentSpacing`. The text should be wrap based on terminal width before indented.
*
* In order to call indent multiple times on the same set or text, the caller must wrap based on
* the number of times the text has been indented. For example.
*
* ```javascript
* const body = `main line\n${indent(wrap('indented example line', 4))}`
* const header = 'SECTION'
* console.log(`${header}\n${indent(wrap(body))}`
* ```
* will output
* ```
* SECTION
* main line
* indented example line
* ```
*
* If the terminal width was 24 and the `4` was not provided in the first wrap, it would like like the following.
* ```
* SECTION
* main line
* indented example
* line
* ```
* @param body the text to indent
* @param spacing the final number of spaces this text will be indented
* @returns the formatted indented text
*/
indent(body: string, spacing?: number): string;
renderList(input: (string | undefined)[][], opts: {
indentation: number;
multiline?: boolean | undefined;
spacer?: string | undefined;
stripAnsi?: boolean | undefined;
}): string;
section(header: string, body: [string, string | undefined][] | HelpSection | HelpSectionKeyValueTable | string): string;
/**
* Wrap text according to `opts.maxWidth` which is typically set to the terminal width. All text
* will be rendered before bring wrapped, otherwise it could mess up the lengths.
*
* A terminal will automatically wrap text, so this method is primarily used for indented
* text. For indented text, specify the indentation so it is taken into account during wrapping.
*
* Here is an example of wrapping with indentation.
* ```
* <------ terminal window width ------>
* <---------- no indentation --------->
* This is my text that will be wrapped
* once it passes maxWidth.
*
* <- indent -><------ text space ----->
* This is my text that will
* be wrapped once it passes
* maxWidth.
*
* <-- indent not taken into account ->
* This is my text that will
* be wrapped
* once it passes maxWidth.
* ```
* @param body the text to wrap
* @param spacing the indentation size to subtract from the terminal width
* @returns the formatted wrapped text
*/
wrap(body: string, spacing?: number): string;
}

194
node_modules/@oclif/core/lib/help/formatter.js generated vendored Normal file
View File

@@ -0,0 +1,194 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HelpFormatter = void 0;
const ansis_1 = __importDefault(require("ansis"));
const indent_string_1 = __importDefault(require("indent-string"));
const string_width_1 = __importDefault(require("string-width"));
const widest_line_1 = __importDefault(require("widest-line"));
const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
const screen_1 = require("../screen");
const theme_1 = require("../ux/theme");
const util_1 = require("./util");
class HelpFormatter {
config;
indentSpacing = 2;
opts;
/**
* Takes a string and replaces `<%= prop =>` with the value of prop, where prop is anything on
* `config=Interfaces.Config` or `opts=Interface.HelpOptions`.
*
* ```javascript
* `<%= config.bin =>` // will resolve to the bin defined in `pjson.oclif`.
* ```
*/
render;
constructor(config, opts = {}) {
this.config = config;
this.opts = { maxWidth: screen_1.stdtermwidth, ...opts };
this.render = (0, util_1.template)(this);
}
/**
* Indent by `this.indentSpacing`. The text should be wrap based on terminal width before indented.
*
* In order to call indent multiple times on the same set or text, the caller must wrap based on
* the number of times the text has been indented. For example.
*
* ```javascript
* const body = `main line\n${indent(wrap('indented example line', 4))}`
* const header = 'SECTION'
* console.log(`${header}\n${indent(wrap(body))}`
* ```
* will output
* ```
* SECTION
* main line
* indented example line
* ```
*
* If the terminal width was 24 and the `4` was not provided in the first wrap, it would like like the following.
* ```
* SECTION
* main line
* indented example
* line
* ```
* @param body the text to indent
* @param spacing the final number of spaces this text will be indented
* @returns the formatted indented text
*/
indent(body, spacing = this.indentSpacing) {
return (0, indent_string_1.default)(body, spacing);
}
renderList(input, opts) {
if (input.length === 0) {
return '';
}
const renderMultiline = () => {
let output = '';
for (let [left, right] of input) {
if (!left && !right)
continue;
if (left) {
if (opts.stripAnsi)
left = ansis_1.default.strip(left);
output += this.wrap(left.trim(), opts.indentation);
}
if (right) {
if (opts.stripAnsi)
right = ansis_1.default.strip(right);
output += '\n';
output += this.indent(this.wrap(right.trim(), opts.indentation + 2), 4);
}
output += '\n\n';
}
return output.trim();
};
if (opts.multiline)
return renderMultiline();
const maxLength = (0, widest_line_1.default)(input.map((i) => i[0]).join('\n'));
let output = '';
let spacer = opts.spacer || '\n';
let cur = '';
for (const [left, r] of input) {
let right = r;
if (cur) {
output += spacer;
output += cur;
}
cur = left || '';
if (opts.stripAnsi)
cur = ansis_1.default.strip(cur);
if (!right) {
cur = cur.trim();
continue;
}
if (opts.stripAnsi)
right = ansis_1.default.strip(right);
right = this.wrap(right.trim(), opts.indentation + maxLength + 2);
const [first, ...lines] = right.split('\n').map((s) => s.trim());
cur += ' '.repeat(maxLength - (0, string_width_1.default)(cur) + 2);
cur += first;
if (lines.length === 0) {
continue;
}
// if we start putting too many lines down, render in multiline format
if (lines.length > 4)
return renderMultiline();
// if spacer is not defined, separate all rows with a newline
if (!opts.spacer)
spacer = '\n';
cur += '\n';
cur += this.indent(lines.join('\n'), maxLength + 2);
}
if (cur) {
output += spacer;
output += cur;
}
return output.trim();
}
section(header, body) {
// Always render template strings with the provided render function before wrapping and indenting
let newBody;
if (typeof body === 'string') {
newBody = this.render(body);
}
else if (Array.isArray(body)) {
newBody = body.map((entry) => {
if ('name' in entry) {
const tableEntry = entry;
return [this.render(tableEntry.name), this.render(tableEntry.description)];
}
const [left, right] = entry;
return [this.render(left), right && this.render(right)];
});
}
else if ('header' in body) {
return this.section(body.header, body.body);
}
else {
newBody = body
.map((entry) => [entry.name, entry.description])
.map(([left, right]) => [this.render(left), right && this.render(right)]);
}
const output = [
(0, theme_1.colorize)(this.config?.theme?.sectionHeader, (0, theme_1.colorize)('bold', header)),
(0, theme_1.colorize)(this.config?.theme?.sectionDescription, this.indent(Array.isArray(newBody) ? this.renderList(newBody, { indentation: 2, stripAnsi: this.opts.stripAnsi }) : newBody)),
].join('\n');
return this.opts.stripAnsi ? ansis_1.default.strip(output) : output;
}
/**
* Wrap text according to `opts.maxWidth` which is typically set to the terminal width. All text
* will be rendered before bring wrapped, otherwise it could mess up the lengths.
*
* A terminal will automatically wrap text, so this method is primarily used for indented
* text. For indented text, specify the indentation so it is taken into account during wrapping.
*
* Here is an example of wrapping with indentation.
* ```
* <------ terminal window width ------>
* <---------- no indentation --------->
* This is my text that will be wrapped
* once it passes maxWidth.
*
* <- indent -><------ text space ----->
* This is my text that will
* be wrapped once it passes
* maxWidth.
*
* <-- indent not taken into account ->
* This is my text that will
* be wrapped
* once it passes maxWidth.
* ```
* @param body the text to wrap
* @param spacing the indentation size to subtract from the terminal width
* @returns the formatted wrapped text
*/
wrap(body, spacing = this.indentSpacing) {
return (0, wrap_ansi_1.default)(this.render(body), this.opts.maxWidth - spacing, { hard: true });
}
}
exports.HelpFormatter = HelpFormatter;

46
node_modules/@oclif/core/lib/help/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { Command } from '../command';
import * as Interfaces from '../interfaces';
import { CommandHelp } from './command';
import { HelpFormatter } from './formatter';
export { CommandHelp } from './command';
export { HelpFormatter, type HelpSection, type HelpSectionKeyValueTable, type HelpSectionRenderer } from './formatter';
export { getHelpFlagAdditions, normalizeArgv, standardizeIDFromArgv } from './util';
export declare abstract class HelpBase extends HelpFormatter {
constructor(config: Interfaces.Config, opts?: Partial<Interfaces.HelpOptions>);
/**
* Show help for an individual command
* @param command
* @param topics
*/
abstract showCommandHelp(command: Command.Loadable, topics: Interfaces.Topic[]): Promise<void>;
/**
* Show help, used in multi-command CLIs
* @param args passed into your command, useful for determining which type of help to display
*/
abstract showHelp(argv: string[]): Promise<void>;
}
export declare class Help extends HelpBase {
protected CommandHelpClass: typeof CommandHelp;
constructor(config: Interfaces.Config, opts?: Partial<Interfaces.HelpOptions>);
private get _topics();
protected get sortedCommands(): Command.Loadable[];
protected get sortedTopics(): Interfaces.Topic[];
protected command(command: Command.Loadable): string;
protected description(c: Command.Loadable): string;
protected formatCommand(command: Command.Loadable): string;
protected formatCommands(commands: Array<Command.Loadable>): string;
protected formatRoot(): string;
protected formatTopic(topic: Interfaces.Topic): string;
protected formatTopics(topics: Interfaces.Topic[]): string;
protected getCommandHelpClass(command: Command.Loadable): CommandHelp;
protected log(...args: string[]): void;
showCommandHelp(command: Command.Loadable): Promise<void>;
showHelp(argv: string[]): Promise<void>;
protected showRootHelp(): Promise<void>;
protected showTopicHelp(topic: Interfaces.Topic): Promise<void>;
protected summary(c: Command.Loadable): string | undefined;
}
interface HelpBaseDerived {
new (config: Interfaces.Config, opts?: Partial<Interfaces.HelpOptions>): HelpBase;
}
export declare function loadHelpClass(config: Interfaces.Config): Promise<HelpBaseDerived>;

345
node_modules/@oclif/core/lib/help/index.js generated vendored Normal file
View File

@@ -0,0 +1,345 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Help = exports.HelpBase = exports.standardizeIDFromArgv = exports.normalizeArgv = exports.getHelpFlagAdditions = exports.HelpFormatter = exports.CommandHelp = void 0;
exports.loadHelpClass = loadHelpClass;
const ansis_1 = __importDefault(require("ansis"));
const ts_path_1 = require("../config/ts-path");
const error_1 = require("../errors/error");
const module_loader_1 = require("../module-loader");
const symbols_1 = require("../symbols");
const cache_default_value_1 = require("../util/cache-default-value");
const ids_1 = require("../util/ids");
const util_1 = require("../util/util");
const ux_1 = require("../ux");
const theme_1 = require("../ux/theme");
const command_1 = require("./command");
const formatter_1 = require("./formatter");
const root_1 = __importDefault(require("./root"));
const util_2 = require("./util");
var command_2 = require("./command");
Object.defineProperty(exports, "CommandHelp", { enumerable: true, get: function () { return command_2.CommandHelp; } });
var formatter_2 = require("./formatter");
Object.defineProperty(exports, "HelpFormatter", { enumerable: true, get: function () { return formatter_2.HelpFormatter; } });
var util_3 = require("./util");
Object.defineProperty(exports, "getHelpFlagAdditions", { enumerable: true, get: function () { return util_3.getHelpFlagAdditions; } });
Object.defineProperty(exports, "normalizeArgv", { enumerable: true, get: function () { return util_3.normalizeArgv; } });
Object.defineProperty(exports, "standardizeIDFromArgv", { enumerable: true, get: function () { return util_3.standardizeIDFromArgv; } });
function getHelpSubject(args, config) {
// for each help flag that starts with '--' create a new flag with same name sans '--'
const mergedHelpFlags = (0, util_2.getHelpFlagAdditions)(config);
for (const arg of args) {
if (arg === '--')
return;
if (mergedHelpFlags.includes(arg) || arg === 'help')
continue;
if (arg.startsWith('-'))
return;
return arg;
}
}
class HelpBase extends formatter_1.HelpFormatter {
constructor(config, opts = {}) {
super(config, opts);
if (!config.topicSeparator)
config.topicSeparator = ':'; // back-support @oclif/config
}
}
exports.HelpBase = HelpBase;
class Help extends HelpBase {
CommandHelpClass = command_1.CommandHelp;
constructor(config, opts = {}) {
super(config, opts);
}
/*
* _topics is to work around Interfaces.topics mistakenly including commands that do
* not have children, as well as topics. A topic has children, either commands or other topics. When
* this is fixed upstream config.topics should return *only* topics with children,
* and this can be removed.
*/
get _topics() {
return this.config.topics.filter((topic) => {
// it is assumed a topic has a child if it has children
const hasChild = this.config.topics.some((subTopic) => subTopic.name.includes(`${topic.name}:`));
return hasChild;
});
}
get sortedCommands() {
let { commands } = this.config;
commands = commands.filter((c) => this.opts.all || !c.hidden);
commands = (0, util_1.sortBy)(commands, (c) => c.id);
commands = (0, util_1.uniqBy)(commands, (c) => c.id);
return commands;
}
get sortedTopics() {
let topics = this._topics;
topics = topics.filter((t) => this.opts.all || !t.hidden);
topics = (0, util_1.sortBy)(topics, (t) => t.name);
topics = (0, util_1.uniqBy)(topics, (t) => t.name);
return topics;
}
command(command) {
return this.formatCommand(command);
}
description(c) {
const description = this.render(c.description || '');
if (c.summary) {
return description;
}
return description.split('\n').slice(1).join('\n');
}
formatCommand(command) {
if (this.config.topicSeparator !== ':') {
command.id = command.id.replaceAll(':', this.config.topicSeparator);
command.aliases = command.aliases && command.aliases.map((a) => a.replaceAll(':', this.config.topicSeparator));
}
const help = this.getCommandHelpClass(command);
return help.generate();
}
formatCommands(commands) {
if (commands.length === 0)
return '';
const body = this.renderList(commands
.filter((c) => (this.opts.hideAliasesFromRoot ? !c.aliases?.includes(c.id) : true))
.map((c) => {
if (this.config.topicSeparator !== ':')
c.id = c.id.replaceAll(':', this.config.topicSeparator);
const summary = this.summary(c);
return [
(0, theme_1.colorize)(this.config?.theme?.command, c.id),
summary && (0, theme_1.colorize)(this.config?.theme?.sectionDescription, ansis_1.default.strip(summary)),
];
}), {
indentation: 2,
spacer: '\n',
stripAnsi: this.opts.stripAnsi,
});
return this.section('COMMANDS', body);
}
formatRoot() {
const help = new root_1.default(this.config, this.opts);
return help.root();
}
formatTopic(topic) {
let description = this.render(topic.description || '');
const summary = description.split('\n')[0];
description = description.split('\n').slice(1).join('\n');
let topicID = `${topic.name}:COMMAND`;
if (this.config.topicSeparator !== ':')
topicID = topicID.replaceAll(':', this.config.topicSeparator);
let output = (0, util_1.compact)([
(0, theme_1.colorize)(this.config?.theme?.commandSummary, summary),
this.section(this.opts.usageHeader || 'USAGE', `${(0, theme_1.colorize)(this.config?.theme?.dollarSign, '$')} ${(0, theme_1.colorize)(this.config?.theme?.bin, this.config.bin)} ${topicID}`),
description &&
this.section('DESCRIPTION', this.wrap((0, theme_1.colorize)(this.config?.theme?.sectionDescription, description))),
]).join('\n\n');
if (this.opts.stripAnsi)
output = ansis_1.default.strip(output);
return output + '\n';
}
formatTopics(topics) {
if (topics.length === 0)
return '';
const body = this.renderList(topics.map((c) => {
if (this.config.topicSeparator !== ':')
c.name = c.name.replaceAll(':', this.config.topicSeparator);
return [
(0, theme_1.colorize)(this.config?.theme?.topic, c.name),
c.description && this.render((0, theme_1.colorize)(this.config?.theme?.sectionDescription, c.description.split('\n')[0])),
];
}), {
indentation: 2,
spacer: '\n',
stripAnsi: this.opts.stripAnsi,
});
return this.section('TOPICS', body);
}
getCommandHelpClass(command) {
return new this.CommandHelpClass(command, this.config, this.opts);
}
log(...args) {
return this.opts.sendToStderr ? ux_1.ux.stderr(args) : ux_1.ux.stdout(args);
}
async showCommandHelp(command) {
const name = command.id;
const depth = name.split(':').length;
const subTopics = this.sortedTopics.filter((t) => t.name.startsWith(name + ':') && t.name.split(':').length === depth + 1);
const subCommands = this.sortedCommands.filter((c) => c.id.startsWith(name + ':') && c.id.split(':').length === depth + 1);
const plugin = this.config.plugins.get(command.pluginName);
const state = this.config.pjson?.oclif?.state || plugin?.pjson?.oclif?.state || command.state;
if (state) {
this.log(state === 'deprecated'
? `${(0, util_2.formatCommandDeprecationWarning)((0, ids_1.toConfiguredId)(name, this.config), command.deprecationOptions)}\n`
: `This command is in ${state}.\n`);
}
if (command.deprecateAliases && command.aliases.includes(name)) {
const actualCmd = this.config.commands.find((c) => c.aliases.includes(name));
const actualCmdName = actualCmd ? (0, ids_1.toConfiguredId)(actualCmd.id, this.config) : '';
const opts = { ...command.deprecationOptions, ...(actualCmd ? { to: actualCmdName } : {}) };
this.log(`${(0, util_2.formatCommandDeprecationWarning)((0, ids_1.toConfiguredId)(name, this.config), opts)}\n`);
}
const summary = this.summary(command);
if (summary) {
this.log(summary + '\n');
}
this.log(this.formatCommand(command));
this.log('');
if (subTopics.length > 0) {
this.log(this.formatTopics(subTopics));
this.log('');
}
if (subCommands.length > 0) {
const aliases = [];
const uniqueSubCommands = subCommands.filter((p) => {
aliases.push(...p.aliases);
return !aliases.includes(p.id);
});
this.log(this.formatCommands(uniqueSubCommands));
this.log('');
}
}
async showHelp(argv) {
const originalArgv = argv.slice(1);
argv = argv.filter((arg) => !(0, util_2.getHelpFlagAdditions)(this.config).includes(arg));
if (this.config.topicSeparator !== ':')
argv = (0, util_2.standardizeIDFromArgv)(argv, this.config);
const subject = getHelpSubject(argv, this.config);
if (!subject) {
if (this.config.isSingleCommandCLI) {
const rootCmd = this.config.findCommand(symbols_1.SINGLE_COMMAND_CLI_SYMBOL);
if (rootCmd) {
// set the command id to an empty string to prevent the
// SINGLE_COMMAND_CLI_SYMBOL from being displayed in the help output
rootCmd.id = '';
await this.showCommandHelp(rootCmd);
return;
}
}
await this.showRootHelp();
return;
}
const command = this.config.findCommand(subject);
if (command) {
if (command.id === symbols_1.SINGLE_COMMAND_CLI_SYMBOL) {
// If the command is the root command of a single command CLI,
// then set the command id to an empty string to prevent the
// the SINGLE_COMMAND_CLI_SYMBOL from being displayed in the help output.
command.id = '';
}
if (command.hasDynamicHelp && command.pluginType !== 'jit') {
const loaded = await command.load();
for (const [name, flag] of Object.entries(loaded.flags ?? {})) {
// As of v3 each flag that needs to be re-evaluated has the `hasDynamicHelp` property.
// However, we cannot assume that the absence of this property means that the flag
// doesn't need to be re-evaluated since any command from a v2 or older plugin will
// not have the `hasDynamicHelp` property on it.
// In the future we could improve performance by skipping any flag that doesn't
// have `hasDynamicHelp === true`
if (flag.type === 'boolean')
continue;
// eslint-disable-next-line no-await-in-loop
command.flags[name].default = await (0, cache_default_value_1.cacheDefaultValue)(flag, false);
}
await this.showCommandHelp(command);
}
else {
await this.showCommandHelp(command);
}
return;
}
const topic = this.config.findTopic(subject);
if (topic) {
await this.showTopicHelp(topic);
return;
}
if (this.config.flexibleTaxonomy) {
const matches = this.config.findMatches(subject, originalArgv);
if (matches.length > 0) {
const result = await this.config.runHook('command_incomplete', {
argv: originalArgv.filter((o) => !subject.split(':').includes(o)),
id: subject,
matches,
});
if (result.successes.length > 0)
return;
}
}
(0, error_1.error)(`Command ${subject} not found.`);
}
async showRootHelp() {
let rootTopics = this.sortedTopics;
let rootCommands = this.sortedCommands;
const state = this.config.pjson?.oclif?.state;
if (state) {
this.log(state === 'deprecated' ? `${this.config.bin} is deprecated` : `${this.config.bin} is in ${state}.\n`);
}
this.log(this.formatRoot());
this.log('');
if (!this.opts.all) {
rootTopics = rootTopics.filter((t) => !t.name.includes(':'));
rootCommands = rootCommands.filter((c) => !c.id.includes(':'));
}
if (rootTopics.length > 0) {
this.log(this.formatTopics(rootTopics));
this.log('');
}
if (rootCommands.length > 0) {
rootCommands = rootCommands.filter((c) => c.id);
this.log(this.formatCommands(rootCommands));
this.log('');
}
}
async showTopicHelp(topic) {
const { name } = topic;
const depth = name.split(':').length;
const subTopics = this.sortedTopics.filter((t) => t.name.startsWith(name + ':') && t.name.split(':').length === depth + 1);
const commands = this.sortedCommands.filter((c) => c.id.startsWith(name + ':') && c.id.split(':').length === depth + 1);
const state = this.config.pjson?.oclif?.state;
if (state)
this.log(`This topic is in ${state}.\n`);
this.log(this.formatTopic(topic));
if (subTopics.length > 0) {
this.log(this.formatTopics(subTopics));
this.log('');
}
if (commands.length > 0) {
this.log(this.formatCommands(commands));
this.log('');
}
}
summary(c) {
if (this.opts.sections && !this.opts.sections.map((s) => s.toLowerCase()).includes('summary'))
return;
if (c.summary)
return (0, theme_1.colorize)(this.config?.theme?.commandSummary, this.render(c.summary.split('\n')[0]));
return c.description && (0, theme_1.colorize)(this.config?.theme?.commandSummary, this.render(c.description).split('\n')[0]);
}
}
exports.Help = Help;
function extractClass(exported) {
return exported && exported.default ? exported.default : exported;
}
function determineLocation(helpClass) {
if (typeof helpClass === 'string')
return { identifier: 'default', target: helpClass };
if (!helpClass.identifier)
return { ...helpClass, identifier: 'default' };
return helpClass;
}
async function loadHelpClass(config) {
if (config.pjson.oclif?.helpClass) {
const { identifier, target } = determineLocation(config.pjson.oclif?.helpClass);
try {
const path = (await (0, ts_path_1.tsPath)(config.root, target)) ?? target;
const module = await (0, module_loader_1.load)(config, path);
const helpClass = module[identifier] ?? (identifier === 'default' ? extractClass(module) : undefined);
return extractClass(helpClass);
}
catch (error) {
throw new Error(`Unable to load configured help class "${target}", failed with message:\n${error.message}`);
}
}
return Help;
}

11
node_modules/@oclif/core/lib/help/root.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import * as Interfaces from '../interfaces';
import { HelpFormatter } from './formatter';
export default class RootHelp extends HelpFormatter {
config: Interfaces.Config;
opts: Interfaces.HelpOptions;
constructor(config: Interfaces.Config, opts: Interfaces.HelpOptions);
protected description(): string | undefined;
root(): string;
protected usage(): string;
protected version(): string;
}

47
node_modules/@oclif/core/lib/help/root.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ansis_1 = __importDefault(require("ansis"));
const util_1 = require("../util/util");
const theme_1 = require("../ux/theme");
const formatter_1 = require("./formatter");
class RootHelp extends formatter_1.HelpFormatter {
config;
opts;
constructor(config, opts) {
super(config, opts);
this.config = config;
this.opts = opts;
}
description() {
let description = this.config.pjson.oclif.description || this.config.pjson.description || '';
description = this.render(description);
description = description.split('\n').slice(1).join('\n');
if (!description)
return;
return this.section('DESCRIPTION', this.wrap((0, theme_1.colorize)(this.config?.theme?.sectionDescription, description)));
}
root() {
let description = this.config.pjson.oclif.description || this.config.pjson.description || '';
description = this.render(description);
description = description.split('\n')[0];
let output = (0, util_1.compact)([
(0, theme_1.colorize)(this.config?.theme?.commandSummary, description),
this.version(),
this.usage(),
this.description(),
]).join('\n\n');
if (this.opts.stripAnsi)
output = ansis_1.default.strip(output);
return output;
}
usage() {
return this.section(this.opts.usageHeader || 'USAGE', this.wrap(`${(0, theme_1.colorize)(this.config?.theme?.dollarSign, '$')} ${(0, theme_1.colorize)(this.config?.theme?.bin, this.config.bin)} ${(0, theme_1.colorize)(this.config?.theme?.sectionDescription, '[COMMAND]')}`));
}
version() {
return this.section('VERSION', this.wrap((0, theme_1.colorize)(this.config?.theme?.version, this.config.userAgent)));
}
}
exports.default = RootHelp;

7
node_modules/@oclif/core/lib/help/util.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { Deprecation, Config as IConfig } from '../interfaces';
export declare function template(context: any): (t: string) => string;
export declare function standardizeIDFromArgv(argv: string[], config: IConfig): string[];
export declare function getHelpFlagAdditions(config: IConfig): string[];
export declare function formatFlagDeprecationWarning(flag: string, opts: Deprecation | true): string;
export declare function formatCommandDeprecationWarning(command: string, opts?: Deprecation): string;
export declare function normalizeArgv(config: IConfig, argv?: string[]): string[];

129
node_modules/@oclif/core/lib/help/util.js generated vendored Normal file
View File

@@ -0,0 +1,129 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.template = template;
exports.standardizeIDFromArgv = standardizeIDFromArgv;
exports.getHelpFlagAdditions = getHelpFlagAdditions;
exports.formatFlagDeprecationWarning = formatFlagDeprecationWarning;
exports.formatCommandDeprecationWarning = formatCommandDeprecationWarning;
exports.normalizeArgv = normalizeArgv;
const ejs = __importStar(require("ejs"));
const util_1 = require("../config/util");
const ids_1 = require("../util/ids");
function template(context) {
function render(t) {
return ejs.render(t, context);
}
return render;
}
const isFlag = (s) => s.startsWith('-');
const isArgWithValue = (s) => s.includes('=');
function collateSpacedCmdIDFromArgs(argv, config) {
if (argv.length === 1)
return argv;
const findId = (argv) => {
const ids = (0, util_1.collectUsableIds)(config.commandIDs);
const final = [];
const idPresent = (id) => ids.has(id);
const finalizeId = (s) => (s ? [...final, s] : final).filter(Boolean).join(':');
const hasArgs = () => {
const id = finalizeId();
if (!id)
return false;
const cmd = config.findCommand(id);
return Boolean(cmd && (cmd.strict === false || Object.keys(cmd.args ?? {}).length > 0));
};
for (const arg of argv) {
if (idPresent(finalizeId(arg)))
final.push(arg);
// If the parent topic has a command that expects positional arguments, then we cannot
// assume that any subsequent string could be part of the command name
else if (isArgWithValue(arg) || isFlag(arg) || hasArgs())
break;
else
final.push(arg);
}
return finalizeId();
};
const id = findId(argv);
if (id) {
const argvSlice = argv.slice(id.split(':').length);
return [id, ...argvSlice];
}
return argv; // ID is argv[0]
}
function standardizeIDFromArgv(argv, config) {
if (argv.length === 0)
return argv;
if (config.topicSeparator === ' ')
argv = collateSpacedCmdIDFromArgs(argv, config);
else if (config.topicSeparator !== ':')
argv[0] = (0, ids_1.toStandardizedId)(argv[0], config);
return argv;
}
function getHelpFlagAdditions(config) {
const helpFlags = ['--help'];
const additionalHelpFlags = config.pjson.oclif.additionalHelpFlags ?? [];
return [...new Set([...additionalHelpFlags, ...helpFlags]).values()];
}
function formatFlagDeprecationWarning(flag, opts) {
let message = `The "${flag}" flag has been deprecated`;
if (opts === true)
return `${message}.`;
if (opts.message)
return opts.message;
if (opts.version) {
message += ` and will be removed in version ${opts.version}`;
}
message += opts.to ? `. Use "${opts.to}" instead.` : '.';
return message;
}
function formatCommandDeprecationWarning(command, opts) {
let message = `The "${command}" command has been deprecated`;
if (!opts)
return `${message}.`;
if (opts.message)
return opts.message;
if (opts.version) {
message += ` and will be removed in version ${opts.version}`;
}
message += opts.to ? `. Use "${opts.to}" instead.` : '.';
return message;
}
function normalizeArgv(config, argv = process.argv.slice(2)) {
if (config.topicSeparator !== ':' && !argv[0]?.includes(':'))
argv = standardizeIDFromArgv(argv, config);
return argv;
}

19
node_modules/@oclif/core/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
export * as Args from './args';
export { Command } from './command';
export { Config, Plugin } from './config';
export * as Errors from './errors';
export { handle } from './errors/handle';
export { execute } from './execute';
export * as Flags from './flags';
export { flush } from './flush';
export { CommandHelp, Help, HelpBase, type HelpSection, type HelpSectionKeyValueTable, type HelpSectionRenderer, loadHelpClass, } from './help';
export * as Interfaces from './interfaces';
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 { type Settings, settings } from './settings';
export { toConfiguredId, toStandardizedId } from './util/ids';
export { ux } from './ux';

100
node_modules/@oclif/core/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,100 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ux = exports.toStandardizedId = exports.toConfiguredId = exports.settings = exports.Performance = exports.Parser = exports.ModuleLoader = exports.getLogger = exports.Interfaces = exports.loadHelpClass = exports.HelpBase = exports.Help = exports.CommandHelp = exports.flush = exports.Flags = exports.execute = exports.handle = exports.Errors = exports.Plugin = exports.Config = exports.Command = exports.Args = void 0;
const util_1 = require("./util/util");
function checkCWD() {
try {
process.cwd();
}
catch (error) {
if (error.code === 'ENOENT') {
process.stderr.write('WARNING: current directory does not exist\n');
}
}
}
function checkNodeVersion() {
if (process.env.OCLIF_DISABLE_ENGINE_WARNING && (0, util_1.isTruthy)(process.env.OCLIF_DISABLE_ENGINE_WARNING))
return;
try {
const path = require('node:path');
const semver = require('semver');
const root = path.join(__dirname, '..');
const pjson = require(path.join(root, 'package.json'));
if (!semver.satisfies(process.versions.node, pjson.engines.node)) {
process.emitWarning(`Node version must be ${pjson.engines.node} to use this CLI. Current node version: ${process.versions.node}`);
}
}
catch {
// ignore
}
}
checkCWD();
checkNodeVersion();
exports.Args = __importStar(require("./args"));
var command_1 = require("./command");
Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return command_1.Command; } });
var config_1 = require("./config");
Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return config_1.Config; } });
Object.defineProperty(exports, "Plugin", { enumerable: true, get: function () { return config_1.Plugin; } });
exports.Errors = __importStar(require("./errors"));
var handle_1 = require("./errors/handle");
Object.defineProperty(exports, "handle", { enumerable: true, get: function () { return handle_1.handle; } });
var execute_1 = require("./execute");
Object.defineProperty(exports, "execute", { enumerable: true, get: function () { return execute_1.execute; } });
exports.Flags = __importStar(require("./flags"));
var flush_1 = require("./flush");
Object.defineProperty(exports, "flush", { enumerable: true, get: function () { return flush_1.flush; } });
var help_1 = require("./help");
Object.defineProperty(exports, "CommandHelp", { enumerable: true, get: function () { return help_1.CommandHelp; } });
Object.defineProperty(exports, "Help", { enumerable: true, get: function () { return help_1.Help; } });
Object.defineProperty(exports, "HelpBase", { enumerable: true, get: function () { return help_1.HelpBase; } });
Object.defineProperty(exports, "loadHelpClass", { enumerable: true, get: function () { return help_1.loadHelpClass; } });
exports.Interfaces = __importStar(require("./interfaces"));
var logger_1 = require("./logger");
Object.defineProperty(exports, "getLogger", { enumerable: true, get: function () { return logger_1.getLogger; } });
var main_1 = require("./main");
Object.defineProperty(exports, "run", { enumerable: true, get: function () { return main_1.run; } });
exports.ModuleLoader = __importStar(require("./module-loader"));
exports.Parser = __importStar(require("./parser"));
var performance_1 = require("./performance");
Object.defineProperty(exports, "Performance", { enumerable: true, get: function () { return performance_1.Performance; } });
var settings_1 = require("./settings");
Object.defineProperty(exports, "settings", { enumerable: true, get: function () { return settings_1.settings; } });
var ids_1 = require("./util/ids");
Object.defineProperty(exports, "toConfiguredId", { enumerable: true, get: function () { return ids_1.toConfiguredId; } });
Object.defineProperty(exports, "toStandardizedId", { enumerable: true, get: function () { return ids_1.toStandardizedId; } });
var ux_1 = require("./ux");
Object.defineProperty(exports, "ux", { enumerable: true, get: function () { return ux_1.ux; } });

View File

@@ -0,0 +1,2 @@
export type AlphabetUppercase = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z';
export type AlphabetLowercase = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';

2
node_modules/@oclif/core/lib/interfaces/alphabet.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

22
node_modules/@oclif/core/lib/interfaces/args.d.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import { ArgInput } from './parser';
/**
* Infer the args that are returned by Command.parse. This is useful for when you want to assign the args as a class property.
*
* @example
* export type StatusArgs = Interfaces.InferredArgs<typeof Status.args>
*
* export default class Status {
* static args = {
* force: Args.boolean({char: 'f', description: 'a flag'}),
* }
*
* public args!: StatusArgs
*
* public async run(): Promise<StatusArgs> {
* const result = await this.parse(Status)
* this.args = result.args
* return result.args
* }
* }
*/
export type InferredArgs<T> = T extends ArgInput<infer F> ? F : unknown;

2
node_modules/@oclif/core/lib/interfaces/args.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

139
node_modules/@oclif/core/lib/interfaces/config.d.ts generated vendored Normal file
View File

@@ -0,0 +1,139 @@
import { Command } from '../command';
import { Hook, Hooks } from './hooks';
import { OclifConfiguration, PJSON, S3Templates } from './pjson';
import { Options, Plugin } from './plugin';
import { Theme } from './theme';
import { Topic } from './topic';
export type LoadOptions = Config | Options | string | undefined;
export type PlatformTypes = 'wsl' | NodeJS.Platform;
export type ArchTypes = 'arm' | 'arm64' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x32' | 'x64' | 'x86';
export type PluginVersionDetail = {
root: string;
type: string;
version: string;
};
export type VersionDetails = {
architecture: string;
cliVersion: string;
nodeVersion: string;
osVersion?: string;
pluginVersions?: Record<string, PluginVersionDetail>;
rootPath?: string;
shell?: string;
};
export interface Config {
/**
* process.arch
*/
readonly arch: ArchTypes;
/**
* bin name of CLI command
*/
readonly bin: string;
/**
* name of any bin aliases that will execute the cli
*/
readonly binAliases?: string[] | undefined;
readonly binPath?: string | undefined;
/**
* cache directory to use for CLI
*
* example ~/Library/Caches/mycli or ~/.cache/mycli
*/
readonly cacheDir: string;
readonly channel: string;
readonly commandIDs: string[];
readonly commands: Command.Loadable[];
/**
* config directory to use for CLI
*
* example: ~/.config/mycli
*/
readonly configDir: string;
/**
* data directory to use for CLI
*
* example: ~/.local/share/mycli
*/
readonly dataDir: string;
/**
* base dirname to use in cacheDir/configDir/dataDir
*/
readonly dirname: string;
findCommand(id: string, opts: {
must: true;
}): Command.Loadable;
findCommand(id: string, opts?: {
must: boolean;
}): Command.Loadable | undefined;
findMatches(id: string, argv: string[]): Command.Loadable[];
findTopic(id: string, opts: {
must: true;
}): Topic;
findTopic(id: string, opts?: {
must: boolean;
}): Topic | undefined;
readonly flexibleTaxonomy?: boolean;
getAllCommandIDs(): string[];
getAllCommands(): Command.Loadable[];
getPluginsList(): Plugin[];
/**
* path to home directory
*
* example: /home/myuser
*/
readonly home: string;
readonly isSingleCommandCLI: boolean;
readonly name: string;
/**
* npm registry to use for installing plugins
*/
readonly npmRegistry?: string | undefined;
readonly nsisCustomization?: string | undefined;
readonly pjson: PJSON;
/**
* process.platform
*/
readonly platform: PlatformTypes;
readonly plugins: Map<string, Plugin>;
readonly root: string;
runCommand<T = unknown>(id: string, argv?: string[], cachedCommand?: Command.Loadable): Promise<T>;
runHook<T extends keyof Hooks>(event: T, opts: Hooks[T]['options'], timeout?: number, captureErrors?: boolean): Promise<Hook.Result<Hooks[T]['return']>>;
s3Key(type: 'unversioned' | 'versioned', ext: '.tar.gz' | '.tar.xz', 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;
scopedEnvVarKeys(key: string): string[];
scopedEnvVarTrue(key: string): boolean;
/**
* active shell
*/
readonly shell: string;
readonly theme?: Theme | undefined;
readonly topics: Topic[];
topicSeparator: ' ' | ':';
readonly updateConfig: NonNullable<OclifConfiguration['update']>;
/**
* user agent to use for http calls
*
* example: mycli/1.2.3 (darwin-x64) node-9.0.0
*/
readonly userAgent: string;
readonly valid: boolean;
readonly version: string;
readonly versionDetails: VersionDetails;
/**
* if windows
*/
readonly windows: boolean;
}
export declare namespace Config {
namespace s3Key {
interface Options {
[key: string]: any;
arch?: ArchTypes;
platform?: PlatformTypes;
}
}
}

2
node_modules/@oclif/core/lib/interfaces/config.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

27
node_modules/@oclif/core/lib/interfaces/errors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
export type CommandError = Error & {
exitCode?: number;
};
export interface OclifError {
oclif: {
exit?: number | undefined;
};
}
export interface PrettyPrintableError {
/**
* a unique error code for this error class
*/
code?: string | undefined;
/**
* message to display related to the error
*/
message?: string | undefined;
/**
* a url to find out more information related to this error
* or fixing the error
*/
ref?: string | undefined;
/**
* a suggestion that may be useful or provide additional context
*/
suggestions?: string[] | undefined;
}

2
node_modules/@oclif/core/lib/interfaces/errors.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

34
node_modules/@oclif/core/lib/interfaces/flags.d.ts generated vendored Normal file
View File

@@ -0,0 +1,34 @@
import { FlagInput } from './parser';
/**
* Infer the flags that are returned by Command.parse. This is useful for when you want to assign the flags as a class property.
*
* @example
* export type StatusFlags = Interfaces.InferredFlags<typeof Status.flags && typeof Status.baseFlags>
*
* export abstract class BaseCommand extends Command {
* static enableJsonFlag = true
*
* static flags = {
* config: Flags.string({
* description: 'specify config file',
* }),
* }
* }
*
* export default class Status extends BaseCommand {
* static flags = {
* force: Flags.boolean({char: 'f', description: 'a flag'}),
* }
*
* public flags!: StatusFlags
*
* public async run(): Promise<StatusFlags> {
* const result = await this.parse(Status)
* this.flags = result.flags
* return result.flags
* }
* }
*/
export type InferredFlags<T> = T extends FlagInput<infer F> ? F & {
json: boolean | undefined;
} : unknown;

2
node_modules/@oclif/core/lib/interfaces/flags.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

58
node_modules/@oclif/core/lib/interfaces/help.d.ts generated vendored Normal file
View File

@@ -0,0 +1,58 @@
export interface HelpOptions {
all?: boolean;
/**
* Use docopts as the usage. Defaults to true.
*/
docopts?: boolean;
/**
* Order in which to sort flags in help output. Defaults to `alphabetical`.
*
* `alphabetical`: Sort flags alphabetically. All flags with short characters will come first.
* `none`: Do not sort flags. They will appear in the order in which they were defined on the command.
*/
flagSortOrder?: 'alphabetical' | 'none';
/**
* If true, hide command aliases from the root help output. Defaults to false.
*/
hideAliasesFromRoot?: boolean;
/**
* By default, the command summary is show at the top of the help and as the first line in
* the command description. Repeating the summary in the command description improves readability
* especially for long command help output. If there is no `command.summary`, the first line of
* the description is treated as the summary. Some CLIs, especially with very simple commands, may
* not want the duplication.
*/
hideCommandSummaryInDescription?: boolean;
maxWidth: number;
/**
* Respect the `noCacheDefault` property on flags. Defaults to false.
*/
respectNoCacheDefault?: boolean;
/**
* Only show the help for the specified sections. Defaults to all sections.
*/
sections?: string[];
/**
* By default, the help output is sent to stdout. If this is true, it will be sent to stderr.
*/
sendToStderr?: boolean;
/**
* By default, titles show flag values as `<value>`. Some CLI developers may prefer titles
* to show the flag name as the value. i.e. `--myflag=myflag` instead of `--myflag=<value>`.
* An individual flag can set this using `flag.helpValue=flag.name`.
*/
showFlagNameInTitle?: boolean;
/**
* By default, option values on flags are shown in the flag's description. This is because
* long options list ruin the formatting of help. If a CLI knows all commands will not
* do this, it can be turned off at a help level using this property. An individual flag
* can set this using `flag.helpValue=options.join('|')`.
*/
showFlagOptionsInTitle?: boolean;
stripAnsi?: boolean;
/**
* Use USAGE, but some may want to use USAGE as used in gnu man pages. See help recommendations at
* http://www.gnu.org/software/help2man/#--help-recommendations
*/
usageHeader?: string;
}

2
node_modules/@oclif/core/lib/interfaces/help.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

185
node_modules/@oclif/core/lib/interfaces/hooks.d.ts generated vendored Normal file
View File

@@ -0,0 +1,185 @@
import { Command } from '../command';
import { Config } from './config';
import { Input, OutputFlags } from './parser';
import { Plugin } from './plugin';
interface HookMeta {
options: Record<string, unknown>;
return: any;
}
type Context = {
debug(...args: any[]): void;
error(message: Error | string, options?: {
code?: string;
exit?: number;
}): void;
exit(code?: number): void;
log(message?: any, ...args: any[]): void;
warn(message: string): void;
};
export interface Hooks {
[event: string]: HookMeta;
command_incomplete: {
options: {
argv: string[];
id: string;
matches: Command.Loadable[];
};
return: unknown;
};
command_not_found: {
options: {
argv?: string[];
id: string;
};
return: unknown;
};
finally: {
options: {
argv: string[];
id: string;
Command: Command.Loadable | undefined;
error: Error | undefined;
};
return: void;
};
init: {
options: {
argv: string[];
id: string | undefined;
};
return: void;
};
jit_plugin_not_installed: {
options: {
argv: string[];
command: Command.Loadable;
id: string;
pluginName: string;
pluginVersion: string;
};
return: unknown;
};
'plugins:preinstall': {
options: {
plugin: {
name: string;
tag: string;
type: 'npm';
} | {
type: 'repo';
url: string;
};
};
return: void;
};
postrun: {
options: {
Command: Command.Class;
argv: string[];
result?: any;
};
return: void;
};
preparse: {
options: {
argv: string[];
options: Input<OutputFlags<any>, OutputFlags<any>, OutputFlags<any>>;
};
return: string[];
};
prerun: {
options: {
Command: Command.Class;
argv: string[];
};
return: void;
};
preupdate: {
options: {
channel: string;
version: string;
};
return: void;
};
update: {
options: {
channel: string;
version: string;
};
return: void;
};
}
export type Hook<T extends keyof P, P extends Hooks = Hooks> = (this: Hook.Context, options: P[T]['options'] & {
config: Config;
context: Context;
}) => Promise<P[T]['return']>;
export declare namespace Hook {
/**
* Runs at the end of the CLI lifecycle - regardless of success or failure.
*/
type Finally = Hook<'finally'>;
/**
* Runs when the CLI is initialized before a command is executed.
*/
type Init = Hook<'init'>;
/**
* Runs before the `plugins install` command from @oclif/plugin-plugins is run.
*/
type PluginsPreinstall = Hook<'plugins:preinstall'>;
/**
* Runs after the `init` hook, after a command is found but before it is executed.
*/
type Prerun = Hook<'prerun'>;
/**
* Runs after a command is successfully executed. Does not run if the command fails.
*/
type Postrun = Hook<'postrun'>;
/**
* Runs before the CLI is updated by `update` command from @oclif/plugin-update.
*/
type Preupdate = Hook<'preupdate'>;
/**
* Runs before a command's flags and args are parsed. Useful for modifying the command line arguments before they are parsed.
*
* The return value is a string[] of the modified arguments.
*/
type Preparse = Hook<'preparse'>;
/**
* Runs once the `update` command from @oclif/plugin-update is run.
*/
type Update = Hook<'update'>;
/**
* Runs when a command is not found.
*/
type CommandNotFound = Hook<'command_not_found'>;
/**
* Runs when a partial command is entered and no matching command is found.
*/
type CommandIncomplete = Hook<'command_incomplete'>;
/**
* Runs when a command from an uninstalled JIT plugins is run.
*/
type JitPluginNotInstalled = Hook<'jit_plugin_not_installed'>;
interface Context {
config: Config;
debug(...args: any[]): void;
error(message: Error | string, options?: {
code?: string;
exit?: number;
}): void;
exit(code?: number): void;
log(message?: any, ...args: any[]): void;
warn(message: string): void;
}
interface Result<T> {
failures: Array<{
error: Error;
plugin: Plugin;
}>;
successes: Array<{
plugin: Plugin;
result: T;
}>;
}
}
export {};

2
node_modules/@oclif/core/lib/interfaces/hooks.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

16
node_modules/@oclif/core/lib/interfaces/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
export type { AlphabetLowercase, AlphabetUppercase } from './alphabet';
export type { InferredArgs } from './args';
export type { ArchTypes, Config, LoadOptions, PlatformTypes, PluginVersionDetail, VersionDetails } from './config';
export type { CommandError, OclifError, PrettyPrintableError } from './errors';
export type { InferredFlags } from './flags';
export type { HelpOptions } from './help';
export type { Hook, Hooks } from './hooks';
export type { Logger } from './logger';
export type { Manifest } from './manifest';
export type { Arg, ArgDefinition, ArgInput, BooleanFlag, CustomOptions, Deprecation, Flag, FlagDefinition, FlagInput, Input, OptionFlag, OutputArgs, OutputFlags, ParserOutput, } from './parser';
export type { LinkedPlugin, OclifConfiguration, PJSON, S3, S3Templates, UserPJSON, UserPlugin } from './pjson';
export type { Options, Plugin, PluginOptions } from './plugin';
export type { S3Manifest } from './s3-manifest';
export type { Theme } from './theme';
export type { Topic } from './topic';
export type { TSConfig } from './ts-config';

2
node_modules/@oclif/core/lib/interfaces/index.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

9
node_modules/@oclif/core/lib/interfaces/logger.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
export type Logger = {
debug: (formatter: unknown, ...args: unknown[]) => void;
error: (formatter: unknown, ...args: unknown[]) => void;
info: (formatter: unknown, ...args: unknown[]) => void;
trace: (formatter: unknown, ...args: unknown[]) => void;
warn: (formatter: unknown, ...args: unknown[]) => void;
child: (namespace: string) => Logger;
namespace: string;
};

2
node_modules/@oclif/core/lib/interfaces/logger.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,7 @@
import { Command } from '../command';
export type Manifest = {
commands: {
[id: string]: Command.Cached;
};
version: string;
};

2
node_modules/@oclif/core/lib/interfaces/manifest.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

467
node_modules/@oclif/core/lib/interfaces/parser.d.ts generated vendored Normal file
View File

@@ -0,0 +1,467 @@
import { Command } from '../command';
import { AlphabetLowercase, AlphabetUppercase } from './alphabet';
export type FlagOutput = {
[name: string]: any;
};
export type ArgOutput = {
[name: string]: any;
};
export type CLIParseErrorOptions = {
parse: {
input?: ParserInput | undefined;
output?: ParserOutput | undefined;
};
exit?: number | undefined;
};
export type OutputArgs<T extends ParserInput['args']> = {
[P in keyof T]: any;
};
export type OutputFlags<T extends ParserInput['flags']> = {
[P in keyof T]: any;
};
export type ParserOutput<TFlags extends OutputFlags<any> = any, BFlags extends OutputFlags<any> = any, TArgs extends OutputFlags<any> = any> = {
flags: TFlags & BFlags & {
json: boolean | undefined;
};
args: TArgs;
argv: unknown[];
raw: ParsingToken[];
metadata: Metadata;
nonExistentFlags: string[];
};
export type ArgToken = {
type: 'arg';
arg: string;
input: string;
};
export type FlagToken = {
type: 'flag';
flag: string;
input: string;
};
export type ParsingToken = ArgToken | FlagToken;
export type FlagUsageOptions = {
displayRequired?: boolean;
};
export type Metadata = {
flags: {
[key: string]: MetadataFlag;
};
};
export type MetadataFlag = {
setFromDefault?: boolean;
defaultHelp?: unknown;
};
export type ListItem = [string, string | undefined];
export type List = ListItem[];
export type CustomOptions = Record<string, unknown>;
export type DefaultContext<T> = {
options: T;
flags: Record<string, string>;
};
/**
* Type to define a default value for a flag.
* @param context The context of the flag.
*/
export type FlagDefault<T, P = CustomOptions> = T | ((context: DefaultContext<P & OptionFlag<T, P>>) => Promise<T>);
/**
* Type to define a defaultHelp value for a flag.
* The defaultHelp value is used in the help output for the flag and when writing a manifest.
* It is also can be used to provide a value for the flag when issuing certain error messages.
*
* @param context The context of the flag.
*/
export type FlagDefaultHelp<T, P = CustomOptions> = T | ((context: DefaultContext<P & OptionFlag<T, P>>) => Promise<string | undefined>);
/**
* Type to define a default value for an arg.
* @param context The context of the arg.
*/
export type ArgDefault<T, P = CustomOptions> = T | ((context: DefaultContext<Arg<T, P>>) => Promise<T>);
/**
* Type to define a defaultHelp value for an arg.
* @param context The context of the arg.
*/
export type ArgDefaultHelp<T, P = CustomOptions> = T | ((context: DefaultContext<Arg<T, P>>) => Promise<string | undefined>);
export type FlagRelationship = string | {
name: string;
when: (flags: Record<string, unknown>) => Promise<boolean>;
};
export type Relationship = {
type: 'all' | 'some' | 'none' | 'only';
flags: FlagRelationship[];
};
export type Deprecation = {
to?: string;
message?: string;
version?: string | number;
};
export type FlagProps = {
name: string;
char?: AlphabetLowercase | AlphabetUppercase;
/**
* A short summary of flag usage to show in the flag list.
* If not provided, description will be used.
*/
summary?: string;
/**
* A description of flag usage. If summary is provided, the description
* is assumed to be a longer description and will be shown in a separate
* section within help.
*/
description?: string;
/**
* The flag label to show in help. Defaults to "[-<char>] --<name>" where -<char> is
* only displayed if the char is defined.
*/
helpLabel?: string;
/**
* Shows this flag in a separate list in the help.
*/
helpGroup?: string;
/**
* Accept an environment variable as input
*/
env?: string;
/**
* If true, the flag will not be shown in the help.
*/
hidden?: boolean;
/**
* If true, the flag will be required.
*/
required?: boolean;
/**
* List of flags that this flag depends on.
*/
dependsOn?: string[];
/**
* List of flags that cannot be used with this flag.
*/
exclusive?: string[];
/**
* List of the only flags that can be used with this flag.
*/
combinable?: string[];
/**
* Exactly one of these flags must be provided.
*/
exactlyOne?: string[];
/**
* Define complex relationships between flags.
*/
relationships?: Relationship[];
/**
* Make the flag as deprecated.
*/
deprecated?: true | Deprecation;
/**
* Alternate names that can be used for this flag.
*/
aliases?: string[];
/**
* Alternate short chars that can be used for this flag.
*/
charAliases?: (AlphabetLowercase | AlphabetUppercase)[];
/**
* Emit deprecation warning when a flag alias is provided
*/
deprecateAliases?: boolean;
/**
* If true, the value returned by defaultHelp will not be cached in the oclif.manifest.json.
* This is helpful if the default value contains sensitive data that shouldn't be published to npm.
*/
noCacheDefault?: boolean;
/**
* At least one of these flags must be provided.
*/
atLeastOne?: string[];
};
export type ArgProps = {
name: string;
/**
* A description of flag usage. If summary is provided, the description
* is assumed to be a longer description and will be shown in a separate
* section within help.
*/
description?: string;
/**
* If true, the flag will not be shown in the help.
*/
hidden?: boolean;
/**
* If true, the flag will be required.
*/
required?: boolean;
options?: string[];
ignoreStdin?: boolean;
/**
* If true, the value returned by defaultHelp will not be cached in the oclif.manifest.json.
* This is helpful if the default value contains sensitive data that shouldn't be published to npm.
*/
noCacheDefault?: boolean;
};
export type BooleanFlagProps = FlagProps & {
type: 'boolean';
allowNo: boolean;
};
export type OptionFlagProps = FlagProps & {
type: 'option';
helpValue?: string | string[];
options?: readonly string[];
multiple?: boolean;
/**
* Parse one value per flag; allow `-m val1 -m val2`, disallow `-m val1 val2`.
* Set to true to use "multiple: true" flags together with args.
* Only respected if multiple is set to true.
*/
multipleNonGreedy?: boolean;
/**
* Delimiter to separate the values for a multiple value flag.
* Only respected if multiple is set to true. Default behavior is to
* separate on spaces.
*/
delimiter?: ',';
/**
* Allow input value to be read from stdin if the provided value is `-`.
* If set to `only`, the flag will only accept input from stdin.
* Should only be used on one flag at a time.
*/
allowStdin?: boolean | 'only';
};
export type FlagParserContext = Command & {
token: FlagToken;
};
type NonNullableElementOf<T> = [NonNullable<T>] extends [Array<infer U>] ? U : T;
export type FlagParser<T, I extends string | boolean, P = CustomOptions> = (input: I, context: FlagParserContext, opts: P & OptionFlag<T, P>) => Promise<NonNullableElementOf<T> | undefined>;
export type ArgParserContext = Command & {
token: ArgToken;
};
export type ArgParser<T, P = CustomOptions> = (input: string, context: ArgParserContext, opts: P & Arg<T, P>) => Promise<T>;
export type Arg<T, P = CustomOptions> = ArgProps & {
options?: T[];
defaultHelp?: ArgDefaultHelp<T>;
input: string[];
default?: ArgDefault<T | undefined>;
parse: ArgParser<T, P>;
};
export type ArgDefinition<T, P = CustomOptions> = {
(options: P & ({
required: true;
} | {
default: ArgDefault<T>;
}) & Partial<Arg<T, P>>): Arg<T, P>;
(options?: P & Partial<Arg<T, P>>): Arg<T | undefined, P>;
};
export type BooleanFlag<T> = FlagProps & BooleanFlagProps & {
/**
* specifying a default of false is the same as not specifying a default
*/
default?: FlagDefault<boolean>;
parse: (input: boolean, context: FlagParserContext, opts: FlagProps & BooleanFlagProps) => Promise<T>;
};
export type OptionFlag<T, P = CustomOptions> = FlagProps & OptionFlagProps & {
parse: FlagParser<T | undefined, string, P>;
defaultHelp?: FlagDefaultHelp<T, P>;
input: string[];
default?: FlagDefault<T | undefined, P>;
};
type ReturnTypeSwitches = {
multiple: boolean;
requiredOrDefaulted: boolean;
};
/**
* The logic here is as follows:
* - If requiredOrDefaulted is true && multiple is true, then the return type is T[]
* - It's possible that T extends an Array, if so we want to return T so that the return isn't T[][]
* - If requiredOrDefaulted is true && multiple is false, then the return type is T
* - If requiredOrDefaulted is false && multiple is true, then the return type is T[] | undefined
* - It's possible that T extends an Array, if so we want to return T so that the return isn't T[][]
* - If requiredOrDefaulted is false && multiple is false, then the return type is T | undefined
*/
type FlagReturnType<T, R extends ReturnTypeSwitches> = R['requiredOrDefaulted'] extends true ? R['multiple'] extends true ? [T] extends [Array<unknown>] ? T : T[] : T : R['multiple'] extends true ? [T] extends [Array<unknown>] ? T | undefined : T[] | undefined : T | undefined;
/**
* FlagDefinition types a function that takes `options` and returns an OptionFlag<T>.
*
* This is returned by `Flags.custom()` and `Flags.option()`, which each take a `defaults` object
* that mirrors the OptionFlag interface.
*
* The `T` in the `OptionFlag<T>` return type is determined by a combination of the provided defaults for
* `multiple`, `required`, and `default` and the provided options for those same properties. If these properties
* are provided in the options, they override the defaults.
*
* no options or defaults -> T | undefined
* `required` -> T
* `default` -> T
* `multiple` -> T[] | undefined
* `required` + `multiple` -> T[]
* `default` + `multiple` -> T[]
*/
export type FlagDefinition<T, P = CustomOptions, R extends ReturnTypeSwitches = {
multiple: false;
requiredOrDefaulted: false;
}> = {
(options: P & {
multiple: false;
required: true;
} & Partial<OptionFlag<FlagReturnType<T, {
multiple: false;
requiredOrDefaulted: true;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: false;
requiredOrDefaulted: true;
}>>;
(options: P & {
multiple: true;
required: false;
} & Partial<OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: false;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: false;
}>>;
(options: P & {
multiple: false;
required: false;
} & Partial<OptionFlag<FlagReturnType<T, {
multiple: false;
requiredOrDefaulted: false;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: false;
requiredOrDefaulted: false;
}>>;
(options: R['multiple'] extends true ? // `multiple` is defaulted to true and either `required=true` or `default` are provided in options
P & ({
required: true;
} | {
default: OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>, P>['default'];
}) & Partial<OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>, P>> : // `multiple` is NOT defaulted to true and either `required=true` or `default` are provided in options
P & {
multiple?: false | undefined;
} & ({
required: true;
} | {
default: OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>, P>['default'];
}) & Partial<OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>>;
(options: R['multiple'] extends true ? // `multiple` is defaulted to true and either `required=true` or `default` are provided in options
P & ({
required: true;
} | {
default: OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: true;
}>, P>['default'];
}) & Partial<OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: true;
}>, P>> : // `multiple` is NOT defaulted to true but `multiple=true` and either `required=true` or `default` are provided in options
P & {
multiple: true;
} & ({
required: true;
} | {
default: OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: true;
}>, P>['default'];
}) & Partial<OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: true;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: true;
}>>;
(options: P & {
multiple?: false | undefined;
} & ({
required: true;
} | {
default: OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>, P>['default'];
}) & Partial<OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: true;
}>>;
(options: P & {
required: false;
} & Partial<OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: false;
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: R['multiple'];
requiredOrDefaulted: false;
}>>;
(options: P & {
multiple: false;
} & Partial<OptionFlag<FlagReturnType<T, {
multiple: false;
requiredOrDefaulted: R['requiredOrDefaulted'];
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: false;
requiredOrDefaulted: R['requiredOrDefaulted'];
}>>;
(options?: P & {
multiple?: false | undefined;
} & Partial<OptionFlag<FlagReturnType<T, R>, P>>): OptionFlag<FlagReturnType<T, R>>;
(options: P & {
multiple: true;
} & Partial<OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: R['requiredOrDefaulted'];
}>, P>>): OptionFlag<FlagReturnType<T, {
multiple: true;
requiredOrDefaulted: R['requiredOrDefaulted'];
}>>;
};
export type Flag<T> = BooleanFlag<T> | OptionFlag<T>;
export type Input<TFlags extends FlagOutput, BFlags extends FlagOutput, AFlags extends ArgOutput> = {
flags?: FlagInput<TFlags>;
baseFlags?: FlagInput<BFlags>;
enableJsonFlag?: true | false;
args?: ArgInput<AFlags>;
strict?: boolean | undefined;
context?: ParserContext;
'--'?: boolean;
};
export type ParserInput = {
argv: string[];
flags: FlagInput<any>;
args: ArgInput<any>;
strict: boolean;
context: ParserContext | undefined;
'--'?: boolean | undefined;
};
export type ParserContext = Command & {
token?: FlagToken | ArgToken | undefined;
};
export type FlagInput<T extends FlagOutput = {
[flag: string]: any;
}> = {
[P in keyof T]: Flag<T[P]>;
};
export type ArgInput<T extends ArgOutput = {
[arg: string]: any;
}> = {
[P in keyof T]: Arg<T[P]>;
};
export {};

2
node_modules/@oclif/core/lib/interfaces/parser.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

313
node_modules/@oclif/core/lib/interfaces/pjson.d.ts generated vendored Normal file
View File

@@ -0,0 +1,313 @@
import { HelpOptions } from './help';
import { Theme } from './theme';
export type CommandDiscovery = {
/**
* The strategy to use for loading commands.
*
* - `pattern` will use glob patterns to find command files in the specified `target`.
* - `explicit` will use `import` (or `require` for CJS) to load the commands from the
* specified `target`.
* - `single` will use the `target` which should export a command class. This is for CLIs that
* only have a single command.
*
* In both cases, the `oclif.manifest.json` file will be used to find the commands if it exists.
*/
strategy: 'pattern' | 'explicit' | 'single';
/**
* If the `strategy` is `pattern`, this is the **directory** to use to find command files.
*
* If the `strategy` is `explicit`, this is the **file** that exports the commands.
* - This export must be an object with keys that are the command names and values that are the command classes.
* - Unless `identifier` is specified, the default export will be used.
*
* @example
* ```typescript
* // in src/commands.ts
* import {Command} from '@oclif/core'
* import Hello from './commands/hello/index.js'
* import HelloWorld from './commands/hello/world.js'
*
* export default {
* hello: Hello,
* 'hello:world': HelloWorld,
* } satisfies Record<string, Command.Class>
* ```
*/
target: string;
/**
* The glob patterns to use to find command files when no `oclif.manifest.json` is present.
* This is only used when `strategy` is `pattern`.
*/
globPatterns?: string[];
/**
* The name of the export to used when loading the command object from the `target` file. Only
* used when `strategy` is `explicit`. Defaults to `default`.
*
* @example
* ```typescript
* // in src/commands.ts
* import {Command} from '@oclif/core'
* import Hello from './commands/hello/index.js'
* import HelloWorld from './commands/hello/world.js'
*
* export const MY_COMMANDS = {
* hello: Hello,
* 'hello:world': HelloWorld,
* } satisfies Record<string, Command.Class>
* ```
*
* In the package.json:
* ```json
* {
* "oclif": {
* "commands": {
* "strategy": "explicit",
* "target": "./dist/index.js",
* "identifier": "MY_COMMANDS"
* }
* }
* ```
*/
identifier?: string;
};
export type HookOptions = {
/**
* The file path containing hook.
*/
target: string;
/**
* The name of the export to use when loading the hook function from the `target` file. Defaults to `default`.
*/
identifier: 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;
indexVersionLimit?: number | undefined;
templates?: {
target: S3Templates;
vanilla: S3Templates;
} | undefined;
xz?: boolean | undefined;
};
export type OclifConfiguration = {
/**
* 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;
};
/**
* 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[] | (string | HookOptions)[];
};
/**
* Plugins that can be installed just-in-time.
*/
jitPlugins?: Record<string, string>;
macos?: {
identifier?: string;
sign?: string;
};
/**
* 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?: OclifConfiguration['topics'];
};
};
/**
* Tar flags configuration for different platforms.
*
* {
* "tarFlags": {
* "win32": "--force-local",
* "darwin": "--no-xattrs"
* }
* }
*
*/
tarFlags?: {
[platform: string]: string;
};
update?: {
autoupdate?: {
debounce?: number;
rollout?: number;
};
disableNpmLookup?: boolean;
node?: {
targets?: string[];
version?: string;
options?: string | string[];
};
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 UserPlugin = {
name: string;
tag?: string;
type: 'user';
url?: string;
};
export type LinkedPlugin = {
name: string;
root: string;
type: 'link';
};
export type UserPJSON = {
oclif: {
plugins?: (UserPlugin | LinkedPlugin)[];
};
private?: boolean;
};
export type PJSON = {
[k: string]: any;
dependencies?: {
[name: string]: string;
};
devDependencies?: {
[name: string]: string;
};
name: string;
oclif: OclifConfiguration;
version: string;
};

2
node_modules/@oclif/core/lib/interfaces/pjson.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

104
node_modules/@oclif/core/lib/interfaces/plugin.d.ts generated vendored Normal file
View File

@@ -0,0 +1,104 @@
import { Command } from '../command';
import { Logger } from './logger';
import { HookOptions, PJSON } from './pjson';
import { Topic } from './topic';
export interface PluginOptions {
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 | undefined;
type?: string | undefined;
url?: string | undefined;
}
export interface Options extends PluginOptions {
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<string, Plugin> | undefined;
userPlugins?: boolean | undefined;
version?: string | undefined;
}
export interface Plugin {
/**
* ../config version
*/
_base: string;
/**
* aliases from package.json dependencies
*/
alias: string;
readonly commandIDs: string[];
commands: Command.Loadable[];
readonly commandsDir: string | undefined;
findCommand(id: string, opts: {
must: true;
}): Promise<Command.Class>;
findCommand(id: string, opts?: {
must: boolean;
}): Promise<Command.Class> | undefined;
readonly hasManifest: boolean;
hooks: {
[key: string]: HookOptions[];
};
/**
* True if the plugin is the root plugin.
*/
isRoot: boolean;
load(): Promise<void>;
/**
* Plugin is written in ESM or CommonJS
*/
moduleType: 'commonjs' | 'module';
/**
* name from package.json
*/
name: string;
readonly options: Options;
parent?: Plugin | undefined;
/**
* full package.json
*
* parsed with read-pkg
*/
pjson: PJSON;
/**
* base path of plugin
*/
root: string;
/**
* npm dist-tag of plugin
* only used for user plugins
*/
tag?: string | undefined;
readonly topics: Topic[];
/**
* used to tell the user how the plugin was installed
* examples: core, link, user, dev
*/
type: string;
/**
* if it appears to be an npm package but does not look like it's really a CLI plugin, this is set to false
*/
valid: boolean;
/**
* version from package.json
*
* example: 1.2.3
*/
version: string;
}

2
node_modules/@oclif/core/lib/interfaces/plugin.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,14 @@
export interface S3Manifest {
baseDir: string;
gz: string;
node: {
compatible: string;
recommended: string;
};
rollout?: number;
sha: string;
sha256gz: string;
sha256xz?: string;
version: string;
xz?: string;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

32
node_modules/@oclif/core/lib/interfaces/theme.d.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
export declare const STANDARD_ANSI: readonly ["white", "black", "blue", "yellow", "green", "red", "magenta", "cyan", "gray", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright", "bgBlack", "bgRed", "bgGreen", "bgYellow", "bgBlue", "bgMagenta", "bgCyan", "bgWhite", "bgGray", "bgBlackBright", "bgRedBright", "bgGreenBright", "bgYellowBright", "bgBlueBright", "bgMagentaBright", "bgCyanBright", "bgWhiteBright", "bold", "underline", "dim", "italic", "strikethrough"];
export type StandardAnsi = (typeof STANDARD_ANSI)[number];
export type JsonTheme = {
brace?: string | StandardAnsi;
bracket?: string | StandardAnsi;
colon?: string | StandardAnsi;
comma?: string | StandardAnsi;
key?: string | StandardAnsi;
string?: string | StandardAnsi;
number?: string | StandardAnsi;
boolean?: string | StandardAnsi;
null?: string | StandardAnsi;
};
export type Theme = {
[key: string]: string | StandardAnsi | Theme | undefined;
alias?: string | StandardAnsi;
bin?: string | StandardAnsi;
command?: string | StandardAnsi;
commandSummary?: string | StandardAnsi;
dollarSign?: string | StandardAnsi;
flag?: string | StandardAnsi;
flagDefaultValue?: string | StandardAnsi;
flagOptions?: string | StandardAnsi;
flagRequired?: string | StandardAnsi;
flagSeparator?: string | StandardAnsi;
json?: JsonTheme;
sectionDescription?: string | StandardAnsi;
sectionHeader?: string | StandardAnsi;
spinner?: string | StandardAnsi;
topic?: string | StandardAnsi;
version?: string | StandardAnsi;
};

44
node_modules/@oclif/core/lib/interfaces/theme.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.STANDARD_ANSI = void 0;
exports.STANDARD_ANSI = [
'white',
'black',
'blue',
'yellow',
'green',
'red',
'magenta',
'cyan',
'gray',
'blackBright',
'redBright',
'greenBright',
'yellowBright',
'blueBright',
'magentaBright',
'cyanBright',
'whiteBright',
'bgBlack',
'bgRed',
'bgGreen',
'bgYellow',
'bgBlue',
'bgMagenta',
'bgCyan',
'bgWhite',
'bgGray',
'bgBlackBright',
'bgRedBright',
'bgGreenBright',
'bgYellowBright',
'bgBlueBright',
'bgMagentaBright',
'bgCyanBright',
'bgWhiteBright',
'bold',
'underline',
'dim',
'italic',
'strikethrough',
];

5
node_modules/@oclif/core/lib/interfaces/topic.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
export interface Topic {
description?: string | undefined;
hidden?: boolean | undefined;
name: string;
}

2
node_modules/@oclif/core/lib/interfaces/topic.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

23
node_modules/@oclif/core/lib/interfaces/ts-config.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
export interface TSConfig {
compilerOptions: {
baseUrl?: string;
emitDecoratorMetadata?: boolean;
esModuleInterop?: boolean;
experimentalDecorators?: boolean;
jsx?: boolean;
module?: string;
moduleResolution?: string;
outDir?: string;
rootDir?: string;
rootDirs?: string[];
sourceMap?: boolean;
target?: string;
};
extends?: string;
'ts-node'?: {
esm?: boolean;
experimentalSpecifierResolution?: 'explicit' | 'node';
scope?: boolean;
swc?: boolean;
};
}

2
node_modules/@oclif/core/lib/interfaces/ts-config.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

14
node_modules/@oclif/core/lib/logger.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { LoadOptions } from './interfaces/config';
import { Logger } from './interfaces/logger';
/**
* Returns a logger instance for the given namespace.
* If a namespace is provided, a child logger is returned.
* If no namespace is provided, the root logger is returned.
*/
export declare function getLogger(namespace?: string): Logger;
/**
* Convenience function to create a debug function for a specific namespace
*/
export declare function makeDebug(namespace: string): Logger['debug'];
export declare function setLogger(loadOptions: LoadOptions): void;
export declare function clearLoggers(): void;

89
node_modules/@oclif/core/lib/logger.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLogger = getLogger;
exports.makeDebug = makeDebug;
exports.setLogger = setLogger;
exports.clearLoggers = clearLoggers;
const debug_1 = __importDefault(require("debug"));
const OCLIF_NS = 'oclif';
function makeLogger(namespace = OCLIF_NS) {
const debug = (0, debug_1.default)(namespace);
return {
child: (ns, delimiter) => makeLogger(`${namespace}${delimiter ?? ':'}${ns}`),
debug,
error: (formatter, ...args) => makeLogger(`${namespace}:error`).debug(formatter, ...args),
info: debug,
namespace,
trace: debug,
warn: debug,
};
}
/**
* Cache of logger instances. This is used to prevent creating multiple logger instances for the same namespace.
*
* The root logger is stored under the 'root' key as well as it's namespace.
*/
const cachedLoggers = new Map();
/**
* Returns a logger instance for the given namespace.
* If a namespace is provided, a child logger is returned.
* If no namespace is provided, the root logger is returned.
*/
function getLogger(namespace) {
let rootLogger = cachedLoggers.get('root');
if (!rootLogger) {
set(makeLogger(OCLIF_NS));
}
rootLogger = cachedLoggers.get('root');
if (namespace) {
const cachedLogger = cachedLoggers.get(namespace);
if (cachedLogger)
return cachedLogger;
const logger = rootLogger.child(namespace);
cachedLoggers.set(namespace, logger);
return logger;
}
return rootLogger;
}
function ensureItMatchesInterface(newLogger) {
return (typeof newLogger.child === 'function' &&
typeof newLogger.debug === 'function' &&
typeof newLogger.error === 'function' &&
typeof newLogger.info === 'function' &&
typeof newLogger.trace === 'function' &&
typeof newLogger.warn === 'function' &&
typeof newLogger.namespace === 'string');
}
function set(newLogger) {
if (cachedLoggers.has(newLogger.namespace))
return;
if (cachedLoggers.has('root'))
return;
if (ensureItMatchesInterface(newLogger)) {
cachedLoggers.set(newLogger.namespace, newLogger);
cachedLoggers.set('root', newLogger);
}
else {
process.emitWarning('Logger does not match the Logger interface. Using default logger.');
}
}
/**
* Convenience function to create a debug function for a specific namespace
*/
function makeDebug(namespace) {
return (formatter, ...args) => getLogger(namespace).debug(formatter, ...args);
}
function setLogger(loadOptions) {
if (loadOptions && typeof loadOptions !== 'string' && 'logger' in loadOptions && loadOptions.logger) {
set(loadOptions.logger);
}
else {
set(makeLogger(OCLIF_NS));
}
}
function clearLoggers() {
cachedLoggers.clear();
}

4
node_modules/@oclif/core/lib/main.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import * as Interfaces from './interfaces';
export declare const helpAddition: (argv: string[], config: Interfaces.Config) => boolean;
export declare const versionAddition: (argv: string[], config?: Interfaces.Config) => boolean;
export declare function run(argv?: string[], options?: Interfaces.LoadOptions): Promise<unknown>;

106
node_modules/@oclif/core/lib/main.js generated vendored Normal file
View File

@@ -0,0 +1,106 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.versionAddition = exports.helpAddition = void 0;
exports.run = run;
const node_url_1 = require("node:url");
const cache_1 = __importDefault(require("./cache"));
const config_1 = require("./config");
const help_1 = require("./help");
const logger_1 = require("./logger");
const performance_1 = require("./performance");
const symbols_1 = require("./symbols");
const ux_1 = require("./ux");
const helpAddition = (argv, config) => {
if (argv.length === 0 && !config.isSingleCommandCLI)
return true;
const mergedHelpFlags = (0, help_1.getHelpFlagAdditions)(config);
for (const arg of argv) {
if (mergedHelpFlags.includes(arg))
return true;
if (arg === '--')
return false;
}
return false;
};
exports.helpAddition = helpAddition;
const versionAddition = (argv, config) => {
const additionalVersionFlags = config?.pjson.oclif.additionalVersionFlags ?? [];
const mergedVersionFlags = [...new Set(['--version', ...additionalVersionFlags]).values()];
if (mergedVersionFlags.includes(argv[0]))
return true;
return false;
};
exports.versionAddition = versionAddition;
async function run(argv, options) {
const marker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, 'main.run');
const initMarker = performance_1.Performance.mark(performance_1.OCLIF_MARKER_OWNER, 'main.run#init');
const showHelp = async (argv) => {
const Help = await (0, help_1.loadHelpClass)(config);
const help = new Help(config, config.pjson.oclif.helpOptions ?? config.pjson.helpOptions);
await help.showHelp(argv);
};
(0, logger_1.setLogger)(options);
const { debug } = (0, logger_1.getLogger)('main');
debug(`process.execPath: ${process.execPath}`);
debug(`process.execArgv: ${process.execArgv}`);
debug('process.argv: %O', process.argv);
argv = argv ?? process.argv.slice(2);
// Handle the case when a file URL string or URL is passed in such as 'import.meta.url'; covert to file path.
if (options && ((typeof options === 'string' && options.startsWith('file://')) || options instanceof node_url_1.URL)) {
options = (0, node_url_1.fileURLToPath)(options);
}
const config = await config_1.Config.load(options ?? require.main?.filename ?? __dirname);
cache_1.default.getInstance().set('config', config);
// If this is a single command CLI, then insert the SINGLE_COMMAND_CLI_SYMBOL into the argv array to serve as the command id.
if (config.isSingleCommandCLI) {
argv = [symbols_1.SINGLE_COMMAND_CLI_SYMBOL, ...argv];
}
const [id, ...argvSlice] = (0, help_1.normalizeArgv)(config, argv);
const runFinally = async (cmd, error) => {
marker?.stop();
if (!initMarker?.stopped)
initMarker?.stop();
await performance_1.Performance.collect();
performance_1.Performance.debug();
await config.runHook('finally', { argv: argvSlice, Command: cmd, error, id });
};
// run init hook
await config.runHook('init', { argv: argvSlice, id });
// display version if applicable
if ((0, exports.versionAddition)(argv, config)) {
ux_1.ux.stdout(config.userAgent);
await runFinally();
return;
}
// display help version if applicable
if ((0, exports.helpAddition)(argv, config)) {
await showHelp(argv);
await runFinally();
return;
}
// find & run command
const cmd = config.findCommand(id);
if (!cmd) {
const topic = config.flexibleTaxonomy ? null : config.findTopic(id);
if (topic) {
await showHelp([id]);
await runFinally();
return;
}
}
initMarker?.stop();
let err;
try {
return await config.runCommand(id, argvSlice, cmd);
}
catch (error) {
err = error;
throw error;
}
finally {
await runFinally(cmd, err);
}
}

71
node_modules/@oclif/core/lib/module-loader.d.ts generated vendored Normal file
View File

@@ -0,0 +1,71 @@
import { Command } from './command';
import { Config as IConfig, Plugin as IPlugin } from './interfaces';
/**
* Loads and returns a module.
*
* Uses `getPackageType` to determine if `type` is set to 'module. If so loads '.js' files as ESM otherwise uses
* a bare require to load as CJS. Also loads '.mjs' files as ESM.
*
* Uses dynamic import to load ESM source or require for CommonJS.
*
* A unique error, ModuleLoadError, combines both CJS and ESM loader module not found errors into a single error that
* provides a consistent stack trace and info.
*
* @param {IConfig|IPlugin} config - Oclif config or plugin config.
* @param {string} modulePath - NPM module name or file path to load.
*
* @returns {Promise<*>} The entire ESM module from dynamic import or CJS module by require.
*/
export declare function load<T = any>(config: IConfig | IPlugin, modulePath: string): Promise<T>;
/**
* Loads a module and returns an object with the module and data about the module.
*
* Uses `getPackageType` to determine if `type` is set to `module`. If so loads '.js' files as ESM otherwise uses
* a bare require to load as CJS. Also loads '.mjs' files as ESM.
*
* Uses dynamic import to load ESM source or require for CommonJS.
*
* A unique error, ModuleLoadError, combines both CJS and ESM loader module not found errors into a single error that
* provides a consistent stack trace and info.
*
* @param {IConfig|IPlugin} config - Oclif config or plugin config.
* @param {string} modulePath - NPM module name or file path to load.
*
* @returns {Promise<{isESM: boolean, module: *, filePath: string}>} An object with the loaded module & data including
* file path and whether the module is ESM.
*/
export declare function loadWithData<T = any>(config: IConfig | IPlugin, modulePath: string): Promise<{
filePath: string;
isESM: boolean;
module: T;
}>;
/**
* Loads a module and returns an object with the module and data about the module.
*
* Uses cached `isESM` and `relativePath` in plugin manifest to determine if dynamic import (isESM = true)
* or require (isESM = false | undefined) should be used.
*
* A unique error, ModuleLoadError, combines both CJS and ESM loader module not found errors into a single error that
* provides a consistent stack trace and info.
*
* @param {Command.Cached} cached - Cached command data from plugin manifest.
* @param {string} modulePath - NPM module name or file path to load.
*
* @returns {Promise<{isESM: boolean, module: *, filePath: string}>} An object with the loaded module & data including
* file path and whether the module is ESM.
*/
export declare function loadWithDataFromManifest<T = any>(cached: Command.Cached, modulePath: string): Promise<{
filePath: string;
isESM: boolean;
module: T;
}>;
/**
* For `.js` files uses `getPackageType` to determine if `type` is set to `module` in associated `package.json`. If
* the `modulePath` provided ends in `.mjs` it is assumed to be ESM.
*
* @param {string} filePath - File path to test.
*
* @returns {boolean} The modulePath is an ES Module.
* @see https://www.npmjs.com/package/get-package-type
*/
export declare function isPathModule(filePath: string): boolean;

206
node_modules/@oclif/core/lib/module-loader.js generated vendored Normal file
View File

@@ -0,0 +1,206 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.load = load;
exports.loadWithData = loadWithData;
exports.loadWithDataFromManifest = loadWithDataFromManifest;
exports.isPathModule = isPathModule;
const getPackageType = require('get-package-type');
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const node_url_1 = require("node:url");
const ts_path_1 = require("./config/ts-path");
const module_load_1 = require("./errors/errors/module-load");
const fs_1 = require("./util/fs");
/**
* Defines file extension resolution when source files do not have an extension.
*/
const SUPPORTED_EXTENSIONS = ['.ts', '.js', '.mjs', '.cjs', '.mts', '.cts', '.tsx', '.jsx'];
const isPlugin = (config) => config.type !== undefined;
function handleError(error, isESM, path) {
if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') {
throw new module_load_1.ModuleLoadError(`${isESM ? 'import()' : 'require'} failed to load ${path}: ${error.message}`);
}
throw error;
}
/**
* Loads and returns a module.
*
* Uses `getPackageType` to determine if `type` is set to 'module. If so loads '.js' files as ESM otherwise uses
* a bare require to load as CJS. Also loads '.mjs' files as ESM.
*
* Uses dynamic import to load ESM source or require for CommonJS.
*
* A unique error, ModuleLoadError, combines both CJS and ESM loader module not found errors into a single error that
* provides a consistent stack trace and info.
*
* @param {IConfig|IPlugin} config - Oclif config or plugin config.
* @param {string} modulePath - NPM module name or file path to load.
*
* @returns {Promise<*>} The entire ESM module from dynamic import or CJS module by require.
*/
async function load(config, modulePath) {
let filePath;
let isESM;
try {
;
({ filePath, isESM } = await resolvePath(config, modulePath));
return (isESM ? await import((0, node_url_1.pathToFileURL)(filePath).href) : require(filePath));
}
catch (error) {
handleError(error, isESM, filePath ?? modulePath);
}
}
/**
* Loads a module and returns an object with the module and data about the module.
*
* Uses `getPackageType` to determine if `type` is set to `module`. If so loads '.js' files as ESM otherwise uses
* a bare require to load as CJS. Also loads '.mjs' files as ESM.
*
* Uses dynamic import to load ESM source or require for CommonJS.
*
* A unique error, ModuleLoadError, combines both CJS and ESM loader module not found errors into a single error that
* provides a consistent stack trace and info.
*
* @param {IConfig|IPlugin} config - Oclif config or plugin config.
* @param {string} modulePath - NPM module name or file path to load.
*
* @returns {Promise<{isESM: boolean, module: *, filePath: string}>} An object with the loaded module & data including
* file path and whether the module is ESM.
*/
async function loadWithData(config, modulePath) {
let filePath;
let isESM;
try {
;
({ filePath, isESM } = await resolvePath(config, modulePath));
const module = isESM ? await import((0, node_url_1.pathToFileURL)(filePath).href) : require(filePath);
return { filePath, isESM, module };
}
catch (error) {
handleError(error, isESM, filePath ?? modulePath);
}
}
/**
* Loads a module and returns an object with the module and data about the module.
*
* Uses cached `isESM` and `relativePath` in plugin manifest to determine if dynamic import (isESM = true)
* or require (isESM = false | undefined) should be used.
*
* A unique error, ModuleLoadError, combines both CJS and ESM loader module not found errors into a single error that
* provides a consistent stack trace and info.
*
* @param {Command.Cached} cached - Cached command data from plugin manifest.
* @param {string} modulePath - NPM module name or file path to load.
*
* @returns {Promise<{isESM: boolean, module: *, filePath: string}>} An object with the loaded module & data including
* file path and whether the module is ESM.
*/
async function loadWithDataFromManifest(cached, modulePath) {
const { id, isESM, relativePath } = cached;
if (!relativePath) {
throw new module_load_1.ModuleLoadError(`Cached command ${id} does not have a relative path`);
}
if (isESM === undefined) {
throw new module_load_1.ModuleLoadError(`Cached command ${id} does not have the isESM property set`);
}
const filePath = (0, node_path_1.join)(modulePath, relativePath.join(node_path_1.sep));
try {
const module = isESM ? await import((0, node_url_1.pathToFileURL)(filePath).href) : require(filePath);
return { filePath, isESM, module };
}
catch (error) {
handleError(error, isESM, filePath ?? modulePath);
}
}
/**
* For `.js` files uses `getPackageType` to determine if `type` is set to `module` in associated `package.json`. If
* the `modulePath` provided ends in `.mjs` it is assumed to be ESM.
*
* @param {string} filePath - File path to test.
*
* @returns {boolean} The modulePath is an ES Module.
* @see https://www.npmjs.com/package/get-package-type
*/
function isPathModule(filePath) {
const extension = (0, node_path_1.extname)(filePath).toLowerCase();
switch (extension) {
case '.js':
case '.jsx':
case '.ts':
case '.tsx': {
return getPackageType.sync(filePath) === 'module';
}
case '.mjs':
case '.mts': {
return true;
}
default: {
return false;
}
}
}
/**
* Resolves a modulePath first by `require.resolve` to allow Node to resolve an actual module. If this fails then
* the `modulePath` is resolved from the root of the provided config. `Config.tsPath` is used for initial resolution.
* If this file path does not exist then several extensions are tried from `s_EXTENSIONS` in order: '.js', '.mjs',
* '.cjs'. After a file path has been selected `isPathModule` is used to determine if the file is an ES Module.
*
* @param {IConfig|IPlugin} config - Oclif config or plugin config.
* @param {string} modulePath - File path to load.
*
* @returns {{isESM: boolean, filePath: string}} An object including file path and whether the module is ESM.
*/
async function resolvePath(config, modulePath) {
let isESM;
let filePath;
try {
filePath = require.resolve(modulePath);
isESM = isPathModule(filePath);
}
catch {
filePath =
(isPlugin(config) ? await (0, ts_path_1.tsPath)(config.root, modulePath, config) : await (0, ts_path_1.tsPath)(config.root, modulePath)) ??
modulePath;
let fileExists = false;
let isDirectory = false;
if ((0, fs_1.existsSync)(filePath)) {
fileExists = true;
try {
if ((0, node_fs_1.lstatSync)(filePath)?.isDirectory?.()) {
fileExists = false;
isDirectory = true;
}
}
catch { }
}
if (!fileExists) {
// Try all supported extensions.
let foundPath = findFile(filePath);
if (!foundPath && isDirectory) {
// Since filePath is a directory, try looking for index file.
foundPath = findFile((0, node_path_1.join)(filePath, 'index'));
}
if (foundPath) {
filePath = foundPath;
}
}
isESM = isPathModule(filePath);
}
return { filePath, isESM };
}
/**
* Try adding the different extensions from `s_EXTENSIONS` to find the file.
*
* @param {string} filePath - File path to load.
*
* @returns {string | null} Modified file path including extension or null if file is not found.
*/
function findFile(filePath) {
for (const extension of SUPPORTED_EXTENSIONS) {
const testPath = `${filePath}${extension}`;
if ((0, fs_1.existsSync)(testPath)) {
return testPath;
}
}
return null;
}

52
node_modules/@oclif/core/lib/parser/errors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,52 @@
import { CLIError } from '../errors';
import { Arg, ArgInput, CLIParseErrorOptions, OptionFlag } from '../interfaces/parser';
export { CLIError } from '../errors';
export type Validation = {
name: string;
reason?: string | undefined;
status: 'failed' | 'success';
validationFn: string;
};
export declare class CLIParseError extends CLIError {
parse: CLIParseErrorOptions['parse'];
showHelp: boolean;
constructor(options: CLIParseErrorOptions & {
message: string;
});
}
export declare class InvalidArgsSpecError extends CLIParseError {
args: ArgInput;
constructor({ args, exit, parse }: CLIParseErrorOptions & {
args: ArgInput;
});
}
export declare class RequiredArgsError extends CLIParseError {
args: Arg<any>[];
constructor({ args, exit, flagsWithMultiple, parse, }: CLIParseErrorOptions & {
args: Arg<any>[];
flagsWithMultiple?: string[];
});
}
export declare class UnexpectedArgsError extends CLIParseError {
args: unknown[];
constructor({ args, exit, parse }: CLIParseErrorOptions & {
args: unknown[];
});
}
export declare class NonExistentFlagsError extends CLIParseError {
flags: string[];
constructor({ exit, flags, parse }: CLIParseErrorOptions & {
flags: string[];
});
}
export declare class FlagInvalidOptionError extends CLIParseError {
constructor(flag: OptionFlag<any>, input: string);
}
export declare class ArgInvalidOptionError extends CLIParseError {
constructor(arg: Arg<any>, input: string);
}
export declare class FailedFlagValidationError extends CLIParseError {
constructor({ exit, failed, parse }: CLIParseErrorOptions & {
failed: Validation[];
});
}

104
node_modules/@oclif/core/lib/parser/errors.js generated vendored Normal file
View File

@@ -0,0 +1,104 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FailedFlagValidationError = exports.ArgInvalidOptionError = exports.FlagInvalidOptionError = exports.NonExistentFlagsError = exports.UnexpectedArgsError = exports.RequiredArgsError = exports.InvalidArgsSpecError = exports.CLIParseError = exports.CLIError = void 0;
const cache_1 = __importDefault(require("../cache"));
const errors_1 = require("../errors");
const util_1 = require("../util/util");
const list_1 = __importDefault(require("../ux/list"));
const theme_1 = require("../ux/theme");
var errors_2 = require("../errors");
Object.defineProperty(exports, "CLIError", { enumerable: true, get: function () { return errors_2.CLIError; } });
class CLIParseError extends errors_1.CLIError {
parse;
showHelp = false;
constructor(options) {
options.message += '\nSee more help with --help';
super(options.message, { exit: options.exit });
this.parse = options.parse;
}
}
exports.CLIParseError = CLIParseError;
class InvalidArgsSpecError extends CLIParseError {
args;
constructor({ args, exit, parse }) {
let message = 'Invalid argument spec';
const namedArgs = Object.values(args).filter((a) => a.name);
if (namedArgs.length > 0) {
const list = (0, list_1.default)(namedArgs.map((a) => [`${a.name} (${a.required ? 'required' : 'optional'})`, a.description]));
message += `:\n${list}`;
}
super({ exit: cache_1.default.getInstance().get('exitCodes')?.invalidArgsSpec ?? exit, message, parse });
this.args = args;
}
}
exports.InvalidArgsSpecError = InvalidArgsSpecError;
class RequiredArgsError extends CLIParseError {
args;
constructor({ args, exit, flagsWithMultiple, parse, }) {
let message = `Missing ${args.length} required arg${args.length === 1 ? '' : 's'}`;
const namedArgs = args.filter((a) => a.name);
if (namedArgs.length > 0) {
const list = (0, list_1.default)(namedArgs.map((a) => {
const description = a.options ? `(${a.options.join('|')}) ${a.description}` : a.description;
return [a.name, description];
}));
message += `:\n${list}`;
}
if (flagsWithMultiple?.length) {
const flags = flagsWithMultiple.map((f) => `--${f}`).join(', ');
message += `\n\nNote: ${flags} allow${flagsWithMultiple.length === 1 ? 's' : ''} multiple values. Because of this you need to provide all arguments before providing ${flagsWithMultiple.length === 1 ? 'that flag' : 'those flags'}.`;
message += '\nAlternatively, you can use "--" to signify the end of the flags and the beginning of arguments.';
}
super({ exit: cache_1.default.getInstance().get('exitCodes')?.requiredArgs ?? exit, message, parse });
this.args = args;
this.showHelp = true;
}
}
exports.RequiredArgsError = RequiredArgsError;
class UnexpectedArgsError extends CLIParseError {
args;
constructor({ args, exit, parse }) {
const message = `Unexpected argument${args.length === 1 ? '' : 's'}: ${args.join(', ')}`;
super({ exit: cache_1.default.getInstance().get('exitCodes')?.unexpectedArgs ?? exit, message, parse });
this.args = args;
this.showHelp = true;
}
}
exports.UnexpectedArgsError = UnexpectedArgsError;
class NonExistentFlagsError extends CLIParseError {
flags;
constructor({ exit, flags, parse }) {
const message = `Nonexistent flag${flags.length === 1 ? '' : 's'}: ${flags.join(', ')}`;
super({ exit: cache_1.default.getInstance().get('exitCodes')?.nonExistentFlag ?? exit, message, parse });
this.flags = flags;
this.showHelp = true;
}
}
exports.NonExistentFlagsError = NonExistentFlagsError;
class FlagInvalidOptionError extends CLIParseError {
constructor(flag, input) {
const message = `Expected --${flag.name}=${input} to be one of: ${flag.options.join(', ')}`;
super({ message, parse: {} });
}
}
exports.FlagInvalidOptionError = FlagInvalidOptionError;
class ArgInvalidOptionError extends CLIParseError {
constructor(arg, input) {
const message = `Expected ${input} to be one of: ${arg.options.join(', ')}`;
super({ message, parse: {} });
}
}
exports.ArgInvalidOptionError = ArgInvalidOptionError;
class FailedFlagValidationError extends CLIParseError {
constructor({ exit, failed, parse }) {
const reasons = failed.map((r) => r.reason);
const deduped = (0, util_1.uniq)(reasons);
const errString = deduped.length === 1 ? 'error' : 'errors';
const message = `The following ${errString} occurred:\n ${(0, theme_1.colorize)('dim', deduped.join('\n '))}`;
super({ exit: cache_1.default.getInstance().get('exitCodes')?.failedFlagValidation ?? exit, message, parse });
}
}
exports.FailedFlagValidationError = FailedFlagValidationError;

3
node_modules/@oclif/core/lib/parser/help.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import { Flag, FlagUsageOptions } from '../interfaces/parser';
export declare function flagUsage(flag: Flag<any>, options?: FlagUsageOptions): [string, string | undefined];
export declare function flagUsages(flags: Flag<any>[], options?: FlagUsageOptions): [string, string | undefined][];

29
node_modules/@oclif/core/lib/parser/help.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flagUsage = flagUsage;
exports.flagUsages = flagUsages;
const util_1 = require("../util/util");
const ux_1 = require("../ux");
function flagUsage(flag, options = {}) {
const label = [];
if (flag.helpLabel) {
label.push(flag.helpLabel);
}
else {
if (flag.char)
label.push(`-${flag.char}`);
if (flag.name)
label.push(` --${flag.name}`);
}
const usage = flag.type === 'option' ? ` ${flag.name.toUpperCase()}` : '';
let description = flag.summary || flag.description || '';
if (options.displayRequired && flag.required)
description = `(required) ${description}`;
description = description ? (0, ux_1.colorize)('dim', description) : undefined;
return [` ${label.join(',').trim()}${usage}`, description];
}
function flagUsages(flags, options = {}) {
if (flags.length === 0)
return [];
return (0, util_1.sortBy)(flags, (f) => [f.char ? -1 : 1, f.char, f.name]).map((f) => flagUsage(f, options));
}

Some files were not shown because too many files have changed in this diff Show More