UNPKG

@minecraft/creator-tools

Version:

Minecraft Creator Tools command line and libraries.

74 lines (73 loc) 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildObjectFromSchema = void 0; exports.buildProperty = buildProperty; const SchemaParser_1 = require("../UX/shared/components/SchemaForm/SchemaParser"); const buildObjectFromSchema = (schema, initialValues) => { const definitions = Object.entries(schema.definitions || []); const root = buildRoot(schema, definitions, initialValues); return root; }; exports.buildObjectFromSchema = buildObjectFromSchema; function buildRoot(schema, references, initialValues) { if (schema.type === "array") { if (initialValues && Array.isArray(initialValues)) { return initialValues; } return []; } if (schema.type !== "object") { throw new Error(`Unsupported root schema type. Only 'object' and 'array' root types are supported, but received type: '${schema.type}'.`); } return buildObject(schema, references, initialValues); } function buildObject(schema, references, initialValues) { const obj = {}; const properties = Object.entries(schema.properties || []); for (const [name, prop] of properties) { obj[name] = buildProperty(prop, references); } if (initialValues) { Object.assign(obj, initialValues); } return obj; } function buildProperty(prop, references, parent, uiDef) { if (!!prop?.$ref) { const resolved = (0, SchemaParser_1.resolveReferenceFromPath)(prop.$ref, references); prop = resolved?.definition || null; } const options = prop?.oneOf || prop?.anyOf; if (!!options) { const bestOneOf = (0, SchemaParser_1.findBestOneOf)(options, references, parent); if (!!bestOneOf) { const { definition: oneOfDef } = bestOneOf; return buildProperty(oneOfDef, references); } } if (!prop) { return { error: true, message: `[buildProperty] Unexpected Failure determining type | prop is null`, }; } if (!!prop.enum) { return prop.default ?? prop.enum[0]; } if (!prop.type) { //This helps handle the MC specific case where we do the bool as object pattern, which does not get a type in schema return undefined; } switch (prop.type) { case "string": case "number": case "integer": case "boolean": return prop.default; case "array": return []; case "object": return buildObject(prop, references); } return { error: true, message: `[buildProperty] Failure | type: ${prop?.type} | ref: ${prop.$ref}` }; }