export function setupStaticGeneration (nuxt: any, options: ModuleOptions) {
  const staticImages: Record<string, string> = {} // url ~> hashed file name

  nuxt.hook('vue-renderer:ssr:prepareContext', (renderContext: any) => {
    renderContext.image = renderContext.image || {}
    renderContext.image.mapToStatic = <MapToStatic> function ({ url, format }: ResolvedImage, input: string) {
      if (!staticImages[url]) {
        const { pathname } = parseURL(input)
        const params: any = {
          name: trimExt(basename(pathname)),
          ext: (format && `.${format}`) || guessExt(input),
          hash: hash(url),
          // TODO: pass from runtimeConfig to mapStatic as param
          publicPath: nuxt.options.app.cdnURL ? '/' : withoutTrailingSlash(nuxt.options.build.publicPath)
        }

        staticImages[url] = options.staticFilename.replace(/\[(\w+)]/g, (match, key) => params[key] || match)
      }
      return joinURL(nuxt.options.app.cdnURL || nuxt.options.app.basePath, staticImages[url])
    }
  })

  nuxt.hook('generate:done', async () => {
    const limit = pLimit(8)
    const downloads = Object.entries(staticImages).map(([url, name]) => {
      if (!hasProtocol(url)) {
        url = joinURL(options.internalUrl, url)
      }
      return limit(() => downloadImage({
        url,
        name,
        outDir: nuxt.options.generate.dir
      }))
    })
    await Promise.all(downloads)
  })
}


async function downloadImage ({ url, name, outDir }: { url: string, name: string, outDir: string }) {
  try {
    const response = await fetch(url)
    if (!response.ok) { throw new Error(`Unexpected response ${response.statusText}`) }
    const dstFile = join(outDir, name)
    await mkdirp(dirname(dstFile))
    await pipeline(response.body, createWriteStream(dstFile))
    logger.success('Generated static image ' + relative(process.cwd(), dstFile))
  } catch (error: any) {
    logger.error(error?.message)
  }
}


(renderContext: any) => {
    renderContext.image = renderContext.image || {}
    renderContext.image.mapToStatic = <MapToStatic> function ({ url, format }: ResolvedImage, input: string) {
      if (!staticImages[url]) {
        const { pathname } = parseURL(input)
        const params: any = {
          name: trimExt(basename(pathname)),
          ext: (format && `.${format}`) || guessExt(input),
          hash: hash(url),
          // TODO: pass from runtimeConfig to mapStatic as param
          publicPath: nuxt.options.app.cdnURL ? '/' : withoutTrailingSlash(nuxt.options.build.publicPath)
        }

        staticImages[url] = options.staticFilename.replace(/\[(\w+)]/g, (match, key) => params[key] || match)
      }
      return joinURL(nuxt.options.app.cdnURL || nuxt.options.app.basePath, staticImages[url])
    }
  }


(match, key) => params[key] || match


async () => {
    const limit = pLimit(8)
    const downloads = Object.entries(staticImages).map(([url, name]) => {
      if (!hasProtocol(url)) {
        url = joinURL(options.internalUrl, url)
      }
      return limit(() => downloadImage({
        url,
        name,
        outDir: nuxt.options.generate.dir
      }))
    })
    await Promise.all(downloads)
  }


([url, name]) => {
      if (!hasProtocol(url)) {
        url = joinURL(options.internalUrl, url)
      }
      return limit(() => downloadImage({
        url,
        name,
        outDir: nuxt.options.generate.dir
      }))
    }


() => downloadImage({
        url,
        name,
        outDir: nuxt.options.generate.dir
      })


class CustomDate extends React.PureComponent<Props> {
  render() {
    const { intl, date, format = DATE_FORMAT } = this.props;

    const dateObject = new Date(date);
    if (!dateObject) {
      return null;
    }

    if (!dateObject.getTime || isNaN(dateObject.getTime())) {
      console.warn("CustomDate was passed an invalid date: ", this.props.date);
      return null;
    }

    return <>{formatDate(dateObject, intl.locale, format)}</>;
  }
}


interface Props {
  date: Date;
  format?: DateFormat;
  intl: InjectedIntl;
}


render() {
    const { intl, date, format = DATE_FORMAT } = this.props;

    const dateObject = new Date(date);
    if (!dateObject) {
      return null;
    }

    if (!dateObject.getTime || isNaN(dateObject.getTime())) {
      console.warn("CustomDate was passed an invalid date: ", this.props.date);
      return null;
    }

    return <>{formatDate(dateObject, intl.locale, format)}</>;
  }


formatDate(dateObject, intl


@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [PagerComponent],
  exports: [PagerComponent]

})
export class ApppagerModule { }


export function TakeActionMixin<Base extends Constructor>(Resource: Base) {
  @namespace(schema)
  class TakeActionClass extends TransferActionMixin(Resource) implements TakeAction {
  }
  return TakeActionClass
}


@namespace(schema)
  class TakeActionClass extends TransferActionMixin(Resource) implements TakeAction {
  }


class TakeActionImpl extends TakeActionMixin(RdfResourceImpl) {
  constructor(arg: ResourceNode, init?: Initializer<TakeAction>) {
    super(arg, init)
    this.types.add(schema.TakeAction)
  }

  static readonly __mixins: Mixin[] = [TakeActionMixin, TransferActionMixin];
}


export interface TakeAction extends Schema.TransferAction, RdfResource {
}


item => {
            this.docs = this.toAsyncApiMap(item);
            return this.docs;
        }


([docName, doc]) => docs.set(docName, this.toAsyncApi(doc))


([k, v]) => s.set(k, v)


([k, v]) => s.set(k, {
            description: v.description,
            operation: this.mapOperation(v.subscribe, v.publish)
        })


([k, v]) => s.set(k, {
            type: v.type,
            properties: v.properties,
            example: new Example(v.example)
        })


@Injectable()
export class AsyncApiService {

    private nameSubject: Subject<string>;
    private docs: Map<string, AsyncApi>;

    constructor(private http: HttpClient) {
        this.nameSubject = new Subject<string>();
    }

    public setCurrentAsyncApiName(currnetAsyncApiName: string) {
        this.nameSubject.next(currnetAsyncApiName);
    }

    public getCurrentAsyncApiName(): Observable<string> {
        return this.nameSubject.asObservable();
    }

    public getAsyncApis(): Observable<Map<string, AsyncApi>> {
        if (this.docs) {
            return of(this.docs);
        }

        return this.http.get<Map<string, ServerAsyncApi>>(Endpoints.docs).pipe(map(item => {
            this.docs = this.toAsyncApiMap(item);
            return this.docs;
        }));
    }

    toAsyncApiMap(response: Map<string, ServerAsyncApi>): Map<string, AsyncApi> {
        const docs = new Map<string, AsyncApi>();
        Object.entries(response).forEach(([docName, doc]) => docs.set(docName, this.toAsyncApi(doc)));
        return docs;
    }

    toAsyncApi(item: ServerAsyncApi): AsyncApi {
        return {
            info: item.info,
            servers: this.mapServers(item.servers),
            channels: this.mapChannels(item.channels),
            components: {
                schemas: this.mapSchemas(item.components.schemas)
            }
        };
    }

    private mapServers(servers: { [key: string]: Server }): Map<string, Server> {
        const s = new Map<string, Server>();
        Object.entries(servers).forEach(([k, v]) => s.set(k, v));
        return s;
    }

    private mapChannels(channels: {
        [key: string]: {
            description?: string;
            subscribe?: {
                message: Message;
                bindings?: any;
            };
            publish?: {
                message: Message;
                bindings?: any;
            };
        }
    }): Map<string, Channel> {
        const s = new Map<string, Channel>();
        Object.entries(channels).forEach(([k, v]) => s.set(k, {
            description: v.description,
            operation: this.mapOperation(v.subscribe, v.publish)
        }));
        return s;
    }

    private mapOperation(subscribe: { message: Message; bindings?: any; }, publish: { message: Message; bindings?: any; }): Operation {
        const isSubscribe = !!subscribe;

        if (isSubscribe) {
            return {
                type: this.getProtocol(subscribe) + " producer",
                message: subscribe.message,
                bindings: subscribe.bindings
            }
        } else {
            return {
                type: this.getProtocol(publish) + " consumer",
                message: publish.message,
                bindings: publish.bindings
            }
        }
    }

    private getProtocol(operation: { message: Message; bindings?: any; }): string {
        return Object.keys(operation.bindings)[0];
    }

    mapSchemas(schemas: { [key: string]: { type: string; properties: object; example: object; } }): Map<string, Schema> {
        const s = new Map<string, Schema>();
        Object.entries(schemas).forEach(([k, v]) => s.set(k, {
            type: v.type,
            properties: v.properties,
            example: new Example(v.example)
        }));
        return s;
    }

}


interface ServerAsyncApi {
    asyncapi: string;
    info: Info;
    servers: {
        [key: string]: {
            url: string;
            protocol: string;
        };
    };
    channels: {
        [key: string]: {
            description?: string;
            subscribe?: {
                message: Message;
                bindings?: any;
            };
            publish?: {
                message: Message;
                bindings?: any;
            };
        };
    };
    components: {
        schemas: {
            [key: string]: {
                type: string;
                properties: object;
                example: object;
            };
        };
    };
}


public setCurrentAsyncApiName(currnetAsyncApiName: string) {
        this.nameSubject.next(currnetAsyncApiName);
    }


public getCurrentAsyncApiName(): Observable<string> {
        return this.nameSubject.asObservable();
    }


public getAsyncApis(): Observable<Map<string, AsyncApi>> {
        if (this.docs) {
            return of(this.docs);
        }

        return this.http.get<Map<string, ServerAsyncApi>>(Endpoints.docs).pipe(map(item => {
            this.docs = this.toAsyncApiMap(item);
            return this.docs;
        }));
    }


toAsyncApiMap(response: Map<string, ServerAsyncApi>): Map<string, AsyncApi> {
        const docs = new Map<string, AsyncApi>();
        Object.entries(response).forEach(([docName, doc]) => docs.set(docName, this.toAsyncApi(doc)));
        return docs;
    }


