generated from Exabyte-io/template-definitions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschemas.ts
293 lines (264 loc) · 8.64 KB
/
schemas.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { JSONSchema } from "@exabyte-io/esse.js/schema";
import { JSONSchema7Definition } from "json-schema";
import forEach from "lodash/forEach";
import hasProperty from "lodash/has";
import isEmpty from "lodash/isEmpty";
import { JSONSchemasInterface } from "../JSONSchemasInterface";
export * from "@exabyte-io/esse.js/lib/js/esse/schemaUtils";
export const schemas: { [key: string]: string } = {};
interface SubstitutionMap {
[key: string]: string;
}
interface Parameter {
key: string;
values: string[] | boolean[];
namesMap?: SubstitutionMap;
}
interface Node {
data: {
key: string;
value: string;
name: string;
};
staticOptions?: Parameter[];
children?: Node[];
[otherKey: string]: unknown;
}
/**
* Returns previously registered schema for InMemoryEntity
* @returns
*/
export function getSchemaByClassName(className: string) {
return schemas[className] ? JSONSchemasInterface.schemaById(schemas[className]) : null;
}
/**
* Register additional Entity classes to be resolved with jsonSchema property
* @param {String} className - class name derived from InMemoryEntity
* @param {String} schemaId - class schemaId
*/
export function registerClassName(className: string, schemaId: string) {
schemas[className] = schemaId;
}
export function typeofSchema(schema: JSONSchema) {
if (schema?.type) {
return schema.type;
}
if (hasProperty(schema, "properties")) {
return "object";
}
if (hasProperty(schema, "items")) {
return "array";
}
}
function extractEnumOptions(nodes?: Node[]) {
if (!nodes || !nodes.length) return {};
return {
enum: nodes.map((node) => node.data.value),
enumNames: nodes.map((node) => node.data.name),
};
}
function substituteName(value: unknown, mapping?: SubstitutionMap) {
if (typeof value !== "string") {
return JSON.stringify(value);
}
return mapping ? mapping[value] : value;
}
function createStaticFields(node: Node) {
if (!node.staticOptions) return {};
const fields: { [key: string]: { enum: string[] | boolean[]; enumNames: string[] } } = {};
node.staticOptions
.filter((o) => o.key && o.values)
.forEach((o) => {
fields[o.key] = {
enum: o.values,
enumNames: o.values.map((v) => substituteName(v, o.namesMap)),
};
});
return fields;
}
/**
* @summary Recursively generate `dependencies` for RJSF schema based on tree.
* @param {Object[]} nodes - Array of nodes (e.g. `[tree]` or `node.children`)
* @returns {{}|{dependencies: {}}}
*/
export function buildDependencies(nodes?: Node[]): JSONSchema {
const isEveryTerminal = nodes && nodes.every((node) => !node.children?.length);
const isWithStaticOptions = nodes && nodes.some((node) => node?.staticOptions);
if (!nodes || !nodes.length || !nodes[0].data) return {};
const parentKey = nodes[0].data.key;
const cases = nodes.map((node) => {
const childKey = node.children?.length && node.children[0].data.key;
return {
properties: {
[parentKey]: extractEnumOptions([node]),
...(childKey ? { [childKey]: extractEnumOptions(node.children) } : {}),
...createStaticFields(node),
},
...buildDependencies(node.children),
};
});
return cases.length && (!isEveryTerminal || isWithStaticOptions)
? {
dependencies: {
[parentKey]: {
oneOf: cases,
},
},
}
: {};
}
interface Props {
// Schema
schema?: JSONSchema;
// Schema id (takes precedence over `schema` when both are provided)
schemaId?: string;
// Array of nodes
nodes: Node[];
// Whether properties in main schema should be modified (add `enum` and `enumNames`)
modifyProperties?: boolean;
}
/**
* Combine schema and dependencies block for usage with react-jsonschema-form (RJSF)
*/
export function getSchemaWithDependencies({
schema = {},
schemaId,
nodes,
modifyProperties = false,
}: Props): JSONSchema {
const mainSchema = schemaId ? JSONSchemasInterface.schemaById(schemaId) || {} : schema;
if (!isEmpty(mainSchema) && typeofSchema(mainSchema) !== "object") {
console.error("getSchemaWithDependencies() only accepts schemas of type 'object'");
return {};
}
// RJSF does not automatically render dropdown widget if `enum` is not present
if (modifyProperties && nodes.length) {
const mod = {
[nodes[0].data.key]: {
...extractEnumOptions(nodes),
},
};
forEach(mod, (extraFields, key) => {
if (mainSchema.properties && hasProperty(mainSchema, `properties.${key}`)) {
mainSchema.properties[key] = {
...(mainSchema.properties[key] as object),
...extraFields,
};
}
});
}
return {
...(schemaId ? mainSchema : schema),
...buildDependencies(nodes),
};
}
const DEFAULT_GENERATIVE_KEYS = ["name"];
interface NamedEntity {
name: string;
}
const baseSchema = (definitionName: string, enforceUnique = true): JSONSchema => {
return {
type: "array",
items: {
$ref: `#/definitions/${definitionName}`,
},
uniqueItems: enforceUnique,
};
};
const defaultNamedEntitySchema = (name: string) => {
return {
properties: {
name: {
type: "string",
enum: [name],
},
},
} as JSONSchema;
};
/**
* Retrieves an RJSF schema with an id matching the provided name
*/
export const schemaByNamedEntityName = (name: string): JSONSchema | undefined => {
const translatedName = name.replace(/_/g, "-");
const schema = JSONSchemasInterface.matchSchema({
$id: {
$regex: `${translatedName}$`,
},
});
return schema;
};
/*
* Filters an RJSF schema for all the properties used to generate a new schema
*/
const filterForGenerativeProperties = (schema: JSONSchema) => {
if (!schema.properties || typeof schema.properties !== "object") return {};
const generativeFilter = ([propertyKey, property]: [string, JSONSchema7Definition]) => {
return (
(typeof property === "object" && // JSONSchema7Definition type allows for boolean
property?.$comment &&
property.$comment.includes("isGenerative:true")) ||
DEFAULT_GENERATIVE_KEYS.includes(propertyKey)
);
};
// @ts-ignore : JSONSchema6 and JSONSchema7 are incompatible
const generativeProperties = Object.entries(schema.properties).filter(generativeFilter);
const properties = Object.fromEntries(generativeProperties);
return { properties, required: Object.keys(properties) } as JSONSchema; // all included fields are required based on isGenerative flag
};
/*
* Filters an RJSF schema for all the properties used to generate a new schema
*/
const buildNamedEntitiesDependencies = (entities: NamedEntity[]) => {
return {
dependencies: {
name: {
oneOf: entities.map((entity) => {
const schema =
schemaByNamedEntityName(entity.name) ||
defaultNamedEntitySchema(entity.name);
return {
...filterForGenerativeProperties(schema),
};
}),
},
},
};
};
/**
* Generates an RJSF definition with a list of subschemas as enumerated options
*/
const buildNamedEntitiesDefinitions = (
entities: NamedEntity[],
defaultEntity: NamedEntity,
entityType: string,
) => {
if (!Array.isArray(entities) || entities.length < 1) return {};
return {
definitions: {
[entityType]: {
properties: {
name: {
type: "string",
enum: entities.map((entity) => entity.name),
default: defaultEntity.name || entities[0].name,
},
},
...buildNamedEntitiesDependencies(entities),
},
},
};
};
/*
* Generates an RJSF scheme with a list of subschemas as enumerated options
*/
export const buildNamedEntitySchema = (
entities: NamedEntity[],
defaultEntity: NamedEntity,
entityType: string,
enforceUnique = true,
): JSONSchema => {
return {
...buildNamedEntitiesDefinitions(entities, defaultEntity, entityType),
...baseSchema(entityType, enforceUnique),
} as JSONSchema;
};