From ea458fdb4e7fbb4c4c3fc9510026ee0b13d1b766 Mon Sep 17 00:00:00 2001 From: Abhinav Deval Date: Sun, 29 Nov 2026 23:34:43 +0530 Subject: [PATCH 1/3] feat(form): add decoupled extension schema parser and profile YAML generator Signed-off-by: Abhinav Deval --- src/form/catalog.ts | 339 ++++++++++++++++++++++++++++++++ src/form/form.test.ts | 441 ++++++++++++++++++++++++++++++++++++++++++ src/form/generator.ts | 420 ++++++++++++++++++++++++++++++++++++++++ src/form/index.ts | 3 + src/form/types.ts | 146 ++++++++++++++ src/index.ts | 3 + 6 files changed, 1352 insertions(+) create mode 100644 src/form/catalog.ts create mode 100644 src/form/form.test.ts create mode 100644 src/form/generator.ts create mode 100644 src/form/index.ts create mode 100644 src/form/types.ts diff --git a/src/form/catalog.ts b/src/form/catalog.ts new file mode 100644 index 0000000..108e398 --- /dev/null +++ b/src/form/catalog.ts @@ -0,0 +1,339 @@ +import { + ConditionalRule, + ExtractedConditionForm, + FormEnumOption, + FormFieldDescriptor, + FormFieldType, + JsonSchemaProperty, + RuntimeConditionsExtensionDefinition, +} from './types'; + +/** + * Formats camelCase/snake_case property names into human-readable labels, + * preserving common technical acronyms and units (MiB, GiB, CPU, GPU, URI, etc.). + */ +export function formatFieldLabel(propName: string): string { + if (!propName) return ''; + + const acronymMap: Record = { + mib: 'MiB', + gib: 'GiB', + tib: 'TiB', + kib: 'KiB', + cpu: 'CPU', + gpu: 'GPU', + uri: 'URI', + url: 'URL', + id: 'ID', + ip: 'IP', + dns: 'DNS', + tls: 'TLS', + ssl: 'SSL', + http: 'HTTP', + https: 'HTTPS', + api: 'API', + db: 'DB', + vm: 'VM', + ram: 'RAM', + os: 'OS', + io: 'IO', + }; + + // Protect mixed-case unit suffixes (MiB, GiB, TiB, KiB) before splitting camelCase + const unitTokens: Record = { + mib: 'ZZZMIBZZZ', + gib: 'ZZZGIBZZZ', + tib: 'ZZZTIBZZZ', + kib: 'ZZZKIBZZZ', + }; + + let s = propName; + for (const [unit, token] of Object.entries(unitTokens)) { + s = s.replace(new RegExp(unit, 'gi'), token); + } + + // Split camelCase & transition boundaries + s = s + .replace(/([a-z\d])([A-Z])/g, '$1 $2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') + .replace(/[-_.]+/g, ' ') + .trim(); + + // Restore unit tokens + s = s + .replace(/ZZZMIBZZZ/g, 'MiB') + .replace(/ZZZGIBZZZ/g, 'GiB') + .replace(/ZZZTIBZZZ/g, 'TiB') + .replace(/ZZZKIBZZZ/g, 'KiB'); + + const words = s.split(/\s+/).map(word => { + const lower = word.toLowerCase(); + if (acronymMap[lower]) { + return acronymMap[lower]; + } + return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); + }); + + return words.join(' '); +} + +/** + * Validates and parses a raw extension object into a type-safe definition. + */ +export function parseExtensionDefinition( + raw: unknown, +): RuntimeConditionsExtensionDefinition { + if (!raw || typeof raw !== 'object') { + throw new Error('Extension definition must be a valid non-null object'); + } + + const def = raw as Partial; + + if (def.kind !== 'RuntimeConditionsExtensionDefinition') { + throw new Error( + `Invalid extension kind: expected "RuntimeConditionsExtensionDefinition", got "${def.kind}"`, + ); + } + + if (!def.metadata?.id || !def.metadata?.version) { + throw new Error('Extension definition missing metadata.id or metadata.version'); + } + + if (!def.spec?.kinds || !Array.isArray(def.spec.kinds)) { + throw new Error('Extension definition missing spec.kinds array'); + } + + if (!def.spec?.interfaceTypes || !Array.isArray(def.spec.interfaceTypes)) { + throw new Error('Extension definition missing spec.interfaceTypes array'); + } + + if (!def.spec?.schemas || !Array.isArray(def.spec.schemas)) { + throw new Error('Extension definition missing spec.schemas array'); + } + + return def as RuntimeConditionsExtensionDefinition; +} + +/** + * Collects statically required field names (unconditionally required across all inputs). + * Excludes conditional (if/then) requirements to prevent false rejections. + */ +function collectStaticRequiredFields( + schema: JsonSchemaProperty, + targetScope: 'interface' | 'condition', +): Set { + const reqs = new Set(); + + if (targetScope === 'condition') { + if (Array.isArray(schema.required)) { + schema.required.forEach(r => reqs.add(r)); + } + } else { + const iface = schema.properties?.interface as JsonSchemaProperty | undefined; + if (iface && Array.isArray(iface.required)) { + iface.required.forEach(r => reqs.add(r)); + } + } + + return reqs; +} + +/** + * Extracts conditional rules (if/then blocks) from root schema and allOf blocks. + */ +function extractConditionalRules(schema: JsonSchemaProperty): ConditionalRule[] { + const rules: ConditionalRule[] = []; + + if (schema.if && schema.then) { + rules.push({ if: schema.if, then: schema.then }); + } + + if (Array.isArray(schema.allOf)) { + for (const sub of schema.allOf) { + if (sub.if && sub.then) { + rules.push({ if: sub.if, then: sub.then }); + } + } + } + + // Also check interface-level if/then if present + const iface = schema.properties?.interface as JsonSchemaProperty | undefined; + if (iface) { + if (iface.if && iface.then) { + rules.push({ if: iface.if, then: iface.then }); + } + if (Array.isArray(iface.allOf)) { + for (const sub of iface.allOf) { + if (sub.if && sub.then) { + rules.push({ if: sub.if, then: sub.then }); + } + } + } + } + + return rules; +} + +/** + * Extracts form field descriptors from an extension definition. + * Covers interface fields, condition-level fields (e.g. env, configuration), + * enums with descriptions, and dynamic validation metadata. + */ +export function extractConditionForms( + ext: RuntimeConditionsExtensionDefinition, +): ExtractedConditionForm[] { + const result: ExtractedConditionForm[] = []; + + for (const schemaItem of ext.spec.schemas) { + const kindObj = ext.spec.kinds.find( + k => k.name === schemaItem.appliesToKind, + ); + const ifaceTypeObj = ext.spec.interfaceTypes.find( + i => + i.name === schemaItem.appliesToInterfaceType && + i.targetKind === schemaItem.appliesToKind, + ); + + const fields: FormFieldDescriptor[] = []; + const schemaObj = schemaItem.schema ?? {}; + const conditionalRules = extractConditionalRules(schemaObj); + + // 1. Extract Interface fields (if interface property exists) + const ifaceSchema = schemaObj.properties?.interface as JsonSchemaProperty | undefined; + const ifaceProps = ifaceSchema?.properties ?? {}; + const ifaceRequiredSet = collectStaticRequiredFields(schemaObj, 'interface'); + + for (const [propName, propVal] of Object.entries(ifaceProps)) { + if (propVal && typeof propVal === 'object' && 'const' in propVal) { + continue; + } + + const pSchema = (propVal || {}) as JsonSchemaProperty; + const isRequired = ifaceRequiredSet.has(propName); + + let fieldType: FormFieldType = 'string'; + let enumOptions: FormEnumOption[] | undefined; + + if (Array.isArray(pSchema.enum)) { + fieldType = 'enum'; + const fieldValueMatch = ext.spec.fieldValues?.find( + fv => + fv.targetKind === schemaItem.appliesToKind && + fv.targetType === schemaItem.appliesToInterfaceType && + (fv.field === `interface.${propName}` || fv.field === propName), + ); + + enumOptions = pSchema.enum.map(val => { + const sVal = String(val); + const desc = fieldValueMatch?.valueDescriptions?.[sVal]; + return { + value: sVal, + label: sVal.charAt(0).toUpperCase() + sVal.slice(1), + description: desc, + }; + }); + } else if (pSchema.type === 'integer') { + fieldType = 'integer'; + } else if (pSchema.type === 'number') { + fieldType = 'number'; + } else if (pSchema.type === 'boolean') { + fieldType = 'boolean'; + } else if (pSchema.type === 'array') { + fieldType = 'array'; + } else if (pSchema.type === 'object') { + fieldType = 'object'; + } + + const fieldDoc = ext.spec.interfaceFields?.find( + f => + f.targetKind === schemaItem.appliesToKind && + f.targetType === schemaItem.appliesToInterfaceType && + f.name === propName, + ); + + const description = + fieldDoc?.description || + pSchema.description || + `Specifies ${propName}`; + + fields.push({ + name: propName, + path: `interface.${propName}`, + location: 'interface', + label: formatFieldLabel(propName), + description, + type: fieldType, + required: isRequired, + defaultValue: pSchema.default, + minimum: pSchema.minimum, + maximum: pSchema.maximum, + pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, + enumOptions, + }); + } + + // 2. Extract Condition-level fields (e.g. env, configuration) + const rootProps = schemaObj.properties ?? {}; + const conditionRequiredSet = collectStaticRequiredFields(schemaObj, 'condition'); + + for (const [propName, propVal] of Object.entries(rootProps)) { + if (['kind', 'interface', 'name', 'optional'].includes(propName)) { + continue; + } + + const pSchema = (propVal || {}) as JsonSchemaProperty; + const isRequired = conditionRequiredSet.has(propName); + + let fieldType: FormFieldType = 'string'; + if (pSchema.type === 'array') { + fieldType = 'array'; + } else if (pSchema.type === 'object') { + fieldType = 'object'; + } else if (pSchema.type === 'boolean') { + fieldType = 'boolean'; + } else if (pSchema.type === 'integer') { + fieldType = 'integer'; + } + + const condDoc = ext.spec.conditionFields?.find( + cf => + cf.name === propName && + (!cf.appliesToKinds || cf.appliesToKinds.includes(schemaItem.appliesToKind)) && + (!cf.appliesToInterfaceTypes || cf.appliesToInterfaceTypes.includes(schemaItem.appliesToInterfaceType)), + ); + + const description = + condDoc?.description || + pSchema.description || + `Condition property ${propName}`; + + fields.push({ + name: propName, + path: propName, + location: 'condition', + label: formatFieldLabel(propName), + description, + type: fieldType, + required: isRequired, + defaultValue: pSchema.default, + minimum: pSchema.minimum, + maximum: pSchema.maximum, + pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, + }); + } + + result.push({ + extensionId: ext.metadata.id, + version: ext.metadata.version, + kind: schemaItem.appliesToKind, + kindDescription: kindObj?.description, + interfaceType: schemaItem.appliesToInterfaceType, + interfaceTypeDescription: ifaceTypeObj?.description, + schemaId: schemaItem.id, + fields, + conditionalRules: conditionalRules.length > 0 ? conditionalRules : undefined, + }); + } + + return result; +} diff --git a/src/form/form.test.ts b/src/form/form.test.ts new file mode 100644 index 0000000..825fb1e --- /dev/null +++ b/src/form/form.test.ts @@ -0,0 +1,441 @@ +import { + extractConditionForms, + formatFieldLabel, +} from './catalog'; +import { + buildProfile, + buildProfileCondition, + serializeProfileToYaml, +} from './generator'; +import { RuntimeConditionsExtensionDefinition } from './types'; + +const sampleGpuExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/rc/gpu/0.1.0/runtimeconditions.extension.yaml', + version: '0.1.0', + description: 'Requires GPU hardware', + }, + spec: { + kinds: [{ name: 'rc.gpu', description: 'Requires GPU' }], + interfaceTypes: [{ name: 'device', targetKind: 'rc.gpu' }], + interfaceFields: [ + { + name: 'count', + targetKind: 'rc.gpu', + targetType: 'device', + description: 'Number of devices', + }, + { + name: 'minMemoryMiB', + targetKind: 'rc.gpu', + targetType: 'device', + description: 'Memory per GPU in MiB', + }, + { + name: 'vendor', + targetKind: 'rc.gpu', + targetType: 'device', + description: 'Hardware vendor', + }, + ], + fieldValues: [ + { + field: 'interface.vendor', + targetKind: 'rc.gpu', + targetType: 'device', + values: ['nvidia', 'amd', 'intel'], + valueDescriptions: { + nvidia: 'NVIDIA GPU hardware.', + amd: 'AMD GPU hardware.', + intel: 'Intel GPU hardware.', + }, + }, + ], + schemas: [ + { + id: 'rc-gpu-device', + appliesToKind: 'rc.gpu', + appliesToInterfaceType: 'device', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'rc.gpu' }, + interface: { + type: 'object', + required: ['type', 'count'], + properties: { + type: { const: 'device' }, + count: { + type: 'integer', + minimum: 1, + description: 'Minimum number of whole GPU devices.', + }, + minMemoryMiB: { + type: 'integer', + minimum: 1, + description: 'Minimum memory per GPU in mebibytes.', + }, + vendor: { + enum: ['nvidia', 'amd', 'intel'], + description: 'Required GPU hardware vendor.', + }, + }, + additionalProperties: false, + }, + }, + additionalProperties: false, + }, + }, + ], + }, +}; + +// Extension with conditional rules (if access == read_write -> persistence; if no env -> path) +const sampleFileSystemExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/rc/file-system/0.2.0/runtimeconditions.extension.yaml', + version: '0.2.0', + description: 'File system mounts', + }, + spec: { + kinds: [{ name: 'rc.file_system' }], + interfaceTypes: [{ name: 'mount', targetKind: 'rc.file_system' }], + conditionFields: [ + { + name: 'env', + appliesToKinds: ['rc.file_system'], + appliesToInterfaceTypes: ['mount'], + description: 'Environment variables for the path.', + }, + ], + interfaceFields: [ + { + name: 'path', + targetKind: 'rc.file_system', + targetType: 'mount', + description: 'Full path of folder.', + }, + { + name: 'access', + targetKind: 'rc.file_system', + targetType: 'mount', + description: 'read_only or read_write.', + }, + { + name: 'persistence', + targetKind: 'rc.file_system', + targetType: 'mount', + description: 'Required if access is read_write.', + }, + ], + schemas: [ + { + id: 'file-system-mount', + appliesToKind: 'rc.file_system', + appliesToInterfaceType: 'mount', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'rc.file_system' }, + interface: { + type: 'object', + required: ['type', 'access'], + properties: { + type: { const: 'mount' }, + path: { type: 'string' }, + access: { enum: ['read_only', 'read_write'] }, + persistence: { type: 'string' }, + }, + }, + env: { + type: 'array', + description: 'Environment variables.', + }, + }, + allOf: [ + { + if: { + properties: { + interface: { + properties: { + access: { const: 'read_write' }, + }, + }, + }, + }, + then: { + properties: { + interface: { + required: ['persistence'], + }, + }, + }, + }, + { + if: { + not: { + required: ['env'], + }, + }, + then: { + properties: { + interface: { + required: ['path'], + }, + }, + }, + }, + ], + }, + }, + ], + }, +}; + +const sampleNatsExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/nats/service/0.2.0/runtimeconditions.extension.yaml', + version: '0.2.0', + description: 'NATS configuration input', + }, + spec: { + kinds: [{ name: 'nats.service' }], + interfaceTypes: [{ name: 'service', targetKind: 'nats.service' }], + conditionFields: [ + { + name: 'configuration', + appliesToKinds: ['nats.service'], + appliesToInterfaceTypes: ['service'], + description: 'NATS configuration settings', + }, + ], + schemas: [ + { + id: 'nats-service-configuration', + appliesToKind: 'nats.service', + appliesToInterfaceType: 'service', + schema: { + type: 'object', + properties: { + configuration: { + type: 'object', + description: 'NATS environment configuration', + }, + }, + }, + }, + ], + }, +}; + +describe('Catalog & Form Extraction', () => { + it('formats acronym labels cleanly without breaking units or case', () => { + expect(formatFieldLabel('minMemoryMiB')).toBe('Min Memory MiB'); + expect(formatFieldLabel('minMemoryGiB')).toBe('Min Memory GiB'); + expect(formatFieldLabel('cpuCores')).toBe('CPU Cores'); + expect(formatFieldLabel('workloadURI')).toBe('Workload URI'); + expect(formatFieldLabel('gpuVendor')).toBe('GPU Vendor'); + expect(formatFieldLabel('contentBasedDeduplication')).toBe('Content Based Deduplication'); + }); + + it('extracts root conditionFields and does not falsely make conditional fields statically required', () => { + const [form] = extractConditionForms(sampleFileSystemExtension); + expect(form.fields).toBeDefined(); + + const envField = form.fields.find(f => f.name === 'env'); + expect(envField).toBeDefined(); + expect(envField?.location).toBe('condition'); + + // path and persistence must NOT be statically required + const pathField = form.fields.find(f => f.name === 'path'); + expect(pathField?.required).toBe(false); + + const persistenceField = form.fields.find(f => f.name === 'persistence'); + expect(persistenceField?.required).toBe(false); + + // access IS statically required + const accessField = form.fields.find(f => f.name === 'access'); + expect(accessField?.required).toBe(true); + + expect(form.conditionalRules).toHaveLength(2); + }); + + it('extracts properties when interface key is omitted', () => { + const [form] = extractConditionForms(sampleNatsExtension); + expect(form.fields).toHaveLength(1); + expect(form.fields[0].name).toBe('configuration'); + expect(form.fields[0].location).toBe('condition'); + }); +}); + +describe('Validation & Generation Engine', () => { + it('rejects numbers below minimum for both number and string inputs', () => { + const [gpuForm] = extractConditionForms(sampleGpuExtension); + + // number 0 rejected by minimum: 1 + expect(() => + buildProfileCondition({ + kind: 'rc.gpu', + interfaceType: 'device', + fields: gpuForm.fields, + values: { count: 0 }, + }), + ).toThrow(/must be at least 1/i); + + // string "0" rejected by minimum: 1 + expect(() => + buildProfileCondition({ + kind: 'rc.gpu', + interfaceType: 'device', + fields: gpuForm.fields, + values: { count: '0' }, + }), + ).toThrow(/must be at least 1/i); + + // float 2.5 rejected + expect(() => + buildProfileCondition({ + kind: 'rc.gpu', + interfaceType: 'device', + fields: gpuForm.fields, + values: { count: 2.5 }, + }), + ).toThrow(/must be a valid integer/i); + + // whitespace rejected + expect(() => + buildProfileCondition({ + kind: 'rc.gpu', + interfaceType: 'device', + fields: gpuForm.fields, + values: { count: ' ' }, + }), + ).toThrow(/is required/i); + }); + + it('handles boolean strings accurately', () => { + const [gpuForm] = extractConditionForms(sampleGpuExtension); + + const cond = buildProfileCondition({ + kind: 'rc.gpu', + interfaceType: 'device', + optional: ('false' as unknown as boolean), + fields: gpuForm.fields, + values: { count: 1 }, + }); + + expect(cond.optional).toBe(false); + }); + + it('strictly requires interfaceType and does not silently default', () => { + const [gpuForm] = extractConditionForms(sampleGpuExtension); + + expect(() => + buildProfileCondition({ + kind: 'rc.gpu', + interfaceType: '', + fields: gpuForm.fields, + values: { count: 1 }, + }), + ).toThrow(/interfaceType is required/i); + }); + + it('evaluates conditional requirements accurately (accepts valid env-only profile)', () => { + const [fsForm] = extractConditionForms(sampleFileSystemExtension); + + // 1. Valid env-only profile: access = read_only, env is provided, path is omitted -> SUCCESS! + const cond = buildProfileCondition({ + kind: 'rc.file_system', + interfaceType: 'mount', + fields: fsForm.fields, + conditionalRules: fsForm.conditionalRules, + values: { + access: 'read_only', + env: ['DATA_DIR'], + }, + }); + + expect(cond.interface.access).toBe('read_only'); + expect(cond.interface.path).toBeUndefined(); + expect((cond as Record).env).toEqual(['DATA_DIR']); + + // 2. access = read_write without persistence -> REJECTED! + expect(() => + buildProfileCondition({ + kind: 'rc.file_system', + interfaceType: 'mount', + fields: fsForm.fields, + conditionalRules: fsForm.conditionalRules, + values: { + access: 'read_write', + env: ['DATA_DIR'], + }, + }), + ).toThrow(/persistence/i); + + // 3. Neither env nor path provided -> REJECTED! + expect(() => + buildProfileCondition({ + kind: 'rc.file_system', + interfaceType: 'mount', + fields: fsForm.fields, + conditionalRules: fsForm.conditionalRules, + values: { + access: 'read_only', + }, + }), + ).toThrow(/path/i); + }); + + it('safely formats YAML without coercing version numbers or special strings', () => { + const profile = buildProfile({ + name: 'test: special # comment', + workloadUri: 'https://example.com/workload?a=1&b=2', + workloadVersion: '1.0', + conditions: [ + { + kind: 'rc.gpu', + interfaceType: 'device', + name: 'name: with "quotes" and \\backslashes\\', + fields: [ + { + name: 'count', + path: 'interface.count', + location: 'interface', + label: 'Count', + description: 'GPU Count', + type: 'integer', + required: true, + }, + ], + values: { + count: 1, + }, + }, + ], + }); + + const yaml = serializeProfileToYaml(profile); + + // Version "1.0" must be quoted to avoid being parsed as number 1 + expect(yaml).toContain('version: "1.0"'); + + // Name with special chars must be quoted + expect(yaml).toContain('name: "test: special # comment"'); + + // Condition name with quotes and backslashes must be safely escaped + expect(yaml).toContain('\\"quotes\\"'); + expect(yaml).toContain('backslashes'); + + // No [object Object] + expect(yaml).not.toContain('[object Object]'); + }); +}); diff --git a/src/form/generator.ts b/src/form/generator.ts new file mode 100644 index 0000000..4ef2e41 --- /dev/null +++ b/src/form/generator.ts @@ -0,0 +1,420 @@ +import { Condition, RuntimeConditionsProfile } from '../profiles'; +import { + ConditionalRule, + ConditionGenerationInput, + FormFieldDescriptor, + GenerateProfileOptions, + JsonSchemaProperty, +} from './types'; + +/** + * Validates a single value against its field descriptor constraints. + */ +function validateFieldValue(field: FormFieldDescriptor, val: unknown): unknown { + if (field.type === 'integer') { + let num: number; + if (typeof val === 'number') { + if (!Number.isInteger(val)) { + throw new Error(`Field "${field.label}" must be a valid integer, got float: ${val}`); + } + num = val; + } else { + const str = String(val).trim(); + if (str === '' || !/^-?\d+$/.test(str)) { + throw new Error(`Field "${field.label}" must be a valid integer, got: "${val}"`); + } + num = parseInt(str, 10); + } + + if (field.minimum !== undefined && num < field.minimum) { + throw new Error(`Field "${field.label}" must be at least ${field.minimum}, got: ${num}`); + } + if (field.maximum !== undefined && num > field.maximum) { + throw new Error(`Field "${field.label}" must be at most ${field.maximum}, got: ${num}`); + } + return num; + } + + if (field.type === 'number') { + const num = Number(val); + if (isNaN(num)) { + throw new Error(`Field "${field.label}" must be a valid number, got: "${val}"`); + } + if (field.minimum !== undefined && num < field.minimum) { + throw new Error(`Field "${field.label}" must be at least ${field.minimum}, got: ${num}`); + } + if (field.maximum !== undefined && num > field.maximum) { + throw new Error(`Field "${field.label}" must be at most ${field.maximum}, got: ${num}`); + } + return num; + } + + if (field.type === 'boolean') { + if (val === true || val === 'true') return true; + if (val === false || val === 'false') return false; + throw new Error(`Field "${field.label}" must be a boolean (true or false), got: "${val}"`); + } + + if (field.type === 'enum' && field.enumOptions) { + const allowed = field.enumOptions.map(o => o.value); + const sVal = String(val); + if (!allowed.includes(sVal)) { + throw new Error( + `Field "${field.label}" must be one of [${allowed.join(', ')}], got: "${sVal}"`, + ); + } + return sVal; + } + + return val; +} + +/** + * Evaluates whether submitted form values satisfy an if condition block. + */ +function evaluateIfCondition( + ifSchema: JsonSchemaProperty, + values: Record, +): boolean { + // 1. Evaluate if.properties + if (ifSchema.properties) { + for (const [propKey, propRule] of Object.entries(ifSchema.properties)) { + if (propKey === 'interface' && propRule.properties) { + for (const [ifaceKey, ifaceRule] of Object.entries(propRule.properties)) { + const actualVal = values[ifaceKey] ?? values[`interface.${ifaceKey}`]; + if (ifaceRule.const !== undefined && actualVal !== ifaceRule.const) { + return false; + } + if (Array.isArray(ifaceRule.enum) && !ifaceRule.enum.includes(actualVal as string)) { + return false; + } + } + } else { + const actualVal = values[propKey]; + if (propRule.const !== undefined && actualVal !== propRule.const) { + return false; + } + if (Array.isArray(propRule.enum) && !propRule.enum.includes(actualVal as string)) { + return false; + } + } + } + } + + // 2. Evaluate if.required (checks presence of field) + if (Array.isArray(ifSchema.required)) { + for (const reqProp of ifSchema.required) { + const val = values[reqProp] ?? values[`interface.${reqProp}`]; + if (val === undefined || val === null || val === '') { + return false; + } + } + } + + // 3. Evaluate if.not + if (ifSchema.not) { + return !evaluateIfCondition(ifSchema.not, values); + } + + return true; +} + +/** + * Validates dynamic conditional rules (if/then) against submitted values. + */ +function validateConditionalRules( + rules: ConditionalRule[] | undefined, + fields: FormFieldDescriptor[], + values: Record, + kind: string, +): void { + if (!rules || rules.length === 0) return; + + const fieldLabelMap = new Map(fields.map(f => [f.name, f.label])); + + for (const rule of rules) { + if (!rule.if || !rule.then) continue; + + const conditionMet = evaluateIfCondition(rule.if, values); + if (!conditionMet) continue; + + // Condition met: verify then requirements + const reqs: string[] = []; + if (Array.isArray(rule.then.required)) { + reqs.push(...rule.then.required); + } + const ifaceThen = rule.then.properties?.interface as JsonSchemaProperty | undefined; + if (ifaceThen && Array.isArray(ifaceThen.required)) { + reqs.push(...ifaceThen.required); + } + + for (const reqField of reqs) { + const val = values[reqField] ?? values[`interface.${reqField}`]; + const isMissing = + val === undefined || + val === null || + (typeof val === 'string' && val.trim() === '') || + (Array.isArray(val) && val.length === 0); + + if (isMissing) { + const label = fieldLabelMap.get(reqField) || reqField; + throw new Error( + `Field "${label}" (${reqField}) is required for condition kind "${kind}" under current configuration`, + ); + } + } + } +} + +/** + * Builds a single spec-compliant Condition from form input. + * Fully decoupled from Backstage Entity model. + */ +export function buildProfileCondition(input: ConditionGenerationInput): Condition { + const { kind, interfaceType, name, optional, fields, conditionalRules, values } = input; + + if (!interfaceType || !interfaceType.trim()) { + throw new Error(`interfaceType is required for condition kind "${kind}"`); + } + + const condition: Condition = { + kind, + interface: { + type: interfaceType.trim(), + }, + }; + + if (name && name.trim()) { + condition.name = name.trim(); + } + + if (optional !== undefined) { + if (typeof optional === 'string') { + condition.optional = (optional as string).toLowerCase() === 'true'; + } else { + condition.optional = Boolean(optional); + } + } + + // 1. Check static required fields and extract values + for (const field of fields) { + let val = values[field.name]; + + const isBlank = + val === undefined || + val === null || + (typeof val === 'string' && val.trim() === ''); + + // Fall back to defaultValue if provided and value is missing or blank + if (isBlank && field.defaultValue !== undefined) { + val = field.defaultValue; + } + + const isEmpty = + val === undefined || + val === null || + (typeof val === 'string' && val.trim() === ''); + + if (field.required && isEmpty) { + throw new Error( + `Field "${field.label}" (${field.name}) is required for condition kind "${kind}"`, + ); + } + + if (!isEmpty) { + const validated = validateFieldValue(field, val); + if (field.location === 'interface') { + condition.interface[field.name] = validated; + } else { + (condition as Record)[field.name] = validated; + } + } + } + + // 2. Validate dynamic conditional rules (e.g. if access == read_write -> persistence required) + validateConditionalRules(conditionalRules, fields, values, kind); + + return condition; +} + +/** + * Derives a clean metadata name from workload URI. + */ +function deriveProfileName(options: GenerateProfileOptions): string { + if (options.name && options.name.trim()) { + return options.name.trim(); + } + try { + const cleanUri = options.workloadUri.replace(/\.git$/, '').replace(/\/+$/, ''); + const segments = cleanUri.split('/'); + const last = segments[segments.length - 1]; + if (last) { + return `${last.toLowerCase().replace(/[^a-z0-9-]/g, '-')}-profile`; + } + } catch { + // fallback + } + return 'workload-profile'; +} + +/** + * Builds a complete, spec-compliant RuntimeConditionsProfile. + */ +export function buildProfile(options: GenerateProfileOptions): RuntimeConditionsProfile { + if (!options.workloadUri || !options.workloadUri.trim()) { + throw new Error('workloadUri is required to generate a Runtime Conditions Profile'); + } + + const extensionSet = new Set(); + for (const cond of options.conditions) { + if (cond.extensionId) { + extensionSet.add(cond.extensionId); + } + } + + const conditions: Condition[] = options.conditions.map(c => buildProfileCondition(c)); + + const profile: RuntimeConditionsProfile = { + metadata: { + name: deriveProfileName(options), + }, + workload: { + uri: options.workloadUri.trim(), + }, + extensions: Array.from(extensionSet), + conditions, + }; + + if (options.workloadVersion && options.workloadVersion.trim()) { + profile.workload.version = options.workloadVersion.trim(); + } + + return profile; +} + +/** + * Formats a string value for YAML. Safely quotes strings starting with numbers, + * special characters, hyphens, or matching YAML keywords. + */ +function formatYamlString(val: string): string { + if (val.includes('\n')) { + return JSON.stringify(val); + } + + // Pure safe identifier: starts with ASCII letter, only letters, digits, underscores, or dots + const isSafeIdentifier = /^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(val); + const isReservedKeyword = /^(true|false|null|yes|no|on|off|y|n)$/i.test(val); + + if (isSafeIdentifier && !isReservedKeyword) { + return val; + } + + return JSON.stringify(val); +} + +/** + * Recursively formats an arbitrary value into clean canonical YAML lines with indentation. + */ +function formatYamlValue(val: unknown, indentLevel: number): string { + const indent = ' '.repeat(indentLevel); + + if (val === null || val === undefined) { + return 'null'; + } + + if (typeof val === 'boolean') { + return val ? 'true' : 'false'; + } + + if (typeof val === 'number') { + return String(val); + } + + if (typeof val === 'string') { + return formatYamlString(val); + } + + if (Array.isArray(val)) { + if (val.length === 0) return '[]'; + const lines: string[] = []; + for (const item of val) { + if (typeof item === 'object' && item !== null && !Array.isArray(item)) { + const entries = Object.entries(item); + if (entries.length === 0) { + lines.push(`${indent}- {}`); + } else { + const [firstKey, firstVal] = entries[0]; + if (typeof firstVal === 'object' && firstVal !== null) { + if (Array.isArray(firstVal) && firstVal.length === 0) { + lines.push(`${indent}- ${firstKey}: []`); + } else if (!Array.isArray(firstVal) && Object.keys(firstVal).length === 0) { + lines.push(`${indent}- ${firstKey}: {}`); + } else { + lines.push(`${indent}- ${firstKey}:\n${formatYamlValue(firstVal, indentLevel + 2)}`); + } + } else { + lines.push(`${indent}- ${firstKey}: ${formatYamlValue(firstVal, indentLevel + 1)}`); + } + + for (let i = 1; i < entries.length; i++) { + const [k, v] = entries[i]; + if (typeof v === 'object' && v !== null) { + if (Array.isArray(v) && v.length === 0) { + lines.push(`${indent} ${k}: []`); + } else if (!Array.isArray(v) && Object.keys(v).length === 0) { + lines.push(`${indent} ${k}: {}`); + } else { + lines.push(`${indent} ${k}:\n${formatYamlValue(v, indentLevel + 2)}`); + } + } else { + lines.push(`${indent} ${k}: ${formatYamlValue(v, indentLevel + 1)}`); + } + } + } + } else { + lines.push(`${indent}- ${formatYamlValue(item, indentLevel + 1)}`); + } + } + return lines.join('\n'); + } + + if (typeof val === 'object') { + const entries = Object.entries(val as Record); + if (entries.length === 0) return '{}'; + const lines: string[] = []; + for (const [k, v] of entries) { + if (v === undefined) continue; + if (typeof v === 'object' && v !== null) { + if (Array.isArray(v) && v.length === 0) { + lines.push(`${indent}${k}: []`); + } else if (!Array.isArray(v) && Object.keys(v).length === 0) { + lines.push(`${indent}${k}: {}`); + } else { + lines.push(`${indent}${k}:\n${formatYamlValue(v, indentLevel + 1)}`); + } + } else { + lines.push(`${indent}${k}: ${formatYamlValue(v, indentLevel + 1)}`); + } + } + return lines.join('\n'); + } + + return JSON.stringify(val); +} + +/** + * Serializes a RuntimeConditionsProfile to canonical YAML format. + * Produces 100% valid, spec-compliant YAML with safe string escaping and nested support. + */ +export function serializeProfileToYaml(profile: RuntimeConditionsProfile): string { + const rootObj: Record = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsProfile', + metadata: profile.metadata, + workload: profile.workload, + extensions: profile.extensions, + conditions: profile.conditions, + }; + + return formatYamlValue(rootObj, 0) + '\n'; +} diff --git a/src/form/index.ts b/src/form/index.ts new file mode 100644 index 0000000..9295b71 --- /dev/null +++ b/src/form/index.ts @@ -0,0 +1,3 @@ +export * from './types'; +export * from './catalog'; +export * from './generator'; diff --git a/src/form/types.ts b/src/form/types.ts new file mode 100644 index 0000000..9d0677d --- /dev/null +++ b/src/form/types.ts @@ -0,0 +1,146 @@ +/** + * Core type definitions for Runtime Conditions Extension definitions and Dynamic Form generation. + * Decoupled from Backstage UI to allow reuse across CLI and runtimeconditions.io web playground. + */ + +export interface ExtensionMetadata { + id: string; + version: string; + description?: string; +} + +export interface ExtensionKind { + name: string; + description?: string; +} + +export interface ExtensionInterfaceType { + name: string; + targetKind: string; + description?: string; +} + +export interface ExtensionConditionField { + name: string; + appliesToKinds?: string[]; + appliesToInterfaceTypes?: string[]; + description?: string; +} + +export interface ExtensionInterfaceField { + name: string; + targetKind: string; + targetType: string; + description?: string; +} + +export interface ExtensionFieldValue { + field: string; + targetKind: string; + targetType: string; + values: string[]; + valueDescriptions?: Record; +} + +export interface JsonSchemaProperty { + type?: string; + enum?: (string | number | boolean)[]; + const?: unknown; + description?: string; + minimum?: number; + maximum?: number; + pattern?: string; + default?: unknown; + required?: string[]; + properties?: Record; + items?: JsonSchemaProperty | JsonSchemaProperty[]; + oneOf?: JsonSchemaProperty[]; + anyOf?: JsonSchemaProperty[]; + allOf?: JsonSchemaProperty[]; + if?: JsonSchemaProperty; + then?: JsonSchemaProperty; + else?: JsonSchemaProperty; + not?: JsonSchemaProperty; + $ref?: string; + [key: string]: unknown; +} + +export interface ExtensionSchemaItem { + id: string; + appliesToKind: string; + appliesToInterfaceType: string; + description?: string; + schema: JsonSchemaProperty; +} + +export interface RuntimeConditionsExtensionDefinition { + apiVersion: string; + kind: 'RuntimeConditionsExtensionDefinition'; + metadata: ExtensionMetadata; + spec: { + kinds: ExtensionKind[]; + interfaceTypes: ExtensionInterfaceType[]; + conditionFields?: ExtensionConditionField[]; + interfaceFields?: ExtensionInterfaceField[]; + fieldValues?: ExtensionFieldValue[]; + schemas: ExtensionSchemaItem[]; + }; +} + +export type FormFieldType = 'string' | 'integer' | 'number' | 'boolean' | 'enum' | 'object' | 'array'; + +export interface FormEnumOption { + value: string; + label: string; + description?: string; +} + +export interface FormFieldDescriptor { + name: string; + path: string; // e.g. 'interface.count' or 'env' or 'configuration' + location: 'interface' | 'condition'; + label: string; + description?: string; + type: FormFieldType; + required: boolean; + defaultValue?: unknown; + minimum?: number; + maximum?: number; + pattern?: string; + enumOptions?: FormEnumOption[]; +} + +export interface ConditionalRule { + if?: JsonSchemaProperty; + then?: JsonSchemaProperty; +} + +export interface ExtractedConditionForm { + extensionId: string; + version: string; + kind: string; + kindDescription?: string; + interfaceType: string; + interfaceTypeDescription?: string; + schemaId: string; + fields: FormFieldDescriptor[]; + conditionalRules?: ConditionalRule[]; +} + +export interface ConditionGenerationInput { + kind: string; + interfaceType: string; + extensionId?: string; + name?: string; + optional?: boolean; + fields: FormFieldDescriptor[]; + conditionalRules?: ConditionalRule[]; + values: Record; +} + +export interface GenerateProfileOptions { + name?: string; + workloadUri: string; + workloadVersion?: string; + conditions: ConditionGenerationInput[]; +} diff --git a/src/index.ts b/src/index.ts index 8adfa5a..8413e0f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,3 +3,6 @@ export { EntityRuntimeConditionsContent, isRuntimeConditionsAvailable, } from './plugin'; + +export * from './profiles'; +export * from './form'; From 466f8a3a8a94e4ba50a2783c9499168cba7aaf93 Mon Sep 17 00:00:00 2001 From: Abhinav Deval Date: Mon, 30 Nov 2026 13:51:27 +0530 Subject: [PATCH 2/3] refactor(form): simplify label formatting, make version optional, and streamline type extraction --- src/form/catalog.ts | 83 +++++++------------------------------------ src/form/form.test.ts | 9 ++--- src/form/generator.ts | 12 +------ src/form/types.ts | 7 ++-- 4 files changed, 19 insertions(+), 92 deletions(-) diff --git a/src/form/catalog.ts b/src/form/catalog.ts index 108e398..f52ebbe 100644 --- a/src/form/catalog.ts +++ b/src/form/catalog.ts @@ -9,48 +9,12 @@ import { } from './types'; /** - * Formats camelCase/snake_case property names into human-readable labels, - * preserving common technical acronyms and units (MiB, GiB, CPU, GPU, URI, etc.). + * Formats camelCase/snake_case property names into human-readable labels. */ export function formatFieldLabel(propName: string): string { if (!propName) return ''; - const acronymMap: Record = { - mib: 'MiB', - gib: 'GiB', - tib: 'TiB', - kib: 'KiB', - cpu: 'CPU', - gpu: 'GPU', - uri: 'URI', - url: 'URL', - id: 'ID', - ip: 'IP', - dns: 'DNS', - tls: 'TLS', - ssl: 'SSL', - http: 'HTTP', - https: 'HTTPS', - api: 'API', - db: 'DB', - vm: 'VM', - ram: 'RAM', - os: 'OS', - io: 'IO', - }; - - // Protect mixed-case unit suffixes (MiB, GiB, TiB, KiB) before splitting camelCase - const unitTokens: Record = { - mib: 'ZZZMIBZZZ', - gib: 'ZZZGIBZZZ', - tib: 'ZZZTIBZZZ', - kib: 'ZZZKIBZZZ', - }; - let s = propName; - for (const [unit, token] of Object.entries(unitTokens)) { - s = s.replace(new RegExp(unit, 'gi'), token); - } // Split camelCase & transition boundaries s = s @@ -59,18 +23,7 @@ export function formatFieldLabel(propName: string): string { .replace(/[-_.]+/g, ' ') .trim(); - // Restore unit tokens - s = s - .replace(/ZZZMIBZZZ/g, 'MiB') - .replace(/ZZZGIBZZZ/g, 'GiB') - .replace(/ZZZTIBZZZ/g, 'TiB') - .replace(/ZZZKIBZZZ/g, 'KiB'); - const words = s.split(/\s+/).map(word => { - const lower = word.toLowerCase(); - if (acronymMap[lower]) { - return acronymMap[lower]; - } return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); }); @@ -95,8 +48,8 @@ export function parseExtensionDefinition( ); } - if (!def.metadata?.id || !def.metadata?.version) { - throw new Error('Extension definition missing metadata.id or metadata.version'); + if (!def.metadata?.id) { + throw new Error('Extension definition missing metadata.id'); } if (!def.spec?.kinds || !Array.isArray(def.spec.kinds)) { @@ -232,16 +185,8 @@ export function extractConditionForms( description: desc, }; }); - } else if (pSchema.type === 'integer') { - fieldType = 'integer'; - } else if (pSchema.type === 'number') { - fieldType = 'number'; - } else if (pSchema.type === 'boolean') { - fieldType = 'boolean'; - } else if (pSchema.type === 'array') { - fieldType = 'array'; - } else if (pSchema.type === 'object') { - fieldType = 'object'; + } else if (pSchema.type) { + fieldType = pSchema.type as FormFieldType; } const fieldDoc = ext.spec.interfaceFields?.find( @@ -264,7 +209,6 @@ export function extractConditionForms( description, type: fieldType, required: isRequired, - defaultValue: pSchema.default, minimum: pSchema.minimum, maximum: pSchema.maximum, pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, @@ -285,16 +229,14 @@ export function extractConditionForms( const isRequired = conditionRequiredSet.has(propName); let fieldType: FormFieldType = 'string'; - if (pSchema.type === 'array') { - fieldType = 'array'; - } else if (pSchema.type === 'object') { - fieldType = 'object'; - } else if (pSchema.type === 'boolean') { - fieldType = 'boolean'; - } else if (pSchema.type === 'integer') { - fieldType = 'integer'; + if (pSchema.type) { + fieldType = pSchema.type as FormFieldType; } + // Look up the extension's documentation for this condition-level field. A conditionFields + // entry documents this property when its name matches AND it targets this schema's kind and + // interface type. An entry that omits appliesToKinds / appliesToInterfaceTypes is untargeted + // and so applies to every kind / interface type. const condDoc = ext.spec.conditionFields?.find( cf => cf.name === propName && @@ -315,7 +257,6 @@ export function extractConditionForms( description, type: fieldType, required: isRequired, - defaultValue: pSchema.default, minimum: pSchema.minimum, maximum: pSchema.maximum, pattern: typeof pSchema.pattern === 'string' ? pSchema.pattern : undefined, @@ -331,7 +272,7 @@ export function extractConditionForms( interfaceTypeDescription: ifaceTypeObj?.description, schemaId: schemaItem.id, fields, - conditionalRules: conditionalRules.length > 0 ? conditionalRules : undefined, + conditionalRules, }); } diff --git a/src/form/form.test.ts b/src/form/form.test.ts index 825fb1e..7a7a1e5 100644 --- a/src/form/form.test.ts +++ b/src/form/form.test.ts @@ -237,12 +237,9 @@ const sampleNatsExtension: RuntimeConditionsExtensionDefinition = { }; describe('Catalog & Form Extraction', () => { - it('formats acronym labels cleanly without breaking units or case', () => { - expect(formatFieldLabel('minMemoryMiB')).toBe('Min Memory MiB'); - expect(formatFieldLabel('minMemoryGiB')).toBe('Min Memory GiB'); - expect(formatFieldLabel('cpuCores')).toBe('CPU Cores'); - expect(formatFieldLabel('workloadURI')).toBe('Workload URI'); - expect(formatFieldLabel('gpuVendor')).toBe('GPU Vendor'); + it('formats camelCase and snake_case names into Title Case labels', () => { + expect(formatFieldLabel('minMemory')).toBe('Min Memory'); + expect(formatFieldLabel('read_only')).toBe('Read Only'); expect(formatFieldLabel('contentBasedDeduplication')).toBe('Content Based Deduplication'); }); diff --git a/src/form/generator.ts b/src/form/generator.ts index 4ef2e41..3894b5e 100644 --- a/src/form/generator.ts +++ b/src/form/generator.ts @@ -198,17 +198,7 @@ export function buildProfileCondition(input: ConditionGenerationInput): Conditio // 1. Check static required fields and extract values for (const field of fields) { - let val = values[field.name]; - - const isBlank = - val === undefined || - val === null || - (typeof val === 'string' && val.trim() === ''); - - // Fall back to defaultValue if provided and value is missing or blank - if (isBlank && field.defaultValue !== undefined) { - val = field.defaultValue; - } + const val = values[field.name]; const isEmpty = val === undefined || diff --git a/src/form/types.ts b/src/form/types.ts index 9d0677d..be753ae 100644 --- a/src/form/types.ts +++ b/src/form/types.ts @@ -5,7 +5,7 @@ export interface ExtensionMetadata { id: string; - version: string; + version?: string; description?: string; } @@ -103,7 +103,6 @@ export interface FormFieldDescriptor { description?: string; type: FormFieldType; required: boolean; - defaultValue?: unknown; minimum?: number; maximum?: number; pattern?: string; @@ -117,14 +116,14 @@ export interface ConditionalRule { export interface ExtractedConditionForm { extensionId: string; - version: string; + version?: string; kind: string; kindDescription?: string; interfaceType: string; interfaceTypeDescription?: string; schemaId: string; fields: FormFieldDescriptor[]; - conditionalRules?: ConditionalRule[]; + conditionalRules: ConditionalRule[]; } export interface ConditionGenerationInput { From 020e95478eca900e6897150b238fcf2ccb6defd4 Mon Sep 17 00:00:00 2001 From: Abhinav Deval Date: Mon, 30 Nov 2026 15:37:29 +0530 Subject: [PATCH 3/3] refactor(form): drop generator from this PR and use raw field names as labels Signed-off-by: Abhinav Deval --- src/form/catalog.ts | 20 +-- src/form/form.test.ts | 177 +----------------- src/form/generator.ts | 410 ------------------------------------------ src/form/index.ts | 3 +- src/form/types.ts | 18 -- 5 files changed, 8 insertions(+), 620 deletions(-) delete mode 100644 src/form/generator.ts diff --git a/src/form/catalog.ts b/src/form/catalog.ts index f52ebbe..31d62e0 100644 --- a/src/form/catalog.ts +++ b/src/form/catalog.ts @@ -9,25 +9,11 @@ import { } from './types'; /** - * Formats camelCase/snake_case property names into human-readable labels. + * Returns property names as field labels as-is, preserving raw field + * names for developer familiarity. */ export function formatFieldLabel(propName: string): string { - if (!propName) return ''; - - let s = propName; - - // Split camelCase & transition boundaries - s = s - .replace(/([a-z\d])([A-Z])/g, '$1 $2') - .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') - .replace(/[-_.]+/g, ' ') - .trim(); - - const words = s.split(/\s+/).map(word => { - return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); - }); - - return words.join(' '); + return propName || ''; } /** diff --git a/src/form/form.test.ts b/src/form/form.test.ts index 7a7a1e5..d8d64e4 100644 --- a/src/form/form.test.ts +++ b/src/form/form.test.ts @@ -2,11 +2,6 @@ import { extractConditionForms, formatFieldLabel, } from './catalog'; -import { - buildProfile, - buildProfileCondition, - serializeProfileToYaml, -} from './generator'; import { RuntimeConditionsExtensionDefinition } from './types'; const sampleGpuExtension: RuntimeConditionsExtensionDefinition = { @@ -237,10 +232,10 @@ const sampleNatsExtension: RuntimeConditionsExtensionDefinition = { }; describe('Catalog & Form Extraction', () => { - it('formats camelCase and snake_case names into Title Case labels', () => { - expect(formatFieldLabel('minMemory')).toBe('Min Memory'); - expect(formatFieldLabel('read_only')).toBe('Read Only'); - expect(formatFieldLabel('contentBasedDeduplication')).toBe('Content Based Deduplication'); + it('preserves field names as labels for developer familiarity', () => { + expect(formatFieldLabel('minMemory')).toBe('minMemory'); + expect(formatFieldLabel('read_only')).toBe('read_only'); + expect(formatFieldLabel('contentBasedDeduplication')).toBe('contentBasedDeduplication'); }); it('extracts root conditionFields and does not falsely make conditional fields statically required', () => { @@ -272,167 +267,3 @@ describe('Catalog & Form Extraction', () => { expect(form.fields[0].location).toBe('condition'); }); }); - -describe('Validation & Generation Engine', () => { - it('rejects numbers below minimum for both number and string inputs', () => { - const [gpuForm] = extractConditionForms(sampleGpuExtension); - - // number 0 rejected by minimum: 1 - expect(() => - buildProfileCondition({ - kind: 'rc.gpu', - interfaceType: 'device', - fields: gpuForm.fields, - values: { count: 0 }, - }), - ).toThrow(/must be at least 1/i); - - // string "0" rejected by minimum: 1 - expect(() => - buildProfileCondition({ - kind: 'rc.gpu', - interfaceType: 'device', - fields: gpuForm.fields, - values: { count: '0' }, - }), - ).toThrow(/must be at least 1/i); - - // float 2.5 rejected - expect(() => - buildProfileCondition({ - kind: 'rc.gpu', - interfaceType: 'device', - fields: gpuForm.fields, - values: { count: 2.5 }, - }), - ).toThrow(/must be a valid integer/i); - - // whitespace rejected - expect(() => - buildProfileCondition({ - kind: 'rc.gpu', - interfaceType: 'device', - fields: gpuForm.fields, - values: { count: ' ' }, - }), - ).toThrow(/is required/i); - }); - - it('handles boolean strings accurately', () => { - const [gpuForm] = extractConditionForms(sampleGpuExtension); - - const cond = buildProfileCondition({ - kind: 'rc.gpu', - interfaceType: 'device', - optional: ('false' as unknown as boolean), - fields: gpuForm.fields, - values: { count: 1 }, - }); - - expect(cond.optional).toBe(false); - }); - - it('strictly requires interfaceType and does not silently default', () => { - const [gpuForm] = extractConditionForms(sampleGpuExtension); - - expect(() => - buildProfileCondition({ - kind: 'rc.gpu', - interfaceType: '', - fields: gpuForm.fields, - values: { count: 1 }, - }), - ).toThrow(/interfaceType is required/i); - }); - - it('evaluates conditional requirements accurately (accepts valid env-only profile)', () => { - const [fsForm] = extractConditionForms(sampleFileSystemExtension); - - // 1. Valid env-only profile: access = read_only, env is provided, path is omitted -> SUCCESS! - const cond = buildProfileCondition({ - kind: 'rc.file_system', - interfaceType: 'mount', - fields: fsForm.fields, - conditionalRules: fsForm.conditionalRules, - values: { - access: 'read_only', - env: ['DATA_DIR'], - }, - }); - - expect(cond.interface.access).toBe('read_only'); - expect(cond.interface.path).toBeUndefined(); - expect((cond as Record).env).toEqual(['DATA_DIR']); - - // 2. access = read_write without persistence -> REJECTED! - expect(() => - buildProfileCondition({ - kind: 'rc.file_system', - interfaceType: 'mount', - fields: fsForm.fields, - conditionalRules: fsForm.conditionalRules, - values: { - access: 'read_write', - env: ['DATA_DIR'], - }, - }), - ).toThrow(/persistence/i); - - // 3. Neither env nor path provided -> REJECTED! - expect(() => - buildProfileCondition({ - kind: 'rc.file_system', - interfaceType: 'mount', - fields: fsForm.fields, - conditionalRules: fsForm.conditionalRules, - values: { - access: 'read_only', - }, - }), - ).toThrow(/path/i); - }); - - it('safely formats YAML without coercing version numbers or special strings', () => { - const profile = buildProfile({ - name: 'test: special # comment', - workloadUri: 'https://example.com/workload?a=1&b=2', - workloadVersion: '1.0', - conditions: [ - { - kind: 'rc.gpu', - interfaceType: 'device', - name: 'name: with "quotes" and \\backslashes\\', - fields: [ - { - name: 'count', - path: 'interface.count', - location: 'interface', - label: 'Count', - description: 'GPU Count', - type: 'integer', - required: true, - }, - ], - values: { - count: 1, - }, - }, - ], - }); - - const yaml = serializeProfileToYaml(profile); - - // Version "1.0" must be quoted to avoid being parsed as number 1 - expect(yaml).toContain('version: "1.0"'); - - // Name with special chars must be quoted - expect(yaml).toContain('name: "test: special # comment"'); - - // Condition name with quotes and backslashes must be safely escaped - expect(yaml).toContain('\\"quotes\\"'); - expect(yaml).toContain('backslashes'); - - // No [object Object] - expect(yaml).not.toContain('[object Object]'); - }); -}); diff --git a/src/form/generator.ts b/src/form/generator.ts deleted file mode 100644 index 3894b5e..0000000 --- a/src/form/generator.ts +++ /dev/null @@ -1,410 +0,0 @@ -import { Condition, RuntimeConditionsProfile } from '../profiles'; -import { - ConditionalRule, - ConditionGenerationInput, - FormFieldDescriptor, - GenerateProfileOptions, - JsonSchemaProperty, -} from './types'; - -/** - * Validates a single value against its field descriptor constraints. - */ -function validateFieldValue(field: FormFieldDescriptor, val: unknown): unknown { - if (field.type === 'integer') { - let num: number; - if (typeof val === 'number') { - if (!Number.isInteger(val)) { - throw new Error(`Field "${field.label}" must be a valid integer, got float: ${val}`); - } - num = val; - } else { - const str = String(val).trim(); - if (str === '' || !/^-?\d+$/.test(str)) { - throw new Error(`Field "${field.label}" must be a valid integer, got: "${val}"`); - } - num = parseInt(str, 10); - } - - if (field.minimum !== undefined && num < field.minimum) { - throw new Error(`Field "${field.label}" must be at least ${field.minimum}, got: ${num}`); - } - if (field.maximum !== undefined && num > field.maximum) { - throw new Error(`Field "${field.label}" must be at most ${field.maximum}, got: ${num}`); - } - return num; - } - - if (field.type === 'number') { - const num = Number(val); - if (isNaN(num)) { - throw new Error(`Field "${field.label}" must be a valid number, got: "${val}"`); - } - if (field.minimum !== undefined && num < field.minimum) { - throw new Error(`Field "${field.label}" must be at least ${field.minimum}, got: ${num}`); - } - if (field.maximum !== undefined && num > field.maximum) { - throw new Error(`Field "${field.label}" must be at most ${field.maximum}, got: ${num}`); - } - return num; - } - - if (field.type === 'boolean') { - if (val === true || val === 'true') return true; - if (val === false || val === 'false') return false; - throw new Error(`Field "${field.label}" must be a boolean (true or false), got: "${val}"`); - } - - if (field.type === 'enum' && field.enumOptions) { - const allowed = field.enumOptions.map(o => o.value); - const sVal = String(val); - if (!allowed.includes(sVal)) { - throw new Error( - `Field "${field.label}" must be one of [${allowed.join(', ')}], got: "${sVal}"`, - ); - } - return sVal; - } - - return val; -} - -/** - * Evaluates whether submitted form values satisfy an if condition block. - */ -function evaluateIfCondition( - ifSchema: JsonSchemaProperty, - values: Record, -): boolean { - // 1. Evaluate if.properties - if (ifSchema.properties) { - for (const [propKey, propRule] of Object.entries(ifSchema.properties)) { - if (propKey === 'interface' && propRule.properties) { - for (const [ifaceKey, ifaceRule] of Object.entries(propRule.properties)) { - const actualVal = values[ifaceKey] ?? values[`interface.${ifaceKey}`]; - if (ifaceRule.const !== undefined && actualVal !== ifaceRule.const) { - return false; - } - if (Array.isArray(ifaceRule.enum) && !ifaceRule.enum.includes(actualVal as string)) { - return false; - } - } - } else { - const actualVal = values[propKey]; - if (propRule.const !== undefined && actualVal !== propRule.const) { - return false; - } - if (Array.isArray(propRule.enum) && !propRule.enum.includes(actualVal as string)) { - return false; - } - } - } - } - - // 2. Evaluate if.required (checks presence of field) - if (Array.isArray(ifSchema.required)) { - for (const reqProp of ifSchema.required) { - const val = values[reqProp] ?? values[`interface.${reqProp}`]; - if (val === undefined || val === null || val === '') { - return false; - } - } - } - - // 3. Evaluate if.not - if (ifSchema.not) { - return !evaluateIfCondition(ifSchema.not, values); - } - - return true; -} - -/** - * Validates dynamic conditional rules (if/then) against submitted values. - */ -function validateConditionalRules( - rules: ConditionalRule[] | undefined, - fields: FormFieldDescriptor[], - values: Record, - kind: string, -): void { - if (!rules || rules.length === 0) return; - - const fieldLabelMap = new Map(fields.map(f => [f.name, f.label])); - - for (const rule of rules) { - if (!rule.if || !rule.then) continue; - - const conditionMet = evaluateIfCondition(rule.if, values); - if (!conditionMet) continue; - - // Condition met: verify then requirements - const reqs: string[] = []; - if (Array.isArray(rule.then.required)) { - reqs.push(...rule.then.required); - } - const ifaceThen = rule.then.properties?.interface as JsonSchemaProperty | undefined; - if (ifaceThen && Array.isArray(ifaceThen.required)) { - reqs.push(...ifaceThen.required); - } - - for (const reqField of reqs) { - const val = values[reqField] ?? values[`interface.${reqField}`]; - const isMissing = - val === undefined || - val === null || - (typeof val === 'string' && val.trim() === '') || - (Array.isArray(val) && val.length === 0); - - if (isMissing) { - const label = fieldLabelMap.get(reqField) || reqField; - throw new Error( - `Field "${label}" (${reqField}) is required for condition kind "${kind}" under current configuration`, - ); - } - } - } -} - -/** - * Builds a single spec-compliant Condition from form input. - * Fully decoupled from Backstage Entity model. - */ -export function buildProfileCondition(input: ConditionGenerationInput): Condition { - const { kind, interfaceType, name, optional, fields, conditionalRules, values } = input; - - if (!interfaceType || !interfaceType.trim()) { - throw new Error(`interfaceType is required for condition kind "${kind}"`); - } - - const condition: Condition = { - kind, - interface: { - type: interfaceType.trim(), - }, - }; - - if (name && name.trim()) { - condition.name = name.trim(); - } - - if (optional !== undefined) { - if (typeof optional === 'string') { - condition.optional = (optional as string).toLowerCase() === 'true'; - } else { - condition.optional = Boolean(optional); - } - } - - // 1. Check static required fields and extract values - for (const field of fields) { - const val = values[field.name]; - - const isEmpty = - val === undefined || - val === null || - (typeof val === 'string' && val.trim() === ''); - - if (field.required && isEmpty) { - throw new Error( - `Field "${field.label}" (${field.name}) is required for condition kind "${kind}"`, - ); - } - - if (!isEmpty) { - const validated = validateFieldValue(field, val); - if (field.location === 'interface') { - condition.interface[field.name] = validated; - } else { - (condition as Record)[field.name] = validated; - } - } - } - - // 2. Validate dynamic conditional rules (e.g. if access == read_write -> persistence required) - validateConditionalRules(conditionalRules, fields, values, kind); - - return condition; -} - -/** - * Derives a clean metadata name from workload URI. - */ -function deriveProfileName(options: GenerateProfileOptions): string { - if (options.name && options.name.trim()) { - return options.name.trim(); - } - try { - const cleanUri = options.workloadUri.replace(/\.git$/, '').replace(/\/+$/, ''); - const segments = cleanUri.split('/'); - const last = segments[segments.length - 1]; - if (last) { - return `${last.toLowerCase().replace(/[^a-z0-9-]/g, '-')}-profile`; - } - } catch { - // fallback - } - return 'workload-profile'; -} - -/** - * Builds a complete, spec-compliant RuntimeConditionsProfile. - */ -export function buildProfile(options: GenerateProfileOptions): RuntimeConditionsProfile { - if (!options.workloadUri || !options.workloadUri.trim()) { - throw new Error('workloadUri is required to generate a Runtime Conditions Profile'); - } - - const extensionSet = new Set(); - for (const cond of options.conditions) { - if (cond.extensionId) { - extensionSet.add(cond.extensionId); - } - } - - const conditions: Condition[] = options.conditions.map(c => buildProfileCondition(c)); - - const profile: RuntimeConditionsProfile = { - metadata: { - name: deriveProfileName(options), - }, - workload: { - uri: options.workloadUri.trim(), - }, - extensions: Array.from(extensionSet), - conditions, - }; - - if (options.workloadVersion && options.workloadVersion.trim()) { - profile.workload.version = options.workloadVersion.trim(); - } - - return profile; -} - -/** - * Formats a string value for YAML. Safely quotes strings starting with numbers, - * special characters, hyphens, or matching YAML keywords. - */ -function formatYamlString(val: string): string { - if (val.includes('\n')) { - return JSON.stringify(val); - } - - // Pure safe identifier: starts with ASCII letter, only letters, digits, underscores, or dots - const isSafeIdentifier = /^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(val); - const isReservedKeyword = /^(true|false|null|yes|no|on|off|y|n)$/i.test(val); - - if (isSafeIdentifier && !isReservedKeyword) { - return val; - } - - return JSON.stringify(val); -} - -/** - * Recursively formats an arbitrary value into clean canonical YAML lines with indentation. - */ -function formatYamlValue(val: unknown, indentLevel: number): string { - const indent = ' '.repeat(indentLevel); - - if (val === null || val === undefined) { - return 'null'; - } - - if (typeof val === 'boolean') { - return val ? 'true' : 'false'; - } - - if (typeof val === 'number') { - return String(val); - } - - if (typeof val === 'string') { - return formatYamlString(val); - } - - if (Array.isArray(val)) { - if (val.length === 0) return '[]'; - const lines: string[] = []; - for (const item of val) { - if (typeof item === 'object' && item !== null && !Array.isArray(item)) { - const entries = Object.entries(item); - if (entries.length === 0) { - lines.push(`${indent}- {}`); - } else { - const [firstKey, firstVal] = entries[0]; - if (typeof firstVal === 'object' && firstVal !== null) { - if (Array.isArray(firstVal) && firstVal.length === 0) { - lines.push(`${indent}- ${firstKey}: []`); - } else if (!Array.isArray(firstVal) && Object.keys(firstVal).length === 0) { - lines.push(`${indent}- ${firstKey}: {}`); - } else { - lines.push(`${indent}- ${firstKey}:\n${formatYamlValue(firstVal, indentLevel + 2)}`); - } - } else { - lines.push(`${indent}- ${firstKey}: ${formatYamlValue(firstVal, indentLevel + 1)}`); - } - - for (let i = 1; i < entries.length; i++) { - const [k, v] = entries[i]; - if (typeof v === 'object' && v !== null) { - if (Array.isArray(v) && v.length === 0) { - lines.push(`${indent} ${k}: []`); - } else if (!Array.isArray(v) && Object.keys(v).length === 0) { - lines.push(`${indent} ${k}: {}`); - } else { - lines.push(`${indent} ${k}:\n${formatYamlValue(v, indentLevel + 2)}`); - } - } else { - lines.push(`${indent} ${k}: ${formatYamlValue(v, indentLevel + 1)}`); - } - } - } - } else { - lines.push(`${indent}- ${formatYamlValue(item, indentLevel + 1)}`); - } - } - return lines.join('\n'); - } - - if (typeof val === 'object') { - const entries = Object.entries(val as Record); - if (entries.length === 0) return '{}'; - const lines: string[] = []; - for (const [k, v] of entries) { - if (v === undefined) continue; - if (typeof v === 'object' && v !== null) { - if (Array.isArray(v) && v.length === 0) { - lines.push(`${indent}${k}: []`); - } else if (!Array.isArray(v) && Object.keys(v).length === 0) { - lines.push(`${indent}${k}: {}`); - } else { - lines.push(`${indent}${k}:\n${formatYamlValue(v, indentLevel + 1)}`); - } - } else { - lines.push(`${indent}${k}: ${formatYamlValue(v, indentLevel + 1)}`); - } - } - return lines.join('\n'); - } - - return JSON.stringify(val); -} - -/** - * Serializes a RuntimeConditionsProfile to canonical YAML format. - * Produces 100% valid, spec-compliant YAML with safe string escaping and nested support. - */ -export function serializeProfileToYaml(profile: RuntimeConditionsProfile): string { - const rootObj: Record = { - apiVersion: 'runtimeconditions.io/v1alpha1', - kind: 'RuntimeConditionsProfile', - metadata: profile.metadata, - workload: profile.workload, - extensions: profile.extensions, - conditions: profile.conditions, - }; - - return formatYamlValue(rootObj, 0) + '\n'; -} diff --git a/src/form/index.ts b/src/form/index.ts index 9295b71..cccf986 100644 --- a/src/form/index.ts +++ b/src/form/index.ts @@ -1,3 +1,2 @@ export * from './types'; -export * from './catalog'; -export * from './generator'; +export * from './catalog'; \ No newline at end of file diff --git a/src/form/types.ts b/src/form/types.ts index be753ae..50da374 100644 --- a/src/form/types.ts +++ b/src/form/types.ts @@ -125,21 +125,3 @@ export interface ExtractedConditionForm { fields: FormFieldDescriptor[]; conditionalRules: ConditionalRule[]; } - -export interface ConditionGenerationInput { - kind: string; - interfaceType: string; - extensionId?: string; - name?: string; - optional?: boolean; - fields: FormFieldDescriptor[]; - conditionalRules?: ConditionalRule[]; - values: Record; -} - -export interface GenerateProfileOptions { - name?: string; - workloadUri: string; - workloadVersion?: string; - conditions: ConditionGenerationInput[]; -}