toAsyncApi(item: ServerAsyncApi): AsyncApi {
        return {
            info: item.info,
            servers: this.mapServers(item.servers),
            channels: this.mapChannels(item.channels),
            components: {
                schemas: this.mapSchemas(item.components.schemas)
            }
        };
    }


private mapServers(servers: { [key: string]: Server }): Map<string, Server> {
        const s = new Map<string, Server>();
        Object.entries(servers).forEach(([k, v]) => s.set(k, v));
        return s;
    }


private mapChannels(channels: {
        [key: string]: {
            description?: string;
            subscribe?: {
                message: Message;
                bindings?: any;
            };
            publish?: {
                message: Message;
                bindings?: any;
            };
        }
    }): Map<string, Channel> {
        const s = new Map<string, Channel>();
        Object.entries(channels).forEach(([k, v]) => s.set(k, {
            description: v.description,
            operation: this.mapOperation(v.subscribe, v.publish)
        }));
        return s;
    }


private mapOperation(subscribe: { message: Message; bindings?: any; }, publish: { message: Message; bindings?: any; }): Operation {
        const isSubscribe = !!subscribe;

        if (isSubscribe) {
            return {
                type: this.getProtocol(subscribe) + " producer",
                message: subscribe.message,
                bindings: subscribe.bindings
            }
        } else {
            return {
                type: this.getProtocol(publish) + " consumer",
                message: publish.message,
                bindings: publish.bindings
            }
        }
    }


private getProtocol(operation: { message: Message; bindings?: any; }): string {
        return Object.keys(operation.bindings)[0];
    }


mapSchemas(schemas: { [key: string]: { type: string; properties: object; example: object; } }): Map<string, Schema> {
        const s = new Map<string, Schema>();
        Object.entries(schemas).forEach(([k, v]) => s.set(k, {
            type: v.type,
            properties: v.properties,
            example: new Example(v.example)
        }));
        return s;
    }


export declare class DateTimeWidgetComponent extends WidgetComponent implements OnInit {
    formService: FormService;
    private dateAdapter;
    private userPreferencesService;
    minDate: Moment;
    maxDate: Moment;
    displayDate: Moment;
    constructor(formService: FormService, dateAdapter: DateAdapter<Moment>, userPreferencesService: UserPreferencesService);
    ngOnInit(): void;
    onDateChanged(newDateValue: any): void;
}


onDateChanged(newDateValue: any): void;


export class UserInfo {

	@numeric({isFormat:true,allowDecimal:true })
    @toFloat()
	totalAmount: number;

}


(): Partial<AudioModel> => ({
  src: '',
  customCssClass: '',
  triggerCheck: false,
  autoPlay: false,
  startTime: 0,
  endTime: 0,
  enableReplay: true,
  subtitles: [],
})


export interface AudioModel extends JanusAbsolutePositioned, JanusCustomCss {
  src: string;
  customCssClass: string;
  triggerCheck: boolean;
  autoPlay: boolean;
  startTime: number;
  endTime: number;
  enableReplay: boolean;
  subtitles: any;
}


(props: TabItemProps) => {
    return (<>{props.children}</>)
}


