@jsonjoy.com/json-type
Version:
High-performance JSON Pointer implementation
131 lines (130 loc) • 4.27 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toJtdForm = toJtdForm;
const NUMS_TYPE_MAPPING = new Map([
['u8', 'uint8'],
['u16', 'uint16'],
['u32', 'uint32'],
['i8', 'int8'],
['i16', 'int16'],
['i32', 'int32'],
['f32', 'float32'],
]);
/**
* Main router function that converts any Schema to JTD form.
* Uses a switch statement to route to the appropriate converter logic.
*/
function toJtdForm(schema) {
const typeName = schema.kind;
switch (typeName) {
case 'any': {
const form = { nullable: true };
return form;
}
case 'bool': {
const form = { type: 'boolean' };
return form;
}
case 'con': {
const constSchema = schema;
const value = constSchema.value;
const valueType = typeof value;
switch (valueType) {
case 'boolean':
case 'string':
return { type: valueType };
case 'number': {
if (value !== Math.round(value))
return { type: 'float64' };
if (value >= 0) {
if (value <= 255)
return { type: 'uint8' };
if (value <= 65535)
return { type: 'uint16' };
if (value <= 4294967295)
return { type: 'uint32' };
}
else {
if (value >= -128)
return { type: 'int8' };
if (value >= -32768)
return { type: 'int16' };
if (value >= -2147483648)
return { type: 'int32' };
}
return { type: 'float64' };
}
}
const form = { nullable: false };
return form;
}
case 'num': {
const numSchema = schema;
return {
type: (NUMS_TYPE_MAPPING.get(numSchema.format || '') ?? 'float64'),
};
}
case 'str': {
return { type: 'string' };
}
case 'arr': {
const arraySchema = schema;
return {
elements: [toJtdForm(arraySchema.type)],
};
}
case 'obj': {
const objSchema = schema;
const form = {};
if (objSchema.fields && objSchema.fields.length > 0) {
form.properties = {};
form.optionalProperties = {};
for (const field of objSchema.fields) {
const fieldName = field.key;
const fieldType = field.value;
if (fieldType) {
const fieldJtd = toJtdForm(fieldType);
// Check if field is optional
if (field.optional === true) {
form.optionalProperties[fieldName] = fieldJtd;
}
else {
form.properties[fieldName] = fieldJtd;
}
}
}
}
// Handle additional properties - check the schema for unknownFields
if (objSchema.unknownFields === false) {
form.additionalProperties = false;
}
return form;
}
case 'tup': {
const tupleSchema = schema;
return {
elements: tupleSchema.types.map((element) => toJtdForm(element)),
};
}
case 'map': {
const mapSchema = schema;
return {
values: toJtdForm(mapSchema.value),
};
}
case 'ref': {
const refSchema = schema;
return {
ref: refSchema.ref,
};
}
// case 'or':
// case 'bin':
// case 'fn':
// case 'fn$':
default: {
const form = { nullable: false };
return form;
}
}
}