#!/usr/bin/env node
import {
  DEFAULT_OPTIONS,
  __commonJS,
  __require,
  compile,
  error,
  pathTransform
} from "./chunk-7NAOY4KW.js";

// package.json
var require_package = __commonJS({
  "package.json"(exports, module) {
    module.exports = {
      name: "@kickstartds/json-schema-to-typescript",
      version: "13.1.8",
      description: "compile json schema to typescript typings",
      main: "./dist/index.cjs",
      module: "./dist/index.js",
      bin: {
        json2ts: "dist/cli.js"
      },
      types: "./dist/index.d.ts",
      engines: {
        node: ">=16.0.0"
      },
      exports: {
        ".": {
          require: "./dist/index.cjs",
          import: "./dist/index.js",
          types: "./dist/index.d.ts"
        }
      },
      scripts: {
        build: "npm run lint && npm run clean && npm run build:browser && npm run build:server",
        "build:browser": "browserify src/index.ts -s jstt -p tsify > dist/bundle.js",
        "build:server": "tsup src/index.ts src/cli.ts --format cjs,esm --dts --clean",
        "build:test": "tsup test/test.ts test/e2e --external ava",
        clean: "shx rm -rf dist && mkdir dist",
        format: 'prettier "{src,test}/*.ts" --write',
        "format-check": 'prettier "{src,test}/*.ts" --check',
        lint: "eslint src/*.ts test/*.ts",
        tdd: "concurrently -r -p '' -k 'npm run watch' 'npm run watch:test'",
        test: "npm run pre-test && ava --timeout=300s --verbose",
        stresstest: "seq 1 10 | xargs -I{} npm test",
        postinstall: "patch-package",
        prepublishOnly: "npm test",
        "pre-test": "npm run clean && npm run format-check && npm run build:server && npm run build:test",
        watch: "tsup src/index.ts src/cli.ts --watch",
        "watch:test": "ava -w"
      },
      repository: {
        type: "git",
        url: "git+https://github.com/bcherny/json-schema-to-typescript.git"
      },
      keywords: [
        "json",
        "schema",
        "typescript",
        "compile",
        "transpile",
        "api",
        "interface",
        "typing",
        "share"
      ],
      type: "module",
      author: "Boris Cherny <boris@performancejs.com> (http://performancejs.com/)",
      license: "MIT",
      bugs: {
        url: "https://github.com/bcherny/json-schema-to-typescript/issues"
      },
      homepage: "https://github.com/bcherny/json-schema-to-typescript#readme",
      dependencies: {
        "@bcherny/json-schema-ref-parser": "10.0.5-fork",
        "@types/json-schema": "^7.0.11",
        "@types/lodash-es": "^4.17.9",
        "@types/prettier": "^2.6.1",
        "cli-color": "^2.0.2",
        "get-stdin": "^8.0.0",
        glob: "^7.1.6",
        "glob-promise": "^4.2.2",
        "is-glob": "^4.0.3",
        "lodash-es": "^4.17.21",
        minimist: "^1.2.6",
        mkdirp: "^1.0.4",
        "patch-package": "^8.0.0",
        "postinstall-postinstall": "^2.1.0",
        prettier: "^2.6.2"
      },
      devDependencies: {
        "@kickstartds/jsonschema-utils": "^2.4.6",
        "@swc/core": "^1.3.82",
        "@types/cli-color": "^2.0.2",
        "@types/glob": "^7.2.0",
        "@types/is-glob": "^4.0.2",
        "@types/minimist": "^1.2.2",
        "@types/mkdirp": "^1.0.2",
        "@types/node": "^17.0.33",
        "@types/rimraf": "^3.0.2",
        "@typescript-eslint/eslint-plugin": "^5.23.0",
        "@typescript-eslint/parser": "^5.23.0",
        ava: "^5.3.1",
        browserify: "^17.0.0",
        "browserify-shim": "^3.8.14",
        concurrently: "^7.2.0",
        eslint: "^8.15.0",
        "eslint-config-prettier": "^8.5.0",
        "eslint-plugin-prettier": "^4.0.0",
        "pascal-case": "^3.1.2",
        rimraf: "^3.0.2",
        shx: "^0.3.4",
        tsify: "^5.0.4",
        tsup: "^7.2.0",
        typescript: "^4.9.5"
      },
      ava: {
        files: [
          "./dist/test.cjs"
        ],
        ignoredByWatcher: [
          "./src"
        ],
        snapshotDir: "./test/__snapshots__"
      },
      browserify: {
        transform: [
          "browserify-shim"
        ]
      },
      "browserify-shim": {
        prettier: "global:prettier"
      }
    };
  }
});