(props: TabFolderProps) => {
    const [active, setActive] = useState(props.value || props.children[0]?.props.value)
    const buttons = props.children.map((child) => {
        const onClick = (e) => {
            setActive(child.props.value)
        }
        return (
            <div key={child.props.value} className={classNames('tab-button', active === child.props.value ? 'active' : '')}


(child) => {
        const onClick = (e) => {
            setActive(child.props.value)
        }
        return (
            <div key={child.props.value} className={classNames('tab-button', active === child.props.value ? 'active' : ''


(e) => {
            setActive(child.props.value)
        }


(child) => {
        return (
            <div key={child.props.value} className={classNames(props.className, 'tab-item', active === child.props.value ? 'active' : ''


interface TabItemProps {
    className?: string
    value: string
    label?: string
    help?: string
    children: ReactElement[]
}


interface TabFolderProps {
    className?: string
    value?: string
    help?: string
    children: ReactElement<TabItemProps>[]
}


classNames('tab-button', active


classNames(props


(http: Http) => new TranslateStaticLoader(http, 'assets/data/translations', '.json')


/**
 * Snapshot options overriding the video stream configuration. Not specifying any options will
 * get you the characteristics of the video stream.
 */
export interface SnapshotOptions {
    /**
     * Resolution of the returned image. For supported resolutions, check in parameter
     * Properties.Image.Resolution.
     *
     * Remarks: You can always use the npm package axis-configuration to read parameters.
     */
    resolution?: string;
    /**
     * Selects the video source (1...n, "quad"). If omitted the default value camera 1 is used.
     * This argument is only valid for Axis products with more than one video source. That is
     * cameras with multiple view areas and video encoders with multiple video channels.
     */
    camera?: number | 'quad';
    /**
     * Adjusts the compression level (0...100) of the image. Higher values correspond to higher
     * compression, that is lower quality and smaller image size. Note: This value is internally
     * mapped and is therefore product-dependent.
     */
    compression?:
        | 0
        | 1
        | 2
        | 3
        | 4
        | 5
        | 6
        | 7
        | 8
        | 9
        | 10
        | 11
        | 12
        | 13
        | 14
        | 15
        | 16
        | 17
        | 18
        | 19
        | 20
        | 21
        | 22
        | 23
        | 24
        | 25
        | 26
        | 27
        | 28
        | 29
        | 30
        | 31
        | 32
        | 33
        | 34
        | 35
        | 36
        | 37
        | 38
        | 39
        | 40
        | 41
        | 42
        | 43
        | 44
        | 45
        | 46
        | 47
        | 48
        | 49
        | 50
        | 51
        | 52
        | 53
        | 54
        | 55
        | 56
        | 57
        | 58
        | 59
        | 60
        | 61
        | 62
        | 63
        | 64
        | 65
        | 66
        | 67
        | 68
        | 69
        | 70
        | 71
        | 72
        | 73
        | 74
        | 75
        | 76
        | 77
        | 78
        | 79
        | 80
        | 81
        | 82
        | 83
        | 84
        | 85
        | 86
        | 87
        | 88
        | 89
        | 90
        | 91
        | 92
        | 93
        | 94
        | 95
        | 96
        | 97
        | 98
        | 99
        | 100;
    /**
     * Rotate the image clockwise (0, 90, 180, 270). The number of rotation alternatives in an Axis
     * product is defined by the parameter Properties.Image.Rotation.
     *
     * Remarks: You can always use the npm package axis-configuration to read parameters.
     */
    rotation?: 0 | 90 | 180 | 270;
    /**
     * The color palette to use in thermal cameras. Applicable if
     * Properties.Image.Palette.StreamPalette=yes or does not exist. See the
     * {link https://www.axis.com/vapix-library/subjects/t10037719/section/t10051895/display?section=t10051895-t10051895-t10051056|VAPIX documentation}
     * for more information.
     */
    palette?: string;
    /**
     * Enable/disable (1, 0) square pixel (aspect ratio) correction. If the parameter is set to 1
     * the Axis product will adjusts the aspect ratio to make it appear as intended.
     */
    squarepixel?: 0 | 1;
}


repo =>{
      this.userService.updateData(this.username)
      console.log(repo)
      this.repos = repo
  }


repo =>{
    console.log(repo)
    this.repos = repo
  }


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  user:Users;
  repos:any;
  username:string

  constructor( private userService:UserRequestService) {

    this.userService.getRepos().subscribe(repo =>{
      this.userService.updateData(this.username)
      console.log(repo)
      this.repos = repo
  });
}
search(){

  this.userService.updateData(this.username)
  this.userService.getUser()
  this.user = this.userService.user
  this.userService.getRepos().subscribe(repo =>{
    console.log(repo)
    this.repos = repo
  });
}
  ngOnInit(){

    this.userService.getUser()
    this.user = this.userService.user

  }
}


search(){

  this.userService.updateData(this.username)
  this.userService.getUser()
  this.user = this.userService.user
  this.userService.getRepos().subscribe(repo =>{
    console.log(repo)
    this.repos = repo
  });
}


ngOnInit(){

    this.userService.getUser()
    this.user = this.userService.user

  }


(colors: Colors): TokenGroup[] => [
  {
    name: "Chalky",
    scope: [
      "entity.name.type",
      "entity.other.inherited-class",
      "keyword.other.type",
      "punctuation.definition.annotation",
      "storage.modifier.import",
      "storage.modifier.package",
      "storage.type.annotation",
      "storage.type.built-in",
      "storage.type.generic",
      // storage.type.java and storage.type.groovy are necessary because
      // storage.type uses violet for JS/TS const, let, and var
      "storage.type.java",
      "storage.type.groovy",
      "storage.type.primitive",
      "support.class",
      "support.other.namespace",
      "support.type",
      "variable.language.this",
    ],
    settings: {
      foreground: colors.chalky,
    },
  },
  {
    name: "Coral",
    scope: [
      "constant.other.character-class",
      "entity.name.tag",
      "heading",
      "meta.object-literal.key",
      "punctuation.definition.list.begin.markdown",
      "punctuation.definition.list.end.markdown",
      "punctuation.definition.template-expression",
      "punctuation.section.embedded",
      "support.type.property-name",
      "variable.object.property",
      "variable.other.enummember",
    ],
    settings: {
      foreground: colors.coral,
    },
  },
  {
    name: "Cyan",
    scope: [
      "constant.character.escape",
      "keyword.operator",
      "markup.underline.link",
      "string.regexp",
      "string.url",
    ],
    settings: {
      foreground: colors.cyan,
    },
  },
  {
    name: "Malibu",
    scope: [
      "entity.name.function",
      "entity.other.attribute-name.id.css",
      "string.other.link",
      "support.function",
      "variable.language.super",
    ],
    settings: {
      foreground: colors.malibu,
    },
  },
  {
    name: "Ivory",
    scope: [
      "meta.brace",
      "punctuation.accessor",
      "punctuation.definition.block",
      "punctuation.separator",
      "support.type.property-name.css",
    ],
    settings: {
      foreground: colors.ivory,
    },
  },
  {
    name: "Sage",
    scope: [
      "markup.inline",
      "markup.quote",
      "source.ini",
      "string.other.link.description",
      "string",
    ],
    settings: {
      foreground: colors.sage,
    },
  },
  {
    name: "Stone",
    scope: ["comment"],
    settings: {
      foreground: colors.stone,
    },
  },
  {
    name: "Violet",
    scope: [
      "keyword.operator.new",
      "keyword",
      "markup.italic",
      "punctuation.definition.block.tag",
      "storage.modifier",
      "storage.type",
    ],
    settings: {
      foreground: colors.violet,
    },
  },
  {
    name: "Whiskey",
    scope: [
      "constant",
      "entity.other.attribute-name",
      "keyword.operator.quantifier.regexp",
      "markup.bold",
      "support.constant",
      "variable.other.constant",
      "variable.parameter",
    ],
    settings: {
      foreground: colors.whiskey,
    },
  },
]


async (connectionLogger, connection, clientConfiguration, rawSql, values, inheritedQueryId) => {
  return executeQuery(
    connectionLogger,
    connection,
    clientConfiguration,
    rawSql,
    values,
    inheritedQueryId,
    async (finalConnection, finalSql, finalValues) => {
      const result: QueryResult & {notices?: NoticeType[], } = await finalConnection.query(finalSql, finalValues);

      return {
        command: result.command as QueryResultType<unknown>['command'],
        fields: (result.fields || []).map((field) => {
          return {
            dataTypeId: field.dataTypeID,
            name: field.name,
          };
        }),
        notices: result.notices ?? [],
        rowCount: result.rowCount || 0,
        rows: result.rows || [],
      };
    },
  );
}


async (finalConnection, finalSql, finalValues) => {
      const result: QueryResult & {notices?: NoticeType[], } = await finalConnection.query(finalSql, finalValues);

      return {
        command: result.command as QueryResultType<unknown>['command'],
        fields: (result.fields || []).map((field) => {
          return {
            dataTypeId: field.dataTypeID,
            name: field.name,
          };
        }),
        notices: result.notices ?? [],
        rowCount: result.rowCount || 0,
        rows: result.rows || [],
      };
    }


(field) => {
          return {
            dataTypeId: field.dataTypeID,
            name: field.name,
          };
        }


/**
 * {358}
 */
export interface IArcsineInDegrees {

    /**
     * {551}
     */
    value: ValueNumberType
}


async function mockStdout(test: (outLines: string[]) => Promise<void>) {
  const oldStdoutWriter = process.stdout.write.bind(process.stdout);
  const lines: string[] = [];
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  process.stdout.write = (message) => {
    if (message && typeof message === 'string') {
      lines.push(message);
    }
  };

  try {
    await test(lines);
  } finally {
    process.stdout.write = oldStdoutWriter;
  }
}


// eslint-disable-next-line @typescript-eslint/no-explicit-any
function verifyCmdFlags(verifications: Dictionary<any>) {
    const merged = Object.assign({}, DEFAULT_CMD_PROPS.flags, verifications);
    const numOfFlagsMessage = 'Number of flag definitions for the command should match';
    expect(keysOf(testCommandMeta.cmd.flags).length, numOfFlagsMessage).to.equal(keysOf(merged).length);
    keysOf(merged).forEach((key) => {
      expect(testCommandMeta.cmd.flags, `test for flag: ${key}`).to.have.property(key).and.include(merged[key]);
    });
  }


function verifyInstanceProps(props: Dictionary = {}) {
    const merged = Object.assign({}, DEFAULT_INSTANCE_PROPS, props);
    keysOf(testCommandMeta.cmdInstance)
      .filter((key) => !!merged[key])
      .forEach((key) => {
        expect(testCommandMeta.cmdInstance[key], `test for instance prop: ${key}`).to.deep.equal(merged[key]);
      });

    expect(testCommandMeta.cmdInstance['ux']).to.be.ok.and.be.instanceof(UX);
  }


function verifyUXOutput(output = {}) {
    const out = Object.assign({}, UX_OUTPUT_BASE, output);
    keysOf(out).forEach((key) => {
      expect(UX_OUTPUT[key], `test UX output for ${key}()`).to.deep.equal(out[key]);
    });
  }


async function validateFlag(flagType: keyof typeof flags, val: string, err: boolean) {
      const create = flags[flagType];
      class TestCommand extends BaseTestCommand {
        public static flagsConfig = {
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          doflag: create({ char: 'i', description: 'my desc' }),
        };
      }
      const output = await TestCommand.run(['--doflag', val]);
      if (err) {
        const sfdxError = SfdxError.create('@salesforce/command', 'flags', 'InvalidFlagTypeError', [
          val,
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore kind doesn't exist
          TestCommand.flagsConfig.doflag.kind,
          ERR_NEXT_STEPS[flagType] || '',
        ]);
        expect(output).to.equal(undefined);
        expect(process.exitCode).to.equal(1);
        verifyUXOutput({
          error: [['ERROR running TestCommand: ', sfdxError.message]],
        });
      } else {
        expect(output).to.equal(TestCommand.output);
        verifyUXOutput();
      }
    }


function validateFlagAttributes(output: unknown, errName: string, flagName: string) {
      const sfdxError = SfdxError.create('@salesforce/command', 'flags', errName, [flagName]);
      expect(output).to.equal(undefined);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [['ERROR running TestCommand: ', sfdxError.message]],
      });
    }


(obj: unknown): obj is { code: string; oclif: { exit: number } } => {
  const errorMaybe = obj as { code: string; oclif: { exit: number } };
  return typeof errorMaybe.code === 'string' && errorMaybe.oclif && typeof errorMaybe.oclif.exit === 'number';
}


() => ({ value: undefined })


(message) => {
    if (message && typeof message === 'string') {
      lines.push(message);
    }
  }


() => {
    process.exitCode = 0;

    UX_OUTPUT = cloneJson(UX_OUTPUT_BASE);
    configAggregatorCreate = $$.SANDBOX.stub(ConfigAggregator, 'create').returns(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Promise.resolve(DEFAULT_INSTANCE_PROPS.configAggregator) as any
    );

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns({ is: () => false } as any);

    // Stub all UX methods to update the UX_OUTPUT object
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(UX.prototype, 'log').callsFake((args: any) => UX_OUTPUT.log.push(args) as any);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(UX.prototype, 'logJson').callsFake((args: any) => UX_OUTPUT.logJson.push(args) as any);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(UX.prototype, 'error').callsFake((...args: any[]) => UX_OUTPUT.error.push(args) as any);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(UX.prototype, 'errorJson').callsFake((args: any) => UX_OUTPUT.errorJson.push(args) as any);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(UX.prototype, 'table').callsFake((args: any[]) => UX_OUTPUT.table.push(args) as any);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    $$.SANDBOX.stub(UX.prototype, 'warn').callsFake(function (this: UX, args: string[]) {
      UX_OUTPUT.warn.push(args);
      UX.warnings.add(util.format(args));
    } as any); // eslint-disable-line @typescript-eslint/no-explicit-any

    // Ensure BaseTestCommand['result'] is not defined before all tests
    BaseTestCommand.result = {};

    // Ensure BaseTestCommand.flagsConfig is returned to base state
    BaseTestCommand.flagsConfig = {
      flag1: flags.string({ char: 'f', description: 'my desc' }),
    };

    jsonToStdout = env.getBoolean('SFDX_JSON_TO_STDOUT');
    env.unset('SFDX_JSON_TO_STDOUT');

    UX.warnings.clear();
  }


() => false


(args: any) => UX_OUTPUT.log.push(args) as any


(args: any) => UX_OUTPUT.logJson.push(args) as any


(...args: any[]) => UX_OUTPUT.error.push(args) as any


(args: any) => UX_OUTPUT.errorJson.push(args) as any


(args: any[]) => UX_OUTPUT.table.push(args) as any


() => {
    UX.warnings = new Set();
    env.setBoolean('SFDX_JSON_TO_STDOUT', jsonToStdout);
  }


(key) => {
      expect(testCommandMeta.cmd.flags, `test for flag: ${key}`).to.have.property(key).and.include(merged[key]);
    }


(key) => !!merged[key]


(key) => {
        expect(testCommandMeta.cmdInstance[key], `test for instance prop: ${key}`).to.deep.equal(merged[key]);
      }


(key) => {
      expect(UX_OUTPUT[key], `test UX output for ${key}()`).to.deep.equal(out[key]);
    }


() => {
    let result: JsonMap = {};
    const x: SfdxResult = {
      display(): void {
        result = ensureJsonMap(this.data);
      },
    };
    if (x.display) {
      const resultStub = stubInterface<Result>($$.SANDBOX, { data: { foo: 'bar' } });
      x.display.call(resultStub);
      expect(result).to.have.property('foo', 'bar');
    }
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const fakeOrg: any = 'fake_org';
    $$.SANDBOX.stub(Org, 'create').returns(fakeOrg);
    class TestCommand extends BaseTestCommand {}
    TestCommand['supportsUsername'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps({ org: fakeOrg });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const fakeOrg: any = 'fake_org';
    $$.SANDBOX.stub(Org, 'create').returns(fakeOrg);
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresUsername'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps({ org: fakeOrg });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const fakeOrg: any = 'fake_devhub_org';
    $$.SANDBOX.stub(Org, 'create').returns(fakeOrg);
    class TestCommand extends BaseTestCommand {}
    TestCommand['supportsDevhubUsername'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetdevhubusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps({ hubOrg: fakeOrg });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const fakeOrg: any = 'fake_devhub_org';
    $$.SANDBOX.stub(Org, 'create').returns(fakeOrg);
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresDevhubUsername'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetdevhubusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps({ hubOrg: fakeOrg });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    let apiVersion: string;
    $$.SANDBOX.stub(Org, 'create').returns({
      getConnection: () => ({
        setApiVersion: (version: string) => {
          apiVersion = version;
        },
        getApiVersion: () => apiVersion,
      }),
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } as any);
    // Run the command
    class ApiVersionCommand extends SfdxCommand {
      protected static requiresUsername = true;
      public async run() {
        expect(this.org && this.org.getConnection().getApiVersion()).to.equal('40.0');
        return { finished: true };
      }
    }
    const output = await ApiVersionCommand.run(['--apiversion=40.0']);
    expect(output.finished).to.be.true;
  }


() => ({
        setApiVersion: (version: string) => {
          apiVersion = version;
        },
        getApiVersion: () => apiVersion,
      })


(version: string) => {
          apiVersion = version;
        }


() => apiVersion


async () => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const fakeProject: any = 'fake_project';
    $$.SANDBOX.stub(SfdxProject, 'resolve').withArgs().returns(fakeProject);
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresProject'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
    });
    verifyInstanceProps({ project: fakeProject });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    class TestCommand extends BaseTestCommand {}
    TestCommand.flagsConfig.verbose = flags.builtin();

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      verbose: { type: 'boolean' },
    });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    class TestCommand extends BaseTestCommand {}
    const cmdArgs = [{ name: 'file' }];
    TestCommand['args'] = cmdArgs;

    // Run the command
    const output = await TestCommand.run(['arg1_val', '--flag1', 'flag1_val']);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args').to.equal(cmdArgs);
    verifyCmdFlags({
      flag1: { type: 'option' },
    });
    verifyInstanceProps({
      flags: Object.assign({ flag1: 'flag1_val' }, DEFAULT_INSTANCE_PROPS.flags),
      args: { file: 'arg1_val' },
    });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    class TestCommand extends BaseTestCommand {}

    return mockStdout(async (lines: string[]) => {
      let output: Optional<string>;
      try {
        output = await TestCommand.run(['-h']);
        fail('Expected EEXIT error');
      } catch (err) {
        if (!hasErrorProperties(err)) {
          fail('Invalid error');
        }
        expect(err.code).to.equal('EEXIT');
        expect(err.oclif.exit).to.equal(0);
      }

      expect(output).to.equal(undefined);
      expect(process.exitCode).to.equal(0);

      // Check that the first line of the logged output is `USAGE` once ANSI colors have been removed
      expect(lines.length).to.be.gte(1);
      // eslint-disable-next-line no-control-regex
      const help = lines[0].slice(0, lines[0].indexOf('\n')).replace(/\u001b\[[0-9]+m/g, '');
      expect(help).to.equal('USAGE');
    });
  }


async (lines: string[]) => {
      let output: Optional<string>;
      try {
        output = await TestCommand.run(['-h']);
        fail('Expected EEXIT error');
      } catch (err) {
        if (!hasErrorProperties(err)) {
          fail('Invalid error');
        }
        expect(err.code).to.equal('EEXIT');
        expect(err.oclif.exit).to.equal(0);
      }

      expect(output).to.equal(undefined);
      expect(process.exitCode).to.equal(0);

      // Check that the first line of the logged output is `USAGE` once ANSI colors have been removed
      expect(lines.length).to.be.gte(1);
      // eslint-disable-next-line no-control-regex
      const help = lines[0].slice(0, lines[0].indexOf('\n')).replace(/\u001b\[[0-9]+m/g, '');
      expect(help).to.equal('USAGE');
    }


() => {
    class TestCommand extends BaseTestCommand {
      public static flagsConfig = {
        help: flags.help({ char: 'h' }),
      };
    }

    return mockStdout(async (lines: string[]) => {
      // Run the command

      let output: Optional<string>;
      try {
        output = await TestCommand.run(['-h']);
        fail('Expected EEXIT error');
      } catch (err) {
        if (!hasErrorProperties(err)) {
          fail('Invalid error');
        }
        expect(err.code).to.equal('EEXIT');
        expect(err.oclif.exit).to.equal(0);
      }

      expect(output).to.equal(undefined);
      expect(process.exitCode).to.equal(0);
      // Check that the first line of the logged output is `USAGE` once ANSI colors have been removed
      expect(lines.length).to.be.gte(1);
      // eslint-disable-next-line no-control-regex
      const help = lines[0].slice(0, lines[0].indexOf('\n')).replace(/\u001b\[[0-9]+m/g, '');
      expect(help).to.equal('USAGE');
    });
  }


async (lines: string[]) => {
      // Run the command

      let output: Optional<string>;
      try {
        output = await TestCommand.run(['-h']);
        fail('Expected EEXIT error');
      } catch (err) {
        if (!hasErrorProperties(err)) {
          fail('Invalid error');
        }
        expect(err.code).to.equal('EEXIT');
        expect(err.oclif.exit).to.equal(0);
      }

      expect(output).to.equal(undefined);
      expect(process.exitCode).to.equal(0);
      // Check that the first line of the logged output is `USAGE` once ANSI colors have been removed
      expect(lines.length).to.be.gte(1);
      // eslint-disable-next-line no-control-regex
      const help = lines[0].slice(0, lines[0].indexOf('\n')).replace(/\u001b\[[0-9]+m/g, '');
      expect(help).to.equal('USAGE');
    }


() => {
    class TestCommand extends BaseTestCommand {
      public static flagsConfig = {
        foo: flags.boolean({ char: 'h', description: 'foo' }),
      };
    }

    return mockStdout(async () => {
      const output = await TestCommand.run(['-h']);

      expect(output).to.equal(TestCommand.output);
      expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
      verifyInstanceProps({
        flags: Object.assign({ foo: true }, DEFAULT_INSTANCE_PROPS.flags),
      });
      const expectedResult = {
        data: TestCommand.output,
        tableColumnData: undefined,
      };
      expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
      verifyUXOutput();
    });
  }


async () => {
      const output = await TestCommand.run(['-h']);

      expect(output).to.equal(TestCommand.output);
      expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
      verifyInstanceProps({
        flags: Object.assign({ foo: true }, DEFAULT_INSTANCE_PROPS.flags),
      });
      const expectedResult = {
        data: TestCommand.output,
        tableColumnData: undefined,
      };
      expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
      verifyUXOutput();
    }


() => {
    afterEach(() => {
      env.unset('SFDX_CONTENT_TYPE');
    });

    it('should set this.isJson and only output ux.logJson with the --json flag', async () => {
      // Run the command
      class TestCommand extends BaseTestCommand {}
      const output = await TestCommand.run(['--json']);

      expect(output).to.equal(TestCommand.output);
      expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
      verifyCmdFlags({ flag1: { type: 'option' } });
      verifyInstanceProps({
        flags: Object.assign({ json: true }, DEFAULT_INSTANCE_PROPS.flags),
        isJson: true,
      });
      const expectedResult = {
        data: TestCommand.output,
        tableColumnData: undefined,
      };
      expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
      verifyUXOutput({ logJson: [{ status: 0, result: TestCommand.output }] });
    });

    it('should set this.isJson and only output ux.logJson with SFDX_CONTENT_TYPE=JSON', async () => {
      // Run the command
      class TestCommand extends BaseTestCommand {}

      env.setString('SFDX_CONTENT_TYPE', 'Json');
      const output = await TestCommand.run([]);

      expect(output).to.equal(TestCommand.output);
      expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
      verifyCmdFlags({ flag1: { type: 'option' } });
      verifyInstanceProps({
        flags: Object.assign({ json: true }, DEFAULT_INSTANCE_PROPS.flags),
        isJson: true,
      });
      const expectedResult = {
        data: TestCommand.output,
        tableColumnData: undefined,
      };
      expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
      verifyUXOutput({ logJson: [{ status: 0, result: TestCommand.output }] });
    });
  }


() => {
      env.unset('SFDX_CONTENT_TYPE');
    }


async () => {
      // Run the command
      class TestCommand extends BaseTestCommand {}
      const output = await TestCommand.run(['--json']);

      expect(output).to.equal(TestCommand.output);
      expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
      verifyCmdFlags({ flag1: { type: 'option' } });
      verifyInstanceProps({
        flags: Object.assign({ json: true }, DEFAULT_INSTANCE_PROPS.flags),
        isJson: true,
      });
      const expectedResult = {
        data: TestCommand.output,
        tableColumnData: undefined,
      };
      expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
      verifyUXOutput({ logJson: [{ status: 0, result: TestCommand.output }] });
    }


async () => {
      // Run the command
      class TestCommand extends BaseTestCommand {}

      env.setString('SFDX_CONTENT_TYPE', 'Json');
      const output = await TestCommand.run([]);

      expect(output).to.equal(TestCommand.output);
      expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
      verifyCmdFlags({ flag1: { type: 'option' } });
      verifyInstanceProps({
        flags: Object.assign({ json: true }, DEFAULT_INSTANCE_PROPS.flags),
        isJson: true,
      });
      const expectedResult = {
        data: TestCommand.output,
        tableColumnData: undefined,
      };
      expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
      verifyUXOutput({ logJson: [{ status: 0, result: TestCommand.output }] });
    }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {
      protected getJsonResultObject(result: AnyJson, status: number) {
        return Object.assign(super.getJsonResultObject(result, status), {
          myData: 'test',
        });
      }
    }
    const output = await TestCommand.run(['--json']);

    expect(output).to.equal(TestCommand.output);
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput({ logJson: [{ status: 0, result: TestCommand.output, myData: 'test' }] });
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    const loglevel = 'info';
    const output = await TestCommand.run(['--loglevel', loglevel]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps({
      flags: { loglevel },
    });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
    expect(testCommandMeta.cmdInstance['logger'].getLevel()).to.equal(LoggerLevel.INFO);
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    const loglevel = 'INFO';
    const output = await TestCommand.run(['--loglevel', loglevel]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps({
      flags: { loglevel: loglevel.toLowerCase() },
    });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
    expect(testCommandMeta.cmdInstance['logger'].getLevel()).to.equal(LoggerLevel.INFO);
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    const tableColumnData = ['foo', 'bar', 'baz'];
    TestCommand['tableColumnData'] = tableColumnData;
    TestCommand.output = [
      { foo: 1000, bar: 'moscow mule', baz: false },
      { foo: 2000, bar: 'The Melvin', baz: true },
      { foo: 3000, bar: 'NE IPA', baz: true },
      { foo: 4000, bar: 'Guinness', baz: 0 },
    ];
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData,
    };
    expect(testCommandMeta.cmdInstance['result']).to.deep.include(expectedResult);
    verifyUXOutput({ table: [TestCommand.output] });
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    const tableColumnData = ['foo', 'bar', 'baz'];
    TestCommand['tableColumnData'] = tableColumnData;
    TestCommand.output = [] as JsonArray;
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData,
    };
    expect(testCommandMeta.cmdInstance['result']).to.deep.include(expectedResult);
    verifyUXOutput({ log: ['No results found.'] });
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    const tableColumnData = ['foo', 'bar', 'baz'];
    TestCommand['result']['tableColumnData'] = tableColumnData;
    TestCommand.output = [
      { foo: 1000, bar: 'moscow mule', baz: false },
      { foo: 2000, bar: 'The Melvin', baz: true },
      { foo: 3000, bar: 'NE IPA', baz: true },
      { foo: 4000, bar: 'Guinness', baz: 0 },
    ];
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData,
    };
    expect(testCommandMeta.cmdInstance['result']).to.deep.include(expectedResult);
    verifyUXOutput({ table: [TestCommand.output] });
  }


async () => {
    // Run the command
    const tableColumnData = {
      columns: [
        { key: 'foo', label: 'Foo' },
        { key: 'bar', label: 'Bar' },
        { key: 'baz', label: 'Baz' },
      ],
    };
    // Implement a new command here to ensure the compiler checks the shape of `result`
    class MyTestCommand extends BaseTestCommand {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      public static result: any = {
        tableColumnData,
        display() {
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          this.ux.log(`CUSTOM: ${this.data}`);
        },
      };
    }
    MyTestCommand.output = [
      { Foo: 1000, Bar: 'moscow mule', Baz: false },
      { Foo: 2000, Bar: 'The Melvin', Baz: true },
      { Foo: 3000, Bar: 'NE IPA', Baz: true },
      { Foo: 4000, Bar: 'Guinness', Baz: 0 },
    ];
    const output = await MyTestCommand.run([]);

    expect(output).to.equal(MyTestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps();
    const expectedResult = {
      data: MyTestCommand.output,
      tableColumnData,
    };
    expect(testCommandMeta.cmdInstance['result']).to.deep.include(expectedResult);
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
    verifyUXOutput({ log: [`CUSTOM: ${MyTestCommand.output}`] });
  }


async () => {
    // Run the command
    class TestCommand extends BaseTestCommand {}
    TestCommand['result']['display'] = function (this: Result) {
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
      this.ux.log(`CUSTOM: ${this.data}`);
    };
    TestCommand.output = 'new string output';
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.deep.include(expectedResult);
    verifyUXOutput({ log: [`CUSTOM: ${TestCommand.output}`] });
  }


async () => {
    const apiVersion = '42.0';
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const configAggregator: any = {
      getInfo: () => ({ value: apiVersion }),
    };
    configAggregatorCreate.restore();
    configAggregatorCreate = $$.SANDBOX.stub(ConfigAggregator, 'create').returns(configAggregator);

    // Run the command
    class TestCommand extends BaseTestCommand {}
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({ flag1: { type: 'option' } });
    verifyInstanceProps({ configAggregator });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput({
      warn: [`apiVersion configuration overridden at "${apiVersion}"`],
    });
  }


() => ({ value: apiVersion })


async () => {
    const apiVersion = '42.0';
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const configAggregator: any = {
      getInfo: () => ({ value: apiVersion }),
    };
    configAggregatorCreate.restore();
    configAggregatorCreate = $$.SANDBOX.stub(ConfigAggregator, 'create').returns(configAggregator);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const fakeOrg: any = 'fake_org';
    $$.SANDBOX.stub(Org, 'create').returns(fakeOrg);

    // Run the command
    class TestCommand extends BaseTestCommand {}
    TestCommand['supportsUsername'] = true;
    const apiversionFlagVal = '43.0';
    const output = await TestCommand.run(['--apiversion', apiversionFlagVal]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps({
      configAggregator,
      org: fakeOrg,
      flags: Object.assign({ apiversion: apiversionFlagVal }, DEFAULT_INSTANCE_PROPS.flags),
    });
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    $$.SANDBOX.stub(SfdxProject, 'resolve').throws('InvalidProjectWorkspace');
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresProject'] = true;

    const output = await TestCommand.run([]);

    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(1);
    verifyUXOutput({
      error: [['ERROR running TestCommand: ', 'This command is required to run from within an SFDX project.']],
    });
  }


async () => {
    $$.SANDBOX.stub(Org, 'create').throws('NoUsername');
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresUsername'] = true;

    const output = await TestCommand.run([]);

    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(1);
    verifyUXOutput({
      error: [
        [
          'ERROR running TestCommand: ',
          'This command requires a username. Specify it with the -u parameter or with the "sfdx config:set defaultusername=<username>" command.',
        ],
      ],
    });
  }


async () => {
    $$.SANDBOX.stub(Org, 'create').throws('NoUsername');
    class TestCommand extends BaseTestCommand {
      public static varargs = true;
    }
    TestCommand['requiresUsername'] = true;
    const emitSpy = $$.SANDBOX.spy(process, 'emit');

    await TestCommand.run(['--targetusername', 'foo@bar.org', '--json', 'foo=bar']);

    const expectationMsg = 'Expected the command catch handler to emit a "cmdError" event';
    const expectedFlags = {
      targetusername: 'foo@bar.org',
      loglevel: 'warn',
      json: true,
      foo: 'bar',
    };

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    expect((emitSpy.calledOnceWith as any)('cmdError'), expectationMsg).to.equal(true);
    expect(emitSpy.firstCall.args[0]).to.equal('cmdError');
    expect(emitSpy.firstCall.args[1]).to.be.instanceOf(Error);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    expect((emitSpy.firstCall.args as any)[2]).to.deep.equal(expectedFlags);
  }


async () => {
    $$.SANDBOX.stub(Org, 'create').throws('NoUsername');
    class TestCommand extends BaseTestCommand {}
    TestCommand['supportsUsername'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    $$.SANDBOX.stub(Org, 'create').throws('NoUsername');
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresDevhubUsername'] = true;

    const output = await TestCommand.run([]);

    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(1);
    verifyUXOutput({
      error: [
        [
          'ERROR running TestCommand: ',
          'This command requires a dev hub username. Specify it with the -v parameter or with the "sfdx config:set defaultdevhubusername=<username>" command.',
        ],
      ],
    });
  }


async () => {
    $$.SANDBOX.stub(Org, 'create').throws('NoUsername');
    class TestCommand extends BaseTestCommand {}
    TestCommand['supportsDevhubUsername'] = true;

    // Run the command
    const output = await TestCommand.run([]);

    expect(output).to.equal(TestCommand.output);
    expect(testCommandMeta.cmd.args, 'TestCommand.args should be undefined').to.equal(undefined);
    verifyCmdFlags({
      flag1: { type: 'option' },
      targetdevhubusername: { type: 'option' },
      apiversion: { type: 'option' },
    });
    verifyInstanceProps();
    const expectedResult = {
      data: TestCommand.output,
      tableColumnData: undefined,
    };
    expect(testCommandMeta.cmdInstance['result']).to.include(expectedResult);
    verifyUXOutput();
  }


async () => {
    const sfdxError = new SfdxError('err_msg', 'TestError', ['take action 1'], 100);
    sfdxError.data = 'here is more data';
    sfdxError.stack = 'here is the stack';
    $$.SANDBOX.stub(Org, 'create').throws(sfdxError);
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresUsername'] = true;

    const output = await TestCommand.run(['--json']);

    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(100);
    verifyUXOutput({
      logJson: [
        {
          actions: sfdxError.actions,
          commandName: 'TestCommand',
          data: 'here is more data',
          exitCode: 100,
          message: sfdxError.message,
          name: sfdxError.name,
          result: sfdxError.data,
          stack: sfdxError.stack,
          status: 100,
          warnings: [],
        },
      ],
    });
  }


async () => {
    const sfdxError = new SfdxError('err_msg', 'TestError', ['take action 1'], 100);
    sfdxError.data = 'here is more data';
    sfdxError.stack = 'here is the stack';
    $$.SANDBOX.stub(Org, 'create').throws(sfdxError);
    class TestCommand extends BaseTestCommand {}
    TestCommand['requiresUsername'] = true;

    UX.warnings.add('DO NOT USE ME...');
    const output = await TestCommand.run(['--json']);

    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(100);
    verifyUXOutput({
      logJson: [
        {
          actions: sfdxError.actions,
          commandName: 'TestCommand',
          data: 'here is more data',
          exitCode: 100,
          message: sfdxError.message,
          name: sfdxError.name,
          result: sfdxError.data,
          stack: sfdxError.stack,
          status: 100,
          warnings: ['DO NOT USE ME...'],
        },
      ],
    });
  }


async () => {
    Lifecycle.getInstance().removeAllListeners('test1');
    Lifecycle.getInstance().removeAllListeners('test2');

    expect(Lifecycle.getInstance().getListeners('test1').length).to.be.equal(0);
    expect(Lifecycle.getInstance().getListeners('test2').length).to.be.equal(0);

    // Run the command
    class TestCommand extends BaseTestCommand {}
    await TestCommand.run([]);

    expect(Lifecycle.getInstance().getListeners('test1').length).to.be.equal(1);
    expect(Lifecycle.getInstance().getListeners('test2').length).to.be.equal(1);
  }


() => {
    const validator = (name: string, value: unknown) => {
      if (isEmpty(value)) {
        throw Error(`Vararg [${name}] must not be empty.`);
      }
    };

    it('should be added to the command instance when varargs = true', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = true;
      await TestCommand.run(['-f', 'blah', 'foo=bar']);
      expect(testCommandMeta.cmdInstance).to.have.deep.property('varargs', {
        foo: 'bar',
      });
    });

    it('should be added to the command instance when varargs are required', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: true };
      await TestCommand.run(['-f', 'blah', 'foo=bar and this', 'username=me@my.org']);
      expect(testCommandMeta.cmdInstance).to.have.deep.property('varargs', {
        foo: 'bar and this',
        username: 'me@my.org',
      });
    });

    it('should be added to the command instance when varargs pass validation', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: false, validator };
      const cmdArgs = [{ name: 'file' }];
      TestCommand['args'] = cmdArgs;
      await TestCommand.run(['myFile.json', '-f', 'blah', 'foo=bar']);
      expect(testCommandMeta.cmdInstance).to.have.deep.property('varargs', {
        foo: 'bar',
      });
    });

    it('should throw when varargs are required and not provided', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: true, validator };
      await TestCommand.run([]);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [
          [
            'ERROR running TestCommand: ',
            'Provide required name=value pairs for the command. Enclose any values that contain spaces in double quotes.',
          ],
        ],
      });
    });

    it('should throw when varargs are not in the correct format', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = true;
      await TestCommand.run(['-f', 'blah', 'foobar', '=', 'yadda']);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [
          [
            'ERROR running TestCommand: ',
            'Setting variables must be in the format <key>=<value> or <key>="<value with spaces>" but found foobar.',
          ],
        ],
      });
    });

    it('should throw when duplicate varargs are provided', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: false, validator };
      await TestCommand.run(['-f', 'blah', 'foo=bar', 'foo=that']);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [['ERROR running TestCommand: ', "Cannot set variable name 'foo' twice for the same command."]],
      });
    });

    it('should throw when varargs do not pass validation', async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: false, validator };
      await TestCommand.run(['-f', 'blah', 'foo=']);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [['ERROR running TestCommand: ', 'Vararg [foo] must not be empty.']],
      });
    });
  }


