@genkit-ai/dotprompt
Version:
Genkit AI framework `.prompt` file format and management library.
107 lines • 3.12 kB
JavaScript
import {
__spreadProps,
__spreadValues
} from "./chunk-DFMI36TU.mjs";
const JSON_SCHEMA_SCALAR_TYPES = [
"string",
"boolean",
"null",
"number",
"integer",
"any"
];
const WILDCARD_PROPERTY_NAME = "(*)";
function picoschema(schema) {
if (!schema)
return null;
if ([...JSON_SCHEMA_SCALAR_TYPES, "object", "array"].includes(
schema == null ? void 0 : schema.type
)) {
return schema;
}
if (typeof (schema == null ? void 0 : schema.properties) === "object") {
return __spreadProps(__spreadValues({}, schema), { type: "object" });
}
return parsePico(schema);
}
function extractDescription(input) {
if (!input.includes(","))
return [input, null];
const match = input.match(/(.*?), *(.*)$/);
return [match[1], match[2]];
}
function parsePico(obj, path = []) {
if (typeof obj === "string") {
const [type, description] = extractDescription(obj);
if (!JSON_SCHEMA_SCALAR_TYPES.includes(type)) {
throw new Error(`Picoschema: Unsupported scalar type '${type}'.`);
}
if (type === "any") {
return description ? { description } : {};
}
return description ? { type, description } : { type };
} else if (typeof obj !== "object") {
throw new Error(
"Picoschema: only consists of objects and strings. Got: " + JSON.stringify(obj)
);
}
const schema = {
type: "object",
properties: {},
required: [],
additionalProperties: false
};
for (const key in obj) {
if (key === WILDCARD_PROPERTY_NAME) {
schema.additionalProperties = parsePico(obj[key], [...path, key]);
continue;
}
const [name, typeInfo] = key.split("(");
const isOptional = name.endsWith("?");
const propertyName = isOptional ? name.slice(0, -1) : name;
if (!isOptional) {
schema.required.push(propertyName);
}
if (!typeInfo) {
const prop = parsePico(obj[key], [...path, key]);
if (isOptional && typeof prop.type === "string") {
prop.type = [prop.type, "null"];
}
schema.properties[propertyName] = prop;
continue;
}
const [type, description] = extractDescription(
typeInfo.substring(0, typeInfo.length - 1)
);
if (type === "array") {
schema.properties[propertyName] = {
type: isOptional ? ["array", "null"] : "array",
items: parsePico(obj[key], [...path, key])
};
} else if (type === "object") {
const prop = parsePico(obj[key], [...path, key]);
if (isOptional)
prop.type = [prop.type, "null"];
schema.properties[propertyName] = prop;
} else if (type === "enum") {
const prop = { enum: obj[key] };
if (isOptional)
prop.enum.push(null);
schema.properties[propertyName] = prop;
} else {
throw new Error(
"Picoschema: parenthetical types must be 'object' or 'array', got: " + type
);
}
if (description) {
schema.properties[propertyName].description = description;
}
}
if (!schema.required.length)
delete schema.required;
return schema;
}
export {
picoschema
};
//# sourceMappingURL=picoschema.mjs.map