#!/usr/bin/env node
function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
    var f, y, t, g, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    };
    return(g = {
        next: verb(0),
        "throw": verb(1),
        "return": verb(2)
    }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
        return this;
    }), g);
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(_)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { DEFAULT_OPTIONS, __commonJS, __require, compile, error, pathTransform } from "./chunk-7YXBFBLJ.js";
// package.json
var require_package = __commonJS({
    "package.json": function(exports, module) {
        module.exports = {
            name: "@kickstartds/json-schema-to-typescript",
            version: "13.1.3",
            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": "^4.14.182",
                "@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: "^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: {
                "@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",
                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"
                ]
            },
            browserify: {
                transform: [
                    "browserify-shim"
                ]
            },
            "browserify-shim": {
                prettier: "global:prettier"
            }
        };
    }
});
// src/cli.ts
import getStdin from "get-stdin";
import { readFile, writeFile } from "fs/promises";
import { existsSync, lstatSync, readdirSync } from "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"
    ]
}));
function main(argv) {
    return _main.apply(this, arguments);
}
function _main() {
    _main = _async_to_generator(function(argv) {
        var argIn, argOut, ISGLOB, ISDIR, result, e;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (argv.help) {
                        printHelp();
                        process.exit(0);
                    }
                    argIn = argv._[0] || argv.input;
                    argOut = argv._[1] || argv.output;
                    ISGLOB = isGlob(argIn);
                    ISDIR = isDir(argIn);
                    if ((ISGLOB || ISDIR) && argOut && argOut.includes(".d.ts")) {
                        throw new ReferenceError("You have specified a single file ".concat(argOut, " output for a multi file input ").concat(argIn, ". This feature is not yet supported, refer to issue #272 (https://github.com/bcherny/json-schema-to-typescript/issues/272)"));
                    }
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        8,
                        ,
                        9
                    ]);
                    if (!ISGLOB) return [
                        3,
                        3
                    ];
                    return [
                        4,
                        processGlob(argIn, argOut, argv)
                    ];
                case 2:
                    _state.sent();
                    return [
                        3,
                        7
                    ];
                case 3:
                    if (!ISDIR) return [
                        3,
                        5
                    ];
                    return [
                        4,
                        processDir(argIn, argOut, argv)
                    ];
                case 4:
                    _state.sent();
                    return [
                        3,
                        7
                    ];
                case 5:
                    return [
                        4,
                        processFile(argIn, argv)
                    ];
                case 6:
                    result = _state.sent();
                    outputResult(result, argOut);
                    _state.label = 7;
                case 7:
                    return [
                        3,
                        9
                    ];
                case 8:
                    e = _state.sent();
                    error(e);
                    process.exit(1);
                    return [
                        3,
                        9
                    ];
                case 9:
                    return [
                        2
                    ];
            }
        });
    });
    return _main.apply(this, arguments);
}
function isDir(path) {
    return existsSync(path) && lstatSync(path).isDirectory();
}
function processGlob(argIn, argOut, argv) {
    return _processGlob.apply(this, arguments);
}
function _processGlob() {
    _processGlob = _async_to_generator(function(argIn, argOut, argv) {
        var files, results;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    return [
                        4,
                        glob(argIn)
                    ];
                case 1:
                    files = _state.sent();
                    if (files.length === 0) {
                        throw ReferenceError('You passed a glob pattern "'.concat(argIn, '", but there are no files that match that pattern in ').concat(process.cwd()));
                    }
                    return [
                        4,
                        Promise.all(files.map(function() {
                            var _ref = _async_to_generator(function(file) {
                                var _tmp;
                                return _ts_generator(this, function(_state) {
                                    switch(_state.label){
                                        case 0:
                                            _tmp = [
                                                file
                                            ];
                                            return [
                                                4,
                                                processFile(file, argv)
                                            ];
                                        case 1:
                                            return [
                                                2,
                                                _tmp.concat([
                                                    _state.sent()
                                                ])
                                            ];
                                    }
                                });
                            });
                            return function(file) {
                                return _ref.apply(this, arguments);
                            };
                        }()))
                    ];
                case 2:
                    results = _state.sent();
                    results.forEach(function(param) {
                        var _param = _sliced_to_array(param, 2), file = _param[0], result = _param[1];
                        var outputPath = argOut && "".concat(argOut, "/").concat(basename(file, ".json"), ".d.ts");
                        outputResult(result, outputPath);
                    });
                    return [
                        2
                    ];
            }
        });
    });
    return _processGlob.apply(this, arguments);
}
function processDir(argIn, argOut, argv) {
    return _processDir.apply(this, arguments);
}
function _processDir() {
    _processDir = _async_to_generator(function(argIn, argOut, argv) {
        var files, results;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    files = getPaths(argIn);
                    return [
                        4,
                        Promise.all(files.map(function() {
                            var _ref = _async_to_generator(function(file) {
                                var _tmp, outputPath, _tmp1;
                                return _ts_generator(this, function(_state) {
                                    switch(_state.label){
                                        case 0:
                                            if (!!argOut) return [
                                                3,
                                                2
                                            ];
                                            _tmp = [
                                                file
                                            ];
                                            return [
                                                4,
                                                processFile(file, argv)
                                            ];
                                        case 1:
                                            return [
                                                2,
                                                _tmp.concat([
                                                    _state.sent()
                                                ])
                                            ];
                                        case 2:
                                            outputPath = pathTransform(argOut, argIn, file);
                                            _tmp1 = [
                                                file
                                            ];
                                            return [
                                                4,
                                                processFile(file, argv)
                                            ];
                                        case 3:
                                            return [
                                                2,
                                                _tmp1.concat([
                                                    _state.sent(),
                                                    outputPath
                                                ])
                                            ];
                                        case 4:
                                            return [
                                                2
                                            ];
                                    }
                                });
                            });
                            return function(file) {
                                return _ref.apply(this, arguments);
                            };
                        }()))
                    ];
                case 1:
                    results = _state.sent();
                    results.forEach(function(param) {
                        var _param = _sliced_to_array(param, 3), file = _param[0], result = _param[1], outputPath = _param[2];
                        return outputResult(result, outputPath ? "".concat(outputPath, "/").concat(basename(file, ".json"), ".d.ts") : void 0);
                    });
                    return [
                        2
                    ];
            }
        });
    });
    return _processDir.apply(this, arguments);
}
function outputResult(result, outputPath) {
    return _outputResult.apply(this, arguments);
}
function _outputResult() {
    _outputResult = _async_to_generator(function(result, outputPath) {
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    if (!!outputPath) return [
                        3,
                        1
                    ];
                    process.stdout.write(result);
                    return [
                        3,
                        3
                    ];
                case 1:
                    if (!isDir(dirname(outputPath))) {
                        mkdirp.sync(dirname(outputPath));
                    }
                    return [
                        4,
                        writeFile(outputPath, result)
                    ];
                case 2:
                    return [
                        2,
                        _state.sent()
                    ];
                case 3:
                    return [
                        2
                    ];
            }
        });
    });
    return _outputResult.apply(this, arguments);
}
function processFile(argIn, argv) {
    return _processFile.apply(this, arguments);
}
function _processFile() {
    _processFile = _async_to_generator(function(argIn, argv) {
        var schema, _;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    _ = JSON.parse;
                    return [
                        4,
                        readInput(argIn)
                    ];
                case 1:
                    schema = _.apply(JSON, [
                        _state.sent()
                    ]);
                    return [
                        2,
                        compile(schema, argIn, argv)
                    ];
            }
        });
    });
    return _processFile.apply(this, arguments);
}
function getPaths(path) {
    var paths = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
    if (existsSync(path) && lstatSync(path).isDirectory()) {
        readdirSync(resolve(path)).forEach(function(item) {
            return 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() {
    var pkg = require_package();
    process.stdout.write("\n".concat(pkg.name, " ").concat(pkg.version, "\nUsage: json2ts [--input, -i] [IN_FILE] [--output, -o] [OUT_FILE] [OPTIONS]\n\nWith no IN_FILE, or when IN_FILE is -, read standard input.\nWith no OUT_FILE and when IN_FILE is specified, create .d.ts file in the same directory.\nWith no OUT_FILE nor IN_FILE, write to standard output.\n\nYou can use any of the following options by adding them at the end.\nBoolean values can be set to false using the 'no-' prefix.\n\n  --additionalProperties\n      Default value for additionalProperties, when it is not explicitly set\n  --cwd=XXX\n      Root directory for resolving $ref\n  --declareExternallyReferenced\n      Declare external schemas referenced via '$ref'?\n  --enableConstEnums\n      Prepend enums with 'const'?\n  --format\n      Format code? Set this to false to improve performance.\n  --maxItems\n      Maximum number of unioned tuples to emit when representing bounded-size\n      array types, before falling back to emitting unbounded arrays. Increase\n      this to improve precision of emitted types, decrease it to improve\n      performance, or set it to -1 to ignore minItems and maxItems.\n  --style.XXX=YYY\n      Prettier configuration\n  --unknownAny\n      Output unknown type instead of any type\n  --unreachableDefinitions\n      Generates code for definitions that aren't referenced by the schema\n"));
}