(name: string, value: unknown) => {
      if (isEmpty(value)) {
        throw Error(`Vararg [${name}] must not be empty.`);
      }
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = true;
      await TestCommand.run(['-f', 'blah', 'foo=bar']);
      expect(testCommandMeta.cmdInstance).to.have.deep.property('varargs', {
        foo: 'bar',
      });
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: true };
      await TestCommand.run(['-f', 'blah', 'foo=bar and this', 'username=me@my.org']);
      expect(testCommandMeta.cmdInstance).to.have.deep.property('varargs', {
        foo: 'bar and this',
        username: 'me@my.org',
      });
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: false, validator };
      const cmdArgs = [{ name: 'file' }];
      TestCommand['args'] = cmdArgs;
      await TestCommand.run(['myFile.json', '-f', 'blah', 'foo=bar']);
      expect(testCommandMeta.cmdInstance).to.have.deep.property('varargs', {
        foo: 'bar',
      });
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: true, validator };
      await TestCommand.run([]);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [
          [
            'ERROR running TestCommand: ',
            'Provide required name=value pairs for the command. Enclose any values that contain spaces in double quotes.',
          ],
        ],
      });
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = true;
      await TestCommand.run(['-f', 'blah', 'foobar', '=', 'yadda']);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [
          [
            'ERROR running TestCommand: ',
            'Setting variables must be in the format <key>=<value> or <key>="<value with spaces>" but found foobar.',
          ],
        ],
      });
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: false, validator };
      await TestCommand.run(['-f', 'blah', 'foo=bar', 'foo=that']);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [['ERROR running TestCommand: ', "Cannot set variable name 'foo' twice for the same command."]],
      });
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand['varargs'] = { required: false, validator };
      await TestCommand.run(['-f', 'blah', 'foo=']);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [['ERROR running TestCommand: ', 'Vararg [foo] must not be empty.']],
      });
    }


