Code Monkey home page Code Monkey logo

fhir-codegen's Introduction

fhir-codegen

A .Net library and related utilities to work with FHIR specifications.

Documentation

Detailed documentation can be found on the documentation site.

Projects in this Repository

Project source code is hosted on GitHub.

All projects are currently built on .Net 7.0 and tested on multiple platforms, though Windows is the primary development platform. The .Net 6.0 SDK and runtimes are available for free at: https://dotnet.microsoft.com/en-us/download .

Microsoft.Health.Fhir.CodeGenCommon

This project is a class library that contains the common (normalized) models used in these projects. The project is lightweight and used to ensure that additional projects (e.g., a WASM UI) have access to all the models.

Detailed information about the models can be found in the Common Models Documentation.

Microsoft.Health.Fhir.SpecManager

This project is a class library that contains the logic used in the various projects. For example, this project contains the code to:

  • download packages,
  • resolve canonical URLs,
  • normalize different versions of FHIR,
  • read metadata (CapabilityStatement or Conformance) from FHIR servers,
  • compare packages or artifacts,
  • convert normalized models into language-specific models,
  • etc.

More information about this project can be found in the API Documentation.

Export Languages

The projects in this repository can be used to translate FHIR packages (core or IG) into other forms - e.g., programming language definitions (C#, TypeScript, etc.), or data files for consumption (Info, Cytoscape, etc.).

More information about current languages can be found on the Export Languages Page. Information about adding new languages can be found on the Extending Page.

FhirCodeGenBlazor

This project is a server-side Blazor application that can be used to interact with the code-generation library. Generally, it can:

  • manage the FHIR Package Cache (~/.fhir) - add/update/remove packages
  • browse package artifacts
  • search across element information (e.g., resource/logical models elements)
  • compare packages or artifacts (Diff Tool)
  • perform exports
  • etc.

To run this project from a command line:

  • dotnet run --project src/FhirCodeGenBlazor/FhirCodeGenBlazor.csproj or, you can build a release version to run:
  • dotnet build src/FhirCodeGenBlazor/FhirCodeGenBlazor.csproj -c Release
  • dotnet ./src/FhirCodeGenBlazor/bin/Release/net7.0/FhirCodeGenBlazor.dll

More information about this project can be found in the API Documentation.

More information about this project can be found in the Blazor UI Documentation.

fhir-codegen-cli

This project is a command-line application that can be used to perform export operations (e.g., for CI Pipelines). Generally, it can:

  • manage the FHIR Package Cache (~/.fhir) - add/update packages
  • perform exports / transforms of FHIR packages

To run this project from a command line:

  • dotnet run --project src/fhir-codegen-cli/fhir-codegen-cli.csproj -- [options] or, you can build a release version to run:
  • dotnet build src/fhir-codegen-cli/fhir-codegen-cli.csproj -c Release
  • dotnet ./src/fhir-codegen-cli/bin/Release/net7.0/fhir-codegen-cli.dll
Usage:
  fhir-codegen-cli [options]

Options:
  -o, --output-path <output-path>                File or directory to write output.
  --package-directory <package-directory>        The path to a local directory for FHIR packages, if different than the default 
                                                 FHIR cache (~/.fhir); e.g., (.../fhirPackages)).
  -l, --language <language>                      Name of the language to export (default: Info|TypeScript|CSharpBasic).
  --language-help                                Display languages and their options. [default: False]
  --language-options, --opts <language-options>  Language specific options, see documentation for more details. Example: 
                                                 Lang1|opt=a|opt2=b|Lang2|opt=tt|opt3=oo.
  --language-input-dir <language-input-dir>      The full path to a local directory to pass additional content to languages.
  --offline-mode                                 Offline mode (will not download missing packages). [default: False]
  -k, --export-keys <export-keys>                '|' separated list of items to export (not present to export everything).
  --official-expansions-only                     Set to restrict value-sets to only official expansions. [default: False]
  --experimental, --include-experimental         If the output should include structures marked experimental. [default: False]
  --export-types, --types <export-types>         Types of FHIR structures to export (primitive|complex|resource|interaction|enum),
                                                 default is all.
  --extension-support <extension-support>        The level of extensions to include (none|official|officialNonPrimitive|nonPrimitive|all),
                                                 default is nonPrimitive.
  --fhir-server-url, --server <fhir-server-url>  FHIR Server URL to pull a CapabilityStatement or Conformance from. The server
                                                 must provide application/fhir+json support.
  -p, --packages <packages>                      '|' separated list of packages, with or without version numbers,
                                                 e.g., hl7.fhir.r4.core#4.0.1|hl7.fhir.us.core#latest.
  --load-DSTU2, --load-r2 <load-DSTU2>           If FHIR DSTU2 should be loaded, which version (e.g., 1.0.2 or latest)
  --load-r3, --load-STU3 <load-STU3>             If FHIR STU3 should be loaded, which version (e.g., 3.0.2 or latest)
  --load-r4 <load-r4>                            If FHIR R4 should be loaded, which version (e.g., 4.0.1 or latest)
  --load-r4b <load-r4b>                          If FHIR R4B should be loaded, which version (e.g., 4.3.0 or latest)
  --load-r5 <load-r5>                            If FHIR R5 should be loaded, which version (e.g., 5.0.0-ballot or latest)
  --ci-branch <ci-branch>                        If loading from the CI server, the name of the branch to use.
  -v, --verbose                                  Show verbose output. [default: False]
  --version                                      Show version information
  -?, -h, --help                                 Show help and usage information

