@atomic-ehr/codegen 0.0.2-canary.20251121141554.c9f1e0b → 0.0.2-canary.20251121164115.c134ba7

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/dist/cli/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import b from'picocolors';import wn from'yargs';import {hideBin}from'yargs/helpers';import*as x from'fs';import x__default,{existsSync}from'fs';import*as F from'path';import F__default,{dirname,resolve}from'path';import*as D from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as pt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';import*as vt from'yaml';var B=class n{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let o=this.options.timestamp?`${b.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${b.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${r(e)} ${i}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e))return;(n.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,b.green));}error(e,t){this.isSuppressed(3)||(console.error(this.formatMessage("X",e,b.red)),t&&this.options.verbose&&(console.error(b.red(` ${t.message}`)),t.stack&&console.error(b.gray(t.stack))));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,b.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,b.blue));}debug(e){this.options.verbose&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,b.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,b.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,b.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${b.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${b.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${o}${t(e)}`);}dim(e){this.plain(e,b.gray);}child(e){return new n({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},M=new B;function ye(n){M.success(n);}function I(n,e){M.error(n,e);}function Ae(n){M.warn(n);}function Se(n){M.info(n);}function _e(n){M.step(n);}function Mt(n){M.dim(n);}function Ge(n){M.configure(n);}function E(n={}){return new B(n)}function ze(n){console.log(),console.log(b.cyan(b.bold(`\u2501\u2501\u2501 ${n} \u2501\u2501\u2501`)));}function We(n,e,t){let r=n;e&&(r+=` ${b.gray(`(${e}ms)`)}`),ye(r),t&&Object.entries(t).forEach(([o,i])=>{Mt(` ${o}: ${i}`);});}function U(n,e="\u2022"){n.forEach(t=>{console.log(b.gray(` ${e} ${t}`));});}var be=n=>n.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),z=n=>be(n).map(e=>e.toLowerCase()).join("-"),qe=n=>{if(n.length===0)throw new Error("Empty string");return n[0]?.toUpperCase()+n.substring(1).toLowerCase()},Je=n=>{if(n.length===0)throw new Error("Empty string");let[e,...t]=be(n);return [e?.toLowerCase(),...t.map(qe)].join("")},L=n=>be(n).map(qe).join("");var w=n=>!n||n.length===0?n:n.charAt(0).toUpperCase()+n.slice(1),te=n=>n.map(e=>w(e));var Ke=n=>`<${n.identifier.url}> from ${n.identifier.package}#${n.identifier.version}`;var Te=class{opts;currentDir;currentFileDescriptor;writtenFilesSet=new Set;constructor(e){this.opts=e,this.currentDir=e.outputDir;}logger(){return this.opts.logger}cd(e,t){let r=this.currentDir;this.currentDir=e.startsWith("/")?F.join(this.opts.outputDir,e):F.join(this.currentDir,e),x.existsSync(this.currentDir)||x.mkdirSync(this.currentDir,{recursive:true}),this.logger()?.debug(`cd '${this.currentDir}'`),t(),this.currentDir=r;}cat(e,t){if(this.currentFileDescriptor)throw new Error("Can't open file in file");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let r=`${this.currentDir}/${e}`;try{this.currentFileDescriptor=x.openSync(r,"w"),this.writtenFilesSet.add(e),this.logger()?.debug(`cat > '${r}'`),t();}finally{this.currentFileDescriptor&&(x.fsyncSync(this.currentFileDescriptor),x.closeSync(this.currentFileDescriptor)),this.currentFileDescriptor=void 0;}}write(e){if(!this.currentFileDescriptor)throw new Error("No file opened");x.writeSync(this.currentFileDescriptor,e);}async generate(e){throw new Error("Not implemented")}writtenFiles(){return Array.from(this.writtenFilesSet)}},H=class extends Te{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 b from'picocolors';import In from'yargs';import {hideBin}from'yargs/helpers';import*as x from'fs';import x__default,{existsSync}from'fs';import*as P from'path';import P__default,{dirname,resolve}from'path';import*as D from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as pt from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';import*as vt from'yaml';var U=class r{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,n){let o=this.options.timestamp?`${b.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${b.cyan(`[${this.options.prefix}]`)} `:"";return `${o}${n(e)} ${i}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e))return;(r.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,b.green));}error(e,t){this.isSuppressed(3)||(console.error(this.formatMessage("X",e,b.red)),t&&this.options.verbose&&(console.error(b.red(` ${t.message}`)),t.stack&&console.error(b.gray(t.stack))));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,b.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,b.blue));}debug(e){this.options.verbose&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,b.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,b.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,b.blue));}plain(e,t=n=>n){let n=this.options.timestamp?`${b.gray(new Date().toLocaleTimeString())} `:"",o=this.options.prefix?`${b.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${n}${o}${t(e)}`);}dim(e){this.plain(e,b.gray);}child(e){return new r({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},M=new U;function Se(r){M.success(r);}function F(r,e){M.error(r,e);}function Ae(r){M.warn(r);}function be(r){M.info(r);}function _e(r){M.step(r);}function Dt(r){M.dim(r);}function Ge(r){M.configure(r);}function E(r={}){return new U(r)}function ze(r){console.log(),console.log(b.cyan(b.bold(`\u2501\u2501\u2501 ${r} \u2501\u2501\u2501`)));}function We(r,e,t){let n=r;e&&(n+=` ${b.gray(`(${e}ms)`)}`),Se(n),t&&Object.entries(t).forEach(([o,i])=>{Dt(` ${o}: ${i}`);});}function H(r,e="\u2022"){r.forEach(t=>{console.log(b.gray(` ${e} ${t}`));});}var ve=r=>r.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),W=r=>ve(r).map(e=>e.toLowerCase()).join("-"),qe=r=>{if(r.length===0)throw new Error("Empty string");return r[0]?.toUpperCase()+r.substring(1).toLowerCase()},Je=r=>{if(r.length===0)throw new Error("Empty string");let[e,...t]=ve(r);return [e?.toLowerCase(),...t.map(qe)].join("")},L=r=>ve(r).map(qe).join("");var I=r=>!r||r.length===0?r:r.charAt(0).toUpperCase()+r.slice(1),ne=r=>r.map(e=>I(e));var Ke=r=>`<${r.identifier.url}> from ${r.identifier.package}#${r.identifier.version}`;var ke=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||x.existsSync(e)||x.mkdirSync(e,{recursive:true});}onDiskOpenFile(e){return this.opts.inMemoryOnly?-1:x.openSync(e,"w")}onDiskCloseFile(e){this.opts.inMemoryOnly||(x.fsyncSync(e),x.closeSync(e));}onDiskWrite(e,t){this.opts.inMemoryOnly||x.writeSync(e,t);}cd(e,t){let n=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=n;}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 n=P.normalize(`${this.currentDir}/${e}`);try{let o=this.onDiskOpenFile(n);this.logger()?.debug(`cat > '${n}'`),this.currentFile={descriptor:o,relPath:n},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:n,absPath:P.resolve(n),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:n})=>({relPath:e,absPath:t,content:n.join()})).sort((e,t)=>e.relPath.localeCompare(t.relPath))}},A=class extends ke{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 ne=(n,e=true)=>{let t=n.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t},S=n=>`${n.name}#${n.version}`,ke=n=>`${n.name}@${n.version}`;var Re=(n,e)=>(e||(e={name:"undefined",version:"undefined"}),{...n,package_meta:n.package_meta||e,name:n.name,url:n.url,base:n.base}),Ce=n=>n?.kind==="primitive-type",N=n=>n?.kind==="nested",Xe=n=>n?.kind==="profile";var A=n=>n?.identifier.kind==="resource"||n?.identifier.kind==="complex-type"||n?.identifier.kind==="logical",Ye=n=>n?.identifier.kind==="complex-type",$=n=>n?.identifier.kind==="resource",Ze=n=>n?.identifier.kind==="primitive-type",O=n=>n?.identifier.kind==="logical",re=n=>n?.identifier.kind==="profile";function Qe(n){return n?.identifier.kind==="binding"}function et(n){return n?.identifier.kind==="value-set"}var W=n=>n?n.choices===void 0:false,_=n=>n?n.choices!==void 0:false,xe=n=>n?.resourceType==="ValueSet",tt=n=>n?.resourceType==="CodeSystem",nt=(n,e)=>{if(!n.url)throw new Error("ValueSet must have a URL");if(!n.name)throw new Error("ValueSet must have a name");return {...n,package_meta:n.package_meta||e,name:n.name,url:n.url}};var rt={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Lt(n){return n.split("-").map(e=>w(e)).join("-")}function jt(n){let e=n;for(let t in rt)e=e.replaceAll(t,rt[t]??"");return e}function Vt(n){let e=Number(n[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${n}`:n}function it(n){let e=Lt(n);return e=Vt(e),e=jt(e),e=w(e),e}function P(n){return w(Je(n.replaceAll(".","-")))}var Bt={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"},Ut=["Reference","Expression"],Ht=n=>n.required?["required"]:[],At=n=>{let e=ct(at(n.identifier));return w(e)},_t=n=>n.base?`: ${n.base.name}`:"",Gt=(n,e=true)=>{if(!n)return;let t=n.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),P(t)},at=n=>{if(n.kind==="nested"){let e=n.url,t=Gt(e,false);if(!t)return "";let[r,o]=t.split("#"),i=te((o??"").split(".")).join("");return P([r,i].join(""))}return P(n.name)},zt=n=>Ut.includes(n),ct=n=>zt(n)?`Resource${n}`:n,ie=class extends H{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(i=>P(i.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=At(e),o=_t(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],[i])=>o.localeCompare(i));for(let[o,i]of r)this.generateField(o,i,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(_(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),i=Ht(t),s=L(e);return ["public",...i,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=ct(o);let i="",s=t.required?"":"?",c=t.array?"[]":"";return `${i}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=at(e.type):e.type.kind==="primitive-type"&&(t=Bt[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,r){let i=`${P(t.binding?.name??e)}Enum`;return this.enums[r]||(this.enums[r]={}),t.enum&&(this.enums[r][i]=t.enum),i}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=P(t.identifier.package);this.generateType(t,r);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=P(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(`${it(r)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let r of t){let o=e.filter(i=>P(i.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=F__default.resolve(this.opts.staticSourceDir);x__default.cpSync(e,this.opts.outputDir,{recursive:true});}generateHelperFile(){let e="src/api/writer-generator/csharp/Helper.cs",t=F__default.join(this.opts.outputDir,"Helper.cs");x__default.copyFileSync(e,t);}};var Wt=async(n,e)=>{let r=(await n.packageJson(e.name)).dependencies;return r!==void 0?Object.entries(r).map(([o,i])=>({name:o,version:i})):[]},dt=n=>({pkg:n,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),ut=async(n,e,t,r,o)=>{let i=S(e);if(o?.info(`${" ".repeat(t*2)}+ ${i}`),r[i])return r[i];let s=dt(e);for(let a of await n.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||xe(a)||tt(a)))continue;let u=l;s.canonicalResolution[u]&&o?.dry_warn(`Duplicate canonical URL: ${u} at ${i}.`),s.canonicalResolution[u]=[{deep:t,pkg:e,pkgId:i,resource:a}];}let c=await Wt(n,e);for(let a of c){let{canonicalResolution:l}=await ut(n,a,t+1,r,o);for(let[u,h]of Object.entries(l)){let m=u;s.canonicalResolution[m]=[...s.canonicalResolution[m]||[],...h];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,u)=>l.deep-u.deep);return r[i]=s,s},lt=(n,e,t)=>{let r=Object.values(n).flatMap(o=>o.canonicalResolution[e]);if(!r)throw new Error(`No canonical resolution found for ${e} in any package`);return r[0]?.resource},q=async(n,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:r})=>{let o=r??await n.packages(),i={};for(let d of o)await ut(n,d,0,i,e);for(let{pkg:d,canonicalResolution:g}of Object.values(i)){let p=S(d);if(!i[p])throw new Error(`Package ${p} not found`);let f=0;e?.info(`FHIR Schema conversion for '${S(d)}' begins...`);for(let[y,T]of Object.entries(g)){let v=T[0];if(!v)throw new Error("Resource not found");let C=v.resource,Z=v.pkg;if(isStructureDefinition(C)){let R=Re(pt.translate(C),Z);f++,i[p].fhirSchemas[R.url]=R;}if(xe(C)){let R=nt(C,Z);i[p].valueSets[R.url]=R;}}e?.info(`FHIR Schema conversion for '${S(d)}' completed: ${f} successful`);}let s=(d,g)=>i[S(d)]?.fhirSchemas[g]||t&&i[S(t)]?.fhirSchemas[g],c=(d,g)=>i[S(d)]?.valueSets[g]||t&&i[S(t)]?.valueSets[g],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,g)=>{let p=s(d,g);if(p===void 0)throw new Error(`Failed to resolve FHIR Schema: '${g}'`);let f=[p];for(;p?.base;){let y=p.package_meta,T=a(p.base);if(p=s(y,T),p===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${g}'. Problem: '${T}' from '${S(y)}'`);f.push(p);}return f};return {...n,testAppendFs(d){let g=Re(d),p=S(g.package_meta);i[p]||(i[p]=dt(g.package_meta)),i[p].fhirSchemas[g.url]=g;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,g)=>l(d,g).filter(p=>p.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,g)=>{let p=lt(i,g);if(isStructureDefinition(p))return p},allFs:()=>Object.values(i).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(i).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>lt(i,d),resolveElementSnapshot:(d,g)=>{let p=l(d.package_meta,d.url),f=qt(p,g);return Jt(f)},getAllElementKeys:d=>{let g=new Set;for(let[p,f]of Object.entries(d)){g.add(p);for(let y of f?.choices||[])d[y]||g.add(y);}return Array.from(g)},resolver:i}};var qt=(n,e)=>{let[t,...r]=e;return t===void 0?[]:n.map(o=>{if(!o.elements)return;let i=o.elements?.[t];for(let s of r)i=i?.elements?.[s];return i}).filter(o=>o!==void 0)};function Jt(n){let e=n.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}function Ie(n){let e=n.split("|")[0];return e||n}function Kt(n){return n.split("|")[1]}function Xt(n){return n.derivation==="constraint"?"profile":n.kind==="primitive-type"?"primitive-type":n.kind==="complex-type"?"complex-type":n.kind==="resource"?"resource":n.kind==="logical"?"logical":"resource"}function j(n){return {kind:Xt(n),package:n.package_meta.name,version:n.package_meta.version,name:n.name,url:n.url}}var Yt=n=>{let e=n.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):n};function oe(n,e,t){let r=Ie(t),o=Yt(r),i={package_meta:{name:"missing_valuesets",version:Kt(r)||"0.0.0"},id:t},s=n.resolveVs(e,r)||i,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 se(n,e,t){let r=e.join("."),[o,i,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[n.package_meta,`${n.name}.${r}_binding`,`${n.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:i,url:s}}function ae(n,e,t,r){let o={};if(e.derivation==="constraint"){let a=n.resolveFsSpecializations(e.package_meta,e.url).map(l=>we(n,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let i=t.join("."),s=o[i]??`${e.url}#${i}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:i,url:s}}function ft(n,e,t){let r=[];for(let[o,i]of Object.entries(t)){let s=[...e,o];J(i)&&r.push([s,i]),i.elements&&r.push(...ft(n,s,i.elements));}return r}function Zt(n,e,t,r,o){let i={};for(let[s,c]of Object.entries(r)){let a=[...t,s],l=n.resolveElementSnapshot(e,a);J(l)?i[s]=le(n,e,a,l,o):i[s]=ce(n,e,a,l,o);}return i}function we(n,e,t){if(!e.elements)return;let r=ft(e,[],e.elements).filter(([i,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[i,s]of r){let c=ae(n,e,i,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=n.ensureSpecializationCanonicalUrl(a),u=n.resolveFs(e.package_meta,l);if(!u)throw new Error(`Could not resolve base type ${a}`);let h={kind:"complex-type",package:u.package_meta.name,version:u.package_meta.version,name:a,url:l},m=Zt(n,e,i,s.elements??{},t),d={identifier:c,base:h,fields:m};o.push(d);}return o.sort((i,s)=>i.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function gt(n){let e=[];for(let t of n){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 mt(n,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),i=n.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(i).has(r)}function ht(n,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),i=n.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(i).has(r)}var Qt=(n,e,t)=>{if(t.refers)return t.refers.map(r=>{let o=n.ensureSpecializationCanonicalUrl(r),i=n.resolveFs(e.package_meta,o);if(!i)throw new Error(`Failed to resolve fs for ${o}`);return j(i)})};function $e(n,e,t,r,o){if(r.elementReference){let i=r.elementReference.slice(1).filter((s,c)=>c%2===1);return ae(n,e,i,o)}else if(r.type){let i=n.ensureSpecializationCanonicalUrl(r.type),s=n.resolveFs(e.package_meta,i);if(!s)throw new Error(`Could not resolve field type: '${r.type}' (from '${e.url}' in '${S(e.package_meta)}')`);return j(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=(n,e,t,r,o)=>{let i,s;r.binding&&(i=se(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(s=Pe(n,e,r,o)));let c=$e(n,e,t,r,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:mt(n,e,t),excluded:ht(n,e,t),reference:Qt(n,e,r),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:i,enum:s}};function J(n){let e=n.type==="BackboneElement",t=n.type==="Element"&&n.elements!==void 0&&Object.keys(n.elements).length>0,r=n.type===void 0&&n.choiceOf===void 0&&n.elements!==void 0&&Object.keys(n.elements).length>0;return e||t||r}function le(n,e,t,r,o){return {type:ae(n,e,t,o),array:r.array||false,required:mt(n,e,t),excluded:ht(n,e,t)}}function Ee(n,e,t,r){let o=Ie(t)||t,i=n.resolveVs(e,o);if(i)return en(n,i)}function en(n,e,t){if(e.expansion?.contains)return e.expansion.contains;let r=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let i of o.concept)r.push({system:o.system,code:i.code,display:i.display});else if(o.system&&!o.filter)try{let i=n.resolveAny(o.system);if(i?.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(i.concept,o.system);}}catch{}}return r.length>0?r:void 0}var yt=100;function Pe(n,e,t,r){if(!t.binding)return;let o=t.binding.strength,i=t.binding.valueSet;if(!i||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Ee(n,e.package_meta,i);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>yt){r?.dry_warn(`Value set ${i} has ${a.length} which is more than ${yt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function tn(n,e,t,r,o){if(!r.binding?.valueSet)return;let i=se(e,t,r.binding.bindingName),s=$e(n,e,t,r,o),c=oe(n,e.package_meta,r.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Pe(n,e,r,o);return {identifier:i,type:s,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function St(n,e,t){let r=new Set;if(!e.elements)return [];let o=[];function i(a,l){for(let[u,h]of Object.entries(a)){let m=[...l,u],d=m.join(".");if(!r.has(d)){if(r.add(d),h.binding){let g=tn(n,e,m,h,t);g&&o.push(g);}h.elements&&i(h.elements,m);}}}i(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 nn(n,e,t,r,o){if(!r)return;let i={};for(let s of n.getAllElementKeys(r)){let c=[...t,s],a=n.resolveElementSnapshot(e,c);J(a)?i[s]=le(n,e,c,a,o):i[s]=ce(n,e,c,a,o);}return i}function rn(n){let e=[];for(let t of Object.values(n))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function on(n,e){return !!(n.base==="Extension"||n.base==="http://hl7.org/fhir/StructureDefinition/Extension"||n.url?.includes("/extension/")||n.url?.includes("-extension")||n.name?.toLowerCase().includes("extension")||n.type==="Extension")}async function pe(n,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=oe(n,e.package_meta,e.url),o=Ee(n,e.package_meta,e.url);return {identifier:r,description:e.description,concept:o,compose:o?void 0:e.compose}}function Ne(n,e,t,r){let o=[];e&&o.push(e),t&&o.push(...rn(t)),r&&o.push(...gt(r));let i={};for(let a of o)a.url!==n.url&&(i[a.url]=a);let s=new Set(r?.map(a=>a.identifier.url)),c=Object.values(i).filter(a=>Xe(n)||!N(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function sn(n,e,t){let r=j(e),o;if(e.base&&e.type!=="Element"){let u=n.resolveFs(e.package_meta,n.ensureSpecializationCanonicalUrl(e.base));if(!u)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${S(e.package_meta)}`);o=j(u);}let i=nn(n,e,[],e.elements,t),s=we(n,e,t),c=Ne(r,o,i,s),a={identifier:r,base:o,fields:i,nested:s,description:e.description,dependencies:c},l=St(n,e,t);return [a,...l]}async function de(n,e,t){let r=sn(n,e,t);if(on(e,j(e))){let o=r[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return r}var Oe=n=>{let e={};for(let t of n){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 i=Object.values(o);i.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=i;}return e},an=(n,e,t)=>{if(n=structuredClone(n),Ze(n)||et(n)||Qe(n))return n;for(let r of e.ignoreFields??[]){if(n.fields&&!n.fields[r])throw new Error(`Field ${r} not found`);n.fields&&delete n.fields[r];}return n.dependencies=Ne(n.identifier,n.base,n.fields,n.nested),n},Tt=(n,e,t)=>{let r=[];for(let[s,c]of Object.entries(e))for(let[a,l]of Object.entries(c)){let u=n.resolveByUrl(s,a);if(!u)throw new Error(`Schema not found for ${s} ${a}`);let h=an(u,l);r.push(h);}let o=(s,c)=>{if(s.length===0)return Object.values(c);for(let l of s)c[JSON.stringify(l.identifier)]=l;let a=[];for(let l of s)if(A(l)){if(!l.dependencies)continue;if(l.dependencies.forEach(u=>{let h=n.resolve(u);if(!h)throw new Error(`Schema not found for ${u}`);let m=JSON.stringify(h.identifier);c[m]||a.push(h);}),l.nested)for(let u of l.nested){if(N(u.identifier))continue;let h=JSON.stringify(u.identifier);c[h]||a.push(u);}}return o(a,c)},i=o(r,{});return De(i,t)},cn=n=>{let e=n.filter(i=>$(i)||O(i)),t=[];for(let i of e)i.base&&t.push({parent:i.base,child:i.identifier});let r=[...t],o=i=>{let s=t.filter(a=>a.parent.name===i.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let i of t){let s=o(i.child);for(let c of s)t.some(a=>a.parent.name===i.parent.name&&a.child.name===c.name)||r.push({parent:i.parent,child:c});}return r},De=(n,e)=>{let t={},r=p=>{let f=p.identifier.url,y=p.identifier.package;if(t[f]||(t[f]={}),t[f][p.identifier.package]&&y!=="shared"){let T=JSON.stringify(p.identifier,void 0,2),v=JSON.stringify(t[f][y]?.identifier,void 0,2);if(T!==v)throw new Error(`Duplicate schema: ${T} and ${v}`);return}t[f][y]=p;};for(let p of n)r(p);let o=cn(n),i=p=>t[p.url]?.[p.package],s=(p,f)=>t[f]?.[p],c=p=>o.filter(f=>f.parent.name===p.name).map(f=>f.child),a=p=>{let f=[],y=p;for(;y;){f.push(y);let T=y.base;if(T===void 0)break;let v=i(T);if(!v){e?.warn(`Failed to resolve base type: ${f.map(C=>`${C.identifier.url} (${C.identifier.kind})`).join(", ")}`);return}y=v;}return f},l=p=>{let f=a(p);if(f===void 0)throw new Error(`Failed to resolve base type: ${p.identifier.url} (${p.identifier.kind})`);return f},u=p=>{let f=l(p).find(y=>y.identifier.kind!=="profile");if(!f)throw new Error(`No non-constraint schema found in hierarchy for: ${p.identifier.name}`);return f};return {_schemaIndex:t,_relations:o,collectComplexTypes:()=>n.filter(Ye),collectResources:()=>n.filter($),collectLogicalModels:()=>n.filter(O),collectProfiles:()=>n.filter(re),resolve:i,resolveByUrl:s,resourceChildren:c,tryHierarchy:a,hierarchy:l,findLastSpecialization:u,findLastSpecializationByIdentifier:p=>{let f=i(p);return f?u(f).identifier:p},flatProfile:p=>{let f=l(p),y=f.filter(R=>R.identifier.kind==="profile"),T=f.find(R=>R.identifier.kind!=="profile");if(!T)throw new Error(`No non-constraint schema found in hierarchy for ${p.identifier.name}`);let v={};for(let R of y.slice().reverse()){let Q=R;if(Q.fields)for(let[ee,He]of Object.entries(Q.fields))v[ee]?v[ee]={...v[ee],...He}:v[ee]={...He};}let C={};for(let R of y.flatMap(Q=>Q.dependencies??[]))C[R.url]=R;let Z=Object.values(C);return {...p,base:T.identifier,fields:v,dependencies:Z}},isWithMetaField:p=>{let f=a(p);return f?f.filter(A).some(y=>y.fields?.meta!==void 0):false},exportTree:async p=>{let f={};for(let[T,v]of Object.entries(Oe(n))){f[T]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let C of v)f[T][C.identifier.kind][C.identifier.url]={};}let y=p.endsWith(".yaml")?vt.stringify(f):JSON.stringify(f,void 0,2);await D.mkdir(F.dirname(p),{recursive:true}),await D.writeFile(p,y);}}};var K=class{manager;options;logger;constructor(e={}){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.logger=e.logger||E({verbose:this.options.verbose,prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(S);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),q(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],r=0,o=0;for(let i of e)try{let s=pt.translate(i);t.push(s),r++,this.logger?.debug(`Converted StructureDefinition: ${i.name||i.id} (${i.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${i.name||i.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 q(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let i=0,s=0;for(let c of e)try{let a=await pe(r,c,t);a&&(o.push(a),i++,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: ${i}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,r){let o={name:e,version:t||"latest"},i=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(i.allVs(),r);return [...(await Promise.all(i.allFs().map(async l=>await de(i,l,r)))).flat(),...s]}};var X="Use CodeableReference which is not provided by FHIR R4.",pn="Use Availability which is not provided by FHIR R4.",Rt={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":pn,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":X,"http://hl7.org/fhir/StructureDefinition/specimen-additive":X,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":X,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":X,"http://hl7.org/fhir/StructureDefinition/workflow-reason":X},"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."}},Ct=async(n,e)=>{let t=[];for(let r of n.allFs()){let o=S(r.package_meta);if(Rt[o]?.[r.url]){e?.dry_warn(`Skip ${r.url} from ${o}. Reason: ${Rt[o]?.[r.url]}`);continue}t.push(...await de(n,r,e));}for(let r of n.allVs())t.push(await pe(n,r));return t};var dn={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"},xt=n=>{let e=dn[n];if(e===void 0)throw new Error(`Unknown primitive type ${n}`);return e},un=n=>z(n),It=n=>n.kind==="profile"?`${k(n)}_profile`:L(n.name),fn=n=>`${It(n)}.ts`,Me=(n,e=true)=>{if(!n)return;let t=ne(n,e);if(t)return Le(t)},k=n=>{if(n.kind==="nested"){let e=n.url,t=Me(e,false);if(!t)return "";let[r,o]=t.split("#"),i=te((o??"").split(".")).join("");return Le([r,i].join(""))}return Le(n.name)},wt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),G=n=>wt.has(n)?`"${n}"`:n.includes(" ")||n.includes("-")?`"${n}"`:n,Le=n=>(wt.has(n)&&(n=`${n}_`),n.replace(/[- ]/g,"_")),V=(n,e)=>e.startsWith('"')?`${n}[${e}]`:`${n}.${e}`,Ft=n=>`(${n.map(e=>`"${e}"`).join(" | ")})`,fe=class extends H{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:It(r.identifier),resourceName:k(r.identifier),nestedTypes:$(r)&&r.nested||O(r)&&r.nested?r.nested.map(o=>k(o.identifier)):[],helpers:$(r)||O(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){if(e.dependencies){let t=[],r=[];for(let o of e.dependencies)["complex-type","resource","logical"].includes(o.kind)?t.push({tsPackage:`../${z(o.package)}/${L(o.name)}`,name:w(o.name),dep:o}):N(o)?t.push({tsPackage:`../${z(o.package)}/${L(Me(o.url)??"")}`,name:k(o),dep:o}):r.push(o);t.sort((o,i)=>o.name.localeCompare(i.name));for(let o of t)this.debugComment(o.dep),this.tsImportType(o.tsPackage,o.name);for(let o of r)this.debugComment("skip:",o);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${z(r.package)}/${L(r.name)}`,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,t){if(t.type.kind==="primitive-type"){let r=G(`_${e}`);this.lineSM(`${r}?: 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 ${Me(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!$(t)){this.lineSM(`export type ${r} = object`);return}this.curlyBlock(["export","interface",r,o],()=>{if($(t)||O(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 i=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of i){if(_(c))continue;this.debugComment(s,":",c);let a=G(s),l;c.enum?l=Ft(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(" | ")}>`:Ce(c.type)?l=xt(c.type.name):N(c.type)?l=k(c.type):l=c.type.name;let u=c.required?"":"?",h=c.array?"[]":"";this.lineSM(`${a}${u}: ${l}${h}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(s,c);}});}generateResourceTypePredicate(e){if(!$(e)&&!O(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,i]of Object.entries(t.fields??{})){if(_(i))continue;this.debugComment(o,i);let s=G(o),c;if(i.enum)c=Ft(i.enum);else if(i.reference&&i.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||_(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let u=l.reference.map(m=>m.name),h=i.reference.map(m=>{let d=e.findLastSpecializationByIdentifier(m);return d.name!==m.name?`"${d.name}" /*${m.name}*/`:`'${m.name}'`}).join(" | ");u.length===1&&u[0]==="Resource"&&h!=='"Resource"'?c=`Reference<"Resource" /* ${h} */ >`:c=`Reference<${h}>`;}else if(N(i.type))c=k(i.type);else if(Ce(i.type))c=xt(i.type.name);else {if(i.type===void 0)throw new Error(`Undefined type for '${o}' field at ${Ke(t)}`);c=i.type.name;}this.lineSM(`${s}${i.required?"":"?"}: ${c}${i.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=k(e.base),r=k(e.identifier),o=Object.entries(e.fields||{}).filter(([i,s])=>s&&W(s)&&s.type!==void 0).map(([i])=>G(i));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(i=>{this.line(`${i}: ${V("profile",i)},`);});});}),this.line();}generateExtractProfile(e,t){let r=k(t.base),o=k(t.identifier),i=Object.entries(t.fields||{}).filter(([a,l])=>W(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}`,"=>"],()=>{i.forEach(a=>{let l=G(a),u=t.fields?.[a],h=s.fields?.[a];if(!W(u)||!W(h))return;u.required&&!h.required&&this.curlyBlock([`if (${V("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let m=u?.reference?.map(g=>g.name),d=h?.reference?.map(g=>g.name);if(m&&d&&m.length!==d.length){let g=`reference_is_valid_${l}`;this.curlyBlock(["const",g,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(f=>{this.line(`|| ref.reference?.startsWith('${f}/')`);}),this.line(";");});});let p=u?.required?"":`!${V("resource",l)} || `;u.array?p+=`${V("resource",l)}.every( (ref) => ${g}(ref) )`:p+=`!${g}(${V("resource",l)})`,this.curlyBlock(["if (",p,")"],()=>{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}',`),i.forEach(a=>{let l=G(a);c[a]?this.line(`${l}:`,`${V("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${V("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${fn(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t),this.generateResourceTypePredicate(t);else if(re(t)){let r=e.flatProfile(t);this.generateDependenciesImports(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=Oe(t);this.cd("/",()=>{for(let[o,i]of Object.entries(r)){let s=un(o);this.cd(s,()=>{for(let c of i)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(i);});}});}};var $t=n=>{let e=()=>n.writtenFiles().map(t=>({path:F.normalize(F.join(n.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),timestamp:new Date}));return {generate:async({index:t})=>(await n.generate(t),e()),setOutputDir:t=>n.opts.outputDir=t,build:async t=>e()}},Pt=n=>{let e=n.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},mn=async(n,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${n.outputDir}`),x.rmSync(n.outputDir,{recursive:!0,force:!0}),n.typeSchemaOutputDir&&(e.info(`Clean ${n.typeSchemaOutputDir}`),x.rmSync(n.typeSchemaOutputDir,{recursive:!0,force:!0})),n.exportTypeTree&&(e.info(`Clean ${n.exportTypeTree}`),x.rmSync(n.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},hn=async(n,e,t)=>{await D.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let r={};for(let o of n){let i={name:o.identifier.package,version:o.identifier.version},s=Pt(S(i)),c=Pt(`${o.identifier.name}(${ne(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=F.join(e,s,c);r[l]||(r[l]=[]),r[l]?.some(u=>u===a)||r[l].push(a);}for(let[o,i]of Object.entries(r))await Promise.all(i.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await D.mkdir(F.dirname(a),{recursive:true}),await D.writeFile(a,s);}));},yn=async(n,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await D.mkdir(F.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let r of n){let o=JSON.stringify(r,null,2);await D.appendFile(e,`${o}
7
- `);}},Sn=async(n,e,t)=>{if(e.typeSchemaOutputDir)try{F.extname(e.typeSchemaOutputDir)===".ndjson"?await yn(n,e.typeSchemaOutputDir,t):await hn(n,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}},Y=class{schemas=[];options;generators=new Map;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,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},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||E({verbose:this.options.verbose,prefix:"API"});}fromPackage(e,t){let r=ke({name:e,version:t||"latest"});return this.packages.push(r),this}fromPackageRef(e){return this.packages.push(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:F.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//",generateProfile:true},openResourceTypeSet:false},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},i=$t(new fe(o));return this.generators.set("typescript",i),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}csharp(e,t){let r=$t(new ie({outputDir:F.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new B({prefix:"C#",timestamp:true,verbose: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&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose: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&&mn(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache"}),o=await r.init(),i=Object.values(o),s=await q(r,{logger:this.logger,focusedPackages:i}),c=await Ct(s,this.logger);await Sn(c,this.options,this.logger);let a=De(c,this.logger);this.options.treeShake&&(a=Tt(a,this.options.treeShake,this.logger)),this.options.exportTypeTree&&await a.exportTree(this.options.exportTypeTree),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,{schemas:c,index:a}),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}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,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{let i=await o.generate(t);e.filesGenerated.push(...i.map(s=>s.path||s.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(i){if(e.errors.push(`${r} generator failed: ${i instanceof Error?i.message:String(i)}`),this.options.throwException)throw i}}}};var je={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,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:""},me=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Ve=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 i of o)r[i]!==void 0&&typeof r[i]!="boolean"&&t.errors.push({path:i,message:`${i} must be a boolean`,value:r[i]});if(r.typescript!==void 0){let i=this.validateTypeScriptConfig(r.typescript);t.errors.push(...i);}if(r.typeSchema!==void 0){let i=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...i);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:i});}):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((i,s)=>{typeof i!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:i});}):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 i of o)r[i]!==void 0&&typeof r[i]!="boolean"&&t.push({path:`typescript.${i}`,message:`${i} must be a boolean`,value:r[i]});if(r.validatorOptions!==void 0){let i=this.validateValidatorOptions(r.validatorOptions);t.push(...i);}if(r.guardOptions!==void 0){let i=this.validateGuardOptions(r.guardOptions);t.push(...i);}if(r.profileOptions!==void 0){let i=this.validateProfileOptions(r.profileOptions);t.push(...i);}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 i of o)r[i]!==void 0&&typeof r[i]!="boolean"&&t.push({path:`typescript.validatorOptions.${i}`,message:`${i} must be a boolean`,value:r[i]});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 i of o)r[i]!==void 0&&typeof r[i]!="boolean"&&t.push({path:`typescript.guardOptions.${i}`,message:`${i} must be a boolean`,value:r[i]});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 i of o)r[i]!==void 0&&typeof r[i]!="boolean"&&t.push({path:`typescript.profileOptions.${i}`,message:`${i} must be a boolean`,value:r[i]});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 i=["cacheDir","cacheKeyPrefix"];for(let s of i)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}},Be=class{validator=new Ve;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 i=await import(resolve(e));t=i.default||i;}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(i=>`${i.path}: ${i.message}`).join(`
6
+ `);for(let n of t)this.line(this.opts.commentLinePrefix,n);}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,n){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${n?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,n){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${n?.filter(Boolean).join(" ")??""}`);}};var re=(r,e=true)=>{let t=r.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),t},S=r=>`${r.name}#${r.version}`,Te=r=>`${r.name}@${r.version}`;var Ce=(r,e)=>(e||(e={name:"undefined",version:"undefined"}),{...r,package_meta:r.package_meta||e,name:r.name,url:r.url,base:r.base}),Re=r=>r?.kind==="primitive-type",N=r=>r?.kind==="nested",Xe=r=>r?.kind==="profile";var _=r=>r?.identifier.kind==="resource"||r?.identifier.kind==="complex-type"||r?.identifier.kind==="logical",Ye=r=>r?.identifier.kind==="complex-type",w=r=>r?.identifier.kind==="resource",Ze=r=>r?.identifier.kind==="primitive-type",O=r=>r?.identifier.kind==="logical",ie=r=>r?.identifier.kind==="profile";function Qe(r){return r?.identifier.kind==="binding"}function et(r){return r?.identifier.kind==="value-set"}var q=r=>r?r.choices===void 0:false,G=r=>r?r.choices!==void 0:false,xe=r=>r?.resourceType==="ValueSet",tt=r=>r?.resourceType==="CodeSystem",nt=(r,e)=>{if(!r.url)throw new Error("ValueSet must have a URL");if(!r.name)throw new Error("ValueSet must have a name");return {...r,package_meta:r.package_meta||e,name:r.name,url:r.url}};var rt={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function Mt(r){return r.split("-").map(e=>I(e)).join("-")}function Lt(r){let e=r;for(let t in rt)e=e.replaceAll(t,rt[t]??"");return e}function jt(r){let e=Number(r[0]);return Number.isInteger(e)&&!Number.isNaN(e)?`_${r}`:r}function it(r){let e=Mt(r);return e=jt(e),e=Lt(e),e=I(e),e}function $(r){return I(Je(r.replaceAll(".","-")))}var Bt={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"},Vt=["Reference","Expression"],Ut=r=>r.required?["required"]:[],Ht=r=>{let e=ct(at(r.identifier));return I(e)},At=r=>r.base?`: ${r.base.name}`:"",_t=(r,e=true)=>{if(!r)return;let t=r.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),$(t)},at=r=>{if(r.kind==="nested"){let e=r.url,t=_t(e,false);if(!t)return "";let[n,o]=t.split("#"),i=ne((o??"").split(".")).join("");return $([n,i].join(""))}return $(r.name)},Gt=r=>Vt.includes(r),ct=r=>Gt(r)?`Resource${r}`:r,oe=class extends A{enums={};constructor(e){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",...e});}async generate(e){let t=e.collectComplexTypes(),n=e.collectResources(),o=Array.from(new Set(n.map(i=>$(i.identifier.package))));this.generateAllFiles(t,n,o),this.copyStaticFiles();}generateAllFiles(e,t,n){this.generateUsingFile(n),this.generateBaseTypes(e),this.generateResources(t),this.generateEnumFiles(n),this.generateResourceDictionaries(t,n),this.generateHelperFile();}generateType(e,t){let n=Ht(e),o=At(e);this.curlyBlock(["public","class",n,o],()=>{this.generateFields(e,t),this.generateNestedTypes(e,t),this.line(),this.includeHelperMethods();}),this.line();}generateFields(e,t){if(!e.fields)return;let n=Object.entries(e.fields).sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of n)this.generateField(o,i,t);}generateNestedTypes(e,t){if(!(!("nested"in e)||!e.nested)){this.line();for(let n of e.nested)this.generateType(n,t);}}generateField(e,t,n){try{if(G(t))return;let o=this.buildFieldDeclaration(e,t,n);this.line(...o);}catch(o){this.logger()?.error(`Error processing field ${e}: ${o.message}`);}}buildFieldDeclaration(e,t,n){let o=this.determineFieldType(e,t,n),i=Ut(t),s=L(e);return ["public",...i,o,s,"{ get; set; }"].filter(Boolean)}determineFieldType(e,t,n){let o=this.getBaseTypeName(t);"enum"in t&&t.enum&&(o=this.registerAndGetEnumType(e,t,n)),o=ct(o);let i="",s=t.required?"":"?",c=t.array?"[]":"";return `${i}${o}${c}${s}`}getBaseTypeName(e){if("type"in e){let t=e.type.name.toString();return e.type.kind==="nested"?t=at(e.type):e.type.kind==="primitive-type"&&(t=Bt[e.type.name]??"string"),t}return ""}registerAndGetEnumType(e,t,n){let i=`${$(t.binding?.name??e)}Enum`;return this.enums[n]||(this.enums[n]={}),t.enum&&(this.enums[n][i]=t.enum),i}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(n=>`${this.opts.targetNamespace}.${n}`)];for(let n of t)this.lineSM("global","using",n);}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 n=$(t.identifier.package);this.generateType(t,n);}});});}generateResources(e){for(let t of e)this.generateResourceFile(t);}generateResourceFile(e){let t=$(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[n,o]of Object.entries(t))this.generateEnum(n,o);}generateEnum(e,t){this.curlyBlock(["public","enum",e],()=>{for(let n of t)this.line(`[Description("${n}")]`),this.line(`${it(n)},`);}),this.line();}generateResourceDictionaries(e,t){this.cd("/",async()=>{for(let n of t){let o=e.filter(i=>$(i.identifier.package)===n);if(o.length===0)return;this.cat(`${n}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.targetNamespace}`),this.generateResourceDictionaryClass(n,o);});}});}generateResourceDictionaryClass(e,t){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let n of t){let o=n.identifier.name;this.line(`{ typeof(${e}.${o}), "${o}" },`);}}),this.lineSM();});}copyStaticFiles(){if(!this.opts.staticSourceDir)return;let e=P__default.resolve(this.opts.staticSourceDir);x__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");x__default.copyFileSync(e,t);}};var zt=async(r,e)=>{let n=(await r.packageJson(e.name)).dependencies;return n!==void 0?Object.entries(n).map(([o,i])=>({name:o,version:i})):[]},dt=r=>({pkg:r,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),ut=async(r,e,t,n,o)=>{let i=S(e);if(o?.info(`${" ".repeat(t*2)}+ ${i}`),n[i])return n[i];let s=dt(e);for(let a of await r.search({package:e})){let l=a.url;if(!l||!(isStructureDefinition(a)||xe(a)||tt(a)))continue;let u=l;s.canonicalResolution[u]&&o?.dry_warn(`Duplicate canonical URL: ${u} at ${i}.`),s.canonicalResolution[u]=[{deep:t,pkg:e,pkgId:i,resource:a}];}let c=await zt(r,e);for(let a of c){let{canonicalResolution:l}=await ut(r,a,t+1,n,o);for(let[u,h]of Object.entries(l)){let m=u;s.canonicalResolution[m]=[...s.canonicalResolution[m]||[],...h];}}for(let a of Object.values(s.canonicalResolution))a.sort((l,u)=>l.deep-u.deep);return n[i]=s,s},lt=(r,e,t)=>{let n=Object.values(r).flatMap(o=>o.canonicalResolution[e]);if(!n)throw new Error(`No canonical resolution found for ${e} in any package`);return n[0]?.resource},J=async(r,{logger:e,fallbackPackageForNameResolution:t,focusedPackages:n})=>{let o=n??await r.packages(),i={};for(let d of o)await ut(r,d,0,i,e);for(let{pkg:d,canonicalResolution:g}of Object.values(i)){let p=S(d);if(!i[p])throw new Error(`Package ${p} not found`);let f=0;e?.info(`FHIR Schema conversion for '${S(d)}' begins...`);for(let[y,k]of Object.entries(g)){let v=k[0];if(!v)throw new Error("Resource not found");let R=v.resource,Q=v.pkg;if(isStructureDefinition(R)){let C=Ce(pt.translate(R),Q);f++,i[p].fhirSchemas[C.url]=C;}if(xe(R)){let C=nt(R,Q);i[p].valueSets[C.url]=C;}}e?.info(`FHIR Schema conversion for '${S(d)}' completed: ${f} successful`);}let s=(d,g)=>i[S(d)]?.fhirSchemas[g]||t&&i[S(t)]?.fhirSchemas[g],c=(d,g)=>i[S(d)]?.valueSets[g]||t&&i[S(t)]?.valueSets[g],a=d=>d.match(/^[a-zA-Z0-9]+$/)&&`http://hl7.org/fhir/StructureDefinition/${d}`||d,l=(d,g)=>{let p=s(d,g);if(p===void 0)throw new Error(`Failed to resolve FHIR Schema: '${g}'`);let f=[p];for(;p?.base;){let y=p.package_meta,k=a(p.base);if(p=s(y,k),p===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${g}'. Problem: '${k}' from '${S(y)}'`);f.push(p);}return f};return {...r,testAppendFs(d){let g=Ce(d),p=S(g.package_meta);i[p]||(i[p]=dt(g.package_meta)),i[p].fhirSchemas[g.url]=g;},resolveFs:s,resolveFsGenealogy:l,resolveFsSpecializations:(d,g)=>l(d,g).filter(p=>p.derivation==="specialization"),ensureSpecializationCanonicalUrl:a,resolveSd:(d,g)=>{let p=lt(i,g);if(isStructureDefinition(p))return p},allFs:()=>Object.values(i).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(i).flatMap(d=>Object.values(d.valueSets)),resolveVs:c,resolveAny:d=>lt(i,d),resolveElementSnapshot:(d,g)=>{let p=l(d.package_meta,d.url),f=Wt(p,g);return qt(f)},getAllElementKeys:d=>{let g=new Set;for(let[p,f]of Object.entries(d)){g.add(p);for(let y of f?.choices||[])d[y]||g.add(y);}return Array.from(g)},resolver:i}};var Wt=(r,e)=>{let[t,...n]=e;return t===void 0?[]:r.map(o=>{if(!o.elements)return;let i=o.elements?.[t];for(let s of n)i=i?.elements?.[s];return i}).filter(o=>o!==void 0)};function qt(r){let e=r.reverse(),t=Object.assign({},...e);return t.elements=void 0,t}function Ie(r){let e=r.split("|")[0];return e||r}function Jt(r){return r.split("|")[1]}function Kt(r){return r.derivation==="constraint"?"profile":r.kind==="primitive-type"?"primitive-type":r.kind==="complex-type"?"complex-type":r.kind==="resource"?"resource":r.kind==="logical"?"logical":"resource"}function B(r){return {kind:Kt(r),package:r.package_meta.name,version:r.package_meta.version,name:r.name,url:r.url}}var Xt=r=>{let e=r.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(""):r};function se(r,e,t){let n=Ie(t),o=Xt(n),i={package_meta:{name:"missing_valuesets",version:Jt(n)||"0.0.0"},id:t},s=r.resolveVs(e,n)||i,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:n}}function ae(r,e,t){let n=e.join("."),[o,i,s]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[r.package_meta,`${r.name}.${n}_binding`,`${r.url}#${n}_binding`];return {kind:"binding",package:o.name,version:o.version,name:i,url:s}}function ce(r,e,t,n){let o={};if(e.derivation==="constraint"){let a=r.resolveFsSpecializations(e.package_meta,e.url).map(l=>we(r,l,n)).filter(l=>l!==void 0).flat();for(let l of a.reverse())o[l.identifier.name]=l.identifier.url;}let i=t.join("."),s=o[i]??`${e.url}#${i}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:i,url:s}}function ft(r,e,t){let n=[];for(let[o,i]of Object.entries(t)){let s=[...e,o];K(i)&&n.push([s,i]),i.elements&&n.push(...ft(r,s,i.elements));}return n}function Yt(r,e,t,n,o){let i={};for(let[s,c]of Object.entries(n)){let a=[...t,s],l=r.resolveElementSnapshot(e,a);K(l)?i[s]=pe(r,e,a,l,o):i[s]=le(r,e,a,l,o);}return i}function we(r,e,t){if(!e.elements)return;let n=ft(e,[],e.elements).filter(([i,s])=>s.elements&&Object.keys(s.elements).length>0),o=[];for(let[i,s]of n){let c=ce(r,e,i,t),a;s.type==="BackboneElement"||!s.type?a="BackboneElement":a=s.type;let l=r.ensureSpecializationCanonicalUrl(a),u=r.resolveFs(e.package_meta,l);if(!u)throw new Error(`Could not resolve base type ${a}`);let h={kind:"complex-type",package:u.package_meta.name,version:u.package_meta.version,name:a,url:l},m=Yt(r,e,i,s.elements??{},t),d={identifier:c,base:h,fields:m};o.push(d);}return o.sort((i,s)=>i.identifier.url.localeCompare(s.identifier.url)),o.length===0?void 0:o}function gt(r){let e=[];for(let t of r){t.base&&e.push(t.base);for(let n of Object.values(t.fields||{}))"type"in n&&n.type&&e.push(n.type),"binding"in n&&n.binding&&e.push(n.binding);}return e}function mt(r,e,t){let n=t[t.length-1];if(!n)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),i=r.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(i).has(n)}function ht(r,e,t){let n=t[t.length-1];if(!n)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let o=t.slice(0,-1),i=r.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(i).has(n)}var Zt=(r,e,t)=>{if(t.refers)return t.refers.map(n=>{let o=r.ensureSpecializationCanonicalUrl(n),i=r.resolveFs(e.package_meta,o);if(!i)throw new Error(`Failed to resolve fs for ${o}`);return B(i)})};function $e(r,e,t,n,o){if(n.elementReference){let i=n.elementReference.slice(1).filter((s,c)=>c%2===1);return ce(r,e,i,o)}else if(n.type){let i=r.ensureSpecializationCanonicalUrl(n.type),s=r.resolveFs(e.package_meta,i);if(!s)throw new Error(`Could not resolve field type: '${n.type}' (from '${e.url}' in '${S(e.package_meta)}')`);return B(s)}else {if(n.choices)return;if(e.derivation==="constraint")return;throw o?.error(`Can't recognize element type '${e.url}' (${e.derivation}) at '${t.join(".")}': ${JSON.stringify(n,void 0,2)}`),new Error("Unrecognized element type")}}var le=(r,e,t,n,o)=>{let i,s;n.binding&&(i=ae(e,t,n.binding.bindingName),n.binding.strength==="required"&&n.type==="code"&&(s=Pe(r,e,n,o)));let c=$e(r,e,t,n,o);return c||o?.warn(`Field type not found for '${e.url}#${t.join(".")}' (${e.derivation})`),{type:c,required:mt(r,e,t),excluded:ht(r,e,t),reference:Zt(r,e,n),array:n.array||false,min:n.min,max:n.max,choices:n.choices,choiceOf:n.choiceOf,binding:i,enum:s}};function K(r){let e=r.type==="BackboneElement",t=r.type==="Element"&&r.elements!==void 0&&Object.keys(r.elements).length>0,n=r.type===void 0&&r.choiceOf===void 0&&r.elements!==void 0&&Object.keys(r.elements).length>0;return e||t||n}function pe(r,e,t,n,o){return {type:ce(r,e,t,o),array:n.array||false,required:mt(r,e,t),excluded:ht(r,e,t)}}function Ee(r,e,t,n){let o=Ie(t)||t,i=r.resolveVs(e,o);if(i)return Qt(r,i)}function Qt(r,e,t){if(e.expansion?.contains)return e.expansion.contains;let n=[];if(e.compose?.include){for(let o of e.compose.include)if(o.concept)for(let i of o.concept)n.push({system:o.system,code:i.code,display:i.display});else if(o.system&&!o.filter)try{let i=r.resolveAny(o.system);if(i?.concept){let s=(c,a)=>{for(let l of c)n.push({system:a,code:l.code,display:l.display}),l.concept&&s(l.concept,a);};s(i.concept,o.system);}}catch{}}return n.length>0?n:void 0}var yt=100;function Pe(r,e,t,n){if(!t.binding)return;let o=t.binding.strength,i=t.binding.valueSet;if(!i||!(o==="required"||o==="extensible"&&(t.type==="code"||t.type==="Coding")||o==="preferred"&&(t.type==="code"||t.type==="Coding")))return;let c=Ee(r,e.package_meta,i);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>yt){n?.dry_warn(`Value set ${i} has ${a.length} which is more than ${yt} codes, which may cause issues with code generation.`);return}return a.length>0?a:void 0}function en(r,e,t,n,o){if(!n.binding?.valueSet)return;let i=ae(e,t,n.binding.bindingName),s=$e(r,e,t,n,o),c=se(r,e.package_meta,n.binding.valueSet),a=[];s&&a.push(s),a.push(c);let l=Pe(r,e,n,o);return {identifier:i,type:s,valueset:c,strength:n.binding.strength,enum:l,dependencies:a}}function St(r,e,t){let n=new Set;if(!e.elements)return [];let o=[];function i(a,l){for(let[u,h]of Object.entries(a)){let m=[...l,u],d=m.join(".");if(!n.has(d)){if(n.add(d),h.binding){let g=en(r,e,m,h,t);g&&o.push(g);}h.elements&&i(h.elements,m);}}}i(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 tn(r,e,t,n,o){if(!n)return;let i={};for(let s of r.getAllElementKeys(n)){let c=[...t,s],a=r.resolveElementSnapshot(e,c);K(a)?i[s]=pe(r,e,c,a,o):i[s]=le(r,e,c,a,o);}return i}function nn(r){let e=[];for(let t of Object.values(r))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function rn(r,e){return !!(r.base==="Extension"||r.base==="http://hl7.org/fhir/StructureDefinition/Extension"||r.url?.includes("/extension/")||r.url?.includes("-extension")||r.name?.toLowerCase().includes("extension")||r.type==="Extension")}async function de(r,e,t){if(!e.url)throw new Error("ValueSet URL is required");let n=se(r,e.package_meta,e.url),o=Ee(r,e.package_meta,e.url);return {identifier:n,description:e.description,concept:o,compose:o?void 0:e.compose}}function Ne(r,e,t,n){let o=[];e&&o.push(e),t&&o.push(...nn(t)),n&&o.push(...gt(n));let i={};for(let a of o)a.url!==r.url&&(i[a.url]=a);let s=new Set(n?.map(a=>a.identifier.url)),c=Object.values(i).filter(a=>Xe(r)||!N(a)?true:!s.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function on(r,e,t){let n=B(e),o;if(e.base&&e.type!=="Element"){let u=r.resolveFs(e.package_meta,r.ensureSpecializationCanonicalUrl(e.base));if(!u)throw new Error(`Base resource not found '${e.base}' for <${e.url}> from ${S(e.package_meta)}`);o=B(u);}let i=tn(r,e,[],e.elements,t),s=we(r,e,t),c=Ne(n,o,i,s),a={identifier:n,base:o,fields:i,nested:s,description:e.description,dependencies:c},l=St(r,e,t);return [a,...l]}async function ue(r,e,t){let n=on(r,e,t);if(rn(e,B(e))){let o=n[0];if(!o)throw new Error("Expected schema to be defined");o.metadata={isExtension:true};}return n}var Oe=r=>{let e={};for(let t of r){let n=t.identifier.package;e[n]||(e[n]=[]),e[n].push(t);}for(let[t,n]of Object.entries(e)){let o={};for(let s of n)o[JSON.stringify(s.identifier)]=s;let i=Object.values(o);i.sort((s,c)=>s.identifier.name.localeCompare(c.identifier.name)),e[t]=i;}return e},sn=(r,e,t)=>{if(r=structuredClone(r),Ze(r)||et(r)||Qe(r))return r;for(let n of e.ignoreFields??[]){if(r.fields&&!r.fields[n])throw new Error(`Field ${n} not found`);r.fields&&delete r.fields[n];}return r.dependencies=Ne(r.identifier,r.base,r.fields,r.nested),r},kt=(r,e,t)=>{let n=[];for(let[s,c]of Object.entries(e))for(let[a,l]of Object.entries(c)){let u=r.resolveByUrl(s,a);if(!u)throw new Error(`Schema not found for ${s} ${a}`);let h=sn(u,l);n.push(h);}let o=(s,c)=>{if(s.length===0)return Object.values(c);for(let l of s)c[JSON.stringify(l.identifier)]=l;let a=[];for(let l of s)if(_(l)){if(!l.dependencies)continue;if(l.dependencies.forEach(u=>{let h=r.resolve(u);if(!h)throw new Error(`Schema not found for ${u}`);let m=JSON.stringify(h.identifier);c[m]||a.push(h);}),l.nested)for(let u of l.nested){if(N(u.identifier))continue;let h=JSON.stringify(u.identifier);c[h]||a.push(u);}}return o(a,c)},i=o(n,{});return De(i,t)},an=r=>{let e=r.filter(i=>w(i)||O(i)),t=[];for(let i of e)i.base&&t.push({parent:i.base,child:i.identifier});let n=[...t],o=i=>{let s=t.filter(a=>a.parent.name===i.name).map(a=>a.child),c=[];for(let a of s)c.push(...o(a));return [...s,...c]};for(let i of t){let s=o(i.child);for(let c of s)t.some(a=>a.parent.name===i.parent.name&&a.child.name===c.name)||n.push({parent:i.parent,child:c});}return n},De=(r,e)=>{let t={},n=p=>{let f=p.identifier.url,y=p.identifier.package;if(t[f]||(t[f]={}),t[f][p.identifier.package]&&y!=="shared"){let k=JSON.stringify(p.identifier,void 0,2),v=JSON.stringify(t[f][y]?.identifier,void 0,2);if(k!==v)throw new Error(`Duplicate schema: ${k} and ${v}`);return}t[f][y]=p;};for(let p of r)n(p);let o=an(r),i=p=>t[p.url]?.[p.package],s=(p,f)=>t[f]?.[p],c=p=>o.filter(f=>f.parent.name===p.name).map(f=>f.child),a=p=>{let f=[],y=p;for(;y;){f.push(y);let k=y.base;if(k===void 0)break;let v=i(k);if(!v){e?.warn(`Failed to resolve base type: ${f.map(R=>`${R.identifier.url} (${R.identifier.kind})`).join(", ")}`);return}y=v;}return f},l=p=>{let f=a(p);if(f===void 0)throw new Error(`Failed to resolve base type: ${p.identifier.url} (${p.identifier.kind})`);return f},u=p=>{let f=l(p).find(y=>y.identifier.kind!=="profile");if(!f)throw new Error(`No non-constraint schema found in hierarchy for: ${p.identifier.name}`);return f};return {_schemaIndex:t,_relations:o,collectComplexTypes:()=>r.filter(Ye),collectResources:()=>r.filter(w),collectLogicalModels:()=>r.filter(O),collectProfiles:()=>r.filter(ie),resolve:i,resolveByUrl:s,resourceChildren:c,tryHierarchy:a,hierarchy:l,findLastSpecialization:u,findLastSpecializationByIdentifier:p=>{let f=i(p);return f?u(f).identifier:p},flatProfile:p=>{let f=l(p),y=f.filter(C=>C.identifier.kind==="profile"),k=f.find(C=>C.identifier.kind!=="profile");if(!k)throw new Error(`No non-constraint schema found in hierarchy for ${p.identifier.name}`);let v={};for(let C of y.slice().reverse()){let ee=C;if(ee.fields)for(let[te,He]of Object.entries(ee.fields))v[te]?v[te]={...v[te],...He}:v[te]={...He};}let R={};for(let C of y.flatMap(ee=>ee.dependencies??[]))R[C.url]=C;let Q=Object.values(R);return {...p,base:k.identifier,fields:v,dependencies:Q}},isWithMetaField:p=>{let f=a(p);return f?f.filter(_).some(y=>y.fields?.meta!==void 0):false},exportTree:async p=>{let f={};for(let[k,v]of Object.entries(Oe(r))){f[k]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},logical:{}};for(let R of v)f[k][R.identifier.kind][R.identifier.url]={};}let y=p.endsWith(".yaml")?vt.stringify(f):JSON.stringify(f,void 0,2);await D.mkdir(P.dirname(p),{recursive:true}),await D.writeFile(p,y);}}};var X=class{manager;options;logger;constructor(e={}){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.logger=e.logger||E({verbose:this.options.verbose,prefix:"TypeSchema"});}async registerFromPackageMetas(e){let t=e.map(S);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),J(this.manager,{focusedPackages:e})}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=[],n=0,o=0;for(let i of e)try{let s=pt.translate(i);t.push(s),n++,this.logger?.debug(`Converted StructureDefinition: ${i.name||i.id} (${i.resourceType})`);}catch(s){o++,this.logger?.warn(`Failed to convert StructureDefinition ${i.name||i.id}: ${s instanceof Error?s.message:String(s)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${n}/${e.length} successful, ${o} failed`),t}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let n=await J(this.manager,{logger:this.logger}),o=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let i=0,s=0;for(let c of e)try{let a=await de(n,c,t);a&&(o.push(a),i++,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: ${i}/${e.length} successful, ${s} failed`);}return o}async generateFromPackage(e,t,n){let o={name:e,version:t||"latest"},i=await this.registerFromPackageMetas([o]),s=await this.generateValueSetSchemas(i.allVs(),n);return [...(await Promise.all(i.allFs().map(async l=>await ue(i,l,n)))).flat(),...s]}};var Y="Use CodeableReference which is not provided by FHIR R4.",ln="Use Availability which is not provided by FHIR R4.",Ct={"hl7.fhir.uv.extensions.r4#1.0.0":{"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":ln,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":Y,"http://hl7.org/fhir/StructureDefinition/specimen-additive":Y,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":Y,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":Y,"http://hl7.org/fhir/StructureDefinition/workflow-reason":Y},"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."}},Rt=async(r,e)=>{let t=[];for(let n of r.allFs()){let o=S(n.package_meta);if(Ct[o]?.[n.url]){e?.dry_warn(`Skip ${n.url} from ${o}. Reason: ${Ct[o]?.[n.url]}`);continue}t.push(...await ue(r,n,e));}for(let n of r.allVs())t.push(await de(r,n));return t};var pn={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"},xt=r=>{let e=pn[r];if(e===void 0)throw new Error(`Unknown primitive type ${r}`);return e},dn=r=>W(r),It=r=>r.kind==="profile"?`${T(r)}_profile`:L(r.name),un=r=>`${It(r)}.ts`,Me=(r,e=true)=>{if(!r)return;let t=re(r,e);if(t)return Le(t)},T=r=>{if(r.kind==="nested"){let e=r.url,t=Me(e,false);if(!t)return "";let[n,o]=t.split("#"),i=ne((o??"").split(".")).join("");return Le([n,i].join(""))}return Le(r.name)},wt=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),z=r=>wt.has(r)?`"${r}"`:r.includes(" ")||r.includes("-")?`"${r}"`:r,Le=r=>(wt.has(r)&&(r=`${r}_`),r.replace(/[- ]/g,"_")),V=(r,e)=>e.startsWith('"')?`${r}[${e}]`:`${r}.${e}`,Ft=r=>`(${r.map(e=>`"${e}"`).join(" | ")})`,ge=class extends A{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.flatMap(n=>[{identifier:n.identifier,tsPackageName:It(n.identifier),resourceName:T(n.identifier),nestedTypes:w(n)&&n.nested||O(n)&&n.nested?n.nested.map(o=>T(o.identifier)):[],helpers:w(n)||O(n)?[`is${T(n.identifier)}`]:[]}]).sort((n,o)=>n.resourceName.localeCompare(o.resourceName));t=Array.from(new Map(t.map(n=>[n.resourceName.toLowerCase(),n])).values()).sort((n,o)=>n.resourceName.localeCompare(o.resourceName));for(let n of t)this.debugComment(n.identifier),this.lineSM(`export type { ${[n.resourceName,...n.nestedTypes].join(", ")} } from "./${n.tsPackageName}"`),n.helpers.length>0&&this.lineSM(`export { ${n.helpers.join(", ")} } from "./${n.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],n=[];for(let o of e.dependencies)["complex-type","resource","logical"].includes(o.kind)?t.push({tsPackage:`../${W(o.package)}/${L(o.name)}`,name:I(o.name),dep:o}):N(o)?t.push({tsPackage:`../${W(o.package)}/${L(Me(o.url)??"")}`,name:T(o),dep:o}):n.push(o);t.sort((o,i)=>o.name.localeCompare(i.name));for(let o of t)this.debugComment(o.dep),this.tsImportType(o.tsPackage,o.name);for(let o of n)this.debugComment("skip:",o);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(n=>["complex-type"].includes(n.kind)).map(n=>({tsPackage:`../${W(n.package)}/${L(n.name)}`,name:I(n.name)}));if(t&&t.length>0){for(let n of t)this.lineSM(`export type { ${n.name} } from "${n.tsPackage}"`);this.line();}}addFieldExtension(e,t){if(t.type.kind==="primitive-type"){let n=z(`_${e}`);this.lineSM(`${n}?: Element`);}}generateType(e,t){let n;t.identifier.name==="Reference"?n="Reference<T extends string = string>":(t.identifier.kind,n=T(t.identifier));let o;if(t.base&&(o=`extends ${Me(t.base.url)}`),this.debugComment(t.identifier),!t.fields&&!o&&!w(t)){this.lineSM(`export type ${n} = object`);return}this.curlyBlock(["export","interface",n,o],()=>{if(w(t)||O(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 i=Object.entries(t.fields).sort((s,c)=>s[0].localeCompare(c[0]));for(let[s,c]of i){if(G(c))continue;this.debugComment(s,":",c);let a=z(s),l;c.enum?l=Ft(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(" | ")}>`:Re(c.type)?l=xt(c.type.name):N(c.type)?l=T(c.type):l=c.type.name;let u=c.required?"":"?",h=c.array?"[]":"";this.lineSM(`${a}${u}: ${l}${h}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(s,c);}});}generateResourceTypePredicate(e){if(!w(e)&&!O(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 n of t.nested)this.generateType(e,n),this.line();}generateProfileType(e,t){this.debugComment("flatProfile",t);let n=T(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",n],()=>{this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line();for(let[o,i]of Object.entries(t.fields??{})){if(G(i))continue;this.debugComment(o,i);let s=z(o),c;if(i.enum)c=Ft(i.enum);else if(i.reference&&i.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||G(l)||l.reference===void 0)throw new Error(`Invalid field declaration for ${o}`);let u=l.reference.map(m=>m.name),h=i.reference.map(m=>{let d=e.findLastSpecializationByIdentifier(m);return d.name!==m.name?`"${d.name}" /*${m.name}*/`:`'${m.name}'`}).join(" | ");u.length===1&&u[0]==="Resource"&&h!=='"Resource"'?c=`Reference<"Resource" /* ${h} */ >`:c=`Reference<${h}>`;}else if(N(i.type))c=T(i.type);else if(Re(i.type))c=xt(i.type.name);else {if(i.type===void 0)throw new Error(`Undefined type for '${o}' field at ${Ke(t)}`);c=i.type.name;}this.lineSM(`${s}${i.required?"":"?"}: ${c}${i.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=T(e.base),n=T(e.identifier),o=Object.entries(e.fields||{}).filter(([i,s])=>s&&q(s)&&s.type!==void 0).map(([i])=>z(i));this.curlyBlock([`export const attach_${n}_to_${t} =`,`(resource: ${t}, profile: ${n}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),o.forEach(i=>{this.line(`${i}: ${V("profile",i)},`);});});}),this.line();}generateExtractProfile(e,t){let n=T(t.base),o=T(t.identifier),i=Object.entries(t.fields||{}).filter(([a,l])=>q(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_${n} =`,`(resource: ${n}): ${o}`,"=>"],()=>{i.forEach(a=>{let l=z(a),u=t.fields?.[a],h=s.fields?.[a];if(!q(u)||!q(h))return;u.required&&!h.required&&this.curlyBlock([`if (${V("resource",l)} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let m=u?.reference?.map(g=>g.name),d=h?.reference?.map(g=>g.name);if(m&&d&&m.length!==d.length){let g=`reference_is_valid_${l}`;this.curlyBlock(["const",g,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{d.forEach(f=>{this.line(`|| ref.reference?.startsWith('${f}/')`);}),this.line(";");});});let p=u?.required?"":`!${V("resource",l)} || `;u.array?p+=`${V("resource",l)}.every( (ref) => ${g}(ref) )`:p+=`!${g}(${V("resource",l)})`,this.curlyBlock(["if (",p,")"],()=>{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}',`),i.forEach(a=>{let l=z(a);c[a]?this.line(`${l}:`,`${V("resource",l)} as ${o}['${l}'],`):this.line(`${l}:`,`${V("resource",l)},`);});});});}generateResourceModule(e,t){this.cat(`${un(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.comment("CanonicalURL:",t.identifier.url),this.generateType(e,t),this.generateResourceTypePredicate(t);else if(ie(t)){let n=e.flatProfile(t);this.generateDependenciesImports(n),this.comment("CanonicalURL:",t.identifier.url),this.generateProfileType(e,n),this.generateAttachProfile(n),this.generateExtractProfile(e,n);}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)):[]],n=Oe(t);this.cd("/",()=>{for(let[o,i]of Object.entries(n)){let s=dn(o);this.cd(s,()=>{for(let c of i)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(i);});}});}};var $t=r=>{let e=r.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return e.length===0?"unknown":e},gn=async(r,e)=>{e.info("Cleaning outputs...");try{e.info(`Clean ${r.outputDir}`),x.rmSync(r.outputDir,{recursive:!0,force:!0}),r.typeSchemaOutputDir&&(e.info(`Clean ${r.typeSchemaOutputDir}`),x.rmSync(r.typeSchemaOutputDir,{recursive:!0,force:!0})),r.exportTypeTree&&(e.info(`Clean ${r.exportTypeTree}`),x.rmSync(r.exportTypeTree,{recursive:!0,force:!0}));}catch(t){e.warn(`Error cleaning output directory: ${t instanceof Error?t.message:String(t)}`);}},mn=async(r,e,t)=>{await D.mkdir(e,{recursive:true}),t.info(`Writing TypeSchema files to ${e}/...`);let n={};for(let o of r){let i={name:o.identifier.package,version:o.identifier.version},s=$t(S(i)),c=$t(`${o.identifier.name}(${re(o.identifier.url)})`),a=JSON.stringify(o,null,2),l=P.join(e,s,c);n[l]||(n[l]=[]),n[l]?.some(u=>u===a)||n[l].push(a);}for(let[o,i]of Object.entries(n))await Promise.all(i.map(async(s,c)=>{let a;c===0?a=`${o}.typeschema.json`:a=`${o}-${c}.typeschema.json`,await D.mkdir(P.dirname(a),{recursive:true}),await D.writeFile(a,s);}));},hn=async(r,e,t)=>{t.info(`Writing TypeSchema files to: ${e}`),await D.mkdir(P.dirname(e),{recursive:true}),t.info(`Writing TypeSchemas to one file ${e}...`);for(let n of r){let o=JSON.stringify(n,null,2);await D.appendFile(e,`${o}
7
+ `);}},yn=async(r,e,t)=>{if(e.typeSchemaOutputDir)try{P.extname(e.typeSchemaOutputDir)===".ndjson"?await hn(r,e.typeSchemaOutputDir,t):await mn(r,e.typeSchemaOutputDir,t),t.info("Writing TypeSchema - DONE");}catch(n){if(t.error("Failed to write TypeSchema output",n instanceof Error?n:new Error(String(n))),e.throwException)throw n}},Z=class{schemas=[];options;generators=new Map;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,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},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||E({verbose:this.options.verbose,prefix:"API"});}fromPackage(e,t){let n=Te({name:e,version:t||"latest"});return this.packages.push(n),this}fromPackageRef(e){return this.packages.push(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},...Object.fromEntries(Object.entries(e).filter(([s,c])=>c!==void 0))},i=new ge(o);return this.generators.set("typescript",i),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}csharp(e,t){let n=new oe({outputDir:P.join(this.options.outputDir,"/types"),staticSourceDir:t??void 0,targetNamespace:e,logger:new U({prefix:"C#",timestamp:true,verbose:true,suppressLoggingLevel:[]})});return this.generators.set("C#",n),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}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose: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&&gn(this.options,this.logger),this.logger.info("Initialize Canonical Manager");let n=CanonicalManager({packages:this.packages,workingDir:".codegen-cache/canonical-manager-cache"}),o=await n.init(),i=Object.values(o),s=await J(n,{logger:this.logger,focusedPackages:i}),c=await Rt(s,this.logger);await yn(c,this.options,this.logger);let a=De(c,this.logger);this.options.treeShake&&(a=kt(a,this.options.treeShake,this.logger)),this.options.exportTypeTree&&await a.exportTree(this.options.exportTypeTree),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,a),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(n){if(this.logger.error("Code generation failed",n instanceof Error?n:new Error(String(n))),t.errors.push(n instanceof Error?n.message:String(n)),this.options.throwException)throw n}return {...t,success:t.errors.length===0,duration:performance.now()-e}}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async executeGenerators(e,t){for(let[n,o]of this.generators.entries()){this.logger.info(`Generating ${n}...`);try{await o.generate(t);let i=o.writtenFiles();e.filesGenerated.push(...i.map(s=>s.absPath)),this.logger.info(`Generating ${n} finished successfully`);}catch(i){if(e.errors.push(`${n} generator failed: ${i instanceof Error?i.message:String(i)}`),this.options.throwException)throw i}}}};var je={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,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:""},he=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Be=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 n=e;n.outputDir!==void 0&&typeof n.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:n.outputDir});let o=["verbose","overwrite","validate","cache"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.errors.push({path:i,message:`${i} must be a boolean`,value:n[i]});if(n.typescript!==void 0){let i=this.validateTypeScriptConfig(n.typescript);t.errors.push(...i);}if(n.typeSchema!==void 0){let i=this.validateTypeSchemaConfig(n.typeSchema);t.errors.push(...i);}return n.packages!==void 0&&(Array.isArray(n.packages)?n.packages.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`packages[${s}]`,message:"package name must be a string",value:i});}):t.errors.push({path:"packages",message:"packages must be an array",value:n.packages})),n.files!==void 0&&(Array.isArray(n.files)?n.files.forEach((i,s)=>{typeof i!="string"&&t.errors.push({path:`files[${s}]`,message:"file path must be a string",value:i});}):t.errors.push({path:"files",message:"files must be an array",value:n.files})),t.valid=t.errors.length===0,t.valid&&(t.config=n),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 n=e;n.moduleFormat!==void 0&&(["esm","cjs"].includes(n.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:n.moduleFormat})),n.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(n.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:n.namingConvention}));let o=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.${i}`,message:`${i} must be a boolean`,value:n[i]});if(n.validatorOptions!==void 0){let i=this.validateValidatorOptions(n.validatorOptions);t.push(...i);}if(n.guardOptions!==void 0){let i=this.validateGuardOptions(n.guardOptions);t.push(...i);}if(n.profileOptions!==void 0){let i=this.validateProfileOptions(n.profileOptions);t.push(...i);}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 n=e,o=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.validatorOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e;n.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(n.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:n.targetTSVersion}));let o=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.guardOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e;n.generateKind!==void 0&&(["interface","type","both"].includes(n.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:n.generateKind})),n.subfolder!==void 0&&typeof n.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:n.subfolder});let o=["includeConstraints","includeDocumentation","strictMode"];for(let i of o)n[i]!==void 0&&typeof n[i]!="boolean"&&t.push({path:`typescript.profileOptions.${i}`,message:`${i} must be a boolean`,value:n[i]});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 n=e,o=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let s of o)n[s]!==void 0&&typeof n[s]!="boolean"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a boolean`,value:n[s]});let i=["cacheDir","cacheKeyPrefix"];for(let s of i)n[s]!==void 0&&typeof n[s]!="string"&&t.push({path:`typeSchema.${s}`,message:`${s} must be a string`,value:n[s]});if(n.maxAge!==void 0&&(typeof n.maxAge!="number"||n.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:n.maxAge}),n.profiles!==void 0)if(typeof n.profiles!="object"||n.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:n.profiles});else {let s=n.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}},Ve=class{validator=new Be;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 i=await import(resolve(e));t=i.default||i;}else {let o=await readFile(e,"utf-8");t=JSON.parse(o);}let n=this.validator.validate(t);if(!n.valid){let o=n.errors.map(i=>`${i.path}: ${i.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 me){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...je,...e,typescript:{...je.typescript,...e.typescript}}}},Tn=new Be;async function he(n){return Tn.autoload(n)}var Nt={command:"generate",describe:"Generate code based on configuration file settings",builder:n=>n.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 n=>{if(n._.length>1){let s=n._.slice(1).join(" ");I(`Invalid syntax: 'atomic-codegen generate ${s}'
9
+ ${o}`)}if(!n.config)throw new Error("Invalid configuration");return this.mergeWithDefaults(n.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 he){let n=resolve(e,t);if(existsSync(n))return n}return null}mergeWithDefaults(e){return {...je,...e,typescript:{...je.typescript,...e.typescript}}}},vn=new Ve;async function ye(r){return vn.autoload(r)}var Et={command:"generate",describe:"Generate code based on configuration file settings",builder:r=>r.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 r=>{if(r._.length>1){let s=r._.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,8 +14,8 @@ 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 Cn(e);if(!t){let s=me.map(c=>` - ${c}`).join(`
18
- `);I(`No configuration file found. Please create one of the following files in your project root:
17
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Cn(e);if(!t){let s=he.map(c=>` - ${c}`).join(`
18
+ `);F(`No configuration file found. Please create one of the following files in your project root:
19
19
  ${s}
20
20
 
21
21
  Example atomic-codegen.config.ts:
@@ -27,13 +27,13 @@ export default defineConfig({
27
27
  typescript: {
28
28
  generateIndex: true
29
29
  }
30
- });`),process.exit(1);}let r=await he(e),o=n.verbose??r.verbose??false,i=E({verbose:o,prefix:"Generate"});try{_e("Starting generation from config"),o&&(i.info(`Config file: ${t}`),i.info(`Output directory: ${r.outputDir||"./generated"}`),i.info(`Packages: ${r.packages?.length||0}`),i.info(`Files: ${r.files?.length||0}`),i.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let s=new Y({outputDir:r.outputDir||"./generated",verbose:o,overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:i});if(r.packages&&r.packages.length>0){i.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let a of r.packages){let[l,u]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,u);}}else throw r.files&&r.files.length>0?(i.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,u,h)=>{let m=Math.round(l/u*100);i.progress(`[${a}] ${m}% - ${h||"Processing..."}`);}),i.step("Executing generation...");let c=await s.generate();if(c.success){if(ye(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),i.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)Ae(a);}else {I(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)i.dim(` ${a}`);process.exit(1);}}catch(s){I("Generation failed with unexpected error",s instanceof Error?s:new Error(String(s))),process.exit(1);}}};async function Cn(n){for(let e of me){let t=resolve(n,e);if(existsSync(t))return t}return null}var Ot={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"}},handler:async n=>{let e=E({verbose:n.verbose,prefix:"TypeSchema"});try{let t=await he(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${n.packages.join(", ")}`),e.info(`Output: ${n.output}`);let r=n.singleFile!==void 0?n.singleFile:t.typeSchema?.singleFile??!1,o=r?"ndjson":n.format;e.debug(`Format: ${o}${r&&n.format==="json"?" (forced from json due to singleFile)":""}`);let i=n.treeshake&&n.treeshake.length>0?n.treeshake:t.typeSchema?.treeshake;i&&i.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${i.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let s=Date.now(),c=new K({verbose:n.verbose,treeshake:i}),a=[];for(let m of n.packages){let[d,g]=m.includes("@")?m.split("@"):[m,void 0];e.progress(`Processing package: ${d}${g?`@${g}`:""}`);let p=await c.generateFromPackage(d,g,e);a.push(...p);}if(a.length===0)throw new Error("No schemas were generated from the specified packages");let l=n.output;if(!l)throw new Error("Output format not specified");await mkdir(dirname(l),{recursive:!0});let u;o==="json"?u=JSON.stringify(a,null,2):u=a.map(m=>JSON.stringify(m)).join(`
31
- `),await writeFile(l,u,"utf-8");let h=Date.now()-s;if(We(`Generated ${a.length} TypeSchema definitions`,h,{schemas:a.length}),e.dim(`Output: ${l}`),n.verbose){e.debug("Generated schemas:");let m=a.map(d=>`${d.identifier?.name||"Unknown"} (${d.identifier?.kind||"unknown"})`);U(m);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Dt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:n=>n.command(Ot).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:n=>{if(!n.subcommand&&n._.length===1){Se("Available typeschema subcommands:"),U(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
30
+ });`),process.exit(1);}let n=await ye(e),o=r.verbose??n.verbose??false,i=E({verbose:o,prefix:"Generate"});try{_e("Starting generation from config"),o&&(i.info(`Config file: ${t}`),i.info(`Output directory: ${n.outputDir||"./generated"}`),i.info(`Packages: ${n.packages?.length||0}`),i.info(`Files: ${n.files?.length||0}`),i.info(`TypeScript generation: ${n.typescript?"enabled":"disabled"}`));let s=new Z({outputDir:n.outputDir||"./generated",verbose:o,overwrite:n.overwrite??!0,cache:n.cache??!0,typeSchemaConfig:n.typeSchema,logger:i});if(n.packages&&n.packages.length>0){i.info(`Loading packages from config: ${n.packages.join(", ")}`);for(let a of n.packages){let[l,u]=a.includes("@")?a.split("@"):[a,void 0];s.fromPackage(l,u);}}else throw n.files&&n.files.length>0?(i.info(`Loading files from config: ${n.files.join(", ")}`),new Error("Not Implemented")):new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(n.typescript)throw new Error("Not Implemented");if(!n.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");o&&s.onProgress((a,l,u,h)=>{let m=Math.round(l/u*100);i.progress(`[${a}] ${m}% - ${h||"Processing..."}`);}),i.step("Executing generation...");let c=await s.generate();if(c.success){if(Se(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),i.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)Ae(a);}else {F(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)i.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 Cn(r){for(let e of he){let t=resolve(r,e);if(existsSync(t))return t}return null}var Nt={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"}},handler:async r=>{let e=E({verbose:r.verbose,prefix:"TypeSchema"});try{let t=await ye(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${r.packages.join(", ")}`),e.info(`Output: ${r.output}`);let n=r.singleFile!==void 0?r.singleFile:t.typeSchema?.singleFile??!1,o=n?"ndjson":r.format;e.debug(`Format: ${o}${n&&r.format==="json"?" (forced from json due to singleFile)":""}`);let i=r.treeshake&&r.treeshake.length>0?r.treeshake:t.typeSchema?.treeshake;i&&i.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${i.join(", ")}`),n&&e.info("Single file output enabled (NDJSON format)");let s=Date.now(),c=new X({verbose:r.verbose,treeshake:i}),a=[];for(let m of r.packages){let[d,g]=m.includes("@")?m.split("@"):[m,void 0];e.progress(`Processing package: ${d}${g?`@${g}`:""}`);let p=await c.generateFromPackage(d,g,e);a.push(...p);}if(a.length===0)throw new Error("No schemas were generated from the specified packages");let l=r.output;if(!l)throw new Error("Output format not specified");await mkdir(dirname(l),{recursive:!0});let u;o==="json"?u=JSON.stringify(a,null,2):u=a.map(m=>JSON.stringify(m)).join(`
31
+ `),await writeFile(l,u,"utf-8");let h=Date.now()-s;if(We(`Generated ${a.length} TypeSchema definitions`,h,{schemas:a.length}),e.dim(`Output: ${l}`),r.verbose){e.debug("Generated schemas:");let m=a.map(d=>`${d.identifier?.name||"Unknown"} (${d.identifier?.kind||"unknown"})`);H(m);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Ot={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:r=>r.command(Nt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:r=>{if(!r.subcommand&&r._.length===1){be("Available typeschema subcommands:"),H(["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
- Examples:`),U(["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}n.subcommand&&!["generate","validate","merge"].includes(n.subcommand)&&(I(`Unknown typeschema subcommand: ${n.subcommand}
34
- `),Se("Available typeschema subcommands:"),U(["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));}};async function Pn(n){Ge({verbose:n.verbose||n.debug,timestamp:n.debug});}function En(){return wn(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Pn).command(Dt).command(Nt).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("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(n=>{n._.length===0&&(ze("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(`
33
+ Examples:`),H(["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}r.subcommand&&!["generate","validate","merge"].includes(r.subcommand)&&(F(`Unknown typeschema subcommand: ${r.subcommand}
34
+ `),be("Available typeschema subcommands:"),H(["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));}};async function $n(r){Ge({verbose:r.verbose||r.debug,timestamp:r.debug});}function Pn(){return In(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware($n).command(Ot).command(Et).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("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(r=>{r._.length===0&&(ze("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
- 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((n,e,t)=>{e?I(e.message,e):I(n),I(`
39
- Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Ue(){await En().parseAsync();}import.meta.main&&Ue().catch(n=>{n("Unexpected error:",n),process.exit(1);});Ue().catch(n=>{console.error("CLI Error:",n instanceof Error?n.message:n),process.exit(1);});
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((r,e,t)=>{e?F(e.message,e):F(r),F(`
39
+ Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Ue(){await Pn().parseAsync();}import.meta.main&&Ue().catch(r=>{r("Unexpected error:",r),process.exit(1);});Ue().catch(r=>{console.error("CLI Error:",r instanceof Error?r.message:r),process.exit(1);});
package/dist/index.d.ts CHANGED
@@ -478,6 +478,7 @@ declare function defineConfig(config: Config): Config;
478
478
 
479
479
  type FileSystemWriterOptions = {
480
480
  outputDir: string;
481
+ inMemoryOnly?: boolean;
481
482
  logger?: CodegenLogger;
482
483
  };
483
484
  type WriterOptions = FileSystemWriterOptions & {
@@ -570,15 +571,6 @@ declare class APIBuilder {
570
571
  treeShake(tree: TreeShake): this;
571
572
  writeTypeSchemas(target: string): this;
572
573
  generate(): Promise<GenerationResult>;
573
- /**
574
- * Generate and return the results without writing to files
575
- */
576
- build(): Promise<{
577
- typescript?: {
578
- content: string;
579
- filename: string;
580
- }[];
581
- }>;
582
574
  /**
583
575
  * Clear all configuration and start fresh
584
576
  */