async () => {
      return validateFlag('filepath', '/my/path/to/file.txt', false);
    }


async () => {
      return validateFlag('directory', '/my/path/to/??file.txt', true);
    }


async () => {
      return validateFlag('date', 'this is a date', true);
    }


async () => {
      return validateFlag('datetime', '01-02-2018', false);
    }


async () => {
      return validateFlag('email', 'this is my email', true);
    }


async () => {
      return validateFlag('email', 'me@my.org', false);
    }


async () => {
      return validateFlag('email', 'me@my.', true);
    }


async () => {
      return validateFlag('array', 'one,two,three', false);
    }


async () => {
      return validateFlag('id', 'a07B0000003uuuuuuu', false);
    }


async () => {
      return validateFlag('id', 'a07B0000003', true);
    }


async () => {
      return validateFlag('id', 'a07B00000&*3uuuuuuu', true);
    }


async () => {
      return validateFlag('number', '42', false);
    }


async () => {
      return validateFlag('number', '42.0', false);
    }


async () => {
      return validateFlag('number', '42foo', true);
    }


async () => {
      return validateFlag('number', '0', false);
    }


async () => {
      return validateFlag('url', 'this is a url', true);
    }


async () => {
      return validateFlag('url', 'htttp://salesforce.com', false);
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        myflag: flags.string({
          char: 'm',
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore ignore invalid longDescription value
          longDescription: false,
          description: 'my desc',
        }),
      };

      const output = await TestCommand.run(['--myflag', 'input']);
      validateFlagAttributes(output, 'InvalidLongDescriptionFormat', 'myflag');
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore ignore error about not providing description
        myflag: flags.string({ char: 'm' }),
      };
      const output = await TestCommand.run(['--myflag', 'input']);
      validateFlagAttributes(output, 'MissingOrInvalidFlagDescription', 'myflag');
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        myflag: flags.string({
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore ignore invalid char value length
          char: 'foo',
          description: 'bar',
        }),
      };
      const output = await TestCommand.run(['--myflag', 'input']);
      validateFlagAttributes(output, 'InvalidFlagChar', 'myflag');
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore ignore invalid char value
        myflag: flags.string({ char: '5', description: 'bar' }),
      };
      const output = await TestCommand.run(['--myflag', 'input']);
      validateFlagAttributes(output, 'InvalidFlagChar', 'myflag');
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        myFlag: {
          char: 'm',
          description: 'foobar',
        },
      };
      const output = await TestCommand.run(['--myFlag', 'input']);
      validateFlagAttributes(output, 'InvalidFlagName', 'myFlag');
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        myFlag: flags.boolean({
          char: 'm',
          description: 'foobar',
        }),
      };
      const output = await TestCommand.run(['--myFlag', 'input']);
      validateFlagAttributes(output, 'InvalidFlagName', 'myFlag');
    }


