json-schema-to-typescript
Advanced tools
Comparing version 13.1.2 to 14.0.0
@@ -5,2 +5,6 @@ # Changelog | ||
## 14.0.0 | ||
- 967eb13 Require Node v16+ | ||
## 13.1.0 | ||
@@ -7,0 +11,0 @@ |
@@ -35,42 +35,18 @@ #!/usr/bin/env node | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; | ||
} | ||
var __asyncValues = (this && this.__asyncValues) || function (o) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var m = o[Symbol.asyncIterator], i; | ||
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); | ||
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } | ||
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var minimist = require("minimist"); | ||
var get_stdin_1 = __importDefault(require("get-stdin")); | ||
var fs_1 = require("mz/fs"); | ||
var mkdirp = __importStar(require("mkdirp")); | ||
var glob_promise_1 = __importDefault(require("glob-promise")); | ||
var isGlob = require("is-glob"); | ||
var path_1 = require("path"); | ||
var index_1 = require("./index"); | ||
var utils_1 = require("./utils"); | ||
const minimist = require("minimist"); | ||
const fs_1 = require("mz/fs"); | ||
const mkdirp = __importStar(require("mkdirp")); | ||
const glob_1 = require("glob"); | ||
const isGlob = require("is-glob"); | ||
const path_1 = require("path"); | ||
const index_1 = require("./index"); | ||
const utils_1 = require("./utils"); | ||
main(minimist(process.argv.slice(2), { | ||
@@ -96,47 +72,31 @@ alias: { | ||
function main(argv) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var argIn, argOut, ISGLOB, ISDIR, result, e_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (argv.help) { | ||
printHelp(); | ||
process.exit(0); | ||
} | ||
argIn = argv._[0] || argv.input; | ||
argOut = argv._[1] || argv.output // the output can be omitted so this can be undefined | ||
; | ||
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)")); | ||
} | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 8, , 9]); | ||
if (!ISGLOB) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, processGlob(argIn, argOut, argv)]; | ||
case 2: | ||
_a.sent(); | ||
return [3 /*break*/, 7]; | ||
case 3: | ||
if (!ISDIR) return [3 /*break*/, 5]; | ||
return [4 /*yield*/, processDir(argIn, argOut, argv)]; | ||
case 4: | ||
_a.sent(); | ||
return [3 /*break*/, 7]; | ||
case 5: return [4 /*yield*/, processFile(argIn, argv)]; | ||
case 6: | ||
result = _a.sent(); | ||
outputResult(result, argOut); | ||
_a.label = 7; | ||
case 7: return [3 /*break*/, 9]; | ||
case 8: | ||
e_1 = _a.sent(); | ||
(0, utils_1.error)(e_1); | ||
process.exit(1); | ||
return [3 /*break*/, 9]; | ||
case 9: return [2 /*return*/]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (argv.help) { | ||
printHelp(); | ||
process.exit(0); | ||
} | ||
const argIn = argv._[0] || argv.input; | ||
const argOut = argv._[1] || argv.output; // the output can be omitted so this can be undefined | ||
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 { | ||
// Process input as either glob, directory, or single file | ||
if (ISGLOB) { | ||
yield processGlob(argIn, argOut, argv); | ||
} | ||
}); | ||
else if (ISDIR) { | ||
yield processDir(argIn, argOut, argv); | ||
} | ||
else { | ||
const result = yield processFile(argIn, argv); | ||
outputResult(result, argOut); | ||
} | ||
} | ||
catch (e) { | ||
(0, utils_1.error)(e); | ||
process.exit(1); | ||
} | ||
}); | ||
@@ -149,37 +109,15 @@ } | ||
function processGlob(argIn, argOut, argv) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var files, results; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, (0, glob_promise_1.default)(argIn)]; // execute glob pattern match | ||
case 1: | ||
files = _a.sent() // execute glob pattern match | ||
; | ||
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 /*yield*/, Promise.all(files.map(function (file) { return __awaiter(_this, void 0, void 0, function () { | ||
var _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = [file]; | ||
return [4 /*yield*/, processFile(file, argv)]; | ||
case 1: return [2 /*return*/, _a.concat([_b.sent()])]; | ||
} | ||
}); | ||
}); })) | ||
// careful to do this serially | ||
]; | ||
case 2: | ||
results = _a.sent(); | ||
// careful to do this serially | ||
results.forEach(function (_a) { | ||
var file = _a[0], result = _a[1]; | ||
var outputPath = argOut && "".concat(argOut, "/").concat((0, path_1.basename)(file, '.json'), ".d.ts"); | ||
outputResult(result, outputPath); | ||
}); | ||
return [2 /*return*/]; | ||
} | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const files = yield (0, glob_1.glob)(argIn); // execute glob pattern match | ||
if (files.length === 0) { | ||
throw ReferenceError(`You passed a glob pattern "${argIn}", but there are no files that match that pattern in ${process.cwd()}`); | ||
} | ||
// we can do this concurrently for perf | ||
const results = yield Promise.all(files.map((file) => __awaiter(this, void 0, void 0, function* () { | ||
return [file, yield processFile(file, argv)]; | ||
}))); | ||
// careful to do this serially | ||
results.forEach(([file, result]) => { | ||
const outputPath = argOut && `${argOut}/${(0, path_1.basename)(file, '.json')}.d.ts`; | ||
outputResult(result, outputPath); | ||
}); | ||
@@ -189,78 +127,40 @@ }); | ||
function processDir(argIn, argOut, argv) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var files, results; | ||
var _this = this; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
files = getPaths(argIn); | ||
return [4 /*yield*/, Promise.all(files.map(function (file) { return __awaiter(_this, void 0, void 0, function () { | ||
var _a, outputPath, _b; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
if (!!argOut) return [3 /*break*/, 2]; | ||
_a = [file]; | ||
return [4 /*yield*/, processFile(file, argv)]; | ||
case 1: return [2 /*return*/, _a.concat([_c.sent()])]; | ||
case 2: | ||
outputPath = (0, utils_1.pathTransform)(argOut, argIn, file); | ||
_b = [file]; | ||
return [4 /*yield*/, processFile(file, argv)]; | ||
case 3: return [2 /*return*/, _b.concat([_c.sent(), outputPath])]; | ||
} | ||
}); | ||
}); })) | ||
// careful to do this serially | ||
]; | ||
case 1: | ||
results = _a.sent(); | ||
// careful to do this serially | ||
results.forEach(function (_a) { | ||
var file = _a[0], result = _a[1], outputPath = _a[2]; | ||
return outputResult(result, outputPath ? "".concat(outputPath, "/").concat((0, path_1.basename)(file, '.json'), ".d.ts") : undefined); | ||
}); | ||
return [2 /*return*/]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const files = getPaths(argIn); | ||
// we can do this concurrently for perf | ||
const results = yield Promise.all(files.map((file) => __awaiter(this, void 0, void 0, function* () { | ||
if (!argOut) { | ||
return [file, yield processFile(file, argv)]; | ||
} | ||
}); | ||
else { | ||
const outputPath = (0, utils_1.pathTransform)(argOut, argIn, file); | ||
return [file, yield processFile(file, argv), outputPath]; | ||
} | ||
}))); | ||
// careful to do this serially | ||
results.forEach(([file, result, outputPath]) => outputResult(result, outputPath ? `${outputPath}/${(0, path_1.basename)(file, '.json')}.d.ts` : undefined)); | ||
}); | ||
} | ||
function outputResult(result, outputPath) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!!outputPath) return [3 /*break*/, 1]; | ||
process.stdout.write(result); | ||
return [3 /*break*/, 3]; | ||
case 1: | ||
if (!isDir((0, path_1.dirname)(outputPath))) { | ||
mkdirp.sync((0, path_1.dirname)(outputPath)); | ||
} | ||
return [4 /*yield*/, (0, fs_1.writeFile)(outputPath, result)]; | ||
case 2: return [2 /*return*/, _a.sent()]; | ||
case 3: return [2 /*return*/]; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!outputPath) { | ||
process.stdout.write(result); | ||
} | ||
else { | ||
if (!isDir((0, path_1.dirname)(outputPath))) { | ||
mkdirp.sync((0, path_1.dirname)(outputPath)); | ||
} | ||
}); | ||
return yield (0, fs_1.writeFile)(outputPath, result); | ||
} | ||
}); | ||
} | ||
function processFile(argIn, argv) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var schema, _a, _b; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_b = (_a = JSON).parse; | ||
return [4 /*yield*/, readInput(argIn)]; | ||
case 1: | ||
schema = _b.apply(_a, [_c.sent()]); | ||
return [2 /*return*/, (0, index_1.compile)(schema, argIn, argv)]; | ||
} | ||
}); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const schema = JSON.parse(yield readInput(argIn)); | ||
return (0, index_1.compile)(schema, argIn, argv); | ||
}); | ||
} | ||
function getPaths(path, paths) { | ||
if (paths === void 0) { paths = []; } | ||
function getPaths(path, paths = []) { | ||
if ((0, fs_1.existsSync)(path) && (0, fs_1.lstatSync)(path).isDirectory()) { | ||
(0, fs_1.readdirSync)((0, path_1.resolve)(path)).forEach(function (item) { return getPaths((0, path_1.join)(path, item), paths); }); | ||
(0, fs_1.readdirSync)((0, path_1.resolve)(path)).forEach(item => getPaths((0, path_1.join)(path, item), paths)); | ||
} | ||
@@ -273,11 +173,68 @@ else { | ||
function readInput(argIn) { | ||
if (!argIn) { | ||
return (0, get_stdin_1.default)(); | ||
} | ||
return (0, fs_1.readFile)((0, path_1.resolve)(process.cwd(), argIn), 'utf-8'); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!argIn) { | ||
return readStream(process.stdin); | ||
} | ||
return (0, fs_1.readFile)((0, path_1.resolve)(process.cwd(), argIn), 'utf-8'); | ||
}); | ||
} | ||
function readStream(stream) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
var _a, stream_1, stream_1_1; | ||
var _b, e_1, _c, _d; | ||
const chunks = []; | ||
try { | ||
for (_a = true, stream_1 = __asyncValues(stream); stream_1_1 = yield stream_1.next(), _b = stream_1_1.done, !_b; _a = true) { | ||
_d = stream_1_1.value; | ||
_a = false; | ||
const chunk = _d; | ||
chunks.push(chunk); | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (!_a && !_b && (_c = stream_1.return)) yield _c.call(stream_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
return Buffer.concat(chunks).toString('utf8'); | ||
}); | ||
} | ||
function printHelp() { | ||
var pkg = require('../../package.json'); | ||
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")); | ||
const pkg = require('../../package.json'); | ||
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 | ||
`); | ||
} | ||
//# sourceMappingURL=cli.js.map |
import { Options } from './'; | ||
export declare function format(code: string, options: Options): string; | ||
export declare function format(code: string, options: Options): Promise<string>; |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.format = void 0; | ||
var prettier_1 = require("prettier"); | ||
const prettier_1 = require("prettier"); | ||
function format(code, options) { | ||
if (!options.format) { | ||
return code; | ||
} | ||
return (0, prettier_1.format)(code, __assign({ parser: 'typescript' }, options.style)); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!options.format) { | ||
return code; | ||
} | ||
return (0, prettier_1.format)(code, Object.assign({ parser: 'typescript' }, options.style)); | ||
}); | ||
} | ||
exports.format = format; | ||
//# sourceMappingURL=formatter.js.map |
"use strict"; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateType = exports.generate = void 0; | ||
var lodash_1 = require("lodash"); | ||
var index_1 = require("./index"); | ||
var AST_1 = require("./types/AST"); | ||
var utils_1 = require("./utils"); | ||
function generate(ast, options) { | ||
if (options === void 0) { options = index_1.DEFAULT_OPTIONS; } | ||
const lodash_1 = require("lodash"); | ||
const index_1 = require("./index"); | ||
const AST_1 = require("./types/AST"); | ||
const utils_1 = require("./utils"); | ||
function generate(ast, options = index_1.DEFAULT_OPTIONS) { | ||
return ([ | ||
@@ -29,4 +19,3 @@ options.bannerComment, | ||
exports.generate = generate; | ||
function declareEnums(ast, options, processed) { | ||
if (processed === void 0) { processed = new Set(); } | ||
function declareEnums(ast, options, processed = new Set()) { | ||
if (processed.has(ast)) { | ||
@@ -36,3 +25,3 @@ return ''; | ||
processed.add(ast); | ||
var type = ''; | ||
let type = ''; | ||
switch (ast.type) { | ||
@@ -45,5 +34,5 @@ case 'ENUM': | ||
case 'INTERSECTION': | ||
return ast.params.reduce(function (prev, ast) { return prev + declareEnums(ast, options, processed); }, ''); | ||
return ast.params.reduce((prev, ast) => prev + declareEnums(ast, options, processed), ''); | ||
case 'TUPLE': | ||
type = ast.params.reduce(function (prev, ast) { return prev + declareEnums(ast, options, processed); }, ''); | ||
type = ast.params.reduce((prev, ast) => prev + declareEnums(ast, options, processed), ''); | ||
if (ast.spreadParam) { | ||
@@ -54,3 +43,3 @@ type += declareEnums(ast.spreadParam, options, processed); | ||
case 'INTERFACE': | ||
return getSuperTypesAndParams(ast).reduce(function (prev, ast) { return prev + declareEnums(ast, options, processed); }, ''); | ||
return getSuperTypesAndParams(ast).reduce((prev, ast) => prev + declareEnums(ast, options, processed), ''); | ||
default: | ||
@@ -60,4 +49,3 @@ return ''; | ||
} | ||
function declareNamedInterfaces(ast, options, rootASTName, processed) { | ||
if (processed === void 0) { processed = new Set(); } | ||
function declareNamedInterfaces(ast, options, rootASTName, processed = new Set()) { | ||
if (processed.has(ast)) { | ||
@@ -67,3 +55,3 @@ return ''; | ||
processed.add(ast); | ||
var type = ''; | ||
let type = ''; | ||
switch (ast.type) { | ||
@@ -79,3 +67,3 @@ case 'ARRAY': | ||
getSuperTypesAndParams(ast) | ||
.map(function (ast) { return declareNamedInterfaces(ast, options, rootASTName, processed); }) | ||
.map(ast => declareNamedInterfaces(ast, options, rootASTName, processed)) | ||
.filter(Boolean) | ||
@@ -91,3 +79,3 @@ .join('\n'), | ||
type = ast.params | ||
.map(function (_) { return declareNamedInterfaces(_, options, rootASTName, processed); }) | ||
.map(_ => declareNamedInterfaces(_, options, rootASTName, processed)) | ||
.filter(Boolean) | ||
@@ -104,4 +92,3 @@ .join('\n'); | ||
} | ||
function declareNamedTypes(ast, options, rootASTName, processed) { | ||
if (processed === void 0) { processed = new Set(); } | ||
function declareNamedTypes(ast, options, rootASTName, processed = new Set()) { | ||
if (processed.has(ast)) { | ||
@@ -123,6 +110,4 @@ return ''; | ||
return getSuperTypesAndParams(ast) | ||
.map(function (ast) { | ||
return (ast.standaloneName === rootASTName || options.declareExternallyReferenced) && | ||
declareNamedTypes(ast, options, rootASTName, processed); | ||
}) | ||
.map(ast => (ast.standaloneName === rootASTName || options.declareExternallyReferenced) && | ||
declareNamedTypes(ast, options, rootASTName, processed)) | ||
.filter(Boolean) | ||
@@ -136,3 +121,3 @@ .join('\n'); | ||
ast.params | ||
.map(function (ast) { return declareNamedTypes(ast, options, rootASTName, processed); }) | ||
.map(ast => declareNamedTypes(ast, options, rootASTName, processed)) | ||
.filter(Boolean) | ||
@@ -154,5 +139,5 @@ .join('\n'), | ||
function generateTypeUnmemoized(ast, options) { | ||
var type = generateRawType(ast, options); | ||
const type = generateRawType(ast, options); | ||
if (options.strictIndexSignatures && ast.keyName === '[k: string]') { | ||
return "".concat(type, " | undefined"); | ||
return `${type} | undefined`; | ||
} | ||
@@ -171,4 +156,4 @@ return type; | ||
case 'ARRAY': | ||
return (function () { | ||
var type = (0, exports.generateType)(ast.params, options); | ||
return (() => { | ||
const type = (0, exports.generateType)(ast.params, options); | ||
return type.endsWith('"') ? '(' + type + ')[]' : type + '[]'; | ||
@@ -197,7 +182,7 @@ })(); | ||
case 'TUPLE': | ||
return (function () { | ||
var minItems = ast.minItems; | ||
var maxItems = ast.maxItems || -1; | ||
var spreadParam = ast.spreadParam; | ||
var astParams = __spreadArray([], ast.params, true); | ||
return (() => { | ||
const minItems = ast.minItems; | ||
const maxItems = ast.maxItems || -1; | ||
let spreadParam = ast.spreadParam; | ||
const astParams = [...ast.params]; | ||
if (minItems > 0 && minItems > astParams.length && ast.spreadParam === undefined) { | ||
@@ -213,3 +198,3 @@ // this is a valid state, and JSONSchema doesn't care about the item type | ||
// fill the tuple with any elements | ||
for (var i = astParams.length; i < maxItems; i += 1) { | ||
for (let i = astParams.length; i < maxItems; i += 1) { | ||
astParams.push(options.unknownAny ? AST_1.T_UNKNOWN : AST_1.T_ANY); | ||
@@ -220,3 +205,3 @@ } | ||
if (spreadParam) { | ||
var spread = '...(' + (0, exports.generateType)(spreadParam, options) + ')[]'; | ||
const spread = '...(' + (0, exports.generateType)(spreadParam, options) + ')[]'; | ||
params.push(spread); | ||
@@ -229,3 +214,3 @@ } | ||
} | ||
var paramsList = astParams.map(function (param) { return (0, exports.generateType)(param, options); }); | ||
const paramsList = astParams.map(param => (0, exports.generateType)(param, options)); | ||
if (paramsList.length > minItems) { | ||
@@ -244,4 +229,4 @@ /* | ||
*/ | ||
var cumulativeParamsList = paramsList.slice(0, minItems); | ||
var typesToUnion = []; | ||
const cumulativeParamsList = paramsList.slice(0, minItems); | ||
const typesToUnion = []; | ||
if (cumulativeParamsList.length > 0) { | ||
@@ -255,3 +240,3 @@ // actually has minItems, so add the initial state | ||
} | ||
for (var i = minItems; i < paramsList.length; i += 1) { | ||
for (let i = minItems; i < paramsList.length; i += 1) { | ||
cumulativeParamsList.push(paramsList[i]); | ||
@@ -281,23 +266,17 @@ if (i === paramsList.length - 1) { | ||
function generateSetOperation(ast, options) { | ||
var members = ast.params.map(function (_) { return (0, exports.generateType)(_, options); }); | ||
var separator = ast.type === 'UNION' ? '|' : '&'; | ||
const members = ast.params.map(_ => (0, exports.generateType)(_, options)); | ||
const separator = ast.type === 'UNION' ? '|' : '&'; | ||
return members.length === 1 ? members[0] : '(' + members.join(' ' + separator + ' ') + ')'; | ||
} | ||
function generateInterface(ast, options) { | ||
return ("{" + | ||
return (`{` + | ||
'\n' + | ||
ast.params | ||
.filter(function (_) { return !_.isPatternProperty && !_.isUnreachableDefinition; }) | ||
.map(function (_a) { | ||
var isRequired = _a.isRequired, keyName = _a.keyName, ast = _a.ast; | ||
return [isRequired, keyName, ast, (0, exports.generateType)(ast, options)]; | ||
}) | ||
.map(function (_a) { | ||
var isRequired = _a[0], keyName = _a[1], ast = _a[2], type = _a[3]; | ||
return ((0, AST_1.hasComment)(ast) && !ast.standaloneName ? generateComment(ast.comment, ast.deprecated) + '\n' : '') + | ||
escapeKeyName(keyName) + | ||
(isRequired ? '' : '?') + | ||
': ' + | ||
type; | ||
}) | ||
.filter(_ => !_.isPatternProperty && !_.isUnreachableDefinition) | ||
.map(({ isRequired, keyName, ast }) => [isRequired, keyName, ast, (0, exports.generateType)(ast, options)]) | ||
.map(([isRequired, keyName, ast, type]) => ((0, AST_1.hasComment)(ast) && !ast.standaloneName ? generateComment(ast.comment, ast.deprecated) + '\n' : '') + | ||
escapeKeyName(keyName) + | ||
(isRequired ? '' : '?') + | ||
': ' + | ||
type) | ||
.join('\n') + | ||
@@ -308,3 +287,3 @@ '\n' + | ||
function generateComment(comment, deprecated) { | ||
var commentLines = ['/**']; | ||
const commentLines = ['/**']; | ||
if (deprecated) { | ||
@@ -314,3 +293,3 @@ commentLines.push(' * @deprecated'); | ||
if (typeof comment !== 'undefined') { | ||
commentLines.push.apply(commentLines, comment.split('\n').map(function (_) { return ' * ' + _; })); | ||
commentLines.push(...comment.split('\n').map(_ => ' * ' + _)); | ||
} | ||
@@ -324,8 +303,5 @@ commentLines.push(' */'); | ||
(options.enableConstEnums ? 'const ' : '') + | ||
"enum ".concat((0, utils_1.toSafeString)(ast.standaloneName), " {") + | ||
`enum ${(0, utils_1.toSafeString)(ast.standaloneName)} {` + | ||
'\n' + | ||
ast.params.map(function (_a) { | ||
var ast = _a.ast, keyName = _a.keyName; | ||
return keyName + ' = ' + (0, exports.generateType)(ast, options); | ||
}).join(',\n') + | ||
ast.params.map(({ ast, keyName }) => keyName + ' = ' + (0, exports.generateType)(ast, options)).join(',\n') + | ||
'\n' + | ||
@@ -336,5 +312,5 @@ '}'); | ||
return (((0, AST_1.hasComment)(ast) ? generateComment(ast.comment, ast.deprecated) + '\n' : '') + | ||
"export interface ".concat((0, utils_1.toSafeString)(ast.standaloneName), " ") + | ||
`export interface ${(0, utils_1.toSafeString)(ast.standaloneName)} ` + | ||
(ast.superTypes.length > 0 | ||
? "extends ".concat(ast.superTypes.map(function (superType) { return (0, utils_1.toSafeString)(superType.standaloneName); }).join(', '), " ") | ||
? `extends ${ast.superTypes.map(superType => (0, utils_1.toSafeString)(superType.standaloneName)).join(', ')} ` | ||
: '') + | ||
@@ -345,3 +321,3 @@ generateInterface(ast, options)); | ||
return (((0, AST_1.hasComment)(ast) ? generateComment(ast.comment) + '\n' : '') + | ||
"export type ".concat((0, utils_1.toSafeString)(ast.standaloneName), " = ").concat((0, exports.generateType)((0, lodash_1.omit)(ast, 'standaloneName') /* TODO */, options))); | ||
`export type ${(0, utils_1.toSafeString)(ast.standaloneName)} = ${(0, exports.generateType)((0, lodash_1.omit)(ast, 'standaloneName') /* TODO */, options)}`); | ||
} | ||
@@ -358,4 +334,4 @@ function escapeKeyName(keyName) { | ||
function getSuperTypesAndParams(ast) { | ||
return ast.params.map(function (param) { return param.ast; }).concat(ast.superTypes); | ||
return ast.params.map(param => param.ast).concat(ast.superTypes); | ||
} | ||
//# sourceMappingURL=generator.js.map |
import { JSONSchema4 } from 'json-schema'; | ||
import { Options as $RefOptions } from '@bcherny/json-schema-ref-parser'; | ||
import { ParserOptions as $RefOptions } from '@apidevtools/json-schema-ref-parser'; | ||
import { Options as PrettierOptions } from 'prettier'; | ||
@@ -7,3 +7,3 @@ export { EnumJSONSchema, JSONSchema, NamedEnumJSONSchema, CustomTypeJSONSchema } from './types/JSONSchema'; | ||
/** | ||
* [$RefParser](https://github.com/BigstickCarpet/json-schema-ref-parser) Options, used when resolving `$ref`s | ||
* [$RefParser](https://github.com/APIDevTools/json-schema-ref-parser) Options, used when resolving `$ref`s | ||
*/ | ||
@@ -10,0 +10,0 @@ $refOptions: $RefOptions; |
"use strict"; | ||
var __extends = (this && this.__extends) || (function () { | ||
var extendStatics = function (d, b) { | ||
extendStatics = Object.setPrototypeOf || | ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | ||
return extendStatics(d, b); | ||
}; | ||
return function (d, b) { | ||
if (typeof b !== "function" && b !== null) | ||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); | ||
extendStatics(d, b); | ||
function __() { this.constructor = d; } | ||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | ||
}; | ||
})(); | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -37,49 +11,27 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ValidationError = exports.compile = exports.compileFromFile = exports.DEFAULT_OPTIONS = void 0; | ||
var fs_1 = require("fs"); | ||
var lodash_1 = require("lodash"); | ||
var path_1 = require("path"); | ||
var formatter_1 = require("./formatter"); | ||
var generator_1 = require("./generator"); | ||
var normalizer_1 = require("./normalizer"); | ||
var optimizer_1 = require("./optimizer"); | ||
var parser_1 = require("./parser"); | ||
var resolver_1 = require("./resolver"); | ||
var utils_1 = require("./utils"); | ||
var validator_1 = require("./validator"); | ||
var util_1 = require("util"); | ||
var linker_1 = require("./linker"); | ||
var optionValidator_1 = require("./optionValidator"); | ||
const fs_1 = require("fs"); | ||
const lodash_1 = require("lodash"); | ||
const path_1 = require("path"); | ||
const formatter_1 = require("./formatter"); | ||
const generator_1 = require("./generator"); | ||
const normalizer_1 = require("./normalizer"); | ||
const optimizer_1 = require("./optimizer"); | ||
const parser_1 = require("./parser"); | ||
const resolver_1 = require("./resolver"); | ||
const utils_1 = require("./utils"); | ||
const validator_1 = require("./validator"); | ||
const util_1 = require("util"); | ||
const linker_1 = require("./linker"); | ||
const optionValidator_1 = require("./optionValidator"); | ||
exports.DEFAULT_OPTIONS = { | ||
$refOptions: {}, | ||
additionalProperties: true, | ||
bannerComment: "/* eslint-disable */\n/**\n* This file was automatically generated by json-schema-to-typescript.\n* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,\n* and run json-schema-to-typescript to regenerate this file.\n*/", | ||
additionalProperties: true, // TODO: default to empty schema (as per spec) instead | ||
bannerComment: `/* eslint-disable */ | ||
/** | ||
* This file was automatically generated by json-schema-to-typescript. | ||
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, | ||
* and run json-schema-to-typescript to regenerate this file. | ||
*/`, | ||
cwd: process.cwd(), | ||
@@ -104,78 +56,64 @@ declareExternallyReferenced: true, | ||
}; | ||
function compileFromFile(filename, options) { | ||
if (options === void 0) { options = exports.DEFAULT_OPTIONS; } | ||
var contents = (0, utils_1.Try)(function () { return (0, fs_1.readFileSync)(filename); }, function () { | ||
throw new ReferenceError("Unable to read file \"".concat(filename, "\"")); | ||
function compileFromFile(filename, options = exports.DEFAULT_OPTIONS) { | ||
const contents = (0, utils_1.Try)(() => (0, fs_1.readFileSync)(filename), () => { | ||
throw new ReferenceError(`Unable to read file "${filename}"`); | ||
}); | ||
var schema = (0, utils_1.Try)(function () { return JSON.parse(contents.toString()); }, function () { | ||
throw new TypeError("Error parsing JSON in file \"".concat(filename, "\"")); | ||
const schema = (0, utils_1.Try)(() => JSON.parse(contents.toString()), () => { | ||
throw new TypeError(`Error parsing JSON in file "${filename}"`); | ||
}); | ||
return compile(schema, (0, utils_1.stripExtension)(filename), __assign({ cwd: (0, path_1.dirname)(filename) }, options)); | ||
return compile(schema, (0, utils_1.stripExtension)(filename), Object.assign({ cwd: (0, path_1.dirname)(filename) }, options)); | ||
} | ||
exports.compileFromFile = compileFromFile; | ||
function compile(schema, name, options) { | ||
if (options === void 0) { options = {}; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
function compile(schema_1, name_1) { | ||
return __awaiter(this, arguments, void 0, function* (schema, name, options = {}) { | ||
(0, optionValidator_1.validateOptions)(options); | ||
const _options = (0, lodash_1.merge)({}, exports.DEFAULT_OPTIONS, options); | ||
const start = Date.now(); | ||
function time() { | ||
return "(".concat(Date.now() - start, "ms)"); | ||
return `(${Date.now() - start}ms)`; | ||
} | ||
var _options, start, _schema, _a, dereferencedPaths, dereferencedSchema, linked, errors, normalized, parsed, optimized, generated, formatted; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
(0, optionValidator_1.validateOptions)(options); | ||
_options = (0, lodash_1.merge)({}, exports.DEFAULT_OPTIONS, options); | ||
start = Date.now(); | ||
// normalize options | ||
if (!(0, lodash_1.endsWith)(_options.cwd, '/')) { | ||
_options.cwd += '/'; | ||
} | ||
_schema = (0, lodash_1.cloneDeep)(schema); | ||
return [4 /*yield*/, (0, resolver_1.dereference)(_schema, _options)]; | ||
case 1: | ||
_a = _b.sent(), dereferencedPaths = _a.dereferencedPaths, dereferencedSchema = _a.dereferencedSchema; | ||
if (process.env.VERBOSE) { | ||
if ((0, util_1.isDeepStrictEqual)(_schema, dereferencedSchema)) { | ||
(0, utils_1.log)('green', 'dereferencer', time(), '✅ No change'); | ||
} | ||
else { | ||
(0, utils_1.log)('green', 'dereferencer', time(), '✅ Result:', dereferencedSchema); | ||
} | ||
} | ||
linked = (0, linker_1.link)(dereferencedSchema); | ||
if (process.env.VERBOSE) { | ||
(0, utils_1.log)('green', 'linker', time(), '✅ No change'); | ||
} | ||
errors = (0, validator_1.validate)(linked, name); | ||
if (errors.length) { | ||
errors.forEach(function (_) { return (0, utils_1.error)(_); }); | ||
throw new ValidationError(); | ||
} | ||
if (process.env.VERBOSE) { | ||
(0, utils_1.log)('green', 'validator', time(), '✅ No change'); | ||
} | ||
normalized = (0, normalizer_1.normalize)(linked, dereferencedPaths, name, _options); | ||
(0, utils_1.log)('yellow', 'normalizer', time(), '✅ Result:', normalized); | ||
parsed = (0, parser_1.parse)(normalized, _options); | ||
(0, utils_1.log)('blue', 'parser', time(), '✅ Result:', parsed); | ||
optimized = (0, optimizer_1.optimize)(parsed, _options); | ||
(0, utils_1.log)('cyan', 'optimizer', time(), '✅ Result:', optimized); | ||
generated = (0, generator_1.generate)(optimized, _options); | ||
(0, utils_1.log)('magenta', 'generator', time(), '✅ Result:', generated); | ||
formatted = (0, formatter_1.format)(generated, _options); | ||
(0, utils_1.log)('white', 'formatter', time(), '✅ Result:', formatted); | ||
return [2 /*return*/, formatted]; | ||
// normalize options | ||
if (!(0, lodash_1.endsWith)(_options.cwd, '/')) { | ||
_options.cwd += '/'; | ||
} | ||
// Initial clone to avoid mutating the input | ||
const _schema = (0, lodash_1.cloneDeep)(schema); | ||
const { dereferencedPaths, dereferencedSchema } = yield (0, resolver_1.dereference)(_schema, _options); | ||
if (process.env.VERBOSE) { | ||
if ((0, util_1.isDeepStrictEqual)(_schema, dereferencedSchema)) { | ||
(0, utils_1.log)('green', 'dereferencer', time(), '✅ No change'); | ||
} | ||
}); | ||
else { | ||
(0, utils_1.log)('green', 'dereferencer', time(), '✅ Result:', dereferencedSchema); | ||
} | ||
} | ||
const linked = (0, linker_1.link)(dereferencedSchema); | ||
if (process.env.VERBOSE) { | ||
(0, utils_1.log)('green', 'linker', time(), '✅ No change'); | ||
} | ||
const errors = (0, validator_1.validate)(linked, name); | ||
if (errors.length) { | ||
errors.forEach(_ => (0, utils_1.error)(_)); | ||
throw new ValidationError(); | ||
} | ||
if (process.env.VERBOSE) { | ||
(0, utils_1.log)('green', 'validator', time(), '✅ No change'); | ||
} | ||
const normalized = (0, normalizer_1.normalize)(linked, dereferencedPaths, name, _options); | ||
(0, utils_1.log)('yellow', 'normalizer', time(), '✅ Result:', normalized); | ||
const parsed = (0, parser_1.parse)(normalized, _options); | ||
(0, utils_1.log)('blue', 'parser', time(), '✅ Result:', parsed); | ||
const optimized = (0, optimizer_1.optimize)(parsed, _options); | ||
(0, utils_1.log)('cyan', 'optimizer', time(), '✅ Result:', optimized); | ||
const generated = (0, generator_1.generate)(optimized, _options); | ||
(0, utils_1.log)('magenta', 'generator', time(), '✅ Result:', generated); | ||
const formatted = yield (0, formatter_1.format)(generated, _options); | ||
(0, utils_1.log)('white', 'formatter', time(), '✅ Result:', formatted); | ||
return formatted; | ||
}); | ||
} | ||
exports.compile = compile; | ||
var ValidationError = /** @class */ (function (_super) { | ||
__extends(ValidationError, _super); | ||
function ValidationError() { | ||
return _super !== null && _super.apply(this, arguments) || this; | ||
} | ||
return ValidationError; | ||
}(Error)); | ||
class ValidationError extends Error { | ||
} | ||
exports.ValidationError = ValidationError; | ||
//# sourceMappingURL=index.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.link = void 0; | ||
var JSONSchema_1 = require("./types/JSONSchema"); | ||
var lodash_1 = require("lodash"); | ||
const JSONSchema_1 = require("./types/JSONSchema"); | ||
const lodash_1 = require("lodash"); | ||
/** | ||
@@ -10,4 +10,3 @@ * Traverses over the schema, giving each node a reference to its | ||
*/ | ||
function link(schema, parent) { | ||
if (parent === void 0) { parent = null; } | ||
function link(schema, parent = null) { | ||
if (!Array.isArray(schema) && !(0, lodash_1.isPlainObject)(schema)) { | ||
@@ -28,6 +27,6 @@ return schema; | ||
if (Array.isArray(schema)) { | ||
schema.forEach(function (child) { return link(child, schema); }); | ||
schema.forEach(child => link(child, schema)); | ||
} | ||
// Objects | ||
for (var key in schema) { | ||
for (const key in schema) { | ||
link(schema[key], schema); | ||
@@ -34,0 +33,0 @@ } |
"use strict"; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.normalize = void 0; | ||
var JSONSchema_1 = require("./types/JSONSchema"); | ||
var utils_1 = require("./utils"); | ||
var util_1 = require("util"); | ||
var rules = new Map(); | ||
const JSONSchema_1 = require("./types/JSONSchema"); | ||
const utils_1 = require("./utils"); | ||
const util_1 = require("util"); | ||
const rules = new Map(); | ||
function hasType(schema, type) { | ||
@@ -26,11 +17,11 @@ return schema.type === type || (Array.isArray(schema.type) && schema.type.includes(type)); | ||
} | ||
rules.set('Remove `type=["null"]` if `enum=[null]`', function (schema) { | ||
rules.set('Remove `type=["null"]` if `enum=[null]`', schema => { | ||
if (Array.isArray(schema.enum) && | ||
schema.enum.some(function (e) { return e === null; }) && | ||
schema.enum.some(e => e === null) && | ||
Array.isArray(schema.type) && | ||
schema.type.includes('null')) { | ||
schema.type = schema.type.filter(function (type) { return type !== 'null'; }); | ||
schema.type = schema.type.filter(type => type !== 'null'); | ||
} | ||
}); | ||
rules.set('Destructure unary types', function (schema) { | ||
rules.set('Destructure unary types', schema => { | ||
if (schema.type && Array.isArray(schema.type) && schema.type.length === 1) { | ||
@@ -40,3 +31,3 @@ schema.type = schema.type[0]; | ||
}); | ||
rules.set('Add empty `required` property if none is defined', function (schema) { | ||
rules.set('Add empty `required` property if none is defined', schema => { | ||
if (isObjectType(schema) && !('required' in schema)) { | ||
@@ -46,3 +37,3 @@ schema.required = []; | ||
}); | ||
rules.set('Transform `required`=false to `required`=[]', function (schema) { | ||
rules.set('Transform `required`=false to `required`=[]', schema => { | ||
if (schema.required === false) { | ||
@@ -52,3 +43,3 @@ schema.required = []; | ||
}); | ||
rules.set('Default additionalProperties', function (schema, _, options) { | ||
rules.set('Default additionalProperties', (schema, _, options) => { | ||
if (isObjectType(schema) && !('additionalProperties' in schema) && schema.patternProperties === undefined) { | ||
@@ -58,3 +49,3 @@ schema.additionalProperties = options.additionalProperties; | ||
}); | ||
rules.set('Transform id to $id', function (schema, fileName) { | ||
rules.set('Transform id to $id', (schema, fileName) => { | ||
if (!(0, utils_1.isSchemaLike)(schema)) { | ||
@@ -64,3 +55,3 @@ return; | ||
if (schema.id && schema.$id && schema.id !== schema.$id) { | ||
throw ReferenceError("Schema must define either id or $id, not both. Given id=".concat(schema.id, ", $id=").concat(schema.$id, " in ").concat(fileName)); | ||
throw ReferenceError(`Schema must define either id or $id, not both. Given id=${schema.id}, $id=${schema.$id} in ${fileName}`); | ||
} | ||
@@ -72,3 +63,3 @@ if (schema.id) { | ||
}); | ||
rules.set('Add an $id to anything that needs it', function (schema, fileName, _options, _key, dereferencedPaths) { | ||
rules.set('Add an $id to anything that needs it', (schema, fileName, _options, _key, dereferencedPaths) => { | ||
if (!(0, utils_1.isSchemaLike)(schema)) { | ||
@@ -88,3 +79,3 @@ return; | ||
// TODO: Normalize upstream | ||
var dereferencedName = dereferencedPaths.get(schema); | ||
const dereferencedName = dereferencedPaths.get(schema); | ||
if (!schema.$id && !schema.title && dereferencedName) { | ||
@@ -97,18 +88,18 @@ schema.$id = (0, utils_1.toSafeString)((0, utils_1.justName)(dereferencedName)); | ||
}); | ||
rules.set('Escape closing JSDoc comment', function (schema) { | ||
rules.set('Escape closing JSDoc comment', schema => { | ||
(0, utils_1.escapeBlockComment)(schema); | ||
}); | ||
rules.set('Add JSDoc comments for minItems and maxItems', function (schema) { | ||
rules.set('Add JSDoc comments for minItems and maxItems', schema => { | ||
if (!isArrayType(schema)) { | ||
return; | ||
} | ||
var commentsToAppend = [ | ||
'minItems' in schema ? "@minItems ".concat(schema.minItems) : '', | ||
'maxItems' in schema ? "@maxItems ".concat(schema.maxItems) : '', | ||
const commentsToAppend = [ | ||
'minItems' in schema ? `@minItems ${schema.minItems}` : '', | ||
'maxItems' in schema ? `@maxItems ${schema.maxItems}` : '', | ||
].filter(Boolean); | ||
if (commentsToAppend.length) { | ||
schema.description = utils_1.appendToDescription.apply(void 0, __spreadArray([schema.description], commentsToAppend, false)); | ||
schema.description = (0, utils_1.appendToDescription)(schema.description, ...commentsToAppend); | ||
} | ||
}); | ||
rules.set('Optionally remove maxItems and minItems', function (schema, _fileName, options) { | ||
rules.set('Optionally remove maxItems and minItems', (schema, _fileName, options) => { | ||
if (!isArrayType(schema)) { | ||
@@ -124,3 +115,3 @@ return; | ||
}); | ||
rules.set('Normalize schema.minItems', function (schema, _fileName, options) { | ||
rules.set('Normalize schema.minItems', (schema, _fileName, options) => { | ||
if (options.ignoreMinAndMaxItems) { | ||
@@ -133,7 +124,7 @@ return; | ||
} | ||
var minItems = schema.minItems; | ||
const { minItems } = schema; | ||
schema.minItems = typeof minItems === 'number' ? minItems : 0; | ||
// cannot normalize maxItems because maxItems = 0 has an actual meaning | ||
}); | ||
rules.set('Remove maxItems if it is big enough to likely cause OOMs', function (schema, _fileName, options) { | ||
rules.set('Remove maxItems if it is big enough to likely cause OOMs', (schema, _fileName, options) => { | ||
if (options.ignoreMinAndMaxItems || options.maxItems === -1) { | ||
@@ -145,3 +136,3 @@ return; | ||
} | ||
var maxItems = schema.maxItems, minItems = schema.minItems; | ||
const { maxItems, minItems } = schema; | ||
// minItems is guaranteed to be a number after the previous rule runs | ||
@@ -152,13 +143,13 @@ if (maxItems !== undefined && maxItems - minItems > options.maxItems) { | ||
}); | ||
rules.set('Normalize schema.items', function (schema, _fileName, options) { | ||
rules.set('Normalize schema.items', (schema, _fileName, options) => { | ||
if (options.ignoreMinAndMaxItems) { | ||
return; | ||
} | ||
var maxItems = schema.maxItems, minItems = schema.minItems; | ||
var hasMaxItems = typeof maxItems === 'number' && maxItems >= 0; | ||
var hasMinItems = typeof minItems === 'number' && minItems > 0; | ||
const { maxItems, minItems } = schema; | ||
const hasMaxItems = typeof maxItems === 'number' && maxItems >= 0; | ||
const hasMinItems = typeof minItems === 'number' && minItems > 0; | ||
if (schema.items && !Array.isArray(schema.items) && (hasMaxItems || hasMinItems)) { | ||
var items = schema.items; | ||
const items = schema.items; | ||
// create a tuple of length N | ||
var newItems = Array(maxItems || minItems || 0).fill(items); | ||
const newItems = Array(maxItems || minItems || 0).fill(items); | ||
if (!hasMaxItems) { | ||
@@ -177,3 +168,3 @@ // if there is no maximum, then add a spread item to collect the rest | ||
}); | ||
rules.set('Remove extends, if it is empty', function (schema) { | ||
rules.set('Remove extends, if it is empty', schema => { | ||
if (!schema.hasOwnProperty('extends')) { | ||
@@ -186,3 +177,3 @@ return; | ||
}); | ||
rules.set('Make extends always an array, if it is defined', function (schema) { | ||
rules.set('Make extends always an array, if it is defined', schema => { | ||
if (schema.extends == null) { | ||
@@ -195,5 +186,5 @@ return; | ||
}); | ||
rules.set('Transform definitions to $defs', function (schema, fileName) { | ||
rules.set('Transform definitions to $defs', (schema, fileName) => { | ||
if (schema.definitions && schema.$defs && !(0, util_1.isDeepStrictEqual)(schema.definitions, schema.$defs)) { | ||
throw ReferenceError("Schema must define either definitions or $defs, not both. Given id=".concat(schema.id, " in ").concat(fileName)); | ||
throw ReferenceError(`Schema must define either definitions or $defs, not both. Given id=${schema.id} in ${fileName}`); | ||
} | ||
@@ -205,3 +196,3 @@ if (schema.definitions) { | ||
}); | ||
rules.set('Transform const to singleton enum', function (schema) { | ||
rules.set('Transform const to singleton enum', schema => { | ||
if (schema.const !== undefined) { | ||
@@ -213,3 +204,3 @@ schema.enum = [schema.const]; | ||
function normalize(rootSchema, dereferencedPaths, filename, options) { | ||
rules.forEach(function (rule) { return (0, utils_1.traverse)(rootSchema, function (schema, key) { return rule(schema, filename, options, key, dereferencedPaths); }); }); | ||
rules.forEach(rule => (0, utils_1.traverse)(rootSchema, (schema, key) => rule(schema, filename, options, key, dereferencedPaths))); | ||
return rootSchema; | ||
@@ -216,0 +207,0 @@ } |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.optimize = void 0; | ||
var lodash_1 = require("lodash"); | ||
var generator_1 = require("./generator"); | ||
var AST_1 = require("./types/AST"); | ||
var utils_1 = require("./utils"); | ||
function optimize(ast, options, processed) { | ||
if (processed === void 0) { processed = new Set(); } | ||
const lodash_1 = require("lodash"); | ||
const generator_1 = require("./generator"); | ||
const AST_1 = require("./types/AST"); | ||
const utils_1 = require("./utils"); | ||
function optimize(ast, options, processed = new Set()) { | ||
if (processed.has(ast)) { | ||
@@ -26,5 +14,9 @@ return ast; | ||
switch (ast.type) { | ||
case 'ARRAY': | ||
return Object.assign(ast, { | ||
params: optimize(ast.params, options, processed), | ||
}); | ||
case 'INTERFACE': | ||
return Object.assign(ast, { | ||
params: ast.params.map(function (_) { return Object.assign(_, { ast: optimize(_.ast, options, processed) }); }), | ||
params: ast.params.map(_ => Object.assign(_, { ast: optimize(_.ast, options, processed) })), | ||
}); | ||
@@ -34,33 +26,33 @@ case 'INTERSECTION': | ||
// Start with the leaves... | ||
var optimizedAST_1 = Object.assign(ast, { | ||
params: ast.params.map(function (_) { return optimize(_, options, processed); }), | ||
const optimizedAST = Object.assign(ast, { | ||
params: ast.params.map(_ => optimize(_, options, processed)), | ||
}); | ||
// [A, B, C, Any] -> Any | ||
if (optimizedAST_1.params.some(function (_) { return _.type === 'ANY'; })) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A, B, C, Any] -> Any', optimizedAST_1); | ||
if (optimizedAST.params.some(_ => _.type === 'ANY')) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A, B, C, Any] -> Any', optimizedAST); | ||
return AST_1.T_ANY; | ||
} | ||
// [A, B, C, Unknown] -> Unknown | ||
if (optimizedAST_1.params.some(function (_) { return _.type === 'UNKNOWN'; })) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A, B, C, Unknown] -> Unknown', optimizedAST_1); | ||
if (optimizedAST.params.some(_ => _.type === 'UNKNOWN')) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A, B, C, Unknown] -> Unknown', optimizedAST); | ||
return AST_1.T_UNKNOWN; | ||
} | ||
// [A (named), A] -> [A (named)] | ||
if (optimizedAST_1.params.every(function (_) { | ||
var a = (0, generator_1.generateType)(omitStandaloneName(_), options); | ||
var b = (0, generator_1.generateType)(omitStandaloneName(optimizedAST_1.params[0]), options); | ||
if (optimizedAST.params.every(_ => { | ||
const a = (0, generator_1.generateType)(omitStandaloneName(_), options); | ||
const b = (0, generator_1.generateType)(omitStandaloneName(optimizedAST.params[0]), options); | ||
return a === b; | ||
}) && | ||
optimizedAST_1.params.some(function (_) { return _.standaloneName !== undefined; })) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A (named), A] -> [A (named)]', optimizedAST_1); | ||
optimizedAST_1.params = optimizedAST_1.params.filter(function (_) { return _.standaloneName !== undefined; }); | ||
optimizedAST.params.some(_ => _.standaloneName !== undefined)) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A (named), A] -> [A (named)]', optimizedAST); | ||
optimizedAST.params = optimizedAST.params.filter(_ => _.standaloneName !== undefined); | ||
} | ||
// [A, B, B] -> [A, B] | ||
var params = (0, lodash_1.uniqBy)(optimizedAST_1.params, function (_) { return (0, generator_1.generateType)(_, options); }); | ||
if (params.length !== optimizedAST_1.params.length) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A, B, B] -> [A, B]', optimizedAST_1); | ||
optimizedAST_1.params = params; | ||
const params = (0, lodash_1.uniqBy)(optimizedAST.params, _ => (0, generator_1.generateType)(_, options)); | ||
if (params.length !== optimizedAST.params.length) { | ||
(0, utils_1.log)('cyan', 'optimizer', '[A, B, B] -> [A, B]', optimizedAST); | ||
optimizedAST.params = params; | ||
} | ||
return Object.assign(optimizedAST_1, { | ||
params: optimizedAST_1.params.map(function (_) { return optimize(_, options, processed); }), | ||
return Object.assign(optimizedAST, { | ||
params: optimizedAST.params.map(_ => optimize(_, options, processed)), | ||
}); | ||
@@ -78,5 +70,5 @@ default: | ||
default: | ||
return __assign(__assign({}, ast), { standaloneName: undefined }); | ||
return Object.assign(Object.assign({}, ast), { standaloneName: undefined }); | ||
} | ||
} | ||
//# sourceMappingURL=optimizer.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateOptions = void 0; | ||
function validateOptions(_a) { | ||
var maxItems = _a.maxItems; | ||
function validateOptions({ maxItems }) { | ||
if (maxItems !== undefined && maxItems < -1) { | ||
throw RangeError("Expected options.maxItems to be >= -1, but was given ".concat(maxItems, ".")); | ||
throw RangeError(`Expected options.maxItems to be >= -1, but was given ${maxItems}.`); | ||
} | ||
@@ -9,0 +8,0 @@ } |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.parse = void 0; | ||
var lodash_1 = require("lodash"); | ||
var util_1 = require("util"); | ||
var typesOfSchema_1 = require("./typesOfSchema"); | ||
var AST_1 = require("./types/AST"); | ||
var JSONSchema_1 = require("./types/JSONSchema"); | ||
var utils_1 = require("./utils"); | ||
function parse(schema, options, keyName, processed, usedNames) { | ||
if (processed === void 0) { processed = new Map(); } | ||
if (usedNames === void 0) { usedNames = new Set(); } | ||
const lodash_1 = require("lodash"); | ||
const util_1 = require("util"); | ||
const typesOfSchema_1 = require("./typesOfSchema"); | ||
const AST_1 = require("./types/AST"); | ||
const JSONSchema_1 = require("./types/JSONSchema"); | ||
const utils_1 = require("./utils"); | ||
function parse(schema, options, keyName, processed = new Map(), usedNames = new Set()) { | ||
if ((0, JSONSchema_1.isPrimitive)(schema)) { | ||
@@ -30,11 +17,11 @@ if ((0, JSONSchema_1.isBoolean)(schema)) { | ||
} | ||
var types = (0, typesOfSchema_1.typesOfSchema)(schema); | ||
const types = (0, typesOfSchema_1.typesOfSchema)(schema); | ||
if (types.length === 1) { | ||
var ast_1 = parseAsTypeWithCache(schema, types[0], options, keyName, processed, usedNames); | ||
(0, utils_1.log)('blue', 'parser', 'Types:', types, 'Input:', schema, 'Output:', ast_1); | ||
return ast_1; | ||
const ast = parseAsTypeWithCache(schema, types[0], options, keyName, processed, usedNames); | ||
(0, utils_1.log)('blue', 'parser', 'Types:', types, 'Input:', schema, 'Output:', ast); | ||
return ast; | ||
} | ||
// Be careful to first process the intersection before processing its params, | ||
// so that it gets first pick for standalone name. | ||
var ast = parseAsTypeWithCache({ | ||
const ast = parseAsTypeWithCache({ | ||
$id: schema.$id, | ||
@@ -45,7 +32,6 @@ allOf: [], | ||
}, 'ALL_OF', options, keyName, processed, usedNames); | ||
ast.params = types.map(function (type) { | ||
// We hoist description (for comment) and id/title (for standaloneName) | ||
// to the parent intersection type, so we remove it from the children. | ||
return parseAsTypeWithCache((0, utils_1.maybeStripNameHints)(schema), type, options, keyName, processed, usedNames); | ||
}); | ||
ast.params = types.map(type => | ||
// We hoist description (for comment) and id/title (for standaloneName) | ||
// to the parent intersection type, so we remove it from the children. | ||
parseAsTypeWithCache((0, utils_1.maybeStripNameHints)(schema), type, options, keyName, processed, usedNames)); | ||
(0, utils_1.log)('blue', 'parser', 'Types:', types, 'Input:', schema, 'Output:', ast); | ||
@@ -55,7 +41,5 @@ return ast; | ||
exports.parse = parse; | ||
function parseAsTypeWithCache(schema, type, options, keyName, processed, usedNames) { | ||
if (processed === void 0) { processed = new Map(); } | ||
if (usedNames === void 0) { usedNames = new Set(); } | ||
function parseAsTypeWithCache(schema, type, options, keyName, processed = new Map(), usedNames = new Set()) { | ||
// If we've seen this node before, return it. | ||
var cachedTypeMap = processed.get(schema); | ||
let cachedTypeMap = processed.get(schema); | ||
if (!cachedTypeMap) { | ||
@@ -65,3 +49,3 @@ cachedTypeMap = new Map(); | ||
} | ||
var cachedAST = cachedTypeMap.get(type); | ||
const cachedAST = cachedTypeMap.get(type); | ||
if (cachedAST) { | ||
@@ -73,3 +57,3 @@ return cachedAST; | ||
// TODO: Investigate alternative approaches (lazy-computing nodes, etc.) | ||
var ast = {}; | ||
const ast = {}; | ||
cachedTypeMap.set(type, ast); | ||
@@ -83,3 +67,3 @@ // Update the AST in place. This updates the `processed` cache, as well | ||
return { | ||
keyName: keyName, | ||
keyName, | ||
type: options.unknownAny ? 'UNKNOWN' : 'ANY', | ||
@@ -89,3 +73,3 @@ }; | ||
return { | ||
keyName: keyName, | ||
keyName, | ||
type: 'NEVER', | ||
@@ -96,3 +80,3 @@ }; | ||
return { | ||
keyName: keyName, | ||
keyName, | ||
params: schema, | ||
@@ -103,4 +87,4 @@ type: 'LITERAL', | ||
function parseNonLiteral(schema, type, options, keyName, processed, usedNames) { | ||
var definitions = getDefinitionsMemoized((0, JSONSchema_1.getRootSchema)(schema)); // TODO | ||
var keyNameFromDefinition = (0, lodash_1.findKey)(definitions, function (_) { return _ === schema; }); | ||
const definitions = getDefinitionsMemoized((0, JSONSchema_1.getRootSchema)(schema)); // TODO | ||
const keyNameFromDefinition = (0, lodash_1.findKey)(definitions, _ => _ === schema); | ||
switch (type) { | ||
@@ -111,9 +95,9 @@ case 'ALL_OF': | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: schema.allOf.map(function (_) { return parse(_, options, undefined, processed, usedNames); }), | ||
params: schema.allOf.map(_ => parse(_, options, undefined, processed, usedNames)), | ||
type: 'INTERSECTION', | ||
}; | ||
case 'ANY': | ||
return __assign(__assign({}, (options.unknownAny ? AST_1.T_UNKNOWN : AST_1.T_ANY)), { comment: schema.description, deprecated: schema.deprecated, keyName: keyName, standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames) }); | ||
return Object.assign(Object.assign({}, (options.unknownAny ? AST_1.T_UNKNOWN : AST_1.T_ANY)), { comment: schema.description, deprecated: schema.deprecated, keyName, standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames) }); | ||
case 'ANY_OF': | ||
@@ -123,5 +107,5 @@ return { | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: schema.anyOf.map(function (_) { return parse(_, options, undefined, processed, usedNames); }), | ||
params: schema.anyOf.map(_ => parse(_, options, undefined, processed, usedNames)), | ||
type: 'UNION', | ||
@@ -133,3 +117,3 @@ }; | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -142,3 +126,3 @@ type: 'BOOLEAN', | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
params: schema.tsType, | ||
@@ -152,8 +136,8 @@ standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition !== null && keyNameFromDefinition !== void 0 ? keyNameFromDefinition : keyName, usedNames), | ||
params: schema.enum.map(function (_, n) { return ({ | ||
params: schema.enum.map((_, n) => ({ | ||
ast: parseLiteral(_, undefined), | ||
keyName: schema.tsEnumNames[n], | ||
}); }), | ||
})), | ||
type: 'ENUM', | ||
@@ -167,3 +151,3 @@ }; | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -176,3 +160,3 @@ type: 'NEVER', | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -185,3 +169,3 @@ type: 'NULL', | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -193,3 +177,3 @@ type: 'NUMBER', | ||
comment: schema.description, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -203,5 +187,5 @@ type: 'OBJECT', | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: schema.oneOf.map(function (_) { return parse(_, options, undefined, processed, usedNames); }), | ||
params: schema.oneOf.map(_ => parse(_, options, undefined, processed, usedNames)), | ||
type: 'UNION', | ||
@@ -215,3 +199,3 @@ }; | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -223,12 +207,12 @@ type: 'STRING', | ||
// normalised to not be undefined | ||
var minItems_1 = schema.minItems; | ||
var maxItems_1 = schema.maxItems; | ||
var arrayType = { | ||
const minItems = schema.minItems; | ||
const maxItems = schema.maxItems; | ||
const arrayType = { | ||
comment: schema.description, | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
maxItems: maxItems_1, | ||
minItems: minItems_1, | ||
keyName, | ||
maxItems, | ||
minItems, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: schema.items.map(function (_) { return parse(_, options, undefined, processed, usedNames); }), | ||
params: schema.items.map(_ => parse(_, options, undefined, processed, usedNames)), | ||
type: 'TUPLE', | ||
@@ -248,5 +232,5 @@ }; | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: parse(schema.items, options, "{keyNameFromDefinition}Items", processed, usedNames), | ||
params: parse(schema.items, options, `{keyNameFromDefinition}Items`, processed, usedNames), | ||
type: 'ARRAY', | ||
@@ -259,6 +243,6 @@ }; | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: schema.type.map(function (type) { | ||
var member = __assign(__assign({}, (0, lodash_1.omit)(schema, '$id', 'description', 'title')), { type: type }); | ||
params: schema.type.map(type => { | ||
const member = Object.assign(Object.assign({}, (0, lodash_1.omit)(schema, '$id', 'description', 'title')), { type }); | ||
return parse((0, utils_1.maybeStripDefault)(member), options, undefined, processed, usedNames); | ||
@@ -272,5 +256,5 @@ }), | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
params: schema.enum.map(function (_) { return parseLiteral(_, undefined); }), | ||
params: schema.enum.map(_ => parseLiteral(_, undefined)), | ||
type: 'UNION', | ||
@@ -282,5 +266,5 @@ }; | ||
// normalised to not be undefined | ||
var minItems = schema.minItems; | ||
var maxItems = typeof schema.maxItems === 'number' ? schema.maxItems : -1; | ||
var params = options.unknownAny ? AST_1.T_UNKNOWN : AST_1.T_ANY; | ||
const minItems = schema.minItems; | ||
const maxItems = typeof schema.maxItems === 'number' ? schema.maxItems : -1; | ||
const params = options.unknownAny ? AST_1.T_UNKNOWN : AST_1.T_ANY; | ||
if (minItems > 0 || maxItems >= 0) { | ||
@@ -290,5 +274,5 @@ return { | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
maxItems: schema.maxItems, | ||
minItems: minItems, | ||
minItems, | ||
// create a tuple of length N | ||
@@ -305,4 +289,4 @@ params: Array(Math.max(maxItems, minItems) || 0).fill(params), | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
params: params, | ||
keyName, | ||
params, | ||
standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames), | ||
@@ -317,3 +301,3 @@ type: 'ARRAY', | ||
function standaloneName(schema, keyNameFromDefinition, usedNames) { | ||
var name = schema.title || schema.$id || keyNameFromDefinition; | ||
const name = schema.title || schema.$id || keyNameFromDefinition; | ||
if (name) { | ||
@@ -324,7 +308,7 @@ return (0, utils_1.generateName)(name, usedNames); | ||
function newInterface(schema, options, processed, usedNames, keyName, keyNameFromDefinition) { | ||
var name = standaloneName(schema, keyNameFromDefinition, usedNames); | ||
const name = standaloneName(schema, keyNameFromDefinition, usedNames); | ||
return { | ||
comment: schema.description, | ||
deprecated: schema.deprecated, | ||
keyName: keyName, | ||
keyName, | ||
params: parseSchema(schema, options, processed, usedNames, name), | ||
@@ -339,7 +323,7 @@ standaloneName: name, | ||
// TODO: Type it upstream | ||
var superTypes = schema.extends; | ||
const superTypes = schema.extends; | ||
if (!superTypes) { | ||
return []; | ||
} | ||
return superTypes.map(function (_) { return parse(_, options, undefined, processed, usedNames); }); | ||
return superTypes.map(_ => parse(_, options, undefined, processed, usedNames)); | ||
} | ||
@@ -350,3 +334,3 @@ /** | ||
function parseSchema(schema, options, processed, usedNames, parentSchemaName) { | ||
var asts = (0, lodash_1.map)(schema.properties, function (value, key) { return ({ | ||
let asts = (0, lodash_1.map)(schema.properties, (value, key) => ({ | ||
ast: parse(value, options, key, processed, usedNames), | ||
@@ -357,4 +341,4 @@ isPatternProperty: false, | ||
keyName: key, | ||
}); }); | ||
var singlePatternProperty = false; | ||
})); | ||
let singlePatternProperty = false; | ||
if (schema.patternProperties) { | ||
@@ -365,8 +349,9 @@ // partially support patternProperties. in the case that | ||
singlePatternProperty = !schema.additionalProperties && Object.keys(schema.patternProperties).length === 1; | ||
asts = asts.concat((0, lodash_1.map)(schema.patternProperties, function (value, key) { | ||
var ast = parse(value, options, key, processed, usedNames); | ||
var comment = "This interface was referenced by `".concat(parentSchemaName, "`'s JSON-Schema definition\nvia the `patternProperty` \"").concat(key.replace('*/', '*\\/'), "\"."); | ||
ast.comment = ast.comment ? "".concat(ast.comment, "\n\n").concat(comment) : comment; | ||
asts = asts.concat((0, lodash_1.map)(schema.patternProperties, (value, key) => { | ||
const ast = parse(value, options, key, processed, usedNames); | ||
const comment = `This interface was referenced by \`${parentSchemaName}\`'s JSON-Schema definition | ||
via the \`patternProperty\` "${key.replace('*/', '*\\/')}".`; | ||
ast.comment = ast.comment ? `${ast.comment}\n\n${comment}` : comment; | ||
return { | ||
ast: ast, | ||
ast, | ||
isPatternProperty: !singlePatternProperty, | ||
@@ -380,8 +365,9 @@ isRequired: singlePatternProperty || (0, lodash_1.includes)(schema.required || [], key), | ||
if (options.unreachableDefinitions) { | ||
asts = asts.concat((0, lodash_1.map)(schema.$defs, function (value, key) { | ||
var ast = parse(value, options, key, processed, usedNames); | ||
var comment = "This interface was referenced by `".concat(parentSchemaName, "`'s JSON-Schema\nvia the `definition` \"").concat(key, "\"."); | ||
ast.comment = ast.comment ? "".concat(ast.comment, "\n\n").concat(comment) : comment; | ||
asts = asts.concat((0, lodash_1.map)(schema.$defs, (value, key) => { | ||
const ast = parse(value, options, key, processed, usedNames); | ||
const comment = `This interface was referenced by \`${parentSchemaName}\`'s JSON-Schema | ||
via the \`definition\` "${key}".`; | ||
ast.comment = ast.comment ? `${ast.comment}\n\n${comment}` : comment; | ||
return { | ||
ast: ast, | ||
ast, | ||
isPatternProperty: false, | ||
@@ -422,5 +408,3 @@ isRequired: (0, lodash_1.includes)(schema.required || [], key), | ||
} | ||
function getDefinitions(schema, isSchema, processed) { | ||
if (isSchema === void 0) { isSchema = true; } | ||
if (processed === void 0) { processed = new Set(); } | ||
function getDefinitions(schema, isSchema = true, processed = new Set()) { | ||
if (processed.has(schema)) { | ||
@@ -431,10 +415,10 @@ return {}; | ||
if (Array.isArray(schema)) { | ||
return schema.reduce(function (prev, cur) { return (__assign(__assign({}, prev), getDefinitions(cur, false, processed))); }, {}); | ||
return schema.reduce((prev, cur) => (Object.assign(Object.assign({}, prev), getDefinitions(cur, false, processed))), {}); | ||
} | ||
if ((0, lodash_1.isPlainObject)(schema)) { | ||
return __assign(__assign({}, (isSchema && hasDefinitions(schema) ? schema.$defs : {})), Object.keys(schema).reduce(function (prev, cur) { return (__assign(__assign({}, prev), getDefinitions(schema[cur], false, processed))); }, {})); | ||
return Object.assign(Object.assign({}, (isSchema && hasDefinitions(schema) ? schema.$defs : {})), Object.keys(schema).reduce((prev, cur) => (Object.assign(Object.assign({}, prev), getDefinitions(schema[cur], false, processed))), {})); | ||
} | ||
return {}; | ||
} | ||
var getDefinitionsMemoized = (0, lodash_1.memoize)(getDefinitions); | ||
const getDefinitionsMemoized = (0, lodash_1.memoize)(getDefinitions); | ||
/** | ||
@@ -441,0 +425,0 @@ * TODO: Reduce rate of false positives |
@@ -1,7 +0,7 @@ | ||
import $RefParser = require('@bcherny/json-schema-ref-parser'); | ||
import { ParserOptions as $RefOptions } from '@apidevtools/json-schema-ref-parser'; | ||
import { JSONSchema } from './types/JSONSchema'; | ||
export type DereferencedPaths = WeakMap<$RefParser.JSONSchemaObject, string>; | ||
export type DereferencedPaths = WeakMap<JSONSchema, string>; | ||
export declare function dereference(schema: JSONSchema, { cwd, $refOptions }: { | ||
cwd: string; | ||
$refOptions: $RefParser.Options; | ||
$refOptions: $RefOptions; | ||
}): Promise<{ | ||
@@ -8,0 +8,0 @@ dereferencedPaths: DereferencedPaths; |
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
@@ -22,52 +11,15 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
}; | ||
var __generator = (this && this.__generator) || function (thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; | ||
} | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.dereference = void 0; | ||
var $RefParser = require("@bcherny/json-schema-ref-parser"); | ||
var utils_1 = require("./utils"); | ||
function dereference(schema, _a) { | ||
var cwd = _a.cwd, $refOptions = _a.$refOptions; | ||
return __awaiter(this, void 0, void 0, function () { | ||
var parser, dereferencedPaths, dereferencedSchema; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
(0, utils_1.log)('green', 'dereferencer', 'Dereferencing input schema:', cwd, schema); | ||
parser = new $RefParser(); | ||
dereferencedPaths = new WeakMap(); | ||
return [4 /*yield*/, parser.dereference(cwd, schema, __assign(__assign({}, $refOptions), { dereference: __assign(__assign({}, $refOptions.dereference), { onDereference: function ($ref, schema) { | ||
dereferencedPaths.set(schema, $ref); | ||
} }) }))]; | ||
case 1: | ||
dereferencedSchema = (_b.sent()) // TODO: fix types | ||
; | ||
return [2 /*return*/, { dereferencedPaths: dereferencedPaths, dereferencedSchema: dereferencedSchema }]; | ||
} | ||
}); | ||
const json_schema_ref_parser_1 = require("@apidevtools/json-schema-ref-parser"); | ||
const utils_1 = require("./utils"); | ||
function dereference(schema_1, _a) { | ||
return __awaiter(this, arguments, void 0, function* (schema, { cwd, $refOptions }) { | ||
(0, utils_1.log)('green', 'dereferencer', 'Dereferencing input schema:', cwd, schema); | ||
const parser = new json_schema_ref_parser_1.$RefParser(); | ||
const dereferencedPaths = new WeakMap(); | ||
const dereferencedSchema = (yield parser.dereference(cwd, schema, Object.assign(Object.assign({}, $refOptions), { dereference: Object.assign(Object.assign({}, $refOptions.dereference), { onDereference($ref, schema) { | ||
dereferencedPaths.set(schema, $ref); | ||
} }) }))); // TODO: fix types | ||
return { dereferencedPaths, dereferencedSchema }; | ||
}); | ||
@@ -74,0 +26,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isCompound = exports.isPrimitive = exports.isBoolean = exports.getRootSchema = exports.Parent = void 0; | ||
var lodash_1 = require("lodash"); | ||
const lodash_1 = require("lodash"); | ||
exports.Parent = Symbol('Parent'); | ||
exports.getRootSchema = (0, lodash_1.memoize)(function (schema) { | ||
var parent = schema[exports.Parent]; | ||
exports.getRootSchema = (0, lodash_1.memoize)((schema) => { | ||
const parent = schema[exports.Parent]; | ||
if (!parent) { | ||
@@ -9,0 +9,0 @@ return schema; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.typesOfSchema = void 0; | ||
var lodash_1 = require("lodash"); | ||
var JSONSchema_1 = require("./types/JSONSchema"); | ||
const lodash_1 = require("lodash"); | ||
const JSONSchema_1 = require("./types/JSONSchema"); | ||
/** | ||
@@ -20,5 +20,4 @@ * Duck types a JSONSchema schema or property to determine which kind of AST node to parse it into. | ||
// Collect matched types | ||
var matchedTypes = []; | ||
for (var _i = 0, _a = Object.entries(matchers); _i < _a.length; _i++) { | ||
var _b = _a[_i], schemaType = _b[0], f = _b[1]; | ||
const matchedTypes = []; | ||
for (const [schemaType, f] of Object.entries(matchers)) { | ||
if (f(schema)) { | ||
@@ -35,7 +34,7 @@ matchedTypes.push(schemaType); | ||
exports.typesOfSchema = typesOfSchema; | ||
var matchers = { | ||
ALL_OF: function (schema) { | ||
const matchers = { | ||
ALL_OF(schema) { | ||
return 'allOf' in schema; | ||
}, | ||
ANY: function (schema) { | ||
ANY(schema) { | ||
if (Object.keys(schema).length === 0) { | ||
@@ -48,6 +47,6 @@ // The empty schema {} validates any value | ||
}, | ||
ANY_OF: function (schema) { | ||
ANY_OF(schema) { | ||
return 'anyOf' in schema; | ||
}, | ||
BOOLEAN: function (schema) { | ||
BOOLEAN(schema) { | ||
if ('enum' in schema) { | ||
@@ -64,19 +63,19 @@ return false; | ||
}, | ||
CUSTOM_TYPE: function () { | ||
CUSTOM_TYPE() { | ||
return false; // Explicitly handled before we try to match | ||
}, | ||
NAMED_ENUM: function (schema) { | ||
NAMED_ENUM(schema) { | ||
return 'enum' in schema && 'tsEnumNames' in schema; | ||
}, | ||
NAMED_SCHEMA: function (schema) { | ||
NAMED_SCHEMA(schema) { | ||
// 8.2.1. The presence of "$id" in a subschema indicates that the subschema constitutes a distinct schema resource within a single schema document. | ||
return '$id' in schema && ('patternProperties' in schema || 'properties' in schema); | ||
}, | ||
NEVER: function (schema) { | ||
NEVER(schema) { | ||
return schema === false; | ||
}, | ||
NULL: function (schema) { | ||
NULL(schema) { | ||
return schema.type === 'null'; | ||
}, | ||
NUMBER: function (schema) { | ||
NUMBER(schema) { | ||
if ('enum' in schema) { | ||
@@ -93,3 +92,3 @@ return false; | ||
}, | ||
OBJECT: function (schema) { | ||
OBJECT(schema) { | ||
return (schema.type === 'object' && | ||
@@ -104,9 +103,9 @@ !(0, lodash_1.isPlainObject)(schema.additionalProperties) && | ||
}, | ||
ONE_OF: function (schema) { | ||
ONE_OF(schema) { | ||
return 'oneOf' in schema; | ||
}, | ||
REFERENCE: function (schema) { | ||
REFERENCE(schema) { | ||
return '$ref' in schema; | ||
}, | ||
STRING: function (schema) { | ||
STRING(schema) { | ||
if ('enum' in schema) { | ||
@@ -123,3 +122,3 @@ return false; | ||
}, | ||
TYPED_ARRAY: function (schema) { | ||
TYPED_ARRAY(schema) { | ||
if (schema.type && schema.type !== 'array') { | ||
@@ -130,6 +129,6 @@ return false; | ||
}, | ||
UNION: function (schema) { | ||
UNION(schema) { | ||
return Array.isArray(schema.type); | ||
}, | ||
UNNAMED_ENUM: function (schema) { | ||
UNNAMED_ENUM(schema) { | ||
if ('tsEnumNames' in schema) { | ||
@@ -147,6 +146,6 @@ return false; | ||
}, | ||
UNNAMED_SCHEMA: function () { | ||
UNNAMED_SCHEMA() { | ||
return false; // Explicitly handled as the default case | ||
}, | ||
UNTYPED_ARRAY: function (schema) { | ||
UNTYPED_ARRAY(schema) { | ||
return schema.type === 'array' && !('items' in schema); | ||
@@ -153,0 +152,0 @@ }, |
"use strict"; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isSchemaLike = exports.appendToDescription = exports.maybeStripNameHints = exports.maybeStripDefault = exports.pathTransform = exports.escapeBlockComment = exports.log = exports.error = exports.generateName = exports.toSafeString = exports.stripExtension = exports.justName = exports.traverse = exports.Try = void 0; | ||
var lodash_1 = require("lodash"); | ||
var path_1 = require("path"); | ||
var JSONSchema_1 = require("./types/JSONSchema"); | ||
const lodash_1 = require("lodash"); | ||
const path_1 = require("path"); | ||
const JSONSchema_1 = require("./types/JSONSchema"); | ||
// TODO: pull out into a separate package | ||
@@ -27,3 +18,3 @@ function Try(fn, err) { | ||
// keys that shouldn't be traversed by the catchall step | ||
var BLACKLISTED_KEYS = new Set([ | ||
const BLACKLISTED_KEYS = new Set([ | ||
'id', | ||
@@ -65,3 +56,3 @@ '$defs', | ||
function traverseObjectKeys(obj, callback, processed) { | ||
Object.keys(obj).forEach(function (k) { | ||
Object.keys(obj).forEach(k => { | ||
if (obj[k] && typeof obj[k] === 'object' && !Array.isArray(obj[k])) { | ||
@@ -73,6 +64,5 @@ traverse(obj[k], callback, processed, k); | ||
function traverseArray(arr, callback, processed) { | ||
arr.forEach(function (s, k) { return traverse(s, callback, processed, k.toString()); }); | ||
arr.forEach((s, k) => traverse(s, callback, processed, k.toString())); | ||
} | ||
function traverse(schema, callback, processed, key) { | ||
if (processed === void 0) { processed = new Set(); } | ||
function traverse(schema, callback, processed = new Set(), key) { | ||
// Handle recursive schemas | ||
@@ -103,3 +93,3 @@ if (processed.has(schema)) { | ||
if (schema.items) { | ||
var items = schema.items; | ||
const { items } = schema; | ||
if (Array.isArray(items)) { | ||
@@ -134,5 +124,5 @@ traverseArray(items, callback, processed); | ||
Object.keys(schema) | ||
.filter(function (key) { return !BLACKLISTED_KEYS.has(key); }) | ||
.forEach(function (key) { | ||
var child = schema[key]; | ||
.filter(key => !BLACKLISTED_KEYS.has(key)) | ||
.forEach(key => { | ||
const child = schema[key]; | ||
if (child && typeof child === 'object') { | ||
@@ -147,4 +137,3 @@ traverseObjectKeys(child, callback, processed); | ||
*/ | ||
function justName(filename) { | ||
if (filename === void 0) { filename = ''; } | ||
function justName(filename = '') { | ||
return stripExtension((0, path_1.basename)(filename)); | ||
@@ -174,9 +163,9 @@ } | ||
// uppercase leading underscores followed by lowercase | ||
.replace(/^_[a-z]/g, function (match) { return match.toUpperCase(); }) | ||
.replace(/^_[a-z]/g, match => match.toUpperCase()) | ||
// remove non-leading underscores followed by lowercase (convert snake_case) | ||
.replace(/_[a-z]/g, function (match) { return match.substr(1, match.length).toUpperCase(); }) | ||
.replace(/_[a-z]/g, match => match.substr(1, match.length).toUpperCase()) | ||
// uppercase letters after digits, dollars | ||
.replace(/([\d$]+[a-zA-Z])/g, function (match) { return match.toUpperCase(); }) | ||
.replace(/([\d$]+[a-zA-Z])/g, match => match.toUpperCase()) | ||
// uppercase first letter after whitespace | ||
.replace(/\s+([a-zA-Z])/g, function (match) { return (0, lodash_1.trim)(match.toUpperCase()); }) | ||
.replace(/\s+([a-zA-Z])/g, match => (0, lodash_1.trim)(match.toUpperCase())) | ||
// remove remaining whitespace | ||
@@ -187,3 +176,3 @@ .replace(/\s/g, '')); | ||
function generateName(from, usedNames) { | ||
var name = toSafeString(from); | ||
let name = toSafeString(from); | ||
if (!name) { | ||
@@ -194,6 +183,6 @@ name = 'NoName'; | ||
if (usedNames.has(name)) { | ||
var counter = 1; | ||
var nameWithCounter = "".concat(name).concat(counter); | ||
let counter = 1; | ||
let nameWithCounter = `${name}${counter}`; | ||
while (usedNames.has(nameWithCounter)) { | ||
nameWithCounter = "".concat(name).concat(counter); | ||
nameWithCounter = `${name}${counter}`; | ||
counter++; | ||
@@ -207,28 +196,20 @@ } | ||
exports.generateName = generateName; | ||
function error() { | ||
function error(...messages) { | ||
var _a; | ||
var messages = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
messages[_i] = arguments[_i]; | ||
} | ||
if (!process.env.VERBOSE) { | ||
return console.error(messages); | ||
} | ||
console.error.apply(console, __spreadArray([(_a = getStyledTextForLogging('red')) === null || _a === void 0 ? void 0 : _a('error')], messages, false)); | ||
console.error((_a = getStyledTextForLogging('red')) === null || _a === void 0 ? void 0 : _a('error'), ...messages); | ||
} | ||
exports.error = error; | ||
function log(style, title) { | ||
function log(style, title, ...messages) { | ||
var _a; | ||
var messages = []; | ||
for (var _i = 2; _i < arguments.length; _i++) { | ||
messages[_i - 2] = arguments[_i]; | ||
} | ||
if (!process.env.VERBOSE) { | ||
return; | ||
} | ||
var lastMessage = null; | ||
let lastMessage = null; | ||
if (messages.length > 1 && typeof messages[messages.length - 1] !== 'string') { | ||
lastMessage = messages.splice(messages.length - 1, 1); | ||
} | ||
console.info.apply(console, __spreadArray([require('cli-color').whiteBright.bgCyan('debug'), (_a = getStyledTextForLogging(style)) === null || _a === void 0 ? void 0 : _a(title)], messages, false)); | ||
console.info(require('cli-color').whiteBright.bgCyan('debug'), (_a = getStyledTextForLogging(style)) === null || _a === void 0 ? void 0 : _a(title), ...messages); | ||
if (lastMessage) { | ||
@@ -264,8 +245,7 @@ console.dir(lastMessage, { depth: 6, maxArrayLength: 6 }); | ||
function escapeBlockComment(schema) { | ||
var replacer = '* /'; | ||
const replacer = '* /'; | ||
if (schema === null || typeof schema !== 'object') { | ||
return; | ||
} | ||
for (var _i = 0, _a = Object.keys(schema); _i < _a.length; _i++) { | ||
var key = _a[_i]; | ||
for (const key of Object.keys(schema)) { | ||
if (key === 'description' && typeof schema[key] === 'string') { | ||
@@ -289,6 +269,6 @@ schema[key] = schema[key].replace(/\*\//g, replacer); | ||
function pathTransform(outputPath, inputPath, filePath) { | ||
var inPathList = (0, path_1.normalize)(inputPath).split(path_1.sep); | ||
var filePathList = (0, path_1.dirname)((0, path_1.normalize)(filePath)).split(path_1.sep); | ||
var filePathRel = filePathList.filter(function (f, i) { return f !== inPathList[i]; }); | ||
return path_1.posix.join.apply(path_1.posix, __spreadArray([path_1.posix.normalize(outputPath)], filePathRel, false)); | ||
const inPathList = (0, path_1.normalize)(inputPath).split(path_1.sep); | ||
const filePathList = (0, path_1.dirname)((0, path_1.normalize)(filePath)).split(path_1.sep); | ||
const filePathRel = filePathList.filter((f, i) => f !== inPathList[i]); | ||
return path_1.posix.join(path_1.posix.normalize(outputPath), ...filePathRel); | ||
} | ||
@@ -363,9 +343,5 @@ exports.pathTransform = pathTransform; | ||
exports.maybeStripNameHints = maybeStripNameHints; | ||
function appendToDescription(existingDescription) { | ||
var values = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
values[_i - 1] = arguments[_i]; | ||
} | ||
function appendToDescription(existingDescription, ...values) { | ||
if (existingDescription) { | ||
return "".concat(existingDescription, "\n\n").concat(values.join('\n')); | ||
return `${existingDescription}\n\n${values.join('\n')}`; | ||
} | ||
@@ -379,7 +355,7 @@ return values.join('\n'); | ||
} | ||
var parent = schema[JSONSchema_1.Parent]; | ||
const parent = schema[JSONSchema_1.Parent]; | ||
if (parent === null) { | ||
return true; | ||
} | ||
var JSON_SCHEMA_KEYWORDS = [ | ||
const JSON_SCHEMA_KEYWORDS = [ | ||
'$defs', | ||
@@ -397,3 +373,3 @@ 'allOf', | ||
]; | ||
if (JSON_SCHEMA_KEYWORDS.some(function (_) { return parent[_] === schema; })) { | ||
if (JSON_SCHEMA_KEYWORDS.some(_ => parent[_] === schema)) { | ||
return false; | ||
@@ -400,0 +376,0 @@ } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validate = void 0; | ||
var utils_1 = require("./utils"); | ||
var rules = new Map(); | ||
rules.set('Enum members and tsEnumNames must be of the same length', function (schema) { | ||
const utils_1 = require("./utils"); | ||
const rules = new Map(); | ||
rules.set('Enum members and tsEnumNames must be of the same length', schema => { | ||
if (schema.enum && schema.tsEnumNames && schema.enum.length !== schema.tsEnumNames.length) { | ||
@@ -11,9 +11,9 @@ return false; | ||
}); | ||
rules.set('tsEnumNames must be an array of strings', function (schema) { | ||
if (schema.tsEnumNames && schema.tsEnumNames.some(function (_) { return typeof _ !== 'string'; })) { | ||
rules.set('tsEnumNames must be an array of strings', schema => { | ||
if (schema.tsEnumNames && schema.tsEnumNames.some(_ => typeof _ !== 'string')) { | ||
return false; | ||
} | ||
}); | ||
rules.set('When both maxItems and minItems are present, maxItems >= minItems', function (schema) { | ||
var maxItems = schema.maxItems, minItems = schema.minItems; | ||
rules.set('When both maxItems and minItems are present, maxItems >= minItems', schema => { | ||
const { maxItems, minItems } = schema; | ||
if (typeof maxItems === 'number' && typeof minItems === 'number') { | ||
@@ -23,4 +23,4 @@ return maxItems >= minItems; | ||
}); | ||
rules.set('When maxItems exists, maxItems >= 0', function (schema) { | ||
var maxItems = schema.maxItems; | ||
rules.set('When maxItems exists, maxItems >= 0', schema => { | ||
const { maxItems } = schema; | ||
if (typeof maxItems === 'number') { | ||
@@ -30,4 +30,4 @@ return maxItems >= 0; | ||
}); | ||
rules.set('When minItems exists, minItems >= 0', function (schema) { | ||
var minItems = schema.minItems; | ||
rules.set('When minItems exists, minItems >= 0', schema => { | ||
const { minItems } = schema; | ||
if (typeof minItems === 'number') { | ||
@@ -37,12 +37,12 @@ return minItems >= 0; | ||
}); | ||
rules.set('deprecated must be a boolean', function (schema) { | ||
var typeOfDeprecated = typeof schema.deprecated; | ||
rules.set('deprecated must be a boolean', schema => { | ||
const typeOfDeprecated = typeof schema.deprecated; | ||
return typeOfDeprecated === 'boolean' || typeOfDeprecated === 'undefined'; | ||
}); | ||
function validate(schema, filename) { | ||
var errors = []; | ||
rules.forEach(function (rule, ruleName) { | ||
(0, utils_1.traverse)(schema, function (schema, key) { | ||
const errors = []; | ||
rules.forEach((rule, ruleName) => { | ||
(0, utils_1.traverse)(schema, (schema, key) => { | ||
if (rule(schema) === false) { | ||
errors.push("Error at key \"".concat(key, "\" in file \"").concat(filename, "\": ").concat(ruleName)); | ||
errors.push(`Error at key "${key}" in file "${filename}": ${ruleName}`); | ||
} | ||
@@ -49,0 +49,0 @@ return schema; |
{ | ||
"name": "json-schema-to-typescript", | ||
"version": "13.1.2", | ||
"version": "14.0.0", | ||
"description": "compile json schema to typescript typings", | ||
@@ -11,3 +11,3 @@ "main": "dist/src/index.js", | ||
"engines": { | ||
"node": ">=12.0.0" | ||
"node": ">=16.0.0" | ||
}, | ||
@@ -52,39 +52,40 @@ "scripts": { | ||
"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", | ||
"@apidevtools/json-schema-ref-parser": "^11.5.5", | ||
"@types/json-schema": "^7.0.15", | ||
"@types/lodash": "^4.17.0", | ||
"@types/prettier": "^3.0.0", | ||
"cli-color": "^2.0.4", | ||
"glob": "^10.3.12", | ||
"is-glob": "^4.0.3", | ||
"js-yaml": "^4.1.0", | ||
"lodash": "^4.17.21", | ||
"minimist": "^1.2.6", | ||
"mkdirp": "^1.0.4", | ||
"minimist": "^1.2.8", | ||
"mkdirp": "^3.0.1", | ||
"mz": "^2.7.0", | ||
"prettier": "^2.6.2" | ||
"node-fetch": "^3.3.2", | ||
"prettier": "^3.2.5" | ||
}, | ||
"devDependencies": { | ||
"@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/mz": "^2.7.4", | ||
"@types/node": "^17.0.33", | ||
"@types/rimraf": "^3.0.2", | ||
"@typescript-eslint/eslint-plugin": "^5.23.0", | ||
"@typescript-eslint/parser": "^5.23.0", | ||
"ava": "^4.2.0", | ||
"@types/cli-color": "^2.0.6", | ||
"@types/glob": "^8.1.0", | ||
"@types/is-glob": "^4.0.4", | ||
"@types/js-yaml": "^4.0.9", | ||
"@types/minimist": "^1.2.5", | ||
"@types/mkdirp": "^2.0.0", | ||
"@types/mz": "^2.7.8", | ||
"@types/node": "^20.12.7", | ||
"@types/rimraf": "^4.0.5", | ||
"@typescript-eslint/eslint-plugin": "^7.7.0", | ||
"@typescript-eslint/parser": "^7.7.0", | ||
"ava": "^6.1.2", | ||
"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", | ||
"browserify-shim": "^3.8.16", | ||
"concurrently": "^8.2.2", | ||
"eslint": "^9.1.0", | ||
"eslint-config-prettier": "^9.1.0", | ||
"eslint-plugin-prettier": "^5.1.3", | ||
"rimraf": "^5.0.5", | ||
"shx": "^0.3.4", | ||
"tsify": "^5.0.4", | ||
"typescript": "^4.6.4" | ||
"typescript": "^5.4.5" | ||
}, | ||
@@ -95,5 +96,2 @@ "ava": { | ||
], | ||
"ignoredByWatcher": [ | ||
"./src" | ||
], | ||
"snapshotDir": "./test/__snapshots__" | ||
@@ -100,0 +98,0 @@ }, |
@@ -98,3 +98,3 @@ # json-schema-to-typescript [![Build Status][build]](https://github.com/bcherny/json-schema-to-typescript/actions?query=branch%3Amaster+workflow%3ACI) [![npm]](https://www.npmjs.com/package/json-schema-to-typescript) [![mit]](https://opensource.org/licenses/MIT) | ||
| unreachableDefinitions | boolean | `false` | Generates code for `$defs` that aren't referenced by the schema. | | ||
| $refOptions | object | `{}` | [$RefParser](https://github.com/BigstickCarpet/json-schema-ref-parser) Options, used when resolving `$ref`s | | ||
| $refOptions | object | `{}` | [$RefParser](https://github.com/APIDevTools/json-schema-ref-parser) Options, used when resolving `$ref`s | | ||
## CLI | ||
@@ -101,0 +101,0 @@ |
#!/usr/bin/env node | ||
import minimist = require('minimist') | ||
import getStdin from 'get-stdin' | ||
import {readFile, writeFile, existsSync, lstatSync, readdirSync} from 'mz/fs' | ||
import * as mkdirp from 'mkdirp' | ||
import glob from 'glob-promise' | ||
import {glob} from 'glob' | ||
import isGlob = require('is-glob') | ||
@@ -144,5 +143,5 @@ import {join, resolve, dirname, basename} from 'path' | ||
function readInput(argIn?: string) { | ||
async function readInput(argIn?: string): Promise<string> { | ||
if (!argIn) { | ||
return getStdin() | ||
return readStream(process.stdin) | ||
} | ||
@@ -152,2 +151,8 @@ return readFile(resolve(process.cwd(), argIn), 'utf-8') | ||
async function readStream(stream: NodeJS.ReadStream): Promise<string> { | ||
const chunks = [] | ||
for await (const chunk of stream) chunks.push(chunk) | ||
return Buffer.concat(chunks).toString('utf8') | ||
} | ||
function printHelp() { | ||
@@ -154,0 +159,0 @@ const pkg = require('../../package.json') |
import {format as prettify} from 'prettier' | ||
import {Options} from './' | ||
export function format(code: string, options: Options): string { | ||
export async function format(code: string, options: Options): Promise<string> { | ||
if (!options.format) { | ||
@@ -6,0 +6,0 @@ return code |
import {readFileSync} from 'fs' | ||
import {JSONSchema4} from 'json-schema' | ||
import {Options as $RefOptions} from '@bcherny/json-schema-ref-parser' | ||
import {ParserOptions as $RefOptions} from '@apidevtools/json-schema-ref-parser' | ||
import {cloneDeep, endsWith, merge} from 'lodash' | ||
@@ -23,3 +23,3 @@ import {dirname} from 'path' | ||
/** | ||
* [$RefParser](https://github.com/BigstickCarpet/json-schema-ref-parser) Options, used when resolving `$ref`s | ||
* [$RefParser](https://github.com/APIDevTools/json-schema-ref-parser) Options, used when resolving `$ref`s | ||
*/ | ||
@@ -180,3 +180,3 @@ $refOptions: $RefOptions | ||
const formatted = format(generated, _options) | ||
const formatted = await format(generated, _options) | ||
log('white', 'formatter', time(), '✅ Result:', formatted) | ||
@@ -183,0 +183,0 @@ |
@@ -15,2 +15,6 @@ import {uniqBy} from 'lodash' | ||
switch (ast.type) { | ||
case 'ARRAY': | ||
return Object.assign(ast, { | ||
params: optimize(ast.params, options, processed), | ||
}) | ||
case 'INTERFACE': | ||
@@ -17,0 +21,0 @@ return Object.assign(ast, { |
@@ -1,10 +0,10 @@ | ||
import $RefParser = require('@bcherny/json-schema-ref-parser') | ||
import {$RefParser, ParserOptions as $RefOptions} from '@apidevtools/json-schema-ref-parser' | ||
import {JSONSchema} from './types/JSONSchema' | ||
import {log} from './utils' | ||
export type DereferencedPaths = WeakMap<$RefParser.JSONSchemaObject, string> | ||
export type DereferencedPaths = WeakMap<JSONSchema, string> | ||
export async function dereference( | ||
schema: JSONSchema, | ||
{cwd, $refOptions}: {cwd: string; $refOptions: $RefParser.Options}, | ||
{cwd, $refOptions}: {cwd: string; $refOptions: $RefOptions}, | ||
): Promise<{dereferencedPaths: DereferencedPaths; dereferencedSchema: JSONSchema}> { | ||
@@ -14,7 +14,7 @@ log('green', 'dereferencer', 'Dereferencing input schema:', cwd, schema) | ||
const dereferencedPaths: DereferencedPaths = new WeakMap() | ||
const dereferencedSchema = (await parser.dereference(cwd, schema as any, { | ||
const dereferencedSchema = (await parser.dereference(cwd, schema, { | ||
...$refOptions, | ||
dereference: { | ||
...$refOptions.dereference, | ||
onDereference($ref, schema) { | ||
onDereference($ref: string, schema: JSONSchema) { | ||
dereferencedPaths.set(schema, $ref) | ||
@@ -21,0 +21,0 @@ }, |
@@ -6,3 +6,4 @@ { | ||
"lib": [ | ||
"es2015" | ||
"DOM", | ||
"es2015", | ||
], | ||
@@ -16,5 +17,6 @@ "module": "commonjs", | ||
"preserveConstEnums": true, | ||
"skipLibCheck": true, | ||
"sourceMap": true, | ||
"strict": true, | ||
"target": "es5" | ||
"target": "es6" | ||
}, | ||
@@ -21,0 +23,0 @@ "exclude": [ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
7
2358970
22
13522
+ Addedjs-yaml@^4.1.0
+ Addednode-fetch@^3.3.2
+ Added@apidevtools/json-schema-ref-parser@11.7.0(transitive)
+ Added@isaacs/cliui@8.0.2(transitive)
+ Added@pkgjs/parseargs@0.11.0(transitive)
+ Added@types/prettier@3.0.0(transitive)
+ Addedansi-regex@5.0.16.1.0(transitive)
+ Addedansi-styles@4.3.06.2.1(transitive)
+ Addedbrace-expansion@2.0.1(transitive)
+ Addedcolor-convert@2.0.1(transitive)
+ Addedcolor-name@1.1.4(transitive)
+ Addedcross-spawn@7.0.3(transitive)
+ Addeddata-uri-to-buffer@4.0.1(transitive)
+ Addedeastasianwidth@0.2.0(transitive)
+ Addedemoji-regex@8.0.09.2.2(transitive)
+ Addedfetch-blob@3.2.0(transitive)
+ Addedforeground-child@3.3.0(transitive)
+ Addedformdata-polyfill@4.0.10(transitive)
+ Addedglob@10.4.5(transitive)
+ Addedis-fullwidth-code-point@3.0.0(transitive)
+ Addedisexe@2.0.0(transitive)
+ Addedjackspeak@3.4.3(transitive)
+ Addedlru-cache@10.4.3(transitive)
+ Addedminimatch@9.0.5(transitive)
+ Addedminipass@7.1.2(transitive)
+ Addedmkdirp@3.0.1(transitive)
+ Addednode-domexception@1.0.0(transitive)
+ Addednode-fetch@3.3.2(transitive)
+ Addedpackage-json-from-dist@1.0.1(transitive)
+ Addedpath-key@3.1.1(transitive)
+ Addedpath-scurry@1.11.1(transitive)
+ Addedprettier@3.3.3(transitive)
+ Addedshebang-command@2.0.0(transitive)
+ Addedshebang-regex@3.0.0(transitive)
+ Addedsignal-exit@4.1.0(transitive)
+ Addedstring-width@4.2.35.1.2(transitive)
+ Addedstrip-ansi@6.0.17.1.0(transitive)
+ Addedweb-streams-polyfill@3.3.3(transitive)
+ Addedwhich@2.0.2(transitive)
+ Addedwrap-ansi@7.0.08.1.0(transitive)
- Removedget-stdin@^8.0.0
- Removedglob-promise@^4.2.2
- Removed@bcherny/json-schema-ref-parser@10.0.5-fork(transitive)
- Removed@types/glob@7.2.0(transitive)
- Removed@types/minimatch@5.1.2(transitive)
- Removed@types/node@22.7.5(transitive)
- Removed@types/prettier@2.7.3(transitive)
- Removedbrace-expansion@1.1.11(transitive)
- Removedcall-me-maybe@1.0.2(transitive)
- Removedconcat-map@0.0.1(transitive)
- Removedfs.realpath@1.0.0(transitive)
- Removedget-stdin@8.0.0(transitive)
- Removedglob@7.2.3(transitive)
- Removedglob-promise@4.2.2(transitive)
- Removedinflight@1.0.6(transitive)
- Removedinherits@2.0.4(transitive)
- Removedminimatch@3.1.2(transitive)
- Removedmkdirp@1.0.4(transitive)
- Removedonce@1.4.0(transitive)
- Removedpath-is-absolute@1.0.1(transitive)
- Removedprettier@2.8.8(transitive)
- Removedundici-types@6.19.8(transitive)
- Removedwrappy@1.0.2(transitive)
Updated@types/json-schema@^7.0.15
Updated@types/lodash@^4.17.0
Updated@types/prettier@^3.0.0
Updatedcli-color@^2.0.4
Updatedglob@^10.3.12
Updatedminimist@^1.2.8
Updatedmkdirp@^3.0.1
Updatedprettier@^3.2.5