-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathsnapshotGenerator.ts
283 lines (240 loc) · 13.1 KB
/
snapshotGenerator.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
import type { Bundle } from "./model/bundle";
import type { StructureDefinition } from "./model/structure-definition";
import type { ElementDefinition } from "./model/element-definition";
import type { ParseConformance } from "./parseConformance";
/**
* Responsible for creating snapshots on StructureDefinition resources based on the differential of the profile.
*/
export class SnapshotGenerator {
/**
* A string that represents all options possible in STU3 and R4 for choice elements, ex: value[x], effective[x], etc.)
* It is used to create a regex that tests that value[x] matches valueQuantity in an ElementDefinition.path.
*/
private readonly choiceRegexString = '(Instant|Time|Date|DateTime|Decimal|Boolean|Integer|String|Uri|Base64Binary|Code|Id|Oid|UnsignedInt|PositiveInt|Markdown|Url|Canonical|Uuid|Identifier|HumanName|Address|ContactPoint|Timing|Quantity|SimpleQuantity|Attachment|Range|Period|Ratio|CodeableConcept|Coding|SampledData|Age|Distance|Duration|Count|Money|MoneyQuantity|Annotation|Signature|ContactDetail|Contributor|DataRequirement|ParameterDefinition|RelatedArtifact|TriggerDefinition|UsageContext|Expression|Reference|Narrative|Extension|Meta|ElementDefinition|Dosage|Xhtml)';
/**
* The parser containing FHIR versioning and base profile information
*/
private readonly parser: ParseConformance;
/**
* The bundle passed into the constructor whose structure definitions should have snapshots generated
*/
private readonly bundle: Bundle;
/**
* A field that tracks what profiles have been processed during the .generate() operation, so that profiles are not processed multiple times in a single run.
*/
private processedUrls: string[] = [];
/**
*
* @param parser (ParseConformance) The parser that holds FHIR version information, and has base FHIR structures loaded in it
* @param bundle The bundle including structure definitions whose snapshot should be generated
*/
constructor(parser: ParseConformance, bundle: Bundle) {
this.parser = parser;
this.bundle = bundle;
}
/**
* Creates a bundle out of StructureDefinition resources. This is just for making it easier to pass a bundle to the constructor of this class.
* @param structureDefinitions
*/
static createBundle(...structureDefinitions: StructureDefinition[]) {
const entries = structureDefinitions.map((sd: StructureDefinition) => {
return {resource: sd};
});
const bundle: Bundle = {
resourceType: 'Bundle',
total: structureDefinitions.length,
entry: entries
};
return bundle;
}
/**
* Gets a StructureDefinition based on the url and type. First determines if the url represents a base resource in the FHIR spec, then looks through
* the bundle passed to the constructor of the class to find the structure.
* @param url The url of the profile to retrieve
* @param type The type of resource the profile constrains (ex: Composition, or Patient, or Person, etc.)
*/
private getStructureDefinition(url: string, type: string) {
const isBaseProfile = this.parser.isBaseProfile(url);
const fhirBase = isBaseProfile ?
this.parser.structureDefinitions.find(sd => sd.url.toLowerCase() === ('http://hl7.org/fhir/StructureDefinition/' + type).toLowerCase()) :
null;
if (isBaseProfile && !fhirBase) {
throw new Error(`Base profile for ${url} not found. Perhaps the structures have not been loaded?`);
}
if (fhirBase) {
return fhirBase;
}
const parentEntry = this.bundle.entry.find(entry => entry.resource.url === url);
if (!parentEntry) {
throw new Error(`Cannot find base definition "${url}" in bundle or core FHIR specification.`)
}
this.process(parentEntry.resource);
return parentEntry.resource;
}
private merge(diff: any, snapshot: any) {
const dest = JSON.parse(JSON.stringify(snapshot));
const explicitOverwrites = ['id', 'representation', 'sliceName', 'sliceIsConstraining', 'label', 'code', 'short', 'definition', 'comment', 'requirements', 'alias', 'min', 'max', 'contentReference',
'meaningWhenMissing', 'orderMeaning', 'maxLength', 'condition', 'mustSupport', 'isModifier', 'isModifierReason', 'isSummary', 'example'];
for (const eo of explicitOverwrites) {
if (diff.hasOwnProperty(eo)) dest[eo] = diff[eo];
}
if (diff.slicing && dest.slicing) {
if (diff.slicing.hasOwnProperty('discriminator')) dest.slicing.discriminator = diff.slicing.discriminator;
if (diff.slicing.hasOwnProperty('description')) dest.slicing.description = diff.slicing.description;
if (diff.slicing.hasOwnProperty('ordered')) dest.slicing.ordered = diff.slicing.ordered;
if (diff.slicing.hasOwnProperty('rules')) dest.slicing.rules = diff.slicing.rules;
} else if (diff.slicing) {
dest.slicing = diff.slicing;
}
if (diff.base && dest.base) {
if (diff.base.hasOwnProperty('path')) dest.base.path = diff.base.path;
if (diff.base.hasOwnProperty('min')) dest.base.min = diff.base.min;
if (diff.base.hasOwnProperty('max')) dest.base.max = diff.base.max;
} else if (diff.base) {
dest.base = diff.base;
}
if (diff.type && dest.type) {
for (const dt of dest.type) {
const diffType = diff.type.find(t => t.code === dt.code);
if (diffType) {
if (diffType.hasOwnProperty('profile')) dt.profile = diffType.profile;
if (diffType.hasOwnProperty('targetProfile')) dt.targetProfile = diffType.targetProfile;
if (diffType.hasOwnProperty('aggregation')) dt.aggregation = diffType.aggregation;
if (diffType.hasOwnProperty('versioning')) dt.versioning = diffType.versioning;
}
}
for (const diffType of diff.type) {
if (!dest.type.find(t => t.code === diffType.code)) {
dest.type.push(JSON.parse(JSON.stringify(diffType)));
}
}
} else if (diff.type) {
dest.type = diff.type;
}
if (diff.constraint && dest.constraint) {
for (const dc of dest.constraint) {
const diffConstraint = diff.constraint.find(c => c.key === dc.key);
if (diffConstraint) {
if (diffConstraint.hasOwnProperty('requirements')) dc.requirements = diffConstraint.requirements;
if (diffConstraint.hasOwnProperty('severity')) dc.severity = diffConstraint.severity;
if (diffConstraint.hasOwnProperty('human')) dc.human = diffConstraint.human;
if (diffConstraint.hasOwnProperty('expression')) dc.expression = diffConstraint.expression;
if (diffConstraint.hasOwnProperty('xpath')) dc.xpath = diffConstraint.xpath;
if (diffConstraint.hasOwnProperty('source')) dc.source = diffConstraint.source;
}
}
for (const diffConstraint of diff.constraint) {
if (!dest.constraint.find(c => c.key === diffConstraint.key)) {
dest.constraint.push(JSON.parse(JSON.stringify(diffConstraint)));
}
}
} else if (diff.constraint) {
dest.constraint = diff.constraint;
}
const diffKeys = Object.keys(diff);
const destKeys = Object.keys(dest);
const diffDefaultValueKey = diffKeys.find(k => k.startsWith('defaultValue'));
const diffMinValueKey = diffKeys.find(k => k.startsWith('minValue'));
const diffMaxValueKey = diffKeys.find(k => k.startsWith('maxValue'));
const diffFixedKey = diffKeys.find(k => k.startsWith('fixed'));
const diffPatternKey = diffKeys.find(k => k.startsWith('pattern'));
const destDefaultValueKey = destKeys.find(k => k.startsWith('defaultValue'));
const destMinValueKey = destKeys.find(k => k.startsWith('minValue'));
const destMaxValueKey = destKeys.find(k => k.startsWith('maxValue'));
const destFixedKey = destKeys.find(k => k.startsWith('fixed'));
const destPatternKey = destKeys.find(k => k.startsWith('pattern'));
if (diffDefaultValueKey) {
if (destDefaultValueKey) delete dest[destDefaultValueKey];
dest[diffDefaultValueKey] = diff[diffDefaultValueKey];
}
if (diffMinValueKey) {
if (destMinValueKey) delete dest[destMinValueKey];
dest[diffMinValueKey] = diff[diffMinValueKey];
}
if (diffMaxValueKey) {
if (destMaxValueKey) delete dest[destMaxValueKey];
dest[diffMaxValueKey] = diff[diffMaxValueKey];
}
if (diffFixedKey) {
if (destFixedKey) delete dest[destFixedKey];
dest[diffFixedKey] = diff[diffFixedKey];
}
if (diffPatternKey) {
if (destPatternKey) delete dest[destPatternKey];
dest[diffPatternKey] = diff[diffPatternKey];
}
return dest;
}
/**
* Generates a snapshot for the specified structure definition. If the structure definition is based on another custom profile, that
* custom profile is found in the bundle passed to the constructor, and the snapshot is generated for the base profile, as well (recursively).
* @param structureDefinition The profile to create a snapshot for
*/
private process(structureDefinition: StructureDefinition) {
if (this.parser.isBaseProfile(structureDefinition.url) || this.processedUrls.indexOf(structureDefinition.url) >= 0) {
return;
}
if (!structureDefinition.differential || !structureDefinition.differential.element || structureDefinition.differential.element.length === 0) {
throw new Error(`Structure ${structureDefinition.url} does not have a differential.`);
}
const base = this.getStructureDefinition(structureDefinition.baseDefinition, structureDefinition.type);
const newElements: ElementDefinition[] = JSON.parse(JSON.stringify(base.snapshot.element));
const matched = newElements.filter(newElement => {
if (newElement.path === structureDefinition.type) {
return false;
}
const choiceName = newElement.path.match(/^(.*\.)?(.+)\[x\]/);
const matching = structureDefinition.differential.element.filter((element) => {
const regexString = newElement.path
.replace(/\[x\]/g, this.choiceRegexString)
.replace(/\./g, '\\.');
const regex = new RegExp(regexString, 'gm');
const isMatch = regex.test(element.path);
return isMatch;
});
return matching.length > 0;
});
matched.forEach((snapshotElement) => {
const snapshotIndex = newElements.indexOf(snapshotElement);
const differentialElements = structureDefinition.differential.element.filter(element => {
const regexString = snapshotElement.path
.replace(/\[x\]/g, this.choiceRegexString)
.replace(/\./g, '\\.') +
'(\\..*)?';
const regex = new RegExp(regexString, 'gm');
return regex.test(element.path);
});
const removeElements = newElements.filter((next) => next === snapshotElement || next.path.indexOf(snapshotElement.path + '.') === 0);
removeElements.forEach(removeElement => {
const index = newElements.indexOf(removeElement);
newElements.splice(index, 1);
});
for (let i = differentialElements.length - 1; i >= 0; i--) {
const found = (base.snapshot && base.snapshot.element ? base.snapshot.element : [])
.find(e => e.path === differentialElements[i].path);
const diff = found ? this.merge(differentialElements[i], found) : differentialElements[i];
newElements.splice(snapshotIndex, 0, diff);
}
});
structureDefinition.snapshot = {
element: newElements
};
// Record this profile as having been processed so that we don't re-process it later
this.processedUrls.push(structureDefinition.url);
}
/**
* Generates a snapshot for all structure definitions in the bundle. If a structure definition in the bundle is a base FHIR structure definition, it is
* assumed the structure definition already has a snapshot, and it is ignored.
*/
generate() {
this.processedUrls = [];
if (this.bundle && this.bundle.entry) {
this.bundle.entry.forEach((entry) => {
if (!entry.resource || entry.resource.resourceType !== 'StructureDefinition') {
return;
}
this.process(entry.resource);
});
}
}
}