// src/cli.ts
import getStdin from "get-stdin";
import { readFile, writeFile } from "node:fs/promises";
import { existsSync, lstatSync, readdirSync } from "node:fs";
import * as mkdirp from "mkdirp";
import glob from "glob-promise";
import { join, resolve, dirname, basename } from "path";
var minimist = __require("minimist");
var isGlob = __require("is-glob");
main(
  minimist(process.argv.slice(2), {
    alias: {
      help: ["h"],
      input: ["i"],
      output: ["o"]
    },
    boolean: [
      "additionalProperties",
      "declareExternallyReferenced",
      "enableConstEnums",
      "format",
      "ignoreMinAndMaxItems",
      "strictIndexSignatures",
      "unknownAny",
      "unreachableDefinitions"
    ],
    default: DEFAULT_OPTIONS,
    string: ["bannerComment", "cwd"]
  })
);
async function main(argv) {
  if (argv.help) {
    printHelp();
    process.exit(0);
  }
  const argIn = argv._[0] || argv.input;
  const argOut = argv._[1] || argv.output;
  const ISGLOB = isGlob(argIn);
  const ISDIR = isDir(argIn);
  if ((ISGLOB || ISDIR) && argOut && argOut.includes(".d.ts")) {
    throw new ReferenceError(
      `You have specified a single file ${argOut} output for a multi file input ${argIn}. This feature is not yet supported, refer to issue #272 (https://github.com/bcherny/json-schema-to-typescript/issues/272)`
    );
  }
  try {
    if (ISGLOB) {
      await processGlob(argIn, argOut, argv);
    } else if (ISDIR) {
      await processDir(argIn, argOut, argv);
    } else {
      const result = await processFile(argIn, argv);
      outputResult(result, argOut);
    }
  } catch (e) {
    error(e);
    process.exit(1);
  }
}
function isDir(path) {
  return existsSync(path) && lstatSync(path).isDirectory();
}
async function processGlob(argIn, argOut, argv) {
  const files = await glob(argIn);
  if (files.length === 0) {
    throw ReferenceError(
      `You passed a glob pattern "${argIn}", but there are no files that match that pattern in ${process.cwd()}`
    );
  }
  const results = await Promise.all(
    files.map(async (file) => {
      return [file, await processFile(file, argv)];
    })
  );
  results.forEach(([file, result]) => {
    const outputPath = argOut && `${argOut}/${basename(file, ".json")}.d.ts`;
    outputResult(result, outputPath);
  });
}
async function processDir(argIn, argOut, argv) {
  const files = getPaths(argIn);
  const results = await Promise.all(
    files.map(async (file) => {
      if (!argOut) {
        return [file, await processFile(file, argv)];
      } else {
        const outputPath = pathTransform(argOut, argIn, file);
        return [file, await processFile(file, argv), outputPath];
      }
    })
  );
  results.forEach(
    ([file, result, outputPath]) => outputResult(result, outputPath ? `${outputPath}/${basename(file, ".json")}.d.ts` : void 0)
  );
}
async function outputResult(result, outputPath) {
  if (!outputPath) {
    process.stdout.write(result);
  } else {
    if (!isDir(dirname(outputPath))) {
      mkdirp.sync(dirname(outputPath));
    }
    return await writeFile(outputPath, result);
  }
}
async function processFile(argIn, argv) {
  const schema = JSON.parse(await readInput(argIn));
  return compile(schema, argIn, argv);
}
function getPaths(path, paths = []) {
  if (existsSync(path) && lstatSync(path).isDirectory()) {
    readdirSync(resolve(path)).forEach((item) => getPaths(join(path, item), paths));
  } else {
    paths.push(path);
  }
  return paths;
}
function readInput(argIn) {
  if (!argIn) {
    return getStdin();
  }
  return readFile(resolve(process.cwd(), argIn), "utf-8");
}
function printHelp() {
  const pkg = require_package();
  process.stdout.write(
    `
${pkg.name} ${pkg.version}
Usage: json2ts [--input, -i] [IN_FILE] [--output, -o] [OUT_FILE] [OPTIONS]

With no IN_FILE, or when IN_FILE is -, read standard input.
With no OUT_FILE and when IN_FILE is specified, create .d.ts file in the same directory.
With no OUT_FILE nor IN_FILE, write to standard output.

You can use any of the following options by adding them at the end.
Boolean values can be set to false using the 'no-' prefix.

  --additionalProperties
      Default value for additionalProperties, when it is not explicitly set
  --cwd=XXX
      Root directory for resolving $ref
  --declareExternallyReferenced
      Declare external schemas referenced via '$ref'?
  --enableConstEnums
      Prepend enums with 'const'?
  --format
      Format code? Set this to false to improve performance.
  --maxItems
      Maximum number of unioned tuples to emit when representing bounded-size
      array types, before falling back to emitting unbounded arrays. Increase
      this to improve precision of emitted types, decrease it to improve
      performance, or set it to -1 to ignore minItems and maxItems.
  --style.XXX=YYY
      Prettier configuration
  --unknownAny
      Output unknown type instead of any type
  --unreachableDefinitions
      Generates code for definitions that aren't referenced by the schema
`
  );
}
