@atomic-ehr/codegen 0.0.4-canary.20251218085438.283b979 → 0.0.4-canary.20251218111944.d18e50d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -84,7 +84,7 @@ yarn add @atomic-ehr/codegen
84
84
  See the [examples/](examples/) directory for working demonstrations:
85
85
 
86
86
  - **[typescript-r4/](examples/typescript-r4/)** - FHIR R4 type generation with resource creation demo and profile usage
87
- - **[typescript-ccda/](examples/typescript-ccda/)** - C-CDA on FHIR type generation
87
+ - **[typescript-ccda/](examples/typescript-ccda/)** - C-CDA on FHIR type generation
88
88
  - **[typescript-sql-on-fhir/](examples/typescript-sql-on-fhir/)** - SQL on FHIR ViewDefinition with tree shaking
89
89
  - **[python/](examples/python/)** - Python/Pydantic model generation with configurable field formats
90
90
  - **[csharp/](examples/csharp/)** - C# class generation with namespace configuration
@@ -193,6 +193,32 @@ Tree shaking optimizes the generated output by including only the resources you
193
193
 
194
194
  This feature automatically resolves and includes all dependencies (referenced types, base resources, nested types) while excluding unused resources, significantly reducing the size of generated code and improving compilation times.
195
195
 
196
+ ##### Field-Level Tree Shaking
197
+
198
+ Beyond resource-level filtering, tree shaking supports fine-grained field selection using `selectFields` (whitelist) or `ignoreFields` (blacklist):
199
+
200
+ ```typescript
201
+ .treeShake({
202
+ "hl7.fhir.r4.core#4.0.1": {
203
+ "http://hl7.org/fhir/StructureDefinition/Patient": {
204
+ selectFields: ["id", "name", "birthDate", "gender"]
205
+ },
206
+ "http://hl7.org/fhir/StructureDefinition/Observation": {
207
+ ignoreFields: ["performer", "note"]
208
+ }
209
+ }
210
+ })
211
+ ```
212
+
213
+ **Configuration Rules:**
214
+ - `selectFields`: Only includes the specified fields (whitelist approach)
215
+ - `ignoreFields`: Removes specified fields, keeps everything else (blacklist approach)
216
+ - These options are **mutually exclusive** - you cannot use both in the same rule
217
+
218
+ **Polymorphic Field Handling:**
219
+
220
+ FHIR choice types (like `multipleBirth[x]` which can be boolean or integer) are handled intelligently. Selecting/ignoring the base field affects all variants, while targeting specific variants only affects those types.
221
+
196
222
  ### Generation
197
223
 
198
224
  The generation stage uses a `WriterGenerator` system that transforms Type Schema into target language code. The architecture consists of:
package/dist/cli/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import k from'picocolors';import Jr from'yargs';import {hideBin}from'yargs/helpers';import*as R from'fs';import R__default,{existsSync}from'fs';import*as I from'path';import I__default,{dirname,resolve}from'path';import*as _ from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import Pt from'assert';import {fileURLToPath}from'url';import*as xt from'yaml';import*as Dt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';var q=class i{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,level:1,...e};}shouldLog(e){let t=this.options.level??1;return e>=t}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let o=this.options.timestamp?`${k.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${k.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${r(e)} ${n}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e)||!this.shouldLog(e))return;(i.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,k.green));}error(e,t){if(this.isSuppressed(3)||!this.shouldLog(3))return;console.error(this.formatMessage("X",e,k.red));let r=this.options.level===0;t&&r&&(console.error(k.red(` ${t.message}`)),t.stack&&console.error(k.gray(t.stack)));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,k.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,k.blue));}debug(e){this.shouldLog(0)&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,k.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,k.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,k.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${k.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${k.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${o}${t(e)}`);}dim(e){this.plain(e,k.gray);}child(e){return new i({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}getLevel(){return this.options.level??1}setLevel(e){this.options.level=e;}},V=new q;function $e(i){V.success(i);}function F(i,e){V.error(i,e);}function Xe(i){V.warn(i);}function we(i){V.info(i);}function Qe(i){V.step(i);}function Kt(i){V.dim(i);}function Ze(i){V.configure(i);}function O(i={}){return new q(i)}function et(i){console.log(),console.log(k.cyan(k.bold(`\u2501\u2501\u2501 ${i} \u2501\u2501\u2501`)));}function tt(i,e,t){let r=i;e&&(r+=` ${k.gray(`(${e}ms)`)}`),$e(r),t&&Object.entries(t).forEach(([o,n])=>{Kt(` ${o}: ${n}`);});}function K(i,e="\u2022"){i.forEach(t=>{console.log(k.gray(` ${e} ${t}`));});}var ae=i=>i.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),rt=i=>ae(i).map(e=>e.toLowerCase()).join("-"),it=i=>{if(i.length===0)throw new Error("Empty string");return i[0]?.toUpperCase()+i.substring(1).toLowerCase()},ce=i=>{if(i.length===0)throw new Error("Empty string");let[e,...t]=ae(i);return [e?.toLowerCase(),...t.map(it)].join("")},P=i=>ae(i).map(it).join(""),$=i=>ae(i).map(e=>e.toLowerCase()).join("_"),w=i=>!i||i.length===0?i:i.charAt(0).toUpperCase()+i.slice(1),J=i=>i.map(e=>w(e));var nt=i=>`<${i.identifier.url}> from ${i.identifier.package}#${i.identifier.version}`;var Ee=class{opts;currentDir;currentFile;writtenFilesBuffer={};constructor(e){this.opts=e;}setOutputDir(e){if(this.currentDir)throw new Error("Can't change output dir while writing");this.opts.outputDir=e;}logger(){return this.opts.logger}onDiskMkDir(e){this.opts.inMemoryOnly||R.existsSync(e)||R.mkdirSync(e,{recursive:true});}onDiskOpenFile(e){return this.opts.inMemoryOnly?-1:R.openSync(e,"w")}onDiskCloseFile(e){this.opts.inMemoryOnly||(R.fsyncSync(e),R.closeSync(e));}onDiskWrite(e,t){this.opts.inMemoryOnly||R.writeSync(e,t);}cd(e,t){let r=this.currentDir;this.currentDir=e.startsWith("/")?I.join(this.opts.outputDir,e):I.join(this.currentDir??this.opts.outputDir,e),this.onDiskMkDir(this.currentDir),this.logger()?.debug(`cd '${this.currentDir}'`),t(),this.currentDir=r;}cat(e,t){if(this.currentFile)throw new Error("Can't open file when another file is open");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let r=I.normalize(`${this.currentDir}/${e}`);try{let o=this.onDiskOpenFile(r);this.logger()?.debug(`cat > '${r}'`),this.currentFile={descriptor:o,relPath:r},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:r,absPath:I.resolve(r),tokens:[]},t();}finally{this.currentFile&&this.onDiskCloseFile(this.currentFile.descriptor),this.currentFile=void 0;}}write(e){if(!this.currentFile)throw new Error("No file opened");this.onDiskWrite(this.currentFile.descriptor,e);let t=this.writtenFilesBuffer[this.currentFile.relPath];if(!t)throw new Error("No buffer found");t.tokens.push(e);}writtenFiles(){return Object.values(this.writtenFilesBuffer).map(({relPath:e,absPath:t,tokens:r})=>({relPath:e,absPath:t,content:r.join()})).sort((e,t)=>e.relPath.localeCompare(t.relPath))}},L=class extends Ee{currentIndent=0;indent(){this.currentIndent+=this.opts.tabSize;}deindent(){this.currentIndent-=this.opts.tabSize;}writeIndent(){this.write(" ".repeat(this.currentIndent));}line(...e){e.length===0?this.write(`
2
+ import T from'picocolors';import Zr from'yargs';import {hideBin}from'yargs/helpers';import*as R from'fs';import R__default,{existsSync}from'fs';import*as P from'path';import P__default,{dirname,resolve}from'path';import*as V from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import ne from'assert';import {fileURLToPath}from'url';import*as Ct from'yaml';import*as Ot from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';var J=class i{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,level:1,...e};}shouldLog(e){let t=this.options.level??1;return e>=t}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let o=this.options.timestamp?`${T.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${T.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${r(e)} ${n}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e)||!this.shouldLog(e))return;(i.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,T.green));}error(e,t){if(this.isSuppressed(3)||!this.shouldLog(3))return;console.error(this.formatMessage("X",e,T.red));let r=this.options.level===0;t&&r&&(console.error(T.red(` ${t.message}`)),t.stack&&console.error(T.gray(t.stack)));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,T.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,T.blue));}debug(e){this.shouldLog(0)&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,T.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,T.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,T.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${T.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${T.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${o}${t(e)}`);}dim(e){this.plain(e,T.gray);}child(e){return new i({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}getLevel(){return this.options.level??1}setLevel(e){this.options.level=e;}},A=new J;function Ee(i){A.success(i);}function F(i,e){A.error(i,e);}function Ze(i){A.warn(i);}function Ne(i){A.info(i);}function et(i){A.step(i);}function Yt(i){A.dim(i);}function tt(i){A.configure(i);}function M(i={}){return new J(i)}function rt(i){console.log(),console.log(T.cyan(T.bold(`\u2501\u2501\u2501 ${i} \u2501\u2501\u2501`)));}function it(i,e,t){let r=i;e&&(r+=` ${T.gray(`(${e}ms)`)}`),Ee(r),t&&Object.entries(t).forEach(([o,n])=>{Yt(` ${o}: ${n}`);});}function K(i,e="\u2022"){i.forEach(t=>{console.log(T.gray(` ${e} ${t}`));});}var ce=i=>i.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),nt=i=>ce(i).map(e=>e.toLowerCase()).join("-"),ot=i=>{if(i.length===0)throw new Error("Empty string");return i[0]?.toUpperCase()+i.substring(1).toLowerCase()},le=i=>{if(i.length===0)throw new Error("Empty string");let[e,...t]=ce(i);return [e?.toLowerCase(),...t.map(ot)].join("")},w=i=>ce(i).map(ot).join(""),$=i=>ce(i).map(e=>e.toLowerCase()).join("_"),E=i=>!i||i.length===0?i:i.charAt(0).toUpperCase()+i.slice(1),Y=i=>i.map(e=>E(e));var st=i=>`<${i.identifier.url}> from ${i.identifier.package}#${i.identifier.version}`;var De=class{opts;currentDir;currentFile;writtenFilesBuffer={};constructor(e){this.opts=e;}setOutputDir(e){if(this.currentDir)throw new Error("Can't change output dir while writing");this.opts.outputDir=e;}logger(){return this.opts.logger}onDiskMkDir(e){this.opts.inMemoryOnly||R.existsSync(e)||R.mkdirSync(e,{recursive:true});}onDiskOpenFile(e){return this.opts.inMemoryOnly?-1:R.openSync(e,"w")}onDiskCloseFile(e){this.opts.inMemoryOnly||(R.fsyncSync(e),R.closeSync(e));}onDiskWrite(e,t){this.opts.inMemoryOnly||R.writeSync(e,t);}cd(e,t){let r=this.currentDir;this.currentDir=e.startsWith("/")?P.join(this.opts.outputDir,e):P.join(this.currentDir??this.opts.outputDir,e),this.onDiskMkDir(this.currentDir),this.logger()?.debug(`cd '${this.currentDir}'`),t(),this.currentDir=r;}cat(e,t){if(this.currentFile)throw new Error("Can't open file when another file is open");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let r=P.normalize(`${this.currentDir}/${e}`);try{let o=this.onDiskOpenFile(r);this.logger()?.debug(`cat > '${r}'`),this.currentFile={descriptor:o,relPath:r},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:r,absPath:P.resolve(r),tokens:[]},t();}finally{this.currentFile&&this.onDiskCloseFile(this.currentFile.descriptor),this.currentFile=void 0;}}write(e){if(!this.currentFile)throw new Error("No file opened");this.onDiskWrite(this.currentFile.descriptor,e);let t=this.writtenFilesBuffer[this.currentFile.relPath];if(!t)throw new Error("No buffer found");t.tokens.push(e);}writtenFiles(){return Object.values(this.writtenFilesBuffer).map(({relPath:e,absPath:t,tokens:r})=>({relPath:e,absPath:t,content:r.join()})).sort((e,t)=>e.relPath.localeCompare(t.relPath))}},B=class extends De{currentIndent=0;indent(){this.currentIndent+=this.opts.tabSize;}deindent(){this.currentIndent-=this.opts.tabSize;}writeIndent(){this.write(" ".repeat(this.currentIndent));}line(...e){e.length===0?this.write(`
3
3
  `):(this.writeIndent(),this.write(`${e.join(" ")}
4
4
  `));}lineSM(...e){this.writeIndent(),this.write(`${e.join(" ")};
5
5
  `);}comment(...e){let t=e.join(" ").split(`
