Package Exports
- babelfhir-ts
- babelfhir-ts/out/main.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (babelfhir-ts) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
BabelFHIR-TS
BabelFHIR-TS transforms FHIR® StructureDefinitions into production-ready TypeScript code with full type safety and built-in validation. Unlike generic FHIR type definitions, BabelFHIR-TS generates profile-aware interfaces that understand your Implementation Guide's constraints, extensions, and slicing rules.
Why BabelFHIR-TS?
The FHIR Challenge: Implementation Guides define strict profiles that constrain base FHIR resources with required or must-support elements, custom extensions, value set bindings, and cardinality rules. Existing TypeScript libraries can't capture these requirements when you need profile-specific types, leading to an overhead when using TypeScript to build apps that interact with FHIR servers.
The BabelFHIR-TS Solution: Automatically generates TypeScript interfaces and validation logic directly from StructureDefinition JSON. Your IDE autocompletes required fields, flags missing extensions at compile-time, and validates FHIRPath invariants at runtime.
What you get
- Strongly typed interfaces that merge profile constraints with base FHIR types (types come from
@types/fhir) - Compiled output by default — packages ship JavaScript (
.js) plus TypeScript declarations (.d.ts) - Runtime validation using FHIRPath expressions from the profile—no external validator required for basic checks
- Type-safe extension handling with proper slicing and nested extension support
- Random data builders for testing and development (when class generation is enabled)
- Zero manual mapping—consume any FHIR package or Implementation Guide directly from registries
- Fast and lightweight—minimal runtime deps; only
fhirpathis required for validators - Install any FHIR profile as a node module—use
babelfhir-ts installto add Implementation Guides directly to your project
Use it to build FHIR-compliant APIs, validate incoming resources against profiles, or generate type-safe client SDKs from Implementation Guides.
Installation
Install globally (recommended when using the CLI frequently):
npm install -g babelfhir-tsOr invoke on-demand without a global install:
npx babelfhir-ts --helpRequirements: Node.js 18+ (ESM support) and an internet connection when downloading packages from remote registries.
Quick start
Generate code from a local folder that contains FHIR packages:
babelfhir-ts input/ output/Process a single package archive and write the generated interfaces back into a new .tgz file:
babelfhir-ts hl7.fhir.us.core-8.0.0.tgz us-core-generated.tgzDownload and process a package directly from a registry (defaults to https://packages.simplifier.net):
babelfhir-ts --package hl7.fhir.us.core@8.0.0Install a processed package into your current project:
babelfhir-ts install hl7.fhir.us.core@8.0.0After generation you can import the emitted classes:
import { USCorePatientClass } from "./output/USCorePatientClass";
const patient = USCorePatientClass.random();
const { errors, warnings } = await patient.validate();Using the generated code in your project
Generated profile packages installed via babelfhir-ts install are published as compiled JavaScript with TypeScript declarations:
- JavaScript for runtime:
index.js,*.js - Type declarations for IDE/TS:
index.d.ts,*.d.ts - Dependencies:
@types/fhiris included as a dependency of the generated package (no extra setup in your app)fhirpathis a peer dependency (required only if you use the generated validators/classes)
Install fhirpath in your app if you plan to call .validate() or use the generated classes:
npm install fhirpathImport and use:
// TypeScript or JavaScript
import { AdmissionAppointment, AdmissionAppointmentClass } from "pink.admission-generated";
// Types are available automatically via .d.ts
const appt: AdmissionAppointment = {
resourceType: "Appointment",
status: "booked",
start: "2025-10-23T14:00:00Z",
};
// Optional helper class + validation
const instance = AdmissionAppointmentClass.random();
const result = await new AdmissionAppointmentClass(appt).validate();
console.log(result.errors, result.warnings);CLI reference
babelfhir-ts [options] [<input> [output]]| Argument / option | Description |
|---|---|
<input> |
Directory of FHIR packages/StructureDefinitions, single package (.tgz/.zip), or single StructureDefinition .json. Defaults to ./input when omitted. |
<output> |
Destination directory or archive. Defaults to ./output when omitted. |
install |
Downloads, processes, and installs a package as a project dependency. |
--package <pkg@version> |
Fetch a package from a registry and process it without manual download. |
--registry <url> |
Custom registry base URL (default:https://packages.simplifier.net). |
--log <level> |
Control logging output:none (default), console, or file. |
--no-cache |
Remove the .cache directory once generation completes. |
--no-classes |
Skip emitting helper classes (interfaces & validators only). |
-h, --help |
Print usage help. |
-v, --version |
Print the BabelFHIR-TS version. |
Supported inputs
- Directory – scan all
.tgz,.zip, or.jsonfiles inside the folder - Archive – process a FHIR NPM package in
.tgzor.zipformat - StructureDefinition JSON – generate code for a single profile definition
Generated output
For each StructureDefinition the generator produces:
*.tsinterface definitions (extending the canonical FHIR types)*Class.tscompanions that offer:- constructor helpers (
empty,random,randomClass) - deterministic field filling for required and must-support elements
validate()that evaluates FHIR invariant expressions viafhirpath
- constructor helpers (
- optional validation parity artefacts when you run the test suite (
npm test validatorParity)
The validator relies on fhirpath.evaluate(...) to enforce profile invariants (including min cardinalities, slices, and custom expressions) without requiring a full FHIR server. It intentionally performs high-level checks only: terminology expansion, reference resolution, and other server-backed logic are out of scope, so keep a downstream validator (e.g. the HL7 Java validator CLI) in your QA pipeline for full conformance.
Example: Generated US Core Encounter Profile
Given the US Core Encounter profile, BabelFHIR-TS generates TypeScript interfaces that capture all must-support elements and profile extensions:
import { Encounter, Meta, Extension, Identifier, Coding, CodeableConcept,
Reference, EncounterParticipant, Period, EncounterHospitalization,
EncounterLocation } from "fhir/r4";
// Extension interface with type-safe URL
export interface UsCoreInterpreterNeeded extends Extension {
url: 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-interpreter-needed'
}
// Profile interface extending base Encounter with must-support constraints
export interface USCoreEncounterProfile extends Encounter {
/** Must Support */
meta?: Meta;
/** Must Support */
identifier?: Identifier[];
/** Must Support */
class: Coding;
/** Must Support */
type: CodeableConcept[];
/** Must Support */
subject: Reference;
/** Must Support */
participant?: EncounterParticipant[];
/** Must Support */
period?: Period;
/** Must Support */
reasonCode?: CodeableConcept[];
/** Must Support */
reasonReference?: Reference[];
/** Must Support */
hospitalization?: EncounterHospitalization;
/** Must Support */
location?: EncounterLocation[];
/** Must Support */
serviceProvider?: Reference;
// Typed extension slicing
extension?: (Extension | UsCoreInterpreterNeeded)[];
}
// Generated validator function
export async function validateUSCoreEncounterProfile(
resource: USCoreEncounterProfile
): Promise<{ errors: string[], warnings: string[] }>;
Scripts for contributors
| Script | Purpose |
|---|---|
npm run generate |
Execute the CLI against the local input/ folder and refresh output/. |
npm run generate:check |
End-to-end check: generate, type-check, and lint the emitted output. |
npm test |
Type-check and run all Vitest suites (coverage enabled). |
npm run download-validator |
Fetch the official HL7 validation jar used for parity testing. |
Caching notes
The generator caches downloaded StructureDefinitions and packages inside .cache/. When you need a clean run, pass --no-cache or manually remove the folder. Temporary downloads land in .temp-* directories and are cleaned up automatically.
Limitations
BabelFHIR-TS is a code generation tool that parses FHIR StructureDefinitions and produces TypeScript interfaces and validators. While it handles many common FHIR profiling patterns, there are important limitations to be aware of:
Profile Mapping Accuracy
- Not guaranteed for all IGs: The generator uses heuristics to interpret StructureDefinition constraints, slicing rules, and extensions. Complex or unusual profiling patterns may not map correctly to TypeScript.
- Test before production: Always validate the generated code against your specific Implementation Guide's examples and test cases. We recommend running the official FHIR validator alongside BabelFHIR-TS in your QA pipeline.
- Edge cases: Rare profiling constructs (deeply nested slicing, conditional constraints, complex discriminators) may generate suboptimal or incomplete types.
Validation Scope
- High-level checks only: The generated
validate()functions execute FHIRPath expressions from profile invariants but do not perform:- Terminology expansion or ValueSet validation
- Reference resolution (checking that referenced resources exist)
- Full cardinality enforcement for complex slicing scenarios
- Server-side business logic or workflow rules
- Use the official validator: For production conformance testing, use the HL7 FHIR Validator alongside BabelFHIR-TS.
TypeScript Limitations
- Runtime type checking is limited: TypeScript types are erased at compile time. The generated interfaces provide compile-time safety but cannot enforce constraints at runtime without the validator functions.
- Extension slicing: While the generator creates typed extension interfaces, TypeScript cannot enforce that extension arrays contain exactly the required slices at compile time (this is validated at runtime).
- Choice types: FHIR's
[x]choice types (e.g.,value[x]) are represented as union types in TypeScript, which may require runtime type narrowing.
FHIR Version Support
- R4 only: The current version targets FHIR R4. Support for R5, DSTU2, or STU3 is not yet available.
- Dependencies: Generated code depends on
@types/fhir(R4 definitions) andfhirpath(R4 compatible).
Reporting Issues
If you encounter an Implementation Guide that doesn't generate correctly, please open an issue with:
- The package name and version
- The specific StructureDefinition URL
- Expected vs. actual generated output
- Any validation errors or type mismatches
We continuously improve the generator based on real-world IG usage, and your feedback helps make BabelFHIR-TS more robust.
License
ISC © Maximilian Nussbaumer