From 97ee4fb4e91364f020fb156162cb71396db5e396 Mon Sep 17 00:00:00 2001 From: Abhinav Deval Date: Fri, 4 Dec 2026 14:27:11 +0530 Subject: [PATCH] feat(form): compose schemas and vocabulary across chained extensions --- src/form/catalog.ts | 573 +++++++++++++++++++++++++++++++++++------- src/form/form.test.ts | 513 +++++++++++++++++++++++++++++++++++++ src/form/types.ts | 9 +- 3 files changed, 998 insertions(+), 97 deletions(-) diff --git a/src/form/catalog.ts b/src/form/catalog.ts index 81f21a0..c5fea7f 100644 --- a/src/form/catalog.ts +++ b/src/form/catalog.ts @@ -1,7 +1,12 @@ import type { JSONSchema7, JSONSchema7Definition, JSONSchema7TypeName } from 'json-schema'; import { ConditionalRule, + ExtensionConditionField, ExtensionDependency, + ExtensionFieldValue, + ExtensionInterfaceField, + ExtensionInterfaceType, + ExtensionKind, ExtensionSchemaItem, ExtractedConditionForm, FormEnumOption, @@ -11,8 +16,9 @@ import { } from './types'; interface ExtractionContext { - ext: RuntimeConditionsExtensionDefinition; - schemaItem: ExtensionSchemaItem; + targetKind: string; + targetType: string; + fieldValues: ExtensionFieldValue[]; rootSchema: JSONSchema7; } @@ -371,23 +377,46 @@ function buildEnumOptions( // Match on the canonical dotted path first; keep the bare-name check for top-level paths // (`interface.` or ``) for backward compatibility with the original flat lookup, // while preventing nested leaves from inheriting a top-level entry with the same property name. - const fieldValueMatch = ctx.ext.spec.fieldValues?.find( - fv => - fv.targetKind === ctx.schemaItem.appliesToKind && - fv.targetType === ctx.schemaItem.appliesToInterfaceType && - (fv.field === path || ((path === `interface.${name}` || path === name) && fv.field === name)), - ); + // Merge matching entries in base-to-additive order so additive extensions can override/enrich. + const isTopLevel = path === `interface.${name}` || path === name; + const mergedDescriptions: Record = {}; + for (const fv of ctx.fieldValues) { + if ( + fv.targetKind === ctx.targetKind && + fv.targetType === ctx.targetType && + isTopLevel && + fv.field === name && + fv.valueDescriptions + ) { + Object.assign(mergedDescriptions, fv.valueDescriptions); + } + } + for (const fv of ctx.fieldValues) { + if ( + fv.targetKind === ctx.targetKind && + fv.targetType === ctx.targetType && + fv.field === path && + fv.valueDescriptions + ) { + Object.assign(mergedDescriptions, fv.valueDescriptions); + } + } return schemaProp.enum.map(val => { const strVal = String(val); return { value: strVal, label: strVal.charAt(0).toUpperCase() + strVal.slice(1), - description: fieldValueMatch?.valueDescriptions?.[strVal], + description: mergedDescriptions[strVal], }; }); } +/** Placeholder description used when a schema and the extension docs provide none. */ +function fallbackDescription(name: string, location: 'interface' | 'condition'): string { + return location === 'interface' ? `Specifies ${name}` : `Condition property ${name}`; +} + function extractFieldDescriptor( name: string, path: string, @@ -411,7 +440,7 @@ function extractFieldDescriptor( overrideDescription || pSchema.description || rawSchema.description || - (location === 'interface' ? `Specifies ${name}` : `Condition property ${name}`); + fallbackDescription(name, location); if (isRecursiveRef) { return { @@ -520,113 +549,467 @@ function extractFieldDescriptor( } /** - * Extracts form field descriptors from an extension definition. - * Recursively extracts nested objects, arrays, $ref/$defs, and union variants. + * True when `desc` is missing or is the auto-generated placeholder, i.e. a real description + * from another schema in the chain is allowed to replace it. */ -export function extractConditionForms( - ext: RuntimeConditionsExtensionDefinition, -): ExtractedConditionForm[] { - const result: ExtractedConditionForm[] = []; +function isFallbackDescription(desc: string | undefined, name: string): boolean { + return ( + !desc || + desc === fallbackDescription(name, 'interface') || + desc === fallbackDescription(name, 'condition') + ); +} - for (const schemaItem of ext.spec.schemas) { - const kindObj = (ext.spec.kinds ?? []).find( - k => k.name === schemaItem.appliesToKind, +/** + * Merges `incomingList` into `baseList`. Fields are matched by name and location; matches are + * merged with `mergeFieldDescriptors`, and unmatched incoming fields are appended. + */ +function mergeFieldList( + baseList: FormFieldDescriptor[], + incomingList: FormFieldDescriptor[], +): FormFieldDescriptor[] { + const result = [...baseList]; + for (const incoming of incomingList) { + const idx = result.findIndex( + existing => existing.name === incoming.name && existing.location === incoming.location, ); - const ifaceTypeObj = (ext.spec.interfaceTypes ?? []).find( - i => - i.name === schemaItem.appliesToInterfaceType && - i.targetKind === schemaItem.appliesToKind, + if (idx === -1) { + result.push(incoming); + } else { + result[idx] = mergeFieldDescriptors(result[idx], incoming); + } + } + return result; +} + +/** + * Merges enum options, keeping the incoming (possibly narrowed) value list but falling back to + * the base option's description when the incoming option has none. + */ +function mergeEnumOptions( + baseOpts?: FormEnumOption[], + incomingOpts?: FormEnumOption[], +): FormEnumOption[] | undefined { + if (!incomingOpts) { + return baseOpts; + } + if (!baseOpts) { + return incomingOpts; + } + const baseDescMap = new Map(); + for (const opt of baseOpts) { + if (opt.description !== undefined) { + baseDescMap.set(opt.value, opt.description); + } + } + return incomingOpts.map(opt => ({ + ...opt, + description: opt.description ?? baseDescMap.get(opt.value), + })); +} + +/** + * Merges a refining descriptor (`incoming`, e.g. from a scoped additive schema) into an + * existing descriptor (`base`, e.g. from a base schema or shared shape schema) without losing + * structural constraints such as `oneOf` variants, regex patterns, or enum option descriptions. + * Base wins for `description`, `required`, `type` and structure; `incoming` wins for `constValue`, + * `minimum`, `maximum` and `pattern` (it refines them), and for the enum value list. + */ +function mergeFieldDescriptors( + base: FormFieldDescriptor, + incoming: FormFieldDescriptor, +): FormFieldDescriptor { + const merged: FormFieldDescriptor = { + ...base, + description: isFallbackDescription(base.description, base.name) + ? incoming.description ?? base.description + : base.description, + required: base.required || incoming.required, + // Keep the base type, except when the incoming schema narrows a plain string to an enum, or + // the base was a bare string-typed union that incoming resolves to a concrete object. + type: + (incoming.type === 'enum' && base.type === 'string') || + (base.variants && base.type === 'string' && incoming.type === 'object') + ? incoming.type + : base.type, + constValue: incoming.constValue !== undefined ? incoming.constValue : base.constValue, + minimum: incoming.minimum ?? base.minimum, + maximum: incoming.maximum ?? base.maximum, + pattern: incoming.pattern ?? base.pattern, + enumOptions: mergeEnumOptions(base.enumOptions, incoming.enumOptions), + }; + + if (base.itemDescriptor && incoming.itemDescriptor) { + merged.itemDescriptor = mergeFieldDescriptors(base.itemDescriptor, incoming.itemDescriptor); + } else { + merged.itemDescriptor = base.itemDescriptor ?? incoming.itemDescriptor; + } + + if (base.mapValueDescriptor && incoming.mapValueDescriptor) { + merged.mapValueDescriptor = mergeFieldDescriptors( + base.mapValueDescriptor, + incoming.mapValueDescriptor, ); + } else { + merged.mapValueDescriptor = base.mapValueDescriptor ?? incoming.mapValueDescriptor; + } - const fields: FormFieldDescriptor[] = []; - const schemaObj = schemaItem.schema ?? {}; - const conditionalRules = extractConditionalRules(schemaObj); - const ctx: ExtractionContext = { - ext, - schemaItem, - rootSchema: schemaObj, - }; + if (base.children && incoming.children) { + merged.children = mergeFieldList(base.children, incoming.children); + } else { + merged.children = base.children ?? incoming.children; + } + + // Variants (oneOf/anyOf) vs. children (properties) can arrive from different schemas, e.g. a + // shared shape schema defines `configuration` as `env` OR `alternatives`, while a scoped schema + // refines the same child paths under plain `properties` (narrowing `property` to an enum). + // Branch 1/2: one side has variants and the other has children, so push the refinements into + // each variant's children (matched by child name) rather than keeping both shapes. + // Branch 3: both sides have variants; they are paired by index, which assumes both schemas + // list their branches in the same order. + // Branch 4: only one side has variants (or neither), so keep whatever exists. + if (base.variants && !incoming.variants && incoming.children) { + merged.children = undefined; + merged.variants = base.variants.map(variant => { + if (!variant.children) { + return variant; + } + const refinedChildren = variant.children.map(vChild => { + const match = incoming.children!.find(ic => ic.name === vChild.name); + return match ? mergeFieldDescriptors(vChild, match) : vChild; + }); + return { ...variant, children: refinedChildren }; + }); + } else if (!base.variants && incoming.variants && base.children) { + merged.children = undefined; + merged.variants = incoming.variants.map(variant => { + if (!variant.children) { + return variant; + } + const refinedChildren = variant.children.map(vChild => { + const match = base.children!.find(bc => bc.name === vChild.name); + return match ? mergeFieldDescriptors(match, vChild) : vChild; + }); + return { ...variant, children: refinedChildren }; + }); + } else if (base.variants && incoming.variants) { + const mergedVariants = base.variants.map((bv, idx) => + incoming.variants![idx] ? mergeFieldDescriptors(bv, incoming.variants![idx]) : bv, + ); + // Keep any extra incoming variants instead of silently dropping them. + merged.variants = [...mergedVariants, ...incoming.variants.slice(base.variants.length)]; + } else { + merged.variants = base.variants ?? incoming.variants; + } + + return merged; +} + +/** + * A `conditionFields` entry applies to a target when each of its `appliesToKinds` / + * `appliesToInterfaceTypes` lists is either omitted (applies to everything) or contains the target. + */ +function conditionFieldApplies( + cf: ExtensionConditionField, + targetKind: string, + targetType: string, +): boolean { + const kindMatches = !cf.appliesToKinds || cf.appliesToKinds.includes(targetKind); + const typeMatches = + !cf.appliesToInterfaceTypes || cf.appliesToInterfaceTypes.includes(targetType); + return kindMatches && typeMatches; +} + +/** + * Extracts the interface-level and condition-level fields contributed by one schema for one + * `(targetKind, targetType)`. `conditionFields`, `interfaceFields` and `fieldValues` come from the + * whole resolved extension chain. `unscoped` schemas (no `appliesToKind`) are shared shapes, so + * their condition-level properties are only injected where the owning extension's + * `conditionFields` say the property applies. + */ +function extractFieldsForSchemaItem( + schemaItem: ExtensionSchemaItem, + targetKind: string, + targetType: string, + interfaceFields: ExtensionInterfaceField[], + conditionFields: ExtensionConditionField[], + fieldValues: ExtensionFieldValue[], + ownerConditionFields?: ExtensionConditionField[], + unscoped?: boolean, +): { fields: FormFieldDescriptor[]; conditionalRules: ConditionalRule[] } { + const fields: FormFieldDescriptor[] = []; + const schemaObj = schemaItem.schema ?? {}; + const conditionalRules = extractConditionalRules(schemaObj); + const ctx: ExtractionContext = { + targetKind, + targetType, + fieldValues, + rootSchema: schemaObj, + }; + + // 1. Extract Interface fields (resolve `interface` itself in case it uses `$ref`, + // which is required to uncover its nested `properties` and `required` list). + const rawIfaceSchema = schemaObj.properties?.interface; + const resolvedIface = isSchemaObject(rawIfaceSchema) + ? resolveSchema(rawIfaceSchema, schemaObj, new Set()) + : undefined; + const ifaceSchema = resolvedIface?.schema; + const ifaceProps = ifaceSchema?.properties ?? {}; + const ifaceRequiredSet = new Set(ifaceSchema?.required ?? []); + + // Later (additive) entries take precedence over earlier base entries. + const interfaceFieldsLatestFirst = [...interfaceFields].reverse(); + + for (const [propName, propVal] of Object.entries(ifaceProps)) { + if (!isSchemaObject(propVal) || 'const' in propVal) { + continue; + } - // 1. Extract Interface fields (resolve `interface` itself in case it uses `$ref`, - // which is required to uncover its nested `properties` and `required` list). - const rawIfaceSchema = schemaObj.properties?.interface; - const resolvedIface = isSchemaObject(rawIfaceSchema) - ? resolveSchema(rawIfaceSchema, schemaObj, new Set()) - : undefined; - const ifaceSchema = resolvedIface?.schema; - const ifaceProps = ifaceSchema?.properties ?? {}; - const ifaceRequiredSet = new Set(ifaceSchema?.required ?? []); - - for (const [propName, propVal] of Object.entries(ifaceProps)) { - if (!isSchemaObject(propVal) || 'const' in propVal) { + const fieldDoc = interfaceFieldsLatestFirst.find( + f => + f.targetKind === targetKind && + f.targetType === targetType && + f.name === propName, + ); + + fields.push( + extractFieldDescriptor( + propName, + `interface.${propName}`, + 'interface', + propVal, + ifaceRequiredSet.has(propName), + ctx, + resolvedIface?.refs ?? new Set(), + fieldDoc?.description, + ), + ); + } + + // 2. Extract Condition-level fields (e.g. env, configuration) + const rootProps = schemaObj.properties ?? {}; + const conditionRequiredSet = collectStaticRequiredFields(schemaObj); + + for (const [propName, propVal] of Object.entries(rootProps)) { + if (['kind', 'interface', 'name', 'optional'].includes(propName) || !isSchemaObject(propVal)) { + continue; + } + + // For unscoped shared schemas (e.g. `env-configuration`'s `configuration-shape`), + // only inject a condition-level property into scopes where the owning extension's + // `conditionFields` apply (or all scopes when the property is not restricted there). + if (unscoped && ownerConditionFields) { + const ownerEntriesForProp = ownerConditionFields.filter(cf => cf.name === propName); + if ( + ownerEntriesForProp.length > 0 && + !ownerEntriesForProp.some(cf => conditionFieldApplies(cf, targetKind, targetType)) + ) { continue; } + } - const fieldDoc = ext.spec.interfaceFields?.find( - f => - f.targetKind === schemaItem.appliesToKind && - f.targetType === schemaItem.appliesToInterfaceType && - f.name === propName, - ); + // Look up documentation across the resolved extension chain, preferring more specific + // scope matches and later (additive) extension entries over earlier base entries. + let condDoc: ExtensionConditionField | undefined; + let bestScore = -1; + for (const cf of conditionFields) { + if (cf.name !== propName || !conditionFieldApplies(cf, targetKind, targetType)) { + continue; + } + const score = (cf.appliesToKinds ? 1 : 0) + (cf.appliesToInterfaceTypes ? 1 : 0); + if (score >= bestScore) { + bestScore = score; + condDoc = cf; + } + } - fields.push( - extractFieldDescriptor( - propName, - `interface.${propName}`, - 'interface', - propVal, - ifaceRequiredSet.has(propName), - ctx, - resolvedIface?.refs ?? new Set(), - fieldDoc?.description, - ), - ); + fields.push( + extractFieldDescriptor( + propName, + propName, + 'condition', + propVal, + conditionRequiredSet.has(propName), + ctx, + new Set(), + condDoc?.description, + ), + ); + } + + return { fields, conditionalRules }; +} + +/** + * Extracts form field descriptors from a single extension definition or an array of + * extensions (resolving `spec.dependencies` chains such as `env-configuration` extending + * `common-integrations` and merging additive condition fields and schema constraints). + */ +export function extractConditionForms( + input: RuntimeConditionsExtensionDefinition | RuntimeConditionsExtensionDefinition[], + registry: RuntimeConditionsExtensionDefinition[] = [], +): ExtractedConditionForm[] { + const inputList = Array.isArray(input) ? input : [input]; + const combinedRegistryMap = new Map(); + for (const ext of [...registry, ...inputList]) { + combinedRegistryMap.set(ext.metadata.id, ext); + } + const combinedRegistry = Array.from(combinedRegistryMap.values()); + + // Resolve dependencies topologically across all requested extensions. + const activeExtensions: RuntimeConditionsExtensionDefinition[] = []; + const seenExtIds = new Set(); + for (const ext of inputList) { + const chain = resolveExtensionChain(ext, combinedRegistry); + for (const item of chain) { + if (!seenExtIds.has(item.metadata.id)) { + seenExtIds.add(item.metadata.id); + activeExtensions.push(item); + } } + } - // 2. Extract Condition-level fields (e.g. env, configuration) - const rootProps = schemaObj.properties ?? {}; - const conditionRequiredSet = collectStaticRequiredFields(schemaObj); + // Merge vocabulary across resolved extensions (base -> additive). + const kindMap = new Map(); + const interfaceTypeList: ExtensionInterfaceType[] = []; + const ifaceTypeSeen = new Set(); + const allInterfaceFields: ExtensionInterfaceField[] = []; + const allConditionFields: ExtensionConditionField[] = []; + const allFieldValues: ExtensionFieldValue[] = []; + + for (const ext of activeExtensions) { + for (const k of ext.spec.kinds ?? []) { + if (!kindMap.has(k.name)) { + kindMap.set(k.name, k); + } + } + for (const it of ext.spec.interfaceTypes ?? []) { + const key = `${it.targetKind}::${it.name}`; + if (!ifaceTypeSeen.has(key)) { + ifaceTypeSeen.add(key); + interfaceTypeList.push(it); + } + } + if (ext.spec.interfaceFields) { + allInterfaceFields.push(...ext.spec.interfaceFields); + } + if (ext.spec.conditionFields) { + allConditionFields.push(...ext.spec.conditionFields); + } + if (ext.spec.fieldValues) { + allFieldValues.push(...ext.spec.fieldValues); + } + } - for (const [propName, propVal] of Object.entries(rootProps)) { - if (['kind', 'interface', 'name', 'optional'].includes(propName) || !isSchemaObject(propVal)) { + // Determine target (kind, interfaceType) pairs from scoped schemas in topological order. + const targetPairs: Array<{ + kind: string; + interfaceType: string; + ownerExt: RuntimeConditionsExtensionDefinition; + }> = []; + const pairSeen = new Set(); + + for (const ext of activeExtensions) { + for (const schemaItem of ext.spec.schemas) { + if (!schemaItem.appliesToKind) { continue; } + if (schemaItem.appliesToInterfaceType) { + const key = `${schemaItem.appliesToKind}::${schemaItem.appliesToInterfaceType}`; + if (!pairSeen.has(key)) { + pairSeen.add(key); + targetPairs.push({ + kind: schemaItem.appliesToKind, + interfaceType: schemaItem.appliesToInterfaceType, + ownerExt: ext, + }); + } + } else { + for (const it of interfaceTypeList) { + if (it.targetKind === schemaItem.appliesToKind) { + const key = `${it.targetKind}::${it.name}`; + if (!pairSeen.has(key)) { + pairSeen.add(key); + targetPairs.push({ + kind: it.targetKind, + interfaceType: it.name, + ownerExt: ext, + }); + } + } + } + } + } + } - // 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 result: ExtractedConditionForm[] = []; - fields.push( - extractFieldDescriptor( - propName, - propName, - 'condition', - propVal, - conditionRequiredSet.has(propName), - ctx, - new Set(), - condDoc?.description, - ), - ); + for (const { kind, interfaceType, ownerExt } of targetPairs) { + const kindObj = kindMap.get(kind); + const ifaceTypeObj = interfaceTypeList.find( + i => i.name === interfaceType && i.targetKind === kind, + ); + + let mergedFields: FormFieldDescriptor[] = []; + const mergedRules: ConditionalRule[] = []; + const schemaIds: string[] = []; + const matchedSchemaIds: string[] = []; + const appliedExtensionIds: string[] = []; + const appliedExtSeen = new Set(); + + for (const ext of activeExtensions) { + for (const schemaItem of ext.spec.schemas) { + const isExactScoped = + schemaItem.appliesToKind === kind && + schemaItem.appliesToInterfaceType === interfaceType; + const isKindScoped = + schemaItem.appliesToKind === kind && !schemaItem.appliesToInterfaceType; + const isUnscoped = + !schemaItem.appliesToKind && !schemaItem.appliesToInterfaceType; + + if (!isExactScoped && !isKindScoped && !isUnscoped) { + continue; + } + + matchedSchemaIds.push(schemaItem.id); + + const { fields, conditionalRules } = extractFieldsForSchemaItem( + schemaItem, + kind, + interfaceType, + allInterfaceFields, + allConditionFields, + allFieldValues, + ext.spec.conditionFields, + isUnscoped, + ); + + if (fields.length === 0 && conditionalRules.length === 0) { + continue; + } + + mergedFields = mergeFieldList(mergedFields, fields); + mergedRules.push(...conditionalRules); + schemaIds.push(schemaItem.id); + if (!appliedExtSeen.has(ext.metadata.id)) { + appliedExtSeen.add(ext.metadata.id); + appliedExtensionIds.push(ext.metadata.id); + } + } } result.push({ - extensionId: ext.metadata.id, - version: ext.metadata.version, - kind: schemaItem.appliesToKind, + extensionId: ownerExt.metadata.id, + appliedExtensionIds, + version: ownerExt.metadata.version, + kind, kindDescription: kindObj?.description, - interfaceType: schemaItem.appliesToInterfaceType, + interfaceType, interfaceTypeDescription: ifaceTypeObj?.description, - schemaId: schemaItem.id, - fields, - conditionalRules, + schemaId: schemaIds[0] ?? matchedSchemaIds[0] ?? '', + schemaIds, + fields: mergedFields, + conditionalRules: mergedRules, }); } diff --git a/src/form/form.test.ts b/src/form/form.test.ts index 1fcf849..58ae64f 100644 --- a/src/form/form.test.ts +++ b/src/form/form.test.ts @@ -646,3 +646,516 @@ describe('spec.dependencies parsing & chain resolution', () => { ); }); }); + +const sampleCommonIntegrationsExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/rc/common-integrations/v1alpha4/runtimeconditions.extension.yaml', + version: 'v1alpha4', + description: 'Common integrations', + }, + spec: { + kinds: [ + { name: 'api', description: 'Network API calls' }, + { name: 'cache', description: 'Key/value cache' }, + ], + interfaceTypes: [ + { name: 'http', targetKind: 'api', description: 'HTTP API' }, + { name: 'webhook', targetKind: 'api', description: 'Webhook delivery' }, + { name: 'key_value', targetKind: 'cache', description: 'Key/value store' }, + ], + schemas: [ + { + id: 'api-http-interface', + appliesToKind: 'api', + appliesToInterfaceType: 'http', + schema: sampleApiHttpExtension.spec.schemas[0].schema, + }, + { + id: 'api-webhook-interface', + appliesToKind: 'api', + appliesToInterfaceType: 'webhook', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'api' }, + interface: { + type: 'object', + required: ['type'], + properties: { + type: { const: 'webhook' }, + endpoint: { type: 'string' }, + }, + }, + }, + }, + }, + { + id: 'cache-key-value-interface', + appliesToKind: 'cache', + appliesToInterfaceType: 'key_value', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'cache' }, + interface: { + type: 'object', + required: ['type'], + properties: { + type: { const: 'key_value' }, + engine: { enum: ['redis', 'memcached'] }, + }, + }, + }, + }, + }, + ], + }, +}; + +const sampleEnvConfigurationExtension: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { + id: 'https://runtimeconditions.io/extensions/rc/env-configuration/v1alpha4/runtimeconditions.extension.yaml', + version: 'v1alpha4', + description: 'Environment configuration for common integrations', + }, + spec: { + dependencies: [ + 'https://runtimeconditions.io/extensions/rc/common-integrations/v1alpha4/runtimeconditions.extension.yaml', + ], + conditionFields: [ + { + name: 'configuration', + appliesToKinds: ['api'], + appliesToInterfaceTypes: ['http'], + description: 'HTTP API connection environment variables.', + }, + { + name: 'configuration', + appliesToKinds: ['cache'], + appliesToInterfaceTypes: ['key_value'], + description: 'Cache connection environment variables.', + }, + ], + fieldValues: [ + { + field: 'configuration.env[].property', + targetKind: 'api', + targetType: 'http', + values: ['url', 'baseUrl', 'token'], + valueDescriptions: { + url: 'A full connection URL.', + baseUrl: 'The base URL for HTTP paths.', + token: 'Bearer token or API key.', + }, + }, + { + field: 'configuration.alternatives[].env[].property', + targetKind: 'api', + targetType: 'http', + values: ['url', 'baseUrl', 'token'], + valueDescriptions: { + baseUrl: 'The base URL for HTTP paths.', + }, + }, + { + field: 'configuration.env[].property', + targetKind: 'cache', + targetType: 'key_value', + values: ['url', 'database', 'token'], + valueDescriptions: { + database: 'Redis logical database number.', + }, + }, + ], + schemas: [ + { + id: 'configuration-shape', + description: 'Validates the environment configuration field shape.', + schema: { + type: 'object', + properties: { + configuration: { + type: 'object', + description: 'Give either env or alternatives.', + oneOf: [ + { + required: ['env'], + properties: { + env: { $ref: '#/$defs/envList' }, + }, + }, + { + required: ['alternatives'], + properties: { + alternatives: { + type: 'array', + items: { + type: 'object', + required: ['env'], + properties: { + env: { $ref: '#/$defs/envList' }, + }, + }, + }, + }, + }, + ], + }, + }, + $defs: { + envList: { + type: 'array', + items: { $ref: '#/$defs/envInput' }, + }, + envInput: { + type: 'object', + required: ['property', 'name'], + properties: { + property: { + type: 'string', + description: 'Connection detail carried by the env var.', + }, + name: { + type: 'string', + pattern: '^[A-Za-z_][A-Za-z0-9_]*$', + description: 'Environment variable name.', + }, + sensitive: { type: 'boolean' }, + required: { type: 'boolean' }, + }, + }, + }, + }, + }, + { + id: 'configuration-properties-api-http', + appliesToKind: 'api', + appliesToInterfaceType: 'http', + schema: { + type: 'object', + properties: { + configuration: { $ref: '#/$defs/configuration' }, + }, + $defs: { + allowedProperty: { + enum: ['url', 'baseUrl', 'token'], + }, + configuration: { + type: 'object', + properties: { + env: { + type: 'array', + items: { + type: 'object', + properties: { + property: { $ref: '#/$defs/allowedProperty' }, + }, + }, + }, + alternatives: { + type: 'array', + items: { + type: 'object', + properties: { + env: { + type: 'array', + items: { + type: 'object', + properties: { + property: { $ref: '#/$defs/allowedProperty' }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + id: 'configuration-properties-cache-key-value', + appliesToKind: 'cache', + appliesToInterfaceType: 'key_value', + schema: { + type: 'object', + properties: { + configuration: { $ref: '#/$defs/configuration' }, + }, + $defs: { + allowedProperty: { + enum: ['url', 'database', 'token'], + }, + configuration: { + type: 'object', + properties: { + env: { + type: 'array', + items: { + type: 'object', + properties: { + property: { $ref: '#/$defs/allowedProperty' }, + }, + }, + }, + }, + }, + }, + }, + }, + ], + }, +}; + +describe('Chained extension composition', () => { + it('composes env-configuration onto common-integrations (order-independent and via registry)', () => { + const formsFromArray = extractConditionForms([ + sampleEnvConfigurationExtension, + sampleCommonIntegrationsExtension, + ]); + const formsFromRegistry = extractConditionForms(sampleEnvConfigurationExtension, [ + sampleCommonIntegrationsExtension, + ]); + + expect(formsFromArray).toEqual(formsFromRegistry); + expect(formsFromArray).toHaveLength(3); + + const httpForm = formsFromArray.find( + f => f.kind === 'api' && f.interfaceType === 'http', + ); + expect(httpForm).toBeDefined(); + expect(httpForm?.extensionId).toBe(sampleCommonIntegrationsExtension.metadata.id); + expect(httpForm?.appliedExtensionIds).toEqual([ + sampleCommonIntegrationsExtension.metadata.id, + sampleEnvConfigurationExtension.metadata.id, + ]); + expect(httpForm?.schemaIds).toEqual([ + 'api-http-interface', + 'configuration-shape', + 'configuration-properties-api-http', + ]); + + // Base interface fields remain intact + expect(httpForm?.fields.find(f => f.name === 'spec')?.type).toBe('object'); + expect(httpForm?.fields.find(f => f.name === 'operations')?.type).toBe('array'); + + // Additive condition field combines unscoped shape (oneOf variants + envInput rules) + // with per-(kind, interfaceType) allowedProperty enums and fieldValues descriptions. + const configField = httpForm?.fields.find(f => f.name === 'configuration'); + expect(configField?.location).toBe('condition'); + expect(configField?.description).toBe('HTTP API connection environment variables.'); + expect(configField?.variants).toHaveLength(2); + + const envItems = configField?.variants?.[0].children?.find(c => c.name === 'env') + ?.itemDescriptor?.children; + expect(envItems?.find(c => c.name === 'name')?.pattern).toBe('^[A-Za-z_][A-Za-z0-9_]*$'); + expect(envItems?.find(c => c.name === 'name')?.required).toBe(true); + expect(envItems?.find(c => c.name === 'sensitive')?.type).toBe('boolean'); + + const httpProp = envItems?.find(c => c.name === 'property'); + expect(httpProp?.type).toBe('enum'); + expect(httpProp?.enumOptions?.map(o => o.value)).toEqual(['url', 'baseUrl', 'token']); + expect(httpProp?.enumOptions?.find(o => o.value === 'baseUrl')?.description).toBe( + 'The base URL for HTTP paths.', + ); + + const altEnvItems = configField?.variants?.[1].children + ?.find(c => c.name === 'alternatives') + ?.itemDescriptor?.children?.find(c => c.name === 'env') + ?.itemDescriptor?.children; + const altHttpProp = altEnvItems?.find(c => c.name === 'property'); + expect(altHttpProp?.type).toBe('enum'); + expect(altHttpProp?.enumOptions?.find(o => o.value === 'baseUrl')?.description).toBe( + 'The base URL for HTTP paths.', + ); + + // Separate target scope (`cache` / `key_value`) receives its own enum & descriptions + const cacheForm = formsFromArray.find( + f => f.kind === 'cache' && f.interfaceType === 'key_value', + ); + const cacheConfig = cacheForm?.fields.find(f => f.name === 'configuration'); + expect(cacheConfig?.description).toBe('Cache connection environment variables.'); + const cacheProp = cacheConfig?.variants?.[0].children + ?.find(c => c.name === 'env') + ?.itemDescriptor?.children?.find(c => c.name === 'property'); + expect(cacheProp?.enumOptions?.map(o => o.value)).toEqual(['url', 'database', 'token']); + expect(cacheProp?.enumOptions?.find(o => o.value === 'database')?.description).toBe( + 'Redis logical database number.', + ); + + // Out-of-scope (`api` / `webhook`) does NOT get `configuration` leaked from unscoped shape + const webhookForm = formsFromArray.find( + f => f.kind === 'api' && f.interfaceType === 'webhook', + ); + expect(webhookForm?.appliedExtensionIds).toEqual([ + sampleCommonIntegrationsExtension.metadata.id, + ]); + expect(webhookForm?.fields.find(f => f.name === 'configuration')).toBeUndefined(); + }); + + it('prefers specific/additive conditionFields and fieldValues while preserving base enum valueDescriptions', () => { + const baseExt: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { id: 'base-ext', version: '0.1.0' }, + spec: { + kinds: [{ name: 'api' }], + interfaceTypes: [{ name: 'http', targetKind: 'api' }], + conditionFields: [ + { name: 'mode', description: 'Generic base mode.' }, + ], + fieldValues: [ + { + field: 'mode', + targetKind: 'api', + targetType: 'http', + values: ['fast', 'safe'], + valueDescriptions: { fast: 'Low latency.', safe: 'Strict checks.' }, + }, + ], + schemas: [ + { + id: 'base-http', + appliesToKind: 'api', + appliesToInterfaceType: 'http', + schema: { + type: 'object', + required: ['kind', 'interface'], + properties: { + kind: { const: 'api' }, + interface: { type: 'object', properties: { type: { const: 'http' } } }, + mode: { enum: ['fast', 'safe'] }, + }, + }, + }, + ], + }, + }; + + const additiveExt: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { id: 'add-ext', version: '0.1.0' }, + spec: { + dependencies: ['base-ext'], + conditionFields: [ + { + name: 'mode', + appliesToKinds: ['api'], + appliesToInterfaceTypes: ['http'], + description: 'HTTP-specific mode override.', + }, + ], + fieldValues: [ + { + field: 'mode', + targetKind: 'api', + targetType: 'http', + values: ['safe'], + valueDescriptions: {}, + }, + ], + schemas: [ + { + id: 'add-http-mode', + appliesToKind: 'api', + appliesToInterfaceType: 'http', + schema: { + type: 'object', + properties: { + mode: { enum: ['safe'] }, + }, + }, + }, + ], + }, + }; + + const [form] = extractConditionForms(additiveExt, [baseExt]); + const modeField = form.fields.find(f => f.name === 'mode'); + expect(modeField?.description).toBe('HTTP-specific mode override.'); + + // Narrowed enum keeps base valueDescriptions when incoming does not repeat them + expect(modeField?.enumOptions).toEqual([ + { value: 'safe', label: 'Safe', description: 'Strict checks.' }, + ]); + }); + + it('keeps extra incoming oneOf variants when merging two schemas for the same target', () => { + const mk = (id: string, variants: object[], deps?: string[]): RuntimeConditionsExtensionDefinition => ({ + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { id: `ext-${id}`, version: '0.1.0' }, + spec: { + ...(deps ? { dependencies: deps } : { kinds: [{ name: 'k' }], interfaceTypes: [{ name: 't', targetKind: 'k' }] }), + schemas: [ + { + id, + appliesToKind: 'k', + appliesToInterfaceType: 't', + schema: { + type: 'object', + properties: { cfg: { type: 'object', oneOf: variants } }, + } as RuntimeConditionsExtensionDefinition['spec']['schemas'][number]['schema'], + }, + ], + }, + }); + const base = mk('s1', [{ required: ['a'], properties: { a: { type: 'string' } } }]); + const add = mk( + 's2', + [ + { required: ['a'], properties: { a: { type: 'string' } } }, + { required: ['b'], properties: { b: { type: 'string' } } }, + ], + ['ext-s1'], + ); + + const [form] = extractConditionForms(add, [base]); + expect(form.fields.find(f => f.name === 'cfg')?.variants).toHaveLength(2); + }); + + it('still emits a form (with a schemaId) when no schema contributes any fields', () => { + const ext: RuntimeConditionsExtensionDefinition = { + apiVersion: 'runtimeconditions.io/v1alpha1', + kind: 'RuntimeConditionsExtensionDefinition', + metadata: { id: 'empty-ext', version: '0.1.0' }, + spec: { + kinds: [{ name: 'k' }], + interfaceTypes: [{ name: 't', targetKind: 'k' }], + schemas: [ + { + id: 'empty-schema', + appliesToKind: 'k', + appliesToInterfaceType: 't', + schema: { + type: 'object', + properties: { + kind: { const: 'k' }, + interface: { type: 'object', properties: { type: { const: 't' } } }, + }, + }, + }, + ], + }, + }; + + const [form] = extractConditionForms(ext); + expect(form.schemaId).toBe('empty-schema'); + expect(form.schemaIds).toEqual([]); + expect(form.fields).toEqual([]); + }); + + it('throws a clear error when extracting an extension whose declared dependency is missing', () => { + expect(() => extractConditionForms(sampleEnvConfigurationExtension)).toThrow( + 'Missing dependency', + ); + }); +}); diff --git a/src/form/types.ts b/src/form/types.ts index c3cd759..47eaa6e 100644 --- a/src/form/types.ts +++ b/src/form/types.ts @@ -49,8 +49,9 @@ export type ExtensionDependency = string | { id: string; version?: string }; export interface ExtensionSchemaItem { id: string; - appliesToKind: string; - appliesToInterfaceType: string; + /** Omit both `appliesTo*` fields for a shared (unscoped) schema that applies to every target. */ + appliesToKind?: string; + appliesToInterfaceType?: string; description?: string; schema: JSONSchema7; } @@ -110,12 +111,16 @@ export interface ConditionalRule { export interface ExtractedConditionForm { extensionId: string; + /** Ordered extension IDs that contributed to this form (base extension -> additive extensions). */ + appliedExtensionIds?: string[]; version?: string; kind: string; kindDescription?: string; interfaceType: string; interfaceTypeDescription?: string; schemaId: string; + /** Ordered schema IDs merged into this form when multiple schemas apply. */ + schemaIds?: string[]; fields: FormFieldDescriptor[]; conditionalRules: ConditionalRule[]; }