Skip to content
Merged
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
3 changes: 0 additions & 3 deletions examples/on-the-fly/kbv-condition-diagnosis/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ if (require.main === module) {
treeShake: {
"kbv.basis": {
"https://fhir.kbv.de/StructureDefinition/KBV_PR_Base_Condition_Diagnosis": {},
// Referenced as a Condition.subject target; included so the
// reference type resolves to the profile's base resource.
"https://fhir.kbv.de/StructureDefinition/KBV_PR_Base_Patient": {},
},
},
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ def validate(self) -> dict[str, list[str]]:
errors.extend(validate_reference(self._resource, profile_name, "derivedFrom", ["DocumentReference","ImagingStudy","Media","MolecularSequence","QuestionnaireResponse","Observation"]))
errors.extend(validate_slice_cardinality(self._resource, profile_name, "component", {"code":{"coding":[{"system":"http://loinc.org","code":"8480-6"}]}}, "systolic", 1, 1))
errors.extend(validate_slice_cardinality(self._resource, profile_name, "component", {"code":{"coding":[{"system":"http://loinc.org","code":"8462-4"}]}}, "diastolic", 1, 1))
errors.extend(validate_reference(self._resource, profile_name, "performer", ["PractitionerRole","USCoreCareTeam","USCoreOrganizationProfile","Patient","USCorePractitionerProfile","USCoreRelatedPersonProfile"]))
errors.extend(validate_reference(self._resource, profile_name, "performer", ["PractitionerRole","CareTeam","Organization","Patient","Practitioner","RelatedPerson"]))
warnings.extend(validate_enum(self._resource, profile_name, "category", ["social-history","vital-signs","imaging","laboratory","procedure","survey","exam","therapy","activity"]))
warnings.extend(validate_enum(self._resource, profile_name, "code", ["2708-6","29463-7","3140-1","3150-0","3151-8","39156-5","59408-5","59575-1","59576-9","77606-2","8287-5","8289-1","8302-2","8306-3","8310-5","8462-4","8478-0","8480-6","8867-4","9279-1","9843-4"]))
warnings.extend(validate_enum(self._resource, profile_name, "dataAbsentReason", ["unknown","asked-unknown","temp-unknown","not-asked","asked-declined","masked","not-applicable","unsupported","as-text","error","not-a-number","negative-infinity","positive-infinity","not-performed","not-permitted"]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def validate(self) -> dict[str, list[str]]:
errors.extend(validate_choice_required(self._resource, profile_name, ["effectiveDateTime","effectivePeriod"]))
errors.extend(validate_reference(self._resource, profile_name, "hasMember", ["MolecularSequence","QuestionnaireResponse","Observation"]))
errors.extend(validate_reference(self._resource, profile_name, "derivedFrom", ["DocumentReference","ImagingStudy","Media","MolecularSequence","QuestionnaireResponse","Observation"]))
errors.extend(validate_reference(self._resource, profile_name, "performer", ["PractitionerRole","USCoreCareTeam","USCoreOrganizationProfile","Patient","USCorePractitionerProfile","USCoreRelatedPersonProfile"]))
errors.extend(validate_reference(self._resource, profile_name, "performer", ["PractitionerRole","CareTeam","Organization","Patient","Practitioner","RelatedPerson"]))
errors.extend(validate_excluded(self._resource, profile_name, "valueCodeableConcept"))
errors.extend(validate_excluded(self._resource, profile_name, "valueString"))
errors.extend(validate_excluded(self._resource, profile_name, "valueBoolean"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ def validate(self) -> dict[str, list[str]]:
errors.extend(validate_choice_required(self._resource, profile_name, ["effectiveDateTime","effectivePeriod"]))
errors.extend(validate_reference(self._resource, profile_name, "hasMember", ["MolecularSequence","QuestionnaireResponse","Observation"]))
errors.extend(validate_reference(self._resource, profile_name, "derivedFrom", ["DocumentReference","ImagingStudy","Media","MolecularSequence","QuestionnaireResponse","Observation"]))
errors.extend(validate_reference(self._resource, profile_name, "performer", ["PractitionerRole","USCoreCareTeam","USCoreOrganizationProfile","Patient","USCorePractitionerProfile","USCoreRelatedPersonProfile"]))
errors.extend(validate_reference(self._resource, profile_name, "performer", ["PractitionerRole","CareTeam","Organization","Patient","Practitioner","RelatedPerson"]))
warnings.extend(validate_enum(self._resource, profile_name, "category", ["social-history","vital-signs","imaging","laboratory","procedure","survey","exam","therapy","activity"]))
warnings.extend(validate_enum(self._resource, profile_name, "code", ["2708-6","29463-7","3140-1","3150-0","3151-8","39156-5","59408-5","59575-1","59576-9","77606-2","8287-5","8289-1","8302-2","8306-3","8310-5","8462-4","8478-0","8480-6","8867-4","9279-1","9843-4"]))
warnings.extend(validate_enum(self._resource, profile_name, "dataAbsentReason", ["unknown","asked-unknown","temp-unknown","not-asked","asked-declined","masked","not-applicable","unsupported","as-text","error","not-a-number","negative-infinity","positive-infinity","not-performed","not-permitted"]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ export class USCoreBloodPressureProfile {
...validateSliceFields(res, profileName, "component", {"code":{"coding":[{"system":"http://loinc.org","code":"8480-6"}]}}, "systolic", ["valueQuantity"]),
...validateSliceCardinality(res, profileName, "component", {"code":{"coding":[{"system":"http://loinc.org","code":"8462-4"}]}}, "diastolic", 1, 1),
...validateSliceFields(res, profileName, "component", {"code":{"coding":[{"system":"http://loinc.org","code":"8462-4"}]}}, "diastolic", ["valueQuantity"]),
...validateReference(res, profileName, "performer", ["PractitionerRole","USCoreCareTeam","USCoreOrganizationProfile","Patient","USCorePractitionerProfile","USCoreRelatedPersonProfile"]),
...validateReference(res, profileName, "performer", ["PractitionerRole","CareTeam","Organization","Patient","Practitioner","RelatedPerson"]),
],
warnings: [
...validateEnum(res, profileName, "category", ["social-history","vital-signs","imaging","laboratory","procedure","survey","exam","therapy","activity"]),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ export class USCoreBodyWeightProfile {
...validateChoiceProhibited(res, profileName, ["effectiveTiming","effectiveInstant"]),
...validateReference(res, profileName, "hasMember", ["MolecularSequence","QuestionnaireResponse","Observation"]),
...validateReference(res, profileName, "derivedFrom", ["DocumentReference","ImagingStudy","Media","MolecularSequence","QuestionnaireResponse","Observation"]),
...validateReference(res, profileName, "performer", ["PractitionerRole","USCoreCareTeam","USCoreOrganizationProfile","Patient","USCorePractitionerProfile","USCoreRelatedPersonProfile"]),
...validateReference(res, profileName, "performer", ["PractitionerRole","CareTeam","Organization","Patient","Practitioner","RelatedPerson"]),
...validateChoiceProhibited(res, profileName, ["valueCodeableConcept","valueString","valueBoolean","valueInteger","valueRange","valueRatio","valueSampledData","valueTime","valueDateTime","valuePeriod"]),
],
warnings: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ export class USCoreVitalSignsProfile {
...validateChoiceProhibited(res, profileName, ["effectiveTiming","effectiveInstant"]),
...validateReference(res, profileName, "hasMember", ["MolecularSequence","QuestionnaireResponse","Observation"]),
...validateReference(res, profileName, "derivedFrom", ["DocumentReference","ImagingStudy","Media","MolecularSequence","QuestionnaireResponse","Observation"]),
...validateReference(res, profileName, "performer", ["PractitionerRole","USCoreCareTeam","USCoreOrganizationProfile","Patient","USCorePractitionerProfile","USCoreRelatedPersonProfile"]),
...validateReference(res, profileName, "performer", ["PractitionerRole","CareTeam","Organization","Patient","Practitioner","RelatedPerson"]),
],
warnings: [
...validateEnum(res, profileName, "category", ["social-history","vital-signs","imaging","laboratory","procedure","survey","exam","therapy","activity"]),
Expand Down
4 changes: 2 additions & 2 deletions src/api/writer-generator/python/profile-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ export const collectValidateBody = (
`warnings.extend(validate_must_support(self._resource, profile_name, ${JSON.stringify(pyName)}))`,
);
}
if (field.reference && field.reference.length > 0) {
if (field.reference && field.reference.resource.length > 0) {
helpers.add("validate_reference");
const allowed = field.reference.map((ref) => resolveRef(ref).name);
const allowed = field.reference.resource.map((ref) => resolveRef(ref).name);
errorLines.push(
`errors.extend(validate_reference(self._resource, profile_name, ${JSON.stringify(pyName)}, ${JSON.stringify(allowed)}))`,
);
Expand Down
4 changes: 2 additions & 2 deletions src/api/writer-generator/typescript/profile-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ export const collectRegularFieldValidation = (
if (field.mustSupport && !field.required)
warnings.push(`...validateMustSupport(res, profileName, ${JSON.stringify(name)})`);

if (field.reference && field.reference.length > 0)
if (field.reference && field.reference.resource.length > 0)
errors.push(
`...validateReference(res, profileName, ${JSON.stringify(name)}, ${JSON.stringify(field.reference.map((ref) => resolveRef(ref).name))})`,
`...validateReference(res, profileName, ${JSON.stringify(name)}, ${JSON.stringify(field.reference.resource.map((ref) => resolveRef(ref).name))})`,
);

if (field.slicing?.slices) {
Expand Down
4 changes: 2 additions & 2 deletions src/api/writer-generator/typescript/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export const resolveFieldTsType = (
if (field.type.name === "CodeableConcept") return `CodeableConcept<${tsEnumType(field.enum)}>`;
return tsEnumType(field.enum);
}
if (field.reference && field.reference.length > 0) {
const resolved = field.reference.map((ref) => (resolveRef ? resolveRef(ref) : ref));
if (field.reference && field.reference.resource.length > 0) {
const resolved = field.reference.resource.map((ref) => (resolveRef ? resolveRef(ref) : ref));
const references = resolved
.map((ref) => (isFamilyType?.(ref) ? `string /* ${ref.name} */` : `"${ref.name}"`))
.join(" | ");
Expand Down
31 changes: 26 additions & 5 deletions src/typeschema/core/field-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@
import type { FHIRCoding, FHIRSchemaDiscriminator, FHIRSchemaElement } from "@atomic-ehr/fhirschema";
import type { Register } from "@root/typeschema/register";
import type { CodegenLog } from "@root/utils/log";
import { packageMetaToFhir } from "@typeschema/types";
import { isProfileIdentifier, packageMetaToFhir } from "@typeschema/types";
import type {
BindingIdentifier,
EnumDefinition,
Field,
FieldReference,
FieldSlice,
FieldSlicing,
Name,
PackageMeta,
ProfileIdentifier,
RegularField,
RichFHIRSchema,
TypeIdentifier,
Expand Down Expand Up @@ -90,18 +92,37 @@ function isExcluded(register: Register, fhirSchema: RichFHIRSchema, path: string
return new Set(requires).has(fieldName);
}

/** Resolve reference targets into two independent facts: `resource` — the base
* resource types a reference literal may point at (profiles resolve to their
* base specialization, deduped) — and `profiles` — the profile conformance
* expectations, preserved for profile-aware consumers. */
const buildReferences = (
register: Register,
fhirSchema: RichFHIRSchema,
element: FHIRSchemaElement,
): TypeIdentifier[] | undefined => {
): FieldReference | undefined => {
if (!element.refers) return undefined;
return element.refers.map((ref) => {
const resource: TypeIdentifier[] = [];
const profiles: ProfileIdentifier[] = [];
const seen = new Set<string>();
for (const ref of element.refers) {
const curl = register.ensureSpecializationCanonicalUrl(ref as Name);
const fs = register.resolveFs(fhirSchema.package_meta, curl);
if (!fs) throw new Error(`Failed to resolve fs for ${curl}`);
return mkIdentifier(fs);
});
const id = mkIdentifier(fs);
let resolved: TypeIdentifier = id;
if (isProfileIdentifier(id)) {
profiles.push(id);
const baseFs = register.resolveFsSpecializations(fs.package_meta, fs.url)[0];
if (!baseFs) throw new Error(`Failed to resolve base specialization for ${curl}`);
resolved = mkIdentifier(baseFs);
}
if (!seen.has(resolved.url)) {
seen.add(resolved.url);
resource.push(resolved);
}
}
return { resource, profiles: profiles.length > 0 ? profiles : undefined };
};

const extractSliceFieldNames = (schema: FHIRSchemaElement): Pick<FieldSlice, "required" | "excluded" | "elements"> => {
Expand Down
9 changes: 7 additions & 2 deletions src/typeschema/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,14 @@ export type LogicalTypeSchema = { identifier: LogicalIdentifier } & Specializati

export type SpecializationTypeSchema = ResourceTypeSchema | ComplexTypeTypeSchema | LogicalTypeSchema;

export type FieldReference = {
resource: TypeIdentifier[];
profiles?: ProfileIdentifier[];
};

export interface RegularField {
type: TypeIdentifier;
reference?: TypeIdentifier[];
reference?: FieldReference;
required?: boolean;
excluded?: boolean;
array?: boolean;
Expand Down Expand Up @@ -401,7 +406,7 @@ export interface ChoiceFieldInstance {
required?: boolean;
excluded?: boolean;
array?: boolean;
reference?: TypeIdentifier[];
reference?: FieldReference;
binding?: BindingIdentifier;
enum?: EnumDefinition;
min?: number;
Expand Down
Loading
Loading