"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = __importDefault(require("fs/promises"));
const spawn_please_1 = __importDefault(require("spawn-please"));
const cli_options_1 = __importStar(require("../cli-options"));
const chalk_1 = require("../lib/chalk");
const INJECT_HEADER = '<!-- Do not edit this section by hand. It is auto-generated in build-options.ts. Run "npm run build" or "npm run build:options" to build. -->';
/** Replaces markdown code ticks with <code>...</code> tag. */
const codeHtml = (code) => code.replace(/\b`/g, '</code>').replace(/`/g, '<code>');
/** Replaces the "Options" and "Advanced Options" sections of the README with direct output from "ncu --help". */
const injectReadme = async () => {
    const { default: stripAnsi } = await import('strip-ansi');
    let readme = await promises_1.default.readFile('README.md', 'utf8');
    const optionRows = cli_options_1.default
        .map(option => {
        return `  <tr>
    <td>${option.short ? `-${option.short}, ` : ''}${option.cli !== false ? '--' : ''}${option.long}${option.arg ? ` <${option.arg}>` : ''}</td>
    <td>${codeHtml(option.description)}${option.default ? ` (default: ${JSON.stringify(option.default)})` : ''}</td>
  </tr>`;
    })
        .join('\n');
    // inject options into README
    const optionsStart = readme.indexOf('<!-- BEGIN Options -->') + '<!-- BEGIN Options -->'.length;
    const optionsEnd = readme.indexOf('<!-- END Options -->', optionsStart);
    readme = `${readme.slice(0, optionsStart)}
${INJECT_HEADER}

<table>
${optionRows}
</table>

${readme.slice(optionsEnd)}`;
    // Inject advanced options into README
    // Even though chalkInit has a colorless option, we need stripAnsi to remove the ANSI characters frim the output of cli-table
    await (0, chalk_1.chalkInit)();
    const advancedOptionsStart = readme.indexOf('<!-- BEGIN Advanced Options -->') + '<!-- BEGIN Advanced Options -->'.length;
    const advancedOptionsEnd = readme.indexOf('<!-- END Advanced Options -->', advancedOptionsStart);
    readme = `${readme.slice(0, advancedOptionsStart)}
${INJECT_HEADER}

${cli_options_1.default
        .filter(option => option.help)
        .map(option => `## ${option.long}

${stripAnsi((0, cli_options_1.renderExtendedHelp)(option, { markdown: true }))}
`)
        .join('\n')}
${readme.slice(advancedOptionsEnd)}`;
    return readme;
};
/** Renders a single CLI option for a type definition file. */
const renderOption = (option) => {
    // deepPatternFix needs to be escaped, otherwise it will break the block comment
    const description = option.long === 'deep' ? option.description.replace('**/', '**\\/') : option.description;
    // pre must be internally typed as number and externally typed as boolean to maintain compatibility with the CLI option and the RunOption
    const type = option.long === 'pre' ? 'boolean' : option.type;
    const defaults = 
    // do not render default empty arrays
    option.default && (!Array.isArray(option.default) || option.default.length > 0)
        ? `\n   *\n   * @default ${JSON.stringify(option.default)}\n  `
        : '';
    // all options are optional
    return `  /** ${description}${option.help ? ` Run "ncu --help --${option.long}" for details.` : ''}${defaults} */
  ${option.long}?: ${type}
`;
};
/** Generate /src/types/RunOptions from cli-options so there is a single source of truth. */
const generateRunOptions = (options) => {
    const header = `/** This file is generated automatically from the options specified in /src/cli-options.ts. Do not edit manually. Run "npm run build" or "npm run build:options" to build. */
import { FilterFunction } from './FilterFunction'
import { FilterResultsFunction } from './FilterResultsFunction'
import { GroupFunction } from './GroupFunction'
import { PackageFile } from './PackageFile'
import { TargetFunction } from './TargetFunction'

/** Options that can be given on the CLI or passed to the ncu module to control all behavior. */
export interface RunOptions {
`;
    const footer = '}\n';
    const optionsTypeCode = options.map(renderOption).join('\n');
    const output = `${header}${optionsTypeCode}${footer}`;
    return output;
};
/** Generates a JSON schema for the ncurc file. */
const generateRunOptionsJsonSchema = async () => 
// programmatic usage of typescript-json-schema does not work, at least not straightforwardly.
// Use the CLI which works out-of-the-box.
(0, spawn_please_1.default)('typescript-json-schema', ['tsconfig.json', 'RunOptions']);
(async () => {
    await promises_1.default.writeFile('README.md', await injectReadme());
    await promises_1.default.writeFile('src/types/RunOptions.ts', generateRunOptions(cli_options_1.default));
    await promises_1.default.writeFile('src/types/RunOptions.json', await generateRunOptionsJsonSchema());
    await (0, spawn_please_1.default)('prettier', ['-w', 'src/types/RunOptions.json']);
})();
//# sourceMappingURL=build-options.js.map