More information about this project can be found in the Command Line Documentation.

Examples

  • Download and parse FHIR R4 (latest published version) into the user FHIR cache, then build a TypeScript file in the current directory

    • fhir-codegen-cli -p hl7.fhir.r4#latest --language TypeScript --output-path ./R4.ts
  • Download and parse FHIR R4 (latest published version) into the user FHIR cache, then build a TypeScript file in the current directory, restricted to just the Resources: Patient, Encounter, and Observation

    • fhir-codegen-cli --load-r4 latest --language TypeScript --output-path ./R4.ts --export-keys Patient|Encounter|Observation
  • Download and parse the latest published version of each FHIR release into the user FHIR cache, then build a C# file for each in ./cs

    • fhir-codegen-cli --load-r2 latest --load-r3 latest --load-r4 latest --load-r5 latest --language CSharpBasic --output-path ./cs
  • Download and parse FHIR R4 (latest published version) into the user FHIR cache, then build a C# file in the current directory using the namespace: MyOrg.MyProject.Fhir

    • fhir-codegen-cli -p hl7.fhir.r4#latest --language CSharpBasic --output-path ./cs/R4.cs --language-options CSharpBasic|namespace=MyOrg.MyProject.Fhir

fhir-codegen-test-cli

This project is a minimal test harness for generated TypeScript and CSharp code. It can be used to ensure that the core parsing and generation is working properly, and potentially as an example for other language outputs.

To run this project from a command line:

  • dotnet run --project src/fhir-codegen-test-cli/fhir-codegen-test-cli.csproj -- [options]

