dtsgenerator
Version:
TypeScript d.ts file generator for JSON Schema file
91 lines (90 loc) • 2.96 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeSchema = exports.checkValidMIMEType = exports.reduceTypes = exports.toTSType = void 0;
const tslib_1 = require("tslib");
const debug_1 = tslib_1.__importDefault(require("debug"));
const ts = tslib_1.__importStar(require("typescript"));
const debug = (0, debug_1.default)('dtsgen');
function toTSType(type, debugSource) {
switch (type) {
case 'any':
return ts.SyntaxKind.AnyKeyword;
case 'boolean':
return ts.SyntaxKind.BooleanKeyword;
case 'integer':
return ts.SyntaxKind.NumberKeyword;
case 'null':
return ts.SyntaxKind.NullKeyword;
case 'number':
return ts.SyntaxKind.NumberKeyword;
case 'string':
return ts.SyntaxKind.StringKeyword;
case 'undefined':
return ts.SyntaxKind.UndefinedKeyword;
case 'object':
case 'array':
return undefined;
case 'file':
return ts.SyntaxKind.UnknownKeyword;
default:
if (debugSource) {
debug(`toTSType: unknown type: ${JSON.stringify(debugSource, null, 2)}`);
}
throw new Error('unknown type: ' + type);
}
}
exports.toTSType = toTSType;
function reduceTypes(types) {
if (types.length < 2) {
return types;
}
const set = new Set(types);
return Array.from(set.values());
}
exports.reduceTypes = reduceTypes;
function checkValidMIMEType(mime) {
var _a;
const type = (_a = mime.toLowerCase().split(';')[0]) === null || _a === void 0 ? void 0 : _a.trim();
if (type == null) {
return false;
}
if ([
'application/octet-stream',
'application/x-www-form-urlencoded',
'multipart/form-data',
'application/jwt',
'application/vnd.apple.pkpass',
].includes(type)) {
return true;
}
if (type.startsWith('text/') || type.startsWith('image/')) {
return true;
}
return /^application\/(?:[a-z0-9-_.]+\+)?json5?$/.test(type);
}
exports.checkValidMIMEType = checkValidMIMEType;
function mergeSchema(a, b) {
if ('$ref' in a || '$ref' in b) {
a.$ref = b.$ref || a.$ref;
return false;
}
Object.keys(b).forEach((key) => {
var _a, _b;
const value = b[key];
if (a[key] != null && typeof value !== typeof a[key]) {
debug(`mergeSchema warning: type is mismatched, key=${key}`);
}
if (Array.isArray(value)) {
a[key] = ((_a = a[key]) !== null && _a !== void 0 ? _a : []).concat(value);
}
else if (value != null && typeof value === 'object') {
(_b = a[key]) !== null && _b !== void 0 ? _b : (a[key] = {});
mergeSchema(a[key], value);
}
else {
a[key] = value;
}
});
return true;
}
exports.mergeSchema = mergeSchema;
;