UNPKG

bguard

Version:

**bguard** is a powerful, flexible, and type-safe validation library for TypeScript. It allows developers to define validation schemas for their data structures and ensures that data conforms to the expected types and constraints.

1 lines 2.99 kB
{"version":3,"sources":["../src/codeGen.ts"],"sourcesContent":["import { ctxSymbol } from './helpers/constants';\nimport { type CommonSchema, type ValidatorContext } from './core';\n\nfunction generateBaseType(schemaData: ValidatorContext) {\n if (schemaData.date) return 'Date';\n\n if (schemaData.strictType) {\n if (Array.isArray(schemaData.strictTypeValue)) return schemaData.strictTypeValue.join(' | ');\n return schemaData.strictTypeValue;\n }\n if (!schemaData.type.length) return '';\n const joined = schemaData.type.join(' | ');\n return joined;\n}\n\nconst INDENT_DEFAULT = ` `;\n\nfunction innerGenerator(schema: CommonSchema, isProperty: boolean, indent = INDENT_DEFAULT): string {\n const schemaData = schema[ctxSymbol];\n let code = '';\n\n if (isProperty) {\n code = code + (schemaData.isOptional ? '?: ' : ': ');\n }\n\n if (schemaData.array) {\n const innerArrayCode = innerGenerator(schemaData.array, false, indent + INDENT_DEFAULT);\n code = code + (innerArrayCode.includes('|') ? `(${innerArrayCode})[]` : `${innerArrayCode}[]`);\n }\n\n if (schemaData.object) {\n code = code + '{\\n';\n for (const [keyOfSchema, valueOfSchema] of Object.entries(schemaData.object)) {\n code = code + indent + keyOfSchema + innerGenerator(valueOfSchema, true, indent + INDENT_DEFAULT) + ';\\n';\n }\n code = code + indent.slice(0, -INDENT_DEFAULT.length) + '}';\n }\n\n code = code + generateBaseType(schemaData);\n code = code + (schemaData.isNullable ? ' | null' : '');\n code = code + (schemaData.isOptional ? ' | undefined' : '');\n\n return code;\n}\n\nexport function codeGen(schema: CommonSchema): string {\n const result = innerGenerator(schema, false) + ';';\n return result;\n}\n\nexport function codeGenWithName(typeName: string, schema: CommonSchema): string {\n const result = 'type ' + typeName + ' = ' + codeGen(schema) + '\\n';\n return result;\n}\n"],"mappings":";;;;;AAGA,SAAS,iBAAiB,YAA8B;AACtD,MAAI,WAAW,KAAM,QAAO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