async () => {
      class TestCommand extends BaseTestCommand {}
      TestCommand.flagsConfig = {
        myflag: flags.number({
          char: 'm',
          description: 'my desc',
        }),
      };

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore Allow undefined array value against the compiler spec to test underlying engine
      const output = await TestCommand.run(['--myflag', undefined]);
      expect(output).to.equal(undefined);
      expect(process.exitCode).to.equal(1);
      verifyUXOutput({
        error: [['ERROR running TestCommand: ', 'Flag --myflag expects a value']],
      });
    }


() => {
    it('should support all possible flag types', async () => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      let inputs: Dictionary<any> = {};

      class FlagsTestCommand extends BaseTestCommand {
        public static flagsConfig: FlagsConfig = {
          // oclif
          boolean: flags.boolean({ description: 'boolean' }),
          enum: flags.enum({ description: 'enum', options: ['e', 'f'] }),
          help: flags.help({ char: 'h' }),
          integer: flags.integer({ description: 'integer' }),
          option: flags.option({ description: 'custom', parse: (val: string) => val.toUpperCase() }),
          string: flags.string({ description: 'string' }),
          version: flags.version(),

          // sfdx
          array: flags.array({ description: 'array' }),
          optsarray: flags.array({ description: 'optsarray', options: ['1', '3', '5'] }),
          intarray: flags.array({ description: 'intarray', map: (v: string) => parseInt(v, 10) }),
          optsintarray: flags.array({
            description: 'optsintarray',
            map: (v: string) => parseInt(v, 10),
            options: [1, 3, 5],
          }),
          date: flags.date({ description: 'date' }),
          datetime: flags.datetime({ description: 'datetime' }),
          directory: flags.directory({ description: 'directory' }),
          email: flags.email({ description: 'some email' }),
          filepath: flags.filepath({ description: 'filepath' }),
          id: flags.id({ description: 'id' }),
          milliseconds: flags.milliseconds({ description: 'milliseconds' }),
          minutes: flags.minutes({ description: 'minutes' }),
          number: flags.number({ description: 'number' }),
          seconds: flags.seconds({ description: 'seconds' }),
          url: flags.url({ description: 'url' }),

          // builtins
          apiversion: flags.builtin(),
          concise: flags.builtin(),
          quiet: flags.builtin(),
          verbose: flags.builtin(),
        };

        public static supportsUsername = true;
        public static supportsDevhubUsername = true;

        public async run() {
          await super.run();
          inputs = this.flags;
          return this.statics.output;
        }
      }

      await FlagsTestCommand.run([
        // oclif
        '--boolean',
        '--enum=e',
        // --help exits, so skip it in this test
        '--integer=10',
        '--option=o',
        '--string=s',
        // --version exits, so skip it in this test

        // sfdx
        '--array=1,2,3',
        '--optsarray=1,3,5',
        '--intarray=1,2,3',
        '--optsintarray=1,3,5',
        '--date=01-02-2000 GMT',
        '--datetime=01/02/2000 01:02:34 GMT',
        '--email=bill@thecat.org',
        '--filepath=/home/someone/.config',
        '--id=00Dxxxxxxxxxxxx',
        '--milliseconds=5000',
        '--minutes=2',
        '--number=0xdeadbeef',
        '--seconds=5',
        '--url=http://example.com/foo/bar',

        // builtins
        '--apiversion=42.0',
        '--concise',
        '--quiet',
        '--verbose',
        '--targetdevhubusername=foo',
        '--targetusername=bar',
      ]);

      expect(inputs.boolean).to.be.true;
      expect(inputs.enum).to.equal('e');
      expect(inputs.integer).to.equal(10);
      expect(inputs.option).to.equal('O');
      expect(inputs.string).to.equal('s');

      expect(inputs.array).to.deep.equal(['1', '2', '3']);
      expect(inputs.optsarray).to.deep.equal(['1', '3', '5']);
      expect(inputs.intarray).to.deep.equal([1, 2, 3]);
      expect(inputs.optsintarray).to.deep.equal([1, 3, 5]);
      expect(inputs.date.toISOString()).to.equal('2000-01-02T00:00:00.000Z');
      expect(inputs.datetime.toISOString()).to.equal('2000-01-02T01:02:34.000Z');
      expect(inputs.email).to.equal('bill@thecat.org');
      expect(inputs.filepath).to.equal('/home/someone/.config');
      expect(inputs.id).to.equal('00Dxxxxxxxxxxxx');
      expect(inputs.milliseconds).to.deep.equal(Duration.milliseconds(5000));
      expect(inputs.minutes).to.deep.equal(Duration.minutes(2));
      expect(inputs.number).to.equal(3735928559); // 0xdeadbeef
      expect(inputs.seconds).to.deep.equal(Duration.seconds(5));
      expect(inputs.url).to.deep.equal(new URL('http://example.com/foo/bar'));

      expect(inputs.apiversion).to.equal('42.0');
      expect(inputs.concise).to.be.true;
      expect(inputs.verbose).to.be.true;
      expect(inputs.targetdevhubusername).to.equal('foo');
      expect(inputs.targetusername).to.equal('bar');
    });
  }


async () => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      let inputs: Dictionary<any> = {};

      class FlagsTestCommand extends BaseTestCommand {
        public static flagsConfig: FlagsConfig = {
          // oclif
          boolean: flags.boolean({ description: 'boolean' }),
          enum: flags.enum({ description: 'enum', options: ['e', 'f'] }),
          help: flags.help({ char: 'h' }),
          integer: flags.integer({ description: 'integer' }),
          option: flags.option({ description: 'custom', parse: (val: string) => val.toUpperCase() }),
          string: flags.string({ description: 'string' }),
          version: flags.version(),

          // sfdx
          array: flags.array({ description: 'array' }),
          optsarray: flags.array({ description: 'optsarray', options: ['1', '3', '5'] }),
          intarray: flags.array({ description: 'intarray', map: (v: string) => parseInt(v, 10) }),
          optsintarray: flags.array({
            description: 'optsintarray',
            map: (v: string) => parseInt(v, 10),
            options: [1, 3, 5],
          }),
          date: flags.date({ description: 'date' }),
          datetime: flags.datetime({ description: 'datetime' }),
          directory: flags.directory({ description: 'directory' }),
          email: flags.email({ description: 'some email' }),
          filepath: flags.filepath({ description: 'filepath' }),
          id: flags.id({ description: 'id' }),
          milliseconds: flags.milliseconds({ description: 'milliseconds' }),
          minutes: flags.minutes({ description: 'minutes' }),
          number: flags.number({ description: 'number' }),
          seconds: flags.seconds({ description: 'seconds' }),
          url: flags.url({ description: 'url' }),

          // builtins
          apiversion: flags.builtin(),
          concise: flags.builtin(),
          quiet: flags.builtin(),
          verbose: flags.builtin(),
        };

        public static supportsUsername = true;
        public static supportsDevhubUsername = true;

        public async run() {
          await super.run();
          inputs = this.flags;
          return this.statics.output;
        }
      }

      await FlagsTestCommand.run([
        // oclif
        '--boolean',
        '--enum=e',
        // --help exits, so skip it in this test
        '--integer=10',
        '--option=o',
        '--string=s',
        // --version exits, so skip it in this test

        // sfdx
        '--array=1,2,3',
        '--optsarray=1,3,5',
        '--intarray=1,2,3',
        '--optsintarray=1,3,5',
        '--date=01-02-2000 GMT',
        '--datetime=01/02/2000 01:02:34 GMT',
        '--email=bill@thecat.org',
        '--filepath=/home/someone/.config',
        '--id=00Dxxxxxxxxxxxx',
        '--milliseconds=5000',
        '--minutes=2',
        '--number=0xdeadbeef',
        '--seconds=5',
        '--url=http://example.com/foo/bar',

        // builtins
        '--apiversion=42.0',
        '--concise',
        '--quiet',
        '--verbose',
        '--targetdevhubusername=foo',
        '--targetusername=bar',
      ]);

      expect(inputs.boolean).to.be.true;
      expect(inputs.enum).to.equal('e');
      expect(inputs.integer).to.equal(10);
      expect(inputs.option).to.equal('O');
      expect(inputs.string).to.equal('s');

      expect(inputs.array).to.deep.equal(['1', '2', '3']);
      expect(inputs.optsarray).to.deep.equal(['1', '3', '5']);
      expect(inputs.intarray).to.deep.equal([1, 2, 3]);
      expect(inputs.optsintarray).to.deep.equal([1, 3, 5]);
      expect(inputs.date.toISOString()).to.equal('2000-01-02T00:00:00.000Z');
      expect(inputs.datetime.toISOString()).to.equal('2000-01-02T01:02:34.000Z');
      expect(inputs.email).to.equal('bill@thecat.org');
      expect(inputs.filepath).to.equal('/home/someone/.config');
      expect(inputs.id).to.equal('00Dxxxxxxxxxxxx');
      expect(inputs.milliseconds).to.deep.equal(Duration.milliseconds(5000));
      expect(inputs.minutes).to.deep.equal(Duration.minutes(2));
      expect(inputs.number).to.equal(3735928559); // 0xdeadbeef
      expect(inputs.seconds).to.deep.equal(Duration.seconds(5));
      expect(inputs.url).to.deep.equal(new URL('http://example.com/foo/bar'));

      expect(inputs.apiversion).to.equal('42.0');
      expect(inputs.concise).to.be.true;
      expect(inputs.verbose).to.be.true;
      expect(inputs.targetdevhubusername).to.equal('foo');
      expect(inputs.targetusername).to.equal('bar');
    }


(val: string) => val.toUpperCase()


(v: string) => parseInt(v, 10)


async () => {
    // Run the command
    class StderrCommand extends SfdxCommand {
      public async run() {
        throw new Error('Ahhh!');
      }
    }
    const output = await StderrCommand.run(['--json']);
    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(1);

    const logJson = UX_OUTPUT['logJson'];
    expect(logJson.length, 'logJson did not get called with error json').to.equal(1);
    const json = ensureJsonMap(logJson[0]);
    expect(json.message, 'logJson did not get called with the right error').to.contains('Ahhh!');
    expect(UX_OUTPUT['errorJson'].length, 'errorJson got called when it should not have').to.equal(0);
  }


async () => {
    env.setBoolean('SFDX_JSON_TO_STDOUT', true);
    // Run the command
    class StdoutCommand extends SfdxCommand {
      public async run() {
        throw new Error('Ahhh!');
      }
    }
    const output = await StdoutCommand.run(['--json']);
    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(1);

    const logJson = UX_OUTPUT['logJson'];
    expect(logJson.length, 'logJson did not get called with error json').to.equal(1);
    const json = ensureJsonMap(logJson[0]);
    expect(json.message, 'logJson did not get called with the right error').to.contains('Ahhh!');
    expect(UX_OUTPUT['errorJson'].length, 'errorJson got called when it should not have').to.equal(0);
  }


async () => {
    env.setBoolean('SFDX_JSON_TO_STDOUT', false);
    // Run the command
    class StdoutCommand extends SfdxCommand {
      public async run() {
        throw new Error('Ahhh!');
      }
    }
    const output = await StdoutCommand.run(['--json']);
    expect(output).to.equal(undefined);
    expect(process.exitCode).to.equal(1);

    const logJson = UX_OUTPUT['errorJson'];
    expect(logJson.length, 'logJson did not get called with error json').to.equal(1);
    const json = ensureJsonMap(logJson[0]);
    expect(json.message, 'logJson did not get called with the right error').to.contains('Ahhh!');
    expect(UX_OUTPUT['logJson'].length, 'errorJson got called when it should not have').to.equal(0);
  }


() => {
    class TestCommand extends BaseTestCommand {
      public static readonly deprecated = {
        message: "Don't use this junk no more, dig?",
        version: 41,
      };
      public static readonly flagsConfig: FlagsConfig = {
        foo: flags.boolean({
          description: 'crufty stuff',
          deprecated: {
            message: 'For the love of Mike, stop using this!',
            version: '41.0',
            to: 'bar',
          },
        }),
      };
      public async run() {
        return 'I ran!';
      }
    }

    it('should emit command and flag deprecation warnings', async () => {
      const output = await TestCommand.run(['--foo']);
      expect(output).to.equal('I ran!');
      expect(process.exitCode).to.equal(0);

      const commandWarning =
        'The command "TestCommand" has been deprecated and will be removed in v42.0 or later. Don\'t use this junk no more, dig?';
      expect(UX_OUTPUT.warn[0]).to.include(commandWarning);

      const flagWarning =
        'The flag "foo" has been deprecated and will be removed in v42.0 or later. Use "bar" instead. For the love of Mike, stop using this!';
      expect(UX_OUTPUT.warn[1]).to.include(flagWarning);
    });

    it('should collect command and flag deprecation warnings when outputting json', async () => {
      await TestCommand.run(['--foo', '--json']);
      expect(UX_OUTPUT.logJson[0]).to.deep.equal({
        status: 0,
        result: 'I ran!',
        warnings: [
          'The command "TestCommand" has been deprecated and will be removed in v42.0 or later. Don\'t use this junk no more, dig?',
          'The flag "foo" has been deprecated and will be removed in v42.0 or later. Use "bar" instead. For the love of Mike, stop using this!',
        ],
      });
    });
  }


async () => {
      const output = await TestCommand.run(['--foo']);
      expect(output).to.equal('I ran!');
      expect(process.exitCode).to.equal(0);

      const commandWarning =
        'The command "TestCommand" has been deprecated and will be removed in v42.0 or later. Don\'t use this junk no more, dig?';
      expect(UX_OUTPUT.warn[0]).to.include(commandWarning);

      const flagWarning =
        'The flag "foo" has been deprecated and will be removed in v42.0 or later. Use "bar" instead. For the love of Mike, stop using this!';
      expect(UX_OUTPUT.warn[1]).to.include(flagWarning);
    }


