Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/components/api-request.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LitElement, html } from 'lit';
import { renderConditions } from './conditions.js';

import { unsafeHTML } from 'lit/directives/unsafe-html.js';
import { keyed } from 'lit/directives/keyed.js';
Expand Down Expand Up @@ -245,10 +246,11 @@ export default class ApiRequest extends LitElement {
</div>`
: ''
}
${generatedParamSchema.constraints.length || displayAllowedValuesHints || generatedParamSchema.pattern
${generatedParamSchema.constraints.length || generatedParamSchema.conditions?.length || displayAllowedValuesHints || generatedParamSchema.pattern
? html`
<div class="param-constraint" style="margin-top: 1rem;">
${generatedParamSchema.constraints.length ? html`<span style="font-weight:bold">Constraints: </span>${generatedParamSchema.constraints.join(', ')}<br>` : ''}
${renderConditions(generatedParamSchema.conditions)}
${generatedParamSchema.pattern ? html`
<div class="tooltip tooltip-replace" style="cursor: pointer; max-width: 100%; display: flex;">
<div style="white-space:nowrap; font-weight:bold; margin-right: 2px;">Pattern: </div>
Expand Down
12 changes: 12 additions & 0 deletions src/components/conditions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { html } from 'lit';

/* Renders conditional (if/then/else) constraints as indented blocks below the regular constraints */
export function renderConditions(conditions) {
if (!Array.isArray(conditions) || !conditions.length) {
return '';
}
return html`${conditions.map((condition) => html`
<div class='conditional-constraint' style='overflow-wrap:anywhere; margin:2px 8px 2px 0; padding-left:8px; border-left:2px solid var(--border-color, #ccc);'>
${condition.when}: ${condition.rules.map((rule, i) => html`${i > 0 ? ', ' : ''}<span class='bold-text'>${rule.label}${rule.value !== '' ? ': ' : ''}</span>${rule.value}`)}
</div>`)}`;
}
4 changes: 3 additions & 1 deletion src/components/request-form-table.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { renderConditions } from './conditions.js';
/* eslint-disable indent */
import { html } from 'lit';
import { toMarkdown } from '../utils/common-utils.js';
Expand Down Expand Up @@ -76,7 +77,7 @@ function generateFormRows(data, options, dataType = 'object', key = '', descript
}

function generatePrimitiveRow(rowData, parentRecursionOptions) {
const { type, format, readOrWriteOnly, constraints, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = rowData;
const { type, format, readOrWriteOnly, constraints, conditions, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = rowData;
const { key, keyLabel, keyDescr, description, dataType, isRequired, options } = parentRecursionOptions;
if (readOrWriteOnly === '🆁') {
return undefined;
Expand Down Expand Up @@ -115,6 +116,7 @@ function generatePrimitiveRow(rowData, parentRecursionOptions) {
<div class="param-constraint">
${pattern ? html`<span style="font-weight:bold">Pattern: </span>${pattern}<br/>` : ''}
${constraints.length ? html`<span style="font-weight:bold">Constraints: </span>${constraints.join(', ')}<br/>` : ''}
${renderConditions(conditions)}
${allowedValues?.filter(v => v !== '').map((v, i) => html`
${i > 0 ? '|' : html`<span style="font-weight:bold">Allowed: </span>`}
${html`
Expand Down
5 changes: 4 additions & 1 deletion src/components/schema-table.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LitElement, html, css } from 'lit';
import { renderConditions } from './conditions.js';
import { toMarkdown } from '../utils/common-utils.js';
import { unsafeHTML } from 'lit/directives/unsafe-html.js';
import FontStyles from '../styles/font-styles.js';
Expand Down Expand Up @@ -271,6 +272,7 @@ export default class SchemaTable extends LitElement {
<span class=" m-markdown-small">${unsafeHTML(toMarkdown(displayLine))}</span>
${data['::metadata']?.constraints?.length
? html`<div style='display:inline-block; line-break:anywhere; margin-right:8px'><span class='bold-text'>Constraints: </span>${data['::metadata'].constraints.join(', ')}</div><br>` : ''}
${renderConditions(data['::metadata']?.conditions)}
</div>
</div>`
: html`
Expand All @@ -292,7 +294,7 @@ export default class SchemaTable extends LitElement {
}

// For Primitive Data types
const { type, cssType, format, readOrWriteOnly, constraints, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data);
const { type, cssType, format, readOrWriteOnly, constraints, conditions, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data);
if (readOrWriteOnly === '🆁' && this.schemaHideReadOnly === 'true') {
return { result: undefined, keyLabelMaxCharacterLength: newIndentLevel };
}
Expand All @@ -319,6 +321,7 @@ export default class SchemaTable extends LitElement {
${unsafeHTML(toMarkdown(`${`${(schemaTitle || title) ? `**${schemaTitle || title}${schemaDescription || description ? ':' : ''}**` : ''} ${schemaDescription || description}` || ''}`))}
</span>
${constraints.length ? html`<div style='display:inline-block; line-break: anywhere; margin-right:8px;'><span class='bold-text'>Constraints: </span>${constraints.join(', ')}</div><br>` : ''}
${renderConditions(conditions)}
${defaultValue !== '' ? html`<div style='display:inline-block; line-break: anywhere; margin-right:8px'><span class='bold-text'>Default: </span>${defaultValue}</div><br>` : ''}
${allowedValues ? html`<div style='display:inline-block; line-break: anywhere; margin-right:8px'><span class='bold-text'>Allowed: </span>${allowedValues.filter(v => v !== null && v !== undefined).join(' ┃ ')}</div><br>` : ''}
${pattern ? html`<div style='display:inline-block; line-break: anywhere; margin-right:8px'><span class='bold-text'>Pattern: </span>${pattern}</div><br>` : ''}
Expand Down
7 changes: 5 additions & 2 deletions src/components/schema-tree.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { LitElement, html, css } from 'lit';
import { renderConditions } from './conditions.js';
import { toMarkdown } from '../utils/common-utils.js';
import { unsafeHTML } from 'lit/directives/unsafe-html.js';
import { getI18nText } from '../languages/index.js';
Expand Down Expand Up @@ -260,7 +261,8 @@ export default class SchemaTree extends LitElement {
${unsafeHTML(toMarkdown(displayLine))}
</span>
${this.schemaDescriptionExpanded ? html`
${data['::metadata']?.constraints?.length ? html`<div style='display:inline-block; line-break:anywhere; margin-right:8px'><span class='bold-text'>Constraints: </span>${data['::metadata'].constraints.join(', ')}</div><br>` : ''}` : ''}
${data['::metadata']?.constraints?.length ? html`<div style='display:inline-block; line-break:anywhere; margin-right:8px'><span class='bold-text'>Constraints: </span>${data['::metadata'].constraints.join(', ')}</div><br>` : ''}
${renderConditions(data['::metadata']?.conditions)}` : ''}
</div>
</div>
<div class="inside-bracket-wrapper">
Expand All @@ -282,7 +284,7 @@ export default class SchemaTree extends LitElement {
}

// For Primitive Data types
const { type, cssType, format, readOrWriteOnly, constraints, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data);
const { type, cssType, format, readOrWriteOnly, constraints, conditions, defaultValue, example, allowedValues, pattern, schemaDescription, schemaTitle, deprecated } = JSON.parse(data);
if (readOrWriteOnly === '🆁' && this.schemaHideReadOnly === 'true') {
return undefined;
}
Expand Down Expand Up @@ -312,6 +314,7 @@ export default class SchemaTree extends LitElement {
</span>
${this.schemaDescriptionExpanded ? html`
${constraints.length ? html`<div style='display:inline-block; line-break:anywhere; margin-right:8px'><span class='bold-text'>Constraints: </span>${constraints.join(', ')}</div><br>` : ''}
${renderConditions(conditions)}
${defaultValue !== '' ? html`<div style='display:inline-block; line-break:anywhere; margin-right:8px'><span class='bold-text'>Default: </span>${defaultValue}</div><br>` : ''}
${allowedValues ? html`<div style='display:inline-block; line-break:anywhere; margin-right:8px'><span class='bold-text'>Allowed: </span>${allowedValues.filter(v => v !== null && v !== undefined).join(' ┃ ')}</div><br>` : ''}
${pattern ? html`<div style='display:inline-block; line-break: anywhere; margin-right:8px'><span class='bold-text'>Pattern: </span>${pattern}</div><br>` : ''}
Expand Down
143 changes: 142 additions & 1 deletion src/utils/schema-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,15 @@ export function getTypeInfo(parameter, options = { includeNulls: false, enableEx
}
}

info.conditions = Array.isArray(schema['x-conditions']) ? schema['x-conditions'] : [];

info.html = JSON.stringify({
type: info.type,
format: info.format,
cssType: info.cssType,
readOrWriteOnly: info.readOrWriteOnly,
constraints: info.constraints,
conditions: info.conditions,
defaultValue: info.default,
example: info.example,
allowedValues: info.allowedValues,
Expand Down Expand Up @@ -316,14 +319,152 @@ export function isPatternProperty(label) {
* @param {number} level - recursion level
* @param {string} suffix - used for suffixing property names to avoid duplicate props during object composition
*/
function formatConditionValue(value) {
return typeof value === 'string' ? value : JSON.stringify(value);
}

/* Describes the `if` part of a conditional (if/then/else) schema in a human readable way */
function describeCondition(ifSchema) {
if (!ifSchema || typeof ifSchema !== 'object') {
return JSON.stringify(ifSchema);
}
const parts = [];
const properties = ifSchema.properties || {};
Object.keys(properties).forEach((key) => {
const prop = properties[key] || {};
if (typeof prop.const !== 'undefined') {
parts.push(`${key} = ${formatConditionValue(prop.const)}`);
} else if (Array.isArray(prop.enum)) {
parts.push(`${key} is one of ${prop.enum.map(formatConditionValue).join(' | ')}`);
} else if (prop.pattern) {
parts.push(`${key} matches ${prop.pattern}`);
} else {
parts.push(`${key} matches ${JSON.stringify(prop)}`);
}
});
(ifSchema.required || []).filter((key) => !properties[key]).forEach((key) => parts.push(`${key} is set`));
const rest = omitKeys(ifSchema, ['properties', 'required', 'type']);
if (Object.keys(rest).length) {
parts.push(JSON.stringify(rest));
}
return parts.join(' and ') || JSON.stringify(ifSchema);
}

/* Describes the constraints a `then`/`else` branch adds to a single property */
function describeConditionalPropertyConstraints(propSchema) {
if (!propSchema || typeof propSchema !== 'object') {
return [{ label: 'Schema', value: JSON.stringify(propSchema) }];
}
const rules = [];
const add = (label, value) => rules.push({ label, value: String(value) });
if (typeof propSchema.const !== 'undefined') { add('Must be', formatConditionValue(propSchema.const)); }
if (Array.isArray(propSchema.enum)) { add('Allowed', propSchema.enum.map(formatConditionValue).join(' ┃ ')); }
if (propSchema.pattern) { add('Pattern', propSchema.pattern); }
if (propSchema.format) { add('Format', propSchema.format); }
if (propSchema.type) { add('Type', [].concat(propSchema.type).join(' ┃ ')); }
if (propSchema.minLength !== undefined) { add('Min length', propSchema.minLength); }
if (propSchema.maxLength !== undefined) { add('Max length', propSchema.maxLength); }
if (propSchema.minimum !== undefined) { add('Minimum', propSchema.minimum); }
if (propSchema.maximum !== undefined) { add('Maximum', propSchema.maximum); }
if (propSchema.exclusiveMinimum !== undefined) { add('Exclusive minimum', propSchema.exclusiveMinimum); }
if (propSchema.exclusiveMaximum !== undefined) { add('Exclusive maximum', propSchema.exclusiveMaximum); }
if (propSchema.minItems !== undefined) { add('Min items', propSchema.minItems); }
if (propSchema.maxItems !== undefined) { add('Max items', propSchema.maxItems); }
if (propSchema.not) { add('Not', JSON.stringify(propSchema.not)); }
return rules.length ? rules : [{ label: 'Schema', value: JSON.stringify(propSchema) }];
}

function omitKeys(obj, keys) {
return Object.keys(obj).filter((key) => !keys.includes(key)).reduce((acc, key) => Object.assign(acc, { [key]: obj[key] }), {});
}

function isPureConditional(subSchema) {
return subSchema && typeof subSchema === 'object' && Object.prototype.hasOwnProperty.call(subSchema, 'if')
&& Object.keys(subSchema).every((key) => ['if', 'then', 'else', 'description', 'title', '$comment'].includes(key));
}

/* Moves if/then/else rules of an object schema (directly or as allOf entries) onto the affected properties as human readable constraints */
function applyConditionals(rawSchema) {
if (!rawSchema || typeof rawSchema !== 'object') {
return rawSchema;
}
const conditionals = [];
if (Object.prototype.hasOwnProperty.call(rawSchema, 'if')) {
conditionals.push(rawSchema);
}
const allOfConditionals = Array.isArray(rawSchema.allOf) ? rawSchema.allOf.filter(isPureConditional) : [];
conditionals.push(...allOfConditionals);
if (!conditionals.length) {
return rawSchema;
}

const schema = omitKeys(rawSchema, ['if', 'then', 'else']);
if (allOfConditionals.length) {
const remainingAllOf = rawSchema.allOf.filter((s) => !isPureConditional(s));
if (remainingAllOf.length) {
schema.allOf = remainingAllOf;
} else {
delete schema.allOf;
}
}
const properties = Object.assign({}, schema.properties);
const objectConditions = [];
// A condition is { when, rules: [{ label, value }] }, rules with the same `when` are grouped
const addCondition = (target, when, rules) => {
const existing = target.find((c) => c.when === when);
if (existing) {
existing.rules.push(...rules);
} else {
target.push({ when, rules: [...rules] });
}
};
const addPropertyCondition = (key, when, rules) => {
if (!properties[key]) {
addCondition(objectConditions, when, rules.map((r) => ({ label: `${key} ${r.label.toLowerCase()}`, value: r.value })));
return;
}
properties[key] = Object.assign({}, properties[key]);
properties[key]['x-conditions'] = (properties[key]['x-conditions'] || []).map((c) => ({ when: c.when, rules: [...c.rules] }));
addCondition(properties[key]['x-conditions'], when, rules);
};
const applyBranch = (branch, conditionText) => {
if (!branch || typeof branch !== 'object') {
return;
}
const branchProperties = branch.properties || {};
Object.keys(branchProperties).forEach((key) => {
addPropertyCondition(key, `If ${conditionText}`, describeConditionalPropertyConstraints(branchProperties[key]));
});
(branch.required || []).forEach((key) => addPropertyCondition(key, `If ${conditionText}`, [{ label: 'Required', value: '' }]));
const rest = omitKeys(branch, ['properties', 'required']);
if (Object.keys(rest).length) {
addCondition(objectConditions, `If ${conditionText}`, [{ label: 'Schema', value: JSON.stringify(rest) }]);
}
};
conditionals.forEach((conditional) => {
const conditionText = describeCondition(conditional.if);
applyBranch(conditional.then, conditionText);
applyBranch(conditional.else, `not (${conditionText})`);
});

if (schema.properties) {
schema.properties = properties;
}
if (objectConditions.length) {
schema['x-conditions'] = [].concat(schema['x-conditions'] || [], objectConditions);
}
return schema;
}

export function schemaInObjectNotation(rawSchema, options, level = 0, suffix = '') {
const { allOf, oneOf, anyOf, items: arrayItemsSchema, properties: schemaProperties, patternProperties: schemaPatternProperties, ...schema } = (rawSchema || {});
const { allOf, oneOf, anyOf, items: arrayItemsSchema, properties: schemaProperties, patternProperties: schemaPatternProperties, ...schema } = (applyConditionals(rawSchema) || {});
const propertyType = schema.type;
const metadata = { constraints: [] };
if (schema.uniqueItems) { metadata.constraints.push('Requires unique items'); }
if (typeof schema.minItems === 'number' || typeof schema.maxItems === 'number') {
metadata.constraints.push(`Length: [${schema.minItems || 0}${schema.maxItems ? ', ' : '+'}${schema.maxItems || ''}]`);
}
if (Array.isArray(schema['x-conditions'])) { metadata.conditions = schema['x-conditions']; }

if (allOf) {
// If allOf is an array of multiple elements, then all the keys makes a single object
Expand Down
19 changes: 19 additions & 0 deletions tests/schema-utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,22 @@ test('schema-utils.js getTypeInfo shows the unique items constraint only for arr
expect(getTypeInfo({ type: 'string[]┃null', uniqueItems: true }).constraints).to.eql(['Requires unique items']);
t.pass();
});

test('schema-utils.js schemaInObjectNotation shows if/then rules from allOf as constraints on the affected property', (t) => {
const schema = {
type: 'object',
properties: { id: { type: 'string', pattern: '[a-z_]+' }, type: { type: 'string', enum: ['HALL', 'STAND'] } },
allOf: [
{ if: { properties: { type: { const: 'HALL' } }, required: ['type'] }, then: { properties: { id: { pattern: '^hall_' } } } },
{ if: { properties: { type: { const: 'STAND' } } }, then: { required: ['id'] }, else: { properties: { id: { maxLength: 5 } } } }
]
};
const result = schemaInObjectNotation(schema, {});
t.deepEqual(Object.keys(result).filter((k) => !k.startsWith('::')), ['id', 'type']);
t.deepEqual(JSON.parse(result.id).constraints, []);
t.deepEqual(JSON.parse(result.id).conditions, [
{ when: 'If type = HALL', rules: [{ label: 'Pattern', value: '^hall_' }] },
{ when: 'If type = STAND', rules: [{ label: 'Required', value: '' }] },
{ when: 'If not (type = STAND)', rules: [{ label: 'Max length', value: '5' }] }
]);
});
Loading