-
Notifications
You must be signed in to change notification settings - Fork 3
/
SchemaView.ts
753 lines (697 loc) · 23.2 KB
/
SchemaView.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
import { readFile } from 'fs/promises'
import { parse } from 'yaml'
import {
SchemaDefinition, Definition, ClassDefinition, SlotDefinition, ClassDefinitionName, SlotDefinitionName,
EnumDefinition, TypeDefinition, EnumDefinitionName, TypeDefinitionName, Element, SchemaDefinitionName, ElementName
}
from "./MetaModel";
import Namespaces from './Namespaces';
import path from 'path'
import fetch from 'cross-fetch'
import { klona } from 'klona'
export type Name = ClassDefinitionName | SlotDefinitionName
export type OrderedBy = "rank" | "lexical" | "preserve"
function isDefinition(x: Element | Name ): x is Element {
return x!= undefined && (<Element>x).name !== undefined;
}
function orderLexically(elements: Map<ElementName, Element>): Map<ElementName, Element> {
const orderedElements: Map<ElementName, Element> = new Map()
const orderedElementNames = [...elements.keys()].sort()
for (const name of orderedElementNames) {
orderedElements.set(name, elements.get(name))
}
return orderedElements
}
function orderRank(elements: Map<ElementName, Element>): Map<ElementName, Element> {
const rankedElements: Map<Number, Element> = new Map()
const unrankedElements: Map<ElementName, Element> = new Map()
for (const [name, element] of elements) {
if (element.rank !== undefined) {
rankedElements.set(element.rank, element)
} else {
unrankedElements.set(name, element)
}
}
const orderedRanks = [...rankedElements.keys()].sort()
const orderedElements: Map<ElementName, Element> = new Map()
for (const rank of orderedRanks) {
const element = rankedElements.get(rank)
orderedElements.set(element.name, element)
}
for (const [name, element] of unrankedElements) {
orderedElements.set(name, element)
}
return orderedElements
}
function closure<T>(f: (x: T) => T[], x: T, reflexive=true): T[] {
let rv = []
if (reflexive) {
rv = [x]
}
let visited = []
let todo = [x]
while (todo.length > 0) {
let i = todo.pop()
visited.push(i)
let vals = f(i)
for (let v of vals) {
if (!visited.includes(v)) {
todo.push(v)
rv.push(v)
}
}
}
return rv
}
function notFalse(v) {
return v == undefined || v == true
}
async function loadSchema(file: string, baseDir: string | null = null): Promise<SchemaDefinition> {
const isRemote = /^https?:\/\//.test(file)
let content
if (isRemote) {
const response = await fetch(file)
if (!response.ok) {
throw new Error('Could not fetch: ' + file)
}
content = await response.text()
} else {
if (baseDir) {
file = path.join(baseDir, file)
}
content = await readFile(file, 'utf-8')
}
const schema: SchemaDefinition = parse(content)
schema.source_file = file
setNameFromKey(schema, SUBSETS)
setNameFromKey(schema, TYPES)
setNameFromKey(schema, ENUMS)
setNameFromKey(schema, SLOTS)
setNameFromKey(schema, CLASSES)
if (schema.classes) {
Object.values(schema.classes).forEach(cls => setNameFromKey(cls, 'attributes'))
}
return schema
}
function setNameFromKey(schema: SchemaDefinition | ClassDefinition, slotName: SlotDefinitionName): void {
if (!schema) {
return
}
const elements: {[key: ElementName]: Element} = schema[slotName]
if (elements) {
for (const [key, element] of Object.entries(elements)) {
if (element) {
if (!element.name) {
element.name = key
}
} else {
elements[key] = { name: key }
}
}
}
}
interface TraversalSpecificOptions {
mixins?: boolean,
is_a?: boolean,
reflexive?: boolean
}
interface ImportOptions {
imports?: boolean,
}
interface WalkerOptions {
mutate?: boolean,
}
export type TraversalOptions = TraversalSpecificOptions & ImportOptions
const SLOTS = 'slots'
const CLASSES = 'classes'
const ENUMS = 'enums'
const SUBSETS = 'subsets'
const TYPES = 'types'
/**
* operations over schemas
*/
export class SchemaView {
schema: SchemaDefinition
virtual_schema: SchemaDefinition
schemaMap: Map<SchemaDefinitionName, SchemaDefinition>
_namespaces: Namespaces
_importsLoaded: boolean
modifications: number
static async load(file: string, loadImportsClosure: boolean = false) {
const schema = await loadSchema(file)
const view = new SchemaView(schema)
if (loadImportsClosure) {
await view.loadImportsClosure()
}
return view
}
constructor(schema: SchemaDefinition) {
this.schema = schema
this.schemaMap = new Map([[this.schema.name, this.schema]])
this.modifications = 0
this._importsLoaded = false
setNameFromKey(this.schema, SUBSETS)
setNameFromKey(this.schema, TYPES)
setNameFromKey(this.schema, ENUMS)
setNameFromKey(this.schema, SLOTS)
setNameFromKey(this.schema, CLASSES)
if (this.schema.classes) {
Object.values(this.schema.classes).forEach(cls => setNameFromKey(cls, 'attributes'))
}
this._index()
}
_index(): void {
// TODO: merge imports
this.virtual_schema = this.schema
}
/**
* retrieve a ClassDefinition by its name
*
* @param name - class or class name
*/
getClass(name: ClassDefinitionName | ClassDefinition, imports: boolean = true): ClassDefinition {
if (isDefinition(name)) {
return name
}
return this.allClasses('preserve', imports).get(name)
}
/**
* retrieve a EnumDefinition by its name
*
* @param name - enum or enum name
*/
getEnum(name: EnumDefinitionName | EnumDefinition): EnumDefinition {
if (isDefinition(name)) {
return name
}
else {
return this.virtual_schema.enums[name]
}
}
/**
* retrieve a TypeDefinition by its name
*
* @param name - Type or Type name
*/
getType(name: TypeDefinitionName | TypeDefinition, imports: boolean = true): TypeDefinition {
if (isDefinition(name)) {
return name
}
return this.allTypes(imports).get(name)
}
/**
* retrieve a SlotDefinition by its name
*
* @param name - class or class name
*/
getSlot(name: SlotDefinitionName | SlotDefinition): SlotDefinition {
if (isDefinition(name)) {
return name
}
else {
const slot = this.allSlots().get(name)
if (slot) {
return slot
}
else {
for (const [cn, c] of this.allClasses()) {
if (c.attributes != undefined) {
for (const [k, attr] of Object.entries(c.attributes)) {
if (k == name) {
return attr
}
}
}
}
throw 'No such slot: ' + name
}
}
}
/**
* All direct parents
*
* @param elt
* @param opts
*/
parents(elt: ClassDefinition | SlotDefinition, opts: TraversalOptions): Name[] {
let parents = []
if (notFalse(opts.is_a) && elt && elt.is_a != undefined) {
parents = [elt.is_a]
}
if (notFalse(opts.mixins) && elt && elt.mixins != undefined) {
parents = parents.concat(elt.mixins)
}
return parents
}
/**
* Finds all ancestors for a class or slot
*
* @param elt
* @param opts
*/
ancestors(elt: ClassDefinition | SlotDefinition, opts: TraversalOptions): ClassDefinitionName[] {
let t = this
let f = function (x) {
return t.parents(x, opts)
}
return closure(f, elt)
}
/**
* All direct parents
*
* @param elt
* @param opts
*/
classParents(elt: ClassDefinitionName | ClassDefinition, opts: TraversalOptions): ClassDefinitionName[] {
let c = this.getClass(elt)
return this.parents(c, opts)
}
/**
* All direct parents
*
* @param elt
* @param opts
*/
slotParents(elt: SlotDefinitionName | SlotDefinition, opts: TraversalOptions = {}): SlotDefinitionName[] {
let s = this.getSlot(elt)
if (s == undefined) {
throw 'No such slot: ' + elt
}
return this.parents(s, opts)
}
/**
* Finds all ancestors for a class
*
* @param elt
* @param opts
*/
classAncestors(elt: ClassDefinitionName | ClassDefinition, opts: TraversalOptions = {}): ClassDefinitionName[] {
let t = this
let f = function (x) {
return t.classParents(x, opts)
}
return closure(f, elt)
}
/**
* Finds all ancestors for a slot
*
* @param elt
* @param opts
*/
slotAncestors(elt: SlotDefinitionName | SlotDefinition, opts: TraversalOptions = {}): SlotDefinitionName[] {
let t = this
let f = function (x) {
return t.slotParents(x, opts)
}
return closure(f, elt)
}
typeParents(typeName: TypeDefinitionName | TypeDefinition, imports: boolean = true): TypeDefinitionName[] {
const typ = this.getType(typeName, imports)
if (typ.typeof) {
return [typ.typeof]
} else {
return []
}
}
typeAncestors(typeName: TypeDefinitionName, opts: TraversalOptions = {}): TypeDefinitionName[] {
return closure((t) => this.typeParents(t, opts.imports), typeName)
}
mergeSlot(base_slot: SlotDefinition, to_merge: SlotDefinition, isReflexive = false): SlotDefinition {
if (to_merge == undefined) {
return base_slot
}
for (const [k, v] of Object.entries(to_merge)) {
if (!(k in base_slot) || base_slot[k] == undefined) {
// base slot has priority
base_slot[k] = v
}
}
return base_slot
}
/**
* Inferred slot for a slot/class combo
*
* @param slot_name
* @param class_name
* @param opts
*/
inducedSlot(slot_name: SlotDefinitionName, class_name: ClassDefinitionName | ClassDefinition,
opts: TraversalOptions = {}): SlotDefinition {
if (class_name == undefined) {
//throw 'Undefined class for slot:' + slot_name
}
if (slot_name == undefined) {
throw 'No such slot ' + slot_name
}
const cls_ancs = this.classAncestors(class_name)
const slot_ancs = this.slotAncestors(slot_name)
let islot = {}
this.mergeSlot(islot, this.getSlot(slot_name))
for (let cls_anc of cls_ancs) {
let isReflexive = cls_anc == class_name
let cls_anc_obj = this.getClass(cls_anc)
if (cls_anc_obj == undefined) {
throw 'No such ancestor ' + cls_anc + ' of ' + class_name
}
if (cls_anc_obj.attributes != undefined) {
if (slot_name in cls_anc_obj.attributes) {
this.mergeSlot(islot, cls_anc_obj.attributes[slot_name])
}
}
if (cls_anc_obj.slot_usage != undefined) {
if (slot_name in cls_anc_obj.slot_usage) {
this.mergeSlot(islot, cls_anc_obj.slot_usage[slot_name], isReflexive)
}
}
}
for (let slot_anc of slot_ancs) {
this.mergeSlot(islot, this.getSlot(slot_anc))
}
return islot
}
inducedType(typeName: TypeDefinitionName): TypeDefinition {
const typ = klona(this.getType(typeName))
if (typ.typeof) {
const parent = this.inducedType(typ.typeof)
if (!typ.uri) {
typ.uri = parent.uri
}
if (!typ.base) {
typ.base = parent.base
}
if (!typ.repr) {
typ.repr = parent.repr
}
}
return typ
}
classSlots(className: ClassDefinitionName, imports: boolean = true, direct: boolean = false, attributes: boolean = true): SlotDefinitionName[] {
let ancestors: ClassDefinitionName[]
if (direct) {
ancestors = [className]
} else {
ancestors = this.classAncestors(className, { imports })
}
const slots = new Set<SlotDefinitionName>()
for (const ancestorName of ancestors) {
const ancestor = this.getClass(ancestorName)
if (ancestor.slots) {
for (const ancestorSlot of ancestor.slots) {
slots.add(ancestorSlot)
}
}
if (attributes && ancestor.attributes) {
for (const attributeName of Object.keys(ancestor.attributes)) {
slots.add(attributeName)
}
}
}
return Array.from(slots)
}
classInducedSlots(className: ClassDefinitionName, imports: boolean = true): SlotDefinition[] {
return this.classSlots(className).map(slotName => this.inducedSlot(slotName, className, { imports }))
}
/**
* Get the range object for a slot
*
* @param slot
*/
slotRange(slot: SlotDefinition): ClassDefinition | EnumDefinition | TypeDefinition {
let r = slot.range
if (this.schema.classes && r in this.schema.classes) {
return this.getClass(r)
}
else if (this.schema.enums && r in this.schema.enums) {
return this.getClass(r)
}
else if (this.schema.types && r in this.schema.types) {
return this.getType(r)
}
else {
//throw 'Unknown range: ' + r + ' for slot: '+slot.name
}
}
namespaces() {
if (this._namespaces) {
return this._namespaces
}
this._namespaces = new Namespaces()
for (const schema of this.schemaMap.values()) {
for (const [prefix, reference] of Object.entries(schema.prefixes)) {
if (typeof reference === 'string') {
this._namespaces.set(prefix, reference)
} else {
this._namespaces.set(reference.prefix_prefix, reference.prefix_reference)
}
}
}
if (this.schema.default_curi_maps) {
for (const cmap of this.schema.default_curi_maps) {
this._namespaces.addPrefixmap(cmap, false)
}
}
return this._namespaces
}
async loadImport(imp: string, fromSchema: SchemaDefinition = null): Promise<SchemaDefinition> {
if (!fromSchema) {
fromSchema = this.schema
}
let sname = imp
if (sname.includes(':')) {
sname = this.namespaces().uriFor(imp)
}
let fileName = sname + '.yaml'
let baseDir
if (fromSchema.source_file) {
baseDir = path.dirname(fromSchema.source_file)
}
return loadSchema(fileName, baseDir)
}
async loadImportsClosure(): Promise<void> {
if (this._importsLoaded) {
return
}
if (!this.schemaMap) {
this.schemaMap = new Map([[this.schema.name, this.schema]])
}
const visited = new Set()
const todo = [this.schema.name]
while (todo.length > 0) {
const schemaName = todo.pop()
visited.add(schemaName)
if (!this.schemaMap.has(schemaName)) {
const importedSchema = await this.loadImport(schemaName)
this.schemaMap.set(schemaName, importedSchema)
}
const schema = this.schemaMap.get(schemaName)
if (schema.imports) {
for (const i of schema.imports) {
if (!visited.has(i)) {
todo.push(i)
}
}
}
}
for (const schema of this.schemaMap.values()) {
for (const key of [CLASSES, ENUMS, SLOTS, SUBSETS, TYPES]) {
if (schema[key]) {
let element: Element
for (element of Object.values(schema[key])) {
if (element) {
element.from_schema = schema.id
}
}
}
}
if (schema.classes) {
for (const cls of Object.values(schema.classes)) {
if (cls && cls.attributes) {
for (const attr of Object.values(cls.attributes)) {
if (attr) {
attr.from_schema = schema.id
}
}
}
}
}
}
this._importsLoaded = true
}
importsClosure(traverse: boolean = true): SchemaDefinitionName[] {
if (!traverse) {
return [this.schema.name]
}
if (!this._importsLoaded) {
console.warn('importsClosure called with traverse = true, but loadImportsClosure has not been called')
}
return [...this.schemaMap.keys()]
}
inSchema(elementName: ElementName): SchemaDefinitionName {
const map = this.elementBySchemaMap()
return map.get(elementName)
}
elementBySchemaMap(imports: boolean = true): Map<ElementName, SchemaDefinitionName> {
const map = new Map()
const schemas = this.allSchema(imports)
for (const schema of schemas) {
for (const typeKey of [CLASSES, SLOTS, TYPES, ENUMS, SUBSETS]) {
if (schema[typeKey]) {
for (const key of Object.keys(schema[typeKey])) {
map.set(key, schema.name)
}
}
}
if (schema.classes) {
for (const cls of Object.values(schema.classes)) {
if (cls && cls.attributes) {
for (const key of Object.keys(cls.attributes)) {
map.set(key, schema.name)
}
}
}
}
}
return map
}
_getElements(slotName: string, imports: boolean = true): Map<ElementName, Element> {
const schemas = this.allSchema(imports)
const elements: Map<ElementName, Element> = new Map()
for (const schema of schemas) {
if (schema[slotName]) {
for (const [name, cls] of Object.entries(schema[slotName])) {
elements.set(name, cls)
}
}
}
return elements
}
allSchema(imports: boolean = true): SchemaDefinition[] {
const schemaNames = this.importsClosure(imports)
return schemaNames.map(name => this.schemaMap.get(name))
}
allClasses(orderedBy: OrderedBy = "preserve", imports: boolean = true): Map<ClassDefinitionName, ClassDefinition> {
const classes = this._getElements(CLASSES, imports)
let orderedClasses
if (orderedBy === 'lexical') {
orderedClasses = orderLexically(classes)
} else if (orderedBy === 'rank') {
orderedClasses = orderRank(classes)
} else {
orderedClasses = classes
}
return orderedClasses
}
allTypes(imports: boolean = true): Map<TypeDefinitionName, TypeDefinition> {
return this._getElements(TYPES, imports)
}
allEnums(imports: boolean = true): Map<EnumDefinitionName, EnumDefinition> {
return this._getElements(ENUMS, imports)
}
allSlots(imports: boolean = true, attributes: boolean = true, orderedBy: OrderedBy = 'preserve'): Map<SlotDefinitionName, SlotDefinition> {
const slots = klona(this._getElements(SLOTS, imports))
if (attributes) {
for (const cls of this.allClasses().values()) {
if (cls && cls.attributes) {
for (const [attrName, attr] of Object.entries(cls.attributes)) {
if (!slots.has(attrName)) {
slots.set(attrName, attr)
}
}
}
}
}
let orderedSlots: Map<SlotDefinitionName, SlotDefinition>
if (orderedBy === 'lexical') {
orderedSlots = orderLexically(slots)
} else if (orderedBy === 'rank') {
orderedSlots = orderRank(slots)
} else {
orderedSlots = slots
}
return orderedSlots
}
async mergeImports() {
await this.loadImportsClosure()
const toMerge = this.allSchema(true).filter(s => s !== this.schema)
for (const other of toMerge) {
this.mergeSchema(other)
}
this.schema.imports = null
this.setModified()
}
mergeSchema(schema: SchemaDefinition): void {
if (schema.prefixes) {
this.schema.prefixes = {
...schema.prefixes,
...this.schema.prefixes
}
}
if (schema.classes) {
this.schema.classes = {
...schema.classes,
...this.schema.classes
}
}
if (schema.slots) {
this.schema.slots = {
...schema.slots,
...this.schema.slots
}
}
if (schema.types) {
this.schema.types = {
...schema.types,
...this.schema.types
}
}
if (schema.enums) {
this.schema.enums = {
...schema.enums,
...this.schema.enums
}
}
this.setModified()
}
setModified(): void {
this.modifications += 1
}
// DEPRECATED
walk(obj: any, func: Function,
cls: ClassDefinition | SlotDefinition | EnumDefinition = null,
isCollection = false,
opts: WalkerOptions = {mutate: false}): any {
if (obj instanceof Array) {
if (isCollection) {
return obj.map(x => this.walk(x, func, cls))
}
else {
throw 'Array in non-multivalued context: '+JSON.stringify(obj)
}
}
else if (typeof obj == 'object') {
let nuObj = {}
if (isCollection) {
// TODO: check not inlined as list
for (const [k, v] of Object.entries(obj)) {
nuObj[k] = this.walk(v, func, cls, )
}
}
else {
for (const [k, v] of Object.entries(obj)) {
const slot = this.inducedSlot(k, cls)
const range = slot.range
const range_cls = this.getClass(range) // TODO: enums
// TODO! tsgen should not make string here
nuObj[k] = this.walk(v, func, range_cls, slot.multivalued)
}
}
return func(nuObj, cls)
}
else {
if (isCollection) {
throw 'Expected array '+JSON.stringify(obj)
}
return func(obj, cls)
}
}
}