-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathgenerate-code.ts
More file actions
1082 lines (954 loc) · 29.4 KB
/
generate-code.ts
File metadata and controls
1082 lines (954 loc) · 29.4 KB
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { namedTypes as n, builders as b, ASTNode } from 'ast-types';
import { print, parse } from 'recast';
// TODO this is a strange type - shouldn't it be n.statement?
import { StatementKind } from 'ast-types/gen/kinds';
import {
getBuilderName,
getInterfaceName,
getTypeName,
sortKeys,
} from './util';
import { Mapping, MappingSpec, ProfileSpec, Schema } from './types';
import { generateType } from './codegen/generate-types';
import generateValues, { ValueSets } from './codegen/values';
const RESOURCE_NAME = 'resource';
const INPUT_NAME = 'props';
type Options = {
simpleSignatures?: boolean;
/** List of type definitions which can be imported from FHIR */
fhirTypes?: Record<string, true>;
/** base adaptor name to generate types and builders from */
base?: string;
/** valuesets schemas */
valueSets?: any;
// generate metadata including profile urls
generateMeta?: boolean;
};
const getDataTypeBuilderName = (schema: Schema): string | false => {
if (schema.type.includes('Identifier')) {
return 'identifier';
}
if (schema.type.includes('Reference')) {
return 'Reference';
}
return false;
};
const getProfileBuilderName = (profile: ProfileSpec): string =>
`build_${profile.id}`.replace(/-/g, '_');
const generateCode = (
schema: Record<string, Schema[]>,
mappings: MappingSpec = {},
options: Options = {},
): { builders: string; profiles: Record<string, string>; values?: string } => {
const statements: n.Statement[] = [];
const profiles = {};
// This tells us where to load FHIR types from
const fhirImportPath = options.base
? `@openfn/language-${options.base}`
: '../fhir';
if (options.base) {
statements.push(
b.exportAllDeclaration(b.stringLiteral('./datatypes'), null),
);
} else {
statements.push(
b.exportAllDeclaration(b.stringLiteral('./datatypes'), null),
);
}
const imports: n.Statement[] = [];
// Import values so that they get initialised with the builders
if (options.valueSets) {
imports.push(b.importDeclaration([], b.stringLiteral(`./values`)));
}
// generate a builder for each profile
const orderedResources = Object.keys(schema).sort();
for (const resourceType of orderedResources) {
// Note that the schema has already applied include/exclude filters
const sortedProfiles = sortKeys(schema[resourceType]) as Schema[];
for (const profile of sortedProfiles) {
// import this builder
const name = getProfileBuilderName(profile);
const iface = getInterfaceName(profile);
imports.push(
b.importDeclaration(
[
b.importDefaultSpecifier(b.identifier(name)),
b.importSpecifier(b.identifier(iface)),
],
b.stringLiteral(`./profiles/${profile.id}`),
),
);
profiles[profile.id] = generateProfile(
profile,
Object.assign(
{
initialiser: mappings.initialiser,
typeShorthands: mappings.typeShorthands,
},
mappings.overrides?.[resourceType],
),
options.fhirTypes,
fhirImportPath,
options.valueSets,
options.base,
options.generateMeta,
);
}
// Generate the signatures and entrypoint funtion
statements.push(
...generateEntry(
getTypeName(sortedProfiles[0]),
resourceType,
schema[resourceType],
options.simpleSignatures,
mappings.propsToIgnoreInDocs,
options.valueSets,
),
);
}
const program = b.program([...imports, ...statements]);
const builders = print(program).code;
const values = generateValues(options.valueSets);
return { builders, profiles, values };
};
// TODO maybe I need this
type FhirImports = {
types: Record<string, true>;
path: string;
// datatypes: any;
};
const generateProfile = (
profile: Schema,
mappings: MappingSpec,
fhirTypes: Record<string, true> = {},
fhirImport = '../fhir',
valueSets: ValueSets = {},
base?: string,
generateMeta?: boolean,
) => {
const statements = [];
const overrides = Object.assign({}, mappings.any, mappings[profile.id]);
statements.push(
b.importDeclaration(
[b.importDefaultSpecifier(b.identifier('_'))],
b.stringLiteral('lodash'),
),
);
// TODO this import isn't so nice
// Maybe we ONLY take base here and the rest is derived?
if (base) {
statements.push(
b.importDeclaration(
[b.importSpecifier(b.identifier('b'), b.identifier('dt'))],
b.stringLiteral(`@openfn/language-${base}`),
),
);
statements.push(
b.importDeclaration(
[b.importSpecifier(b.identifier('builders'), b.identifier('FHIR'))],
b.stringLiteral(fhirImport),
'type',
),
);
} else {
statements.push(
b.importDeclaration(
[b.importNamespaceSpecifier(b.identifier('dt'))],
b.stringLiteral('../datatypes'),
),
);
statements.push(
b.importDeclaration(
[b.importNamespaceSpecifier(b.identifier('FHIR'))],
b.stringLiteral(fhirImport),
'type',
),
);
}
// TODO It would be better to define this once and import it,
// but that's a bit harder to work out with Lightning I think?
statements.push(
b.tsTypeAliasDeclaration(
b.identifier('MaybeArray<T>'),
b.tsUnionType([
b.tsTypeReference(b.identifier('T')),
b.tsTypeReference(b.identifier('T[]')),
]),
),
);
const typedef = generateType(
profile,
{
...mappings,
overrides,
},
fhirTypes,
valueSets,
);
statements.push(typedef);
const fn = generateBuilder(
profile,
overrides,
mappings.initialiser,
generateMeta,
);
statements.push(b.exportDefaultDeclaration(fn));
// TODO export default
const program = b.program(statements);
return print(program).code;
};
export default generateCode;
// For each prop in the schema, generate a prop in jsdocs
const generateJsDocs = (
schema: Schema[],
ignore: string[] = [],
valueSets: ValueSets,
) => {
const props: string[] = [];
// TODO for now, just generate for the first schema
// Later we have to generate a superset of all props and provide variations
const profile = schema[0];
const validProps = Object.keys(profile.props)
.filter(p => !ignore.includes(p))
.sort();
for (const propName of validProps) {
const prop = profile.props[propName];
let humanType;
let desc = prop.desc;
if (prop.valueSet) {
humanType = 'string';
desc += '. Accepts all values from ' + prop.valueSet;
} else if (prop.type.includes('Coding')) {
// If this is a Coding, we should represent it as a string
// and if possible, lit the values
humanType = 'string';
if (prop.valueSet) {
const values = Object.keys(valueSets[prop.valueSet] || {});
if (values.length) {
desc += `. Accepts values: ${values.join(', ')}`;
}
}
} else {
humanType = prop.type.join('|');
}
props.push(`{${humanType}} [props.${propName}] - ${desc}`);
}
return props.map(p => ` * @param ${p}`).join('\n');
};
// TODO this function is quite different depending on the number of profiles
// if 1 profile, it's a simple function
// if 2+ profiles, we need interfaces and a mapping
// easiest way right now is probably to duplicate:
// simple builder vs interfaced builder
const generateEntry = (
name: string,
resourceType: string,
profiles: Schema[],
simpleSignatures?: boolean,
propsToIgnoreInDocs: string[] = [],
valueSets: ValueSets = {},
) => {
// TODO I think I want to rip out the simple signatures flag and just say:
// for any schema with only a single profile, make it optional to pass the profile string
if (profiles.length === 1) {
simpleSignatures = true;
}
const declarations = [];
const statements = [];
// generate signatures for each profile
for (const profile of profiles) {
const signature = b.exportDeclaration(
false,
b.tsDeclareFunction(b.identifier(getBuilderName(resourceType)), [
b.tsParameterProperty(
b.identifier.from({
name: 'type',
typeAnnotation: b.tsTypeAnnotation(
b.tsLiteralType(b.stringLiteral(profile.id)),
),
}),
),
b.tsParameterProperty(
b.identifier.from({
name: INPUT_NAME,
typeAnnotation: b.tsTypeAnnotation(
b.tsTypeReference(b.identifier(getInterfaceName(profile))),
),
}),
),
]),
);
declarations.push(signature);
}
const map = b.variableDeclaration('const', [
b.variableDeclarator(
b.identifier('mappings'),
b.objectExpression(
profiles.map(profile =>
b.objectProperty(
b.stringLiteral(profile.id),
b.identifier(getProfileBuilderName(profile)),
),
),
),
),
]);
statements.push(map);
if (simpleSignatures) {
// TODO how do we know the default type?
const handleOptionalType = parse(`// Handle optional type parameter
if (typeof type !== "string") {
props = type;
type = "${profiles[0].id}";
}`);
statements.push(...handleOptionalType.program.body);
const override = b.exportDeclaration(
false,
b.tsDeclareFunction(
b.identifier(getBuilderName(resourceType)),
[
b.tsParameterProperty(
// TODO need a full type for this. Where do we get it?
b.identifier.from({
name: INPUT_NAME,
typeAnnotation: b.tsTypeAnnotation(
b.tsTypeReference(b.identifier(getInterfaceName(profiles[0]))),
),
}),
),
],
// What is the return type?
// It's not the same as our props - it's a fhir object
// b.tsTypeAnnotation(b.tsTypeReference(b.identifier('Patient')))
),
);
declarations.push(override);
}
const mapper = parse(`
if (type in mappings) {
return mappings[type](props)
}
throw new Error(\`Error: profile "\${type}" not recognised\`)
`);
statements.push(...mapper.program.body);
const impl = b.exportDeclaration(
false,
b.functionDeclaration(
b.identifier(getBuilderName(resourceType)),
[
b.tsParameterProperty(
b.identifier.from({
name: 'type',
typeAnnotation: b.tsTypeAnnotation(b.tsAnyKeyword()),
}),
),
b.tsParameterProperty(
// TODO need a full type for this. Where do we get it?
b.identifier.from({
name: INPUT_NAME,
typeAnnotation: b.tsTypeAnnotation(b.tsAnyKeyword()),
optional: true,
}),
),
],
b.blockStatement(statements),
),
);
let comment;
if (profiles.length > 1) {
comment = parse(`/**
* Create a ${resourceType} resource.
* @public
* @function
* @param {string} type - A profile type: one of ${profiles.map(p => `\`${p.id}\``).join(', ')}
* @param {object} props - Properties to apply to the resource (includes common and custom properties).
${generateJsDocs(profiles, propsToIgnoreInDocs, valueSets)}
*/
`);
} else {
comment = parse(`/**
* Create a ${resourceType} resource.
* @public
* @function
* @param {object} props - Properties to apply to the resource (includes common and custom properties).
${generateJsDocs(profiles, propsToIgnoreInDocs, valueSets)}
*/
`);
}
declarations[0].comments = comment.program.comments;
declarations[0].comments![0].leading = true;
declarations.push(impl);
return declarations;
};
const generateBuilder = (
schema,
mappings,
initialiser: (r: any) => void,
generateMeta: boolean,
) => {
const body: StatementKind[] = [];
body.push(initResource(schema.type, generateMeta && schema.url));
body.push(...mapProps(schema, mappings));
if (initialiser) {
try {
const init = parse(initialiser.toString());
// Pull the statements out of the function body
// and add them in-line
const fn = init.program.body[0].expression;
body.push(...fn.body.body.filter(n => n.type !== 'ReturnStatement'));
} catch (e) {
console.error(`Failed to process initialiser for ${schema.type}`);
console.error(e);
}
}
body.push(returnResource());
const fn = b.functionDeclaration(
null,
[
b.identifier.from({
name: INPUT_NAME,
typeAnnotation: b.tsTypeAnnotation(
b.tsTypeReference(
b.identifier('Partial'),
b.tsTypeParameterInstantiation([
b.tsTypeReference(b.identifier(getInterfaceName(schema))),
]),
),
),
}),
],
b.blockStatement(body),
);
return fn;
};
const mapProps = (schema, mappings) => {
const props: StatementKind[] = [];
for (const key in schema.props) {
// skip this prop if the mappings is false (or its meta, which is special)
if (mappings[key] === false || key === 'meta') {
continue;
}
const spec = schema.props[key] as Schema;
if (spec) {
if (spec.extension) {
props.push(mapExtension(key, mappings[key], spec));
} else if (spec.isComposite) {
// TODO a composite def may also have a typedef - how do we handle this?
// maybe it's ok just to assign the top object hey?
props.push(mapComposite(key, mappings[key], spec));
} else if (spec.typeDef) {
props.push(mapTypeDef(key, mappings[key], spec));
} else if (spec.type.includes('Coding')) {
props.push(mapCoding(key, mappings[key], spec));
} else if (
// spec.type.includes('Code') ||
spec.type.includes('CodeableConcept')
) {
props.push(mapCodeableConcept(key, mappings[key], spec));
} else {
// TODO what happens if the type is like `reference | identifier`? Such contrasting types?
if (spec.type.includes('Reference')) {
props.push(mapReference(key, mappings[key], spec));
} else if (spec.type.includes('Identifier')) {
props.push(mapIdentifier(key, mappings[key] || {}, spec));
}
}
} else {
console.log('WARNING: schema does not define property', key);
}
}
// now handle any mapped keys
for (const key in mappings) {
if (mappings[key]) {
if (mappings[key].extension) {
props.push(mapExtension(key, mappings[key]));
}
// TODO handle other types of mappings
}
}
return props;
};
// This will generate a.b or a['z-y']
// allowing easy handling of property names that are not safe identifiers
const safelyRefProp = (objectName, propName) => {
if (/[\-\.\\\/\#\@\{\}\[\]]/.test(propName)) {
return b.memberExpression(b.identifier(objectName), b.literal(propName));
}
return b.memberExpression(b.identifier(objectName), b.identifier(propName));
};
// This runs a block of code only if the named property is in the input object
// TODO: don't use key in, use number || boolean || truthy
const ifPropInInput = (
prop: string,
statements: StatementKind[],
alts?: StatementKind[],
inputName = INPUT_NAME,
) =>
b.ifStatement(
b.unaryExpression(
'!',
b.callExpression(
b.memberExpression(b.identifier('_'), b.identifier('isNil')),
[safelyRefProp(inputName, prop)],
),
),
b.blockStatement(statements),
alts ? b.blockStatement(alts) : null,
);
// assigns SOMETHING to a prop on the input
const assignToInput = (prop: string, rhs) =>
b.expressionStatement(
b.assignmentExpression('=', safelyRefProp(RESOURCE_NAME, prop), rhs),
);
// this generates a statement to add the default
const addDefaults = (propName: string, mapping: Mapping, schema: Schema) => {
const defaults = mapping?.defaults ?? schema?.defaults;
if (defaults) {
// generate an assignment statement using the mappings
const parsed = parse(
`${RESOURCE_NAME}.${propName} = ${JSON.stringify(defaults)};`,
{},
);
return parsed.program.body;
}
};
// A simple prop will just take what's in the input and map it right across
// Mapping rules could add extra complications here, like aliasing and converting
const mapSimpleProp = (propName: string, mapping: Mapping, schema: Schema) => {
// This is the actual assignment
const assignProp = assignToInput(
propName,
b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName)),
);
const elseStatement = addDefaults(propName, mapping, schema);
return ifPropInInput(propName, [assignProp], elseStatement);
};
// map a type def (ie, a nested object) property by property
// TODO this is designed to handle singleton and array types
// The array stuff adds a lot of complication and I need tests on both formats
const mapTypeDef = (propName: string, mapping: Mapping, schema: Schema) => {
const statements: any[] = [];
statements.push(
b.variableDeclaration('let', [
b.variableDeclarator(
b.identifier('src'),
b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName)),
),
]),
);
// Map the property name into an underscore var so it's always save
// ie, what if hte prop is called `class` or `break` or `for`?
const safePropName = `_${propName}`;
if (schema.isArray) {
// if this is an array type, we should force the input to be an array
const ast = parse('if (!Array.isArray(src)) { src = [src]; }');
statements.push(...ast.program.body);
statements.push(
b.expressionStatement(
b.assignmentExpression(
'=',
b.memberExpression(
b.identifier(RESOURCE_NAME),
b.identifier(propName),
),
b.arrayExpression([]),
),
),
);
} else {
statements.push(
b.variableDeclaration('let', [
b.variableDeclarator(
b.identifier(safePropName),
b.objectExpression([b.spreadProperty(b.identifier('src'))]),
),
]),
);
}
const assignments: any[] = [];
const inputName = schema.isArray ? 'item' : 'src';
for (const prop in schema.typeDef) {
const body: any[] = [];
const alts = null;
const spec = schema.typeDef[prop];
const sourceValue = safelyRefProp(inputName, prop);
if (spec.extension) {
body.push(
b.expressionStatement(
b.callExpression(
b.memberExpression(
b.identifier('dt'),
b.identifier('addExtension'),
),
[
b.identifier(safePropName),
b.stringLiteral(spec.extension.url),
sourceValue,
],
),
),
);
assignments.push(ifPropInInput(prop, body, alts, inputName));
} else {
// Don't bother to explicitly map simple assignments
// TODO: handle datatypes and special things here too
}
}
if (schema.hasSystem) {
assignments.push(
b.expressionStatement(
b.assignmentExpression(
'=',
b.identifier(safePropName),
b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('mapSystems')),
[b.identifier(safePropName)],
),
),
),
);
}
if (schema.isArray) {
assignments.splice(
0,
0,
b.variableDeclaration('let', [
b.variableDeclarator(
b.identifier(safePropName),
useBuilderWithValueSet(schema),
),
]),
);
assignments.push(
b.expressionStatement(
b.callExpression(
b.memberExpression(
b.memberExpression(
b.identifier(RESOURCE_NAME),
b.identifier(propName),
),
b.identifier('push'),
),
[b.identifier(safePropName)],
),
),
);
statements.push(
b.forOfStatement(
b.variableDeclaration('let', [b.identifier('item')]),
b.identifier('src'),
b.blockStatement(assignments),
),
);
} else {
statements.push(...assignments);
statements.push(
b.expressionStatement(
b.assignmentExpression(
'=',
b.memberExpression(
b.identifier(RESOURCE_NAME),
b.identifier(propName),
),
b.identifier(safePropName),
),
),
);
}
let elseStmnt;
const d = addDefaults(propName, mapping, schema);
if (d) {
elseStmnt = d;
}
return ifPropInInput(propName, statements, elseStmnt);
};
const mapCodeableConcept = (
propName: string,
mapping: Mapping,
schema: Schema,
) => {
const statements: StatementKind[] = [];
if (schema.isArray) {
const mexp = `${INPUT_NAME}.${propName}`; // ie resource.code
const ast = parse(`if (!Array.isArray(${mexp})) { ${mexp} = [${mexp}]; }`);
statements.push(ast.program.body[0]);
}
// the right hand side of the assignment
let rhs: any = b.memberExpression(
b.identifier(INPUT_NAME),
b.identifier(propName),
);
if (schema.valueSet) {
// If there's a value map involved, lookup the value before assignment
rhs = b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('lookupValue')),
[b.stringLiteral(schema.valueSet), rhs],
);
}
const callBuilder = b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('concept')),
[rhs],
);
statements.push(assignToInput(propName, callBuilder));
// TODO maybe this is option driven?
statements.push(
b.expressionStatement(
b.callExpression(
b.memberExpression(
b.identifier('dt'),
b.identifier('ensureConceptText'),
),
[b.memberExpression(b.identifier('resource'), b.identifier(propName))],
),
),
);
let elseStmnt;
const d = addDefaults(propName, mapping, schema);
if (d) {
elseStmnt = d;
}
return ifPropInInput(propName, statements, elseStmnt);
};
// in a coding, the value could be a string (which we map)
// or a Coding object, or a builder shorthand
const mapCoding = (propName: string, mapping: Mapping, schema: Schema) => {
const statements: StatementKind[] = [];
statements.push(
b.variableDeclaration('let', [
b.variableDeclarator(
b.identifier('src'),
b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName)),
),
]),
);
// TODO do we need to support an array of values for coding?
// Probably, but not today
if (schema.valueSet) {
// call the value map
const ast = parse(
`if (typeof src === 'string') {
src = dt.lookupValue('${schema.valueSet}', src);
}`,
);
statements.push(ast.program.body[0]);
}
statements.push(
assignToInput(
propName,
b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('coding')),
[b.identifier('src')],
),
),
);
let elseStmnt;
const d = addDefaults(propName, mapping, schema);
if (d) {
elseStmnt = d;
}
return ifPropInInput(propName, statements, elseStmnt);
};
// // Map a property of the input to some extension
// // This will add a new object to the Extension array
// const mapExtension = (propName: string, mapping: Mapping) => {
// const callBuilder = b.expressionStatement(
// b.callExpression(
// b.memberExpression(b.identifier('dt'), b.identifier('addExtension')),
// [
// b.identifier(RESOURCE_NAME),
// b.stringLiteral(mapping.extension),
// b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName)),
// ],
// ),
// );
// return ifPropInInput(propName, [callBuilder]);
// };
const mapReference = (propName: string, _mapping: Mapping, schema: Schema) => {
const statements: StatementKind[] = [];
if (schema.isArray) {
const mexp = `${INPUT_NAME}.${propName}`; // ie resource.identifier
const ast = parse(`if (!Array.isArray(${mexp})) { ${mexp} = [${mexp}]; }`);
statements.push(ast.program.body[0]);
}
const callBuilder = b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('reference')),
[b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName))],
);
statements.push(assignToInput(propName, callBuilder));
return ifPropInInput(propName, statements);
};
const mapComposite = (propName: string, _mapping: Mapping, _schema: Schema) => {
const deleteKey = b.unaryExpression(
'delete',
b.memberExpression(b.identifier(RESOURCE_NAME), b.identifier(propName)),
);
const callBuilder = b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('composite')),
// util.composite(resource, 'x'', input.x)
[
b.identifier(RESOURCE_NAME),
b.stringLiteral(propName),
b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName)),
],
);
return ifPropInInput(
propName,
[deleteKey, callBuilder].map(b.expressionStatement),
);
};
const mapExtension = (propName: string, _mapping: Mapping, schema: Schema) => {
const statements: StatementKind[] = [];
// first extract the prop
statements.push(
b.variableDeclaration('let', [
b.variableDeclarator(
b.identifier('src'),
b.memberExpression(b.identifier(INPUT_NAME), b.identifier(propName)),
),
]),
);
// Map any values associated with the input
if (schema.valueSet) {
const ast = parse(
`if (typeof src === 'string') {
src = dt.lookupValue('${schema.valueSet}', src);
}`,
);
statements.push(ast.program.body[0]);
}
// run a typed builder
// note that (right now) syntax overlap is subtly different to the main mapping functoins
// So, we duplicate!
if (schema.type.includes('CodeableConcept')) {
statements.push(
b.expressionStatement(
b.assignmentExpression(
'=',
b.identifier('src'),
b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('concept')),
[b.identifier('src')],
),
),
),
);
// TODO maybe this is option driven?
statements.push(
b.expressionStatement(
b.callExpression(
b.memberExpression(
b.identifier('dt'),
b.identifier('ensureConceptText'),
),
[b.identifier('src')],
),
),
);
} else {
console.warn(
`WARNING: Failed to generate typed builder ${propName} for extension ${schema.extension}`,
);
}
// TODO handle other types
// Remove the original prop from the resource (which was added in the initial spread
statements.push(
b.expressionStatement(
b.unaryExpression(
'delete',
b.memberExpression(b.identifier('resource'), b.identifier(propName)),
),
),
);
// add the extension
statements.push(
b.expressionStatement(
b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('addExtension')),
[
b.identifier('resource'),
b.stringLiteral(schema.extension),
b.identifier('src'),
],
),
),
);
return ifPropInInput(propName, statements);
};
const mapIdentifier = (name: string, _mapping: Mapping, schema: Schema) => {
const defaultSystem = schema.defaults?.system;
const statements: StatementKind[] = [];
const createIdentifier = b.callExpression(
b.memberExpression(b.identifier('dt'), b.identifier('identifier')),