6
- `);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/atomic-ehr/codegen","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>{this.comment(e);}),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var le=(i,e=true)=>{let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t};var v=i=>`${i.name}#${i.version}`,pe=i=>`${i.name}@${i.version}`;var Ne=(i,e)=>(e||(e={name:"undefined",version:"undefined"}),{...i,package_meta:i.package_meta||e,name:i.name,url:i.url,base:i.base}),Q=i=>i?.kind==="primitive-type",M=i=>i?.kind==="nested",ot=i=>i?.kind==="complex-type",st=i=>i?.kind==="profile";var A=i=>i?.identifier.kind==="resource"||i?.identifier.kind==="complex-type"||i?.identifier.kind==="logical",at=i=>i?.identifier.kind==="complex-type",E=i=>i?.identifier.kind==="resource",ct=i=>i?.identifier.kind==="primitive-type",B=i=>i?.identifier.kind==="logical",de=i=>i?.identifier.kind==="profile";function lt(i){return i?.identifier.kind==="binding"}function pt(i){return i?.identifier.kind==="value-set"}var Z=i=>i?i.choices===void 0:false,H=i=>i?i.choices!==void 0:false,dt=(i,e)=>{if(!i.url)throw new Error("ValueSet must have a URL");if(!i.name)throw new Error("ValueSet must have a name");return {...i,package_meta:i.package_meta||e,name:i.name,url:i.url}};var ut={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Jt(i){return i.split("-").map(e=>w(e)).join("-")}function Yt(i){let e=i;for(let t in ut)e=e.replaceAll(t,ut[t]??"");return e}function Xt(i){let e=Number(i[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${i}`:i}function gt(i){let e=Jt(i);return e=Xt(e),e=Yt(e),e=w(e),e}function N(i){return w(ce(i.replaceAll(".","-")))}var Qt={boolean:"bool",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"decimal",integer:"int",unsignedInt:"long",positiveInt:"long",integer64:"long",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},Zt=["Reference","Expression"],er=i=>i.required?["required"]:[],tr=i=>{let e=yt(ht(i.identifier));return w(e)},rr=i=>i.base?`: ${i.base.name}`:"",ir=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),N(t)},ht=i=>{if(i.kind==="nested"){let e=i.url,t=ir(e,false);if(!t)return "";let[r,o]=t.split("#"),n=J((o??"").split(".")).join("");return N([r,n].join(""))}return N(i.name)},nr=i=>Zt.includes(i),yt=i=>nr(i)?`Resource${i}`:i,ue=class extends L{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),r=e.collectResources(),o=Array.from(new Set(r.map(n=>N(n.identifier.package))));this.generateAllFiles(t,r,o),this.copyStaticFiles();}generateAllFiles(e,t,r){this.generateUsingFile(r),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(r),this.generateResourceDictionaries(t,r),this.generateHelperFile();}generateType(e,t){let r=tr(e),o=rr(e);this.curlyBlock(["public","class",r,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let r=Object.entries(e.fields).sort(([o],[n])=>o.localeCompare(n));for(let[o,n]of r)this.generateField(o,n,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let r of e.nested)this.generateType(r,t);}}generateField(e,t,r){try{if(H(t))return;let o=this.buildFieldDeclaration(e,t,r);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,r){let o=this.determineFieldType(e,t,r),n=er(t),s=P(e);return ["public",...n,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,r){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,r)),o=yt(o);let n="",s=t.required?"":"?",c=t.array?"[]":"";return `${n}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=ht(e.type):e.type.kind==="primitive-type"&&(t=Qt[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,r){let n=`${N(t.binding?.name??e)}Enum`;return this.enums[r]||(this.enums[r]={}),t.enum&&(this.enums[r][n]=t.enum),n}includeHelperMethods(){this.line("public override string ToString() => "),this.line(" JsonSerializer.Serialize(this, Helper.JsonSerializerOptions);"),this.line();}generateUsingFile(e){this.cd("/",async()=>{this.cat("Usings.cs",()=>{this.generateDisclaimer(),this.generateGlobalUsings(e);});});}generateGlobalUsings(e){let t=["CSharpSDK","System.Text.Json","System.Text.Json.Serialization",this.opts.targetNamespace,...e.map(r=>`${this.opts.targetNamespace}.${r}`)];for(let r of t)this.lineSM("global","using",r);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.targetNamespace);for(let t of e){let r=N(t.identifier.package);this.generateType(t,r);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=N(e.identifier.package);this.cd(`/${t}`,async()=>{this.cat(`${e.identifier.name}.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",`${this.opts.targetNamespace}.${t}`),this.line(),this.generateType(e,t);});});}generateEnumFiles(e){for(let t of e)this.generatePackageEnums(t);}generatePackageEnums(e){let t=this.enums[e];!t||Object.keys(t).length===0||this.cd(`/${e}`,async()=>{this.cat(`${e}Enums.cs`,()=>{this.generateDisclaimer(),this.generateEnumFileContent(e,t);});});}generateEnumFileContent(e,t){this.lineSM("using","System.ComponentModel"),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}.${e}`);for(let[r,o]of Object.entries(t))this.generateEnum(r,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let r of t)this.line(`[Description("${r}")]`),this.line(`${gt(r)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let r of t){let o=e.filter(n=>N(n.identifier.package)===r);if(o.length===0)return;this.cat(`${r}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(r,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let r of t){let o=r.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=I__default.resolve(this.opts.staticSourceDir);R__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=I__default.join(this.opts.outputDir,"Helper.cs");R__default.copyFileSync(e,t);}};function De(i){let e=i.split("|")[0];return e||i}function or(i){return i.split("|")[1]}function sr(i){return i.derivation==="constraint"?"profile":i.kind==="primitive-type"?"primitive-type":i.kind==="complex-type"?"complex-type":i.kind==="resource"?"resource":i.kind==="logical"?"logical":"resource"}function G(i){return {kind:sr(i),package:i.package_meta.name,version:i.package_meta.version,name:i.name,url:i.url}}var ar=i=>{let e=i.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):i};function ge(i,e,t){let r=De(t),o=ar(r),n={package_meta:{name:"missing_valuesets",version:or(r)||"0.0.0"},id:t},s=i.resolveVs(e,r)||n,c=s?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(s.id)?s.id:o;return {kind:"value-set",package:s.package_meta.name,version:s.package_meta.version,name:c,url:r}}function fe(i,e,t){let r=e.join("."),[o,n,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[i.package_meta,`${i.name}.${r}_binding`,`${i.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:n,url:s}}function me(i,e,t,r){let o={};if(e.derivation==="constraint"){let a=i.resolveFsSpecializations(e.package_meta,e.url).map(l=>Oe(i,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let n=t.join("."),s=o[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:s}}function St(i,e,t){let r=[];for(let[o,n]of Object.entries(t)){let s=[...e,o];ee(n)&&r.push([s,n]),n.elements&&r.push(...St(i,s,n.elements));}return r}function cr(i,e,t,r,o){let n={};for(let[s,c]of Object.entries(r)){let a=[...t,s],l=i.resolveElementSnapshot(e,a);ee(l)?n[s]=ye(i,e,a,l,o):n[s]=he(i,e,a,l,o);}return n}function Oe(i,e,t){if(!e.elements)return;let r=St(e,[],e.elements).filter(([n,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[n,s]of r){let c=me(i,e,n,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=i.ensureSpecializationCanonicalUrl(a),p=i.resolveFs(e.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${a}`);let m={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:a,url:l},y=cr(i,e,n,s.elements??{},t),d={identifier:c,base:m,fields:y};o.push(d);}return o.sort((n,s)=>n.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function bt(i){let e=[];for(let t of i){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function vt(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.required||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.required||[]});return new Set(n).has(r)}function Ct(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.excluded||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.excluded||[]});return new Set(n).has(r)}var lr=(i,e,t)=>{if(t.refers)return t.refers.map(r=>{let o=i.ensureSpecializationCanonicalUrl(r),n=i.resolveFs(e.package_meta,o);if(!n)throw new Error(`Failed to resolve fs for ${o}`);return G(n)})};function Le(i,e,t,r,o){if(r.elementReference){let n=r.elementReference.slice(1).filter((s,c)=>c%2===1);return me(i,e,n,o)}else if(r.type){let n=i.ensureSpecializationCanonicalUrl(r.type),s=i.resolveFs(e.package_meta,n);if(!s)throw new Error(`Could not resolve field type: '${r.type}' (from '${e.url}' in '${v(e.package_meta)}')`);return G(s)}else {if(r.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(r,void 0,2)}`),new Error("Unrecognized element type")}}var he=(i,e,t,r,o)=>{let n,s;r.binding&&(n=fe(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(s=Me(i,e,r,o)));let c=Le(i,e,t,r,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:vt(i,e,t),excluded:Ct(i,e,t),reference:lr(i,e,r),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:s}};function ee(i){let e=i.type==="BackboneElement",t=i.type==="Element"&&i.elements!==void 0&&Object.keys(i.elements).length>0,r=i.type===void 0&&i.choiceOf===void 0&&i.elements!==void 0&&Object.keys(i.elements).length>0;return e||t||r}function ye(i,e,t,r,o){return {type:me(i,e,t,o),array:r.array||false,required:vt(i,e,t),excluded:Ct(i,e,t)}}function Be(i,e,t,r){let o=De(t)||t,n=i.resolveVs(e,o);if(n)return dr(i,n)}function dr(i,e,t){if(e.expansion?.contains)return e.expansion.contains.filter(o=>o.code!==void 0).map(o=>(Pt(o.code),{code:o.code,display:o.display,system:o.system}));let r=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let n of o.concept)r.push({system:o.system,code:n.code,display:n.display});else if(o.system&&!o.filter)try{let n=i.resolveAny(o.system);if(n?.concept){let s=(c,a)=>{for(let l of c)r.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(n.concept,o.system);}}catch{}}return r.length>0?r:void 0}var kt=100;function Me(i,e,t,r){if(!t.binding)return;let o=t.binding.strength,n=t.binding.valueSet;if(!n||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Be(i,e.package_meta,n);if(!c||c.length===0)return;let a=c.map(l=>l.code).filter(l=>l&&typeof l=="string"&&l.trim().length>0);if(a.length>kt){r?.dry_warn(`Value set ${n} has ${a.length} which is more than ${kt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function ur(i,e,t,r,o){if(!r.binding?.valueSet)return;let n=fe(e,t,r.binding.bindingName),s=Le(i,e,t,r,o),c=ge(i,e.package_meta,r.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Me(i,e,r,o);return {identifier:n,type:s,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function Tt(i,e,t){let r=new Set;if(!e.elements)return [];let o=[];function n(a,l){for(let[p,m]of Object.entries(a)){let y=[...l,p],d=y.join(".");if(!r.has(d)){if(r.add(d),m.binding){let f=ur(i,e,y,m,t);f&&o.push(f);}m.elements&&n(m.elements,y);}}}n(e.elements,[]),o.sort((a,l)=>a.identifier.name.localeCompare(l.identifier.name));let s=[],c=new Set;for(let a of o)c.has(a.identifier.url)||(c.add(a.identifier.url),s.push(a));return s}function gr(i,e,t,r,o){if(!r)return;let n={};for(let s of i.getAllElementKeys(r)){let c=[...t,s],a=i.resolveElementSnapshot(e,c);ee(a)?n[s]=ye(i,e,c,a,o):n[s]=he(i,e,c,a,o);}return n}function fr(i){let e=[];for(let t of Object.values(i))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function mr(i,e){return !!(i.base==="Extension"||i.base==="http://hl7.org/fhir/StructureDefinition/Extension"||i.url?.includes("/extension/")||i.url?.includes("-extension")||i.name?.toLowerCase().includes("extension")||i.type==="Extension")}async function Se(i,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=ge(i,e.package_meta,e.url),o=Be(i,e.package_meta,e.url);return {identifier:r,description:e.description,concept:o,compose:o?void 0:e.compose}}function _e(i,e,t,r){let o=[];e&&o.push(e),t&&o.push(...fr(t)),r&&o.push(...bt(r));let n={};for(let a of o)a.url!==i.url&&(n[a.url]=a);let s=new Set(r?.map(a=>a.identifier.url)),c=Object.values(n).filter(a=>st(i)||!M(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function hr(i,e,t){let r=G(e),o;if(e.base&&e.type!=="Element"){let p=i.resolveFs(e.package_meta,i.ensureSpecializationCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${v(e.package_meta)}`);o=G(p);}let n=gr(i,e,[],e.elements,t),s=Oe(i,e,t),c=_e(r,o,n,s),a={identifier:r,base:o,fields:n,nested:s,description:e.description,dependencies:c},l=Tt(i,e,t);return [a,...l]}async function be(i,e,t){let r=hr(i,e,t);if(mr(e,G(e))){let o=r[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return r}var z=i=>{let e={};for(let t of i){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e)){let o={};for(let s of r)o[JSON.stringify(s.identifier)]=s;let n=Object.values(o);n.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=n;}return e},yr=(i,e,t)=>{if(i=structuredClone(i),ct(i)||pt(i)||lt(i))return i;for(let r of e.ignoreFields??[]){if(i.fields&&!i.fields[r])throw new Error(`Field ${r} not found`);i.fields&&delete i.fields[r];}return i.dependencies=_e(i.identifier,i.base,i.fields,i.nested),i},Ft=(i,e,{resolutionTree:t,logger:r})=>{let o=[];for(let[c,a]of Object.entries(e))for(let[l,p]of Object.entries(a)){let m=i.resolveByUrl(c,l);if(!m)throw new Error(`Schema not found for ${c} ${l}`);let y=yr(m,p);o.push(y);}let n=(c,a)=>{if(c.length===0)return Object.values(a);for(let p of c)a[JSON.stringify(p.identifier)]=p;let l=[];for(let p of c)if(A(p)){if(!p.dependencies)continue;if(p.dependencies.forEach(m=>{let y=i.resolve(m);if(!y)throw new Error(`Schema not found for ${m}`);let d=JSON.stringify(y.identifier);a[d]||l.push(y);}),p.nested)for(let m of p.nested){if(M(m.identifier))continue;let y=JSON.stringify(m.identifier);a[y]||l.push(m);}}return n(l,a)},s=n(o,{});return je(s,{resolutionTree:t,logger:r})},Sr=i=>{let e={};for(let r of i)e[r.identifier.name]=r;let t={};for(let r of i){let o=r.identifier.name,n=r.base?.name;t[o]||(t[o]=[]),n&&e[n]&&t[o].push(n);}return t},br=i=>{let e=[],t={},r={},o=n=>{if(r[n])throw new Error(`Graph has cycles ${n}`);if(!t[n]){r[n]=true;for(let s of i[n]??[])o(s);r[n]=false,t[n]=true,e.push(n);}};for(let n in i)t[n]||o(n);return e},It=i=>{let e=Sr(i);return br(e).map(r=>i.find(o=>o.identifier.name===r)).filter(Boolean)},vr=i=>{let e=i.filter(n=>E(n)||B(n)),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],o=n=>{let s=t.filter(a=>a.parent.name===n.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let n of t){let s=o(n.child);for(let c of s)t.some(a=>a.parent.name===n.parent.name&&a.child.name===c.name)||r.push({parent:n.parent,child:c});}return r},je=(i,{resolutionTree:e,logger:t})=>{let r={},o=u=>{let g=u.identifier.url,S=u.identifier.package;if(r[g]||(r[g]={}),r[g][u.identifier.package]&&S!=="shared"){let C=JSON.stringify(u.identifier,void 0,2),b=JSON.stringify(r[g][S]?.identifier,void 0,2);if(C!==b)throw new Error(`Duplicate schema: ${C} and ${b}`);return}r[g][S]=u;};for(let u of i)o(u);let n=vr(i),s=u=>r[u.url]?.[u.package],c=(u,g)=>{if(e){let S=e[u]?.[g]?.[0];if(S)return r[g]?.[S.pkg.name]}return r[g]?.[u]},a=u=>n.filter(g=>g.parent.name===u.name).map(g=>g.child),l=u=>{let g=[],S=u;for(;S;){g.push(S);let C=S.base;if(C===void 0)break;let b=s(C);if(!b){t?.warn(`Failed to resolve base type: ${g.map(x=>`${x.identifier.url} (${x.identifier.kind})`).join(", ")}`);return}S=b;}return g},p=u=>{let g=l(u);if(g===void 0)throw new Error(`Failed to resolve base type: ${u.identifier.url} (${u.identifier.kind})`);return g},m=u=>{let g=p(u).find(S=>S.identifier.kind!=="profile");if(!g)throw new Error(`No non-constraint schema found in hierarchy for: ${u.identifier.name}`);return g};return {_schemaIndex:r,_relations:n,collectComplexTypes:()=>i.filter(at),collectResources:()=>i.filter(E),collectLogicalModels:()=>i.filter(B),collectProfiles:()=>i.filter(de),resolve:s,resolveByUrl:c,resourceChildren:a,tryHierarchy:l,hierarchy:p,findLastSpecialization:m,findLastSpecializationByIdentifier:u=>{let g=s(u);return g?m(g).identifier:u},flatProfile:u=>{let g=p(u),S=g.filter(D=>D.identifier.kind==="profile"),C=g.find(D=>D.identifier.kind!=="profile");if(!C)throw new Error(`No non-constraint schema found in hierarchy for ${u.identifier.name}`);let b={};for(let D of S.slice().reverse()){let oe=D;if(oe.fields)for(let[se,Ye]of Object.entries(oe.fields))b[se]?b[se]={...b[se],...Ye}:b[se]={...Ye};}let x={};for(let D of S.flatMap(oe=>oe.dependencies??[]))x[D.url]=D;let j=Object.values(x);return {...u,base:C.identifier,fields:b,dependencies:j}},isWithMetaField:u=>{let g=l(u);return g?g.filter(A).some(S=>S.fields?.meta!==void 0):false},exportTree:async u=>{let g={};for(let[C,b]of Object.entries(z(i))){g[C]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let x of b)g[C][x.identifier.kind][x.identifier.url]={};}let S=u.endsWith(".yaml")?xt.stringify(g):JSON.stringify(g,void 0,2);await _.mkdir(I.dirname(u),{recursive:true}),await _.writeFile(u,S);}}};var kr={boolean:"bool",instant:"str",time:"str",date:"str",dateTime:"str",decimal:"float",integer:"int",unsignedInt:"int",positiveInt:"PositiveInt",integer64:"int",base64Binary:"str",uri:"str",url:"str",canonical:"str",oid:"str",uuid:"str",string:"str",code:"str",markdown:"str",id:"str",xhtml:"str"},Ve={snake_case:$,PascalCase:P,camelCase:ce},Tr=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","List"]),wt=100,Rr=i=>Tr.has(i)?`${i}_`:i,xr=i=>i==="Resource"||i==="Element"?["BaseModel"]:[],Fr=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),$(t)},Ce=i=>{if(i.kind==="nested"){let e=i.url,t=Fr(e,false);if(!t)return "";let[r,o]=t.split("#"),n=J((o??"").split(".")).join("");return P([r,n].join(""))}return P(i.name)},Et=i=>{let e=I.dirname(fileURLToPath(import.meta.url));return __filename.endsWith("dist/index.js")?I.resolve(e,"..","assets","api","writer-generator","python",i):I.resolve(e,"../../..","assets","api","writer-generator","python",i)},ke=class extends L{nameFormatFunction;tsIndex;constructor(e){super(e),this.nameFormatFunction=this.getFieldFormatFunction(e.fieldFormat);}async generate(e){this.tsIndex=e;let t={groupedComplexTypes:z(e.collectComplexTypes()),groupedResources:z(e.collectResources())};this.generateRootPackages(t),this.generateSDKPackages(t);}generateRootPackages(e){this.generateRootInitFile(e),R__default.cpSync(Et("requirements.txt"),I.resolve(this.opts.outputDir,"requirements.txt"));}generateSDKPackages(e){this.generateComplexTypesPackages(e.groupedComplexTypes),this.generateResourcePackages(e);}generateComplexTypesPackages(e){for(let[t,r]of Object.entries(e))this.cd(`/${$(t)}`,()=>{this.generateBasePy(r);});}generateResourcePackages(e){for(let[t,r]of Object.entries(e.groupedResources))this.cd(`/${$(t)}`,()=>{this.generateResourcePackageContent(t,r,e.groupedComplexTypes[t]||[]);});}generateResourcePackageContent(e,t,r){let o=this.pyFhirPackageByName(e);this.generateResourcePackageInit(o,t,r),this.generateResourceFamilies(t);for(let n of t)this.generateResourceModule(n);}generateRootInitFile(e){this.cd("/",()=>{this.cat("__init__.py",()=>{this.generateDisclaimer();let t=this.collectAndImportAllModels(e);this.generateModelRebuilds(t);});});}collectAndImportAllModels(e){let t=[];for(let r of Object.keys(e.groupedResources)){let o=this.pyFhirPackageByName(r);t.push(...this.importComplexTypes(o,e.groupedComplexTypes[r])),t.push(...this.importResources(o,false,e.groupedResources[r]));}return this.line(),t}generateModelRebuilds(e){for(let t of e.sort())this.line(`${t}.model_rebuild()`);}generateBasePy(e){this.cat("base.py",()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateComplexTypes(e),this.line();});}generateComplexTypes(e){for(let t of It(e))this.generateNestedTypes(t),this.line(),this.generateType(t);}generateResourcePackageInit(e,t,r){this.cat("__init__.py",()=>{this.generateDisclaimer(),this.importComplexTypes(e,r);let o=this.importResources(e,true,t);this.line(),this.generateExportsDeclaration(r,o);});}importComplexTypes(e,t){if(!t||t.length===0)return [];let r=t.map(o=>o.identifier.name).sort();return this.pyImportFrom(`${e}.base`,...r),this.line(),r}buildImportLine(e,t){let r="";for(;e.length>0&&r.length<t;){let o=e.shift();if(!o)throw new Error("Unexpected empty entity");r.length>0&&(r+=", "),r+=o;}return e.length>0&&(r+=", \\"),r}importResources(e,t,r){if(!r||r.length===0)return [];let o=[];for(let n of r){let s=this.importOneResource(n,e);!t&&!n.fields||o.push(...s);}return o}importOneResource(e,t){let r=`${t}.${$(e.identifier.name)}`,o=this.collectResourceImportNames(e);this.pyImportFrom(r,...o);let n=[...o];if(this.shouldImportResourceFamily(e)){let s=`${e.identifier.name}Family`;this.pyImportFrom(`${t}.resource_families`,s);}return n}collectResourceImportNames(e){let t=[Ce(e.identifier)];for(let r of e.nested??[]){let o=Ce(r.identifier);t.push(o);}return t}shouldImportResourceFamily(e){return Pt(this.tsIndex!==void 0),e.identifier.kind==="resource"&&this.tsIndex.resourceChildren(e.identifier).length>0}generateExportsDeclaration(e,t){this.squareBlock(["__all__","="],()=>{let r=[...(e||[]).map(o=>o.identifier.name),...t].sort();for(let o of r)this.line(`'${o}',`);});}generateResourceModule(e){this.cat(`${$(e.identifier.name)}.py`,()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateDependenciesImports(e),this.line(),this.generateNestedTypes(e),this.line(),this.generateType(e);});}generateType(e){let t=Ce(e.identifier),r=this.getSuperClasses(e);this.line(`class ${t}(${r.join(", ")}):`),this.indentBlock(()=>{this.generateClassBody(e);}),this.line();}getSuperClasses(e){return [...e.base?[e.base.name]:[],...xr(e.identifier.name)]}generateClassBody(e){if(this.generateModelConfig(),!e.fields){this.line("pass");return}e.identifier.kind==="resource"&&this.generateResourceTypeField(e),this.generateFields(e),e.identifier.kind==="resource"&&this.generateResourceMethods(e);}generateModelConfig(){let e=this.opts.allowExtraFields?"allow":"forbid";this.line(`model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True, extra="${e}")`);}generateResourceTypeField(e){this.line(`${this.nameFormatFunction("resourceType")}: str = Field(`),this.indentBlock(()=>{this.line(`default='${e.identifier.name}',`),this.line("alias='resourceType',"),this.line("serialization_alias='resourceType',"),this.line("frozen=True,"),this.line(`pattern='${e.identifier.name}'`);}),this.line(")");}generateFields(e){let t=Object.entries(e.fields??[]).sort(([r],[o])=>r.localeCompare(o));for(let[r,o]of t){if("choices"in o&&o.choices)continue;let n=this.buildFieldInfo(r,o);this.line(`${n.name}: ${n.type}${n.defaultValue}`);}}buildFieldInfo(e,t){let r=Rr(this.nameFormatFunction(e)),o=this.determineFieldType(t),n=this.getFieldDefaultValue(t,e);return {name:r,type:o,defaultValue:n}}determineFieldType(e){let t=e?this.getBaseFieldType(e):"";return "enum"in e&&e.enum&&(t=`Literal[${e.enum.map(o=>`"${o}"`).join(", ")}]`),e.array&&(t=`PyList[${t}]`),e.required||(t=`${t} | None`),t}getBaseFieldType(e){return "type"in e&&e.type.kind==="resource"?`${e.type.name}Family`:"type"in e&&e.type.kind==="nested"?Ce(e.type):"type"in e&&e.type.kind==="primitive-type"?kr[e.type.name]??"str":"type"in e?e.type.name:""}getFieldDefaultValue(e,t){let r=`alias="${t}", serialization_alias="${t}"`;return e.required?` = Field(${r})`:` = Field(None, ${r})`}generateResourceMethods(e){let t=e.identifier.name.toString();this.line(),this.line("def to_json(self, indent: int | None = None) -> str:"),this.line(" return self.model_dump_json(exclude_unset=True, exclude_none=True, indent=indent)"),this.line(),this.line("@classmethod"),this.line(`def from_json(cls, json: str) -> ${t}:`),this.line(" return cls.model_validate_json(json)");}generateNestedTypes(e){if(e.nested){this.line();for(let t of e.nested)this.generateType(t);}}generateDefaultImports(){this.pyImportFrom("__future__","annotations"),this.pyImportFrom("pydantic","BaseModel","ConfigDict","Field","PositiveInt"),this.pyImportFrom("typing","List as PyList","Literal");}generateDependenciesImports(e){!e.dependencies||e.dependencies.length===0||(this.importComplexTypeDependencies(e.dependencies),this.importResourceDependencies(e.dependencies));}importComplexTypeDependencies(e){let t=e.filter(o=>o.kind==="complex-type"),r=this.groupDependenciesByPackage(t);for(let[o,n]of Object.entries(r))this.pyImportFrom(o,...n.sort());}importResourceDependencies(e){let t=e.filter(r=>r.kind==="resource");for(let r of t){this.pyImportType(r);let o=`${P(r.name)}Family`,n=`${this.pyFhirPackage(r)}.resource_families`;this.pyImportFrom(n,o);}}groupDependenciesByPackage(e){let t={};for(let r of e){let o=this.pyPackage(r);t[o]||(t[o]=[]),t[o].push(r.name);}return t}pyImportFrom(e,...t){let r=`from ${e} import ${t.join(", ")}`;this.shouldUseSingleLineImport(r,t)?this.line(r):this.writeMultiLineImport(e,t);}shouldUseSingleLineImport(e,t){return e.length<=wt||t.length===1}writeMultiLineImport(e,t){this.line(`from ${e} import (\\`),this.indentBlock(()=>{let r=[...t];for(;r.length>0;){let o=this.buildImportLine(r,wt);this.line(o);}}),this.line(")");}pyImportType(e){this.pyImportFrom(this.pyPackage(e),P(e.name));}generateResourceFamilies(e){Pt(this.tsIndex!==void 0);let t=Object.keys(z(e)).map(n=>`${this.opts.rootPackageName}.${n.replaceAll(".","_")}`),r={};for(let n of this.tsIndex.collectResources()){let s=this.tsIndex.resourceChildren(n.identifier).map(c=>c.name);if(s.length>0){let c=`${n.identifier.name}Family`;r[c]=s;}}let o=Object.keys(r);o.length!==0&&this.buildResourceFamiliesFile(t,r,o);}buildResourceFamiliesFile(e,t,r){this.cat("resource_families.py",()=>{this.generateDisclaimer(),this.includeResourceFamilyValidator(),this.line(),this.generateFamilyDefinitions(e,t),this.generateFamilyExports(r);});}includeResourceFamilyValidator(){let e=R__default.readFileSync(Et("resource_family_validator.py"),"utf-8");this.line(e);}generateFamilyDefinitions(e,t){this.line(`packages = [${e.map(r=>`'${r}'`).join(", ")}]`),this.line();for(let[r,o]of Object.entries(t))this.generateFamilyDefinition(r,o);}generateFamilyDefinition(e,t){let r=`${e}_resources`;this.line(`${r} = [${t.map(o=>`'${o}'`).join(", ")}]`),this.line(),this.line(`def validate_and_downcast_${e}(v: Any) -> Any:`),this.line(` return validate_and_downcast(v, packages, ${r})`),this.line(),this.line(`type ${e} = Annotated[Any, BeforeValidator(validate_and_downcast_${e})]`),this.line();}generateFamilyExports(e){this.line(`__all__ = [${e.map(t=>`'${t}'`).join(", ")}]`);}buildPyPackageName(e){return (e?[$(e)]:[""]).join(".")}pyFhirPackage(e){return this.pyFhirPackageByName(e.package)}pyFhirPackageByName(e){return [this.opts.rootPackageName,this.buildPyPackageName(e)].join(".")}pyPackage(e){return e.kind==="complex-type"?`${this.pyFhirPackage(e)}.base`:e.kind==="resource"?[this.pyFhirPackage(e),$(e.name)].join("."):this.pyFhirPackage(e)}getFieldFormatFunction(e){return Ve[e]?Ve[e]:(this.logger()?.warn(`Unknown field format '${e}'. Defaulting to SnakeCase.`),this.logger()?.warn(`Supported formats: ${Object.keys(Ve).join(", ")}`),$)}};var Ue=i=>i!==null&&typeof i=="object"&&i.resourceType==="CodeSystem";var Te=i=>i!==null&&typeof i=="object"&&i.resourceType==="ValueSet";var Ir=async(i,e)=>{let r=(await i.packageJson(e.name)).dependencies;return r!==void 0?Object.entries(r).map(([o,n])=>({name:o,version:n})):[]},Ot=i=>({pkg:i,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),Lt=async(i,e,t,r,o)=>{let n=v(e);if(o?.info(`${" ".repeat(t*2)}+ ${n}`),r[n])return r[n];let s=Ot(e);for(let a of await i.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||Te(a)||Ue(a)))continue;let p=l;s.canonicalResolution[p]&&o?.dry_warn(`Duplicate canonical URL: ${p} at ${n}.`),s.canonicalResolution[p]=[{deep:t,pkg:e,pkgId:n,resource:a}];}let c=await Ir(i,e);for(let a of c){let{canonicalResolution:l}=await Lt(i,a,t+1,r,o);for(let[p,m]of Object.entries(l)){let y=p;s.canonicalResolution[y]=[...s.canonicalResolution[y]||[],...m];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,p)=>l.deep-p.deep);return r[n]=s,s},Nt=(i,e,t)=>{let r=Object.values(i).flatMap(o=>o.canonicalResolution[e]);if(!r)throw new Error(`No canonical resolution found for ${e} in any package`);return r[0]?.resource},te=async(i,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:r})=>{let o=r??await i.packages(),n={};for(let d of o)await Lt(i,d,0,n,e);for(let{pkg:d,canonicalResolution:f}of Object.values(n)){let h=v(d);if(!n[h])throw new Error(`Package ${h} not found`);let u=0;e?.info(`FHIR Schema conversion for '${v(d)}' begins...`);for(let[g,S]of Object.entries(f)){let C=S[0];if(!C)throw new Error("Resource not found");let b=C.resource,x=C.pkg;if(isStructureDefinition(b)){let j=Ne(Dt.translate(b),x);u++,n[h].fhirSchemas[j.url]=j;}if(Te(b)){let j=dt(b,x);n[h].valueSets[j.url]=j;}}e?.info(`FHIR Schema conversion for '${v(d)}' completed: ${u} successful`);}let s=(d,f)=>n[v(d)]?.fhirSchemas[f]||t&&n[v(t)]?.fhirSchemas[f],c=(d,f)=>n[v(d)]?.valueSets[f]||t&&n[v(t)]?.valueSets[f],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,f)=>{let h=s(d,f);if(h===void 0)throw new Error(`Failed to resolve FHIR Schema: '${f}'`);let u=[h];for(;h?.base;){let g=h.package_meta,S=a(h.base);if(h=s(g,S),h===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${f}'. Problem: '${S}' from '${v(g)}'`);u.push(h);}return u};return {...i,testAppendFs(d){let f=Ne(d),h=v(f.package_meta);n[h]||(n[h]=Ot(f.package_meta)),n[h].fhirSchemas[f.url]=f;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,f)=>l(d,f).filter(h=>h.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,f)=>{let h=Nt(n,f);if(isStructureDefinition(h))return h},allFs:()=>Object.values(n).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(n).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>Nt(n,d),resolveElementSnapshot:(d,f)=>{let h=l(d.package_meta,d.url),u=Pr(h,f);return $r(u)},getAllElementKeys:d=>{let f=new Set;for(let[h,u]of Object.entries(d)){f.add(h);for(let g of u?.choices||[])d[g]||f.add(g);}return Array.from(f)},resolver:n,resolutionTree:()=>{let d={};for(let[f,h]of Object.entries(n)){let u=h.pkg.name;d[u]={};for(let[g,S]of Object.entries(h.canonicalResolution)){let C=g;d[u][C]=[];for(let b of S)d[u][C].push({deep:b.deep,pkg:b.pkg});}}return d}}};var Pr=(i,e)=>{let[t,...r]=e;return t===void 0?[]:i.map(o=>{if(!o.elements)return;let n=o.elements?.[t];for(let s of r)n=n?.elements?.[s];return n}).filter(o=>o!==void 0)};function $r(i){let e=i.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}var re=class{manager;options;logger;constructor(e){this.options={...e},this.manager=e.manager,this.logger=e.logger||O({prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(v);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),te(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],r=0,o=0;for(let n of e)try{let s=Dt.translate(n);t.push(s),r++,this.logger?.debug(`Converted StructureDefinition: ${n.name||n.id} (${n.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${n.name||n.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${r}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await te(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,s=0;for(let c of e)try{let a=await Se(r,c,t);a&&(o.push(a),n++,this.logger?.debug(`Converted ValueSet: ${c.name||c.id}`));}catch(a){s++,this.logger?.warn(`Failed to convert ValueSet ${c.name||c.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger?.success(`ValueSet conversion completed: ${n}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,r){let o={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(n.allVs(),r);return [...(await Promise.all(n.allFs().map(async l=>await be(n,l,r)))).flat(),...s]}};var ie="Use CodeableReference which is not provided by FHIR R4.",wr="Use Availability which is not provided by FHIR R4.",Bt={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":wr,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":ie,"http://hl7.org/fhir/StructureDefinition/specimen-additive":ie,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":ie,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":ie,"http://hl7.org/fhir/StructureDefinition/workflow-reason":ie},"hl7.fhir.r5.core#5.0.0":{"http://hl7.org/fhir/StructureDefinition/shareablecodesystem":"FIXME: CodeSystem.concept.concept defined by ElementReference. FHIR Schema generator output broken value in it, so we just skip it for now."}},_t=async(i,e)=>{let t=[];for(let r of i.allFs()){let o=v(r.package_meta);if(Bt[o]?.[r.url]){e?.dry_warn(`Skip ${r.url} from ${o}. Reason: ${Bt[o]?.[r.url]}`);continue}t.push(...await be(i,r,e));}for(let r of i.allVs())t.push(await Se(i,r));return t};var Er={boolean:"boolean",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"number",integer:"number",unsignedInt:"number",positiveInt:"number",integer64:"number",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},jt=i=>{let e=Er[i];if(e===void 0)throw new Error(`Unknown primitive type ${i}`);return e},Ut=i=>rt(i),ze=i=>i.kind==="profile"?`${T(i)}_profile`:P(i.name),Nr=i=>`${ze(i)}.ts`,Re=i=>`${Ut(i.package)}/${ze(i)}`,He=(i,e=true)=>{if(!i)return;let t=le(i,e);if(t)return Ge(t)},T=i=>{if(i.kind==="nested"){let e=i.url,t=He(e,false);if(!t)return "";let[r,o]=t.split("#"),n=J((o??"").split(".")).join("");return Ge([r,n].join(""))}return Ge(i.name)},At=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),X=i=>At.has(i)?`"${i}"`:i.includes(" ")||i.includes("-")?`"${i}"`:i,Ge=i=>(At.has(i)&&(i=`${i}_`),i.replace(/[- ]/g,"_")),W=(i,e)=>e.startsWith('"')?`${i}[${e}]`:`${i}.${e}`,Vt=i=>`(${i.map(e=>`"${e}"`).join(" | ")})`,xe=class extends L{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(r=>[{identifier:r.identifier,tsPackageName:ze(r.identifier),resourceName:T(r.identifier),nestedTypes:E(r)&&r.nested||B(r)&&r.nested?r.nested.map(o=>T(o.identifier)):[],helpers:E(r)||B(r)?[`is${T(r.identifier)}`]:[]}]).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${[r.resourceName,...r.nestedTypes].join(", ")} } from "./${r.tsPackageName}"`),r.helpers.length>0&&this.lineSM(`export { ${r.helpers.join(", ")} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e,t){if(t.dependencies){let r=[],o=[];for(let n of t.dependencies)if(["complex-type","resource","logical"].includes(n.kind))r.push({tsPackage:`../${Re(n)}`,name:w(n.name),dep:n});else if(M(n)){let s={...n};s.name=He(n.url),r.push({tsPackage:`../${Re(s)}`,name:T(n),dep:n});}else o.push(n);r.sort((n,s)=>n.name.localeCompare(s.name));for(let n of r)this.debugComment(n.dep),this.tsImportType(n.tsPackage,n.name);for(let n of o)this.debugComment("skip:",n);if(this.line(),this.withPrimitiveTypeExtension(t)&&t.identifier.name!=="Element"&&t.dependencies.find(n=>n.name==="Element")===void 0){let n="http://hl7.org/fhir/StructureDefinition/Element",s=e.resolveByUrl(t.identifier.package,n);if(!s)throw new Error(`'${n}' not found for ${t.identifier.package}.`);this.tsImportType(`../${Re(s.identifier)}`,"Element");}}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(ot).map(r=>({tsPackage:`../${Re(r)}`,name:w(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e){let t=X(`_${e}`);this.lineSM(`${t}?: Element`);}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=T(t.identifier));let o;if(t.base&&(o=`extends ${He(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!E(t)){this.lineSM(`export type ${r} = object`);return}this.curlyBlock(["export","interface",r,o],()=>{if(E(t)||B(t)){let s=[t.identifier];s.push(...e.resourceChildren(t.identifier));let c=this.opts.openResourceTypeSet&&s.length>1?" | string":"";this.lineSM(`resourceType: ${s.sort((a,l)=>a.name.localeCompare(l.name)).map(a=>`"${a.name}"`).join(" | ")}${c}`),this.line();}if(!t.fields)return;let n=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of n){if(H(c))continue;this.debugComment(s,":",c);let a=X(s),l;c.enum?l=Vt(c.enum):t.identifier.name==="Reference"&&a==="reference"?l="`${T}/${string}`":c.reference&&c.reference.length>0?l=`Reference<${c.reference.map(d=>`"${d.name}"`).join(" | ")}>`:Q(c.type)?l=jt(c.type.name):M(c.type)?l=T(c.type):l=c.type.name;let p=c.required?"":"?",m=c.array?"[]":"";this.lineSM(`${a}${p}: ${l}${m}`),this.withPrimitiveTypeExtension(t)&&Q(c.type)&&this.addFieldExtension(s);}});}withPrimitiveTypeExtension(e){if(!this.opts.primitiveTypeExtension||!A(e))return false;for(let t of Object.values(e.fields??{}))if(!H(t)&&Q(t.type))return true;return false}generateResourceTypePredicate(e){if(!E(e)&&!B(e))return;let t=T(e.identifier);this.curlyBlock(["export","const",`is${t}`,"=",`(resource: unknown): resource is ${t}`,"=>"],()=>{this.lineSM(`return resource !== null && typeof resource === "object" && (resource as {resourceType: string}).resourceType === "${e.identifier.name}"`);});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let r=T(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,n]of Object.entries(t.fields??{})){if(H(n))continue;this.debugComment(o,n);let s=X(o),c;if(n.enum)c=Vt(n.enum);else if(n.reference&&n.reference.length>0){let a=e.findLastSpecialization(t);if(!A(a))throw new Error(`Invalid specialization for ${t.identifier}`);let l=a.fields?.[o];if(l===void 0||H(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let p=l.reference.map(y=>y.name),m=n.reference.map(y=>{let d=e.findLastSpecializationByIdentifier(y);return d.name!==y.name?`"${d.name}" /*${y.name}*/`:`'${y.name}'`}).join(" | ");p.length===1&&p[0]==="Resource"&&m!=='"Resource"'?c=`Reference<"Resource" /* ${m} */ >`:c=`Reference<${m}>`;}else if(M(n.type))c=T(n.type);else if(Q(n.type))c=jt(n.type.name);else {if(n.type===void 0)throw new Error(`Undefined type for '${o}' field at ${nt(t)}`);c=n.type.name;}this.lineSM(`${s}${n.required?"":"?"}: ${c}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=T(e.base),r=T(e.identifier),o=Object.entries(e.fields||{}).filter(([n,s])=>s&&Z(s)&&s.type!==void 0).map(([n])=>X(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(n=>{this.line(`${n}: ${W("profile",n)},`);});});}),this.line();}generateExtractProfile(e,t){let r=T(t.base),o=T(t.identifier),n=Object.entries(t.fields||{}).filter(([a,l])=>Z(l)&&l.type!==void 0).map(([a])=>a),s=e.findLastSpecialization(t);if(!A(s))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${o}_from_${r} =`,`(resource: ${r}): ${o}`,"=>"],()=>{n.forEach(a=>{let l=X(a),p=t.fields?.[a],m=s.fields?.[a];if(!Z(p)||!Z(m))return;p.required&&!m.required&&this.curlyBlock([`if (${W("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let y=p?.reference?.map(f=>f.name),d=m?.reference?.map(f=>f.name);if(y&&d&&y.length!==d.length){let f=`reference_is_valid_${l}`;this.curlyBlock(["const",f,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(u=>{this.line(`|| ref.reference?.startsWith('${u}/')`);}),this.line(";");});});let h=p?.required?"":`!${W("resource",l)} || `;p.array?h+=`${W("resource",l)}.every( (ref) => ${f}(ref) )`:h+=`!${f}(${W("resource",l)})`,this.curlyBlock(["if (",h,")"],()=>{this.lineSM(`throw new Error("'${a}' has different references in profile and specialization")`);}),this.line(),c[a]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(a=>{let l=X(a);c[a]?this.line(`${l}:`,`${W("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${W("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${Nr(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(e,t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t),this.generateResourceTypePredicate(t);else if(de(t)){let r=e.flatProfile(t);this.generateDependenciesImports(e,r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}async generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectLogicalModels(),...this.opts.generateProfile?e.collectProfiles().filter(o=>e.isWithMetaField(o)):[]],r=z(t);this.cd("/",()=>{for(let[o,n]of Object.entries(r)){let s=Ut(o);this.cd(s,()=>{for(let c of n)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(n);});}});}};var Ht=i=>{let e=i.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},Or=async(i,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${i.outputDir}`),R.rmSync(i.outputDir,{recursive:!0,force:!0}),i.typeSchemaOutputDir&&(e.info(`Clean ${i.typeSchemaOutputDir}`),R.rmSync(i.typeSchemaOutputDir,{recursive:!0,force:!0})),i.exportTypeTree&&(e.info(`Clean ${i.exportTypeTree}`),R.rmSync(i.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},Lr=async(i,e,t)=>{await _.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let r={};for(let o of i){let n={name:o.identifier.package,version:o.identifier.version},s=Ht(v(n)),c=Ht(`${o.identifier.name}(${le(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=I.join(e,s,c);r[l]||(r[l]=[]),r[l]?.some(p=>p===a)||r[l].push(a);}for(let[o,n]of Object.entries(r))await Promise.all(n.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await _.mkdir(I.dirname(a),{recursive:true}),await _.writeFile(a,s);}));},Mr=async(i,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await _.mkdir(I.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let r of i){let o=JSON.stringify(r,null,2);await _.appendFile(e,`${o}
7
- `);}},Br=async(i,e,t)=>{if(e.typeSchemaOutputDir)try{I.extname(e.typeSchemaOutputDir)===".ndjson"?await Mr(i,e.typeSchemaOutputDir,t):await Lr(i,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(r){if(t.error("Failed to write TypeSchema output",r instanceof Error?r:new Error(String(r))),e.throwException)throw r}},ne=class{schemas=[];options;generators=new Map;logger;packages=[];localStructurePackages=[];localTgzArchives=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false,typeSchemaOutputDir:e.typeSchemaOutputDir,exportTypeTree:e.exportTypeTree,treeShake:e.treeShake,registry:e.registry},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||O({prefix:"API",level:e.logLevel});}fromPackage(e,t){let r=pe({name:e,version:t||"latest"});return this.packages.push(r),this}fromPackageRef(e){return this.packages.push(e),this}registry(e){return this.options.registry=e,this}localStructureDefinitions(e){return this.localStructurePackages.push(e),this}localTgzPackage(e){return this.localTgzArchives.push(I.resolve(e)),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e){let o={...{...{logger:this.logger,outputDir:I.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//",generateProfile:true},openResourceTypeSet:false,primitiveTypeExtension:true},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},n=new xe(o);return this.generators.set("typescript",n),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}python(e){let o={...{...{logger:this.logger,outputDir:this.options.outputDir,tabSize:4,withDebugComment:false,commentLinePrefix:"#"},rootPackageName:"fhir_types",fieldFormat:"snake_case"},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},n=new ke(o);return this.generators.set("python",n),this.logger.debug("Configured python generator"),this}csharp(e,t){let r=new ue({outputDir:I.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new q({prefix:"C#",timestamp:true,suppressLoggingLevel:[]})});return this.generators.set("C#",r),this.logger.debug("Configured C# generator"),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir(e);return this}setLogLevel(e){return this.logger?.setLevel(e),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}writeTypeTree(e){return this.options.exportTypeTree=e,this}treeShake(e){return this.options.treeShake=e,this}writeTypeSchemas(e){return this.options.typeSchemaOutputDir=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{this.options.cleanOutput&&Or(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let r=this.options.manager||CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache",registry:this.options.registry||void 0});if(this.localStructurePackages.length>0)for(let p of this.localStructurePackages)this.logger.info(`Registering local StructureDefinitions for ${p.package.name}@${p.package.version}`),await r.addLocalPackage({name:p.package.name,version:p.package.version,path:p.path,dependencies:p.dependencies?.map(m=>pe(m))});for(let p of this.localTgzArchives)this.logger.info(`Registering local tgz package: ${p}`),await r.addTgzPackage({archivePath:p});let o=await r.init(),n=Object.values(o),s=await te(r,{logger:this.logger,focusedPackages:n}),c=await _t(s,this.logger);await Br(c,this.options,this.logger);let a={resolutionTree:s.resolutionTree(),logger:this.logger},l=je(c,a);this.options.treeShake&&(l=Ft(l,this.options.treeShake,a)),this.options.exportTypeTree&&await l.exportTree(this.options.exportTypeTree),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,l),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){if(this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r)),this.options.throwException)throw r}return {...t,success:t.errors.length===0,duration:performance.now()-e}}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this.packages=[],this.localStructurePackages=[],this.localTgzArchives=[],this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async executeGenerators(e,t){for(let[r,o]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{await o.generate(t);let n=o.writtenFiles();e.filesGenerated.push(...n.map(s=>s.absPath)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var We={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,registry:"",typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Ie=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],qe=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let o=["verbose","overwrite","validate","cache"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)r[s]!==void 0&&typeof r[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:r[s]});let n=["cacheDir","cacheKeyPrefix"];for(let s of n)r[s]!==void 0&&typeof r[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:r[s]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let s=r.profiles;s.autoDetect!==void 0&&typeof s.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:s.autoDetect});}return t}},Ke=class{validator=new qe;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...We}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let r=this.validator.validate(t);if(!r.valid){let o=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
6
+ `);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/atomic-ehr/codegen","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>{this.comment(e);}),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var pe=(i,e=true)=>{let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t};var v=i=>`${i.name}#${i.version}`,de=i=>`${i.name}@${i.version}`;var Oe=(i,e)=>(e||(e={name:"undefined",version:"undefined"}),{...i,package_meta:i.package_meta||e,name:i.name,url:i.url,base:i.base}),Z=i=>i?.kind==="primitive-type",N=i=>i?.kind==="nested",at=i=>i?.kind==="complex-type",ct=i=>i?.kind==="profile";var _=i=>i?.identifier.kind==="resource"||i?.identifier.kind==="complex-type"||i?.identifier.kind==="logical",lt=i=>i?.identifier.kind==="complex-type",D=i=>i?.identifier.kind==="resource",pt=i=>i?.identifier.kind==="primitive-type",j=i=>i?.identifier.kind==="logical",ue=i=>i?.identifier.kind==="profile";function dt(i){return i?.identifier.kind==="binding"}function ut(i){return i?.identifier.kind==="value-set"}var G=i=>i?i.choices===void 0:false,I=i=>i?i.choices!==void 0:false,Le=i=>i?i.choiceOf!==void 0:false,gt=(i,e)=>{if(!i.url)throw new Error("ValueSet must have a URL");if(!i.name)throw new Error("ValueSet must have a name");return {...i,package_meta:i.package_meta||e,name:i.name,url:i.url}};var ft={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Xt(i){return i.split("-").map(e=>E(e)).join("-")}function Qt(i){let e=i;for(let t in ft)e=e.replaceAll(t,ft[t]??"");return e}function Zt(i){let e=Number(i[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${i}`:i}function mt(i){let e=Xt(i);return e=Zt(e),e=Qt(e),e=E(e),e}function O(i){return E(le(i.replaceAll(".","-")))}var er={boolean:"bool",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"decimal",integer:"int",unsignedInt:"long",positiveInt:"long",integer64:"long",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},tr=["Reference","Expression"],rr=i=>i.required?["required"]:[],ir=i=>{let e=bt(St(i.identifier));return E(e)},nr=i=>i.base?`: ${i.base.name}`:"",or=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),O(t)},St=i=>{if(i.kind==="nested"){let e=i.url,t=or(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return O([r,n].join(""))}return O(i.name)},sr=i=>tr.includes(i),bt=i=>sr(i)?`Resource${i}`:i,ge=class extends B{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),r=e.collectResources(),o=Array.from(new Set(r.map(n=>O(n.identifier.package))));this.generateAllFiles(t,r,o),this.copyStaticFiles();}generateAllFiles(e,t,r){this.generateUsingFile(r),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(r),this.generateResourceDictionaries(t,r),this.generateHelperFile();}generateType(e,t){let r=ir(e),o=nr(e);this.curlyBlock(["public","class",r,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let r=Object.entries(e.fields).sort(([o],[n])=>o.localeCompare(n));for(let[o,n]of r)this.generateField(o,n,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let r of e.nested)this.generateType(r,t);}}generateField(e,t,r){try{if(I(t))return;let o=this.buildFieldDeclaration(e,t,r);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,r){let o=this.determineFieldType(e,t,r),n=rr(t),s=w(e);return ["public",...n,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,r){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,r)),o=bt(o);let n="",s=t.required?"":"?",c=t.array?"[]":"";return `${n}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=St(e.type):e.type.kind==="primitive-type"&&(t=er[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,r){let n=`${O(t.binding?.name??e)}Enum`;return this.enums[r]||(this.enums[r]={}),t.enum&&(this.enums[r][n]=t.enum),n}includeHelperMethods(){this.line("public override string ToString() => "),this.line(" JsonSerializer.Serialize(this, Helper.JsonSerializerOptions);"),this.line();}generateUsingFile(e){this.cd("/",async()=>{this.cat("Usings.cs",()=>{this.generateDisclaimer(),this.generateGlobalUsings(e);});});}generateGlobalUsings(e){let t=["CSharpSDK","System.Text.Json","System.Text.Json.Serialization",this.opts.targetNamespace,...e.map(r=>`${this.opts.targetNamespace}.${r}`)];for(let r of t)this.lineSM("global","using",r);}generateBaseTypes(e){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.targetNamespace);for(let t of e){let r=O(t.identifier.package);this.generateType(t,r);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=O(e.identifier.package);this.cd(`/${t}`,async()=>{this.cat(`${e.identifier.name}.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",`${this.opts.targetNamespace}.${t}`),this.line(),this.generateType(e,t);});});}generateEnumFiles(e){for(let t of e)this.generatePackageEnums(t);}generatePackageEnums(e){let t=this.enums[e];!t||Object.keys(t).length===0||this.cd(`/${e}`,async()=>{this.cat(`${e}Enums.cs`,()=>{this.generateDisclaimer(),this.generateEnumFileContent(e,t);});});}generateEnumFileContent(e,t){this.lineSM("using","System.ComponentModel"),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}.${e}`);for(let[r,o]of Object.entries(t))this.generateEnum(r,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let r of t)this.line(`[Description("${r}")]`),this.line(`${mt(r)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let r of t){let o=e.filter(n=>O(n.identifier.package)===r);if(o.length===0)return;this.cat(`${r}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(r,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let r of t){let o=r.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=P__default.resolve(this.opts.staticSourceDir);R__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=P__default.join(this.opts.outputDir,"Helper.cs");R__default.copyFileSync(e,t);}};var z=i=>{let e={};for(let t of i){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e)){let o={};for(let s of r)o[JSON.stringify(s.identifier)]=s;let n=Object.values(o);n.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=n;}return e},ar=i=>{let e={};for(let r of i)e[r.identifier.name]=r;let t={};for(let r of i){let o=r.identifier.name,n=r.base?.name;t[o]||(t[o]=[]),n&&e[n]&&t[o].push(n);}return t},cr=i=>{let e=[],t={},r={},o=n=>{if(r[n])throw new Error(`Graph has cycles ${n}`);if(!t[n]){r[n]=true;for(let s of i[n]??[])o(s);r[n]=false,t[n]=true,e.push(n);}};for(let n in i)t[n]||o(n);return e},Tt=i=>{let e=ar(i);return cr(e).map(r=>i.find(o=>o.identifier.name===r)).filter(Boolean)},lr=i=>{let e=i.filter(n=>D(n)||j(n)),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],o=n=>{let s=t.filter(a=>a.parent.name===n.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let n of t){let s=o(n.child);for(let c of s)t.some(a=>a.parent.name===n.parent.name&&a.child.name===c.name)||r.push({parent:n.parent,child:c});}return r},me=(i,{resolutionTree:e,logger:t})=>{let r={},o=u=>{let g=u.identifier.url,S=u.identifier.package;if(r[g]||(r[g]={}),r[g][u.identifier.package]&&S!=="shared"){let C=JSON.stringify(u.identifier,void 0,2),b=JSON.stringify(r[g][S]?.identifier,void 0,2);if(C!==b)throw new Error(`Duplicate schema: ${C} and ${b}`);return}r[g][S]=u;};for(let u of i)o(u);let n=lr(i),s=u=>r[u.url]?.[u.package],c=(u,g)=>{if(e){let S=e[u]?.[g]?.[0];if(S)return r[g]?.[S.pkg.name]}return r[g]?.[u]},a=u=>n.filter(g=>g.parent.name===u.name).map(g=>g.child),l=u=>{let g=[],S=u;for(;S;){g.push(S);let C=S.base;if(C===void 0)break;let b=s(C);if(!b){t?.warn(`Failed to resolve base type: ${g.map(x=>`${x.identifier.url} (${x.identifier.kind})`).join(", ")}`);return}S=b;}return g},p=u=>{let g=l(u);if(g===void 0)throw new Error(`Failed to resolve base type: ${u.identifier.url} (${u.identifier.kind})`);return g},m=u=>{let g=p(u).find(S=>S.identifier.kind!=="profile");if(!g)throw new Error(`No non-constraint schema found in hierarchy for: ${u.identifier.name}`);return g};return {_schemaIndex:r,_relations:n,collectComplexTypes:()=>i.filter(lt),collectResources:()=>i.filter(D),collectLogicalModels:()=>i.filter(j),collectProfiles:()=>i.filter(ue),resolve:s,resolveByUrl:c,resourceChildren:a,tryHierarchy:l,hierarchy:p,findLastSpecialization:m,findLastSpecializationByIdentifier:u=>{let g=s(u);return g?m(g).identifier:u},flatProfile:u=>{let g=p(u),S=g.filter(L=>L.identifier.kind==="profile"),C=g.find(L=>L.identifier.kind!=="profile");if(!C)throw new Error(`No non-constraint schema found in hierarchy for ${u.identifier.name}`);let b={};for(let L of S.slice().reverse()){let se=L;if(se.fields)for(let[ae,Qe]of Object.entries(se.fields))b[ae]?b[ae]={...b[ae],...Qe}:b[ae]={...Qe};}let x={};for(let L of S.flatMap(se=>se.dependencies??[]))x[L.url]=L;let U=Object.values(x);return {...u,base:C.identifier,fields:b,dependencies:U}},isWithMetaField:u=>{let g=l(u);return g?g.filter(_).some(S=>S.fields?.meta!==void 0):false},exportTree:async u=>{let g={};for(let[C,b]of Object.entries(z(i))){g[C]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let x of b)g[C][x.identifier.kind][x.identifier.url]={};}let S=u.endsWith(".yaml")?Ct.stringify(g):JSON.stringify(g,void 0,2);await V.mkdir(P.dirname(u),{recursive:true}),await V.writeFile(u,S);}}};var dr={boolean:"bool",instant:"str",time:"str",date:"str",dateTime:"str",decimal:"float",integer:"int",unsignedInt:"int",positiveInt:"PositiveInt",integer64:"int",base64Binary:"str",uri:"str",url:"str",canonical:"str",oid:"str",uuid:"str",string:"str",code:"str",markdown:"str",id:"str",xhtml:"str"},Me={snake_case:$,PascalCase:w,camelCase:le},ur=new Set(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","List"]),xt=100,gr=i=>ur.has(i)?`${i}_`:i,fr=i=>i==="Resource"||i==="Element"?["BaseModel"]:[],mr=(i,e=true)=>{if(!i)return;let t=i.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),$(t)},he=i=>{if(i.kind==="nested"){let e=i.url,t=mr(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return w([r,n].join(""))}return w(i.name)},Ft=i=>{let e=P.dirname(fileURLToPath(import.meta.url));return __filename.endsWith("dist/index.js")?P.resolve(e,"..","assets","api","writer-generator","python",i):P.resolve(e,"../../..","assets","api","writer-generator","python",i)},ye=class extends B{nameFormatFunction;tsIndex;constructor(e){super(e),this.nameFormatFunction=this.getFieldFormatFunction(e.fieldFormat);}async generate(e){this.tsIndex=e;let t={groupedComplexTypes:z(e.collectComplexTypes()),groupedResources:z(e.collectResources())};this.generateRootPackages(t),this.generateSDKPackages(t);}generateRootPackages(e){this.generateRootInitFile(e),R__default.cpSync(Ft("requirements.txt"),P.resolve(this.opts.outputDir,"requirements.txt"));}generateSDKPackages(e){this.generateComplexTypesPackages(e.groupedComplexTypes),this.generateResourcePackages(e);}generateComplexTypesPackages(e){for(let[t,r]of Object.entries(e))this.cd(`/${$(t)}`,()=>{this.generateBasePy(r);});}generateResourcePackages(e){for(let[t,r]of Object.entries(e.groupedResources))this.cd(`/${$(t)}`,()=>{this.generateResourcePackageContent(t,r,e.groupedComplexTypes[t]||[]);});}generateResourcePackageContent(e,t,r){let o=this.pyFhirPackageByName(e);this.generateResourcePackageInit(o,t,r),this.generateResourceFamilies(t);for(let n of t)this.generateResourceModule(n);}generateRootInitFile(e){this.cd("/",()=>{this.cat("__init__.py",()=>{this.generateDisclaimer();let t=this.collectAndImportAllModels(e);this.generateModelRebuilds(t);});});}collectAndImportAllModels(e){let t=[];for(let r of Object.keys(e.groupedResources)){let o=this.pyFhirPackageByName(r);t.push(...this.importComplexTypes(o,e.groupedComplexTypes[r])),t.push(...this.importResources(o,false,e.groupedResources[r]));}return this.line(),t}generateModelRebuilds(e){for(let t of e.sort())this.line(`${t}.model_rebuild()`);}generateBasePy(e){this.cat("base.py",()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateComplexTypes(e),this.line();});}generateComplexTypes(e){for(let t of Tt(e))this.generateNestedTypes(t),this.line(),this.generateType(t);}generateResourcePackageInit(e,t,r){this.cat("__init__.py",()=>{this.generateDisclaimer(),this.importComplexTypes(e,r);let o=this.importResources(e,true,t);this.line(),this.generateExportsDeclaration(r,o);});}importComplexTypes(e,t){if(!t||t.length===0)return [];let r=t.map(o=>o.identifier.name).sort();return this.pyImportFrom(`${e}.base`,...r),this.line(),r}buildImportLine(e,t){let r="";for(;e.length>0&&r.length<t;){let o=e.shift();if(!o)throw new Error("Unexpected empty entity");r.length>0&&(r+=", "),r+=o;}return e.length>0&&(r+=", \\"),r}importResources(e,t,r){if(!r||r.length===0)return [];let o=[];for(let n of r){let s=this.importOneResource(n,e);!t&&!n.fields||o.push(...s);}return o}importOneResource(e,t){let r=`${t}.${$(e.identifier.name)}`,o=this.collectResourceImportNames(e);this.pyImportFrom(r,...o);let n=[...o];if(this.shouldImportResourceFamily(e)){let s=`${e.identifier.name}Family`;this.pyImportFrom(`${t}.resource_families`,s);}return n}collectResourceImportNames(e){let t=[he(e.identifier)];for(let r of e.nested??[]){let o=he(r.identifier);t.push(o);}return t}shouldImportResourceFamily(e){return ne(this.tsIndex!==void 0),e.identifier.kind==="resource"&&this.tsIndex.resourceChildren(e.identifier).length>0}generateExportsDeclaration(e,t){this.squareBlock(["__all__","="],()=>{let r=[...(e||[]).map(o=>o.identifier.name),...t].sort();for(let o of r)this.line(`'${o}',`);});}generateResourceModule(e){this.cat(`${$(e.identifier.name)}.py`,()=>{this.generateDisclaimer(),this.generateDefaultImports(),this.line(),this.generateDependenciesImports(e),this.line(),this.generateNestedTypes(e),this.line(),this.generateType(e);});}generateType(e){let t=he(e.identifier),r=this.getSuperClasses(e);this.line(`class ${t}(${r.join(", ")}):`),this.indentBlock(()=>{this.generateClassBody(e);}),this.line();}getSuperClasses(e){return [...e.base?[e.base.name]:[],...fr(e.identifier.name)]}generateClassBody(e){if(this.generateModelConfig(),!e.fields){this.line("pass");return}e.identifier.kind==="resource"&&this.generateResourceTypeField(e),this.generateFields(e),e.identifier.kind==="resource"&&this.generateResourceMethods(e);}generateModelConfig(){let e=this.opts.allowExtraFields?"allow":"forbid";this.line(`model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True, extra="${e}")`);}generateResourceTypeField(e){this.line(`${this.nameFormatFunction("resourceType")}: str = Field(`),this.indentBlock(()=>{this.line(`default='${e.identifier.name}',`),this.line("alias='resourceType',"),this.line("serialization_alias='resourceType',"),this.line("frozen=True,"),this.line(`pattern='${e.identifier.name}'`);}),this.line(")");}generateFields(e){let t=Object.entries(e.fields??[]).sort(([r],[o])=>r.localeCompare(o));for(let[r,o]of t){if("choices"in o&&o.choices)continue;let n=this.buildFieldInfo(r,o);this.line(`${n.name}: ${n.type}${n.defaultValue}`);}}buildFieldInfo(e,t){let r=gr(this.nameFormatFunction(e)),o=this.determineFieldType(t),n=this.getFieldDefaultValue(t,e);return {name:r,type:o,defaultValue:n}}determineFieldType(e){let t=e?this.getBaseFieldType(e):"";return "enum"in e&&e.enum&&(t=`Literal[${e.enum.map(o=>`"${o}"`).join(", ")}]`),e.array&&(t=`PyList[${t}]`),e.required||(t=`${t} | None`),t}getBaseFieldType(e){return "type"in e&&e.type.kind==="resource"?`${e.type.name}Family`:"type"in e&&e.type.kind==="nested"?he(e.type):"type"in e&&e.type.kind==="primitive-type"?dr[e.type.name]??"str":"type"in e?e.type.name:""}getFieldDefaultValue(e,t){let r=`alias="${t}", serialization_alias="${t}"`;return e.required?` = Field(${r})`:` = Field(None, ${r})`}generateResourceMethods(e){let t=e.identifier.name.toString();this.line(),this.line("def to_json(self, indent: int | None = None) -> str:"),this.line(" return self.model_dump_json(exclude_unset=True, exclude_none=True, indent=indent)"),this.line(),this.line("@classmethod"),this.line(`def from_json(cls, json: str) -> ${t}:`),this.line(" return cls.model_validate_json(json)");}generateNestedTypes(e){if(e.nested){this.line();for(let t of e.nested)this.generateType(t);}}generateDefaultImports(){this.pyImportFrom("__future__","annotations"),this.pyImportFrom("pydantic","BaseModel","ConfigDict","Field","PositiveInt"),this.pyImportFrom("typing","List as PyList","Literal");}generateDependenciesImports(e){!e.dependencies||e.dependencies.length===0||(this.importComplexTypeDependencies(e.dependencies),this.importResourceDependencies(e.dependencies));}importComplexTypeDependencies(e){let t=e.filter(o=>o.kind==="complex-type"),r=this.groupDependenciesByPackage(t);for(let[o,n]of Object.entries(r))this.pyImportFrom(o,...n.sort());}importResourceDependencies(e){let t=e.filter(r=>r.kind==="resource");for(let r of t){this.pyImportType(r);let o=`${w(r.name)}Family`,n=`${this.pyFhirPackage(r)}.resource_families`;this.pyImportFrom(n,o);}}groupDependenciesByPackage(e){let t={};for(let r of e){let o=this.pyPackage(r);t[o]||(t[o]=[]),t[o].push(r.name);}return t}pyImportFrom(e,...t){let r=`from ${e} import ${t.join(", ")}`;this.shouldUseSingleLineImport(r,t)?this.line(r):this.writeMultiLineImport(e,t);}shouldUseSingleLineImport(e,t){return e.length<=xt||t.length===1}writeMultiLineImport(e,t){this.line(`from ${e} import (\\`),this.indentBlock(()=>{let r=[...t];for(;r.length>0;){let o=this.buildImportLine(r,xt);this.line(o);}}),this.line(")");}pyImportType(e){this.pyImportFrom(this.pyPackage(e),w(e.name));}generateResourceFamilies(e){ne(this.tsIndex!==void 0);let t=Object.keys(z(e)).map(n=>`${this.opts.rootPackageName}.${n.replaceAll(".","_")}`),r={};for(let n of this.tsIndex.collectResources()){let s=this.tsIndex.resourceChildren(n.identifier).map(c=>c.name);if(s.length>0){let c=`${n.identifier.name}Family`;r[c]=s;}}let o=Object.keys(r);o.length!==0&&this.buildResourceFamiliesFile(t,r,o);}buildResourceFamiliesFile(e,t,r){this.cat("resource_families.py",()=>{this.generateDisclaimer(),this.includeResourceFamilyValidator(),this.line(),this.generateFamilyDefinitions(e,t),this.generateFamilyExports(r);});}includeResourceFamilyValidator(){let e=R__default.readFileSync(Ft("resource_family_validator.py"),"utf-8");this.line(e);}generateFamilyDefinitions(e,t){this.line(`packages = [${e.map(r=>`'${r}'`).join(", ")}]`),this.line();for(let[r,o]of Object.entries(t))this.generateFamilyDefinition(r,o);}generateFamilyDefinition(e,t){let r=`${e}_resources`;this.line(`${r} = [${t.map(o=>`'${o}'`).join(", ")}]`),this.line(),this.line(`def validate_and_downcast_${e}(v: Any) -> Any:`),this.line(` return validate_and_downcast(v, packages, ${r})`),this.line(),this.line(`type ${e} = Annotated[Any, BeforeValidator(validate_and_downcast_${e})]`),this.line();}generateFamilyExports(e){this.line(`__all__ = [${e.map(t=>`'${t}'`).join(", ")}]`);}buildPyPackageName(e){return (e?[$(e)]:[""]).join(".")}pyFhirPackage(e){return this.pyFhirPackageByName(e.package)}pyFhirPackageByName(e){return [this.opts.rootPackageName,this.buildPyPackageName(e)].join(".")}pyPackage(e){return e.kind==="complex-type"?`${this.pyFhirPackage(e)}.base`:e.kind==="resource"?[this.pyFhirPackage(e),$(e.name)].join("."):this.pyFhirPackage(e)}getFieldFormatFunction(e){return Me[e]?Me[e]:(this.logger()?.warn(`Unknown field format '${e}'. Defaulting to SnakeCase.`),this.logger()?.warn(`Supported formats: ${Object.keys(Me).join(", ")}`),$)}};function Be(i){let e=i.split("|")[0];return e||i}function hr(i){return i.split("|")[1]}function yr(i){return i.derivation==="constraint"?"profile":i.kind==="primitive-type"?"primitive-type":i.kind==="complex-type"?"complex-type":i.kind==="resource"?"resource":i.kind==="logical"?"logical":"resource"}function W(i){return {kind:yr(i),package:i.package_meta.name,version:i.package_meta.version,name:i.name,url:i.url}}var Sr=i=>{let e=i.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):i};function Se(i,e,t){let r=Be(t),o=Sr(r),n={package_meta:{name:"missing_valuesets",version:hr(r)||"0.0.0"},id:t},s=i.resolveVs(e,r)||n,c=s?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(s.id)?s.id:o;return {kind:"value-set",package:s.package_meta.name,version:s.package_meta.version,name:c,url:r}}function be(i,e,t){let r=e.join("."),[o,n,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[i.package_meta,`${i.name}.${r}_binding`,`${i.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:n,url:s}}function ve(i,e,t,r){let o={};if(e.derivation==="constraint"){let a=i.resolveFsSpecializations(e.package_meta,e.url).map(l=>_e(i,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let n=t.join("."),s=o[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:s}}function It(i,e,t){let r=[];for(let[o,n]of Object.entries(t)){let s=[...e,o];ee(n)&&r.push([s,n]),n.elements&&r.push(...It(i,s,n.elements));}return r}function br(i,e,t,r,o){let n={};for(let[s,c]of Object.entries(r)){let a=[...t,s],l=i.resolveElementSnapshot(e,a);ee(l)?n[s]=Te(i,e,a,l,o):n[s]=Ce(i,e,a,l,o);}return n}function _e(i,e,t){if(!e.elements)return;let r=It(e,[],e.elements).filter(([n,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[n,s]of r){let c=ve(i,e,n,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=i.ensureSpecializationCanonicalUrl(a),p=i.resolveFs(e.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${a}`);let m={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:a,url:l},y=br(i,e,n,s.elements??{},t),d={identifier:c,base:m,fields:y};o.push(d);}return o.sort((n,s)=>n.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function Pt(i){let e=[];for(let t of i){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function wt(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.required||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.required||[]});return new Set(n).has(r)}function $t(i,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),n=i.resolveFsGenealogy(e.package_meta,e.url).flatMap(s=>{if(o.length===0)return s.excluded||[];if(!s.elements)return [];let c=s;for(let a of o)c=c?.elements?.[a];return c?.excluded||[]});return new Set(n).has(r)}var vr=(i,e,t)=>{if(t.refers)return t.refers.map(r=>{let o=i.ensureSpecializationCanonicalUrl(r),n=i.resolveFs(e.package_meta,o);if(!n)throw new Error(`Failed to resolve fs for ${o}`);return W(n)})};function je(i,e,t,r,o){if(r.elementReference){let n=r.elementReference.slice(1).filter((s,c)=>c%2===1);return ve(i,e,n,o)}else if(r.type){let n=i.ensureSpecializationCanonicalUrl(r.type),s=i.resolveFs(e.package_meta,n);if(!s)throw new Error(`Could not resolve field type: '${r.type}' (from '${e.url}' in '${v(e.package_meta)}')`);return W(s)}else {if(r.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(r,void 0,2)}`),new Error("Unrecognized element type")}}var Ce=(i,e,t,r,o)=>{let n,s;r.binding&&(n=be(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(s=Ve(i,e,r,o)));let c=je(i,e,t,r,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:wt(i,e,t),excluded:$t(i,e,t),reference:vr(i,e,r),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:s}};function ee(i){let e=i.type==="BackboneElement",t=i.type==="Element"&&i.elements!==void 0&&Object.keys(i.elements).length>0,r=i.type===void 0&&i.choiceOf===void 0&&i.elements!==void 0&&Object.keys(i.elements).length>0;return e||t||r}function Te(i,e,t,r,o){return {type:ve(i,e,t,o),array:r.array||false,required:wt(i,e,t),excluded:$t(i,e,t)}}function Ue(i,e,t,r){let o=Be(t)||t,n=i.resolveVs(e,o);if(n)return Tr(i,n)}function Tr(i,e,t){if(e.expansion?.contains)return e.expansion.contains.filter(o=>o.code!==void 0).map(o=>(ne(o.code),{code:o.code,display:o.display,system:o.system}));let r=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let n of o.concept)r.push({system:o.system,code:n.code,display:n.display});else if(o.system&&!o.filter)try{let n=i.resolveAny(o.system);if(n?.concept){let s=(c,a)=>{for(let l of c)r.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(n.concept,o.system);}}catch{}}return r.length>0?r:void 0}var Et=100;function Ve(i,e,t,r){if(!t.binding)return;let o=t.binding.strength,n=t.binding.valueSet;if(!n||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Ue(i,e.package_meta,n);if(!c||c.length===0)return;let a=c.map(l=>l.code).filter(l=>l&&typeof l=="string"&&l.trim().length>0);if(a.length>Et){r?.dry_warn(`Value set ${n} has ${a.length} which is more than ${Et} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function kr(i,e,t,r,o){if(!r.binding?.valueSet)return;let n=be(e,t,r.binding.bindingName),s=je(i,e,t,r,o),c=Se(i,e.package_meta,r.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Ve(i,e,r,o);return {identifier:n,type:s,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function Nt(i,e,t){let r=new Set;if(!e.elements)return [];let o=[];function n(a,l){for(let[p,m]of Object.entries(a)){let y=[...l,p],d=y.join(".");if(!r.has(d)){if(r.add(d),m.binding){let f=kr(i,e,y,m,t);f&&o.push(f);}m.elements&&n(m.elements,y);}}}n(e.elements,[]),o.sort((a,l)=>a.identifier.name.localeCompare(l.identifier.name));let s=[],c=new Set;for(let a of o)c.has(a.identifier.url)||(c.add(a.identifier.url),s.push(a));return s}function Rr(i,e,t,r,o){if(!r)return;let n={};for(let s of i.getAllElementKeys(r)){let c=[...t,s],a=i.resolveElementSnapshot(e,c);ee(a)?n[s]=Te(i,e,c,a,o):n[s]=Ce(i,e,c,a,o);}return n}function xr(i){let e=[];for(let t of Object.values(i))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Fr(i,e){return !!(i.base==="Extension"||i.base==="http://hl7.org/fhir/StructureDefinition/Extension"||i.url?.includes("/extension/")||i.url?.includes("-extension")||i.name?.toLowerCase().includes("extension")||i.type==="Extension")}async function ke(i,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=Se(i,e.package_meta,e.url),o=Ue(i,e.package_meta,e.url);return {identifier:r,description:e.description,concept:o,compose:o?void 0:e.compose}}function Ae(i,e,t,r){let o=[];e&&o.push(e),t&&o.push(...xr(t)),r&&o.push(...Pt(r));let n={};for(let a of o)a.url!==i.url&&(n[a.url]=a);let s=new Set(r?.map(a=>a.identifier.url)),c=Object.values(n).filter(a=>ct(i)||!N(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function Ir(i,e,t){let r=W(e),o;if(e.base&&e.type!=="Element"){let p=i.resolveFs(e.package_meta,i.ensureSpecializationCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${v(e.package_meta)}`);o=W(p);}let n=Rr(i,e,[],e.elements,t),s=_e(i,e,t),c=Ae(r,o,n,s),a={identifier:r,base:o,fields:n,nested:s,description:e.description,dependencies:c},l=Nt(i,e,t);return [a,...l]}async function Re(i,e,t){let r=Ir(i,e,t);if(Fr(e,W(e))){let o=r[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return r}var He=i=>i!==null&&typeof i=="object"&&i.resourceType==="CodeSystem";var xe=i=>i!==null&&typeof i=="object"&&i.resourceType==="ValueSet";var Pr=async(i,e)=>{let r=(await i.packageJson(e.name)).dependencies;return r!==void 0?Object.entries(r).map(([o,n])=>({name:o,version:n})):[]},Lt=i=>({pkg:i,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),Mt=async(i,e,t,r,o)=>{let n=v(e);if(o?.info(`${" ".repeat(t*2)}+ ${n}`),r[n])return r[n];let s=Lt(e);for(let a of await i.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||xe(a)||He(a)))continue;let p=l;s.canonicalResolution[p]&&o?.dry_warn(`Duplicate canonical URL: ${p} at ${n}.`),s.canonicalResolution[p]=[{deep:t,pkg:e,pkgId:n,resource:a}];}let c=await Pr(i,e);for(let a of c){let{canonicalResolution:l}=await Mt(i,a,t+1,r,o);for(let[p,m]of Object.entries(l)){let y=p;s.canonicalResolution[y]=[...s.canonicalResolution[y]||[],...m];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,p)=>l.deep-p.deep);return r[n]=s,s},Dt=(i,e,t)=>{let r=Object.values(i).flatMap(o=>o.canonicalResolution[e]);if(!r)throw new Error(`No canonical resolution found for ${e} in any package`);return r[0]?.resource},te=async(i,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:r})=>{let o=r??await i.packages(),n={};for(let d of o)await Mt(i,d,0,n,e);for(let{pkg:d,canonicalResolution:f}of Object.values(n)){let h=v(d);if(!n[h])throw new Error(`Package ${h} not found`);let u=0;e?.info(`FHIR Schema conversion for '${v(d)}' begins...`);for(let[g,S]of Object.entries(f)){let C=S[0];if(!C)throw new Error("Resource not found");let b=C.resource,x=C.pkg;if(isStructureDefinition(b)){let U=Oe(Ot.translate(b),x);u++,n[h].fhirSchemas[U.url]=U;}if(xe(b)){let U=gt(b,x);n[h].valueSets[U.url]=U;}}e?.info(`FHIR Schema conversion for '${v(d)}' completed: ${u} successful`);}let s=(d,f)=>n[v(d)]?.fhirSchemas[f]||t&&n[v(t)]?.fhirSchemas[f],c=(d,f)=>n[v(d)]?.valueSets[f]||t&&n[v(t)]?.valueSets[f],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,f)=>{let h=s(d,f);if(h===void 0)throw new Error(`Failed to resolve FHIR Schema: '${f}'`);let u=[h];for(;h?.base;){let g=h.package_meta,S=a(h.base);if(h=s(g,S),h===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${f}'. Problem: '${S}' from '${v(g)}'`);u.push(h);}return u};return {...i,testAppendFs(d){let f=Oe(d),h=v(f.package_meta);n[h]||(n[h]=Lt(f.package_meta)),n[h].fhirSchemas[f.url]=f;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,f)=>l(d,f).filter(h=>h.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,f)=>{let h=Dt(n,f);if(isStructureDefinition(h))return h},allFs:()=>Object.values(n).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(n).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>Dt(n,d),resolveElementSnapshot:(d,f)=>{let h=l(d.package_meta,d.url),u=wr(h,f);return $r(u)},getAllElementKeys:d=>{let f=new Set;for(let[h,u]of Object.entries(d)){f.add(h);for(let g of u?.choices||[])d[g]||f.add(g);}return Array.from(f)},resolver:n,resolutionTree:()=>{let d={};for(let[f,h]of Object.entries(n)){let u=h.pkg.name;d[u]={};for(let[g,S]of Object.entries(h.canonicalResolution)){let C=g;d[u][C]=[];for(let b of S)d[u][C].push({deep:b.deep,pkg:b.pkg});}}return d}}};var wr=(i,e)=>{let[t,...r]=e;return t===void 0?[]:i.map(o=>{if(!o.elements)return;let n=o.elements?.[t];for(let s of r)n=n?.elements?.[s];return n}).filter(o=>o!==void 0)};function $r(i){let e=i.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}var re=class{manager;options;logger;constructor(e){this.options={...e},this.manager=e.manager,this.logger=e.logger||M({prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(v);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),te(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],r=0,o=0;for(let n of e)try{let s=Ot.translate(n);t.push(s),r++,this.logger?.debug(`Converted StructureDefinition: ${n.name||n.id} (${n.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${n.name||n.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${r}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await te(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,s=0;for(let c of e)try{let a=await ke(r,c,t);a&&(o.push(a),n++,this.logger?.debug(`Converted ValueSet: ${c.name||c.id}`));}catch(a){s++,this.logger?.warn(`Failed to convert ValueSet ${c.name||c.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger?.success(`ValueSet conversion completed: ${n}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,r){let o={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(n.allVs(),r);return [...(await Promise.all(n.allFs().map(async l=>await Re(n,l,r)))).flat(),...s]}};var ie="Use CodeableReference which is not provided by FHIR R4.",Er="Use Availability which is not provided by FHIR R4.",_t={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":Er,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":ie,"http://hl7.org/fhir/StructureDefinition/specimen-additive":ie,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":ie,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":ie,"http://hl7.org/fhir/StructureDefinition/workflow-reason":ie},"hl7.fhir.r5.core#5.0.0":{"http://hl7.org/fhir/StructureDefinition/shareablecodesystem":"FIXME: CodeSystem.concept.concept defined by ElementReference. FHIR Schema generator output broken value in it, so we just skip it for now."}},jt=async(i,e)=>{let t=[];for(let r of i.allFs()){let o=v(r.package_meta);if(_t[o]?.[r.url]){e?.dry_warn(`Skip ${r.url} from ${o}. Reason: ${_t[o]?.[r.url]}`);continue}t.push(...await Re(i,r,e));}for(let r of i.allVs())t.push(await ke(i,r));return t};var Nr=(i,e)=>{let t={},r={};for(let o of e){let n=i.fields?.[o];if(!i.fields||!n)throw new Error(`Field ${o} not found`);if(I(n))r[o]||(r[o]={}),r[o].declaration=n.choices;else if(Le(n)){let s=n.choiceOf;r[s]||(r[s]={}),r[s].instances=[...r[s].instances??[],o];}else t[o]=n;}for(let[o,{declaration:n,instances:s}]of Object.entries(r)){let c=s??n;ne(c);for(let l of c){let p=i.fields?.[l];ne(p),t[l]=p;}let a=i.fields?.[o];ne(a),t[o]={...a,choices:c};}i.fields=t;},Dr=(i,e)=>{for(let t of e){let r=i.fields?.[t];if(!i.fields||!r)throw new Error(`Field ${t} not found`);if(i.fields){if(I(r))for(let o of r.choices)delete i.fields[o];if(Le(r)){let o=i.fields[r.choiceOf];ne(I(o)),o.choices=o.choices.filter(n=>n!==t),o.choices.length===0&&delete i.fields[r.choiceOf];}delete i.fields[t];}}},Or=(i,e,t)=>{if(i=structuredClone(i),pt(i)||ut(i)||dt(i))return i;if(e.selectFields){if(e.ignoreFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");Nr(i,e.selectFields);}if(e.ignoreFields){if(e.selectFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");Dr(i,e.ignoreFields);}if(i.nested){let r=new Set,o=n=>{Object.values(n.fields??{}).filter(G).filter(s=>N(s.type)).forEach(s=>{let c=s.type.url;if(!r.has(c)){r.add(c);let a=i.nested?.find(l=>l.identifier.url===c);ne(a),o(a);}});};o(i),i.nested=i.nested.filter(n=>r.has(n.identifier.url));}return i.dependencies=Ae(i.identifier,i.base,i.fields,i.nested),i},Vt=(i,e,{resolutionTree:t,logger:r})=>{let o=[];for(let[c,a]of Object.entries(e))for(let[l,p]of Object.entries(a)){let m=i.resolveByUrl(c,l);if(!m)throw new Error(`Schema not found for ${c} ${l}`);let y=Or(m,p);o.push(y);}let n=(c,a)=>{if(c.length===0)return Object.values(a);for(let p of c)a[JSON.stringify(p.identifier)]=p;let l=[];for(let p of c)if(_(p)){if(!p.dependencies)continue;if(p.dependencies.forEach(m=>{let y=i.resolve(m);if(!y)throw new Error(`Dependent schema ${JSON.stringify(m)} not found for ${JSON.stringify(p.identifier)}`);let d=JSON.stringify(y.identifier);a[d]||l.push(y);}),p.nested)for(let m of p.nested){if(N(m.identifier))continue;let y=JSON.stringify(m.identifier);a[y]||l.push(m);}}return n(l,a)},s=n(o,{});return me(s,{resolutionTree:t,logger:r})};var Lr={boolean:"boolean",instant:"string",time:"string",date:"string",dateTime:"string",decimal:"number",integer:"number",unsignedInt:"number",positiveInt:"number",integer64:"number",base64Binary:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",string:"string",code:"string",markdown:"string",id:"string",xhtml:"string"},Ut=i=>{let e=Lr[i];if(e===void 0)throw new Error(`Unknown primitive type ${i}`);return e},Ht=i=>nt(i),qe=i=>i.kind==="profile"?`${k(i)}_profile`:w(i.name),Mr=i=>`${qe(i)}.ts`,Fe=i=>`${Ht(i.package)}/${qe(i)}`,ze=(i,e=true)=>{if(!i)return;let t=pe(i,e);if(t)return We(t)},k=i=>{if(i.kind==="nested"){let e=i.url,t=ze(e,false);if(!t)return "";let[r,o]=t.split("#"),n=Y((o??"").split(".")).join("");return We([r,n].join(""))}return We(i.name)},Gt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),Q=i=>Gt.has(i)?`"${i}"`:i.includes(" ")||i.includes("-")?`"${i}"`:i,We=i=>(Gt.has(i)&&(i=`${i}_`),i.replace(/[- ]/g,"_")),q=(i,e)=>e.startsWith('"')?`${i}[${e}]`:`${i}.${e}`,At=i=>`(${i.map(e=>`"${e}"`).join(" | ")})`,Ie=class extends B{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(r=>[{identifier:r.identifier,tsPackageName:qe(r.identifier),resourceName:k(r.identifier),nestedTypes:D(r)&&r.nested||j(r)&&r.nested?r.nested.map(o=>k(o.identifier)):[],helpers:D(r)||j(r)?[`is${k(r.identifier)}`]:[]}]).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,o)=>r.resourceName.localeCompare(o.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${[r.resourceName,...r.nestedTypes].join(", ")} } from "./${r.tsPackageName}"`),r.helpers.length>0&&this.lineSM(`export { ${r.helpers.join(", ")} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e,t){if(t.dependencies){let r=[],o=[];for(let n of t.dependencies)if(["complex-type","resource","logical"].includes(n.kind))r.push({tsPackage:`../${Fe(n)}`,name:E(n.name),dep:n});else if(N(n)){let s={...n};s.name=ze(n.url),r.push({tsPackage:`../${Fe(s)}`,name:k(n),dep:n});}else o.push(n);r.sort((n,s)=>n.name.localeCompare(s.name));for(let n of r)this.debugComment(n.dep),this.tsImportType(n.tsPackage,n.name);for(let n of o)this.debugComment("skip:",n);if(this.line(),this.withPrimitiveTypeExtension(t)&&t.identifier.name!=="Element"&&t.dependencies.find(n=>n.name==="Element")===void 0){let n="http://hl7.org/fhir/StructureDefinition/Element",s=e.resolveByUrl(t.identifier.package,n);if(!s)throw new Error(`'${n}' not found for ${t.identifier.package}.`);this.tsImportType(`../${Fe(s.identifier)}`,"Element");}}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(at).map(r=>({tsPackage:`../${Fe(r)}`,name:E(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e){let t=Q(`_${e}`);this.lineSM(`${t}?: Element`);}generateType(e,t){let r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=k(t.identifier));let o;if(t.base&&(o=`extends ${ze(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!D(t)){this.lineSM(`export type ${r} = object`);return}this.curlyBlock(["export","interface",r,o],()=>{if(D(t)||j(t)){let s=[t.identifier];s.push(...e.resourceChildren(t.identifier));let c=this.opts.openResourceTypeSet&&s.length>1?" | string":"";this.lineSM(`resourceType: ${s.sort((a,l)=>a.name.localeCompare(l.name)).map(a=>`"${a.name}"`).join(" | ")}${c}`),this.line();}if(!t.fields)return;let n=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of n){if(I(c))continue;this.debugComment(s,":",c);let a=Q(s),l;c.enum?l=At(c.enum):t.identifier.name==="Reference"&&a==="reference"?l="`${T}/${string}`":c.reference&&c.reference.length>0?l=`Reference<${c.reference.map(d=>`"${d.name}"`).join(" | ")}>`:Z(c.type)?l=Ut(c.type.name):N(c.type)?l=k(c.type):l=c.type.name;let p=c.required?"":"?",m=c.array?"[]":"";this.lineSM(`${a}${p}: ${l}${m}`),this.withPrimitiveTypeExtension(t)&&Z(c.type)&&this.addFieldExtension(s);}});}withPrimitiveTypeExtension(e){if(!this.opts.primitiveTypeExtension||!_(e))return false;for(let t of Object.values(e.fields??{}))if(!I(t)&&Z(t.type))return true;return false}generateResourceTypePredicate(e){if(!D(e)&&!j(e))return;let t=k(e.identifier);this.curlyBlock(["export","const",`is${t}`,"=",`(resource: unknown): resource is ${t}`,"=>"],()=>{this.lineSM(`return resource !== null && typeof resource === "object" && (resource as {resourceType: string}).resourceType === "${e.identifier.name}"`);});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let r=k(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,n]of Object.entries(t.fields??{})){if(I(n))continue;this.debugComment(o,n);let s=Q(o),c;if(n.enum)c=At(n.enum);else if(n.reference&&n.reference.length>0){let a=e.findLastSpecialization(t);if(!_(a))throw new Error(`Invalid specialization for ${t.identifier}`);let l=a.fields?.[o];if(l===void 0||I(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let p=l.reference.map(y=>y.name),m=n.reference.map(y=>{let d=e.findLastSpecializationByIdentifier(y);return d.name!==y.name?`"${d.name}" /*${y.name}*/`:`'${y.name}'`}).join(" | ");p.length===1&&p[0]==="Resource"&&m!=='"Resource"'?c=`Reference<"Resource" /* ${m} */ >`:c=`Reference<${m}>`;}else if(N(n.type))c=k(n.type);else if(Z(n.type))c=Ut(n.type.name);else {if(n.type===void 0)throw new Error(`Undefined type for '${o}' field at ${st(t)}`);c=n.type.name;}this.lineSM(`${s}${n.required?"":"?"}: ${c}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=k(e.base),r=k(e.identifier),o=Object.entries(e.fields||{}).filter(([n,s])=>s&&G(s)&&s.type!==void 0).map(([n])=>Q(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(n=>{this.line(`${n}: ${q("profile",n)},`);});});}),this.line();}generateExtractProfile(e,t){let r=k(t.base),o=k(t.identifier),n=Object.entries(t.fields||{}).filter(([a,l])=>G(l)&&l.type!==void 0).map(([a])=>a),s=e.findLastSpecialization(t);if(!_(s))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${o}_from_${r} =`,`(resource: ${r}): ${o}`,"=>"],()=>{n.forEach(a=>{let l=Q(a),p=t.fields?.[a],m=s.fields?.[a];if(!G(p)||!G(m))return;p.required&&!m.required&&this.curlyBlock([`if (${q("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let y=p?.reference?.map(f=>f.name),d=m?.reference?.map(f=>f.name);if(y&&d&&y.length!==d.length){let f=`reference_is_valid_${l}`;this.curlyBlock(["const",f,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(u=>{this.line(`|| ref.reference?.startsWith('${u}/')`);}),this.line(";");});});let h=p?.required?"":`!${q("resource",l)} || `;p.array?h+=`${q("resource",l)}.every( (ref) => ${f}(ref) )`:h+=`!${f}(${q("resource",l)})`,this.curlyBlock(["if (",h,")"],()=>{this.lineSM(`throw new Error("'${a}' has different references in profile and specialization")`);}),this.line(),c[a]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(a=>{let l=Q(a);c[a]?this.line(`${l}:`,`${q("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${q("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${Mr(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(e,t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t),this.generateResourceTypePredicate(t);else if(ue(t)){let r=e.flatProfile(t);this.generateDependenciesImports(e,r),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}async generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectLogicalModels(),...this.opts.generateProfile?e.collectProfiles().filter(o=>e.isWithMetaField(o)):[]],r=z(t);this.cd("/",()=>{for(let[o,n]of Object.entries(r)){let s=Ht(o);this.cd(s,()=>{for(let c of n)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(n);});}});}};var zt=i=>{let e=i.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},_r=async(i,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${i.outputDir}`),R.rmSync(i.outputDir,{recursive:!0,force:!0}),i.typeSchemaOutputDir&&(e.info(`Clean ${i.typeSchemaOutputDir}`),R.rmSync(i.typeSchemaOutputDir,{recursive:!0,force:!0})),i.exportTypeTree&&(e.info(`Clean ${i.exportTypeTree}`),R.rmSync(i.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},jr=async(i,e,t)=>{await V.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let r={};for(let o of i){let n={name:o.identifier.package,version:o.identifier.version},s=zt(v(n)),c=zt(`${o.identifier.name}(${pe(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=P.join(e,s,c);r[l]||(r[l]=[]),r[l]?.some(p=>p===a)||r[l].push(a);}for(let[o,n]of Object.entries(r))await Promise.all(n.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await V.mkdir(P.dirname(a),{recursive:true}),await V.writeFile(a,s);}));},Vr=async(i,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await V.mkdir(P.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let r of i){let o=JSON.stringify(r,null,2);await V.appendFile(e,`${o}
7
+ `);}},Ur=async(i,e,t)=>{if(e.typeSchemaOutputDir)try{P.extname(e.typeSchemaOutputDir)===".ndjson"?await Vr(i,e.typeSchemaOutputDir,t):await jr(i,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(r){if(t.error("Failed to write TypeSchema output",r instanceof Error?r:new Error(String(r))),e.throwException)throw r}},oe=class{schemas=[];options;generators=new Map;logger;packages=[];localStructurePackages=[];localTgzArchives=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false,typeSchemaOutputDir:e.typeSchemaOutputDir,exportTypeTree:e.exportTypeTree,treeShake:e.treeShake,registry:e.registry},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||M({prefix:"API",level:e.logLevel});}fromPackage(e,t){let r=de({name:e,version:t||"latest"});return this.packages.push(r),this}fromPackageRef(e){return this.packages.push(e),this}registry(e){return this.options.registry=e,this}localStructureDefinitions(e){return this.localStructurePackages.push(e),this}localTgzPackage(e){return this.localTgzArchives.push(P.resolve(e)),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e){let o={...{...{logger:this.logger,outputDir:P.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//",generateProfile:true},openResourceTypeSet:false,primitiveTypeExtension:true},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},n=new Ie(o);return this.generators.set("typescript",n),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}python(e){let o={...{...{logger:this.logger,outputDir:this.options.outputDir,tabSize:4,withDebugComment:false,commentLinePrefix:"#"},rootPackageName:"fhir_types",fieldFormat:"snake_case"},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},n=new ye(o);return this.generators.set("python",n),this.logger.debug("Configured python generator"),this}csharp(e,t){let r=new ge({outputDir:P.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new J({prefix:"C#",timestamp:true,suppressLoggingLevel:[]})});return this.generators.set("C#",r),this.logger.debug("Configured C# generator"),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir(e);return this}setLogLevel(e){return this.logger?.setLevel(e),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}writeTypeTree(e){return this.options.exportTypeTree=e,this}treeShake(e){return this.options.treeShake=e,this}writeTypeSchemas(e){return this.options.typeSchemaOutputDir=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{this.options.cleanOutput&&_r(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let r=this.options.manager||CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache",registry:this.options.registry||void 0});if(this.localStructurePackages.length>0)for(let p of this.localStructurePackages)this.logger.info(`Registering local StructureDefinitions for ${p.package.name}@${p.package.version}`),await r.addLocalPackage({name:p.package.name,version:p.package.version,path:p.path,dependencies:p.dependencies?.map(m=>de(m))});for(let p of this.localTgzArchives)this.logger.info(`Registering local tgz package: ${p}`),await r.addTgzPackage({archivePath:p});let o=await r.init(),n=Object.values(o),s=await te(r,{logger:this.logger,focusedPackages:n}),c=await jt(s,this.logger);await Ur(c,this.options,this.logger);let a={resolutionTree:s.resolutionTree(),logger:this.logger},l=me(c,a);this.options.treeShake&&(l=Vt(l,this.options.treeShake,a)),this.options.exportTypeTree&&await l.exportTree(this.options.exportTypeTree),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,l),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){if(this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r)),this.options.throwException)throw r}return {...t,success:t.errors.length===0,duration:performance.now()-e}}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this.packages=[],this.localStructurePackages=[],this.localTgzArchives=[],this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async executeGenerators(e,t){for(let[r,o]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{await o.generate(t);let n=o.writtenFiles();e.filesGenerated.push(...n.map(s=>s.absPath)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){if(e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`),this.options.throwException)throw n}}}};var Je={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,registry:"",typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},we=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Ke=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let o=["verbose","overwrite","validate","cache"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,s)=>{typeof n!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let n of o)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)r[s]!==void 0&&typeof r[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:r[s]});let n=["cacheDir","cacheKeyPrefix"];for(let s of n)r[s]!==void 0&&typeof r[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:r[s]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let s=r.profiles;s.autoDetect!==void 0&&typeof s.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:s.autoDetect});}return t}},Ye=class{validator=new Ke;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Je}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let r=this.validator.validate(t);if(!r.valid){let o=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
8
8
  `);throw new Error(`Configuration validation failed:
9
- ${o}`)}if(!r.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of Ie){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...We,...e,typescript:{...We.typescript,...e.typescript}}}},Ur=new Ke;async function Pe(i){return Ur.autoload(i)}var zt={command:"generate",describe:"Generate code based on configuration file settings",builder:i=>i.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async i=>{if(i._.length>1){let s=i._.slice(1).join(" ");F(`Invalid syntax: 'atomic-codegen generate ${s}'
9
+ ${o}`)}if(!r.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of we){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...Je,...e,typescript:{...Je.typescript,...e.typescript}}}},zr=new Ye;async function $e(i){return zr.autoload(i)}var qt={command:"generate",describe:"Generate code based on configuration file settings",builder:i=>i.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async i=>{if(i._.length>1){let s=i._.slice(1).join(" ");F(`Invalid syntax: 'atomic-codegen generate ${s}'
10
10
 
11
11
  The CLI has been simplified and no longer uses subcommands.
12
12
 
@@ -14,7 +14,7 @@ The CLI has been simplified and no longer uses subcommands.
14
14
  \u274C Old: atomic-codegen generate typescript
15
15
 
16
16
  All generation settings are now configured in your config file.
17
- Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Gr(e);if(!t){let s=Ie.map(c=>` - ${c}`).join(`
17
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Jr(e);if(!t){let s=we.map(c=>` - ${c}`).join(`
18
18
  `);F(`No configuration file found. Please create one of the following files in your project root:
19
19
  ${s}
20
20
 
@@ -27,13 +27,13 @@ export default defineConfig({
27
27
  typescript: {
28
28
  generateIndex: true
29
29
  }
30
- });`),process.exit(1);}let r=await Pe(e),o=i.verbose??r.verbose??false,n=O({prefix:"Generate"});try{Qe("Starting generation from config"),o&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let s=new ne({outputDir:r.outputDir||"./generated",overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let a of r.packages){let[l,p]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,p);}}else throw r.files&&r.files.length>0?(n.info(`Loading files from config: ${r.files.join(", ")}`),new Error("Not Implemented")):new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript)throw new Error("Not Implemented");if(!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");o&&s.onProgress((a,l,p,m)=>{let y=Math.round(l/p*100);n.progress(`[${a}] ${y}% - ${m||"Processing..."}`);}),n.step("Executing generation...");let c=await s.generate();if(c.success){if($e(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),n.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)Xe(a);}else {F(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)n.dim(` ${a}`);process.exit(1);}}catch(s){F("Generation failed with unexpected error",s instanceof Error?s:new Error(String(s))),process.exit(1);}}};async function Gr(i){for(let e of Ie){let t=resolve(i,e);if(existsSync(t))return t}return null}var Wt={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:true,demandOption:true,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:true,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:false,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:false,describe:"Enable verbose output"},registry:{alias:"r",type:"string",describe:"Custom FHIR package registry URL (default: https://fs.get-ig.org/pkgs/)"}},handler:async i=>{let e=O({prefix:"TypeSchema"});try{let t=await Pe(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${i.packages.join(", ")}`),e.info(`Output: ${i.output}`);let r=i.singleFile!==void 0?i.singleFile:t.typeSchema?.singleFile??!1,o=r?"ndjson":i.format;e.debug(`Format: ${o}${r&&i.format==="json"?" (forced from json due to singleFile)":""}`);let n=i.treeshake&&i.treeshake.length>0?i.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let s=i.registry||t.registry;s&&e.info(`Using custom registry: ${s}`);let c=Date.now(),a=new re({treeshake:n,registry:s,manager:CanonicalManager({packages:[],workingDir:".codegen-cache/canonical-manager-cache",registry:s})}),l=[];for(let d of i.packages){let[f,h]=d.includes("@")?d.split("@"):[d,void 0];e.progress(`Processing package: ${f}${h?`@${h}`:""}`);let u=await a.generateFromPackage(f,h,e);l.push(...u);}if(l.length===0)throw new Error("No schemas were generated from the specified packages");let p=i.output;if(!p)throw new Error("Output format not specified");await mkdir(dirname(p),{recursive:!0});let m;o==="json"?m=JSON.stringify(l,null,2):m=l.map(d=>JSON.stringify(d)).join(`
31
- `),await writeFile(p,m,"utf-8");let y=Date.now()-c;if(tt(`Generated ${l.length} TypeSchema definitions`,y,{schemas:l.length}),e.dim(`Output: ${p}`),i.verbose){e.debug("Generated schemas:");let d=l.map(f=>`${f.identifier?.name||"Unknown"} (${f.identifier?.kind||"unknown"})`);K(d);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var qt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:i=>i.command(Wt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:i=>{if(!i.subcommand&&i._.length===1){we("Available typeschema subcommands:"),K(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
30
+ });`),process.exit(1);}let r=await $e(e),o=i.verbose??r.verbose??false,n=M({prefix:"Generate"});try{et("Starting generation from config"),o&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let s=new oe({outputDir:r.outputDir||"./generated",overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let a of r.packages){let[l,p]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,p);}}else throw r.files&&r.files.length>0?(n.info(`Loading files from config: ${r.files.join(", ")}`),new Error("Not Implemented")):new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript)throw new Error("Not Implemented");if(!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");o&&s.onProgress((a,l,p,m)=>{let y=Math.round(l/p*100);n.progress(`[${a}] ${y}% - ${m||"Processing..."}`);}),n.step("Executing generation...");let c=await s.generate();if(c.success){if(Ee(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),n.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)Ze(a);}else {F(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)n.dim(` ${a}`);process.exit(1);}}catch(s){F("Generation failed with unexpected error",s instanceof Error?s:new Error(String(s))),process.exit(1);}}};async function Jr(i){for(let e of we){let t=resolve(i,e);if(existsSync(t))return t}return null}var Jt={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:true,demandOption:true,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:true,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:false,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:false,describe:"Enable verbose output"},registry:{alias:"r",type:"string",describe:"Custom FHIR package registry URL (default: https://fs.get-ig.org/pkgs/)"}},handler:async i=>{let e=M({prefix:"TypeSchema"});try{let t=await $e(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${i.packages.join(", ")}`),e.info(`Output: ${i.output}`);let r=i.singleFile!==void 0?i.singleFile:t.typeSchema?.singleFile??!1,o=r?"ndjson":i.format;e.debug(`Format: ${o}${r&&i.format==="json"?" (forced from json due to singleFile)":""}`);let n=i.treeshake&&i.treeshake.length>0?i.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let s=i.registry||t.registry;s&&e.info(`Using custom registry: ${s}`);let c=Date.now(),a=new re({treeshake:n,registry:s,manager:CanonicalManager({packages:[],workingDir:".codegen-cache/canonical-manager-cache",registry:s})}),l=[];for(let d of i.packages){let[f,h]=d.includes("@")?d.split("@"):[d,void 0];e.progress(`Processing package: ${f}${h?`@${h}`:""}`);let u=await a.generateFromPackage(f,h,e);l.push(...u);}if(l.length===0)throw new Error("No schemas were generated from the specified packages");let p=i.output;if(!p)throw new Error("Output format not specified");await mkdir(dirname(p),{recursive:!0});let m;o==="json"?m=JSON.stringify(l,null,2):m=l.map(d=>JSON.stringify(d)).join(`
31
+ `),await writeFile(p,m,"utf-8");let y=Date.now()-c;if(it(`Generated ${l.length} TypeSchema definitions`,y,{schemas:l.length}),e.dim(`Output: ${p}`),i.verbose){e.debug("Generated schemas:");let d=l.map(f=>`${f.identifier?.name||"Unknown"} (${f.identifier?.kind||"unknown"})`);K(d);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Kt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:i=>i.command(Jt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:i=>{if(!i.subcommand&&i._.length===1){Ne("Available typeschema subcommands:"),K(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
32
32
  Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
33
33
  Examples:`),K(["atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","atomic-codegen typeschema validate schemas.ndjson","atomic-codegen typeschema merge schema1.ndjson schema2.ndjson -o merged.ndjson"]);return}i.subcommand&&!["generate","validate","merge"].includes(i.subcommand)&&(F(`Unknown typeschema subcommand: ${i.subcommand}
34
- `),we("Available typeschema subcommands:"),K(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
35
- Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};function Xr(i){return i?{debug:0,info:1,warn:2,error:3,silent:4}[i.toLowerCase()]:void 0}async function Qr(i){let e=Xr(i.logLevel);e===void 0&&(i.debug||i.verbose?e=0:e=1),Ze({timestamp:i.debug,level:e});}function Zr(){return Jr(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Qr).command(qt).command(zt).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:false,global:true}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:false,global:true}).option("log-level",{alias:"l",type:"string",choices:["debug","info","warn","error","silent"],description:"Set the log level (default: info)",global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(i=>{i._.length===0&&(et("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
34
+ `),Ne("Available typeschema subcommands:"),K(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
35
+ Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};function ti(i){return i?{debug:0,info:1,warn:2,error:3,silent:4}[i.toLowerCase()]:void 0}async function ri(i){let e=ti(i.logLevel);e===void 0&&(i.debug||i.verbose?e=0:e=1),tt({timestamp:i.debug,level:e});}function ii(){return Zr(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(ri).command(Kt).command(qt).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:false,global:true}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:false,global:true}).option("log-level",{alias:"l",type:"string",choices:["debug","info","warn","error","silent"],description:"Set the log level (default: info)",global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(i=>{i._.length===0&&(rt("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
36
36
  Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
37
37
  Quick examples:`),console.log(" atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson"),console.log(" atomic-codegen generate # Uses atomic-codegen.config.ts"),console.log(`
38
38
  Use 'atomic-codegen --help' to see all options.`),process.exit(0));}).help().version("0.1.0").example("$0 generate","Generate code using atomic-codegen.config.ts").example("$0 generate --verbose","Generate with detailed progress output").example("$0 --config custom-config.ts generate","Use custom configuration file").example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").fail((i,e,t)=>{e?F(e.message,e):F(i),F(`
39
- Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Je(){await Zr().parseAsync();}import.meta.main&&Je().catch(i=>{i("Unexpected error:",i),process.exit(1);});Je().catch(i=>{console.error("CLI Error:",i instanceof Error?i.message:i),process.exit(1);});
39
+ Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Xe(){await ii().parseAsync();}import.meta.main&&Xe().catch(i=>{i("Unexpected error:",i),process.exit(1);});Xe().catch(i=>{console.error("CLI Error:",i instanceof Error?i.message:i),process.exit(1);});
package/dist/index.d.ts CHANGED
@@ -300,11 +300,6 @@ interface BindingTypeSchema {
300
300
  }
301
301
  type Field = RegularField | ChoiceFieldDeclaration | ChoiceFieldInstance;
302
302
 
303
- type TypeSchemaShakeRule = {
304
- ignoreFields?: string[];
305
- };
306
- type TreeShake = Record<string, Record<string, TypeSchemaShakeRule>>;
307
-
308
303
  type FileSystemWriterOptions = {
309
304
  outputDir: string;
310
305
  inMemoryOnly?: boolean;
@@ -325,6 +320,12 @@ interface PythonGeneratorOptions extends WriterOptions {
325
320
  fieldFormat: StringFormatKey;
326
321
  }
327
322
 
323
+ type TreeShake = Record<string, Record<string, TreeShakeRule>>;
324
+ type TreeShakeRule = {
325
+ ignoreFields?: string[];
326
+ selectFields?: string[];
327
+ };
328
+
328
329
  /**
329
330
  * New Config Schema for High-Level API
330
331
  *