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