It will use generated CSharpBasic and TypeScript files for FHIR Versions DSTU2, STU3, R4, and R5. It will then run each through a build process (requires dotnet for C# and tsc for TypeScript) to validate there are no syntax errors in any of the generated files.

Note that this test takes several minutes to run.

Usage

fhir-codegen-test-cli:
  The FHIR CodeGen Test CLI.

Usage:
  fhir-codegen-test-cli [options]

Options:
  --repo-root-path <repo-root-path>    The path to the repository root (if not CWD).
  --verbose                            True to display all output (default: false)
  --fixed-format-statistics            True to output *only* test run statistics:
                                         #run[tab]#passed[tab]#failed[tab]#skipped
                                         (default: false)
  --errors-to-std-error                True to write errors to stderr instead of stdout.
                                         (default: False)
  --version                            Show version information
  -?, -h, --help                       Show help and usage information

Requirements

In order to run TypeScript tests, the system must be able to find the 'tsc' (TypeScript compile) command. Note that it must be installed and accessible by the test application (e.g., npm install -g typescript).

fhirCsR2

This is a library project used to isolate the FHIR DSTU2 definitions. All other versions of FHIR are dynamically parsed, but there has not been justification to port this forward - no technical corrections for DSTU2 are expected, so this is mostly considered legacy.

Pre-Generated Files

The generated directory has static outputs for each of the supported versions of FHIR, in some of the supported languages. These files are used to validate changes to the core loading and parsing, but may be useful otherwise.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Trademarks

FHIR® is the registered trademark of HL7 and is used under Community Project guidelines. This project is not affiliated with, or approved or sponsored by, HL7.

fhir-codegen's People

Contributors

balteravishay avatar bkaney avatar brianpos avatar coderunrepeat avatar dependabot[bot] avatar eugene-blokhin avatar ewoutkramer avatar ginocanessa avatar jdjkelly avatar jmandel avatar joedrowan avatar kennethmyhra avatar marcovisserfurore avatar microsoft-github-operations[bot] avatar microsoftopensource avatar mmsmits avatar richfirely avatar wardweistra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fhir-codegen's Issues

TypeScript_R4.ElementDefinitionExample values all mandatory

In the generated TypeScript_R4 the interface generation of ElementDefinitionExample has all the values (valueCode, valueBoolean etc) as mandatory so that the typescript checking fails when you try and instantiate an ElementDefinition with an example e.g
"example": [ { "valueUri": "http://hl7.org/fhir/v3/MaritalStatus", "label": "General" } ],
then the TypeScript type checking fails. This will be because the profile says that value[x] must have a value but there is no way to represent in an interface that I am aware of to say it must have only one of the multiple types of values that are allowed. If you mark them all as optional then it will type check correctly but not sure how your codegen could evaluate this pattern

FHIR download/caching barfing on R5 500 error.

On first run, the download/caching code is bailing out with TryDownloadAndExtract <<< exception downloading: http://packages2.fhir.org/packages/hl7.fhir.r5.core/5.0.0-snapshot2/, One or more errors occurred. (Response status code does not indicate success: 500 (Internal Server Error).). Not sure if it's an upstream issue with the server, outdated URL etc.

`
➜ fhir-codegen git:(main) dotnet run -p src/fhir-codegen-cli
Warning NETSDK1174: The abbreviation of -p for --project is deprecated. Please use --project.
Starting FhirCacheService...
<<< using cache directory: /Users/preston/.fhir
<< cache contains 10 packges
Starting FhirManager...
LoadCached <<< Loaded and Parsed FHIR DSTU2
Loaded hl7.fhir.r2.core#latest as hl7.fhir.r2.core version 1.0.2
LoadCached <<< Loaded and Parsed FHIR STU3 with 0 errors and 5 warnings
Errors (only able to pass with manual code changes)
Warnings (able to pass, but should be reviewed)

  • CodeSystem SNOMED_CT (snomedct): Duplicate proprety found: Laterality
  • ValueSet Yes/No/Don't Know (yesnodontknow): No Version present
  • ValueSet Example-inactive (inactive): No Version present
  • ValueSet Common UCUM units (ucum-common): No Version present
  • ValueSet All CPT codes (cpt-all): No Version present
    Loaded hl7.fhir.r3.core#latest as hl7.fhir.r3.core version 3.0.2
    LoadCached <<< Loaded and Parsed FHIR R4 with 0 errors and 1 warnings
    Errors (only able to pass with manual code changes)
    Warnings (able to pass, but should be reviewed)
  • CodeSystem SNOMED_CT (snomedct): Duplicate proprety found: Laterality
    Loaded hl7.fhir.r4.core#latest as hl7.fhir.r4.core version 4.0.1
    GetPackageVersionsAndUrls <<< Failed to get package info: NotFound http://packages.fhir.org/hl7.fhir.r4b.core
    GetPackageVersionsAndUrls <<< Failed to get package info: NotFound http://packages.fhir.org/hl7.fhir.r4b.expansions
    LoadCached <<< Loaded and Parsed FHIR R4B with 4 errors and 6 warnings
    Errors (only able to pass with manual code changes)
  • CodeSystem ResourceSecurityCategory (resource-security-category): Status field missing
  • CodeSystem ConceptSubsumptionOutcome (concept-subsumption-outcome): Status field missing
  • CodeSystem StandardsStatus (standards-status): Status field missing
  • CodeSystem ResourceValidationMode (resource-validation-mode): Status field missing
    Warnings (able to pass, but should be reviewed)
  • CodeSystem SNOMED_CT (snomedct): Duplicate proprety found: Laterality
  • ValueSet Yes/No/Don't Know (yesnodontknow): No Version present
  • ValueSet ACMECholCodesPlasma (example-filter): No Version present
  • ValueSet Example-inactive (inactive): No Version present
  • ValueSet Common UCUM units (ucum-common): No Version present
  • ValueSet All CPT codes (cpt-all): No Version present
    Loaded hl7.fhir.r4b.core#latest as hl7.fhir.r4b.core version 4.3.0-snapshot1
    GetPackageVersionsAndUrls <<< Failed to get package info: NotFound http://packages.fhir.org/hl7.fhir.r5.core
    TryDownloadAndExtract <<< exception downloading: http://packages.fhir.org/hl7.fhir.r5.core/5.0.0-snapshot2/, One or more errors occurred. (Response status code does not indicate success: 404 (Not Found).)
    <<< inner: Response status code does not indicate success: 404 (Not Found).
    TryDownloadAndExtract <<< exception downloading: http://packages2.fhir.org/packages/hl7.fhir.r5.core/5.0.0-snapshot2/, One or more errors occurred. (Response status code does not indicate success: 500 (Internal Server Error).)
    <<< inner: Response status code does not indicate success: 500 (Internal Server Error).
    FindOrDownload <<< unable to resolve a directive: hl7.fhir.r5.core#latest
    Unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
    ---> System.Exception: Failed to retrieve hl7.fhir.r5.core#latest
    at Microsoft.Health.Fhir.SpecManager.Manager.FhirManager.LoadFhirCore(FhirSequenceEnum sequence, String version, Boolean offlineMode, Boolean officialExpansionsOnly, String ciBranch) in /Users/preston/Developer/git/fhir-codegen/src/Microsoft.Health.Fhir.SpecManager/Manager/FhirManager.cs:line 351
    at Microsoft.Health.Fhir.SpecManager.Manager.FhirManager.LoadPackages(IEnumerable1 packageDirectives, Boolean offlineMode, Boolean officialExpansionsOnly, Boolean loadDependencies, Boolean skipFhirCore, String ciBranch, List1& failedPackages, Boolean areDependencies) in /Users/preston/Developer/git/fhir-codegen/src/Microsoft.Health.Fhir.SpecManager/Manager/FhirManager.cs:line 495
    at FhirCodegenCli.Program.Process(String fhirSpecDirectory, String outputPath, Boolean verbose, Boolean offlineMode, String language, String exportKeys, String loadR2, String loadR3, String loadR4, String loadR4B, String loadR5, String languageOptions, Boolean officialExpansionsOnly, String fhirServerUrl, Boolean includeExperimental, String exportTypes, String extensionSupport, Boolean languageHelp, String packageDirectory, String packages, String ciBranch, String languageInputDir) in /Users/preston/Developer/git/fhir-codegen/src/fhir-codegen-cli/Program.cs:line 464
    --- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    at System.Delegate.DynamicInvokeImpl(Object[] args)
    at System.Delegate.DynamicInvoke(Object[] args)
    at System.CommandLine.NamingConventionBinder.ModelBindingCommandHandler.InvokeAsync(InvocationContext context)
    at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass4_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass22_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass15_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass26_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass24_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<b__23_0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass21_0.<b__0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<b__8_0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<b__7_0>d.MoveNext()
    --- End of stack trace from previous location ---
    at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass11_0.<b__0>d.MoveNext()

`

Add syntax checks to the deserializer

Currently the deserializer is mostly concerned about the happy path. Add code that does the same checks as the current SDK does:

Xml syntactic checks

  • incorrect/empty namespace . P, R:namespace ignored
  • empty attributes . P, R: whitespace,null then value=null
  • no attribute, no elements P ->S, R:empty child list, value=null SKIP?
  • repeating elements inconsecutively P,->S
  • Invalid FHIR Xhtml P ->T
  • container resources with attributes . P, R:no contained found
  • contained resources with attributes . P, R:no contained found
  • container resources with multiple children . P, R:no contained found

Json syntactic checks

  • incorrect use of null P, R: skip
  • incorrect use/combinations of name and _name . P, R: return main
  • incorrect use of arrays for name and _name . P, R:return main
  • invalid json token type . P: skip unless some useful content found
  • empty string values ->T, p:return null
  • non-arrays with null values . P, R:return null
  • empty objects . P, R:return null
  • obsolete fhir_comments use . P, R:skip

Replace some generated code with calls to (inlined) utility functions.

There are just a small number of "patterns" when generating serializing/deserializing code, and some of these can be extracted into utility functions so we need to generate less code.

In the end, me might be able to swap the utility functions for calls to an interface so the same serializer/deserializer code can be used for xml and json.

Command line code generation gives no output

The section https://github.com/microsoft/fhir-codegen#fhir-codegen-cli tells me:

To run this project from a command line:
dotnet run --project src/fhir-codegen-cli/fhir-codegen-cli.csproj -- [options]

However, running dotnet run --project src/FhirCodeGenBlazor/FhirCodeGenBlazor.csproj -- -p hl7.fhir.r4.core#4.0.1 --language TypeScript --output-path ~/R4.ts does not seem to generate any file.

As reported on https://chat.fhir.org/#narrow/stream/179171-dotnet/topic/Microsoft.20fhir-codegen-cli/near/383004416

Request for string codes to be enums

It would be more ergonomic for string fields values such as these:

public static class AddressTypeCodes {
    public const string POSTAL = "postal";
    public const string PHYSICAL = "physical";
    public const string BOTH = "both";
  }

to be enums

Originally posted by @johnstairs in #2 (comment)

FHIR OpenAPI / Swagger Generation

Hi,

I am trying to find a way to get a full OpenAPI / Swagger definition file for an Azure FHIR API Service.
I asked the azure support and they have redirected to this project.

I have tried to generate a swagger file from R4 definition but I am having difficulties.
If I try with the R4 from package with this command :
fhir-codegen-cli.exe --load-r4 latest --fhir-spec-directory c:\temp\fhirR4 --language OpenApi --output-path c:\temp\FhirR4.json

I can see that there is an error "duplicate property found : Laterality" and the output file seems missing objects like Account

Starting FhirCacheService...
 <<< using cache directory: C:\Users\sthomas\.fhir
 << cache contains 2 packges
Starting FhirManager...
GetPackageVersionsAndUrls <<< Package http://packages2.fhir.org/packages/hl7.fhir.r4.expansions contains NO versions
LoadCached <<< Loaded and Parsed FHIR R4 with 0 errors and 1 warnings

Errors (only able to pass with manual code changes)
Warnings (able to pass, but should be reviewed)
 - CodeSystem SNOMED_CT (snomedct): Duplicate proprety found: Laterality
Loaded hl7.fhir.r4.core#latest as hl7.fhir.r4.core version 4.0.1
+ c:\code\temp\R4.json
Done! Loading: 4.413s, Total: 5.025s

But If I try from the api fhir Service Url there is another error and there is no output :

fhir-codegen-cli.exe --fhir-server-url https://fhirwspocpublic-apiservice.fhir.azurehealthcareapis.com/metadata --language OpenAPI --output-path c:\code\temp\FHIRR4_cli.json
Starting FhirCacheService...
 <<< using cache directory: C:\Users\sthomas\.fhir
 << cache contains 2 packges
Starting FhirManager...
Requesting metadata from https://fhirwspocpublic-apiservice.fhir.azurehealthcareapis.com/metadata...
Connected to https://fhirwspocpublic-apiservice.fhir.azurehealthcareapis.com/metadata, FHIR version: 4.0.1
Server Information from https://fhirwspocpublic-apiservice.fhir.azurehealthcareapis.com/metadata:
            FHIR Version: 4.0.1
           Software Name: Azure Healthcare APIs
        Software Version: 2.3.60
            Release Date:
             Description:
               Resources: 146
GetPackageVersionsAndUrls <<< Package http://packages2.fhir.org/packages/hl7.fhir.r4.expansions contains NO versions
LoadCached <<< Loaded and Parsed FHIR R4 with 0 errors and 1 warnings

Errors (only able to pass with manual code changes)
Warnings (able to pass, but should be reviewed)
 - CodeSystem SNOMED_CT (snomedct): Duplicate proprety found: Laterality
Loaded hl7.fhir.r4.core#latest as hl7.fhir.r4.core version 4.0.1
Unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Health.Fhir.SpecManager.Models.FhirServerInfo..ctor(FhirServerInfo source, FhirVersionInfo info) in C:\code\fhir-codegen\src\Microsoft.Health.Fhir.SpecManager\Models\FhirServerInfo.cs:line 139
   at Microsoft.Health.Fhir.SpecManager.Manager.Exporter.Export(FhirVersionInfo sourceFhirInfo, FhirServerInfo sourceServerInfo, ILanguage exportLanguage, ExporterOptions options, String outputPath, Boolean isPartOfBatch) in C:\code\fhir-codegen\src\Microsoft.Health.Fhir.SpecManager\Manager\Exporter.cs:line 136
   at FhirCodegenCli.Program.Process(String fhirSpecDirectory, String outputPath, Boolean verbose, Boolean offlineMode, String language, String exportKeys, String loadR2, String loadR3, String loadR4, String loadR4B, String loadR5, String languageOptions, Boolean officialExpansionsOnly, String fhirServerUrl, Boolean includeExperimental, String exportTypes, String extensionSupport, Boolean languageHelp, String packageDirectory, String packages, String ciBranch, String languageInputDir) in C:\code\fhir-codegen\src\fhir-codegen-cli\Program.cs:line 544
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.CommandLine.NamingConventionBinder.ModelBindingCommandHandler.InvokeAsync(InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass4_0.<<BuildInvocationChain>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass22_0.<<UseParseErrorReporting>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass15_0.<<UseHelp>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass26_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass24_0.<<UseTypoCorrections>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<UseSuggestDirective>b__23_0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass21_0.<<UseParseDirective>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<UseDebugDirective>b__8_0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c.<<RegisterWithDotnetSuggest>b__7_0>d.MoveNext()
--- End of stack trace from previous location ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass11_0.<<UseExceptionHandler>b__0>d.MoveNext()

Can you please help me on what I am doing wrong ?

Be able to generate code/classes for any package, not just core specs

It would be super useful if fhir-codegen could generate classes from any FHIR package. Right now it is limited to the core packages, but Gino mentioned this is not too far off?

I have heard multiple customers asking for this, to get them started with implementing a specification with strong typing/validation.

Previously discussed at https://chat.fhir.org/#narrow/stream/179171-dotnet/topic/Microsoft.20fhir-codegen-cli/near/383002869

TypeScript_R2 - bug in QuestionnaireResponseGroup

QuestionnaireResponseGroup

This...

export interface QuestionnaireResponseGroup extends BackboneElement {
  /**
   * Reports can consist of complex nested groups.
   */
  group?: QuestionnaireGroup[];

should be this...

export interface QuestionnaireResponseGroup extends BackboneElement {
  /**
   * Reports can consist of complex nested groups.
   */
  group?: QuestionnaireResponseGroup[];

BTW - This was the only bug I found in R2 :)

Handle unknown elements

Maybe we can extend the POCOs to have a backing dictionary to store unknown elements. Use a lazy dictionary?

Consider splitting into two language options for different use cases

I could imagine two variants of the codegen: one optimized for programmer-friendliness, the other optimized for performance. Take this class for example:

  public class DataRequirementSort : Element {
    [JsonProperty("direction")]
    public string Direction { get; set; }
    [JsonProperty("_direction")]
    public Element _Direction { get; set; }
    [JsonProperty("path")]
    public string Path { get; set; }
    [JsonProperty("_path")]
    public Element _Path { get; set; }
  }

For developer-friendliness, it might look like this:

public class DataRequirementSort : Element 
{
    [JsonProperty("direction")]
    public Element<string> Direction { get; set; }
    [JsonProperty("path")]
    public Element<string> Path { get; set; }
}

internal class Element<T>
{
    public Element<string> Id { get; set; }
    public Extension[] Extensions { get; set; }
    public T Value { get; set; }
}

For server-side performance, it might look more like this, given that extensions on primitive types are probably exceedingly rare:

internal class DataRequirementSort : Element
{
    private Dictionary<int, Element> _primitiveElements;

    [JsonProperty("direction")]
    public string Direction { get; set; }
    
    [JsonProperty("_direction")]
    public Element _Direction
    {
        get => GetPrimitiveElement(0);
        set => SetPrimitiveElement(0, value);
    }
    
    [JsonProperty("path")]
    public string Path { get; set; }
    
    [JsonProperty("_path")]
    public Element _Path
    {
        get => GetPrimitiveElement(0);
        set => SetPrimitiveElement(0, value);
    }

    private Element GetPrimitiveElement(int id)
    {
        Element value = null;
        _primitiveElements?.TryGetValue(id, out value);
        return value;
    }

    private void SetPrimitiveElement(int id, Element value)
    {
        (_primitiveElements ?? (_primitiveElements = new Dictionary<int, Element>()))[id] = value;
    }
}

Originally posted by @johnstairs in #2 (comment)

Add Source generation for custom resources

My company is looking into using more and more custom FHIR resources, So I'm looking to develop a source generator to auto generate the resource code based on the structure definition. My idea is that it will look for files with a name that ends with .StructureDefinition.json and then generate code from those files.

I tried my hand in this but I think this could work.
image

I'm currently working on this branch:
https://github.com/almostchristian/fhir-codegen/tree/feature/sourcegen

Some issues that I'm looking to resolving:

  • change namespace to be the same as the <assemblyname>.<folder.path> instead of the constant namespace. This should be a simple change. supported in latest change
  • nested enum and generic Code<T> property generation, I'm still trying to figure out how to get this to work. supported in latest change

Broken on Apple silicon M1 arm64 machines

After building on an M1 macOS machine successfully with a brew install dotnet v6.0.103, running the project results in the following error attempting to link in an x64 library. How do you build and run on machines using Apple's current M1 chips? The link printed by the runtime leads me to believe this should work somehow.

`
➜ fhir-codegen git:(main) dotnet run --project src/fhir-codegen-cli
Failed to load Q, error: dlopen(/opt/homebrew/Cellar/dotnet/6.0.103/libexec/host/fxr/6.0.3/libhostfxr.dylib, 0x0001): tried: '/opt/homebrew/Cellar/dotnet/6.0.103/libexec/host/fxr/6.0.3/libhostfxr.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))
The library libhostfxr.dylib was found, but loading it from /opt/homebrew/Cellar/dotnet/6.0.103/libexec/host/fxr/6.0.3/libhostfxr.dylib failed

Generate extension classes from IG

I am currently using the fhir-codegen to generate the vallue sets frome the FrCore Project.

I would like to know if it would be possible to generate the classes that represents the extension. From what i've read, i've understood that for the moment it is not possible to generate classes for the profiles according to their structure definition, but what about the extensions and the slices (for example the Identifiers for Patient ) ? It would make me avoid to write the extensions classes manually and generate them from the tool..

Thank's for reading and for your attention !

Structurally refactor TypeScript output similar to C# output for direct implementation

(Let me know if you'd prefer I split this issue up more!)

We've been doing some prototypes based on the TypeScript R4 .ts file, and have run into a few challenges I think could benefit from some general refactoring.

First is the lack of a .d.ts file. We tried simply renaming the .ts, but it doesn't work since .d.ts declarations can't have initializers. (Might be other issues.) Second is general performance. The file is > 400,000 lines long, causing editors to choke. Even when cherrypicking specific imports, VS Code, at least, seems to not handle the single file approach well. Third is the general approach to generics covered in #70 that makes it very challenging to implement concrete class definitions for FHIR profiles imposing type and cardinality constraints.

If the direction is to also provide a set of class definitions like the C# version -- which we would love and appreciate! -- I would suggest breaking up the output file substantially, implement some uses of generics (at least for frequently used types), and to add a corresponding concrete class hierarchy with essentially the same deep copy and serialization-type functions as C# outputs.

All this would really make it directly usable for SMART and general FHIR developers. At the moment we can't really base our class definitions off of it because we're trying to enforce profile constraints at a more granular, static level.

Make "Reference" type generic?

Would it be possible to make the TypeScript version of Reference generic? It is very difficult to enforce constraints without this, and TypeScript supports complex "A | B | C | D"-style generics.

We are trying to strictly enforce all manner of constraints in our information models for both IG publishing and software development purposes, and such refinements would be very welcome!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.