UNPKG

core-types-json-schema

Version:
58 lines (57 loc) 2.01 kB
import { ensureArray, stringify, } from 'core-types'; export function annotateJsonSchema(node, jsonSchema) { const description = !node.description && !node.see ? undefined : mergeDescriptionAndSee(node.description, node.see); return { ...jsonSchema, ...(!node.title ? {} : { title: node.title }), ...(!description ? {} : { description }), ...(!node.default ? {} : { default: node.default }), ...(!node.examples ? {} : { examples: node.examples }), ...(!node.comment ? {} : { $comment: node.comment }), }; } export function annotateCoreTypes(node, jsonSchema) { const { description, see } = splitDescriptionAndSee(jsonSchema.description ?? ''); const annotations = { ...(jsonSchema.title ? { title: jsonSchema.title } : {}), ...(jsonSchema.default ? { default: stringify(jsonSchema.default) } : {}), ...(jsonSchema.examples ? { examples: stringify(jsonSchema.examples) } : {}), ...(jsonSchema.$comment ? { comment: jsonSchema.$comment } : {}), ...(description ? { description } : {}), ...((see && see.length > 0) ? { see } : {}), }; return { ...annotations, ...node }; } function mergeDescriptionAndSee(description, see) { const seeAsString = () => ensureArray(see) .map(see => `@see ${see}`) .join("\n"); if (description && see?.length) { return description + "\n\n" + seeAsString(); } return description ? description : seeAsString(); } function splitDescriptionAndSee(data) { const lines = (data ?? '').split("\n"); const see = []; while (lines.length > 0 && lines[lines.length - 1].startsWith('@see ')) see.push(lines.pop().slice(5)); while (lines.length > 0 && !lines[lines.length - 1].trim()) lines.pop(); return { description: lines.join("\n"), see, }; }