diff --git a/src/form/catalog.ts b/src/form/catalog.ts new file mode 100644 index 0000000..31d62e0 --- /dev/null +++ b/src/form/catalog.ts @@ -0,0 +1,266 @@ +import { + ConditionalRule, + ExtractedConditionForm, + FormEnumOption, + FormFieldDescriptor, + FormFieldType, + JsonSchemaProperty, + RuntimeConditionsExtensionDefinition, +} from './types'; + +/** + * Returns property names as field labels as-is, preserving raw field + * names for developer familiarity. + */ +export function formatFieldLabel(propName: string): string { + return propName || ''; +} + +/** + * 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) { + throw new Error('Extension definition missing metadata.id'); + } + + 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) { + fieldType = pSchema.type as FormFieldType; + } + + 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, + 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) { + 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 && + (!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, + 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, + }); + } + + return result; +} diff --git a/src/form/form.test.ts b/src/form/form.test.ts new file mode 100644 index 0000000..d8d64e4 --- /dev/null +++ b/src/form/form.test.ts @@ -0,0 +1,269 @@ +import { + extractConditionForms, + formatFieldLabel, +} from './catalog'; +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('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', () => { + 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'); + }); +}); diff --git a/src/form/index.ts b/src/form/index.ts new file mode 100644 index 0000000..cccf986 --- /dev/null +++ b/src/form/index.ts @@ -0,0 +1,2 @@ +export * from './types'; +export * from './catalog'; \ No newline at end of file diff --git a/src/form/types.ts b/src/form/types.ts new file mode 100644 index 0000000..50da374 --- /dev/null +++ b/src/form/types.ts @@ -0,0 +1,127 @@ +/** + * 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; + 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[]; +} 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';