async () => {
      await TestCommand.run(['--foo', '--json']);
      expect(UX_OUTPUT.logJson[0]).to.deep.equal({
        status: 0,
        result: 'I ran!',
        warnings: [
          'The command "TestCommand" has been deprecated and will be removed in v42.0 or later. Don\'t use this junk no more, dig?',
          'The flag "foo" has been deprecated and will be removed in v42.0 or later. Use "bar" instead. For the love of Mike, stop using this!',
        ],
      });
    }


() => {
  class TestCommand extends BaseTestCommand {
    public format(error: SfdxError) {
      return this.formatError(error);
    }
  }

  it('should return expected base formatting', () => {
    // Set the mode to TEST
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.TEST);

    const message = "it's a trap!";
    const name = 'BadError';

    const sfdxError = new SfdxError(message, name);
    sfdxError.stack = 'stack for BadError';

    const expectedFormat = ['ERROR: ', message];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  });

  it('should return expected formatting with a commandName set', () => {
    // Set the mode to TEST
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.TEST);

    const message = "it's a trap!";
    const name = 'BadError';
    const commandName = 'TestCommand1';

    const sfdxError = new SfdxError(message, name);
    sfdxError.stack = 'stack for BadError';
    sfdxError.setCommandName(commandName);

    const expectedFormat = [`ERROR running ${commandName}: `, message];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  });

  it('should return expected formatting with actions', () => {
    // Set the mode to TEST
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.TEST);

    const message = "it's a trap!";
    const name = 'BadError';
    const actions = ['take action 1', 'take action 2'];

    const sfdxError = new SfdxError(message, name, actions);
    sfdxError.stack = 'stack for BadError';

    const expectedFormat = ['ERROR: ', message, '\n\nTry this:', `\n${actions[0]}`, `\n${actions[1]}`];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  });

  it('should return expected formatting with stack trace (in dev mode)', () => {
    // Set the mode to DEVELOPMENT
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.DEVELOPMENT);

    const message = "it's a trap!";
    const name = 'BadError';

    const sfdxError = new SfdxError(message, name);
    sfdxError.stack = 'stack for BadError';

    const stackMsg = `\n*** Internal Diagnostic ***\n\n${sfdxError.stack}\n******\n`;
    const expectedFormat = ['ERROR: ', message, stackMsg];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  });

  it('should return generate usage by default', () => {
    expect(TestCommand.usage).to.contain('[-f <string>]');
  });
}


() => {
    // Set the mode to TEST
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.TEST);

    const message = "it's a trap!";
    const name = 'BadError';

    const sfdxError = new SfdxError(message, name);
    sfdxError.stack = 'stack for BadError';

    const expectedFormat = ['ERROR: ', message];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  }


() => {
    // Set the mode to TEST
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.TEST);

    const message = "it's a trap!";
    const name = 'BadError';
    const commandName = 'TestCommand1';

    const sfdxError = new SfdxError(message, name);
    sfdxError.stack = 'stack for BadError';
    sfdxError.setCommandName(commandName);

    const expectedFormat = [`ERROR running ${commandName}: `, message];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  }


() => {
    // Set the mode to TEST
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.TEST);

    const message = "it's a trap!";
    const name = 'BadError';
    const actions = ['take action 1', 'take action 2'];

    const sfdxError = new SfdxError(message, name, actions);
    sfdxError.stack = 'stack for BadError';

    const expectedFormat = ['ERROR: ', message, '\n\nTry this:', `\n${actions[0]}`, `\n${actions[1]}`];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  }


() => {
    // Set the mode to DEVELOPMENT
    $$.SANDBOX.stub(Global, 'getEnvironmentMode').returns(Mode.DEVELOPMENT);

    const message = "it's a trap!";
    const name = 'BadError';

    const sfdxError = new SfdxError(message, name);
    sfdxError.stack = 'stack for BadError';

    const stackMsg = `\n*** Internal Diagnostic ***\n\n${sfdxError.stack}\n******\n`;
    const expectedFormat = ['ERROR: ', message, stackMsg];

    const config = stubInterface<IConfig>($$.SANDBOX);
    expect(new TestCommand([], config).format(sfdxError)).to.deep.equal(expectedFormat);
  }


() => {
    expect(TestCommand.usage).to.contain('[-f <string>]');
  }


// The test command
class BaseTestCommand extends SfdxCommand {
  public static output: string | JsonArray = 'default test output';
  public static flagsConfig: FlagsConfig = {
    flag1: flags.string({ char: 'f', description: 'my desc' }),
  };
  public static result: Dictionary;
  protected readonly lifecycleEventNames = ['test1', 'test2'];
  protected get statics(): typeof BaseTestCommand {
    return this.constructor as typeof BaseTestCommand;
  }

  public async run() {
    testCommandMeta = {
      cmdInstance: this,
      cmd: this.statics,
    };
    return this.statics.output;
  }
}


// Run the command
class TestCommand extends BaseTestCommand {}


class TestCommand extends BaseTestCommand {}


// Run the command
class ApiVersionCommand extends SfdxCommand {
      protected static requiresUsername = true;
      public async run() {
        expect(this.org && this.org.getConnection().getApiVersion()).to.equal('40.0');
        return { finished: true };
      }
    }


class TestCommand extends BaseTestCommand {
      public static flagsConfig = {
        help: flags.help({ char: 'h' }),
      };
    }


class TestCommand extends BaseTestCommand {
      public static flagsConfig = {
        foo: flags.boolean({ char: 'h', description: 'foo' }),
      };
    }


// Run the command
class TestCommand extends BaseTestCommand {
      protected getJsonResultObject(result: AnyJson, status: number) {
        return Object.assign(super.getJsonResultObject(result, status), {
          myData: 'test',
        });
      }
    }


// Implement a new command here to ensure the compiler checks the shape of `result`
class MyTestCommand extends BaseTestCommand {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      public static result: any = {
        tableColumnData,
        display() {
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          this.ux.log(`CUSTOM: ${this.data}`);
        },
      };
    }


class TestCommand extends BaseTestCommand {
      public static varargs = true;
    }


class TestCommand extends BaseTestCommand {
        public static flagsConfig = {
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-ignore
          doflag: create({ char: 'i', description: 'my desc' }),
        };
      }


class FlagsTestCommand extends BaseTestCommand {
        public static flagsConfig: FlagsConfig = {
          // oclif
          boolean: flags.boolean({ description: 'boolean' }),
          enum: flags.enum({ description: 'enum', options: ['e', 'f'] }),
          help: flags.help({ char: 'h' }),
          integer: flags.integer({ description: 'integer' }),
          option: flags.option({ description: 'custom', parse: (val: string) => val.toUpperCase() }),
          string: flags.string({ description: 'string' }),
          version: flags.version(),

          // sfdx
          array: flags.array({ description: 'array' }),
          optsarray: flags.array({ description: 'optsarray', options: ['1', '3', '5'] }),
          intarray: flags.array({ description: 'intarray', map: (v: string) => parseInt(v, 10) }),
          optsintarray: flags.array({
            description: 'optsintarray',
            map: (v: string) => parseInt(v, 10),
            options: [1, 3, 5],
          }),
          date: flags.date({ description: 'date' }),
          datetime: flags.datetime({ description: 'datetime' }),
          directory: flags.directory({ description: 'directory' }),
          email: flags.email({ description: 'some email' }),
          filepath: flags.filepath({ description: 'filepath' }),
          id: flags.id({ description: 'id' }),
          milliseconds: flags.milliseconds({ description: 'milliseconds' }),
          minutes: flags.minutes({ description: 'minutes' }),
          number: flags.number({ description: 'number' }),
          seconds: flags.seconds({ description: 'seconds' }),
          url: flags.url({ description: 'url' }),

          // builtins
          apiversion: flags.builtin(),
          concise: flags.builtin(),
          quiet: flags.builtin(),
          verbose: flags.builtin(),
        };

        public static supportsUsername = true;
        public static supportsDevhubUsername = true;

        public async run() {
          await super.run();
          inputs = this.flags;
          return this.statics.output;
        }
      }


// Run the command
class StderrCommand extends SfdxCommand {
      public async run() {
        throw new Error('Ahhh!');
      }
    }


// Run the command
class StdoutCommand extends SfdxCommand {
      public async run() {
        throw new Error('Ahhh!');
      }
    }


class TestCommand extends BaseTestCommand {
      public static readonly deprecated = {
        message: "Don't use this junk no more, dig?",
        version: 41,
      };
      public static readonly flagsConfig: FlagsConfig = {
        foo: flags.boolean({
          description: 'crufty stuff',
          deprecated: {
            message: 'For the love of Mike, stop using this!',
            version: '41.0',
            to: 'bar',
          },
        }),
      };
      public async run() {
        return 'I ran!';
      }
    }


class TestCommand extends BaseTestCommand {
    public format(error: SfdxError) {
      return this.formatError(error);
    }
  }


interface TestCommandMeta {
  cmd: typeof SfdxCommand; // the command constructor props
  cmdInstance: SfdxCommand; // the command instance props
}


public async run() {
    testCommandMeta = {
      cmdInstance: this,
      cmd: this.statics,
    };
    return this.statics.output;
  }


display(): void {
        result = ensureJsonMap(this.data);
      }


public async run() {
        expect(this.org && this.org.getConnection().getApiVersion()).to.equal('40.0');
        return { finished: true };
      }


protected getJsonResultObject(result: AnyJson, status: number) {
        return Object.assign(super.getJsonResultObject(result, status), {
          myData: 'test',
        });
      }


display() {
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          this.ux.log(`CUSTOM: ${this.data}`);
        }


public async run() {
          await super.run();
          inputs = this.flags;
          return this.statics.output;
        }


public async run() {
        throw new Error('Ahhh!');
      }


public async run() {
        return 'I ran!';
      }


public format(error: SfdxError) {
      return this.formatError(error);
    }


() => this.getRemoteData(value)


list => {
                this.data = list;
                this.label = this.ui.spanLabel;
                this.control = this.ui.spanControl;
                if (list.length === 0) {
                    this.label = null;
                    this.offset = this.ui.spanLabel;
                }
                this.grid_span = 4;   // TODO
                this.updateAllChecked();
            }


w => w.checked


item => item.value


item => (item.checked = values.indexOf(item.value) !== -1)


item => (item.checked = this.allChecked)


item => item.checked === false