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
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,16 @@ export class USCoreBodyWeightProfile {
...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"]),
...validateExcluded(res, profileName, "valueCodeableConcept"),
...validateExcluded(res, profileName, "valueString"),
...validateExcluded(res, profileName, "valueBoolean"),
...validateExcluded(res, profileName, "valueInteger"),
...validateExcluded(res, profileName, "valueRange"),
...validateExcluded(res, profileName, "valueRatio"),
...validateExcluded(res, profileName, "valueSampledData"),
...validateExcluded(res, profileName, "valueTime"),
...validateExcluded(res, profileName, "valueDateTime"),
...validateExcluded(res, profileName, "valuePeriod"),
],
warnings: [
...validateEnum(res, profileName, "category", ["social-history","vital-signs","imaging","laboratory","procedure","survey","exam","therapy","activity"]),
Expand Down
24 changes: 24 additions & 0 deletions examples/typescript-us-core/profile-bodyweight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,30 @@ describe("demo", () => {
expect(profile.validate().errors).toEqual([]);
});

test("validate() catches disallowed value[x] variants on raw resource", () => {
const resource: Observation = {
resourceType: "Observation",
meta: { profile: ["http://hl7.org/fhir/us/core/StructureDefinition/us-core-body-weight"] },
status: "final",
category: [
{
coding: {
code: "vital-signs",
system: "http://terminology.hl7.org/CodeSystem/observation-category",
},
},
] as any,
code: { coding: [{ code: "29463-7", system: "http://loinc.org" }] },
subject: { reference: "Patient/pt-1" },
effectiveDateTime: "2024-06-15",
valueString: "not allowed",
};

const profile = USCoreBodyWeightProfile.apply(resource);
const { errors } = profile.validate();
expect(errors).toContain("USCoreBodyWeightProfile: field 'valueString' must not be present");
});

test("getVSCat() returns flat value, getVSCat('raw') includes discriminator", () => {
const profile = USCoreBodyWeightProfile.create({
status: "final",
Expand Down
7 changes: 6 additions & 1 deletion src/api/writer-generator/typescript/profile-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,12 @@ export const generateValidateMethod = (w: TypeScript, tsIndex: TypeSchemaIndex,
const errors: string[] = [];
const warnings: string[] = [];
for (const [name, field] of Object.entries(fields)) {
if (isChoiceInstanceField(field)) continue;
if (isChoiceInstanceField(field)) {
const decl = fields[field.choiceOf];
if (decl && isChoiceDeclarationField(decl) && decl.prohibited?.includes(name))
errors.push(`...validateExcluded(res, profileName, ${JSON.stringify(name)})`);
continue;
}

if (isChoiceDeclarationField(field)) {
if (field.required)
Expand Down
1 change: 1 addition & 0 deletions src/typeschema/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ export interface RegularField {

export interface ChoiceFieldDeclaration {
choices: string[];
prohibited?: string[];
required?: boolean;
excluded?: boolean;
array?: boolean;
Expand Down
49 changes: 48 additions & 1 deletion src/typeschema/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { IrReport } from "./ir/types";
import type { Register } from "./register";
import {
type CanonicalUrl,
type ChoiceFieldInstance,
type ConstrainedChoiceInfo,
type Field,
type Identifier,
Expand Down Expand Up @@ -314,6 +315,50 @@ export const mkTypeSchemaIndex = (
return findLastSpecialization(schema).identifier;
};

/** Narrow choice declarations by finding the most derived schema that constrains each choice group.
* When a child profile declares only specific choice instances without re-declaring the declaration,
* restrict the declaration's choices array to only the allowed instances. */
const narrowMergedChoiceDeclarations = (
mergedFields: Record<string, Field>,
constraintSchemas: TypeSchema[],
): Record<string, Field> => {
const result = { ...mergedFields };
for (const [declName, declField] of Object.entries(result)) {
if (!isChoiceDeclarationField(declField) || declField.excluded) continue;

for (const cSchema of constraintSchemas) {
const sFields = (cSchema as RegularTypeSchema).fields;
if (!sFields) continue;
if (sFields[declName] && isChoiceDeclarationField(sFields[declName])) continue;

const instancesInSchema = Object.entries(sFields)
.filter(([_, f]) => isChoiceInstanceField(f) && (f as ChoiceFieldInstance).choiceOf === declName)
.map(([name]) => name);
if (instancesInSchema.length === 0) continue;

const allowed = new Set(instancesInSchema);
result[declName] = { ...declField, choices: declField.choices.filter((c) => allowed.has(c)) };
break;
}
}

// Compute prohibited for all choice declarations
for (const [declName, declField] of Object.entries(result)) {
if (!isChoiceDeclarationField(declField)) continue;
const permitted = new Set(declField.excluded ? [] : declField.choices);
const prohibited = Object.entries(result)
.filter(
(e): e is [string, ChoiceFieldInstance] =>
isChoiceInstanceField(e[1]) && e[1].choiceOf === declName,
)
.filter(([name]) => !permitted.has(name))
.map(([name]) => name);
if (prohibited.length > 0) result[declName] = { ...declField, prohibited };
}

return result;
};

const flatProfile = (schema: ProfileTypeSchema): ProfileTypeSchema => {
const hierarchySchemas = hierarchy(schema);
const constraintSchemas = hierarchySchemas.filter((s) => s.identifier.kind === "profile");
Expand All @@ -339,6 +384,8 @@ export const mkTypeSchemaIndex = (
}
}

const narrowedFields = narrowMergedChoiceDeclarations(mergedFields, constraintSchemas);

const dependencies = Object.values(
Object.fromEntries(
constraintSchemas
Expand All @@ -362,7 +409,7 @@ export const mkTypeSchemaIndex = (
return {
...schema,
base: nonConstraintSchema.identifier,
fields: mergedFields,
fields: narrowedFields,
dependencies: dependencies,
extensions: mergedExtensions.length > 0 ? mergedExtensions : undefined,
};
Expand Down
10 changes: 10 additions & 0 deletions test/api/write-generator/__snapshots__/typescript.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -1715,6 +1715,16 @@ export class USCoreBodyWeightProfile {
...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"]),
...validateExcluded(res, profileName, "valueCodeableConcept"),
...validateExcluded(res, profileName, "valueString"),
...validateExcluded(res, profileName, "valueBoolean"),
...validateExcluded(res, profileName, "valueInteger"),
...validateExcluded(res, profileName, "valueRange"),
...validateExcluded(res, profileName, "valueRatio"),
...validateExcluded(res, profileName, "valueSampledData"),
...validateExcluded(res, profileName, "valueTime"),
...validateExcluded(res, profileName, "valueDateTime"),
...validateExcluded(res, profileName, "valuePeriod"),
],
warnings: [
...validateEnum(res, profileName, "category", ["social-history","vital-signs","imaging","laboratory","procedure","survey","exam","therapy","activity"]),
Expand Down
Loading