@atomic-ehr/codegen 0.0.18 → 0.0.19-canary.20260917110212.f40edba
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -0
- package/assets/api/writer-generator/python/profile_helpers.py +29 -1
- package/assets/api/writer-generator/typescript/profile-helpers.ts +66 -4
- package/dist/cli/index.js +21 -10
- package/dist/index.d.ts +108 -14
- package/dist/index.js +1352 -608
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/cli/index.js
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import F from'picocolors';import $n from'yargs';import {hideBin}from'yargs/helpers';import {mkdir,writeFile}from'fs/promises';import {dirname}from'path';import we from'assert';import {createHash}from'crypto';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as Ie from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';var se=e=>{console.log(),console.log(F.cyan(F.bold(`\u2501\u2501\u2501 ${e} \u2501\u2501\u2501`)));},ae=(e,n,i)=>{let t=e;if(n&&(t+=` ${F.gray(`(${n}ms)`)}`),console.log(`${F.green("")} ${t}`),i)for(let[r,o]of Object.entries(i))console.log(F.gray(` ${r}: ${o}`));},T=(e,n="\u2022")=>{for(let i of e)console.log(F.gray(` ${n} ${i}`));};var ce={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4};function I(e={}){let n=e.prefix??"",i=new Set(e.suppressTags??[]),t={},r=[],o=new Set,s=e.level??"INFO",a=d=>ce[d]>=ce[s],c={DEBUG:d=>d,INFO:d=>d,WARN:F.yellow,ERROR:F.red,SILENT:d=>d},l=(d,u,f,y)=>{let h=n?`${n}: `:"",S=y?` ${F.dim(`(${y})`)}`:"";return c[d](`${u} ${h}${f}`)+S},p=(d,u,f,y=false)=>{r.push({level:d,tag:f,message:u,suppressed:y,prefix:n,timestamp:Date.now()});},m=(d,u,f,y=false)=>(...h)=>{let S=h.length===2?h[0]:void 0,x=h.length===2?h[1]:h[0];S&&(t[S]=(t[S]??0)+1);let C=S!==void 0&&i.has(S);if(p(d,x,S,C),!C&&a(d)){if(y){let N=`${d}::${S??""}::${x}`;if(o.has(N))return;o.add(N);}f(l(d,u,x,S));}},g={warn:m("WARN","!",console.warn),dryWarn:m("WARN","!",console.warn,true),info:m("INFO","i",console.log),error:m("ERROR","X",console.error),debug:m("DEBUG","D",console.log),fork(d,u){let f=n?`${n}/${d}`:d,y=[...i,...u?.suppressTags??[]];return I({prefix:f,suppressTags:y,level:u?.level??s})},as(){return g},tagCounts(){return t},printTagSummary(){let d=Object.entries(t);if(d.length===0)return;let u=n?`${n}: `:"",f=d.filter(([h])=>!i.has(h)),y=d.filter(([h])=>i.has(h));if(f.length>0){let h=f.reduce((x,[,C])=>x+C,0),S=f.map(([x,C])=>`${x}: ${C}`).join(", ");console.warn(F.yellow(`! ${u}${h} warnings (${S})`));}if(y.length>0){let h=y.reduce((x,[,C])=>x+C,0),S=y.map(([x,C])=>`${x}: ${C}`).join(", ");console.log(F.dim(`i ${u}${h} suppressed (${S})`));}},buffer(){return r},bufferClear(){r.length=0;}};return g}var L=(e,n)=>e<n?-1:e>n?1:0,z=(e,n)=>L(e.sourcePackage,n.sourcePackage)||L(e.sourceCanonical,n.sourceCanonical),le=e=>JSON.stringify([...e].sort(z).map(({sourcePackage:n,sourceCanonical:i})=>[n,i])),pe=(e,n)=>n.sources.length-e.sources.length||L(le(e.sources),le(n.sources))||L(e.schemaHash,n.schemaHash);var b="Use CodeableReference which is not provided by FHIR R4.",_e="Use Availability which is not provided by FHIR R4.",q={"hl7.fhir.uv.extensions.r4":{"http://hl7.org/fhir/StructureDefinition/biologicallyderivedproduct-manipulation":b,"http://hl7.org/fhir/StructureDefinition/biologicallyderivedproduct-processing":b,"http://hl7.org/fhir/StructureDefinition/extended-contact-availability":_e,"http://hl7.org/fhir/StructureDefinition/immunization-procedure":b,"http://hl7.org/fhir/StructureDefinition/specimen-additive":b,"http://hl7.org/fhir/StructureDefinition/workflow-barrier":b,"http://hl7.org/fhir/StructureDefinition/workflow-protectiveFactor":b,"http://hl7.org/fhir/StructureDefinition/workflow-reason":b},"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.","http://hl7.org/fhir/StructureDefinition/publishablecodesystem":"Uses R5-only base types not available in R4 generation."}};function v(e,n){let i=`${e.name}#${e.version}`,t=q[i]?.[n];if(t)return {shouldSkip:true,reason:t};let r=q[e.name]?.[n];return r?{shouldSkip:true,reason:r}:{shouldSkip:false}}var R=e=>`${e.name}#${e.version}`,de=e=>`${e.name}@${e.version}`,me=e=>{let n=JSON.stringify(e);return createHash("sha256").update(n).digest("hex").slice(0,16)},ue=(e,n)=>{let i=e.derivation==="constraint"?"constraint":"specialization";return {...e,derivation:i,kind:e.kind,package_meta:e.package_meta||n,name:e.name,url:e.url,base:e.base}};var W=e=>e?.kind==="nested",fe=e=>e?.kind==="profile";var E=(...e)=>{let n=e.filter(t=>t!==void 0).flatMap(t=>t.map(r=>[r.url,r]));return n.length===0?void 0:Object.values(Object.fromEntries(n)).sort((t,r)=>t.url.localeCompare(r.url))};var ge=e=>[...e.valueFieldTypes??[],...e.profile?[e.profile]:[],...e.subExtensions?.flatMap(n=>n.valueFieldType?[n.valueFieldType]:[])??[]];var ye=(e,n)=>{if(!e.url)throw new Error("ValueSet must have a URL");if(!e.name)throw new Error("ValueSet must have a name");return {...e,package_meta:e.package_meta||n,name:e.name,url:e.url}};function K(e){let n=e.split("|")[0];return n||e}function Ge(e){return e.split("|")[1]}var ze=e=>({package:e.package_meta.name,version:e.package_meta.version,name:e.name,url:e.url});function k(e){let n=ze(e);return e.derivation==="constraint"?{kind:"profile",...n}:e.kind==="primitive-type"?{kind:"primitive-type",...n}:e.kind==="complex-type"?{kind:"complex-type",...n}:e.kind==="resource"?{kind:"resource",...n}:e.kind==="logical"?{kind:"logical",...n}:{kind:"resource",...n}}var qe=/[-_]/,We=/^[a-zA-Z0-9_-]{20,}$/,Ke=e=>{let n=e.split("/"),i=n[n.length-1];return i&&i.length>0?i.split(qe).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(""):e};function H(e,n,i){let t=K(i),r=Ke(t),o={package_meta:{name:"missing_valuesets",version:Ge(t)||"0.0.0"},id:i},s=e.resolveVs(n,t)||o,a=s?.id&&!We.test(s.id)?s.id:r;return {kind:"value-set",package:s.package_meta.name,version:s.package_meta.version,name:a,url:t}}function w(e,n,i){let t=i.binding?.bindingName,r=n.join("."),[o,s,a]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[e.package_meta,`${e.name}.${r}_binding`,`${e.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:s,url:a}}function Y(e,n,i,t){let r=K(i)||i,o=e.resolveVs(n,r);if(o)return Je(e,o)}function Je(e,n,i){if(n.expansion?.contains)return n.expansion.contains.filter(r=>r.code!==void 0).map(r=>(we(r.code),{code:r.code,display:r.display,system:r.system}));let t=[];if(n.compose?.include){for(let r of n.compose.include)if(r.concept)for(let o of r.concept)t.push({system:r.system,code:o.code,display:o.display});else if(r.system&&!r.filter)try{let o=e.resolveAny(r.system);if(o?.concept){let s=(a,c)=>{for(let l of a)t.push({system:c,code:l.code,display:l.display}),l.concept&&s(l.concept,c);};s(o.concept,r.system);}}catch{}}return t.length>0?t:void 0}var he=100,Ze=new Set(["UNK"]),J=new Set(["code","Coding","CodeableConcept","CodeableReference","Quantity","string","uri","Duration"]);function Z(e,n,i,t){if(!i.binding)return;let r=i.binding.strength,o=i.binding.valueSet;if(!o)return;if(!J.has(i.type??"")){t?.dryWarn("#binding",`eld-11: Binding on non-bindable type '${i.type}' (valueSet: ${o})`);return}if(!(r==="required"||r==="extensible"||r==="preferred"))return;let a=Y(e,n.package_meta,o);if(!a||a.length===0)return;let c=a.map(p=>p.code).filter(p=>p&&typeof p=="string"&&p.trim().length>0),l=c.length===1?c[0]:void 0;if(l&&Ze.has(l)){t?.dryWarn("#placeholderValueSet",`Value set ${o} only expands to placeholder code '${l}'; skipping enum generation.`);return}if(c.length>he){t?.dryWarn("#largeValueSet",`Value set ${o} has ${c.length} which is more than ${he} codes, which may cause issues with code generation.`);return}if(c.length!==0)return {isOpen:r!=="required",values:c}}function Qe(e,n,i,t,r){if(!t.binding?.valueSet)return;let o=w(n,i,t),s=H(e,n.package_meta,t.binding.valueSet),a=Z(e,n,t,r);return {identifier:o,valueset:s,strength:t.binding.strength,enum:a,dependencies:[s]}}function Se(e,n,i){let t=new Set;if(!n.elements)return [];let r=[];function o(c,l){for(let[p,m]of Object.entries(c)){let g=[...l,p],d=g.join("."),u=e.resolveElementSnapshot(n,g);if(!t.has(d)){if(t.add(d),u.binding){let f=Qe(e,n,g,u,i);f&&r.push(f);}m.elements&&o(m.elements,g);}}}o(n.elements,[]),r.sort((c,l)=>c.identifier.name.localeCompare(l.identifier.name));let s=[],a=new Set;for(let c of r)a.has(c.identifier.url)||(a.add(c.identifier.url),s.push(c));return s}var Xe=/(?<=[a-z])(?=[A-Z])|[-_.\s]/,en=e=>e.split(Xe).filter(Boolean);var nn=e=>{if(e.length===0)throw new Error("Empty string");return e[0]?.toUpperCase()+e.substring(1).toLowerCase()},Re=e=>{if(e.length===0)throw new Error("Empty string");let[n,...i]=en(e);return [n?.toLowerCase(),...i.map(nn)].join("")};var Q=e=>!e||e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1);var tn=e=>{let n=e.replace(/\[x\]/g,"").replace(/[- :.]/g,"_");return n?Q(n):""},U=e=>{let n=e.replace(/\[x\]/g,"").replace(/:/g,"_");return n?Q(Re(n)):""},rn=(e,n)=>{let i=U(e)||"Extension",t=n.split(".").filter(s=>s&&s!=="extension").join("_"),o=`${t?U(t):""}${i}`;return [i,o,`${o}Extension`]},on=(e,n)=>{let i=tn(n)||"Slice",r=`${U(e)||"Field"}${i}`;return [i,r,`${r}Slice`]},sn=(e,n,i)=>e.reduce((t,r)=>{let o=r.candidates[n]??"";return t[o]=(t[o]??0)+1,i.has(o)&&(t[o]=(t[o]??0)+1),t},{}),an=(e,n)=>{let i=e[0]?.candidates.length??0,t=(r,o)=>{if(r.length===0||o>=i)return {};let s=sn(r,o,n),a=o>=i-1,[c,l]=r.reduce(([p,m],g)=>{let d=g.candidates[o]??"";return (s[d]??0)>1&&!a?[p,[...m,g]]:[{...p,[g.key]:d},m]},[{},[]]);return {...c,...t(l,o+1)}};return t(e,0)},xe=e=>({candidates:rn(e.name,e.path),recommended:""}),Ce=(e,n)=>({candidates:on(e,n),recommended:""}),ke=e=>{let n=(e.extensions??[]).filter(s=>s.url).map(s=>({key:`ext:${s.url}:${s.path}`,candidates:s.nameCandidates.candidates})),i=Object.entries(e.slicing??{}).flatMap(([s,a])=>a.slices?Object.entries(a.slices).map(([c,l])=>({key:`slice:${s}:${c}`,candidates:l.nameCandidates.candidates})):[]),t=new Set(Object.keys(e.fields??{}).map(U)),r=[...n,...i];if(r.length===0)return;let o=an(r,t);for(let s of e.extensions??[]){if(!s.url)continue;let a=`ext:${s.url}:${s.path}`;o[a]&&(s.nameCandidates.recommended=o[a]);}for(let[s,a]of Object.entries(e.slicing??{}))if(a.slices)for(let[c,l]of Object.entries(a.slices)){let p=`slice:${s}:${c}`;o[p]&&(l.nameCandidates.recommended=o[p]);}};var X=e=>e!==null&&typeof e=="object"&&e.resourceType==="CodeSystem";var $=e=>e!==null&&typeof e=="object"&&e.resourceType==="ValueSet";var ln=/^[a-zA-Z0-9]+$/,pn=async(e,n)=>{let i=await e.packageJson(n.name);if(!i)return [];let t=i.dependencies;return t!==void 0?Object.entries(t).map(([r,o])=>({name:r,version:o})):[]},be=e=>({pkg:e,canonicalResolution:{},fhirSchemas:{},valueSets:{}}),Fe=async(e,n,i,t,r)=>{let o=R(n);if(r?.info(`${" ".repeat(i*2)}+ ${o}`),t[o])return t[o];let s=be(n);t[o]=s;for(let c of await e.search({package:n})){let l=c.url;if(!l||!(isStructureDefinition(c)||$(c)||X(c)))continue;let p=l;s.canonicalResolution[p]&&r?.dryWarn("#duplicateCanonical",`Duplicate canonical URL: ${p} at ${o}.`),s.canonicalResolution[p]=[{deep:i,pkg:n,pkgId:o,resource:c}];}let a=await pn(e,n);for(let c of a){let{canonicalResolution:l}=await Fe(e,c,i+1,t,r);for(let[p,m]of Object.entries(l)){let g=p;s.canonicalResolution[g]=[...s.canonicalResolution[g]||[],...m];}}for(let c of Object.values(s.canonicalResolution))c.sort((l,p)=>l.deep-p.deep);return s},dn=(e,n)=>{for(let{pkg:i,canonicalResolution:t}of Object.values(e)){let r=R(i);if(!e[r])throw new Error(`Package ${r} not found`);let o=0;n?.info(`FHIR Schema conversion for '${R(i)}' begins...`);for(let[s,a]of Object.entries(t)){let c=a[0];if(!c)throw new Error("Resource not found");let l=c.resource,p=c.pkg;if(isStructureDefinition(l)){let m=Ie.translate(l),g=ue(m,p);o++,e[r].fhirSchemas[g.url]=g;}if($(l)){let m=ye(l,p);e[r].valueSets[m.url]=m;}}n?.info(`FHIR Schema conversion for '${R(i)}' completed: ${o} successful`);}},mn=(e,n,i)=>{let t=Object.values(e).flatMap(r=>r.canonicalResolution[n]);if(!t)throw new Error(`No canonical resolution found for ${n} in any package`);return t[0]?.resource},un=async(e,{logger:n,focusedPackages:i})=>{let t=i??await e.packages(),r={};for(let d of t)await Fe(e,d,0,r,n);dn(r,n);let o=(d,u)=>{let f=r[R(d)];if(f){let y=f.canonicalResolution[u]?.[0];if(y)return r[y.pkgId]?.fhirSchemas[u]}for(let y of Object.values(r)){let h=y.fhirSchemas[u];if(h&&h.package_meta.name===d.name)return h}for(let y of Object.values(r)){let h=y.fhirSchemas[u];if(h)return h}},s=(d,u)=>{let f=r[R(d)];if(f){let y=f.canonicalResolution[u]?.[0];if(y)return r[y.pkgId]?.valueSets[u]}for(let y of Object.values(r)){let h=y.valueSets[u];if(h&&h.package_meta.name===d.name)return h}for(let y of Object.values(r)){let h=y.valueSets[u];if(h)return h}},a=d=>(d.includes("|")&&(d=d.split("|")[0]),ln.test(d)?`http://hl7.org/fhir/StructureDefinition/${d}`:d),c=(d,u)=>{let f=o(d,u);if(f===void 0)throw new Error(`Failed to resolve FHIR Schema: '${u}'`);let y=[f];for(;f?.base;){let h=f.package_meta,S=a(f.base);if(f=o(h,S),f===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${u}'. Problem: '${S}' from '${R(h)}'`);y.push(f);}return y},l=(d,u)=>c(d,u).filter(f=>f.derivation==="specialization"),p=(d,u)=>{let f=c(d.package_meta,d.url),y=O(f,u);return ee(y)},m=d=>{let u=new Set;for(let[f,y]of Object.entries(d)){u.add(f);for(let h of y?.choices||[])d[h]||u.add(h);}return Array.from(u)},g;return {testAppendFs(d){let u=R(d.package_meta);r[u]||(r[u]=be(d.package_meta)),r[u].fhirSchemas[d.url]=d,g=void 0;},resolveFs:o,resolveFsGenealogy:c,resolveFsSpecializations:l,ensureSpecializationCanonicalUrl:a,resolveSd:(d,u)=>{let f=r[R(d)]?.canonicalResolution[u]?.[0]?.resource;if(isStructureDefinition(f))return f},allSd:()=>Object.values(r).flatMap(d=>Object.values(d.canonicalResolution).flatMap(u=>u.map(f=>{let y=f.resource;return y.package_name?y:{...y,package_name:f.pkg.name,package_version:f.pkg.version}}))).filter(d=>isStructureDefinition(d)).sort((d,u)=>d.url.localeCompare(u.url)),allFs:()=>Object.values(r).flatMap(d=>Object.values(d.fhirSchemas)),allVs:()=>Object.values(r).flatMap(d=>Object.values(d.valueSets)),resolveVs:s,resolveAny:d=>mn(r,d),resolveElementSnapshot:p,getAllElementKeys:m,resolver:r,resolutionTree:()=>{if(g)return g;let d={};for(let[u,f]of Object.entries(r)){let y=f.pkg.name;d[y]={};for(let[h,S]of Object.entries(f.canonicalResolution)){let x=h;d[y][x]=[];for(let C of S)d[y][x].push({deep:C.deep,pkg:C.pkg});}}return g=d,d}}},Te=async(e,n)=>{let i=e.map(de);n?.logger?.info(`Loading FHIR packages: ${i.join(", ")}`);let t=CanonicalManager({packages:i,workingDir:".codegen-cache/canonical-manager-cache",registry:n.registry||void 0});return await t.init(),await un(t,{...n,focusedPackages:e})},O=(e,n)=>{let[i,...t]=n;return i===void 0?[]:e.map(r=>{if(!r.elements)return;let o=r.elements?.[i];for(let s of t)o=o?.elements?.[s];return o}).filter(r=>r!==void 0)};function ee(e){let n=e.reverse(),i=Object.assign({},...n);return i.elements=void 0,i}var ve=(e,n,i)=>{let t=e.resolveFsSpecializations(n.package_meta,n.url),r=O(t,i),o=ee(r).type,s;if(o){let a=e.ensureSpecializationCanonicalUrl(o),l=e.resolveFsGenealogy(n.package_meta,a).flatMap(p=>Object.keys(p.elements??{}));l.length>0&&(s=new Set(l));}for(let a of r)if(!(!a.elements||Object.keys(a.elements).length===0)&&!(s&&!Object.keys(a.elements).some(c=>!s.has(c))))return true;return false},ne=(e,n,i,t,r)=>t.type==="BackboneElement"?true:!r?.elements||r.choiceOf!==void 0?false:ve(e,n,i),fn=e=>e.elements?new Set(te(e,[],e.elements).filter(([n,i])=>i.elements&&Object.keys(i.elements).length>0).map(([n])=>n.join("."))):new Set;function B(e,n,i){let t={},r=n.derivation==="constraint"?e.resolveFsSpecializations(n.package_meta,n.url):e.resolveFsGenealogy(n.package_meta,n.url);for(let p of [...r].reverse()){let m=fn(p);for(let g of m)t[g]=`${p.url}#${g}`;}let o=i.join("."),s=t[o]??`${n.url}#${o}`,a=s.split("#")[0],l=e.resolveFs(n.package_meta,a)?.package_meta??n.package_meta;return {kind:"nested",package:l.name,version:l.version,name:o,url:s}}function te(e,n,i){let t=[];for(let[r,o]of Object.entries(i)){let s=[...n,r];o.elements&&o.choiceOf===void 0&&t.push([s,o]),o.elements&&t.push(...te(e,s,o.elements));}return t}function gn(e,n,i,t,r){let o={},s={},a=e.resolveFsGenealogy(n.package_meta,n.url),c=O(a,i),l=new Set;for(let p of c)if(p.elements)for(let m of Object.keys(p.elements))l.add(m);for(let p of l){let m=[...i,p],g=e.resolveElementSnapshot(n,m);ne(e,n,m,g,t[p])?o[p]=_(e,n,m,g):o[p]=j(e,n,m,g,r);let d=M(p,g);d&&(s[p]=d);}return {fields:o,slicing:Object.keys(s).length>0?s:void 0}}function Ee(e,n,i){if(!n.elements)return;let t=te(n,[],n.elements).filter(([o,s])=>!s.elements||Object.keys(s.elements).length===0?false:s.type!=="BackboneElement"?ve(e,n,o):true),r=[];for(let[o,s]of t){let a=B(e,n,o),c;s.type==="BackboneElement"||!s.type?c="BackboneElement":c=s.type;let l=e.ensureSpecializationCanonicalUrl(c),p=e.resolveFs(n.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${c}`);let m={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:c,url:l},{fields:g,slicing:d}=gn(e,n,o,s.elements??{},i),u={identifier:a,base:m,fields:g,slicing:d};r.push(u);}return r.sort((o,s)=>o.identifier.url.localeCompare(s.identifier.url)),r.length===0?void 0:r}function Pe(e){let n=[];for(let i of e){i.base&&n.push(i.base);for(let t of Object.values(i.fields||{}))"type"in t&&t.type&&n.push(t.type),"binding"in t&&t.binding&&n.push(t.binding);}return n}var yn=new Set(["Availability","CodeableReference","ExtendedContactDetail","MonetaryComponent","RatioRange","VirtualServiceDetail"]),hn=(e,n)=>{let i=e.resolver[R(n)];if(!i)return false;for(let t of Object.values(i.canonicalResolution))for(let r of t)if(r.pkg.name==="hl7.fhir.r4.core")return true;return false},Sn=(e,n,i)=>!yn.has(i)||!hn(e,n)?"":`
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import Me from'picocolors';import Hc from'yargs';import {hideBin}from'yargs/helpers';import*as Ct from'fs/promises';import {mkdir,writeFile,readFile}from'fs/promises';import*as w from'path';import w__default,{dirname}from'path';import xe from'assert';import*as U from'fs';import U__default,{existsSync}from'fs';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import {excludeCanonical}from'@atomic-ehr/fhir-canonical-manager/patch';import {createHash}from'crypto';import {fileURLToPath}from'url';import*as vi from'yaml';import vi__default from'yaml';import*as Ji from'@atomic-ehr/fhirschema';import {isStructureDefinition}from'@atomic-ehr/fhirschema';import {spawn}from'child_process';import*as kr from'util';import ba from'mustache';var ci=e=>{console.log(),console.log(Me.cyan(Me.bold(`\u2501\u2501\u2501 ${e} \u2501\u2501\u2501`)));},St=(e,t,n)=>{let i=e;if(t&&(i+=` ${Me.gray(`(${t}ms)`)}`),console.log(`${Me.green("")} ${i}`),n)for(let[r,o]of Object.entries(n))console.log(Me.gray(` ${r}: ${o}`));},be=(e,t="\u2022")=>{for(let n of e)console.log(Me.gray(` ${t} ${n}`));};var li={DEBUG:0,INFO:1,WARN:2,ERROR:3,SILENT:4};function Q(e={}){let t=e.prefix??"",n=new Set(e.suppressTags??[]),i={},r=[],o=new Set,s=e.level??"INFO",a=f=>li[f]>=li[s],c={DEBUG:f=>f,INFO:f=>f,WARN:Me.yellow,ERROR:Me.red,SILENT:f=>f},l=(f,m,g,y)=>{let h=t?`${t}: `:"",x=y?` ${Me.dim(`(${y})`)}`:"";return c[f](`${m} ${h}${g}`)+x},p=(f,m,g,y=false)=>{r.push({level:f,tag:g,message:m,suppressed:y,prefix:t,timestamp:Date.now()});},d=(f,m,g,y=false)=>(...h)=>{let x=h.length===2?h[0]:void 0,k=h.length===2?h[1]:h[0];x&&(i[x]=(i[x]??0)+1);let $=x!==void 0&&n.has(x);if(p(f,k,x,$),!$&&a(f)){if(y){let q=`${f}::${x??""}::${k}`;if(o.has(q))return;o.add(q);}g(l(f,m,k,x));}},u={warn:d("WARN","!",console.warn),dryWarn:d("WARN","!",console.warn,true),info:d("INFO","i",console.log),error:d("ERROR","X",console.error),debug:d("DEBUG","D",console.log),fork(f,m){let g=t?`${t}/${f}`:f,y=[...n,...m?.suppressTags??[]];return Q({prefix:g,suppressTags:y,level:m?.level??s})},as(){return u},tagCounts(){return i},printTagSummary(){let f=Object.entries(i);if(f.length===0)return;let m=t?`${t}: `:"",g=f.filter(([h])=>!n.has(h)),y=f.filter(([h])=>n.has(h));if(g.length>0){let h=g.reduce((k,[,$])=>k+$,0),x=g.map(([k,$])=>`${k}: ${$}`).join(", ");console.warn(Me.yellow(`! ${m}${h} warnings (${x})`));}if(y.length>0){let h=y.reduce((k,[,$])=>k+$,0),x=y.map(([k,$])=>`${k}: ${$}`).join(", ");console.log(Me.dim(`i ${m}${h} suppressed (${x})`));}},buffer(){return r},bufferClear(){r.length=0;}};return u}var pi=(e={})=>Q(e);var di={version:"0.0.19"};var Fe="Use CodeableReference which is not provided by FHIR R4.",po="Use Availability which is not provided by FHIR R4.",fo=[["biologicallyderivedproduct-manipulation",Fe],["biologicallyderivedproduct-processing",Fe],["extended-contact-availability",po],["immunization-procedure",Fe],["specimen-additive",Fe],["workflow-barrier",Fe],["workflow-protectiveFactor",Fe],["workflow-reason",Fe]],fi={indexEntry:[...fo.map(([e,t])=>excludeCanonical({package:"hl7.fhir.uv.extensions.r4",url:`http://hl7.org/fhir/StructureDefinition/${e}`,reason:t})),excludeCanonical({package:{name:"hl7.fhir.r5.core",version:"5.0.0"},url:"http://hl7.org/fhir/StructureDefinition/shareablecodesystem",reason:"FIXME: CodeSystem.concept.concept defined by ElementReference. FHIR Schema generator output broken value in it, so we just skip it for now."}),excludeCanonical({package:{name:"hl7.fhir.r5.core",version:"5.0.0"},url:"http://hl7.org/fhir/StructureDefinition/publishablecodesystem",reason:"Uses R5-only base types not available in R4 generation."})]};var uo=/(?<=[a-z])(?=[A-Z])|[-_.\s]/,Tt=e=>e.split(uo).filter(Boolean),xt=e=>Tt(e).map(t=>t.toLowerCase()).join("-"),ui=e=>{if(e.length===0)throw new Error("Empty string");return e[0]?.toUpperCase()+e.substring(1).toLowerCase()},de=e=>{if(e.length===0)throw new Error("Empty string");let[t,...n]=Tt(e);return [t?.toLowerCase(),...n.map(ui)].join("")},z=e=>Tt(e).map(ui).join(""),P=e=>Tt(e).map(t=>t.toLowerCase()).join("_"),R=e=>!e||e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1),De=e=>e.map(t=>R(t));var ye=class{opts;currentDir;currentFile;writtenFilesBuffer={};constructor(t){this.opts=t;}setOutputDir(t){if(this.currentDir)throw new Error("Can't change output dir while writing");this.opts.outputDir=t;}logger(){return this.opts.logger}onDiskMkDir(t){this.opts.inMemoryOnly||U.existsSync(t)||U.mkdirSync(t,{recursive:true});}onDiskOpenFile(t){return this.opts.inMemoryOnly?-1:U.openSync(t,"w")}onDiskCloseFile(t){this.opts.inMemoryOnly||(U.fsyncSync(t),U.closeSync(t));}onDiskWrite(t,n){this.opts.inMemoryOnly||U.writeSync(t,n);}cd(t,n){let i=this.currentDir;this.currentDir=t.startsWith("/")?w.join(this.opts.outputDir,t):w.join(this.currentDir??this.opts.outputDir,t),this.onDiskMkDir(this.currentDir),this.logger()?.debug(`cd '${this.currentDir}'`),n(),this.currentDir=i;}cat(t,n){if(!this.currentDir)throw new Error("Should be in a directory (`cd`)");if(this.currentFile)throw new Error("Can't open file when another file is open");if(t.includes("/"))throw new Error(`Change file path separatly: ${t}`);let i=w.normalize(`${this.currentDir}/${t}`);this.writtenFilesBuffer[i]&&(this.logger()?.warn(`File will be rewritten '${i}'`),this.logger()?.debug(`File content: ${this.writtenFilesBuffer[i].tokens.join("")}`));try{let r=this.onDiskOpenFile(i);this.logger()?.debug(`cat > '${i}'`),this.currentFile={descriptor:r,relPath:i},this.writtenFilesBuffer[this.currentFile.relPath]={relPath:i,absPath:w.resolve(i),tokens:[]},n();}finally{this.currentFile&&this.onDiskCloseFile(this.currentFile.descriptor),this.currentFile=void 0;}}write(t){if(!this.currentFile)throw new Error("No file opened");this.onDiskWrite(this.currentFile.descriptor,t);let n=this.writtenFilesBuffer[this.currentFile.relPath];if(!n)throw new Error("No buffer found");n.tokens.push(t);}copyAssets(t,n){n=w.normalize(`${this.currentDir??this.opts.outputDir}/${n}`);let i=U.readFileSync(t,"utf8");this.writtenFilesBuffer[n]={relPath:n,absPath:w.resolve(n),tokens:[i]},this.opts.inMemoryOnly||U.cpSync(t,n);}cp(t,n){if(!this.opts.resolveAssets)throw new Error("resolveAssets is not defined");t=w.resolve(this.opts.resolveAssets(t)),n=w.normalize(`${this.currentDir??this.opts.outputDir}/${n}`);let i=U.readFileSync(t,"utf8");this.writtenFilesBuffer[n]={relPath:n,absPath:w.resolve(n),tokens:[i]},this.opts.inMemoryOnly||U.cpSync(t,n);}writtenFiles(){return Object.values(this.writtenFilesBuffer).map(({relPath:t,absPath:n,tokens:i})=>({relPath:t,absPath:n,content:i.join("")})).sort((t,n)=>t.relPath.localeCompare(n.relPath))}async flushAsync(){if(this.opts.inMemoryOnly)return;let t=this.writtenFiles(),n=new Set;for(let i of t)n.add(w.dirname(i.absPath));await Promise.all(Array.from(n).map(i=>Ct.mkdir(i,{recursive:true}))),await Promise.all(t.map(i=>Ct.writeFile(i.absPath,i.content)));}async generateAsync(t){let n=this.opts.inMemoryOnly;this.opts.inMemoryOnly=true;try{await this.generate(t);}finally{this.opts.inMemoryOnly=n;}await this.flushAsync();}},ve=class extends ye{currentIndent=0;indent(){this.currentIndent+=this.opts.tabSize;}deindent(){this.currentIndent-=this.opts.tabSize;}writeIndent(){this.write(" ".repeat(this.currentIndent));}line(...t){t.length===0?this.write(`
|
|
3
|
+
`):(this.writeIndent(),this.write(`${t.join(" ")}
|
|
4
|
+
`));}lineSM(...t){this.writeIndent(),this.write(`${t.join(" ")};
|
|
5
|
+
`);}comment(...t){let n=t.join(" ").split(`
|
|
6
|
+
`);for(let i of n)this.line(this.opts.commentLinePrefix,i);}debugComment(...t){this.opts.withDebugComment&&(t=t.map(n=>typeof n=="string"?n:JSON.stringify(n,null,2)),this.comment(...t));}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(t=>{this.comment(t);}),this.line();}indentBlock(t){this.indent(),t(),this.deindent();}curlyBlock(t,n,i){this.line(`${t.filter(Boolean).join(" ")} {`),this.indent(),n(),this.deindent(),this.line(`}${i?.filter(Boolean).join(" ")??""}`);}squareBlock(t,n,i){this.line(`${t.filter(Boolean).join(" ")} [`),this.indent(),n(),this.deindent(),this.line(`]${i?.filter(Boolean).join(" ")??""}`);}};var go=/^\d/,se=(e,t=true)=>{let n=e.split("/").pop();if(n&&(t&&n.includes("#")&&(n=n.split("#")[0]),!!n))return go.test(n)&&(n=`number_${n}`),n},Be=e=>({name:e.identifier.package,version:e.identifier.version}),O=e=>`${e.name}#${e.version}`,H=e=>`${e.name}@${e.version}`,kt=e=>{let t=JSON.stringify(e);return createHash("sha256").update(t).digest("hex").slice(0,16)},mi=(e,t)=>{let n=e.derivation==="constraint"?"constraint":"specialization";return {...e,derivation:n,kind:e.kind,package_meta:e.package_meta||t,name:e.name,url:e.url,base:e.base}},oe=e=>e?.kind==="resource";var bt=e=>e?.kind==="complex-type",M=e=>e?.kind==="primitive-type",L=e=>e?.kind==="nested",vt=e=>e?.kind==="profile",et=e=>e?.kind==="profile-snapshot",Rt=e=>({...e,kind:"profile-snapshot"});var fe=(...e)=>{let t=e.filter(i=>i!==void 0).flatMap(i=>i.map(r=>[r.url,r]));return t.length===0?void 0:Object.values(Object.fromEntries(t)).sort((i,r)=>i.url.localeCompare(r.url))},he=e=>e!==void 0&&L(e.identifier),_=e=>e?.identifier.kind==="resource"||e?.identifier.kind==="complex-type"||e?.identifier.kind==="logical",It=e=>e?.identifier.kind==="complex-type",ee=e=>e?.identifier.kind==="resource",$t=e=>e?.identifier.kind==="primitive-type",je=e=>e?.identifier.kind==="logical",V=e=>e?.identifier.kind==="profile",gi=e=>e?.identifier.kind==="binding",Ft=e=>e?.identifier.kind==="value-set",te=e=>e?.identifier.kind==="profile-snapshot",Pe=e=>e?.discriminator?.some(t=>t.type==="type")??false,Pt=e=>[...e.valueFieldTypes??[],...e.profile?[e.profile]:[],...e.subExtensions?.flatMap(t=>t.valueFieldType?[t.valueFieldType]:[])??[]],j=e=>e?e.choices===void 0:false,b=e=>e?e.choices!==void 0:false,A=e=>e?e.choiceOf!==void 0:false,yi=(e,t)=>{if(!e.url)throw new Error("ValueSet must have a URL");if(!e.name)throw new Error("ValueSet must have a name");return {...e,package_meta:e.package_meta||t,name:e.name,url:e.url}};var So=["assets","api","writer-generator"],To=12,Le=(e,t,n)=>{let i=[],r=w.dirname(fileURLToPath(e));for(let o=0;o<To;o++){let s=w.resolve(r,...So,t,n);if(i.push(s),existsSync(s))return s;let a=w.dirname(r);if(a===r)break;r=a;}throw new Error(`Cannot locate generator asset ${t}/${n}. Looked in:
|
|
7
|
+
${i.join(`
|
|
8
|
+
`)}`)};var hi={"!":"Not","<=":"LessOrEqual",">=":"GreaterOrEqual","<":"Less",">":"Greater","=":"Equal","-":"Dash","+":"Plus","*":"Asterisk","/":"Slash","%":"Percent","&":"And","|":"Or","^":"Xor","~":"Tilde","?":"Question",".":"Dot"};function xo(e){return e.split("-").map(t=>R(t)).join("-")}function Co(e){let t=e;for(let n in hi)t=t.replaceAll(n,hi[n]??"");return t}function ko(e){let t=Number(e[0]);return Number.isInteger(t)&&!Number.isNaN(t)?`_${e}`:e}function Si(e){let t=xo(e);return t=ko(t),t=Co(t),t=R(t),t}function Se(e){return R(de(e.replaceAll(".","-")))}var Ti=e=>Le(import.meta.url,"csharp",e),Ro={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"},Io=["Reference","Expression"],$o=e=>e.required?["required"]:[],Fo=e=>{let t=Ci(xi(e.identifier));return R(t)},Po=e=>e.base?`: ${e.base.name}`:"",No=/^\d/,Eo=(e,t=true)=>{if(!e)return;let n=e.split("/").pop();if(n&&(t&&n.includes("#")&&(n=n.split("#")[0]),!!n))return No.test(n)&&(n=`number_${n}`),Se(n)},xi=e=>{if(e.kind==="nested"){let t=e.url,n=Eo(t,false);if(!n)return "";let[i,r]=n.split("#"),o=De((r??"").split(".")).join("");return Se([i,o].join(""))}return Se(e.name)},Oo=e=>Io.includes(e),Ci=e=>Oo(e)?`Resource${e}`:e,Nt=class extends ve{enums={};constructor(t){super({tabSize:4,withDebugComment:false,commentLinePrefix:"//",resolveAssets:t.resolveAssets??Ti,...t});}async generate(t){let n=t.collectComplexTypes(),i=t.collectResources(),r=Array.from(new Set(i.map(o=>Se(o.identifier.package))));this.generateAllFiles(n,i,r),this.copyStaticFiles();}generateAllFiles(t,n,i){this.generateUsingFile(i),this.generateBaseTypes(t),this.generateResources(n),this.generateEnumFiles(i),this.generateResourceDictionaries(n,i),this.generateHelperFile();}generateType(t,n){let i=Fo(t),r=Po(t);this.curlyBlock(["public","class",i,r],()=>{this.generateFields(t,n),this.generateNestedTypes(t,n),this.line(),this.includeHelperMethods();}),this.line();}generateFields(t,n){if(!t.fields)return;let i=Object.entries(t.fields).sort(([r],[o])=>r.localeCompare(o));for(let[r,o]of i)this.generateField(r,o,n);}generateNestedTypes(t,n){if(!(!("nested"in t)||!t.nested)){this.line();for(let i of t.nested)this.generateType(i,n);}}generateField(t,n,i){try{if(b(n))return;let r=this.buildFieldDeclaration(t,n,i);this.line(...r);}catch(r){this.logger()?.error(`Error processing field ${t}: ${r.message}`);}}buildFieldDeclaration(t,n,i){let r=this.determineFieldType(t,n,i),o=$o(n),s=z(t);return ["public",...o,r,s,"{ get; set; }"].filter(Boolean)}determineFieldType(t,n,i){let r=this.getBaseTypeName(n);"enum"in n&&n.enum&&!n.enum.isOpen&&(r=this.registerAndGetEnumType(t,n,i)),r=Ci(r);let o="",s=n.required?"":"?",a=n.array?"[]":"";return `${o}${r}${a}${s}`}getBaseTypeName(t){if("type"in t){let n=t.type.name.toString();return t.type.kind==="nested"?n=xi(t.type):t.type.kind==="primitive-type"&&(n=Ro[t.type.name]??"string"),n}return ""}registerAndGetEnumType(t,n,i){let o=`${Se(n.binding?.name??t)}Enum`;return this.enums[i]||(this.enums[i]={}),n.enum&&(this.enums[i][o]=n.enum.values),o}includeHelperMethods(){this.line("public override string ToString() => "),this.line(" JsonSerializer.Serialize(this, Helper.JsonSerializerOptions);"),this.line();}generateUsingFile(t){this.cd("/",async()=>{this.cat("Usings.cs",()=>{this.generateDisclaimer(),this.generateGlobalUsings(t);});});}generateGlobalUsings(t){let n=["CSharpSDK","System.Text.Json","System.Text.Json.Serialization",this.opts.rootNamespace,...t.map(i=>`${this.opts.rootNamespace}.${i}`)];for(let i of n)this.lineSM("global","using",i);}generateBaseTypes(t){this.cd("/",async()=>{this.cat("base.cs",()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",this.opts.rootNamespace);for(let n of t){let i=Se(n.identifier.package);this.generateType(n,i);}});});}generateResources(t){for(let n of t)this.generateResourceFile(n);}generateResourceFile(t){let n=Se(t.identifier.package);this.cd(`/${n}`,async()=>{this.cat(`${t.identifier.name}.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM("namespace",`${this.opts.rootNamespace}.${n}`),this.line(),this.generateType(t,n);});});}generateEnumFiles(t){for(let n of t)this.generatePackageEnums(n);}generatePackageEnums(t){let n=this.enums[t];!n||Object.keys(n).length===0||this.cd(`/${t}`,async()=>{this.cat(`${t}Enums.cs`,()=>{this.generateDisclaimer(),this.generateEnumFileContent(t,n);});});}generateEnumFileContent(t,n){this.lineSM("using","System.ComponentModel"),this.line(),this.lineSM(`namespace ${this.opts.rootNamespace}.${t}`);for(let[i,r]of Object.entries(n))this.generateEnum(i,r);}generateEnum(t,n){this.curlyBlock(["public","enum",t],()=>{for(let i of n)this.line(`[Description("${i}")]`),this.line(`${Si(i)},`);}),this.line();}generateResourceDictionaries(t,n){this.cd("/",async()=>{for(let i of n){let r=t.filter(o=>Se(o.identifier.package)===i);if(r.length===0)return;this.cat(`${i}ResourceDictionary.cs`,()=>{this.generateDisclaimer(),this.line(),this.lineSM(`namespace ${this.opts.rootNamespace}`),this.generateResourceDictionaryClass(i,r);});}});}generateResourceDictionaryClass(t,n){this.curlyBlock(["public","static","class","ResourceDictionary"],()=>{this.curlyBlock(["public static readonly Dictionary<Type, string> Map = new()"],()=>{for(let i of n){let r=i.identifier.name;this.line(`{ typeof(${t}.${r}), "${r}" },`);}}),this.lineSM();});}copyStaticFiles(){this.cp("Client.cs","Client.cs"),this.cp("Helper.cs","Helper.cs");}generateHelperFile(){if(this.opts.inMemoryOnly)return;let t=Ti("Helper.cs"),n=w__default.join(this.opts.outputDir,"Helper.cs");U__default.copyFileSync(t,n);}};var Ne={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"},Et=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"]),ki=e=>Et.has(e)?`${e}_`:e,vn=/^\d/,nt=(e,t=true)=>{if(!e)return;let n=e.split("/").pop();if(n&&(t&&n.includes("#")&&(n=n.split("#")[0]),!!n))return vn.test(n)&&(n=`number_${n}`),P(n)},Te=e=>{if(e.kind==="nested"){let t=e.url,n=nt(t,false);if(!n)return "";let[i,r]=n.split("#"),o=De((r??"").split(".")).join("");return z([i,o].join(""))}return z(e.name)},_o=e=>(e?[P(e)]:[""]).join("."),ae=(e,t)=>[e,_o(t)].join("."),bn=(e,t)=>ae(e,t.package),Ot=(e,t)=>t.kind==="complex-type"?`${bn(e,t)}.base`:t.kind==="resource"?[bn(e,t),P(t.name)].join("."):bn(e,t),Ee=e=>{if(M(e))return Ne[e.name]??"str";let t=Ne[e.name];return t!==void 0?t:Te(e)},it=(e,t)=>{if(!e.reference||e.reference.resource.length===0)return;let n=e.reference.resource.map(r=>t.findLastSpecializationByIdentifier(r));return n.some(t.isFamilyType)?void 0:`Literal[${[...new Set(n.map(r=>r.name))].map(r=>JSON.stringify(r)).join(", ")}]`};var Ae=e=>{let t={};for(let n of e){let i=n.identifier.package;t[i]||(t[i]=[]),t[i].push(n);}for(let[n,i]of Object.entries(t)){let r={};for(let s of i)r[JSON.stringify(s.identifier)]=s;let o=Object.values(r);o.sort((s,a)=>s.identifier.name.localeCompare(a.identifier.name)),t[n]=o;}return t},Mo=e=>{let t={};for(let i of e)t[i.identifier.name]=i;let n={};for(let i of e){let r=i.identifier.name,o=i.base?.name;n[r]||(n[r]=[]),o&&t[o]&&n[r].push(o);}return n},Do=e=>{let t=[],n={},i={},r=o=>{if(i[o])throw new Error(`Graph has cycles ${o}`);if(!n[o]){i[o]=true;for(let s of e[o]??[])r(s);i[o]=false,n[o]=true,t.push(o);}};for(let o in e)n[o]||r(o);return t},Ri=e=>{let t=Mo(e);return Do(t).map(i=>e.find(r=>r.identifier.name===i)).filter(Boolean)},Bo=e=>{let t={};for(let r of e){if(!_(r)||!r.base)continue;let o=r.base.url;t[o]||(t[o]=[]),t[o].push(r.identifier);}let n={},i=r=>{if(n[r])return n[r];let o=t[r]??[],s=[...o];for(let a of o)s.push(...i(a.url));return n[r]=s,s};for(let r of e){if(!_(r))continue;let o=i(r.identifier.url);if(o.length===0)continue;let s=o.filter(oe),a=o.filter(bt),c={};s.length>0&&(c.resources=s),a.length>0&&(c.complexTypes=a),Object.keys(c).length>0&&(r.typeFamily=c);}},jo=(e,t)=>{let n=[];for(let[i,r]of Object.entries(e.fields??{})){if(b(r)||!r.type)continue;let o=t(r.type);if(o){if(he(o)){let s=o.generic?.params;s?.length&&n.push({kind:"passthrough",fieldName:i,params:s});}else if(_(o)){let s=o.generic?.params;s?.length?n.push({kind:"passthrough",fieldName:i,params:s}):(o.typeFamily?.resources?.length??0)>0&&n.push({kind:"introduce",fieldName:i,constraint:r.type});}}}return n},Lo=(e,t)=>e.length===t.length&&e.every((n,i)=>n===t[i]),_t=e=>e[e.length-1]??"",Ao=e=>{let t=[];for(let n of e)if(n.kind==="introduce"){let i=[n.fieldName];t.find(r=>_t(r.path)===_t(i))||t.push({path:i,constraint:n.constraint});}else for(let i of n.params){let r=[n.fieldName,...i.path];t.find(o=>_t(o.path)===_t(r))||t.push({path:r,constraint:i.constraint});}return t.length===0?[]:t.map((n,i)=>({typeVar:t.length===1?"T":`T${i+1}`,constraint:n.constraint,path:n.path}))},Vo=(e,t)=>{let n=[];for(let s of e)if(_(s)){n.push(s);for(let a of s.nested??[])n.push(a);}else if(V(s))for(let a of s.nested??[])n.push(a);for(let s of n)s.generic=void 0;let i=(s,a)=>{if(s.length!==a.length)return false;for(let[c,l]of s.entries()){let p=a[c];if(!p||l.typeVar!==p.typeVar||!Lo(l.path,p.path)||l.constraint.url!==p.constraint.url)return false}return true},r=true,o=0;for(;r&&o++<=n.length;){r=false;for(let s of n){let a=Ao(jo(s,t)),c=s.generic?.params??[];i(c,a)||(s.generic=a.length>0?{params:a}:void 0,r=true);}}for(let s of e){if(!_(s))continue;let a=[],c=l=>{for(let p of l)L(p.constraint)||a.push(p.constraint);};s.generic&&c(s.generic.params);for(let l of s.nested??[])l.generic&&c(l.generic.params);a.length!==0&&(s.dependencies=fe(s.dependencies,a)??s.dependencies);}},Dt=(e,t)=>Object.entries(e).filter(n=>A(n[1])&&n[1].choiceOf===t),wo=(e,t,n,i)=>{let r=t[n],o=b(r)?r.choices:[];return [...new Set([...o,...i.choices,...Dt(e,n).map(([s])=>s)])]},Go=(e,t)=>{let n=e[t],i=b(n)&&!n.excluded?n.choices:[],r=Dt(e,t).filter(([,o])=>!o.excluded).map(([o])=>o);return [...new Set([...i,...r])]},Uo=(e,t,n,i,r)=>{let o=new Set(b(t)?t.choices:e);for(let s of n.slice().reverse()){let a=s.fields;if(!a)continue;let c=Go(a,i).filter(l=>!o.has(l));c.length>0&&r?.dryWarn("#nonMonotonicChoice",`Profile '${s.identifier.name}' declares choice variant(s) ${c.join(", ")} of '${i}' that an ancestor prohibits; they stay prohibited`),o=zo(o,a,i);}return o},zo=(e,t,n)=>{let i=new Set(e),r=Dt(t,n);for(let[c,l]of r)l.excluded&&i.delete(c);let o=t[n];if(b(o)){if(o.excluded)return new Set;let c=new Set(o.choices);return new Set([...i].filter(l=>c.has(l)))}let s=r.filter(([,c])=>!c.excluded).map(([c])=>c);if(s.length===0)return i;let a=new Set(s);return new Set([...i].filter(c=>a.has(c)))},Rn=(e,{register:t,logger:n,irReport:i={}})=>{let r={},o={},s={},a=S=>{let T=S.identifier.url,C=S.identifier.package;if(r[T]||(r[T]={}),r[T][C]&&C!=="shared"){let v=JSON.stringify(S.identifier,void 0,2),N=JSON.stringify(r[T][C]?.identifier,void 0,2);if(v!==N)throw new Error(`Duplicate schema: ${v} and ${N}`);return}r[T][C]=S,(_(S)||V(S))&&S.nested&&S.nested.forEach(v=>{let N=v.identifier.url,F=v.identifier.package;o[N]??={},o[N][F]=v;});};for(let S of e)a(S);Bo(e);let c=(S=>et(S)?s[S.url]?.[S.package]:r[S.url]?.[S.package]),l=(S=>L(S)?o[S.url]?.[S.package]:et(S)?s[S.url]?.[S.package]:r[S.url]?.[S.package]);Vo(e,l);let p=(S,T)=>{if(t){let v=t.resolutionTree()[S]?.[T]?.[0];if(v)return r[T]?.[v.pkg.name]}if(r[T]?.[S])return r[T]?.[S];if(o[T]?.[S])return o[T]?.[S];if(n?.dryWarn(`Type '${T}' not found in '${S}'`),r[T]){let C=Object.keys(r[T])[0];if(C)return n?.dryWarn(`Type '${T}' fallback to package ${C}`),r[T]?.[C]}if(o[T]){let C=Object.keys(o[T])[0];if(C)return n?.dryWarn(`Type '${T}' fallback to package ${C}`),o[T]?.[C]}},d=S=>{let T=[],C=S;for(;C;){T.push(C);let v=C.base;if(v===void 0||L(v))break;let N=c(v);if(!N){n?.warn("#resolveBase",`Failed to resolve base type: ${T.map(F=>`${F.identifier.url} (${F.identifier.kind})`).join(", ")}`);return}C=N;}return T},u=S=>{let T=d(S);if(T===void 0)throw new Error(`Failed to resolve base type: ${S.identifier.url} (${S.identifier.kind})`);return T},f=S=>{let T=u(S).find(C=>!V(C)&&!te(C));if(!T)throw new Error(`No non-constraint schema found in hierarchy for: ${S.identifier.name}`);return T},m=S=>{let T=l(S);return T?he(T)?m(T.base):f(T).identifier:S},g=S=>{let T=l(S);return !T||!("typeFamily"in T)?false:(T.typeFamily?.resources?.length??0)>0},y=(S,T,C={})=>{let v={...S},N=new Set([...Object.keys(v),...Object.keys(C)]);for(let F of N){let W=v[F]??C[F];if(!b(W))continue;let re=v[F]!==void 0;if(!re&&Dt(v,F).length===0)continue;let Z=wo(v,C,F,W),B=Uo(Z,C[F],T,F,n),X=Z.filter(pe=>!B.has(pe));!re&&X.length===0||(v[F]={...W,choices:Z.filter(pe=>B.has(pe)),...X.length>0?{prohibited:X}:{}});}return v},h=S=>{let T=u(S),C=T.filter(B=>B.identifier.kind==="profile"),v=T.find(B=>B.identifier.kind!=="profile");if(!v)throw new Error(`No non-constraint schema found in hierarchy for ${S.identifier.name}`);let N={},F={};for(let B of C.slice().reverse()){let X=B;if(X.slicing&&Object.assign(F,X.slicing),!!X.fields)for(let[pe,ht]of Object.entries(X.fields)){let ai=N[pe]?{...N[pe],...ht}:{...ht};"min"in ht&&ht.min===0&&(ai.required=false),N[pe]=ai;}}let W=y(N,C,v.fields),re=Object.values(Object.fromEntries(C.flatMap(B=>B.dependencies??[]).map(B=>[B.url,B]))),Z=Object.values([...C.filter(V)].reverse().flatMap(B=>B.extensions??[]).reduce((B,X)=>{let pe=`${X.path}|${X.name}`;return (!B[pe]||X.url?.includes("/"))&&(B[pe]=X),B},{}));return {...S,base:v.identifier,fields:W,slicing:Object.keys(F).length>0?F:void 0,dependencies:re,extensions:Z.length>0?Z:void 0}},x=S=>{let T=h(S),C=T.fields??{},N=u(S).find(W=>W.identifier.kind!=="profile"),F=[];if(N?.fields)for(let[W,re]of Object.entries(N.fields)){if(!re.required||b(re))continue;let Z=C[W];Z?.min!==0&&(Z?.required||F.push(W));}return {identifier:Rt(T.identifier),base:T.base,description:T.description,fields:C,slicing:T.slicing,inheritedRequiredFields:F.length>0?F:void 0,extensions:T.extensions,dependencies:T.dependencies,nested:T.nested}};for(let S of e){if(!V(S)||!d(S)?.some(N=>!V(N)&&!te(N)))continue;let C=x(S),v=s[C.identifier.url]??={};v[C.identifier.package]=C;}let k=()=>Object.values(s).flatMap(S=>Object.values(S)),$=(S,T,C)=>{let v=p(S,T.url);if(!(!v||!("fields"in v)||!v.fields))for(let[N,F]of Object.entries(v.fields)){if(!b(F))continue;let W=F.choices.filter(B=>C.includes(B));if(W.length!==1)continue;let re=W[0],Z=v.fields[re];if(!(!Z||!A(Z)))return {choiceBase:N,variant:re,variantType:Z.type,allChoiceNames:F.choices}}},q=(S,T,C,v)=>{let N=p(S,T.url);if(!N||!("fields"in N)||!N.fields)return;let F=N.fields[v];if(!F||!b(F))return;let W=F.choices.filter(re=>C.includes(re));return W.length>0?W:F.choices},_e=S=>{let T=d(S);return T?T.filter(_).some(C=>C.fields?.meta!==void 0):false},G=()=>{let S={};for(let[T,C]of Object.entries(Ae(e))){S[T]={"primitive-type":{},"complex-type":{},resource:{},"value-set":{},nested:{},binding:{},profile:{},"profile-snapshot":{},logical:{}};for(let v of C)S[T][v.identifier.kind][v.identifier.url]={};}return S},$e=async S=>{let T=G(),C=S.endsWith(".yaml")?vi.stringify(T):JSON.stringify(T,void 0,2);await Ct.mkdir(w.dirname(S),{recursive:true}),await Ct.writeFile(S,C);};return {_schemaIndex:r,schemas:e,schemasByPackage:Ae(e),register:t,collectComplexTypes:()=>e.filter(It),collectResources:()=>e.filter(ee),collectLogicalModels:()=>e.filter(je),collectProfiles:()=>e.filter(V),collectSnapshotProfiles:k,resolve:c,resolveType:l,resolveByUrl:p,tryHierarchy:d,hierarchy:u,findLastSpecialization:f,findLastSpecializationByIdentifier:m,isFamilyType:g,flatProfile:h,constrainedChoice:$,sliceChoiceVariants:q,isWithMetaField:_e,entityTree:G,exportTree:$e,irReport:()=>i,replaceSchemas:S=>Rn(S,{register:t,logger:n,irReport:{...i}})}};var Bt=e=>{let t=e.replace(/\[x\]/g,"_x_").replace(/[- :./]/g,"_");return Et.has(t)&&(t=`${t}_`),vn.test(t)&&(t=`_${t}`),t},In=e=>{if(!e)return "";let t=e.replace(/\[x\]/g,"").replace(/[:./]/g,"_");return P(t)},E=(e,t=P)=>{let n=e.replace(/\[x\]/g,"").replace(/[:./]/g,"_"),i=t(n);return Et.has(i)?`${i}_`:i},Ve=e=>{let t=z(Bt(e.identifier.name));return e.base.name==="Extension"?t.endsWith("Extension")?t:`${t}Extension`:t.endsWith("Profile")?t:`${t}Profile`},we=(e,t)=>{let n=e.findLastSpecialization(t),i=P(Bt(n.identifier.name)),r=P(Bt(t.identifier.name));return `${i}_${r}`},Ge=e=>{let t=e.replace(/\[x]/g,"").replace(/[^a-zA-Z0-9_]/g,"_");return `_${P(t)}_slice_match`},jt=(e,t=P)=>t(`value${z(Bt(e.name))}`),Ii=(e,t)=>{let n={};for(let o of e)o.url&&(n[`${o.url}:${o.path}`]=P(o.nameCandidates.recommended));let i={};for(let o of t)i[`${o.fieldName}:${o.sliceName}`]=P(o.nameCandidates.recommended);let r=new Set([...Object.values(n),...Object.values(i)]);return {extensions:n,slices:i,allBaseNames:r}};var $n=(e,t,n)=>{if(n.profile){let r=e.resolve(n.profile);if(r)return {className:Ve(r),moduleName:we(e,r)}}if(!n.url)return;let i=e.resolveByUrl(t,n.url);if(!(!i||!V(i))&&i.identifier.package===t)return {className:Ve(i),moduleName:we(e,i)}},$i=(e,t,n,i,r)=>{let o=n.identifier.package;for(let s of n.extensions??[]){if(!s.url)continue;let a=r[`${s.url}:${s.path}`]??P(s.nameCandidates.recommended),c=s.path.split(".").filter(p=>p!=="extension"),l=$n(t,o,s);if(s.isComplex&&s.subExtensions)Yo(e,s,a,c,l),Zo(e,s,i,a,c,l);else if(s.valueFieldTypes?.length===1&&s.valueFieldTypes[0]){let p=s.valueFieldTypes[0],d=jt(p,e.nameFormatFunction),u=Ee(p);Xo(e,s,a,c,d,u,l),Qo(e,s,i,a,c,d,u,l);}else es(e,s,a,c,l),ts(e,s,i,a,c,l);}},Ho=(e,t,n)=>{n.length===0?e.line('exts = getattr(self._resource, "extension", None) or []'):(e.line(`target = ensure_path(self._resource.model_dump(by_alias=True, exclude_none=True) if hasattr(self._resource, "model_dump") else self._resource, ${JSON.stringify(n)})`),e.line('exts = target.get("extension", []) if isinstance(target, dict) else []')),e.line(`ext = next((e for e in exts if is_extension(e, ${JSON.stringify(t.url)})), None)`);},rt=(e,t,n)=>{t.length===0?e.line(`push_extension(self._resource, ${n})`):(e.line(`target = ensure_path(self._resource, ${JSON.stringify(t)})`),e.line(`push_extension(target, ${n})`));},Jo=(e,t,n,i)=>{let r=i?.className;e.line("@overload"),e.line(`def ${t}(self) -> ${n} | None: ...`),e.line("@overload"),e.line(`def ${t}(self, mode: Literal["raw"]) -> Extension | None: ...`),r&&(e.line("@overload"),e.line(`def ${t}(self, mode: Literal["profile"]) -> ${r} | None: ...`));let o=r?'Literal["raw", "profile"] | None':'Literal["raw"] | None',s=r?`${n} | Extension | ${r} | None`:`${n} | Extension | None`;e.line(`def ${t}(self, mode: ${o} = None) -> ${s}:`);},Wo=(e,t)=>{e.line("ext_obj = ext if not isinstance(ext, dict) else Extension(**ext)"),e.line('if mode == "raw":'),e.indentBlock(()=>e.line("return ext_obj")),t&&(e.line('if mode == "profile":'),e.indentBlock(()=>e.line(`return ${t.className}.apply(ext_obj)`)));},qo=(e,t,n,i)=>{let r=false;i&&(e.line(`if isinstance(value, ${i.className}):`),e.indentBlock(()=>rt(e,n,"value.to_resource()")),r=true);let o=r?"elif":"if";e.line(`${o} is_extension(value):`),e.indentBlock(()=>{e.line(`if _get_key(value, "url") != ${JSON.stringify(t.url)}:`),e.indentBlock(()=>e.line(`raise ValueError(f"Expected extension url '${t.url}', got {_get_key(value, 'url')!r}")`)),rt(e,n,"value");});},Ko=(e,t)=>{let n=[];return t&&n.push(t.className),n.push("Extension",e),`"${n.join(" | ")}"`},Fn=(e,t,n,i,r,o,s)=>{Jo(e,`get_${n}`,i,o),e.indentBlock(()=>{Ho(e,t,r),e.line("if ext is None:"),e.indentBlock(()=>e.line("return None")),Wo(e,o),s();}),e.line();},Yo=(e,t,n,i,r)=>{Fn(e,t,n,"dict[str, Any]",i,r,()=>{let o=(t.subExtensions??[]).map(s=>{let a=s.valueFieldType?jt(s.valueFieldType,e.nameFormatFunction):"value",c=s.max==="*";return `{"name": ${JSON.stringify(s.url)}, "valueField": ${JSON.stringify(a)}, "isArray": ${c?"True":"False"}}`});e.line(`config = [${o.join(", ")}]`),e.line("return extract_complex_extension(ext, config)");});},Pn=(e,t,n,i,r,o,s,a)=>{let c=Ko(r,s);e.line(`def set_${i}(self, value: ${c}) -> "${n}":`),e.indentBlock(()=>{qo(e,t,o,s),e.line("else:"),e.indentBlock(a),e.line("return self");}),e.line();},Zo=(e,t,n,i,r,o)=>{Pn(e,t,n,i,"dict[str, Any]",r,o,()=>{e.line("assert is_record(value)"),e.line("sub_extensions = []");for(let a of t.subExtensions??[]){let c=a.valueFieldType?jt(a.valueFieldType,e.nameFormatFunction):"value";a.max==="*"?(e.line(`for item in value.get(${JSON.stringify(a.url)}, []):`),e.indentBlock(()=>{e.line(`sub_extensions.append({"url": ${JSON.stringify(a.url)}, ${JSON.stringify(c)}: item})`);})):(e.line(`if value.get(${JSON.stringify(a.url)}) is not None:`),e.indentBlock(()=>{e.line(`sub_extensions.append({"url": ${JSON.stringify(a.url)}, ${JSON.stringify(c)}: value[${JSON.stringify(a.url)}]})`);}));}let s=`Extension(url=${JSON.stringify(t.url)}, extension=sub_extensions)`;rt(e,r,s);});},Xo=(e,t,n,i,r,o,s)=>{Fn(e,t,n,o,i,s,()=>{e.line(`return cast('${o} | None', get_extension_value(ext, ${JSON.stringify(r)}))`);});},Qo=(e,t,n,i,r,o,s,a)=>{Pn(e,t,n,i,s,r,a,()=>{e.line("assert not isinstance(value, Extension)"),rt(e,r,`Extension(url=${JSON.stringify(t.url)}, ${o}=value)`);});},es=(e,t,n,i,r)=>{Fn(e,t,n,"dict[str, Any]",i,r,()=>{e.line('return cast("dict[str, Any] | None", ext if isinstance(ext, dict) else ext.model_dump(by_alias=True, exclude_none=True))');});},ts=(e,t,n,i,r,o)=>{Pn(e,t,n,i,"dict[str, Any]",r,o,()=>{e.line("assert is_record(value)"),rt(e,r,`{"url": ${JSON.stringify(t.url)}, **value}`);});};var Fi=(e,t)=>{if(!e.array||!t?.slices||Pe(t))return;let n=Object.entries(t.slices).filter(([i,r])=>r.min!==void 0&&r.min>=1&&r.match&&Object.keys(r.match).length>0).map(([i])=>i);return n.length>0?n:void 0},Pi=(e,t)=>{for(let n of t){let i=Ge(n.sliceName);e.line(`${i}: dict[str, Any] = ${JSON.stringify(n.match)}`);}t.length>0&&e.line();},Ni=(e,t,n)=>{if(!n||!("fields"in n)||!n.fields)return t;let i={};for(let[r,o]of Object.entries(t)){let s=n.fields[r];if(!s||!j(s)){i[r]=o;continue}let a=s.type?e.resolveType(s.type):void 0,c=l=>l!==null&&typeof l=="object"&&!Array.isArray(l)?Ni(e,l,a):l;if(Array.isArray(o))i[r]=o.map(c);else if(o!==null&&typeof o=="object"){let l=c(o);i[r]=s.array?[l]:l;}else i[r]=o;}return i},ns=(e,t)=>{if(!(!e||!t)){for(let n of Object.values(t))if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=n.resourceType;if(typeof i=="string")return i}}},Ei=(e,t)=>{let n=t.identifier.package;return Object.entries(t.slicing??{}).flatMap(([i,r])=>{let o=t.fields[i];if(!j(o)||!r.slices||!o.type)return [];let s=new Set,a=e.resolveType(o.type);if(a&&"fields"in a&&a.fields)for(let[c,l]of Object.entries(a.fields))b(l)&&s.add(c);return Object.entries(r.slices).filter(([c,l])=>Object.keys(l.match??{}).length>0).map(([c,l])=>{let p=Object.keys(l.match??{}),d=(l.required??[]).filter(y=>!p.includes(y)&&!s.has(y)),u=l.elements?e.constrainedChoice(n,o.type,l.elements):void 0,f=u&&!M(u.variantType)?u:void 0,m=Pe(r),g=ns(m,l.match);return {fieldName:i,sliceName:c,match:Ni(e,l.match??{},a),required:d,array:!!o.array,max:l.max??0,constrainedChoice:f,elementTypeName:o.type&&!M(o.type)?Ee(o.type):void 0,elementTypeId:o.type&&!M(o.type)?o.type:void 0,isTypeDiscriminated:m,typeDiscriminatorResource:g,nameCandidates:l.nameCandidates}})})},Oi=e=>e.elementTypeName&&e.typeDiscriminatorResource?`${e.elementTypeName}[${e.typeDiscriminatorResource}]`:e.elementTypeName??"Any",_i=(e,t,n)=>{for(let i of t){let r=n[`${i.fieldName}:${i.sliceName}`]??i.nameCandidates.recommended,o=Ge(i.sliceName),s=E(i.fieldName,e.nameFormatFunction),a=JSON.stringify(Object.keys(i.match));if(i.isTypeDiscriminated){let c=Oi(i);i.array&&i.max===0?(e.line(`def get_${r}(self, mode: str | None = None) -> list[${c}] | None:`),e.indentBlock(()=>{e.line(`match = self.__class__.${o}`),e.line(`result = get_array_slices(getattr(self._resource, ${JSON.stringify(s)}, None), match)`),e.line(`return cast('list[${c}] | None', result or None)`);})):(e.line(`def get_${r}(self, mode: str | None = None) -> ${c} | None:`),e.indentBlock(()=>{e.line(`match = self.__class__.${o}`),e.line(`return cast('${c} | None', get_array_slice(getattr(self._resource, ${JSON.stringify(s)}, None), match))`);}));}else {let c="dict[str, Any]",l=i.elementTypeName??"Any";e.line("@overload"),e.line(`def get_${r}(self) -> ${c} | None: ...`),e.line("@overload"),e.line(`def get_${r}(self, mode: Literal["raw"]) -> ${l} | None: ...`),e.line(`def get_${r}(self, mode: Literal["raw"] | None = None) -> ${c} | ${l} | None:`),e.indentBlock(()=>{if(e.line(`match = self.__class__.${o}`),i.array?e.line(`item = get_array_slice(getattr(self._resource, ${JSON.stringify(s)}, None), match)`):(e.line(`item = getattr(self._resource, ${JSON.stringify(s)}, None)`),e.line("if item is None or not matches_value(item, match):"),e.indentBlock(()=>{e.line("return None");})),e.line('if mode == "raw":'),e.indentBlock(()=>{e.line(`return cast('${l} | None', item)`);}),e.line("item_dict = item if isinstance(item, dict) else item.model_dump(by_alias=True, exclude_none=True)"),i.constrainedChoice){let p=JSON.stringify(i.constrainedChoice.variant);e.line(`return unwrap_slice_choice(item_dict, ${a}, ${p})`);}else e.line(`return strip_match_keys(item_dict, ${a})`);});}e.line();}},Mi=(e,t,n,i)=>{for(let r of n){let o=i[`${r.fieldName}:${r.sliceName}`]??r.nameCandidates.recommended,s=Ge(r.sliceName),a=E(r.fieldName,e.nameFormatFunction);if(r.isTypeDiscriminated){let c=Oi(r);r.array&&r.max===0?(e.line(`def set_${o}(self, values: list[${c}]) -> "${t}":`),e.indentBlock(()=>{e.line(`match = self.__class__.${s}`),e.line(`items = list(getattr(self._resource, ${JSON.stringify(a)}, None) or [])`),e.line("set_array_slices(items, match, values)"),e.line(`setattr(self._resource, ${JSON.stringify(a)}, items)`),e.line("return self");})):(e.line(`def set_${o}(self, value: ${c} | None = None) -> "${t}":`),e.indentBlock(()=>{e.line(`match = self.__class__.${s}`),e.line(`items = getattr(self._resource, ${JSON.stringify(a)}, None) or []`),e.line("set_array_slice(items, match, value)"),e.line(`setattr(self._resource, ${JSON.stringify(a)}, items)`),e.line("return self");}));}else {let c=r.required.length===0,l=c?`def set_${o}(self, value: dict[str, Any] | None = None) -> "${t}":`:`def set_${o}(self, value: dict[str, Any]) -> "${t}":`;e.line(l),e.indentBlock(()=>{e.line(`match = self.__class__.${s}`);let p=c?"(value or {})":"value";if(r.constrainedChoice){let u=JSON.stringify(r.constrainedChoice.variant);e.line(`wrapped = wrap_slice_choice(${p}, ${u})`),e.line("merged = apply_slice_match(wrapped, match)");}else e.line(`merged = apply_slice_match(${p}, match)`);let d="merged";r.elementTypeName&&(e.line(`element = ${r.elementTypeName}(**merged)`),d="element"),r.array?(e.line(`items = getattr(self._resource, ${JSON.stringify(a)}, None) or []`),e.line(`set_array_slice(items, match, ${d})`),e.line(`setattr(self._resource, ${JSON.stringify(a)}, items)`)):e.line(`setattr(self._resource, ${JSON.stringify(a)}, ${d})`),e.line("return self");});}e.line();}};var Lt=(e,t,n)=>{let i=t?t(e.type):e.type,r=Ee(i);if(r==="str"&&e.enum&&!e.enum.isOpen&&e.enum.values.length>0){let o=`Literal[${e.enum.values.map(s=>JSON.stringify(s)).join(", ")}]`;return e.array?`list[${o}]`:o}if(r==="Reference"&&n){let o=it(e,n);o&&(r=`Reference[${o}]`);}return e.array?`list[${r}]`:r},Ue=e=>{let t=(e.reference?.profiles??[]).map(n=>n.url);return t.length>0?` # ${t.join(", ")}`:void 0},is=(e,t,n,i,r)=>{if(!b(e)||!e.required||e.choices.length!==1)return;let o=e.choices[0];if(!o)return;let s=t[o];if(!s||!A(s))return;let a=Di(s,r);n.push({name:o,pyType:a,typeId:s.type,refComment:Ue(s)}),i.add(o);},Di=(e,t)=>{let n=Ee(e.type);if(n==="Reference"){let i=it(e,t);i&&(n=`Reference[${i}]`);}return n+(e.array?"[]":"")},rs=(e,t,n,i,r)=>{let o=new Set(r),s=e.resolveType(t.base);if(!(!s||!("fields"in s)||!s.fields)){for(let[a,c]of Object.entries(s.fields))if(!o.has(a)&&c.required&&!A(c)&&!b(c)&&j(c)&&c.type){let l=Lt(c,n,e);i.push({name:a,pyType:l,typeId:c.type,refComment:Ue(c)});}}},Bi=(e,t)=>{let n=[],i=[],r=[],o=[],s=[],a=t.fields,c=new Set,l=e.findLastSpecializationByIdentifier,p=new Map;for(let[,u]of Object.entries(a))if(b(u))for(let f of u.choices)p.set(f,u.choices);oe(t.base)&&n.push({name:"resourceType",value:JSON.stringify(t.base.name)});for(let[u,f]of Object.entries(a))if(!f.excluded){if(A(f)){s.push([u,f]);continue}if(b(f)){is(f,a,r,c,e);continue}if(f.valueConstraint&&!f.valueConstraint.validateOnly){let m=JSON.stringify(f.valueConstraint.value);if(n.push({name:u,value:f.array?`[${m}]`:m}),j(f)&&f.type){let g=Lt(f,l,e);o.push({name:u,pyType:g,typeId:f.type,refComment:Ue(f)});}continue}if(j(f)){let m=Fi(f,t.slicing?.[u]);if(m){if(f.type){let g=Lt(f,l,e);i.push({name:u,pyType:g,typeId:f.type,sliceNames:m}),o.push({name:u,pyType:g,typeId:f.type,refComment:Ue(f)});}continue}}if(f.required){let m=Lt(f,l,e);r.push({name:u,pyType:m,typeId:f.type,refComment:Ue(f)});}}rs(e,t,l,r,[...n.map(u=>u.name),...i.map(u=>u.name),...r.map(u=>u.name),...c]);let d=[];for(let[u,f]of s){if(c.has(u))continue;let m=Di(f,e),g=(p.get(u)??[]).filter(y=>y!==u&&!c.has(y));d.push({name:u,pyType:m,typeId:f.type,choiceSiblings:g,refComment:Ue(f)});}return {autoFields:n,sliceAutoFields:i,params:r,accessors:[...o,...d]}},Nn=(e,t)=>{let n=[];for(let i of e.sliceAutoFields)n.push(`${E(i.name,t)}: ${i.pyType} | None = None`);for(let i of e.params)n.push(`${E(i.name,t)}: ${i.pyType}`);return n.length===0?"":`*, ${n.join(", ")}`},ji=(e,t)=>{let n=[];for(let i of e.sliceAutoFields){let r=E(i.name,t);n.push(`${r}=${r}`);}for(let i of e.params){let r=E(i.name,t);n.push(`${r}=${r}`);}return n.join(", ")},Li=(e,t,n,i,r,o)=>{let s=e.nameFormatFunction;e.line("@classmethod"),r?e.line(`def create_resource(cls, ${Nn(o,s)}) -> ${n}:`):e.line(`def create_resource(cls) -> ${n}:`),e.indentBlock(()=>{for(let c of o.sliceAutoFields){let l=E(c.name,s),p=c.sliceNames.map(d=>`cls.${Ge(d)}`);p.length===1?e.line(`${l}_with_defaults = ensure_slice_defaults(list(${l} or []), ${p[0]})`):(e.line(`${l}_with_defaults = ensure_slice_defaults(`),e.indentBlock(()=>{e.line(`list(${l} or []),`);for(let d of p)e.line(`${d},`);}),e.line(")"));}o.sliceAutoFields.length>0&&e.line();let a=[];for(let c of o.autoFields)a.push(`${E(c.name,s)}=${c.value}`);for(let c of o.sliceAutoFields)a.push(`${E(c.name,s)}=${E(c.name,s)}_with_defaults`);for(let c of o.params)a.push(`${E(c.name,s)}=${E(c.name,s)}`);i&&a.push('meta={"profile": [cls.canonical_url]}'),a.length<=2?e.line(`return build_resource(${t}, ${a.join(", ")})`):(e.line("return build_resource("),e.indentBlock(()=>{e.line(`${t},`);for(let c of a)e.line(`${c},`);}),e.line(")"));});},Ai=(e,t,n,i)=>{let r=e.nameFormatFunction;for(let o of n.params){let s=E(o.name,r),a=In(o.name);e.line(`def get_${a}(self) -> ${o.pyType} | None:${o.refComment??""}`),e.indentBlock(()=>{e.line(`return cast('${o.pyType} | None', getattr(self._resource, ${JSON.stringify(s)}, None))`);}),e.line(),e.line(`def set_${a}(self, value: ${o.pyType}) -> "${t}":${o.refComment??""}`),e.indentBlock(()=>{e.line(`setattr(self._resource, ${JSON.stringify(s)}, value)`),e.line("return self");}),e.line();}for(let o of n.accessors){let s=In(o.name);if(i.has(s))continue;let a=E(o.name,r);e.line(`def get_${s}(self) -> ${o.pyType} | None:${o.refComment??""}`),e.indentBlock(()=>{e.line(`return cast('${o.pyType} | None', getattr(self._resource, ${JSON.stringify(a)}, None))`);}),e.line(),e.line(`def set_${s}(self, value: ${o.pyType}) -> "${t}":${o.refComment??""}`),e.indentBlock(()=>{if(o.choiceSiblings?.length)for(let c of o.choiceSiblings)e.line(`setattr(self._resource, ${JSON.stringify(E(c,r))}, None)`);e.line(`setattr(self._resource, ${JSON.stringify(a)}, value)`),e.line("return self");}),e.line();}};var ze=(e,t,n,i,r)=>{let o=["self._resource","profile_name",...i].join(", ");e.push(`${t}.extend(`,` ${n}(${o}, [`,` ${r.map(s=>JSON.stringify(s)).join(",")}`,"]))");},Vi=(e,t,n,i,r)=>{let o=new Set,s=e.fields;for(let[a,c]of Object.entries(s)){let l=E(a,r);if(!A(c)){if(b(c)){if(c.required){o.add("validate_choice_required");let p=c.choices.map(d=>E(d,r));ze(n,"errors","validate_choice_required",[],p);}if(c.prohibited?.length){o.add("validate_choice_prohibited");let p=c.prohibited.map(d=>E(d,r));ze(n,"errors","validate_choice_prohibited",[],p);}continue}os(c,e.slicing?.[a],l,o,n,i,t,r);}}for(let a of e.inheritedRequiredFields??[])o.add("validate_required"),n.push(`errors.extend(validate_required(self._resource, profile_name, ${JSON.stringify(E(a,r))}))`);return o},os=(e,t,n,i,r,o,s,a)=>{if(e.excluded){i.add("validate_excluded"),r.push(`errors.extend(validate_excluded(self._resource, profile_name, ${JSON.stringify(n)}))`);return}if(e.required&&(i.add("validate_required"),r.push(`errors.extend(validate_required(self._resource, profile_name, ${JSON.stringify(n)}))`)),e.valueConstraint){let c=e.valueConstraint.validateOnly?"validate_pattern_value":"validate_fixed_value";i.add(c);let l=JSON.stringify(e.valueConstraint.value);r.push(`errors.extend(${c}(self._resource, profile_name, ${JSON.stringify(n)}, ${l}))`);}if(j(e)){if(e.enum){i.add("validate_enum");let c=e.enum.isOpen?o:r,l=e.enum.isOpen?"warnings":"errors";ze(c,l,"validate_enum",[JSON.stringify(n)],e.enum.values);}if(e.mustSupport&&!e.required&&(i.add("validate_must_support"),o.push(`warnings.extend(validate_must_support(self._resource, profile_name, ${JSON.stringify(n)}))`)),e.reference&&e.reference.resource.length>0){i.add("validate_reference");let c=e.reference.resource.map(l=>s.findLastSpecializationByIdentifier(l).name);ze(r,"errors","validate_reference",[JSON.stringify(n)],c);}t?.slices&&as(e,t,n,i,r,s,a);}},ss=(e,t,n,i,r)=>{let o=[],s=[],a=new Set(Object.keys(t)),c=(e.required??[]).filter(p=>!a.has(p)),l=n.type;for(let p of c){let d=l?i.sliceChoiceVariants(l.package,l,e.elements??[],p):void 0;d&&d.length>0?s.push(d.map(u=>E(u,r))):o.push(E(p,r));}if(l&&e.elements){let p=i.constrainedChoice(l.package,l,e.elements);p&&!c.includes(p.choiceBase)&&o.push(E(p.variant,r));}return {requiredFields:o,choiceGroups:s}},as=(e,t,n,i,r,o,s)=>{if(t.slices)for(let[a,c]of Object.entries(t.slices)){let l=c.match??{};if(Object.keys(l).length===0)continue;if(c.min!==void 0||c.max!==void 0){let f=c.min??0,m=c.max??0;i.add("validate_slice_cardinality"),r.push(`errors.extend(validate_slice_cardinality(self._resource, profile_name, ${JSON.stringify(n)}, ${JSON.stringify(l)}, ${JSON.stringify(a)}, ${f}, ${m}))`);}let{requiredFields:p,choiceGroups:d}=ss(c,l,e,o,s);if(p.length===0&&d.length===0)continue;i.add("validate_slice_fields");let u=[JSON.stringify(n),JSON.stringify(l),JSON.stringify(a)];if(d.length===0){ze(r,"errors","validate_slice_fields",u,p);continue}ze(r,"errors","validate_slice_fields",[...u,JSON.stringify(p)],d);}};var Gi=(e,t)=>{let n=ae(e,t.package);if(oe(t))return `${n}.${P(t.name)}`;if(L(t)){let r=nt(t.url,false)?.split("#")[0];return r?`${n}.${P(r)}`:`${n}.base`}return `${n}.base`},wi=(e,t,n,i)=>{if(M(i)||Ne[i.name]!==void 0)return;let r=Te(i);if(!r||r===n)return;let o=Gi(t,i),s=e.get(o)??new Set;s.add(r),e.set(o,s);},At=(e,t,n,i,r)=>{let o=[r],s=i(r);s!==r&&o.push(s);for(let a of o){if(M(a)||Ne[a.name]!==void 0)continue;let c=Te(a);if(c===n)continue;let l=Gi(t,a),p=e.get(l);p||(p=new Set,e.set(l,p)),p.add(c);}},cs=(e,t,n,i,r)=>{let o=["build_resource"];if(e&&o.push("ensure_profile"),t.sliceAutoFields.length>0&&o.push("ensure_slice_defaults"),n.length>0){let s=n.some(l=>!l.isTypeDiscriminated),a=n.some(l=>l.isTypeDiscriminated&&!(l.array&&l.max===0)),c=n.some(l=>l.isTypeDiscriminated&&l.array&&l.max===0);s&&o.push("apply_slice_match","matches_value","strip_match_keys"),(a||s)&&o.push("get_array_slice","set_array_slice"),c&&o.push("get_array_slices","set_array_slices"),n.some(l=>l.constrainedChoice)&&o.push("wrap_slice_choice","unwrap_slice_choice");}return i.length>0&&(o.push("_get_key","is_extension","get_extension_value","push_extension"),i.some(a=>a.isComplex&&a.subExtensions)&&o.push("extract_complex_extension"),i.some(a=>a.path.split(".").some(c=>c!=="extension"))&&o.push("ensure_path"),i.some(a=>a.isComplex&&a.subExtensions||!(a.valueFieldTypes?.length===1&&a.valueFieldTypes[0]))&&o.push("is_record")),o.push(...r),o.sort(),o},ls=(e,t,n,i,r,o,s)=>{let a=new Map;for(let c of i.params)At(a,e,t,n,c.typeId);for(let c of i.sliceAutoFields)At(a,e,t,n,c.typeId);for(let c of i.accessors)At(a,e,t,n,c.typeId);for(let c of r){if(c.elementTypeId&&wi(a,e,t,c.elementTypeId),!c.isTypeDiscriminated||!c.typeDiscriminatorResource)continue;let l=s.find(p=>p.identifier.kind==="resource"&&p.identifier.name===c.typeDiscriminatorResource)?.identifier;l&&At(a,e,t,n,l);}for(let c of o)c.isComplex&&c.subExtensions||c.valueFieldTypes?.length===1&&c.valueFieldTypes[0]&&wi(a,e,t,c.valueFieldTypes[0]);return a},ps=(e,t,n)=>{let i=new Map;for(let r of n){if(!r.url)continue;let o=$n(e,t.identifier.package,r);o&&!i.has(o.className)&&i.set(o.className,o);}return i},ds=(e,t,n,i,r,o,s,a,c)=>{e.line("from __future__ import annotations"),e.line();let l=[...r.params,...r.accessors,...r.sliceAutoFields].some(h=>h.pyType.includes("Literal[")),p=c.some(h=>!h.isTypeDiscriminated),d=i.length>0||p,u=i.length>0||c.length>0,f=r.params.length>0||r.accessors.length>0||c.length>0||i.length>0,m=[];u&&m.push("Any"),f&&m.push("cast"),(d||l)&&m.push("Literal"),d&&m.push("overload"),m.length>0&&(e.pyImportFrom("typing",...[...m].sort()),e.line());let g=t.base.name,y=ae(e.opts.rootPackageName,t.base.package);n?e.pyImportFrom(`${y}.${P(g)}`,g):e.pyImportFrom(`${y}.base`,g),i.length>0&&e.pyImportFrom(`${y}.base`,"Extension");for(let[h,x]of [...o.entries()].sort(([k],[$])=>k.localeCompare($)))e.pyImportFrom(h,...[...x].sort());for(let[h,x]of [...s.entries()].sort(([k],[$])=>k.localeCompare($)))e.pyImportFrom(`.${x.moduleName}`,h);e.pyImportFrom(`${e.opts.rootPackageName}.profile_helpers`,...a),e.line(),e.line();},fs=(e,t,n,i)=>{e.line("@classmethod"),e.line(`def from_resource(cls, resource: ${t}) -> "${n}":`),e.indentBlock(()=>{i&&(e.line('meta = getattr(resource, "meta", None)'),e.line('profiles = getattr(meta, "profile", None) if meta is not None else None'),e.line("if profiles is None or cls.canonical_url not in profiles:"),e.indentBlock(()=>{e.line(`raise ValueError(f"${n}: meta.profile must include {cls.canonical_url}")`);})),e.line("profile = cls(resource)"),e.line("result = profile.validate()"),e.line('if result["errors"]:'),e.indentBlock(()=>e.line('raise ValueError("; ".join(result["errors"]))')),e.line("return profile");}),e.line();},us=(e,t,n,i)=>{e.line("@classmethod"),e.line(`def apply(cls, resource: ${t}) -> "${n}":`),e.indentBlock(()=>{i&&e.line("ensure_profile(resource, cls.canonical_url)"),e.line("return cls(resource)");}),e.line();},ms=(e,t,n,i)=>{e.line("@classmethod"),n?(e.line(`def create(cls, ${Nn(i,e.nameFormatFunction)}) -> "${t}":`),e.indentBlock(()=>e.line(`return cls.apply(cls.create_resource(${ji(i,e.nameFormatFunction)}))`))):(e.line(`def create(cls) -> "${t}":`),e.indentBlock(()=>e.line("return cls.apply(cls.create_resource())"))),e.line();},gs=(e,t,n,i)=>{e.line("def validate(self) -> dict[str, list[str]]:"),e.indentBlock(()=>{e.line(`profile_name = "${t}"`),e.line("errors: list[str] = []"),e.line("warnings: list[str] = []");for(let r of n)e.line(r);for(let r of i)e.line(r);e.line('return {"errors": errors, "warnings": warnings}');});},ys=e=>{let{w:t,tsIndex:n,flatProfile:i,baseTypeName:r,annotatedBaseTypeName:o,className:s,isResourceBase:a,errorLines:c,warningLines:l,factoryInfo:p,sliceDefs:d,resolvedNames:u}=e,f=p.params.length>0||p.sliceAutoFields.length>0;t.line(`def __init__(self, resource: ${o}) -> None:`),t.indentBlock(()=>t.line("self._resource = resource")),t.line(),fs(t,o,s,a),us(t,o,s,a),Li(t,r,o,a,f,p),t.line(),ms(t,s,f,p),t.line(`def to_resource(self) -> ${o}:`),t.indentBlock(()=>t.line("return self._resource")),t.line(),(p.params.length>0||p.accessors.length>0)&&Ai(t,s,p,u.allBaseNames),(i.extensions??[]).length>0&&$i(t,n,i,s,u.extensions),d.length>0&&(_i(t,d,u.slices),Mi(t,s,d,u.slices)),gs(t,s,c,l);},hs=(e,t,n)=>{let i=Ve(n),r=n.base.name,o=oe(n.base),s=n.identifier.url??"",a=Bi(t,n),c=Ei(t,n),l=[...new Set(c.filter(k=>k.isTypeDiscriminated).map(k=>k.typeDiscriminatorResource).filter(k=>k!==void 0))],p=l.length>0?`${r}[${l.join(" | ")}, Resource]`:r,d=n.extensions??[],u=Ii(d,c),f=[],m=[],g=Vi(n,t,f,m,e.nameFormatFunction),y=cs(o,a,c,d,g),h=ls(e.opts.rootPackageName,r,t.findLastSpecializationByIdentifier,a,c,d,t.schemas),x=ps(t,n,d);if(l.length>0){let $=`${ae(e.opts.rootPackageName,n.base.package)}.resource`,q=h.get($)??new Set;q.add("Resource"),h.set($,q);}ds(e,n,o,d,a,h,x,y,c),e.line(`class ${i}:`),e.indentBlock(()=>{n.description&&(e.line(`"""${n.description}`),e.line(),e.line(`CanonicalURL: ${s}`),e.line('"""'),e.line()),e.line(`canonical_url: str = ${JSON.stringify(s)}`),e.line(),Pi(e,c),ys({w:e,tsIndex:t,flatProfile:n,baseTypeName:r,annotatedBaseTypeName:p,className:i,isResourceBase:o,factoryInfo:a,sliceDefs:c,resolvedNames:u,errorLines:f,warningLines:m});}),e.line();},Ss=(e,t,n)=>{e.cat("__init__.py",()=>{e.generateDisclaimer();let i=new Set;for(let r of n){let o=Ve(r),s=we(t,r);i.has(o)||(i.add(o),e.pyImportFrom(`.${s}`,o));}e.line(),e.squareBlock(["__all__","="],()=>{for(let r of [...i].sort())e.line(`'${r}',`);});});},En=(e,t,n)=>{n.length!==0&&e.cd("profiles",()=>{for(let i of n){let r=we(t,i);e.cat(`${r}.py`,()=>{e.generateDisclaimer(),hs(e,t,i);});}Ss(e,t,n);});};var He=e=>Le(import.meta.url,"python",e),_n={snake_case:P,PascalCase:z,camelCase:de},Ui=100,Vt={Coding:{code:"T"},CodeableConcept:{coding:"Coding[T]"},Reference:{type:"T"}},Mn=e=>e[e.length-1]??"",zi=e=>{let t=new Map,n=i=>{for(let r of i.generic?.params??[])t.has(r.typeVar)||t.set(r.typeVar,r.constraint.name);};n(e);for(let i of e.nested??[])n(i);return Array.from(t.entries()).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({typeVar:i,constraint:r}))},Ts=e=>{let t=e.values.map(n=>`"${n}"`).join(", ");return e.isOpen?`Literal[${t}] | str`:`Literal[${t}]`},wt=class extends ve{nameFormatFunction;tsIndex;forFhirpyClient;fieldFormat;constructor(t){super({...t,resolveAssets:t.resolveAssets??He}),this.nameFormatFunction=this.getFieldFormatFunction(t.fieldFormat),this.forFhirpyClient=this.resolveClient(t),this.fieldFormat=t.fieldFormat;}resolveClient(t){return t.client!==void 0?t.client==="fhirpy":t.fhirpyClient!==void 0?(this.logger()?.warn('python: `fhirpyClient` is deprecated; use `client: "fhirpy" | "none"` instead.'),t.fhirpyClient):true}async generate(t){this.tsIndex=t;let n={groupedComplexTypes:Ae(t.collectComplexTypes()),groupedResources:Ae(t.collectResources())},i=(this.opts.generateProfile??false)&&t.collectSnapshotProfiles().length>0;this.generateRootPackages(n,i),this.generateSDKPackages(t,n);}generateRootPackages(t,n){this.generateRootInitFile(t),this.forFhirpyClient&&(this.fieldFormat==="camelCase"?this.copyAssets(He("fhirpy_base_model_camel_case.py"),"fhirpy_base_model.py"):this.copyAssets(He("fhirpy_base_model.py"),"fhirpy_base_model.py")),n&&this.copyAssets(He("profile_helpers.py"),"profile_helpers.py"),this.copyAssets(He("requirements.txt"),"requirements.txt");}generateSDKPackages(t,n){this.generateComplexTypesPackages(n.groupedComplexTypes),this.generateResourcePackages(t,n);}generateComplexTypesPackages(t){for(let[n,i]of Object.entries(t))this.cd(`/${P(n)}`,()=>{this.generateBasePy(n,i);});}generateResourcePackages(t,n){let i=this.opts.generateProfile?Ae(t.collectSnapshotProfiles()):{};for(let[r,o]of Object.entries(n.groupedResources))this.cd(`/${P(r)}`,()=>{this.generateResourcePackageContent(r,o,n.groupedComplexTypes[r]||[]);let s=i[r];s&&s.length>0&&En(this,t,s);});for(let[r,o]of Object.entries(i))n.groupedResources[r]||!o||o.length===0||this.cd(`/${P(r)}`,()=>{En(this,t,o);});}generateResourcePackageContent(t,n,i){let r=ae(this.opts.rootPackageName,t);this.generateResourcePackageInit(r,n,i),n.some(s=>zi(s).length>0)&&this.copyAssets(He("resource_preprocessor.py"),"resource_preprocessor.py");for(let s of n)this.generateResourceModule(s);}generateRootInitFile(t){this.cd("/",()=>{this.cat("__init__.py",()=>{this.generateDisclaimer();let n=this.collectAndImportAllModels(t);this.generateModelRebuilds(n),this.importProfileRegistrations(t);});});}collectAndImportAllModels(t){let n=[];for(let i of Object.keys(t.groupedResources)){let r=ae(this.opts.rootPackageName,i);n.push(...this.importComplexTypes(r,t.groupedComplexTypes[i])),n.push(...this.importResources(r,false,t.groupedResources[i]));}return this.line(),n}generateModelRebuilds(t){for(let n of t.sort())this.line(`${n}.model_rebuild()`);}importProfileRegistrations(t){if(this.opts.generateProfile){this.line();for(let n of Object.keys(t.groupedResources)){let i=`${ae(this.opts.rootPackageName,n)}.profiles`;this.line(`import ${i} # noqa: F401`);}}}generateBasePy(t,n){let i=n.some(r=>r.identifier.name in Vt);this.cat("base.py",()=>{this.generateDisclaimer(),this.generateDefaultImports(i),i&&(this.line(),this.line("T = TypeVar('T', bound=str, default=str)")),this.line(),this.generateComplexTypes(n),this.line();});}generateComplexTypes(t){for(let n of Ri(t))this.generateNestedTypes(n),this.line(),this.generateType(n);}generateResourcePackageInit(t,n,i){this.cat("__init__.py",()=>{this.generateDisclaimer(),this.importComplexTypes(t,i);let r=this.importResources(t,true,n);this.line(),this.generateExportsDeclaration(i,r);});}importComplexTypes(t,n){if(!n||n.length===0)return [];let i=n.map(r=>r.identifier.name).sort();return this.pyImportFrom(`${t}.base`,...i),this.line(),i}buildImportLine(t,n,i){let r="",o=n;for(;o<t.length&&r.length<i;)r.length>0&&(r+=", "),r+=t[o],o++;return o<t.length&&(r+=", \\"),{line:r,next:o}}importResources(t,n,i){if(!i||i.length===0)return [];let r=[];for(let o of i){let s=this.importOneResource(o,t);!n&&!o.fields||r.push(...s);}return r}importOneResource(t,n){let i=`${n}.${P(t.identifier.name)}`,r=this.collectResourceImportNames(t);return this.pyImportFrom(i,...r),[...r]}collectResourceImportNames(t){let n=[Te(t.identifier)];for(let i of t.nested??[]){let r=Te(i.identifier);n.push(r);}return n}generateExportsDeclaration(t,n){this.squareBlock(["__all__","="],()=>{let i=[...(t||[]).map(r=>r.identifier.name),...n].sort();for(let r of i)this.line(`'${r}',`);});}generateResourceModule(t){let n=zi(t),i=n.length>0;this.cat(`${P(t.identifier.name)}.py`,()=>{if(this.generateDisclaimer(),this.generateDefaultImports(false,i,true),this.generateFhirBaseModelImport(),this.line(),this.generateDependenciesImports(t),i){let r=ae(this.opts.rootPackageName,t.identifier.package);this.pyImportFrom(`${r}.resource_preprocessor`,"preprocess_resource_fields"),this.line();for(let{typeVar:o,constraint:s}of n)this.line(`${o} = TypeVar('${o}', bound=${s}, default=${s})`);}this.line(),this.generateNestedTypes(t),this.line(),this.generateType(t);});}generateFhirBaseModelImport(){this.forFhirpyClient&&this.pyImportFrom(`${this.opts.rootPackageName}.fhirpy_base_model`,"FhirpyBaseModel");}generateType(t){let n=Te(t.identifier),i=this.getSuperClasses(t);this.line(`class ${n}(${i.join(", ")}):`),this.indentBlock(()=>{this.generateClassBody(t);}),this.line();}getSuperClasses(t){let n=[];t.base&&n.push(t.base.name),n.push(...this.injectSuperClasses(t.identifier.url)),t.identifier.name in Vt&&n.push("Generic[T]");let i=t.generic?.params??[];if(i.length>0){let r=i.map(o=>o.typeVar).join(", ");n.push(`Generic[${r}]`);}return n}generateClassBody(t){if(this.generateModelConfig(),!t.fields){this.line("pass");return}ee(t)&&this.generateResourceTypeField(t),this.generateFields(t),this.opts.generateProfile&&t.identifier.name==="Extension"&&this.generateExtensionEqualityMethods(),ee(t)&&this.generateResourceMethods(t),(t.generic?.params?.length??0)>0&&this.generateResourcePreprocessorMethod(t);}generateResourcePreprocessorMethod(t){let n=ae(this.opts.rootPackageName,t.identifier.package);this.line(),this.line("@model_validator(mode='before')"),this.line("@classmethod"),this.line("def _preprocess_resources(cls, data: Any) -> Any:"),this.line(" if isinstance(data, dict):"),this.line(` return preprocess_resource_fields(data, "${n}")`),this.line(" return data");}generateModelConfig(){let t=this.opts.allowExtraFields?"allow":"forbid";this.line(`model_config = ConfigDict(validate_by_name=True, serialize_by_alias=True, extra="${t}")`);}generateResourceTypeField(t){let n=(t.typeFamily?.resources?.length??0)>0;this.line(`${this.nameFormatFunction("resourceType")}: str = Field(`),this.indentBlock(()=>{n||this.line(`default='${t.identifier.name}',`),this.line("alias='resourceType',"),this.line("serialization_alias='resourceType',"),this.forFhirpyClient||this.line("frozen=True,"),this.line(`pattern='${t.identifier.name}'`);}),this.line(")");}generateFields(t){let n=Object.entries(t.fields??[]).sort(([r],[o])=>r.localeCompare(o)),i=this.shouldAddPrimitiveExtensions(t);for(let[r,o]of n){if("choices"in o&&o.choices)continue;let s=this.buildFieldInfo(r,o,t);this.line(`${s.name}: ${s.type}${s.defaultValue}`),i&&"type"in o&&M(o.type)&&this.addPrimitiveExtensionField(r,o.array??false);}}shouldAddPrimitiveExtensions(t){if(!this.opts.primitiveTypeExtension||!_(t))return false;for(let n of Object.values(t.fields??{}))if(!("choices"in n&&n.choices)&&"type"in n&&M(n.type))return true;return false}addPrimitiveExtensionField(t,n){let i=this.nameFormatFunction(`${t}Extension`),r=`_${t}`,o=n?"PyList[Element | None] | None":"Element | None",s=`alias="${r}", serialization_alias="${r}"`;this.line(`${i}: ${o} = Field(None, ${s})`);}buildFieldInfo(t,n,i){let r=ki(this.nameFormatFunction(t)),o=this.determineFieldType(n,t,i),s=this.getFieldDefaultValue(n,t);return {name:r,type:o,defaultValue:s}}determineFieldType(t,n,i){let r=i.identifier.name,o=t?this.getBaseFieldType(t):"",s=Vt[r]?.[n];if(s)return o=s,t.array&&(o=`PyList[${o}]`),t.required||(o=`${o} | None`),o;let a=i.generic?.params??[],c=a.find(l=>Mn(l.path)===n);if(c)return o=c.typeVar,t.array&&(o=`PyList[${o}]`),t.required||(o=`${o} | None`),o;if("type"in t&&t.type&&a.length>0){xe(this.tsIndex!==void 0);let l=this.tsIndex.resolveType(t.type);if(l&&(he(l)||_(l))){let p=l.generic?.params??[];if(p.length>0){let d=p.map(u=>a.find(f=>Mn(f.path)===Mn(u.path))?.typeVar??u.typeVar);o=`${o}[${d.join(", ")}]`;}}}if("enum"in t&&t.enum&&(("type"in t?t.type.name:"")in Vt?o=`${o}[${Ts(t.enum)}]`:t.enum.isOpen||(o=`Literal[${t.enum.values.map(d=>`"${d}"`).join(", ")}]`)),o==="Reference"&&"reference"in t&&t.reference){xe(this.tsIndex!==void 0);let l=it(t,this.tsIndex);l&&(o=`Reference[${l}]`);}return t.array&&(o=`PyList[${o}]`),t.required||(o=`${o} | None`),o}getBaseFieldType(t){return "type"in t&&t.type.kind==="resource"?`${t.type.name}Family`:"type"in t&&t.type.kind==="nested"?Te(t.type):"type"in t&&t.type.kind==="primitive-type"?Ne[t.type.name]??"str":"type"in t?t.type.name:""}getFieldDefaultValue(t,n){let i=`alias="${n}", serialization_alias="${n}"`;return t.required?` = Field(${i})`:` = Field(None, ${i})`}generateResourceMethods(t){this.line(),this.line("def model_post_init(self, __context: Any) -> None:"),this.line(` self.__pydantic_fields_set__.add("${this.nameFormatFunction("resourceType")}")`),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) -> Self:"),this.line(" return cls.model_validate_json(json)");}generateExtensionEqualityMethods(){this.line(),this.line("def __eq__(self, other: object) -> bool:"),this.line(" if not isinstance(other, Extension):"),this.line(" return NotImplemented"),this.line(" return self.model_dump(by_alias=True, exclude_none=True) == other.model_dump(by_alias=True, exclude_none=True)"),this.line(),this.line("def __hash__(self) -> int:"),this.line(" return hash(self.url)");}generateNestedTypes(t){if(t.nested){this.line();for(let n of t.nested)this.generateType(n);}}generateDefaultImports(t,n=false,i=false){this.pyImportFrom("__future__","annotations");let r=["BaseModel","ConfigDict","Field","PositiveInt"];n&&r.push("model_validator"),this.pyImportFrom("pydantic",...r.sort());let o=["Any","List as PyList","Literal"];(t||n)&&o.push("Generic"),this.pyImportFrom("typing",...o.sort());let s=[];(t||n)&&s.push("TypeVar"),i&&s.push("Self"),s.length>0&&this.pyImportFrom("typing_extensions",...s.sort());}generateDependenciesImports(t){!t.dependencies||t.dependencies.length===0||(this.importComplexTypeDependencies(t.dependencies),this.importResourceDependencies(t.dependencies),this.importElementIfNeeded(t));}importElementIfNeeded(t){if(!this.shouldAddPrimitiveExtensions(t)||t.identifier.name==="Element"||t.dependencies?.find(o=>o.name==="Element"))return;xe(this.tsIndex!==void 0);let i=this.tsIndex.resolveByUrl(t.identifier.package,"http://hl7.org/fhir/StructureDefinition/Element");if(!i)return;let r=Ot(this.opts.rootPackageName,i.identifier);this.pyImportFrom(r,"Element");}importComplexTypeDependencies(t){let n=t.filter(r=>r.kind==="complex-type"),i=this.groupDependenciesByPackage(n);for(let[r,o]of Object.entries(i))this.pyImportFrom(r,...o.sort());}importResourceDependencies(t){let n=t.filter(i=>i.kind==="resource");for(let i of n)this.pyImportType(i);}groupDependenciesByPackage(t){let n={};for(let i of t){let r=Ot(this.opts.rootPackageName,i);n[r]||(n[r]=[]),n[r].push(i.name);}return n}pyImportFrom(t,...n){let i=`from ${t} import ${n.join(", ")}`;this.shouldUseSingleLineImport(i,n)?this.line(i):this.writeMultiLineImport(t,n);}shouldUseSingleLineImport(t,n){return t.length<=Ui||n.length===1}writeMultiLineImport(t,n){this.line(`from ${t} import (`),this.indentBlock(()=>{let i=0;for(;i<n.length;){let{line:r,next:o}=this.buildImportLine(n,i,Ui);this.line(r),i=o;}}),this.line(")");}pyImportType(t){this.pyImportFrom(Ot(this.opts.rootPackageName,t),z(t.name));}getFieldFormatFunction(t){return _n[t]?_n[t]:(this.logger()?.warn(`Unknown field format '${t}'. Defaulting to SnakeCase.`),this.logger()?.warn(`Supported formats: ${Object.keys(_n).join(", ")}`),P)}injectSuperClasses(t){let n=nt(t);return n==="resource"?this.forFhirpyClient?["FhirpyBaseModel"]:["BaseModel"]:n==="element"?["BaseModel"]:[]}};var Gt=(e,t)=>e<t?-1:e>t?1:0,ot=(e,t)=>Gt(e.sourcePackage,t.sourcePackage)||Gt(e.sourceCanonical,t.sourceCanonical),Hi=e=>JSON.stringify([...e].sort(ot).map(({sourcePackage:t,sourceCanonical:n})=>[t,n])),Ut=(e,t)=>t.sources.length-e.sources.length||Gt(Hi(e.sources),Hi(t.sources))||Gt(e.schemaHash,t.schemaHash);var Je=e=>e!==null&&typeof e=="object"&&e.resourceType==="CodeSystem";var st=e=>e!==null&&typeof e=="object"&&e.resourceType==="ValueSet";var Wi=/^[a-zA-Z0-9]+$/,Cs="http://hl7.org/fhir/StructureDefinition/Base",Dn=e=>{let[t,n]=e.split("|");return (Wi.test(t)?`http://hl7.org/fhir/StructureDefinition/${t}`:t)!==Cs?false:n===void 0||n.startsWith("4.")},ks=async(e,t)=>{let n=await e.packageJson(t.name);if(!n)return [];let i=n.dependencies;return i!==void 0?Object.entries(i).map(([r,o])=>({name:r,version:o})):[]},bs=e=>{let t=[],n=[...e??[]].reverse();for(;n.length>0;){let i=n.pop();if(i&&(t.push(i),i.concept))for(let r=i.concept.length-1;r>=0;r-=1){let o=i.concept[r];o&&n.push(o);}}return t},qi=(e,t,n)=>{let{packageMeta:i,resources:r}=e,o=new Map;for(let c of r){let l=`${c.resourceType}\0${c.url}`,p=o.get(l)??[];p.push(c),o.set(l,p);}let s=c=>`${c.id??""}\0${c.name??""}`,a=[];for(let c of o.values()){let l=c.slice().sort((d,u)=>s(d).localeCompare(s(u))),p=l[0];if(p){if(l.length>1){let d=l.map(u=>u.id??u.name??u.url);n?.dryWarn("#duplicateCanonical",`Package ${H(i)} contains duplicate ${p.resourceType} canonical URL ${JSON.stringify(p.url)} for resources ${d.join(", ")}; keeping ${p.id??p.name??p.url}`);}a.push(p);}}return a.map(c=>{let l={canonicalUrl:c.url,packageId:i.name,packageVersion:i.version,verification:t};if(c.resourceType==="ValueSet")return {resource:c,entry:{...l,resourceType:c.resourceType}};if(c.resourceType==="NamingSystem")return {resource:c,entry:{...l,resourceType:c.resourceType}};let p={...l,resourceType:"CodeSystem",...c.content!==void 0?{contentMode:c.content}:{}};if(!(c.content==="complete"&&t!=="unverifiable"))return {resource:c,entry:p};let u=bs(c.concept),f=new Set,m={};for(let y of u){if(f.has(y.code))throw new Error(`CodeSystem ${c.url} repeats code ${JSON.stringify(y.code)}`);f.add(y.code),y.display!==void 0&&Object.defineProperty(m,y.code,{value:y.display,enumerable:true,writable:true,configurable:true});}let g={...p,contentMode:"complete",codes:u.map(({code:y})=>y),displays:m};return {resource:c,entry:g}})},vs=e=>{if(!Array.isArray(e))return;let t=[],n=[{source:e,target:t,index:0}];for(;n.length>0;){let i=n[n.length-1];if(!i)break;if(i.index>=i.source.length){i.parent&&i.target.length===0&&delete i.parent.concept,n.pop();continue}let r=i.source[i.index];if(i.index+=1,r===null||typeof r!="object")continue;let o=r;if(typeof o.code!="string")continue;let s={code:o.code,...typeof o.display=="string"?{display:o.display}:{}};if(i.target.push(s),Array.isArray(o.concept)){let a=[];s.concept=a,n.push({source:o.concept,target:a,index:0,parent:s});}}return t},Rs=(e,t)=>{let n=Array.isArray(e.uniqueId)?e.uniqueId.filter(s=>s!==null&&typeof s=="object"&&typeof s.type=="string"&&typeof s.value=="string"&&s.value.length>0):[],i=n.filter(({preferred:s})=>s===true),r=i.length>0?i:n,o=r.find(({type:s})=>s==="uri")??r[0];if(o)return o.type==="oid"&&!o.value.startsWith("urn:oid:")?`urn:oid:${o.value}`:o.type==="uuid"&&!o.value.startsWith("urn:uuid:")?`urn:uuid:${o.value}`:o.value;if(typeof e.id=="string"&&e.id.length>0)return `NamingSystem/${e.id}`;if(typeof e.name=="string"&&e.name.length>0)return `NamingSystem/${e.name}`;t?.dryWarn("NamingSystem has no uniqueId, id, or name and cannot be emitted.");},Is=(e,t)=>{if(Je(e)||st(e)){if(typeof e.url!="string"||e.url.length===0)return;let r=Je(e)?vs(e.concept):void 0;return {resourceType:e.resourceType,...typeof e.id=="string"?{id:e.id}:{},...typeof e.name=="string"?{name:e.name}:{},url:e.url,...Je(e)&&typeof e.content=="string"?{content:e.content}:{},...r&&r.length>0?{concept:r}:{}}}if(e===null||typeof e!="object")return;let n=e;if(n.resourceType!=="NamingSystem")return;let i=typeof n.url=="string"&&n.url.length>0?n.url:Rs(n,t);if(!(i===void 0||i.length===0))return {resourceType:"NamingSystem",...typeof n.id=="string"?{id:n.id}:{},...typeof n.name=="string"?{name:n.name}:{},url:i}},Ki=e=>({pkg:e,canonicalResolution:{},fhirSchemas:{},valueSets:{},terminology:[]}),Yi=async(e,t,n,i,r)=>{let o=O(t);if(r?.info(`${" ".repeat(n*2)}+ ${o}`),i[o])return i[o];let s=Ki(t);i[o]=s;for(let c of await e.search({package:t})){let l=Is(c,r);l&&s.terminology.push(l);let p=c.url;if(!p||!(isStructureDefinition(c)||st(c)||Je(c)))continue;let d=p;s.canonicalResolution[d]&&r?.dryWarn("#duplicateCanonical",`Duplicate canonical URL: ${d} at ${o}.`),s.canonicalResolution[d]=[{deep:n,pkg:t,pkgId:o,resource:c}];}let a=await ks(e,t);for(let c of a){let{canonicalResolution:l}=await Yi(e,c,n+1,i,r);for(let[p,d]of Object.entries(l)){let u=p;s.canonicalResolution[u]=[...s.canonicalResolution[u]||[],...d];}}for(let c of Object.values(s.canonicalResolution))c.sort((l,p)=>l.deep-p.deep);return s},$s=(e,t)=>{for(let{pkg:n,canonicalResolution:i}of Object.values(e)){let r=O(n);if(!e[r])throw new Error(`Package ${r} not found`);let o=0;t?.info(`FHIR Schema conversion for '${O(n)}' begins...`);for(let[s,a]of Object.entries(i)){let c=a[0];if(!c)throw new Error("Resource not found");let l=c.resource,p=c.pkg;if(isStructureDefinition(l)){let d=Ji.translate(l),u=mi(d,p);o++,e[r].fhirSchemas[u.url]=u;}if(st(l)){let d=yi(l,p);e[r].valueSets[d.url]=d;}}t?.info(`FHIR Schema conversion for '${O(n)}' completed: ${o} successful`);}},Fs=(e,t,n)=>{let i=Object.values(e).flatMap(r=>r.canonicalResolution[t]);if(!i)throw new Error(`No canonical resolution found for ${t} in any package`);return i[0]?.resource},Bn=async(e,{logger:t,focusedPackages:n})=>{let i=n??await e.packages(),r={};for(let f of i)await Yi(e,f,0,r,t);$s(r,t);let o=(f,m)=>{let g=r[O(f)];if(g){let y=g.canonicalResolution[m]?.[0];if(y)return r[y.pkgId]?.fhirSchemas[m]}for(let y of Object.values(r)){let h=y.fhirSchemas[m];if(h&&h.package_meta.name===f.name)return h}for(let y of Object.values(r)){let h=y.fhirSchemas[m];if(h)return h}},s=(f,m)=>{let g=r[O(f)];if(g){let y=g.canonicalResolution[m]?.[0];if(y)return r[y.pkgId]?.valueSets[m]}for(let y of Object.values(r)){let h=y.valueSets[m];if(h&&h.package_meta.name===f.name)return h}for(let y of Object.values(r)){let h=y.valueSets[m];if(h)return h}},a=f=>(f.includes("|")&&(f=f.split("|")[0]),Wi.test(f)?`http://hl7.org/fhir/StructureDefinition/${f}`:f),c=(f,m)=>{let g=o(f,m);if(g===void 0)throw new Error(`Failed to resolve FHIR Schema: '${m}'`);let y=[g];for(;g?.base;){let h=g.package_meta,x=a(g.base);if(g.kind==="logical"&&g.derivation==="specialization"&&Dn(g.base))break;if(g=o(h,x),g===void 0)throw new Error(`Failed to resolve FHIR Schema base for '${m}'. Problem: '${x}' from '${O(h)}'`);y.push(g);}return y},l=(f,m)=>c(f,m).filter(g=>g.derivation==="specialization"),p=(f,m)=>{let g=c(f.package_meta,f.url),y=Ht(g,m);return jn(y)},d=f=>{let m=new Set;for(let[g,y]of Object.entries(f)){m.add(g);for(let h of y?.choices||[])f[h]||m.add(h);}return Array.from(m)},u;return {testAppendFs(f){let m=O(f.package_meta);r[m]||(r[m]=Ki(f.package_meta)),r[m].fhirSchemas[f.url]=f,u=void 0;},resolveFs:o,resolveFsGenealogy:c,resolveFsSpecializations:l,ensureSpecializationCanonicalUrl:a,resolveSd:(f,m)=>{let g=r[O(f)]?.canonicalResolution[m]?.[0]?.resource;if(isStructureDefinition(g))return g},allSd:()=>Object.values(r).flatMap(f=>Object.values(f.canonicalResolution).flatMap(m=>m.map(g=>{let y=g.resource;return y.package_name?y:{...y,package_name:g.pkg.name,package_version:g.pkg.version}}))).filter(f=>isStructureDefinition(f)).sort((f,m)=>f.url.localeCompare(m.url)),allFs:()=>Object.values(r).flatMap(f=>Object.values(f.fhirSchemas)),allVs:()=>Object.values(r).flatMap(f=>Object.values(f.valueSets)),allTerminology:()=>Object.values(r).map(({pkg:f,terminology:m})=>({packageMeta:f,resources:m})).sort((f,m)=>H(f.packageMeta).localeCompare(H(m.packageMeta))),resolveVs:s,resolveAny:f=>Fs(r,f),resolveElementSnapshot:p,getAllElementKeys:d,resolver:r,resolutionTree:()=>{if(u)return u;let f={};for(let[m,g]of Object.entries(r)){let y=g.pkg.name;f[y]={};for(let[h,x]of Object.entries(g.canonicalResolution)){let k=h;f[y][k]=[];for(let $ of x)f[y][k].push({deep:$.deep,pkg:$.pkg});}}return u=f,f}}},Zi=async(e,t)=>{let n=e.map(H);t?.logger?.info(`Loading FHIR packages: ${n.join(", ")}`);let i=CanonicalManager({packages:n,workingDir:".codegen-cache/canonical-manager-cache",registry:t.registry||void 0});return await i.init(),await Bn(i,{...t,focusedPackages:e})},Ht=(e,t)=>{let[n,...i]=t;return n===void 0?[]:e.map(r=>{if(!r.elements)return;let o=r.elements?.[n];for(let s of i)o=o?.elements?.[s];return o}).filter(r=>r!==void 0)};function jn(e){let t=e.reverse(),n=Object.assign({},...t);return n.elements=void 0,n}function Ln(e){let t=e.split("|")[0];return t||e}function Ps(e){return e.split("|")[1]}var Ns=e=>({package:e.package_meta.name,version:e.package_meta.version,name:e.name,url:e.url});function ce(e){let t=Ns(e);return e.derivation==="constraint"?{kind:"profile",...t}:e.kind==="primitive-type"?{kind:"primitive-type",...t}:e.kind==="complex-type"?{kind:"complex-type",...t}:e.kind==="resource"?{kind:"resource",...t}:e.kind==="logical"?{kind:"logical",...t}:{kind:"resource",...t}}var Es=/[-_]/,Os=/^[a-zA-Z0-9_-]{20,}$/,_s=e=>{let t=e.split("/"),n=t[t.length-1];return n&&n.length>0?n.split(Es).map(i=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join(""):e};function Jt(e,t,n){let i=Ln(n),r=_s(i),o={package_meta:{name:"missing_valuesets",version:Ps(i)||"0.0.0"},id:n},s=e.resolveVs(t,i)||o,a=s?.id&&!Os.test(s.id)?s.id:r;return {kind:"value-set",package:s.package_meta.name,version:s.package_meta.version,name:a,url:i}}function Wt(e,t,n){let i=n.binding?.bindingName,r=t.join("."),[o,s,a]=i?[{name:"shared",version:"1.0.0"},i,`urn:fhir:binding:${i}`]:[e.package_meta,`${e.name}.${r}_binding`,`${e.url}#${r}_binding`];return {kind:"binding",package:o.name,version:o.version,name:s,url:a}}function at(e,t,n,i){let r=Ln(n)||n,o=e.resolveVs(t,r);if(o)return Ds(e,o)}function Ds(e,t,n){if(t.expansion?.contains)return t.expansion.contains.filter(r=>r.code!==void 0).map(r=>(xe(r.code),{code:r.code,display:r.display,system:r.system}));let i=[];if(t.compose?.include){for(let r of t.compose.include)if(r.concept)for(let o of r.concept)i.push({system:r.system,code:o.code,display:o.display});else if(r.system&&!r.filter)try{let o=e.resolveAny(r.system);if(o?.concept){let s=(a,c)=>{for(let l of a)i.push({system:c,code:l.code,display:l.display}),l.concept&&s(l.concept,c);};s(o.concept,r.system);}}catch{}}return i.length>0?i:void 0}var Xi=100,Bs=new Set(["UNK"]),An=new Set(["code","Coding","CodeableConcept","CodeableReference","Quantity","string","uri","Duration"]);function Vn(e,t,n,i){if(!n.binding)return;let r=n.binding.strength,o=n.binding.valueSet;if(!o)return;if(!An.has(n.type??"")){i?.dryWarn("#binding",`eld-11: Binding on non-bindable type '${n.type}' (valueSet: ${o})`);return}if(!(r==="required"||r==="extensible"||r==="preferred"))return;let a=at(e,t.package_meta,o);if(!a||a.length===0)return;let c=a.map(p=>p.code).filter(p=>p&&typeof p=="string"&&p.trim().length>0),l=c.length===1?c[0]:void 0;if(l&&Bs.has(l)){i?.dryWarn("#placeholderValueSet",`Value set ${o} only expands to placeholder code '${l}'; skipping enum generation.`);return}if(c.length>Xi){i?.dryWarn("#largeValueSet",`Value set ${o} has ${c.length} which is more than ${Xi} codes, which may cause issues with code generation.`);return}if(c.length!==0)return {isOpen:r!=="required",values:c}}function js(e,t,n,i,r){if(!i.binding?.valueSet)return;let o=Wt(t,n,i),s=Jt(e,t.package_meta,i.binding.valueSet),a=Vn(e,t,i,r);return {identifier:o,valueset:s,strength:i.binding.strength,enum:a,dependencies:[s]}}function Qi(e,t,n){let i=new Set;if(!t.elements)return [];let r=[];function o(c,l){for(let[p,d]of Object.entries(c)){let u=[...l,p],f=u.join("."),m=e.resolveElementSnapshot(t,u);if(!i.has(f)){if(i.add(f),m.binding){let g=js(e,t,u,m,n);g&&r.push(g);}d.elements&&o(d.elements,u);}}}o(t.elements,[]),r.sort((c,l)=>c.identifier.name.localeCompare(l.identifier.name));let s=[],a=new Set;for(let c of r)a.has(c.identifier.url)||(a.add(c.identifier.url),s.push(c));return s}var Ls=e=>{let t=e.replace(/\[x\]/g,"").replace(/[- :.]/g,"_");return t?R(t):""},qt=e=>{let t=e.replace(/\[x\]/g,"").replace(/:/g,"_");return t?R(de(t)):""},As=(e,t)=>{let n=qt(e)||"Extension",i=t.split(".").filter(s=>s&&s!=="extension").join("_"),o=`${i?qt(i):""}${n}`;return [n,o,`${o}Extension`]},Vs=(e,t)=>{let n=Ls(t)||"Slice",r=`${qt(e)||"Field"}${n}`;return [n,r,`${r}Slice`]},ws=(e,t,n)=>e.reduce((i,r)=>{let o=r.candidates[t]??"";return i[o]=(i[o]??0)+1,n.has(o)&&(i[o]=(i[o]??0)+1),i},{}),Gs=(e,t)=>{let n=e[0]?.candidates.length??0,i=(r,o)=>{if(r.length===0||o>=n)return {};let s=ws(r,o,t),a=o>=n-1,[c,l]=r.reduce(([p,d],u)=>{let f=u.candidates[o]??"";return (s[f]??0)>1&&!a?[p,[...d,u]]:[{...p,[u.key]:f},d]},[{},[]]);return {...c,...i(l,o+1)}};return i(e,0)},er=e=>({candidates:As(e.name,e.path),recommended:""}),tr=(e,t)=>({candidates:Vs(e,t),recommended:""}),nr=e=>{let t=(e.extensions??[]).filter(s=>s.url).map(s=>({key:`ext:${s.url}:${s.path}`,candidates:s.nameCandidates.candidates})),n=Object.entries(e.slicing??{}).flatMap(([s,a])=>a.slices?Object.entries(a.slices).map(([c,l])=>({key:`slice:${s}:${c}`,candidates:l.nameCandidates.candidates})):[]),i=new Set(Object.keys(e.fields??{}).map(qt)),r=[...t,...n];if(r.length===0)return;let o=Gs(r,i);for(let s of e.extensions??[]){if(!s.url)continue;let a=`ext:${s.url}:${s.path}`;o[a]&&(s.nameCandidates.recommended=o[a]);}for(let[s,a]of Object.entries(e.slicing??{}))if(a.slices)for(let[c,l]of Object.entries(a.slices)){let p=`slice:${s}:${c}`;o[p]&&(l.nameCandidates.recommended=o[p]);}};var ir=(e,t,n)=>{let i=e.resolveFsSpecializations(t.package_meta,t.url),r=Ht(i,n),o=jn(r).type,s;if(o){let a=e.ensureSpecializationCanonicalUrl(o),l=e.resolveFsGenealogy(t.package_meta,a).flatMap(p=>Object.keys(p.elements??{}));l.length>0&&(s=new Set(l));}for(let a of r)if(!(!a.elements||Object.keys(a.elements).length===0)&&!(s&&!Object.keys(a.elements).some(c=>!s.has(c))))return true;return false},wn=(e,t,n,i,r)=>i.type==="BackboneElement"?true:!r?.elements||r.choiceOf!==void 0?false:ir(e,t,n),Us=e=>e.elements?new Set(Gn(e,[],e.elements).filter(([t,n])=>n.elements&&Object.keys(n.elements).length>0).map(([t])=>t.join("."))):new Set;function Kt(e,t,n){let i={},r=t.derivation==="constraint"?e.resolveFsSpecializations(t.package_meta,t.url):e.resolveFsGenealogy(t.package_meta,t.url);for(let p of [...r].reverse()){let d=Us(p);for(let u of d)i[u]=`${p.url}#${u}`;}let o=n.join("."),s=i[o]??`${t.url}#${o}`,a=s.split("#")[0],l=e.resolveFs(t.package_meta,a)?.package_meta??t.package_meta;return {kind:"nested",package:l.name,version:l.version,name:o,url:s}}function Gn(e,t,n){let i=[];for(let[r,o]of Object.entries(n)){let s=[...t,r];o.elements&&o.choiceOf===void 0&&i.push([s,o]),o.elements&&i.push(...Gn(e,s,o.elements));}return i}function zs(e,t,n,i,r){let o={},s={},a=e.resolveFsGenealogy(t.package_meta,t.url),c=Ht(a,n),l=new Set;for(let p of c)if(p.elements)for(let d of Object.keys(p.elements))l.add(d);for(let p of l){let d=[...n,p],u=e.resolveElementSnapshot(t,d);wn(e,t,d,u,i[p])?o[p]=Xt(e,t,d,u):o[p]=Zt(e,t,d,u,r);let f=Yt(p,u);f&&(s[p]=f);}return {fields:o,slicing:Object.keys(s).length>0?s:void 0}}function rr(e,t,n){if(!t.elements)return;let i=Gn(t,[],t.elements).filter(([o,s])=>!s.elements||Object.keys(s.elements).length===0?false:s.type!=="BackboneElement"?ir(e,t,o):true),r=[];for(let[o,s]of i){let a=Kt(e,t,o),c;s.type==="BackboneElement"||!s.type?c="BackboneElement":c=s.type;let l=e.ensureSpecializationCanonicalUrl(c),p=e.resolveFs(t.package_meta,l);if(!p)throw new Error(`Could not resolve base type ${c}`);let d={kind:"complex-type",package:p.package_meta.name,version:p.package_meta.version,name:c,url:l},{fields:u,slicing:f}=zs(e,t,o,s.elements??{},n),m={identifier:a,base:d,fields:u,slicing:f};r.push(m);}return r.sort((o,s)=>o.identifier.url.localeCompare(s.identifier.url)),r.length===0?void 0:r}function or(e){let t=[];for(let n of e){n.base&&t.push(n.base);for(let i of Object.values(n.fields||{}))"type"in i&&i.type&&t.push(i.type),"binding"in i&&i.binding&&t.push(i.binding);}return t}var Hs=new Set(["Availability","CodeableReference","ExtendedContactDetail","MonetaryComponent","RatioRange","VirtualServiceDetail"]),Js=(e,t)=>{let n=e.resolver[O(t)];if(!n)return false;for(let i of Object.values(n.canonicalResolution))for(let r of i)if(r.pkg.name==="hl7.fhir.r4.core")return true;return false},Ws=(e,t,n)=>!Hs.has(n)||!Js(e,t)?"":`
|
|
9
|
+
hint: '${n}' is an R5+ type and is not available when generating against R4.
|
|
10
|
+
Either exclude this canonical via a CanonicalManager patch (excludeCanonical; see src/api/builtin-patches.ts), or upgrade the target to R5.`;function sr(e,t,n){let i=n[n.length-1];if(!i)throw new Error(`Internal error: fieldName is missing for path ${n.join("/")}`);let r=n.slice(0,-1),o=e.resolveFsGenealogy(t.package_meta,t.url).flatMap(s=>{if(r.length===0)return s.required||[];if(!s.elements)return [];let a=s;for(let c of r)a=a?.elements?.[c];return a?.required||[]});return new Set(o).has(i)}function ar(e,t,n){let i=n[n.length-1];if(!i)throw new Error(`Internal error: fieldName is missing for path ${n.join("/")}`);let r=n.slice(0,-1),o=e.resolveFsGenealogy(t.package_meta,t.url).flatMap(s=>{if(r.length===0)return s.excluded||[];if(!s.elements)return [];let a=s;for(let c of r)a=a?.elements?.[c];return a?.excluded||[]});return new Set(o).has(i)}var qs=(e,t,n)=>{if(!n.refers)return;let i=[],r=[],o=new Set;for(let s of n.refers){let a=e.ensureSpecializationCanonicalUrl(s),c=e.resolveFs(t.package_meta,a);if(!c)throw new Error(`Failed to resolve fs for ${a}`);let l=ce(c),p=l;if(vt(l)){r.push(l);let d=e.resolveFsSpecializations(c.package_meta,c.url)[0];if(!d)throw new Error(`Failed to resolve base specialization for ${a}`);p=ce(d);}o.has(p.url)||(o.add(p.url),i.push(p));}return {resource:i,profiles:r.length>0?r:void 0}},Ks=e=>{let t=new Set,n=new Set;if(e.required)for(let r of e.required)t.add(r);if(e.excluded)for(let r of e.excluded)n.add(r);if(e.elements)for(let[r,o]of Object.entries(e.elements))o.min!==void 0&&o.min>0&&t.add(r);let i=e.elements?Object.keys(e.elements):void 0;return {required:t.size>0?Array.from(t):void 0,excluded:n.size>0?Array.from(n):void 0,elements:i&&i.length>0?i:void 0}},Ys=e=>!e||typeof e=="object"&&Object.keys(e).length===0,Qt=(e,t,n)=>{let i=e;for(let o=0;o<t.length-1;o++){let s=t[o];(!i[s]||typeof i[s]!="object")&&(i[s]={}),i=i[s];}let r=t[t.length-1];i[r]=n;},Zs=(e,t)=>{let n=e;for(let i of t)if(n&&typeof n=="object"&&!Array.isArray(n))n=n[i];else return;return n},cr=(e,t,n,i,r)=>{if(n>=t.length||!e.elements)return;let o=t[n],s=e.elements[o];if(s){if(n===t.length-1&&s.fixed?.value!==void 0){Qt(i,t,s.fixed.value);return}if(s.slicing?.slices){r.add(t.slice(0,n+1).join("."));let a=t.slice(n+1);for(let c of Object.values(s.slicing.slices)){if(!c.min||c.min<1||!c.match||typeof c.match!="object")continue;let l=c.match;if(Object.keys(l).length!==0)if(a.length>0){let p=Zs(l,a);p!==void 0&&Qt(i,t,p);}else Qt(i,t.slice(0,n+1),l);}return}cr(s,t,n+1,i,r);}},Xs=(e,t,n)=>{if(e==="$this")return;let i=e.split("."),r=t;for(let s of i)if(r=r?.elements?.[s],!r)return;let o=r.type;!o||o.includes("/")||Qt(n,i,{resourceType:o});},Qs=(e,t)=>{if(!t||!e||e.length===0)return;let n={},i=new Set;for(let r of e)if(r.type==="type")Xs(r.path,t,n);else {if(!t.elements)continue;let o=r.path.split(".");cr(t,o,0,n,i);}if(Object.keys(n).length!==0){for(let r of i){let o=r.split("."),s=n;for(let c=0;c<o.length-1;c++){let l=s[o[c]];if(!l||typeof l!="object"||Array.isArray(l))break;s=l;}let a=o[o.length-1];s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&(s[a]=[s[a]]);}return n}},Yt=(e,t)=>{let n=t.slicing;if(!n)return;let i={};for(let[r,o]of Object.entries(n.slices??{})){if(!o)continue;let{required:s,excluded:a,elements:c}=o.schema?Ks(o.schema):{};i[r]={min:o.min,max:o.max,match:Ys(o.match)?Qs(n.discriminator??[],o.schema):o.match,required:s,excluded:a,elements:c,nameCandidates:tr(e,r)};}return {discriminator:n.discriminator??[],rules:n.rules,ordered:n.ordered,slices:Object.keys(i).length>0?i:void 0}};function We(e,t,n,i,r){if(i.elementReference){let o=i.elementReference.slice(1).filter((s,a)=>a%2===1);return Kt(e,t,o)}if(i.type){let o=e.ensureSpecializationCanonicalUrl(i.type),s=e.resolveFs(t.package_meta,o);if(!s){let a=O(t.package_meta),c=n.join("."),l=Ws(e,t.package_meta,i.type);throw new Error(`Could not resolve field type:
|
|
5
11
|
package: ${a}
|
|
6
|
-
schema: ${
|
|
12
|
+
schema: ${t.url}
|
|
7
13
|
field: ${c}
|
|
8
|
-
type: ${t.type}${l}`)}return k(s)}t.choices||n.derivation!=="constraint"&&r?.dryWarn("#fieldTypeNotFound",`Can't recognize element type: <${n.url}>.${i.join(".")} (pkg: '${R(n.package_meta)}'): missing type info`);}var j=(e,n,i,t,r,o)=>{let s,a;t.binding&&(s=w(n,i,t),J.has(t.type??"")&&(a=Z(e,n,t,r)));let c=P(e,n,i,t,r);c||r?.dryWarn("#fieldTypeNotFound",`Field type not found for '${n.url}#${i.join(".")}' (${n.derivation})`);let l;t.pattern?l={kind:"pattern",type:t.pattern.type,value:t.pattern.value}:t.fixed&&(l={kind:"fixed",type:t.fixed.type,value:t.fixed.value});let p=o??t;if(!l&&p.elements?.coding?.slicing?.slices){let m=p.elements.coding.slicing.slices,g=Object.values(m);g.length>0&&g.every(u=>u.min!==void 0&&u.min>=1&&u.match&&typeof u.match=="object"&&Object.keys(u.match).length>0)&&(l={kind:"fixed",type:"CodeableConcept",value:{coding:g.flatMap(f=>f.match?[f.match]:[])}});}return {type:c,required:Ne(e,n,i),excluded:De(e,n,i),reference:Rn(e,n,t),array:t.array||false,min:t.min,max:t.max,choices:t.choices,choiceOf:t.choiceOf,binding:s,enum:a,valueConstraint:l,mustSupport:t.mustSupport}};function _(e,n,i,t){return {type:B(e,n,i),array:t.array||false,required:Ne(e,n,i),excluded:De(e,n,i)}}var Fn=(e,n,i,t)=>{let r=e.resolveFs(n.package_meta,i);if(!r?.elements)return;let o=[];for(let[s,a]of Object.entries(r.elements)){if(a.choiceOf!=="value"&&!s.startsWith("value"))continue;let c=P(e,r,[s],a,t);c&&o.push(c);}return E(o)},Tn=(e,n,i)=>{let t=[];if(!n.elements)return t;for(let[r,o]of Object.entries(n.elements)){if(!r.startsWith("extension:"))continue;let s=r.split(":")[1];if(!s)continue;let a;for(let[c,l]of Object.entries(o.elements??{}))if(!(l.choiceOf!=="value"&&!c.startsWith("value"))&&(a=P(e,n,[r,c],l,i),a))break;t.push({name:s,url:o.url??s,valueFieldType:a,min:o.min,max:o.max!==void 0?String(o.max):void 0});}return t},vn=(e,n,i)=>{let t=[],o=n.elements?.extension?.slicing?.slices;if(!o||typeof o!="object")return t;for(let[s,a]of Object.entries(o)){let c=a,l=c.schema;if(!l)continue;let p;for(let[m,g]of Object.entries(l.elements??{})){let d=g;if(!(d.choiceOf!=="value"&&!m.startsWith("value"))&&(p=P(e,n,[m],d,i),p))break}t.push({name:s,url:c.match?.url??s,valueFieldType:p,min:l._required?1:l.min??0,max:l.max!==void 0?String(l.max):l.array?"*":"1"});}return t},En=(e,n,i,t)=>{let r=e.resolveFs(n.package_meta,i);if(!r?.elements)return;let o=Tn(e,r,t),s=vn(e,r,t),a=[...o,...s];return a.length>0?a:void 0},He=(e,n,i)=>{let t=[],r=(c,l,p)=>{let m=p.url,g=m?Fn(e,n,m,i):void 0,d=m?En(e,n,m,i):void 0;if(!m){let S=n.elements?.extension?.slicing?.slices?.[l]?.schema;if(S){m=S.elements?.url?.fixed?.value??l;for(let[x,C]of Object.entries(S.elements??{})){let N=C;if(N.choiceOf==="value"||x.startsWith("value")){let oe=P(e,n,[x],N,i);if(oe){g=[oe];break}}}}}let u=d&&d.length>0,f=m?e.resolveFs(n.package_meta,m):void 0,y=f?k(f):void 0,h=[...c,"extension"].join(".");t.push({name:l,path:h,url:m,profile:y,min:p.min,max:p.max!==void 0?String(p.max):void 0,mustSupport:p.mustSupport,valueFieldTypes:g,subExtensions:d,isComplex:u,nameCandidates:xe({name:l,path:h})});},o=(c,l)=>{if(l.extensions)for(let[p,m]of Object.entries(l.extensions))r(c,p,m);if(l.elements)for(let[p,m]of Object.entries(l.elements))o([...c,p],m);};o([],n);let s=new Set,a=t.filter(c=>{let l=`${c.url}:${c.path}`;return s.has(l)?false:(s.add(l),true)});return a.length===0?void 0:a};function Pn(e,n,i,t,r){if(!t)return {};let o={},s={};for(let a of e.getAllElementKeys(t)){let c=[...i,a],l=e.resolveElementSnapshot(n,c),p=l.type?e.ensureSpecializationCanonicalUrl(l.type):void 0;if(p&&v(n.package_meta,p).shouldSkip){r?.warn("#skipCanonical",`Skipping field ${c} for ${p} due to skip hack ${v(n.package_meta,p).reason}`);continue}ne(e,n,c,l,t[a])?o[a]=_(e,n,c,l):o[a]=j(e,n,c,l,r,t[a]);let m=M(a,l);m&&(s[a]=m);}return {fields:o,slicing:Object.keys(s).length>0?s:void 0}}function Nn(e){let n=[];for(let i of Object.values(e))"type"in i&&i.type&&n.push(i.type),"binding"in i&&i.binding&&n.push(i.binding);return n}async function $e(e,n,i){if(!n.url)throw new Error("ValueSet URL is required");let t=H(e,n.package_meta,n.url),r=Y(e,n.package_meta,n.url);return {identifier:t,description:n.description,concept:r,compose:r?void 0:n.compose}}var Ve=(e,n,i)=>{let t=[];return e&&t.push(e),n&&t.push(...Nn(n)),i&&t.push(...Pe(i)),t},Ue=(e,n,i,t)=>{let o=Ve(n,i,t).filter(s=>!(s.url===e.url||W(s)));return E(o)},Dn=(e,n,i,t)=>{let o=Ve(n,i,t).filter(s=>s.url!==e.url);return E(o)};function Oe(e,n,i){let t;if(n.base){let p=e.resolveFs(n.package_meta,e.ensureSpecializationCanonicalUrl(n.base));if(!p)throw new Error(`Base resource not found '${n.base}' for <${n.url}> from ${R(n.package_meta)}`);let m=k(p);we(!W(m),`Unexpected nested base for ${n.url}`),t=m;}let{fields:r,slicing:o}=Pn(e,n,[],n.elements,i),s=Ee(e,n,i),a=Se(e,n,i);if(n.derivation==="constraint"){let p=k(n);if(!t)throw new Error(`Profile ${n.url} must have a base type`);let m=He(e,n,i),g=m?.flatMap(ge),d=Dn(p,t,r,s),u={identifier:p,base:t,fields:r,slicing:o,nested:s,description:n.description,dependencies:E(d,g),extensions:m};return ke(u),[u,...a]}if(n.kind==="primitive-type"){let p=k(n);return we(t,`Primitive type ${n.url} must have a base type`),[{identifier:p,description:n.description,base:t,dependencies:Ue(p,t,r,s)},...a]}let c=k(n);return [{identifier:c,base:t,fields:r,slicing:o,nested:s,description:n.description,dependencies:Ue(c,t,r,s),typeFamily:void 0},...a]}var Ln=(e,n,i)=>{let t={};for(let s of e){let a=`${s.schema.identifier.url}|${s.schema.identifier.package}`,c=me(s.schema);t[a]??={},t[a][c]??={typeSchema:s.schema,sources:[]},t[a][c].sources.push(s);}let r=[],o={};for(let s of Object.values(t)){let a=Object.entries(s).map(([l,p])=>({...p,schemaHash:l,sources:[...p.sources].sort(z)})).sort(pe),c=a[0];if(c)if(a.length>1){let l=c.typeSchema.identifier.url,p=c.typeSchema.identifier.package;i?.dryWarn("#duplicateSchema",`'${l}' from '${p}' has ${a.length} versions`),r.push(c.typeSchema);o[p]??={},o[p][l]=a.flatMap(g=>g.sources.map(d=>({typeSchema:g.typeSchema,sourcePackage:d.sourcePackage,sourceCanonical:d.sourceCanonical})));}else r.push(c.typeSchema);}return {schemas:r,collisions:o}},Be=async(e,n,i)=>{let t=[];for(let r of e.allFs()){let o=R(r.package_meta),s=v(r.package_meta,r.url);if(s.shouldSkip){i?.dryWarn("#skipCanonical",`Skip ${r.url} from ${o}. Reason: ${s.reason}`);continue}for(let a of Oe(e,r,i))t.push({schema:a,sourcePackage:o,sourceCanonical:r.url});}for(let r of e.allVs())t.push({schema:await $e(e,r),sourcePackage:R(r.package_meta),sourceCanonical:r.url});return Ln(t,n,i)};var Me={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 e=>{let n=I({prefix:"TypeSchema"});try{n.info("Generating TypeSchema from FHIR packages"),n.info(`Packages: ${e.packages.join(", ")}`),n.info(`Output: ${e.output}`);let i=e.singleFile?"ndjson":e.format;n.debug(`Format: ${i}${e.singleFile&&e.format==="json"?" (forced from json due to singleFile)":""}`),e.treeshake&&e.treeshake.length>0&&n.info(`Treeshaking enabled for ResourceTypes: ${e.treeshake.join(", ")}`),e.singleFile&&n.info("Single file output enabled (NDJSON format)"),e.registry&&n.info(`Using custom registry: ${e.registry}`);let t=Date.now(),r=e.packages.map(p=>{if(p.includes("@")){let m=p.lastIndexOf("@");return {name:p.slice(0,m),version:p.slice(m+1)||"latest"}}return {name:p,version:"latest"}});n.info(`Processing packages: ${r.map(p=>`${p.name}@${p.version}`).join(", ")}`);let o=await Te(r,{logger:n,registry:e.registry,focusedPackages:r}),{schemas:s}=await Be(o,void 0,n);if(s.length===0)throw new Error("No schemas were generated from the specified packages");let a=e.output;if(!a)throw new Error("Output format not specified");await mkdir(dirname(a),{recursive:!0});let c;i==="json"?c=JSON.stringify(s,null,2):c=s.map(p=>JSON.stringify(p)).join(`
|
|
9
|
-
`),
|
|
14
|
+
type: ${i.type}${l}`)}return ce(s)}i.choices||t.derivation!=="constraint"&&r?.dryWarn("#fieldTypeNotFound",`Can't recognize element type: <${t.url}>.${n.join(".")} (pkg: '${O(t.package_meta)}'): missing type info`);}var Zt=(e,t,n,i,r,o)=>{let s,a;i.binding&&(s=Wt(t,n,i),An.has(i.type??"")&&(a=Vn(e,t,i,r)));let c=We(e,t,n,i,r);c||r?.dryWarn("#fieldTypeNotFound",`Field type not found for '${t.url}#${n.join(".")}' (${t.derivation})`);let l;i.pattern?l={kind:"pattern",type:i.pattern.type,value:i.pattern.value}:i.fixed&&(l={kind:"fixed",type:i.fixed.type,value:i.fixed.value});let p=o??i;if(!l&&p.elements?.coding?.slicing?.slices){let d=p.elements.coding.slicing.slices,u=Object.values(d);if(u.length>0&&u.every(m=>m.min!==void 0&&m.min>=1&&m.match&&typeof m.match=="object"&&typeof m.match.system=="string")){let m=u.flatMap(y=>y.match?[y.match]:[]);l=u.every(y=>typeof y.match.code=="string")?{kind:"fixed",type:"CodeableConcept",value:{coding:m}}:{kind:"pattern",type:"CodeableConcept",value:{coding:m},validateOnly:true};}}return {type:c,required:sr(e,t,n),excluded:ar(e,t,n),reference:qs(e,t,i),array:i.array||false,min:i.min,max:i.max,choices:i.choices,choiceOf:i.choiceOf,binding:s,enum:a,valueConstraint:l,mustSupport:i.mustSupport}};function Xt(e,t,n,i){return {type:Kt(e,t,n),array:i.array||false,required:sr(e,t,n),excluded:ar(e,t,n)}}var ea=(e,t,n,i)=>{let r=e.resolveFs(t.package_meta,n);if(!r?.elements)return;let o=[];for(let[s,a]of Object.entries(r.elements)){if(a.choiceOf!=="value"&&!s.startsWith("value"))continue;let c=We(e,r,[s],a,i);c&&o.push(c);}return fe(o)},ta=(e,t,n)=>{let i=[];if(!t.elements)return i;for(let[r,o]of Object.entries(t.elements)){if(!r.startsWith("extension:"))continue;let s=r.split(":")[1];if(!s)continue;let a;for(let[c,l]of Object.entries(o.elements??{}))if(!(l.choiceOf!=="value"&&!c.startsWith("value"))&&(a=We(e,t,[r,c],l,n),a))break;i.push({name:s,url:o.url??s,valueFieldType:a,min:o.min,max:o.max!==void 0?String(o.max):void 0});}return i},na=(e,t,n)=>{let i=[],o=t.elements?.extension?.slicing?.slices;if(!o||typeof o!="object")return i;for(let[s,a]of Object.entries(o)){let c=a,l=c.schema;if(!l)continue;let p;for(let[d,u]of Object.entries(l.elements??{})){let f=u;if(!(f.choiceOf!=="value"&&!d.startsWith("value"))&&(p=We(e,t,[d],f,n),p))break}i.push({name:s,url:c.match?.url??s,valueFieldType:p,min:l._required?1:l.min??0,max:l.max!==void 0?String(l.max):l.array?"*":"1"});}return i},ia=(e,t,n,i)=>{let r=e.resolveFs(t.package_meta,n);if(!r?.elements)return;let o=ta(e,r,i),s=na(e,r,i),a=[...o,...s];return a.length>0?a:void 0},lr=(e,t,n)=>{let i=[],r=(c,l,p)=>{let d=p.url,u=d?ea(e,t,d,n):void 0,f=d?ia(e,t,d,n):void 0;if(!d){let x=t.elements?.extension?.slicing?.slices?.[l]?.schema;if(x){d=x.elements?.url?.fixed?.value??l;for(let[k,$]of Object.entries(x.elements??{})){let q=$;if(q.choiceOf==="value"||k.startsWith("value")){let _e=We(e,t,[k],q,n);if(_e){u=[_e];break}}}}}let m=f&&f.length>0,g=d?e.resolveFs(t.package_meta,d):void 0,y=g?ce(g):void 0,h=[...c,"extension"].join(".");i.push({name:l,path:h,url:d,profile:y,min:p.min,max:p.max!==void 0?String(p.max):void 0,mustSupport:p.mustSupport,valueFieldTypes:u,subExtensions:f,isComplex:m,nameCandidates:er({name:l,path:h})});},o=(c,l)=>{if(l.extensions)for(let[p,d]of Object.entries(l.extensions))r(c,p,d);if(l.elements)for(let[p,d]of Object.entries(l.elements))o([...c,p],d);};o([],t);let s=new Set,a=i.filter(c=>{let l=`${c.url}:${c.path}`;return s.has(l)?false:(s.add(l),true)});return a.length===0?void 0:a};function ra(e,t,n,i,r){if(!i)return {};let o={},s={};for(let a of e.getAllElementKeys(i)){let c=[...n,a],l=e.resolveElementSnapshot(t,c);wn(e,t,c,l,i[a])?o[a]=Xt(e,t,c,l):o[a]=Zt(e,t,c,l,r,i[a]);let p=Yt(a,l);p&&(s[a]=p);}return {fields:o,slicing:Object.keys(s).length>0?s:void 0}}function oa(e){let t=[];for(let n of Object.values(e))"type"in n&&n.type&&t.push(n.type),"binding"in n&&n.binding&&t.push(n.binding);return t}async function dr(e,t,n){if(!t.url)throw new Error("ValueSet URL is required");let i=Jt(e,t.package_meta,t.url),r=at(e,t.package_meta,t.url);return {identifier:i,description:t.description,concept:r,compose:r?void 0:t.compose}}var fr=(e,t,n)=>{let i=[];return e&&i.push(e),t&&i.push(...oa(t)),n&&i.push(...or(n)),i},en=(e,t,n,i)=>{let o=fr(t,n,i).filter(s=>!(s.url===e.url||L(s)));return fe(o)},Un=(e,t,n,i)=>{let o=fr(t,n,i).filter(s=>s.url!==e.url);return fe(o)};function ur(e,t,n){let i;if(t.base){let p=e.ensureSpecializationCanonicalUrl(t.base),d=e.resolveFs(t.package_meta,p),u=t.kind==="logical"&&t.derivation==="specialization"&&Dn(t.base);if(!d&&!u)throw new Error(`Base resource not found '${t.base}' for <${t.url}> from ${O(t.package_meta)}`);if(d){let f=ce(d);xe(!L(f),`Unexpected nested base for ${t.url}`),i=f;}}let{fields:r,slicing:o}=ra(e,t,[],t.elements,n),s=rr(e,t,n),a=Qi(e,t,n);if(t.derivation==="constraint"){let p=ce(t);if(!i)throw new Error(`Profile ${t.url} must have a base type`);let d=lr(e,t,n),u=d?.flatMap(Pt),f=Un(p,i,r,s),m={identifier:p,base:i,fields:r,slicing:o,nested:s,description:t.description,dependencies:fe(f,u),extensions:d};return nr(m),[m,...a]}if(t.kind==="primitive-type"){let p=ce(t);return xe(i,`Primitive type ${t.url} must have a base type`),[{identifier:p,description:t.description,base:i,dependencies:en(p,i,r,s)},...a]}let c=ce(t);return [{identifier:c,base:i,fields:r,slicing:o,nested:s,description:t.description,dependencies:en(c,i,r,s),typeFamily:void 0},...a]}var sa=(e,t,n)=>{let i={};for(let s of e){let a=`${s.schema.identifier.url}|${s.schema.identifier.package}`,c=kt(s.schema);i[a]??={},i[a][c]??={typeSchema:s.schema,sources:[]},i[a][c].sources.push(s);}let r=[],o={};for(let s of Object.values(i)){let a=Object.entries(s).map(([l,p])=>({...p,schemaHash:l,sources:[...p.sources].sort(ot)})).sort(Ut),c=a[0];if(c)if(a.length>1){let l=c.typeSchema.identifier.url,p=c.typeSchema.identifier.package,d=t?.[l];if(d){let u=a.flatMap(m=>m.sources),f=a.find(m=>m.sources.some(g=>g.sourceCanonical===d.canonical&&g.sourcePackage===d.package));f?r.push(f.typeSchema):(n?.dryWarn("#resolveCollisionMiss",`'${l}': preferred source '${d.canonical}' from '${d.package}' not found among variants: ${u.map(m=>`${m.sourceCanonical} (${m.sourcePackage})`).join(", ")}`),r.push(c.typeSchema));}else n?.dryWarn("#duplicateSchema",`'${l}' from '${p}' has ${a.length} versions`),r.push(c.typeSchema);o[p]??={},o[p][l]=a.flatMap(u=>u.sources.map(f=>({typeSchema:u.typeSchema,sourcePackage:f.sourcePackage,sourceCanonical:f.sourceCanonical})));}else r.push(c.typeSchema);}return {schemas:r,collisions:o}},tn=async(e,t,n)=>{let i=[];for(let r of e.allFs()){let o=O(r.package_meta);for(let s of ur(e,r,n))i.push({schema:s,sourcePackage:o,sourceCanonical:r.url});}for(let r of e.allVs())i.push({schema:await dr(e,r),sourcePackage:O(r.package_meta),sourceCanonical:r.url});return sa(i,t,n)};var mr=(e,t)=>{let n=Object.fromEntries(Object.entries(t).map(([l,p])=>[l,new Set(p)])),i=l=>`${l.package}-${l.version}-${l.kind}-${l.url}`,r=Object.fromEntries(e.schemas.map(l=>{if(n[l.identifier.package]?.has(l.identifier.url)){if(!je(l))throw new Error(`Unexpected schema kind: ${JSON.stringify(l.identifier)}`);return [i(l.identifier),{...l.identifier,kind:"resource"}]}}).filter(l=>l!==void 0)),o=l=>r[i(l)]||l,s=l=>{if(l)return Object.fromEntries(Object.entries(l).map(([p,d])=>b(d)?[p,d]:[p,{...d,type:d.type?o(d.type):void 0}]))},a=e.schemas.map(l=>{if($t(l)||Ft(l))return l;let p=JSON.parse(JSON.stringify(l));return p.identifier=o(p.identifier),p.dependencies=p.dependencies?.map(o),(_(p)||V(p))&&(p.fields=s(p.fields),p.nested=p.nested?.map(d=>({...d,base:o(d.base),fields:s(d.fields)}))),p}),c=e.replaceSchemas(a);return c.irReport().logicalPromotion={packages:Object.fromEntries(Object.entries(t).map(([l,p])=>[l,{promotedCanonicals:[...p].sort()}]))},c};var aa=(e,t)=>{let n={},i={};for(let r of t){let o=e.fields?.[r];if(!e.fields||!o)throw new Error(`Field ${r} not found`);if(b(o))i[r]||(i[r]={}),i[r].declaration=o.choices;else if(A(o)){let s=o.choiceOf;i[s]||(i[s]={}),i[s].instances=[...i[s].instances??[],r];}else n[r]=o;}for(let[r,{declaration:o,instances:s}]of Object.entries(i)){let a=s??o;xe(a);for(let l of a){let p=e.fields?.[l];xe(p),n[l]=p;}let c=e.fields?.[r];xe(c),n[r]={...c,choices:a};}e.fields=n;},ca=(e,t)=>{for(let n of t){let i=e.fields?.[n];if(!e.fields||!i)throw new Error(`Field ${n} not found`);if(e.fields){if(b(i))for(let r of i.choices)delete e.fields[r];if(A(i)){let r=e.fields[i.choiceOf];xe(b(r)),r.choices=r.choices.filter(o=>o!==n),r.choices.length===0&&delete e.fields[i.choiceOf];}delete e.fields[n];}}},la=(e,t)=>{if(e.extensions){for(let n of t)if(!e.extensions.some(i=>i.url===n))throw new Error(`Extension ${n} not found in profile ${e.identifier.url}`);e.extensions=e.extensions.filter(n=>!n.url||!t.includes(n.url)),e.extensions.length===0&&(e.extensions=void 0);}},pa=(e,t,n)=>{let i=Object.keys(t.schemasByPackage),r=Object.keys(n.schemasByPackage),o=i.filter(s=>!r.includes(s));e.skippedPackages=o;for(let[s,a]of Object.entries(n.schemasByPackage)){if(o.includes(s))continue;let c=t.schemasByPackage[s];xe(c),e.packages[s]={skippedCanonicals:c.filter(l=>!a.includes(l)).map(l=>l.identifier.url).sort(),canonicals:Object.fromEntries(a.map(l=>{let p=t.resolve(l.identifier);if(xe(p),!_(p)||(xe(_(l)),!p.fields))return;if(!l.fields)return [l.identifier.url,Object.keys(p.fields)];let d=Object.keys(l.fields),u=Object.keys(p.fields).filter(f=>!d.includes(f)).sort();if(u.length!==0)return [l.identifier.url,{skippedFields:u}]}).filter(l=>l!==void 0))};}},da=(e,t,n)=>{if(e=JSON.parse(JSON.stringify(e)),$t(e)||Ft(e)||gi(e)||te(e))return e;if(t.selectFields){if(t.ignoreFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");aa(e,t.selectFields);}if(t.ignoreFields){if(t.selectFields)throw new Error("Cannot use both ignoreFields and selectFields in the same rule");ca(e,t.ignoreFields);}if(V(e)&&t.ignoreExtensions&&la(e,t.ignoreExtensions),e.slicing){let i=Object.fromEntries(Object.entries(e.slicing).filter(([r])=>e.fields?.[r]));e.slicing=Object.keys(i).length>0?i:void 0;}if(e.nested){let i=new Set,r=o=>{Object.values(o.fields??{}).filter(j).filter(s=>L(s.type)).forEach(s=>{let a=s.type.url;if(!i.has(a)){i.add(a);let c=e.nested?.find(l=>l.identifier.url===a);xe(c),r(c);}});};r(e),e.nested=e.nested.filter(o=>i.has(o.identifier.url));}if(V(e)){let i=e.extensions?.flatMap(Pt);e.dependencies=fe(Un(e.identifier,e.base,e.fields,e.nested),i);}else xe(!L(e.identifier)),e.dependencies=en(e.identifier,e.base,e.fields,e.nested);return e},fa=e=>!_(e)&&!V(e)?[]:[e.fields,...(e.nested??[]).map(n=>n.fields)].flatMap(n=>Object.values(n??{}).filter(j).flatMap(i=>[...i.reference?.resource??[],...i.reference?.profiles??[]]).filter(i=>!L(i))),gr=(e,t,n)=>{let i=[],r=[];for(let[d,u]of Object.entries(t))for(let[f,m]of Object.entries(u)){let g=e.resolveByUrl(d,f);if(!g||he(g))throw new Error(`Schema not found for ${d} ${f}`);let y=da(g,m);if(i.push(y),m.followReferences??n?.followReferences)for(let h of fa(y)){let x=e.resolve(h);if(!x)throw new Error(`Reference target ${JSON.stringify(h)} not found for ${d} ${f}`);r.push(x);}}let o=new Set(i.map(d=>JSON.stringify(d.identifier)));for(let d of r)o.has(JSON.stringify(d.identifier))||i.push(d);let s=(d,u)=>{if(d.length===0)return Object.values(u);for(let m of d)u[JSON.stringify(m.identifier)]=m;let f=[];for(let m of d)if(_(m)||V(m)){if(!m.dependencies)continue;m.dependencies.forEach(g=>{if(L(g))return;let y=e.resolve(g);if(!y)throw new Error(`Dependent schema ${JSON.stringify(g)} not found for ${JSON.stringify(m.identifier)}`);let h=JSON.stringify(y.identifier);u[h]||f.push(y);});}return s(f,u)},a=s(i,{}),c=e.replaceSchemas(a),l={skippedPackages:[],packages:{}},p=c.irReport();return p.treeShake=l,pa(l,e,c),c};var Re=e=>{let t=e.replace(/[^a-zA-Z0-9\-_.@#()]/g,"");return t.length===0?"unknown":t},yr=(e,t)=>{let n=Re(e.identifier.package),i=te(e)?".snapshot":"",r=Re(`${e.identifier.name}(${se(e.identifier.url)})`)+i;return {filename:w.join(n,r),genContent:()=>JSON.stringify(e,null,t?2:void 0)}},hr=(e,t)=>{let n=Re(e.package_meta.name),i=Re(`${e.name}(${se(e.url)})`);return {filename:w.join(n,i),genContent:()=>JSON.stringify(e,null,t?2:void 0)}},Sr=(e,t)=>{let n=Re(e.package_name??"unknown"),i=Re(`${e.name}(${se(e.url)})`);return {filename:w.join(n,i),genContent:()=>JSON.stringify({...e,id:void 0},null,t?2:void 0)}},nn=class extends ye{async generate(t){if(this.logger()?.info("IntrospectionWriter: Begin"),this.opts.typeTree&&(await this.writeTypeTree(t),this.logger()?.info(`IntrospectionWriter: Type tree written to ${this.opts.typeTree}`)),this.opts.typeSchemas){let i=typeof this.opts.typeSchemas=="string"?{target:this.opts.typeSchemas}:this.opts.typeSchemas,r=i.profileSnapshots?[...t.schemas,...t.collectSnapshotProfiles()]:t.schemas;if(w.extname(i.target)===".ndjson")await this.writeNdjson(r,i.target,yr);else {let o=r.map(c=>yr(c,true)),s=new Set,a=o.filter(c=>s.has(c.filename)?false:(s.add(c.filename),true));this.cd(i.target,()=>{for(let{filename:c,genContent:l}of a){let p=`${c}.json`;this.cd(w.dirname(p),()=>{this.cat(w.basename(p),()=>{this.write(l());});});}for(let[c,l]of Object.entries(t.irReport().collisions??{}))this.cd(`${Re(c)}`,()=>{for(let[p,d]of Object.entries(l)){if(d.length<=1)continue;let u=d[0];xe(u);let f=Re(`${u.typeSchema.identifier.name}(${se(p)})`);this.cd(w.join("collisions",f),()=>{for(let m=0;m<d.length;m++){let g=d[m];this.cat(`${m+1}.json`,()=>{this.write(JSON.stringify(g,null,2));});}});}});});}this.logger()?.info(`IntrospectionWriter: ${r.length} TypeSchema written to ${i.target}`);}let n=new Set(t.schemas.map(i=>i.identifier.url));if(this.opts.fhirSchemas&&t.register){let i=this.opts.fhirSchemas,r=t.register.allFs(),o=new Set,s=r.filter(a=>!n.has(a.url)||o.has(a.url)?false:(o.add(a.url),true));w.extname(i)===".ndjson"?await this.writeNdjson(s,i,hr):await this.writeJsonFiles(s.map(a=>hr(a,true)),i),this.logger()?.info(`IntrospectionWriter: ${s.length} FHIR schema written to ${i}`);}if(this.opts.structureDefinitions&&t.register){let i=this.opts.structureDefinitions,r=t.register.allSd(),o=new Set,s=r.filter(a=>!n.has(a.url)||o.has(a.url)?false:(o.add(a.url),true));w.extname(i)===".ndjson"?await this.writeNdjson(s,i,Sr):await this.writeJsonFiles(s.map(a=>Sr(a,true)),i),this.logger()?.info(`IntrospectionWriter: ${s.length} StructureDefinitions written to ${i}`);}}async writeNdjson(t,n,i){this.cd(w.dirname(n),()=>{this.cat(w.basename(n),()=>{for(let r of t){let{genContent:o}=i(r,false);this.write(`${o()}
|
|
15
|
+
`);}});});}async writeJsonFiles(t,n){this.cd(n,()=>{for(let{filename:i,genContent:r}of t){let o=`${i}.json`;this.cd(w.dirname(o),()=>{this.cat(w.basename(o),()=>{this.write(r());});});}});}async writeTypeTree(t){let n=this.opts.typeTree;if(!n)return;let i=t.entityTree(),r=n.endsWith(".yaml")?vi__default.stringify(i):JSON.stringify(i,void 0,2),o=w.dirname(n),s=w.basename(n);this.cd(o,()=>{this.cat(s,()=>{this.write(r);});});}};var ga=(e,t)=>{e.push("## Skipped Packages","");for(let n of [...t].sort())e.push(`- ${n}`);e.push("");},ya=(e,t,n,i)=>{if(e.push(`## Package: \`${t}\``,""),i?.length){e.push("### Promoted Logical Models","");for(let o of i)e.push(`- \`${o}\``);e.push("");}if(!n)return;let r=Object.entries(n.canonicals).filter(([o,s])=>s.skippedFields.length>0);if(r.length>0){e.push("### Modified Canonicals","");for(let[o,s]of r){e.push(`#### \`${o}\``,""),e.push("Skipped fields:","");for(let a of s.skippedFields)e.push(`- \`${a}\``);e.push("");}}if(n.skippedCanonicals.length>0){e.push("### Skipped Canonicals","");for(let o of n.skippedCanonicals)e.push(`- \`${o}\``);e.push("");}},ha=(e,t)=>{let n=new Map;for(let o of e){let s=kt(o.typeSchema);n.has(s)||n.set(s,[]),n.get(s)?.push(o);}let i=[...n.entries()].map(([o,s])=>({entries:[...s].sort(ot),schemaHash:o,sources:s})).sort(Ut).map(o=>o.entries),r=(o,s)=>t?o.some(a=>a.sourceCanonical===t.canonical&&a.sourcePackage===t.package)?"selected":void 0:s===0?"auto":void 0;return i.map((o,s)=>({entries:o,mark:r(o,s)}))},Sa={selected:" (selected)",auto:" (auto)"},Ta=e=>{let t=1;return e.map(n=>{let i=n.entries.map(o=>`${se(o.sourceCanonical)??o.sourceCanonical} (${o.sourcePackage})`).sort().join(", "),r=n.mark?Sa[n.mark]:"";return ` - Version ${t++}${r}: ${i}`})},xa=(e,t,n)=>{if(!t)return;e.push("## Schema Collisions",""),e.push("The following canonicals have multiple schema versions with different content."),e.push("To inspect collision versions, export TypeSchemas using `.introspection({ typeSchemas: 'path' })`"),e.push("and check `<pkg>/collisions/<name>/1.json, 2.json, ...` files.","");let i=[],r=Object.keys(t).sort();for(let o of r){let s=t[o];if(!s)throw new Error(`Missing collisions for package ${o}`);let a=Object.entries(s).sort(([c],[l])=>{let p=c.split("/").pop()??c,d=l.split("/").pop()??l;return p.localeCompare(d)});if(a.length>0){e.push(`### \`${o}\``,"");for(let[c,l]of a){let p=ha(l,n?.[c]),d=Ta(p);e.push(`- \`${c}\` (${p.length} versions)`),e.push(...d),l[0]&&i.push({url:c,firstSource:l[0]});}e.push("");}}if(i.length>0){let o=i.filter(s=>!n?.[s.url]);if(o.length>0){e.push("### Suggested `resolveCollisions` config",""),e.push("Add to `.typeSchema({ resolveCollisions: { ... } })` to resolve remaining collisions:",""),e.push("```typescript"),e.push(".typeSchema({"),e.push(" resolveCollisions: {");for(let{url:s,firstSource:a}of o)e.push(` "${s}": {`),e.push(` package: "${a.sourcePackage}",`),e.push(` canonical: "${a.sourceCanonical}",`),e.push(" },");e.push(" },"),e.push("})"),e.push("```","");}}},Tr=e=>{let t=["# IR Report",""],n=[...new Set([...Object.keys(e.treeShake?.packages??{}),...Object.keys(e.logicalPromotion?.packages??{})])].sort(),i=n.length>0||(e.treeShake?.skippedPackages.length??0)>0,r=Object.keys(e.collisions??{}).length>0;if(!i&&!r)return t.push("No IR modifications applied."),t.join(`
|
|
16
|
+
`);e.treeShake?.skippedPackages.length&&ga(t,e.treeShake.skippedPackages);for(let o of n)ya(t,o,e.treeShake?.packages[o],e.logicalPromotion?.packages[o]?.promotedCanonicals);return r&&xa(t,e.collisions,e.resolveCollisions),t.join(`
|
|
17
|
+
`)};var rn=class extends ye{async generate(t){let n=t.irReport(),i=Tr(n);this.cd("/",()=>{this.cat(this.opts.rootReadmeFileName,()=>{this.write(i);});});}};var on=class{constructor(t){this.mode=t;}mode;apply(t){return this._addDebug(t)}_addDebug(t){if(Array.isArray(t))return t.map(n=>this._addDebug(n));if(t!==null&&typeof t=="object"){let n=t,i={},r=JSON.stringify(n,null,this.mode==="FORMATTED"?2:void 0);for(let[o,s]of Object.entries(n))i[o]=this._addDebug(s);return i.debug=r,i}return t}};var sn=class{constructor(t){this.nameGenerator=t;this.lambda={saveTypeName:()=>(n,i)=>this.nameGenerator.generateType(i(n)),saveEnumValueName:()=>(n,i)=>this.nameGenerator.generateEnumValue(i(n)),saveFieldName:()=>(n,i)=>this.nameGenerator.generateField(i(n)),camelCase:()=>(n,i)=>de(i(n)),snakeCase:()=>(n,i)=>P(i(n)),pascalCase:()=>(n,i)=>z(i(n)),kebabCase:()=>(n,i)=>xt(i(n)),lowerCase:()=>(n,i)=>i(n).toLowerCase(),upperCase:()=>(n,i)=>i(n).toUpperCase()};}nameGenerator;lambda;apply(t){return {...t,lambda:this.lambda}}};var an=class{constructor(t,n,i,r){this.keywords=t;this.typeMap=n;this.nameTransformations=i;this.unsaveCharacterPattern=r;}keywords;typeMap;nameTransformations;unsaveCharacterPattern;_replaceUnsaveChars(t){let n=this.unsaveCharacterPattern instanceof RegExp?this.unsaveCharacterPattern:new RegExp(this.unsaveCharacterPattern,"g");return t.replace(n,"_")}_applyNameTransformations(t,n){for(let i of this.nameTransformations.common)t=t.replace(i.pattern instanceof RegExp?i.pattern:new RegExp(i.pattern,"g"),i.format);for(let i of n)t=t.replace(i.pattern instanceof RegExp?i.pattern:new RegExp(i.pattern,"g"),i.format);return t}_generateTypeName(t){if(this.typeMap[t])t=this.typeMap[t];else {if(t=this._applyNameTransformations(t,this.nameTransformations.type),t=t.charAt(0).toUpperCase()+t.slice(1),this.keywords.has(t))return `_${t}`;t=this._replaceUnsaveChars(t);}return t}generateEnumType(t){return this._generateTypeName(t)}_generateTypeFromTypeRef(t){return t.kind==="primitive-type"?this._generateTypeName(t.name):this._generateTypeName(t.url.split("/").pop()?.split("#").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")??"<UNKNOWN>")}generateFieldType(t){return t.enum?this.generateEnumType(t.binding?.name??t.type.name):this._generateTypeFromTypeRef(t.type)}generateType(t){return typeof t=="string"?this._generateTypeName(t):"url"in t?this._generateTypeFromTypeRef(t):this._generateTypeFromTypeRef(t.identifier)}generateField(t){return t=this._applyNameTransformations(t,this.nameTransformations.field),this.keywords.has(t)?`_${t}`:(t=this._replaceUnsaveChars(t),t)}generateEnumValue(t){return t=this._applyNameTransformations(t,this.nameTransformations.enumValue),this.keywords.has(t)?`_${t}`:(t=this._replaceUnsaveChars(t).toUpperCase(),t)}};var cn=class{templateBaseDir;templateCache={};constructor(t){this.templateBaseDir=w__default.resolve(t);}_normalizeName(t){return t.endsWith(".mustache")?t:`${t}.mustache`}read(t){return this.readTemplate(t.source)}readTemplate(t){let n=this._normalizeName(t);return this.templateCache[n]||(this.templateCache[n]=U__default.readFileSync(w__default.join(this.templateBaseDir,n),"utf-8")),this.templateCache[n]}};var ln=class e{static _array(t){return Array.isArray(t)?t:Array.from(t)}apply(t){return this._addListElementInformation(t)}_addListElementInformation(t){if(Array.isArray(t)||t instanceof Set)return e._array(t).map((n,i,r)=>typeof n=="object"&&n!==null?{...this._addListElementInformation(n),"-index":i,"-length":r.length,"-first":i===0,"-last":i===r.length-1}:n);if(t!==null&&typeof t=="object"){let n=t,i={};for(let[r,o]of Object.entries(n))i[r]=this._addListElementInformation(o);return i}return t}};var Cr=["boolean","instant","time","date","dateTime","decimal","integer","unsignedInt","positiveInt","integer64","base64Binary","uri","url","canonical","oid","uuid","string","code","markdown","id","xhtml"];var pn=class{constructor(t,n,i){this.tsIndex=t;this.nameGenerator=n;this.filterPred=i;}tsIndex;nameGenerator;filterPred;arrayMixinProvider=new ln;createUtility(){return this._createForRoot()}createComplexType(t,n={resourcesByUri:{},complexTypesByUri:{}}){let i=this._createForComplexType(t,n),r=this._createParentsFor(i.schema,n),o=this._createChildrenFor(t,n),s=r.flatMap(a=>a.fields);return this.arrayMixinProvider.apply({...this._createForRoot(),...i,parents:r,children:o,inheritedFields:s,allFields:[...i.fields,...r.flatMap(a=>a.fields)],hasChildren:o.length>0,hasParents:r.length>0,hasInheritedFields:s.length>0})}createResource(t,n={resourcesByUri:{},complexTypesByUri:{}}){let i=this._createForResource(t,n),r=this._createParentsFor(i.schema,n),o=this._createChildrenFor(t,n),s=r.flatMap(a=>a.fields);return this.arrayMixinProvider.apply({...this._createForRoot(),...i,parents:r,children:o,inheritedFields:s,allFields:[...i.fields,...s],hasChildren:o.length>0,hasParents:r.length>0,hasInheritedFields:s.length>0})}_createFor(t,n,i){if(t.kind==="complex-type")return this._createForComplexType(t,n,i);if(t.kind==="resource")return this._createForResource(t,n,i);throw new Error(`Unknown type ${t.kind}`)}_createForComplexType(t,n,i){let r=this.tsIndex.resolveType(t);if(!r)throw new Error(`ComplexType ${t.name} not found`);Object.hasOwn(n.complexTypesByUri,r.identifier.url)||(n.complexTypesByUri[r.identifier.url]=this._createTypeViewModel(r,n,i));let o=n.complexTypesByUri[r.identifier.url];if(!o)throw new Error(`ComplexType ${t.name} not found`);return o}_createForResource(t,n,i){let r=this.tsIndex.resolveType(t);if(!r)throw new Error(`Resource ${t.name} not found`);Object.hasOwn(n.resourcesByUri,r.identifier.url)||(n.resourcesByUri[r.identifier.url]=this._createTypeViewModel(r,n,i));let o=n.resourcesByUri[r.identifier.url];if(!o)throw new Error(`Resource ${t.name} not found`);return o}_createChildrenFor(t,n,i){let r=this.tsIndex.resolveType(t);return r?It(r)?(r.typeFamily?.complexTypes??[]).filter(this.filterPred).map(o=>this._createFor(o,n,i)):ee(r)?(r.typeFamily?.resources??[]).filter(this.filterPred).map(o=>this._createFor(o,n,i)):[]:[]}_createParentsFor(t,n){let i=[],r="base"in t?t.base:void 0;for(;r;){i.push(this._createFor(r,n,void 0));let o=this.tsIndex.resolveType(r);r=o&&"base"in o?o.base:void 0;}return i}_createForNestedType(t,n,i){let r=this._createTypeViewModel(t,n,i),o=this._createParentsFor(t,n),s=this._createChildrenFor(t.identifier,n,i),a=o.flatMap(c=>c.fields);return {...r,parents:o,children:s,inheritedFields:a,allFields:[...r.fields,...a],hasChildren:s.length>0,hasParents:o.length>0,hasInheritedFields:a.length>0}}_createTypeViewModel(t,n,i){let r=Object.entries(("fields"in t?t.fields:{})??{}),o=this._collectNestedComplex(t,n),s=this._collectNestedEnums(r),a=this._collectDependencies(t),c={name:t.identifier.name,saveName:this.nameGenerator.generateType(t)};return {nestedComplexTypes:o,nestedEnums:s,dependencies:a,isNested:!!i,schema:t,...c,isResource:this._createIsResource(t.identifier),isComplexType:this._createIsComplexType(t.identifier),hasFields:r.length>0,hasNestedComplexTypes:o.length>0,hasNestedEnums:s.length>0,fields:r.filter(l=>j(l[1])).sort((l,p)=>l[0].localeCompare(p[0])).map(([l,p])=>({owner:c,schema:p,name:l,saveName:this.nameGenerator.generateField(l),typeName:this.nameGenerator.generateFieldType(p),isArray:p.array??false,isRequired:p.required??false,isEnum:!!p.enum&&!p.enum.isOpen,isSizeConstrained:p.min!==void 0||p.max!==void 0,min:p.min,max:p.max,isResource:this._createIsResource(p.type),isComplexType:this._createIsComplexType(p.type),isPrimitive:this._createIsPrimitiveType(p.type),isCode:p.type?.name==="code",isIdentifier:p.type?.name==="Identifier",isReference:p.type?.name==="Reference"}))}}_collectDependencies(t){let n={resources:[],complexTypes:[]};return "dependencies"in t&&t.dependencies&&(t.dependencies.filter(i=>i.kind==="complex-type").map(i=>({name:i.name,saveName:this.nameGenerator.generateType(i)})).forEach(i=>{n.complexTypes.push(i);}),t.dependencies.filter(i=>i.kind==="resource").map(i=>({name:i.name,saveName:this.nameGenerator.generateType(i)})).forEach(i=>{n.resources.push(i);})),"nested"in t&&t.nested&&t.nested.map(i=>this._collectDependencies(i)).forEach(i=>{i.complexTypes.filter(r=>!n.complexTypes.some(o=>o.name===r.name)).forEach(r=>{n.complexTypes.push(r);}),i.resources.filter(r=>!n.resources.some(o=>o.name===r.name)).forEach(r=>{n.resources.push(r);});}),n}_createIsResource(t){return t.kind!=="resource"?false:Object.fromEntries(this.tsIndex.collectResources().map(n=>n.identifier).map(n=>[`is${n.name.charAt(0).toUpperCase()+n.name.slice(1)}`,n.url===t.url]))}_createIsComplexType(t){return t.kind!=="complex-type"&&t.kind!=="nested"?false:Object.fromEntries(this.tsIndex.collectComplexTypes().map(n=>n.identifier).map(n=>[`is${n.name.charAt(0).toUpperCase()+n.name.slice(1)}`,n.url===t.url]))}_createIsPrimitiveType(t){return t.kind!=="primitive-type"?false:Object.fromEntries(Cr.map(n=>[`is${n.charAt(0).toUpperCase()}${n.slice(1)}`,t.name===n]))}_collectNestedComplex(t,n){let i=[];return "nested"in t&&t.nested&&t.nested.map(r=>this._createForNestedType(r,n,t)).forEach(r=>{i.push(r);}),i}_collectNestedEnums(t){let n={};return t.forEach(([i,r])=>{if("enum"in r&&r.enum&&!r.enum.isOpen){let o=("binding"in r&&r.binding?.name)??i;typeof o=="string"&&(n[o]=n[o]??new Set,r.enum.values.forEach(n[o].add.bind(n[o])));}}),Object.entries(n).map(([i,r])=>({name:i,saveName:this.nameGenerator.generateEnumType(i),values:Array.from(r).map(o=>({name:o,saveName:this.nameGenerator.generateEnumValue(o)}))}))}_createForRoot(){return this.arrayMixinProvider.apply({complexTypes:this.tsIndex.collectComplexTypes().map(t=>t.identifier).map(t=>({name:t.name,saveName:this.nameGenerator.generateType(t)})),resources:this.tsIndex.collectResources().map(t=>t.identifier).map(t=>({name:t.name,saveName:this.nameGenerator.generateType(t)}))})}};function va(e,t){let n=w.resolve(e,"config.json");try{let i=U.readFileSync(n,"utf-8"),r=JSON.parse(i);if(r&&typeof r=="object")return r}catch{}return {}}var br=(e,t)=>{let n={debug:"OFF",hooks:{},meta:{},keywords:[],unsaveCharacterPattern:/[^a-zA-Z0-9]/g,nameTransformations:{common:[],enumValue:[],type:[],field:[]},renderings:{utility:[],resource:[],complexType:[]},shouldRunHooks:true,primitiveTypeMap:{}},i=va(e),r={...n,...t,...i,sources:{staticSource:w.resolve(e,"static"),templateSource:w.resolve(e,"templates")}};return new zn(r)};function Ra(e,t=[],n={}){return new Promise((i,r)=>{let o=spawn(e,t,{stdio:"inherit",...n});o.on("error",r),o.on("close",s=>{s===0?i(s):r(new Error(`Prozess beendet mit Fehlercode ${s}`));});})}var zn=class extends ye{templateFileCache;nameGenerator;lambdaMixinProvider;debugMixinProvider;constructor(t){super(t),this.nameGenerator=new an(new Set(t.keywords),t.primitiveTypeMap,t.nameTransformations,t.unsaveCharacterPattern),this.templateFileCache=new cn(t.sources.templateSource),this.lambdaMixinProvider=new sn(this.nameGenerator),this.debugMixinProvider=t.debug!=="OFF"?new on(t.debug):void 0;}async generate(t){let n=new pn(t,this.nameGenerator,()=>true),i={resourcesByUri:{},complexTypesByUri:{}};t.collectComplexTypes().map(r=>r.identifier).sort((r,o)=>r.url.localeCompare(o.url)).map(r=>n.createComplexType(r,i)).forEach(this._renderComplexType.bind(this)),t.collectResources().map(r=>r.identifier).sort((r,o)=>r.url.localeCompare(o.url)).map(r=>n.createResource(r,i)).forEach(this._renderResource.bind(this)),this._renderUtility(n.createUtility()),this.opts.shouldRunHooks&&await this._runHooks(this.opts.hooks.afterGenerate);}async generateAsync(t){await super.generateAsync(t),this.copyStaticFiles();}copyStaticFiles(){if(this.opts.inMemoryOnly)return;let t=w.resolve(this.opts.sources.staticSource);if(!t)throw new Error("staticDir must be set in subclass.");U.cpSync(t,this.opts.outputDir,{recursive:true});}async _runHooks(t){for(let n of t??[])console.info(`Running hook (${this.opts.outputDir}): ${n.cmd} ${n.args?.join(" ")}`),await Ra(n.cmd,n.args??[],{cwd:this.opts.outputDir}),console.info(`Completed hook: ${n.cmd} ${n.args?.join(" ")}`);}_checkRenderingFilter(t,n){return !n.filter?.whitelist?.length&&!n.filter?.blacklist?.length?true:(n.filter?.blacklist??[]).find(i=>t.name.match(i))?false:(n.filter?.whitelist??[]).find(i=>t.name.match(i))?true:!n.filter.whitelist?.length}_renderUtility(t){this.opts.renderings.utility.forEach(n=>{this.cd(n.path,()=>{this.cat(n.fileNameFormat,()=>{this.write(this._render(t,n));});});});}_renderResource(t){this.opts.renderings.resource.filter(n=>this._checkRenderingFilter(t,n)).forEach(n=>{this.cd(n.path,()=>{this.cat(this._calculateFilename(t,n),()=>{this.write(this._render(t,n));});});});}_renderComplexType(t){this.opts.renderings.complexType.filter(n=>this._checkRenderingFilter(t,n)).forEach(n=>{this.cd(n.path,()=>{this.cat(this._calculateFilename(t,n),()=>{this.write(this._render(t,n));});});});}_calculateFilename(t,n){return kr.format(n.fileNameFormat,t.saveName)}_render(t,n){let i=this.lambdaMixinProvider.apply({meta:{timestamp:this.opts.meta.timestamp??new Date().toISOString(),generator:this.opts.meta.generator??"@atomic-ehr/codegen mustache generator"},model:t,properties:n.properties??{}});return this.debugMixinProvider&&(i=this.debugMixinProvider.apply(i)),ba.render(this.templateFileCache.read(n),i,r=>this.templateFileCache.readTemplate(r))}};var vr=new Set(["class","function","return","if","for","while","const","let","var","import","export","interface"]),ne=e=>(vr.has(e)&&(e=`${e}_`),e.replace(/\[x\]/g,"_x_").replace(/[- :.]/g,"_")),lt=e=>{if(!e)return "";let t=e.replace(/\[x\]/g,"").replace(/:/g,"_");return de(t)},Rr=e=>xt(e.replace(/[@/]/g,"_")),fn=e=>R(D(e)),Ir=e=>`${fn(e)}.ts`,qe=(e,t=true)=>{if(!e)return;let n=se(e,t);if(n)return ne(n)},D=e=>{if(e.kind==="nested"){let n=e.url,i=se(n,false);if(!i)return "";let[r,o]=i.split("#"),s=De((o??"").split(".")).join("");return ne([r,s].join(""))}let t=e.name.includes("/")?se(e.name)??e.name:e.name;return ne(t)},ue=e=>vr.has(e)?`"${e}"`:e.includes(" ")||e.includes("-")?`"${e}"`:e,pt=(e,t)=>{let n=e.findLastSpecializationByIdentifier(t.identifier);return `${R(ne(n.name))}_${ne(t.identifier.name)}`},$r=(e,t)=>`${pt(e,t)}.ts`,Y=e=>{let t=ne(e.identifier.name);return t.endsWith("Profile")?t:`${t}Profile`},un=(e,t,n)=>`${R(e)}_${R(ne(t))}_${R(ne(n))}SliceFlat`,mn=(e,t,n)=>`${R(e)}_${R(ne(t))}_${R(ne(n))}SliceFlatAll`,dt=(e,t)=>`${R(e)}_${R(ne(t))}Flat`,gn=(e,t)=>`${R(e)}_${R(ne(t))}Extracted`,yn=(e,t)=>`${R(e)}_${R(ne(t))}VFlat`,Ce=e=>e.replace(/\[x\]/g,"").replace(/[^a-zA-Z0-9_$]/g,"_"),ft=e=>`value${R(e.name)}`,$a=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Fr=e=>e==="__proto__"?'["__proto__"]':$a.test(e)?e:JSON.stringify(e);var Pr={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"},Nr=e=>{let t=Pr[e];if(t===void 0)throw new Error(`Unknown primitive type ${e}`);return t},Ke=(e,t)=>t.startsWith('"')?`${e}[${t}]`:`${e}.${t}`,Hn=e=>{let t=e.values.map(n=>`"${n}"`).join(" | ");return e.isOpen?`(${t} | string)`:`(${t})`},Fa={Coding:{code:()=>"T"},Reference:{reference:()=>"`${T}/${string}` | `http://${string}` | `https://${string}` | `urn:uuid:${string}` | `urn:oid:${string}` | `#${string}`"},CodeableConcept:{coding:()=>"Coding<T>"}},Jn=(e,t,n,i,r,o)=>{if(r?.[t])return r[t];let s=Fa[e]?.[t];if(s)return s();if(n.enum)return n.type.name==="Coding"?`Coding<${Hn(n.enum)}>`:n.type.name==="CodeableConcept"?`CodeableConcept<${Hn(n.enum)}>`:Hn(n.enum);if(n.reference&&n.reference.resource.length>0){let a={};if(i)for(let l of n.reference.profiles??[]){let p=i(l).name;(a[p]??=[]).push(l.url);}return `Reference<${n.reference.resource.map(l=>{let p=i?i(l):l;if(o?.(p))return `string /* ${p.name} */`;let d=a[p.name];return d?`"${p.name}" /* ${d.join(", ")} */`:`"${p.name}"`}).join(" | ")}>`}return M(n.type)?Nr(n.type.name):L(n.type)?D(n.type):n.type.name},Ye=(e,t,n)=>Jn("","",e,t,void 0,n)+(e.array?"[]":""),le=e=>{if(L(e))return D(e);if(M(e))return Nr(e.name);let t=Pr[e.name];return t!==void 0?t:e.name};var Pa=e=>{if(e)return e.find(t=>t.startsWith("value")&&t!=="value")},Na=/^value/,Ea=e=>{let t=e.replace(Na,"");return {String:"string",Boolean:"boolean",Integer:"number",Decimal:"number",Date:"string",DateTime:"string",Time:"string",Instant:"string",Uri:"string",Url:"string",Canonical:"string",Code:"string",Oid:"string",Id:"string",Markdown:"string",UnsignedInt:"number",PositiveInt:"number",Uuid:"string",Base64Binary:"string"}[t]??t},me=e=>{let t=e.fields.extension,n=e.slicing?.extension;if(!t||b(t)||!n?.slices)return [];let i=[];for(let[r,o]of Object.entries(n.slices)){let s=Pa(o.elements);if(!s)continue;let a=Ea(s),c=o.max===void 0,l=o.min!==void 0&&o.min>=1;i.push({name:lt(r)||r,url:r,valueField:s,tsType:a,isArray:c,isRequired:l});}return i},ut=(e,t,n)=>{let i=e.resolveByUrl(t,n);if(!i||!V(i)||i.identifier.package!==t)return;let r=e.resolve(Rt(i.identifier));if(!r)return;let o=Y(r),s=`./${pt(e,r)}`;return {className:o,modulePath:s,snapshot:r}},qn=(e,t,n,i="input",r=false)=>{e.line(`if (${i}.url !== ${JSON.stringify(t.url)}) throw new Error(\`Expected extension url '${t.url}', got '\${${i}.url}'\`)`),Oe(e,n,i,r);},Oe=(e,t,n,i=false)=>{let r=i?"upsertExtension":"pushExtension";t.length===0?e.line(`${r}(this.resource, ${n})`):(e.line(`const target = ensurePath(this.resource as unknown as Record<string, unknown>, ${JSON.stringify(t)})`),e.line("if (!Array.isArray(target.extension)) target.extension = [] as Extension[]"),e.line(`${r}(target as unknown as { extension?: Extension[] }, ${n})`));},Oa=(e,t,n)=>{n.length===0?e.line(`const ext = this.resource.extension?.find(e => e.url === "${t.url}")`):(e.line(`const target = ensurePath(this.resource as unknown as Record<string, unknown>, ${JSON.stringify(n)})`),e.line(`const ext = (target.extension as Extension[] | undefined)?.find(e => e.url === "${t.url}")`));},_a=(e,t)=>{let n=e.opts.extensionGetterDefault??"flat";return n==="profile"&&!t?"flat":n},Wn=(e,t,n,i)=>e==="profile"&&n?n:e==="raw"?"Extension":e==="vflat"&&i?i:t,Er=(e,t,n,i,r,o,s,a)=>{let c=!!o,l=_a(e,c),p=c?["flat","profile","raw"]:["flat","raw"];a&&p.splice(1,0,"vflat");for(let m of p){let g=Wn(m,r,o?.className,a);e.lineSM(`public ${i}(mode: '${m}'): ${g} | undefined`);}let d=Wn(l,r,o?.className,a);e.lineSM(`public ${i}(): ${d} | undefined`);let u=[...new Set(p.map(m=>Wn(m,r,o?.className,a)))],f=p.map(m=>`'${m}'`).join(" | ");e.curlyBlock(["public",i,`(mode: ${f} = '${l}'): ${u.join(" | ")} | undefined`],()=>{Oa(e,t,n),e.line("if (!ext) return undefined"),e.line("if (mode === 'raw') return ext"),c&&e.line(`if (mode === 'profile') return ${o?.className}.apply(ext)`),s();});},Ma=(e,t)=>{let{ext:n,snapshot:i,setMethodName:r,targetPath:o,extProfileInfo:s}=t,a=D(i.identifier),c=dt(a,n.name),l=s?me(s.snapshot).length>0:false,p=n.max==="1";if(s&&l){let d=`${s.className}Flat | ${s.className} | Extension`;e.curlyBlock(["public",r,`(input: ${d}): this`],()=>{e.ifElseChain([{cond:`input instanceof ${s.className}`,body:()=>Oe(e,o,"input.toResource()",p)},{cond:"isExtension<Extension>(input)",body:()=>qn(e,n,o,"input",p)}],()=>Oe(e,o,`${s.className}.createResource(input)`,p)),e.line("return this");});}else e.curlyBlock(["public",r,`(input: ${c}): this`],()=>{e.line("const subExtensions: Extension[] = []");for(let f of n.subExtensions??[]){let m=f.valueFieldType?ft(f.valueFieldType):"value";f.max==="*"?e.curlyBlock(["if",`(input.${f.name})`],()=>{e.curlyBlock(["for",`(const item of input.${f.name})`],()=>{e.line(`subExtensions.push({ url: "${f.url}", ${m}: item } as Extension)`);});}):e.curlyBlock(["if",`(input.${f.name} !== undefined)`],()=>{e.line(`subExtensions.push({ url: "${f.url}", ${m}: input.${f.name} } as Extension)`);});}let d=`{ url: "${n.url}", extension: subExtensions }`,u=p?"upsertExtension":"pushExtension";o.length===0?e.line(`${u}(this.resource, ${d})`):(e.line(`const target = ensurePath(this.resource as unknown as Record<string, unknown>, ${JSON.stringify(o)})`),e.line("if (!Array.isArray(target.extension)) target.extension = [] as Extension[]"),e.line(`${u}(target as unknown as { extension?: Extension[] }, ${d})`)),e.line("return this");});},Da=e=>{let t=e?me(e.snapshot):[];if(t.length!==0)return t.map(n=>JSON.stringify(n.name)).join(" | ")},Kn=(e,t,n)=>{let i=dt(e,t.name),r=Da(n);if(!r||!n)return {flat:`Partial<${i}>`,vFlat:void 0};let o=`Pick<${n.className}Flat, ${r}>`;return {flat:`Partial<${o}>`,vFlat:o}},Ba=(e,t)=>{let{ext:n,snapshot:i,getMethodName:r,targetPath:o,extProfileInfo:s}=t,a=D(i.identifier),c=n.nameCandidates.recommended,l=gn(a,c),d=Kn(a,n,s).vFlat!==void 0?yn(a,c):void 0;Er(e,n,o,r,l,s,()=>{let u=(n.subExtensions??[]).map(f=>{let m=f.valueFieldType?ft(f.valueFieldType):"value",g=f.max==="*";return `{ name: "${f.url}", valueField: "${m}", isArray: ${g} }`});e.line(`const config = [${u.join(", ")}]`),d&&s&&e.curlyBlock(["if","(mode === 'vflat')"],()=>{e.line(`const { errors } = ${s.className}.apply(ext).validate()`),e.line('if (errors.length > 0) throw new Error(errors.join("; "))'),e.line(`return extractComplexExtension<${d}>(ext, config)`);}),e.line(`return extractComplexExtension<${l}>(ext, config)`);},d);},ja=(e,t,n)=>{let{ext:i,setMethodName:r,targetPath:o,extProfileInfo:s}=n,a=i.valueFieldTypes?.[0];if(!a)return;let c=le(a),l=ft(a),p=i.max==="1";if(s){let u=hn(t,s.snapshot).params.find(y=>y.name===l),f=u?.tsType??c,m=`${s.className} | Extension | ${f}`,g=u?`${s.className}.createResource({ ${l}: value as ${f} })`:`{ url: "${i.url}", ${l}: value as ${c} } as Extension`;e.curlyBlock(["public",r,`(value: ${m}): this`],()=>{e.ifElseChain([{cond:`value instanceof ${s.className}`,body:()=>Oe(e,o,"value.toResource()",p)},{cond:"isExtension(value)",body:()=>qn(e,i,o,"value",p)}],()=>Oe(e,o,g,p)),e.line("return this");});}else e.curlyBlock(["public",r,`(value: ${c}): this`],()=>{let d=`{ url: "${i.url}", ${l}: value } as Extension`;Oe(e,o,d,p),e.line("return this");});},La=(e,t)=>{let{ext:n,getMethodName:i,targetPath:r,extProfileInfo:o}=t,s=n.valueFieldTypes?.[0];if(!s)return;let a=le(s),c=ft(s);Er(e,n,r,i,a,o,()=>{e.line(`return getExtensionValue<${a}>(ext, "${c}")`);});},Aa=(e,t)=>{let{ext:n,setMethodName:i,targetPath:r}=t,o=n.max==="1";e.curlyBlock(["public",i,'(value: Omit<Extension, "url"> | Extension): this'],()=>{e.ifElseChain([{cond:"isExtension(value)",body:()=>qn(e,n,r,"value",o)}],()=>Oe(e,r,`{ url: "${n.url}", ...value } as Extension`,o)),e.line("return this");});},Va=(e,t)=>{let{ext:n,getMethodName:i,targetPath:r}=t;e.curlyBlock(["public",i,"(): Extension | undefined"],()=>{r.length===0?e.line(`return this.resource.extension?.find(e => e.url === "${n.url}")`):(e.line(`const target = ensurePath(this.resource as unknown as Record<string, unknown>, ${JSON.stringify(r)})`),e.line(`return (target.extension as Extension[] | undefined)?.find(e => e.url === "${n.url}")`));});},Or=(e,t,n)=>{for(let i of n.extensions??[]){if(!i.url)continue;let r=i.nameCandidates.recommended,o=i.path.split(".").filter(c=>c!=="extension"),s=ut(t,n.identifier.package,i.url),a={ext:i,snapshot:n,setMethodName:`set${r}`,getMethodName:`get${r}`,targetPath:o,extProfileInfo:s};i.isComplex&&i.subExtensions?(Ma(e,a),e.line(),Ba(e,a)):i.valueFieldTypes?.length===1&&i.valueFieldTypes[0]?(ja(e,t,a),e.line(),La(e,a)):(Aa(e,a),e.line(),Va(e,a)),e.line();}},_r=(e,t,n)=>{let i=false;for(let r of t.extensions??[])if(r.isComplex&&r.subExtensions){i=true;for(let o of r.subExtensions){if(!o.valueFieldType)continue;let s=e.resolveByUrl(t.identifier.package,o.valueFieldType.url);n(s?.identifier??o.valueFieldType);}}else if(r.valueFieldTypes&&r.valueFieldTypes.length===1){if(i=true,r.valueFieldTypes[0]){let o=e.resolveByUrl(t.identifier.package,r.valueFieldTypes[0].url);n(o?.identifier??r.valueFieldTypes[0]);}}else i=true;return i},Mr=(e,t,n)=>{if(t.base.name!=="Extension")return;let i=me(t);for(let r of i){let o=r.tsType;if(["string","boolean","number"].includes(o))continue;let s=`http://hl7.org/fhir/StructureDefinition/${o}`,a=e.resolveByUrl(t.identifier.package,s);a&&n(a.identifier);}};var wa=(e,t,n,i=new Set)=>{let r=new Set([...n.map(o=>R(o)),...i]);return r.has(t)?e.find(o=>!r.has(o))??t:t},Ga=(e,t)=>{let n=new Set,i=e.resolveType(t);if(i&&"fields"in i&&i.fields)for(let[r,o]of Object.entries(i.fields))b(o)&&n.add(r);return n},Yn=e=>{for(let t of Object.values(e)){if(typeof t!="object"||t===null)continue;let n=t;if(typeof n.resourceType=="string")return n.resourceType;let i=Yn(n);if(i)return i}},Dr=(e,t,n)=>{let i=t.identifier.package;for(let[r,o]of Object.entries(t.slicing??{})){let s=t.fields[r];if(!j(s)||!o.slices||!s.type)continue;let a=Pe(o);for(let c of Object.values(o.slices))if(Object.keys(c.match??{}).length>0){n(s.type);let l=c.elements?e.constrainedChoice(i,s.type,c.elements):void 0;if(l&&n(l.variantType),a&&c.match){let p=Yn(c.match);if(p){let d=e.schemas.find(u=>u.identifier.name===p&&u.identifier.kind==="resource");d&&n(d.identifier);}}}}},Br=(e,t)=>{if(!e.array||!t?.slices||Pe(t))return;let n=Object.entries(t.slices).filter(([i,r])=>{if(r.min===void 0||r.min<1||!r.match||Object.keys(r.match).length===0)return false;let o=new Set(Object.keys(r.match));return (r.required??[]).filter(a=>!o.has(a)).length===0}).map(([i])=>i);return n.length>0?n:void 0},jr=(e,t)=>{let n=new Set;return Object.entries(t.slicing??{}).flatMap(([i,r])=>{let o=t.fields[i];if(!j(o)||!r.slices||!o.type)return [];let s=le(o.type),a=t.identifier.package,c=Ga(e,o.type),l=Pe(r);return Object.entries(r.slices).filter(([p,d])=>Object.keys(d.match??{}).length>0).map(([p,d])=>{let u=Object.keys(d.match??{}),f=(d.required??[]).filter(k=>!u.includes(k)&&!c.has(k)),m=d.elements?e.constrainedChoice(a,o.type,d.elements):void 0,g=m&&!M(m.variantType)?m:void 0,y=l?Yn(d.match??{}):void 0,h=y?`${s}<${y}>`:s,x=wa(d.nameCandidates.candidates,d.nameCandidates.recommended,Object.keys(t.fields),n);return n.add(x),{fieldName:i,baseType:s,typedBaseType:h,sliceName:p,baseName:x,match:d.match??{},required:f,excluded:d.excluded??[],array:!!o.array,constrainedChoice:g,typeDiscriminator:l,max:d.max??0}})})},Lr=(e,t,n)=>{let i=Y(n),r=D(n.identifier);for(let o of t){let a=`set${o.baseName}`,c=un(r,o.fieldName,o.sliceName),l=`${i}.${Ce(o.sliceName)}SliceMatch`,p=ue(o.fieldName),d=Ke("this.resource",p),u=o.typedBaseType;if(o.array&&(o.max===0||o.max===void 0)){let g=`(input: ${`(${c} | ${u})[]`}): this`;e.curlyBlock(["public",a,g],()=>{if(e.line(`const match = ${l}`),e.line(`const arr = ${d} ??= []`),o.constrainedChoice){let y=o.constrainedChoice;e.line(`const values = input.map(item => matchesValue(item, match) ? item as ${u} : applySliceMatch<${u}>(wrapSliceChoice<${u}>(item, ${JSON.stringify(y.variant)}), match))`);}else e.line(`const values = input.map(item => matchesValue(item, match) ? item as ${u} : applySliceMatch<${u}>(item, match))`);e.line("setArraySliceAll(arr, match, values)"),e.line("return this");});}else {let m=o.required.length===0,g=`${c} | ${u}`,y=m?`(input?: ${g}): this`:`(input: ${g}): this`;e.curlyBlock(["public",a,y],()=>{e.line(`const match = ${l}`),e.curlyBlock(["if","(input && matchesValue(input, match))"],()=>{o.array?e.line(`setArraySlice(${d} ??= [], match, input as ${u})`):e.line(`${d} = input as ${u}`),e.line("return this");});let h=m?"input ?? {}":"input";if(o.constrainedChoice){let x=o.constrainedChoice;e.line(`const wrapped = wrapSliceChoice<${u}>(${h}, ${JSON.stringify(x.variant)})`),e.line(`const value = applySliceMatch<${u}>(wrapped, match)`);}else e.line(`const value = applySliceMatch<${u}>(${h}, match)`);o.array?e.line(`setArraySlice(${d} ??= [], match, value)`):e.line(`${d} = value`),e.line("return this");});}e.line();}},Ar=(e,t,n)=>{let i=Y(n),r=D(n.identifier),o=e.opts.sliceGetterDefault??"flat";for(let s of t){let c=`get${s.baseName}`,l=mn(r,s.fieldName,s.sliceName),p=`${i}.${Ce(s.sliceName)}SliceMatch`,d=JSON.stringify(Object.keys(s.match)),u=ue(s.fieldName),f=Ke("this.resource",u),m=s.typedBaseType;if(s.array&&(s.max===0||s.max===void 0)){let y=o==="raw"?`${m}[]`:`${l}[]`;e.lineSM(`public ${c}(mode: 'flat'): ${l}[] | undefined`),e.lineSM(`public ${c}(mode: 'raw'): ${m}[] | undefined`),e.lineSM(`public ${c}(): ${y} | undefined`),e.curlyBlock(["public",c,`(mode: 'flat' | 'raw' = '${o}'): (${l} | ${m})[] | undefined`],()=>{if(e.line(`const match = ${p}`),e.line(`const items = getArraySliceAll(${f}, match)`),e.line("if (items.length === 0) return undefined"),s.typeDiscriminator?e.line(`if (mode === 'raw') return items as ${m}[]`):e.line("if (mode === 'raw') return items"),s.constrainedChoice){let h=s.constrainedChoice;e.line(`return items.map(item => unwrapSliceChoice<${l}>(item, ${d}, ${JSON.stringify(h.variant)}))`);}else e.line(`return items as unknown as ${l}[]`);});}else {let y=o==="raw"?m:l;e.lineSM(`public ${c}(mode: 'flat'): ${l} | undefined`),e.lineSM(`public ${c}(mode: 'raw'): ${m} | undefined`),e.lineSM(`public ${c}(): ${y} | undefined`),e.curlyBlock(["public",c,`(mode: 'flat' | 'raw' = '${o}'): ${l} | ${m} | undefined`],()=>{if(e.line(`const match = ${p}`),s.array?(e.line(`const item = getArraySlice(${f}, match)`),e.line("if (!item) return undefined")):(e.line(`const item = ${f}`),e.line("if (!item || !matchesValue(item, match)) return undefined")),s.typeDiscriminator?e.line(`if (mode === 'raw') return item as ${m}`):e.line("if (mode === 'raw') return item"),s.constrainedChoice){let h=s.constrainedChoice;e.line(`return unwrapSliceChoice<${l}>(item, ${d}, ${JSON.stringify(h.variant)})`);}else e.line(`return item as unknown as ${l}`);});}e.line();}};var Ua=(e,t,n,i)=>{let r=[],o=[],s=new Set(Object.keys(t)),a=(e.required??[]).filter(l=>!s.has(l)),c=n.type;for(let l of a){let p=i&&c?i.sliceChoiceVariants(c.package,c,e.elements??[],l):void 0;p&&p.length>0?o.push(p):r.push(l);}if(i&&c&&e.elements){let l=i.constrainedChoice(c.package,c,e.elements);l&&!a.includes(l.choiceBase)&&r.push(l.variant);}return {requiredFields:r,choiceGroups:o}},za=(e,t,n,i,r,o,s,a,c)=>{if(i.excluded){e.push(`...validateExcluded(res, profileName, ${JSON.stringify(n)})`);return}if(i.required&&e.push(`...validateRequired(res, profileName, ${JSON.stringify(n)})`),i.valueConstraint){let l=o&&n==="url"&&i.valueConstraint.value===o.url?o.expr:JSON.stringify(i.valueConstraint.value),p=i.valueConstraint.validateOnly?"validatePatternValue":"validateFixedValue",d=i.array?", true":"";e.push(`...${p}(res, profileName, ${JSON.stringify(n)}, ${l}${d})`);}if(i.enum){let l=i.enum.isOpen?t:e,p=c?.get(n)??JSON.stringify(i.enum.values);l.push(`...validateEnum(res, profileName, ${JSON.stringify(n)}, ${p})`);}if(i.mustSupport&&!i.required&&t.push(`...validateMustSupport(res, profileName, ${JSON.stringify(n)})`),i.reference&&i.reference.resource.length>0){let l=i.reference.resource.flatMap(p=>{let d=r(p),u=s?.resolveType(d),f=u&&"typeFamily"in u?u.typeFamily?.resources??[]:[];return f.length===0?[d.name]:f.filter(m=>!s?.isFamilyType(m)).map(m=>m.name).sort((m,g)=>m.localeCompare(g))});e.push(`...validateReference(res, profileName, ${JSON.stringify(n)}, ${JSON.stringify([...new Set(l)])})`);}if(a?.slices)for(let[l,p]of Object.entries(a.slices)){let d=p.match??{};if(Object.keys(d).length===0)continue;if(p.min!==void 0||p.max!==void 0){let m=p.min??0,g=p.max??0;e.push(`...validateSliceCardinality(res, profileName, ${JSON.stringify(n)}, ${JSON.stringify(d)}, ${JSON.stringify(l)}, ${m}, ${g})`);}let{requiredFields:u,choiceGroups:f}=Ua(p,d,i,s);if(u.length>0||f.length>0){let m=[JSON.stringify(n),JSON.stringify(d),JSON.stringify(l),JSON.stringify(u)];f.length>0&&m.push(JSON.stringify(f)),e.push(`...validateSliceFields(res, profileName, ${m.join(", ")})`);}}},Vr=(e,t,n)=>{let i=n.fields,r=n.identifier.name,o=n.identifier.url,s=o?{url:o,expr:`${Y(n)}.canonicalUrl`}:void 0,a=e.enumTerminologyLinks(t,n);e.curlyBlock(["validate(): { errors: string[]; warnings: string[] }"],()=>{e.line(`const profileName = "${r}"`),e.line("const res = this.resource");let c=[],l=[];for(let[d,u]of Object.entries(i))if(!A(u)){if(b(u)){u.required&&c.push(`...validateChoiceRequired(res, profileName, ${JSON.stringify(u.choices)})`),u.prohibited?.length&&c.push(`...validateChoiceProhibited(res, profileName, ${JSON.stringify(u.prohibited)})`);continue}za(c,l,d,u,t.findLastSpecializationByIdentifier,s,t,n.slicing?.[d],a.exprs);}for(let d of n.inheritedRequiredFields??[])c.push(`...validateRequired(res, profileName, ${JSON.stringify(d)})`);let p=(d,u)=>{u.length===0?e.line(`${d}: [],`):e.squareBlock([`${d}:`],()=>{for(let f of u)e.line(`${f},`);},[","]);};e.curlyBlock(["return"],()=>{p("errors",c),p("warnings",l);});}),e.line();};var wr=e=>`clear${R(lt(e))}`,Ha=(e,t)=>{let n={};for(let[o,s]of Object.entries(e.fields))s.excluded||A(s)&&(n[s.choiceOf]??=[]).push(o);let i=[];for(let[o,s]of Object.entries(e.fields)){if(s.excluded||!A(s)||t.has(o))continue;let a=le(s.type)+(s.array?"[]":""),l=(n[s.choiceOf]?.length??0)>1?wr(s.choiceOf):void 0;i.push({name:o,tsType:a,typeId:s.type,choiceClearMethod:l});}let r=Object.entries(n).filter(([,o])=>o.length>1).map(([o,s])=>({method:wr(o),variants:s.map(ue)}));return {accessors:i,choiceClearMethods:r}},Ja=(e,t,n,i,r,o)=>{if(!b(e)||!e.required||e.choices.length!==1)return;let s=e.choices[0];if(!s)return;let a=t[s];if(!a||!A(a))return;let c=Ye(a,r,o);n.push({name:s,tsType:c,typeId:a.type}),i.add(s);},hn=(e,t)=>{let n=[],i=[],r=[],o=[],s=new Set,a=t.fields,c=new Set,l=e.findLastSpecializationByIdentifier,p=e.isFamilyType;oe(t.base)&&n.push({name:"resourceType",value:JSON.stringify(t.base.name)});for(let[m,g]of Object.entries(a))if(!g.excluded&&!A(g)){if(b(g)){Ja(g,a,r,c,l,p);continue}if(g.valueConstraint&&!g.valueConstraint.validateOnly){let y=g.valueConstraint.value===t.identifier.url?`${Y(t)}.canonicalUrl`:JSON.stringify(g.valueConstraint.value);if(n.push({name:m,value:g.array?`[${y}]`:y}),s.add(m),j(g)&&g.type){let h=Ye(g,l,p);o.push({name:m,tsType:h,typeId:g.type});}continue}if(j(g)){let y=Br(g,t.slicing?.[m]);if(y){if(g.type){let h=Ye(g,l,p);i.push({name:m,tsType:h,typeId:g.type,sliceNames:y}),o.push({name:m,tsType:h,typeId:g.type});}continue}}if(g.required){let y=Ye(g,l,p);r.push({name:m,tsType:y,typeId:g.type});}}Wa(e,t,l,r,[...n.map(m=>m.name),...i.map(m=>m.name),...r.map(m=>m.name),...c],p);let{accessors:d,choiceClearMethods:u}=Ha(t,c),f=[...o,...d];return {autoFields:n,sliceAutoFields:i,params:r,accessors:f,choiceClearMethods:u,fixedFields:s}},Wa=(e,t,n,i,r,o)=>{let s=new Set(r),a=e.resolveType(t.base);if(!(!a||!("fields"in a)||!a.fields)){for(let[c,l]of Object.entries(a.fields))if(!s.has(c)&&l.required&&!A(l)&&!b(l)&&j(l)&&l.type){let p=Ye(l,n,o);i.push({name:c,tsType:p,typeId:l.type});}}},Gr=(e,t,n)=>{n.length!==0&&e.cd("profiles",()=>{e.cat("index.ts",()=>{let i=new Map;for(let r of n){let o=Y(r);i.has(o)||i.set(o,pt(t,r));}for(let r of [...i.keys()].sort())e.tsExport(`./${i.get(r)}`,r);});});},qa=(e,t,n,i,r)=>{let o=n.extensions??[],s=t.isWithMetaField(n),a=n.identifier.url,c=[];n.base.name==="Extension"&&a&&me(n).length>0&&c.push("isRawExtensionInput"),a&&s&&c.push("ensureProfile"),r.autoFields.some(d=>d.name!=="resourceType")&&c.push("applyFixedValue"),(i.length>0||r.sliceAutoFields.length>0)&&c.push("applySliceMatch","matchesValue","setArraySlice","getArraySlice","ensureSliceDefaults"),i.some(d=>d.array&&(d.max===0||d.max===void 0))&&c.push("setArraySliceAll","getArraySliceAll"),o.some(d=>d.path.split(".").some(u=>u!=="extension"))&&c.push("ensurePath"),o.some(d=>d.isComplex&&d.subExtensions)&&c.push("extractComplexExtension"),i.some(d=>d.constrainedChoice)&&c.push("wrapSliceChoice","unwrapSliceChoice"),o.some(d=>d.url)&&(c.push("isExtension","getExtensionValue","pushExtension"),o.some(d=>d.url&&d.max==="1")&&c.push("upsertExtension")),(Object.keys(n.fields).length>0||(n.inheritedRequiredFields?.length??0)>0)&&c.push("validateRequired","validateExcluded","validateFixedValue","validateSliceCardinality","validateSliceFields","validateEnum","validateReference","validateChoiceRequired","validateChoiceProhibited","validateMustSupport"),Object.values(n.fields).some(d=>"valueConstraint"in d&&d.valueConstraint?.validateOnly===true)&&c.push("validatePatternValue"),c.length>0&&(e.tsImport("../../profile-helpers",...c),e.line());},Ur=(e,t,n)=>{let i=e.enumTerminologyLinks(t,n).imports,r=new Map,o=f=>{if(L(f)){let m=qe(f.url,true);if(m)return `../../${e.packageDir(f)}/${z(m)}`}return `../../${e.modulePath(f)}`},s=f=>{if(f.kind==="primitive-type")return;let m=D(f);r.has(m)||r.set(m,{importPath:o(f),tsName:m});};s(n.base),Dr(t,n,s);let a=_r(t,n,s);Mr(t,n,s);let c=hn(t,n);for(let f of c.params)s(f.typeId);for(let f of c.sliceAutoFields)s(f.typeId);for(let f of c.accessors)s(f.typeId);if(a){let m=t.resolveByUrl(n.identifier.package,"http://hl7.org/fhir/StructureDefinition/Extension");m&&s(m.identifier);}let l=new Map;for(let{importPath:f,tsName:m}of r.values()){let g=l.get(f);g||(g=[],l.set(f,g)),g.push(m);}let p=[...l.entries()].sort(([f],[m])=>f.localeCompare(m));for(let[f,m]of p)e.tsImport(f,...m.sort(),{typeOnly:true});p.length>0&&e.line();let d=[...i.entries()].sort(([f],[m])=>f.localeCompare(m));for(let[f,m]of d)e.tsImport(`../../${f}/terminology`,...[...m].sort());d.length>0&&e.line();let u=new Map;for(let f of n.extensions??[]){if(!f.url)continue;let m=ut(t,n.identifier.package,f.url);if(m&&!u.has(m.className)){let g=me(m.snapshot).length>0;u.set(m.className,{modulePath:m.modulePath,hasFlatInput:g});}}for(let[f,{modulePath:m,hasFlatInput:g}]of [...u.entries()].sort(([y],[h])=>y.localeCompare(h))){let y=[f,...g?[`type ${f}Flat`]:[]];e.tsImport(m,...y);}u.size>0&&e.line();},Ka=(e,t)=>{for(let n of t){let i=`${Ce(n.sliceName)}SliceMatch`,r=JSON.stringify(n.match),o=`private static readonly ${i}: Record<string, unknown> = `;o.length+r.length<=(e.opts.lineWidth??120)?e.lineSM(`${o}${r}`):e.curlyBlock([o.trimEnd()],()=>{for(let[s,a]of Object.entries(n.match))e.line(`${JSON.stringify(s)}: ${JSON.stringify(a)},`);});}t.length>0&&e.line();},Ya=(e,t,n,i)=>{let r=Y(n),o=le(n.base),s=t.isWithMetaField(n),a=i.params.length>0||i.sliceAutoFields.length>0,c=`${r}Raw`,l=a?`args: ${c}`:"",p=[...i.autoFields.map(g=>({name:g.name,value:g.value})),...i.sliceAutoFields.map(g=>({name:g.name,value:`${g.name}WithDefaults`})),...i.params.map(g=>({name:g.name,value:`args.${g.name}`}))];e.curlyBlock(["constructor",`(resource: ${o})`],()=>{e.lineSM("this.resource = resource");}),e.line(),e.curlyBlock(["static","from",`(resource: ${o})`,`: ${r}`],()=>{s&&e.curlyBlock(["if",`(!resource.meta?.profile?.includes(${r}.canonicalUrl))`],()=>{e.line(`throw new Error(\`${r}: meta.profile must include \${${r}.canonicalUrl}\`)`);}),e.lineSM(`const profile = new ${r}(resource)`),e.lineSM("const { errors } = profile.validate()"),e.line('if (errors.length > 0) throw new Error(errors.join("; "))'),e.lineSM("return profile");}),e.line(),(s&&oe(n.base)||n.base.name==="Extension")&&(e.curlyBlock(["static","is","(resource: unknown)",`: resource is ${o}`],()=>{e.line('if (typeof resource !== "object" || resource === null) return false;'),s&&oe(n.base)?(e.line("const r = resource as { resourceType?: string; meta?: { profile?: string[] } };"),e.line(`if (r.resourceType !== ${JSON.stringify(n.base.name)}) return false;`),e.lineSM(`return (r.meta?.profile ?? []).includes(${r}.canonicalUrl)`)):e.lineSM(`return (resource as { url?: string }).url === ${r}.canonicalUrl`);}),e.line()),e.curlyBlock(["static","apply",`(resource: ${o})`,`: ${r}`],()=>{s&&e.lineSM(`ensureProfile(resource, ${r}.canonicalUrl)`),n.base.name==="Extension"&&n.identifier.url&&e.lineSM(`resource.url = ${r}.canonicalUrl`);let g=i.autoFields.filter(y=>y.name!=="resourceType");if(g.length>0)for(let y of g)e.lineSM(`applyFixedValue(resource, ${JSON.stringify(y.name)}, ${y.value})`);for(let y of i.sliceAutoFields){let h=y.sliceNames.map(x=>`${r}.${Ce(x)}SliceMatch`);e.line(`resource.${y.name} = ensureSliceDefaults(`),e.indentBlock(()=>{e.line(`[...(resource.${y.name} ?? [])],`);for(let x of h)e.line(`${x},`);}),e.lineSM(")");}e.lineSM(`return new ${r}(resource)`);}),e.line();let u=n.base.name==="Extension"?me(n):[],f=u.length>0,m=a||u.some(g=>g.isRequired);if(f){let g=`${r}Raw`,y=`${r}Flat`;e.curlyBlock(["private static","resolveInput",`(args: ${g} | ${y})`,": Extension[]"],()=>{e.ifElseChain([{cond:`isRawExtensionInput<${g}>(args)`,body:()=>e.lineSM("return args.extension ?? []")}],()=>{e.lineSM("const result: Extension[] = []");for(let k of u)k.isArray?e.curlyBlock(["if",`(args.${k.name})`],()=>{e.curlyBlock(["for",`(const item of args.${k.name})`],()=>{e.lineSM(`result.push({ url: "${k.url}", ${k.valueField}: item } as Extension)`);});}):e.curlyBlock(["if",`(args.${k.name} !== undefined)`],()=>{e.lineSM(`result.push({ url: "${k.url}", ${k.valueField}: args.${k.name} } as Extension)`);});e.lineSM("return result");});}),e.line();let h=m?`args: ${g} | ${y}`:`args?: ${g} | ${y}`;e.curlyBlock(["static","createResource",`(${h})`,`: ${o}`],()=>{let k=m?"args":"args ?? {}";e.lineSM(`const resolvedExtensions = ${r}.resolveInput(${k})`);for(let G of i.sliceAutoFields){if(G.name==="extension")continue;let $e=G.sliceNames.map(S=>`${r}.${Ce(S)}SliceMatch`);e.line(`const ${G.name}WithDefaults = ensureSliceDefaults(`),e.indentBlock(()=>{e.line(`[...(args.${G.name} ?? [])],`);for(let S of $e)e.line(`${S},`);}),e.lineSM(")");}let $=i.sliceAutoFields.find(G=>G.name==="extension");if($){let G=$.sliceNames.map($e=>`${r}.${Ce($e)}SliceMatch`);e.line("const extensionWithDefaults = ensureSliceDefaults("),e.indentBlock(()=>{e.line("resolvedExtensions,");for(let $e of G)e.line(`${$e},`);}),e.lineSM(")");}e.line();let q=$?"extensionWithDefaults":"resolvedExtensions",_e=p.some(G=>G.name==="meta");e.curlyBlock([`const resource: ${o} =`],()=>{for(let G of p)G.name!=="extension"&&(G.name==="meta"&&s||e.line(`${G.name}: ${G.value},`));e.line(`extension: ${q},`),s&&(_e?e.line(`meta: { ...args.meta, profile: [...(args.meta?.profile ?? []), ${r}.canonicalUrl] },`):e.line(`meta: { profile: [${r}.canonicalUrl] },`));}),e.lineSM("return resource");}),e.line();let x=m?`args: ${g} | ${y}`:`args?: ${g} | ${y}`;e.curlyBlock(["static","create",`(${x})`,`: ${r}`],()=>{e.lineSM(`return ${r}.apply(${r}.createResource(args))`);});}else e.curlyBlock(["static","createResource",`(${l})`,`: ${o}`],()=>{for(let g of i.sliceAutoFields){let y=g.sliceNames.map(h=>`${r}.${Ce(h)}SliceMatch`);e.line(`const ${g.name}WithDefaults = ensureSliceDefaults(`),e.indentBlock(()=>{e.line(`[...(args.${g.name} ?? [])],`);for(let h of y)e.line(`${h},`);}),e.lineSM(")");}if(i.sliceAutoFields.length>0&&e.line(),M(n.base))e.lineSM(`const resource = undefined as unknown as ${o}`);else {let g=p.some(y=>y.name==="meta");e.curlyBlock([`const resource: ${o} =`],()=>{for(let y of p)y.name==="meta"&&s||e.line(`${y.name}: ${y.value},`);s&&(g?e.line(`meta: { ...args.meta, profile: [...(args.meta?.profile ?? []), ${r}.canonicalUrl] },`):e.line(`meta: { profile: [${r}.canonicalUrl] },`));});}e.lineSM("return resource");}),e.line(),e.curlyBlock(["static","create",`(${l})`,`: ${r}`],()=>{e.lineSM(`const resource = ${r}.createResource(${a?"args":""})`),e.lineSM(`return ${r}.apply(resource)`);});e.line(),e.curlyBlock(["toResource","()",`: ${o}`],()=>{e.lineSM("return this.resource");}),e.line();},Za=(e,t)=>{e.line("// Field accessors");for(let n of t.params){let i=R(n.name);e.curlyBlock([`get${i}`,"()",`: ${n.tsType} | undefined`],()=>{e.lineSM(`return this.resource.${n.name} as ${n.tsType} | undefined`);}),e.line(),e.curlyBlock([`set${i}`,`(value: ${n.tsType})`,": this"],()=>{e.lineSM(`Object.assign(this.resource, { ${n.name}: value })`),e.lineSM("return this");}),e.line();}for(let n of t.accessors){let i=R(lt(n.name)),r=ue(n.name);e.curlyBlock([`get${i}`,"()",`: ${n.tsType} | undefined`],()=>{e.lineSM(`return ${Ke("this.resource",r)} as ${n.tsType} | undefined`);}),e.line(),t.fixedFields.has(n.name)||(e.curlyBlock([`set${i}`,`(value: ${n.tsType})`,": this"],()=>{n.choiceClearMethod&&e.lineSM(`this.${n.choiceClearMethod}()`),e.lineSM(`Object.assign(this.resource, { ${r}: value })`),e.lineSM("return this");}),e.line());}for(let{method:n,variants:i}of t.choiceClearMethods)e.curlyBlock([n,"()",": void"],()=>{for(let r of i)e.lineSM(`delete ${Ke("this.resource",r)}`);}),e.line();},Xa=(e,t,n)=>{let i=D(n.identifier),r=(n.extensions??[]).filter(o=>o.isComplex&&o.subExtensions);for(let o of r){if(!o.url)continue;let s=ut(t,n.identifier.package,o.url);if(s?me(s.snapshot).length>0:false)continue;let c=dt(i,o.name);e.curlyBlock(["export","type",c,"="],()=>{for(let l of o.subExtensions??[]){let p=l.valueFieldType?le(l.valueFieldType):"unknown",d=l.max==="*",u=l.min!==void 0&&l.min>0;e.lineSM(`${l.name}${u?"":"?"}: ${p}${d?"[]":""}`);}}),e.line();}},Qa=(e,t,n)=>{let i=D(n.identifier),r=(n.extensions??[]).filter(o=>o.isComplex&&o.subExtensions);for(let o of r){if(!o.url)continue;let s=ut(t,n.identifier.package,o.url),{flat:a,vFlat:c}=Kn(i,o,s),l=o.nameCandidates.recommended;e.lineSM(`export type ${gn(i,l)} = ${a}`),c&&e.lineSM(`export type ${yn(i,l)} = ${c}`),e.line();}},Zn=e=>e==null?"undefined":typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.map(Zn).join(", ")}]`:typeof e=="object"?`{ ${Object.entries(e).map(([n,i])=>`${n}: ${Zn(i)}`).join("; ")} }`:"unknown",ec=(e,t,n)=>{if(n.length===0)return;let i=D(t.identifier);for(let r of n){let o=un(i,r.fieldName,r.sliceName),s=mn(i,r.fieldName,r.sliceName),a=r.typeDiscriminator?[]:Object.keys(r.match),c=[...new Set([...r.excluded,...a])];if(r.constrainedChoice){let m=r.constrainedChoice;c.push(m.choiceBase);for(let g of m.allChoiceNames)c.includes(g)||c.push(g);}let l=c.map(m=>JSON.stringify(m)),p=r.required.map(m=>JSON.stringify(m)),d=r.typedBaseType,u=d;l.length>0&&(u=`Omit<${u}, ${l.join(" | ")}>`),p.length>0&&(u=`${u} & Required<Pick<${d}, ${p.join(" | ")}>>`),r.constrainedChoice&&(u=`${u} & ${le(r.constrainedChoice.variantType)}`),e.lineSM(`export type ${o} = ${u}`);let f=a.length>0&&!r.constrainedChoice?a.filter(m=>{let g=r.match[m];return Array.isArray(g)||typeof g!="object"||g===null}).map(m=>({key:m,typeLiteral:Zn(r.match[m])})):[];f.length>0?e.curlyBlock([`export type ${s} = ${o} &`],()=>{for(let m of f)e.lineSM(`readonly ${m.key}: ${m.typeLiteral}`);}):e.lineSM(`export type ${s} = ${o}`),e.line();}},tc=(e,t,n)=>{let i=n.params.length>0||n.sliceAutoFields.length>0,r=t.base.name==="Extension"?me(t):[];if(!i&&r.length===0)return;let o=`${Y(t)}Raw`;e.curlyBlock(["export","type",o,"="],()=>{for(let a of n.params)e.lineSM(`${a.name}: ${a.tsType}`);for(let a of n.sliceAutoFields)e.lineSM(`${a.name}?: ${a.tsType}`);let s=n.params.some(a=>a.name==="extension")||n.sliceAutoFields.some(a=>a.name==="extension");r.length>0&&!s&&e.lineSM("extension?: Extension[]");}),e.line();},nc=(e,t,n)=>{let i=t.base.name==="Extension"?me(t):[];if(i.length===0)return;let r=`${Y(t)}Flat`,o=[...n.params.filter(a=>a.name!=="extension").map(a=>({name:a.name,optional:false,tsType:a.tsType})),...n.sliceAutoFields.filter(a=>a.name!=="extension").map(a=>({name:a.name,optional:true,tsType:a.tsType})),...i.map(a=>({name:a.name,optional:!a.isRequired,tsType:`${a.tsType}${a.isArray?"[]":""}`}))],s=new Set;for(let a of o){if(s.has(a.name))throw new Error(`Flat input field collision for ${r}: ${a.name}`);s.add(a.name);}e.curlyBlock(["export","type",r,"="],()=>{for(let a of o)e.lineSM(`${a.name}${a.optional?"?":""}: ${a.tsType}`);}),e.line();},zr=(e,t,n)=>{let i=le(n.base),r=Y(n),o=jr(t,n),s=hn(t,n);qa(e,t,n,o,s),Xa(e,t,n),Qa(e,t,n),ec(e,n,o),tc(e,n,s),nc(e,n,s);let a=n.identifier.url;e.comment("CanonicalURL:",a,`(pkg: ${O(Be(n))})`),e.curlyBlock(["export","class",r],()=>{let c=t.findLastSpecializationByIdentifier(n.base);oe(c)?e.lineSM(`static readonly resourceType = ${JSON.stringify(c.name)}`):(vt(c)||et(c))&&e.logger()?.error(`Cannot emit static resourceType for profile '${r}': base '${n.base.url}' does not resolve to a specialization`),e.lineSM(`static readonly canonicalUrl = ${JSON.stringify(a)}`),e.line(),Ka(e,o),e.lineSM(`private resource: ${i}`),e.line(),Ya(e,t,n,s),Za(e,s),e.line("// Extensions"),Or(e,t,n),e.line("// Slices"),Lr(e,o,n),Ar(e,o,n),e.line("// Validation"),Vr(e,t,n);}),e.line();};var ic=e=>Le(import.meta.url,"typescript",e),Xn=e=>e[e.length-1]??"",rc=new Set(["Reference","Coding","CodeableConcept"]),oc=/CodeSystem$/,sc=/\[x\]/g,ac=/[^A-Za-z0-9_$]+/g,cc=/\\/g,lc=/[^a-z0-9-]+/g,pc=/^-+|-+$/g,dc=/^[A-Za-z_$]/,Wr=e=>{let t=e.replace(sc,"_x_").replace(ac,"_");return dc.test(t)?t:`_${t}`},Qn=e=>{let t=e.name??e.id??qe(e.url)??"Terminology";return Wr(`${R(t)}${e.resourceType}`)},Hr=e=>`${e.id??""}\0${e.name??""}`,Jr=e=>Rr(e.replace(cc,"_")).replace(lc,"-").replace(pc,"")||"package",fc=e=>{let t=e.map(Qn),n={};for(let r of t)n[r]=(n[r]??0)+1;let i=new Set;return e.map((r,o)=>{let s=t[o]??"Terminology",a=qe(r.url)??r.id??"Resource",c=n[s]===1?s:Wr(`${s}_${z(a)}`),l=c,p=2;for(;i.has(l);)l=`${c}_${p}`,p+=1;return i.add(l),{resource:r,symbol:l}})},Sn=class extends ve{packageDirectories=new Map;constructor(t){super({lineWidth:120,...t,resolveAssets:t.resolveAssets??ic});}packageDir(t){let n="package"in t?{name:t.package,version:t.version}:t;return this.packageDirectories.get(H(n))??Jr(n.name)}modulePath(t){return `${this.packageDir(t)}/${fn(t)}`}moduleSpecifier(t){return this.opts.moduleSpecifierStyle!=="node-esm"||!t.startsWith(".")||t.endsWith(".js")?t:`${t}.js`}directorySpecifier(t){return this.opts.moduleSpecifierStyle!=="node-esm"||!t.startsWith(".")?t:`${t}/index.js`}ifElseChain(t,n){t.forEach((i,r)=>{let o=r===0?"if":"} else if";this.line(`${o} (${i.cond}) {`),this.indent(),i.body(),this.deindent();}),n&&(this.line("} else {"),this.indent(),n(),this.deindent()),this.line("}");}tsImport(t,...n){let i=n[n.length-1],r=typeof i=="object"?i.typeOnly:false,o=typeof i=="object"?n.slice(0,-1):n,s=r?"import type":"import",a=this.moduleSpecifier(t),c=`${s} { ${o.join(", ")} } from "${a}"`;c.length<=(this.opts.lineWidth??120)?this.lineSM(c):this.curlyBlock([s],()=>{for(let l of o)this.line(`${l},`);},[` from "${a}";`]);}tsExport(t,...n){let i=n[n.length-1],r=typeof i=="object"?i.typeOnly:false,o=typeof i=="object"?n.slice(0,-1):n,s=r?"export type":"export";this.lineSM(`${s} { ${o.join(", ")} } from "${this.moduleSpecifier(t)}"`);}tsExportAll(t,n){let i=n?.barrel?this.directorySpecifier(t):this.moduleSpecifier(t);this.lineSM(`export * from "${i}"`);}generateFhirPackageIndexFile(t,n=false){this.cat("index.ts",()=>{n&&this.tsExportAll("./terminology"),t.filter(te).length>0&&this.tsExportAll("./profiles",{barrel:true});let r=t.flatMap(o=>{let s=D(o.identifier),a=te(o)?[]:[s,...ee(o)&&o.nested||je(o)&&o.nested?o.nested.map(l=>D(l.identifier)):[]],c=ee(o)?[`is${s}`]:[];return [{identifier:o.identifier,tsPackageName:fn(o.identifier),resourceName:s,typeExports:a,valueExports:c}]}).sort((o,s)=>o.resourceName.localeCompare(s.resourceName));r=Array.from(new Map(r.map(o=>[o.resourceName.toLowerCase(),o])).values()).sort((o,s)=>o.resourceName.localeCompare(s.resourceName));for(let o of r){this.debugComment(o.identifier);let s=`./${o.tsPackageName}`;o.typeExports.length>0&&this.tsExport(s,...o.typeExports,{typeOnly:true}),o.valueExports.length>0&&this.tsExport(s,...o.valueExports);}});}generateDependenciesImports(t,n,i="../"){if(n.dependencies){let r=[],o=[];for(let s of n.dependencies)["complex-type","resource","logical"].includes(s.kind)?r.push({tsPackage:`${i}${this.modulePath(s)}`,name:D(s),dep:s}):o.push(s);r.sort((s,a)=>s.name.localeCompare(a.name));for(let s of r)this.debugComment(s.dep),this.tsImport(s.tsPackage,s.name,{typeOnly:true});for(let s of o)this.debugComment("skip:",s);if(this.line(),this.withPrimitiveTypeExtension(n)&&n.identifier.name!=="Element"&&n.dependencies.find(s=>s.name==="Element")===void 0){let s="http://hl7.org/fhir/StructureDefinition/Element",a=t.resolveByUrl(n.identifier.package,s);if(!a)throw new Error(`'${s}' not found for ${n.identifier.package}.`);this.tsImport(`${i}${this.modulePath(a.identifier)}`,"Element",{typeOnly:true});}}}generateComplexTypeReexports(t){let n=t.dependencies?.filter(bt);if(n&&n.length>0){for(let i of n)this.debugComment(i),this.tsExport(`../${this.modulePath(i)}`,D(i),{typeOnly:true});this.line();}}addFieldExtension(t,n){let i=ue(`_${t}`),r=n?"(Element | null)[]":"Element";this.lineSM(`${i}?: ${r}`);}generateType(t,n,i){let r,s=["Reference","Coding","CodeableConcept"].includes(n.identifier.name);s?r=`${n.identifier.name}<T extends string = string>`:r=D(n.identifier);let a=s?[]:n.generic?.params??[],c={},l={};if(!s)for(let[d,u]of Object.entries(n.fields??{})){if(b(u)||!u.type)continue;let f=t.resolveType(u.type);if(!f||rc.has(f.identifier.name))continue;let m=ue(d),g=he(f)||_(f)?f.generic?.params:void 0;if(g?.length){let y=g.map(h=>a.find(x=>Xn(x.path)===Xn(h.path))?.typeVar??h.typeVar);l[m]=`<${y.join(", ")}>`;}else if(_(f)&&(f.typeFamily?.resources?.length??0)>0){let y=a.find(h=>Xn(h.path)===d);y&&(c[m]=y.typeVar);}}if(!s&&a.length>0){let d=a.map(u=>`${u.typeVar} extends ${u.constraint.name} = ${u.constraint.name}`);r+=`<${d.join(", ")}>`;}let p;if(n.base&&(p=`extends ${qe(n.base.url)}`),this.debugComment(n.identifier),!n.fields&&!p&&!ee(n)){this.lineSM(`export type ${r} = object`);return}this.curlyBlock(["export","interface",r,p],()=>{if(ee(n)){let u=[n.identifier,...n.typeFamily?.resources??[]],f=this.opts.openResourceTypeSet&&u.length>1?" | string":"";this.lineSM(`resourceType: ${u.sort((m,g)=>m.name.localeCompare(g.name)).map(m=>`"${m.name}"`).join(" | ")}${f}`),this.line();}if(!n.fields)return;let d=Object.entries(n.fields).sort((u,f)=>u[0].localeCompare(f[0]));for(let[u,f]of d){if(b(f)||!f.type)continue;this.debugComment(u,":",f);let m=ue(u),g=Jn(n.identifier.name,m,f,void 0,c,i),y=f.required?"":"?",h=f.array?"[]":"",x=l[m]??"";this.lineSM(`${m}${y}: ${g}${x}${h}`),this.withPrimitiveTypeExtension(n)&&M(f.type)&&this.addFieldExtension(u,f.array??false);}});}withPrimitiveTypeExtension(t){if(!this.opts.primitiveTypeExtension||!_(t))return false;for(let n of Object.values(t.fields??{}))if(!b(n)&&M(n.type))return true;return false}generateResourceTypePredicate(t){if(!ee(t))return;let n=D(t.identifier);this.curlyBlock(["export","const",`is${n}`,"=",`(resource: unknown): resource is ${n}`,"=>"],()=>{this.lineSM(`return resource !== null && typeof resource === "object" && (resource as {resourceType: string}).resourceType === "${t.identifier.name}"`);});}generateNestedTypes(t,n,i){if(n.nested)for(let r of n.nested)this.generateType(t,r,i),this.line();}generateResourceModule(t,n){if(te(n))this.cd("profiles",()=>{this.cat(`${$r(t,n)}`,()=>{this.generateDisclaimer(),Ur(this,t,n),zr(this,t,n);});});else if(_(n)){let i=t.isFamilyType;this.cat(`${Ir(n.identifier)}`,()=>{this.generateDisclaimer(),this.generateDependenciesImports(t,n),this.generateComplexTypeReexports(n),this.generateNestedTypes(t,n,i),this.comment("CanonicalURL:",n.identifier.url,`(pkg: ${O(Be(n))})`),this.generateType(t,n,i),this.generateResourceTypePredicate(n);});}else throw new Error(`Profile generation not implemented for kind: ${n.identifier.kind}`)}generateTerminologyTypes(t){this.cat("terminology-types.ts",()=>{this.generateDisclaimer(),t&&this.tsImport(t,"CodeSystem",{typeOnly:true}),this.line();let n=t?'CodeSystem["content"]':'("not-present" | "example" | "fragment" | "complete" | "supplement")';this.lineSM('export type TerminologyVerification = "registry-integrity" | "unverifiable" | (string & {})'),this.line(),this.curlyBlock(["type","TerminologyEntryBase","="],()=>{this.lineSM("canonicalUrl: string"),this.lineSM("packageId: string"),this.lineSM("packageVersion: string"),this.lineSM("verification: TerminologyVerification");},[";"]),this.line(),this.line("/** `contentMode` is a CodeSystem concept; the other entry kinds have none. */"),this.curlyBlock(["export","type","CodeSystemEntry","=","TerminologyEntryBase","&"],()=>{this.lineSM('resourceType: "CodeSystem"'),this.lineSM(`contentMode?: ${n}`);},[";"]),this.line(),this.curlyBlock(["export","type","ValueSetEntry","=","TerminologyEntryBase","&"],()=>{this.lineSM('resourceType: "ValueSet"');},[";"]),this.line(),this.curlyBlock(["export","type","NamingSystemEntry","=","TerminologyEntryBase","&"],()=>{this.lineSM('resourceType: "NamingSystem"');},[";"]),this.line(),this.line("/** One normalized terminology resource, discriminated by `resourceType`. */"),this.lineSM("export type TerminologyEntry = CodeSystemEntry | ValueSetEntry | NamingSystemEntry"),this.line(),this.line("/** A complete CodeSystem whose codes are embedded: the simplified runtime surface. */"),this.curlyBlock(["export","type","CodedTerminologyEntry<Code extends string = string>","=","CodeSystemEntry","&"],()=>{this.lineSM('contentMode: "complete"'),this.lineSM("codes: readonly Code[]"),this.lineSM("displays: Readonly<Partial<Record<Code, string>>>");},[";"]);});}terminologyModules=new Map;terminologyCodeIndex=new Map;prepareTerminology(t){this.terminologyModules=new Map,this.terminologyCodeIndex=new Map;for(let[n,i]of [...t].sort(([r],[o])=>r.localeCompare(o)))i.terminology&&this.prepareTerminologyModule(n,i.terminology);}prepareTerminologyModule(t,n){let{packageMeta:i}=n,r=this.opts.terminology?.packageVerification?.[H(i)]??"not-recorded",s=qi(n,r,this.logger()).slice().sort(({resource:l},{resource:p})=>{if(l.resourceType!==p.resourceType)return l.resourceType.localeCompare(p.resourceType);let d=Qn(l).localeCompare(Qn(p));if(d!==0)return d;let u=l.url.localeCompare(p.url);return u!==0?u:Hr(l).localeCompare(Hr(p))}),a=fc(s.map(({resource:l})=>l)),c=s.map(({entry:l},p)=>({entry:l,symbol:a[p]?.symbol??"Terminology"}));this.terminologyModules.set(t,c);for(let{entry:l,symbol:p}of c)"codes"in l&&!this.terminologyCodeIndex.has(l.canonicalUrl)&&this.terminologyCodeIndex.set(l.canonicalUrl,{moduleDir:t,symbol:p,codes:new Set(l.codes)});}linkFieldEnum(t,n){if(b(n)||!n.enum||n.enum.values.length===0||!n.binding)return;let i=t.resolveByUrl(n.binding.package,n.binding.url);if(!i)return;let r="concept"in i?i.concept:void 0;if(!r){let f=("dependencies"in i?i.dependencies??[]:[]).filter(y=>y.kind==="value-set"),m=f.length===1?f[0]:void 0,g=m?t.resolveByUrl(m.package,m.url):void 0;r=g&&"concept"in g?g.concept:void 0,!r&&m&&t.register&&(r=at(t.register,{name:m.package,version:m.version},m.url,this.logger()));}if(!r||r.length===0)return;let o=new Set(r.map(({code:u})=>u)),s=n.enum.values;if(s.length!==o.size||!s.every(u=>o.has(u)))return;let a=new Map;for(let u of r){if(!u.system)continue;let f=a.get(u.system)??new Set;f.add(u.code),a.set(u.system,f);}let c=[],l=new Set,p=new Map;for(let[u,f]of a){let m=this.terminologyCodeIndex.get(u);if(!m||f.size!==m.codes.size||![...f].every(y=>m.codes.has(y)))continue;c.push(`...${m.symbol}.codes`);for(let y of f)l.add(y);let g=p.get(m.moduleDir)??new Set;g.add(m.symbol),p.set(m.moduleDir,g);}if(c.length===0)return;let d=s.filter(u=>!l.has(u)).map(u=>JSON.stringify(u));return {expr:`[${[...c,...d].join(", ")}]`,imports:p}}enumTerminologyLinks(t,n){let i=new Map,r=new Map;if(this.terminologyCodeIndex.size===0)return {exprs:i,imports:r};for(let[o,s]of Object.entries(n.fields)){let a=this.linkFieldEnum(t,s);if(a){i.set(o,a.expr);for(let[c,l]of a.imports){let p=r.get(c)??new Set;for(let d of l)p.add(d);r.set(c,p);}}}return {exprs:i,imports:r}}generateTerminologyModule(t){let n=this.terminologyModules.get(t)??[];this.cat("terminology.ts",()=>{this.generateDisclaimer();let r=n.some(({entry:o})=>"codes"in o)?["TerminologyEntry","CodedTerminologyEntry"]:["TerminologyEntry"];this.tsImport("../terminology-types",...r,{typeOnly:true}),this.line(),n.forEach(({entry:o,symbol:s},a)=>{let c="codes"in o,l=s.endsWith("CodeSystem")?s.replace(oc,"Code"):`${s}Code`;if(c){let d=o.codes.map(u=>JSON.stringify(u)).join(" | ")||"never";this.lineSM(`export type ${l} = ${d}`);}let p=c?` as const satisfies CodedTerminologyEntry<${l}>;`:" as const satisfies TerminologyEntry;";this.curlyBlock(["export","const",s,"="],()=>{this.line(`canonicalUrl: ${JSON.stringify(o.canonicalUrl)},`),this.line(`packageId: ${JSON.stringify(o.packageId)},`),this.line(`packageVersion: ${JSON.stringify(o.packageVersion)},`),this.line(`verification: ${JSON.stringify(o.verification)},`),this.line(`resourceType: ${JSON.stringify(o.resourceType)},`),"contentMode"in o&&o.contentMode!==void 0&&this.line(`contentMode: ${JSON.stringify(o.contentMode)},`),c&&(this.line(`codes: [${o.codes.map(d=>JSON.stringify(d)).join(", ")}],`),this.curlyBlock(["displays:"],()=>{for(let d of o.codes){let u=o.displays[d];u!==void 0&&this.line(`${Fr(d)}: ${JSON.stringify(u)},`);}},[","]));},[p]),a<n.length-1&&this.line();});});}async generate(t){let n=[...t.collectComplexTypes(),...t.collectResources(),...t.collectLogicalModels(),...this.opts.generateProfile?t.collectSnapshotProfiles():[]],i=this.opts.terminology?.packages,r=this.opts.terminology?.enabled?(t.register?.allTerminology()??[]).filter(({packageMeta:d,resources:u})=>u.length>0&&(i===void 0||i.includes(H(d)))):[],o=new Map;for(let d of n){let u=Be(d),f=H(u),m=o.get(f)??{packageMeta:u,packageSchemas:[]};m.packageSchemas.push(d),o.set(f,m);}for(let d of r){let u=H(d.packageMeta),f=o.get(u)??{packageMeta:d.packageMeta,packageSchemas:[]};f.terminology=d,o.set(u,f);}let s=new Map;for(let[d,{packageMeta:u}]of o){let f=s.get(u.name)??[];f.push(d),s.set(u.name,f);}let a=new Map;for(let[d,{packageMeta:u,packageSchemas:f,terminology:m}]of o){let g=(s.get(u.name)?.length??0)>1?H(u):u.name,y=Jr(g),h=a.get(y)??[],k=[...new Map(f.map($=>[JSON.stringify($.identifier),$])).values()].sort(($,q)=>$.identifier.name.localeCompare(q.identifier.name));h.push({identity:d,packageSchemas:k,terminology:m}),a.set(y,h);}let c=new Map,l=new Set;for(let[d,u]of a){if(u.length!==1)continue;let f=u[0];f&&(c.set(d,f),l.add(d));}for(let[d,u]of [...a].sort(([f],[m])=>f.localeCompare(m))){if(u.length<2)continue;let f=1;for(let m of u.sort((g,y)=>g.identity.localeCompare(y.identity))){let g=`${d}--${f}`;for(;l.has(g);)f+=1,g=`${d}--${f}`;c.set(g,m),l.add(g),f+=1;}}this.packageDirectories=new Map([...c].flatMap(([d,u])=>{if(u.terminology)return [[H(u.terminology.packageMeta),d]];let f=u.packageSchemas[0];return f?[[H(Be(f)),d]]:[]}));let p=this.opts.generateProfile&&n.some(te);this.prepareTerminology(c),this.cd("/",()=>{if(p&&this.cp("profile-helpers.ts","profile-helpers.ts"),r.length>0){let d=n.find(u=>u.identifier.url==="http://hl7.org/fhir/StructureDefinition/CodeSystem");this.generateTerminologyTypes(d?`./${this.packageDir(d.identifier)}/CodeSystem`:void 0);}for(let[d,{packageSchemas:u,terminology:f}]of [...c].sort(([m],[g])=>m.localeCompare(g)))this.cd(d,()=>{for(let m of u)this.generateResourceModule(t,m);Gr(this,t,u.filter(te)),f&&this.generateTerminologyModule(d),this.generateFhirPackageIndexFile(u,f!==void 0);});});}};var mc=async(e,t)=>{t.info("Cleaning outputs...");try{t.info(`Clean ${e.outputDir}`),U.rmSync(e.outputDir,{recursive:!0,force:!0});}catch(n){t.warn(`Error cleaning output directory: ${n instanceof Error?n.message:String(n)}`);}},xn=class{options;manager;prebuiltRegister;managerInput;logger;generators=[];constructor(t={}){let r={...{outputDir:"./generated",cleanOutput:true,throwException:false},...Object.fromEntries(["outputDir","cleanOutput","throwException","typeSchema"].filter(p=>t[p]!==void 0).map(p=>[p,t[p]]))};this.managerInput={npmPackages:[],localSDs:[],localTgzPackages:[]},this.prebuiltRegister=t.register,this.logger=t.logger??Q({prefix:"api"});let o=p=>typeof p.init=="function";t.manager&&this.logger.warn("'manager' is deprecated; pass the instance via 'canonicalManager' instead.");let s=t.manager??(t.canonicalManager&&o(t.canonicalManager)?t.canonicalManager:void 0);if(s&&t.register)throw new Error("Cannot provide both a CanonicalManager instance and 'register'. Use one or the other.");let a=t.canonicalManager&&!o(t.canonicalManager)?t.canonicalManager:void 0,c={...a},l=[["registry","registry",t.registry],["packageIndex","packageIndex",t.packageIndex],["dropCache","dropCanonicalManagerCache",t.dropCanonicalManagerCache],["patches","patches",t.patches]];for(let[p,d,u]of l)if(u!==void 0){if(c[p]!==void 0)throw new Error(`Cannot set both 'canonicalManager.${p}' and the deprecated '${d}'.`);this.logger.warn(`'${d}' is deprecated; use 'canonicalManager: { ${p} }' \u2014 it configures the CanonicalManager package loader.`),c[p]=u;}this.manager=s??CanonicalManager({packages:[],workingDir:c.workingDir??".codegen-cache/canonical-manager-cache",registry:c.registry,dropCache:c.dropCache,patches:{packageJson:c.patches?.packageJson??[],indexEntry:[...t.builtinPatches??true?fi.indexEntry??[]:[],...c.patches?.indexEntry??[]],fhirResource:c.patches?.fhirResource??[]},preprocessPackage:t.preprocessPackage,packageIndex:c.packageIndex,ignorePackageIndex:t.ignorePackageIndex}),a&&(s||t.register)&&this.logger.warn("loader configuration is ignored when a prebuilt manager/`register` is provided."),this.options=r;}fromPackage(t,n){let i=H({name:t,version:n||"latest"});return this.managerInput.npmPackages.push(i),this}fromPackageRef(t){return this.managerInput.npmPackages.push(t),this}localStructureDefinitions(t){return this.logger.info(`Registering local StructureDefinitions for ${t.package.name}@${t.package.version}`),this.managerInput.localSDs.push({name:t.package.name,version:t.package.version,path:t.path,dependencies:t.dependencies?.map(n=>H(n))}),this}localTgzPackage(t){return this.logger.info(`Registering local tgz package: ${t}`),this.managerInput.localTgzPackages.push({archivePath:w.resolve(t)}),this}introspection(t){let i={...{logger:this.logger,outputDir:this.options.outputDir,inMemoryOnly:false},...Object.fromEntries(Object.entries(t??{}).filter(([o,s])=>s!==void 0))},r=new nn(i);return this.generators.push({name:"introspection",writer:r}),this.logger.debug(`Configured introspection generator (${JSON.stringify(i,void 0,2)})`),this}typescript(t){let r={...{...{logger:this.logger,outputDir:this.generatorOutputDir("/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//",generateProfile:true},openResourceTypeSet:false,primitiveTypeExtension:true},...Object.fromEntries(Object.entries(t).filter(([s,a])=>a!==void 0))};r.terminology?.enabled&&(this.wantsTerminologyTypes=true);let o=new Sn(r);return this.generators.push({name:"typescript",writer:o}),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(r,void 0,2)})`),this}python(t){let r={...{...{logger:this.logger,outputDir:this.options.outputDir,tabSize:4,withDebugComment:false,commentLinePrefix:"#"},rootPackageName:"fhir_types",fieldFormat:"camelCase",primitiveTypeExtension:false},...Object.fromEntries(Object.entries(t).filter(([s,a])=>a!==void 0))},o=new wt(r);return this.generators.push({name:"python",writer:o}),this.logger.debug("Configured python generator"),this}mustache(t,n){let i={logger:this.logger,outputDir:this.options.outputDir},r={meta:{timestamp:new Date().toISOString(),generator:"atomic-codegen"}},o={...i,...r,...n},s=br(t,o);return this.generators.push({name:`mustache[${t}]`,writer:s}),this.logger.debug(`Configured TypeScript generator (${JSON.stringify(o,void 0,2)})`),this}csharp(t){let r={...{...{logger:this.logger,outputDir:this.generatorOutputDir("/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},rootNamespace:"Fhir.Types"},...Object.fromEntries(Object.entries(t).filter(([s,a])=>a!==void 0))},o=new Nt(r);return this.generators.push({name:"csharp",writer:o}),this.logger.debug("Configured C# generator"),this}explicitOutputDir;generatorOutputDir(t){return this.explicitOutputDir!==void 0?this.explicitOutputDir:t===void 0?this.options.outputDir:w.join(this.options.outputDir,t)}outputTo(t){this.logger.debug(`Setting output directory: ${t}`),this.options.outputDir=t,this.explicitOutputDir=t;for(let n of this.generators)n.writer.setOutputDir(t);return this}throwException(t=true){return this.options.throwException=t,this}cleanOutput(t=true){return this.options.cleanOutput=t,this}wantsTerminologyTypes=false;typeSchema(t){return this.options.typeSchema??={},t.treeShake&&(xe(this.options.typeSchema.treeShake===void 0,"treeShake option is already set"),this.options.typeSchema.treeShake=t.treeShake),t.treeShakeDefaults&&(xe(this.options.typeSchema.treeShakeDefaults===void 0,"treeShakeDefaults option is already set"),this.options.typeSchema.treeShakeDefaults=t.treeShakeDefaults),t.promoteLogical&&(xe(this.options.typeSchema.promoteLogical===void 0,"promoteLogical option is already set"),this.options.typeSchema.promoteLogical=t.promoteLogical),t.resolveCollisions&&(xe(this.options.typeSchema.resolveCollisions===void 0,"resolveCollisions option is already set"),this.options.typeSchema.resolveCollisions=t.resolveCollisions),this.irReport({}),this}irReport(t){let i={...{logger:this.logger,outputDir:this.options.outputDir,inMemoryOnly:false},rootReadmeFileName:"README.md",...Object.fromEntries(Object.entries(t??{}).filter(([o,s])=>s!==void 0))},r=new rn(i);return this.generators.push({name:"ir-report",writer:r}),this.logger.debug(`Configured ir-report generator (${JSON.stringify(i,void 0,2)})`),this}async generate(){let t=performance.now(),n={success:false,outputDir:this.options.outputDir,filesGenerated:{},errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.length} generators`);try{let i=this.generators.some(u=>!u.writer.opts.inMemoryOnly);this.options.cleanOutput&&i&&await mc(this.options,this.logger);let r;if(this.prebuiltRegister)this.logger.info("Using prebuilt register"),r=this.prebuiltRegister;else {this.logger.info("Initialize Canonical Manager"),this.managerInput.npmPackages.length>0&&await this.manager.addPackages(...this.managerInput.npmPackages.sort());for(let m of this.managerInput.localSDs)await this.manager.addLocalPackage(m);for(let m of this.managerInput.localTgzPackages)await this.manager.addTgzPackage(m);let u=await this.manager.init(),f=Object.values(u);r=await Bn(this.manager,{logger:this.logger.fork("reg"),focusedPackages:f}),n.inputReport=this.manager.report();}let o=this.logger.fork("ts"),{schemas:s,collisions:a}=await tn(r,this.options.typeSchema?.resolveCollisions,o),c={resolveCollisions:this.options.typeSchema?.resolveCollisions,collisions:a},p=Rn(s,{register:r,irReport:c,logger:o});if(this.options.typeSchema?.treeShake){let u=this.options.typeSchema.treeShake;if(this.wantsTerminologyTypes){let f="http://hl7.org/fhir/StructureDefinition/CodeSystem",m=p.schemas.find(g=>g.identifier.url===f);if(m){let g=m.identifier.package;u={...u,[g]:{...u[g]??{},[f]:{}}};}}p=gr(p,u,this.options.typeSchema.treeShakeDefaults);}this.options.typeSchema?.promoteLogical&&(p=mr(p,this.options.typeSchema.promoteLogical)),o.printTagSummary(),this.logger.debug(`Executing ${this.generators.length} generators`),await this.executeGenerators(n,p),this.logger.info("Generation completed successfully"),n.success=n.errors.length===0;let d=Object.values(n.filesGenerated).reduce((u,f)=>u+Object.keys(f).length,0);this.logger.debug(`Generation completed: ${d} files`);}catch(i){if(this.logger.error(`Code generation failed: ${i instanceof Error?i.message:String(i)}`),n.errors.push(i instanceof Error?i.message:String(i)),this.options.throwException)throw i}return {...n,success:n.errors.length===0,duration:performance.now()-t}}reset(){return this.generators=[],this}getGenerators(){return this.generators.map(t=>t.name)}async executeGenerators(t,n){for(let i of this.generators){this.logger.info(`Generating ${i.name}...`);try{await i.writer.generateAsync(n);let r=i.writer.writtenFiles(),o=t.filesGenerated[i.name]??={};r.forEach(s=>{o[s.relPath]=s.content;}),this.logger.info(`Generating ${i.name} finished successfully`);}catch(r){if(t.errors.push(`${i.name} generator failed: ${r instanceof Error?r.message:String(r)}`),this.options.throwException)throw r}}}};var gt=1,Xe=class extends Error{issues;constructor(t){super([`Invalid generate config (${t.length} problem${t.length===1?"":"s"}):`].concat(t.map(n=>` ${n.path||"<root>"}: ${n.message}`)).join(`
|
|
18
|
+
`)),this.name="GenerateConfigError",this.issues=t;}},gc=["version","options","builders"],yc=["registry","ignorePackageIndex","dropCanonicalManagerCache","throwException","forceDependencies"],hc=["name","fromPackages","fromPackageRefs","localTgzPackages","localStructureDefinitions","typeSchema","introspection","typescript","python","csharp","outputTo","cleanOutput","throwException"],Sc=["name","version"],Tc=["package","path","dependencies"],xc=["treeShake","treeShakeDefaults","promoteLogical","resolveCollisions"],Cc=["ignoreFields","selectFields","ignoreExtensions","followReferences"],Yr=["inMemoryOnly"],ri=[...Yr,"tabSize","withDebugComment","commentLinePrefix","generateProfile"],kc=[...ri,"lineWidth","openResourceTypeSet","primitiveTypeExtension","moduleSpecifierStyle","extensionGetterDefault","sliceGetterDefault","terminology"],bc=["enabled","packages","packageVerification"],vc=[...ri,"allowExtraFields","primitiveTypeExtension","rootPackageName","fieldFormat","client","fhirpyClient"],Rc=[...ri,"staticSourceDir","rootNamespace"],Ic=[...Yr,"typeSchemas","typeTree","fhirSchemas","structureDefinitions"],Kr=["fromPackages","fromPackageRefs","localTgzPackages","localStructureDefinitions"],ti=["introspection","typescript","python","csharp"],$c=(e,t)=>{if(e===t)return "duplicates";if(t.startsWith(e+w.sep))return "is nested inside";if(e.startsWith(t+w.sep))return "contains"},Zr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yt=e=>e===null?"null":Array.isArray(e)?"an array":typeof e=="string"?`a string (${JSON.stringify(e)})`:`a ${typeof e}`,I=(e,t)=>e===""?t:`${e}.${t}`,J=(e,t,n)=>{e.issues.push({path:t,message:n});},ge=(e,t,n,i)=>{for(let r of Object.keys(t))n.includes(r)||J(e,I(i,r),`unknown key "${r}"; allowed keys: ${n.join(", ")}`);},ie=(e,t,n)=>Zr(t)?t:J(e,n,`expected an object, got ${yt(t)}`),ke=(e,t,n)=>typeof t!="string"?J(e,n,`expected a string, got ${yt(t)}`):t.trim()===""?J(e,n,"must not be empty"):t,Ze=(e,t,n)=>typeof t=="boolean"?t:J(e,n,`expected a boolean, got ${yt(t)}`),Cn=(e,t,n)=>Array.isArray(t)?t:J(e,n,`expected an array, got ${yt(t)}`),ni=(e,t,n)=>{let i=Cn(e,t,n);if(!i)return;let r=[];return i.forEach((o,s)=>{let a=ke(e,o,`${n}[${s}]`);a!==void 0&&r.push(a);}),r},Xr=(e,t,n)=>{let i=ie(e,t,n);if(!i)return;let r={};for(let[o,s]of Object.entries(i)){let a=ke(e,s,I(n,o));a!==void 0&&(r[o]=a);}return r},ii=(e,t)=>w.resolve(e.configDir,t),Qr=(e,t,n)=>{let i=ie(e,t,n);if(!i)return;ge(e,i,Sc,n);let r=ke(e,i.name,I(n,"name")),o=ke(e,i.version,I(n,"version"));if(!(r===void 0||o===void 0))return {name:r,version:o}},eo=(e,t,n)=>{let i=Cn(e,t,n);if(!i)return;let r=[];return i.forEach((o,s)=>{let a=Qr(e,o,`${n}[${s}]`);a&&r.push(a);}),r},Fc=(e,t,n)=>{let i=Cn(e,t,n);if(!i)return;let r=[];return i.forEach((o,s)=>{let a=`${n}[${s}]`,c=ie(e,o,a);if(!c)return;ge(e,c,Tc,a);let l=Qr(e,c.package,I(a,"package")),p=ke(e,c.path,I(a,"path")),d=c.dependencies===void 0?void 0:eo(e,c.dependencies,I(a,"dependencies"));!l||p===void 0||r.push({package:l,path:ii(e,p),dependencies:d});}),r},Pc=(e,t,n)=>{let i=ie(e,t,n);if(i)for(let[r,o]of Object.entries(i)){let s=I(n,r),a=ie(e,o,s);if(a)for(let[c,l]of Object.entries(a)){let p=I(s,c),d=ie(e,l,p);d&&ge(e,d,Cc,p);}}},Nc=(e,t,n)=>{let i=ie(e,t,n);if(i)return ge(e,i,xc,n),i.treeShake!==void 0&&Pc(e,i.treeShake,I(n,"treeShake")),i},ei=(e,t,n,i)=>{let r=ie(e,t,n);if(r)return ge(e,r,i,n),r},Ec=(e,t,n)=>{let i=ie(e,t,n);if(!i)return;ge(e,i,kc,n);let r=I(n,"moduleSpecifierStyle"),o=i.moduleSpecifierStyle===void 0?void 0:ke(e,i.moduleSpecifierStyle,r);if(o!==void 0&&!["extensionless","node-esm"].includes(o)&&J(e,r,"expected one of: extensionless, node-esm"),i.terminology===void 0)return i;let s=I(n,"terminology"),a=ie(e,i.terminology,s);if(!a)return i;ge(e,a,bc,s);let c=a.enabled===void 0?void 0:Ze(e,a.enabled,I(s,"enabled")),l=a.packages===void 0?void 0:ni(e,a.packages,I(s,"packages")),p=a.packageVerification===void 0?void 0:Xr(e,a.packageVerification,I(s,"packageVerification"));return {...i,terminology:{enabled:c,packages:l,packageVerification:p}}},Oc=(e,t,n)=>{let i=ie(e,t,n);if(!i)return;ge(e,i,hc,n);let r=ke(e,i.name,I(n,"name")),o=i.outputTo===void 0?J(e,I(n,"outputTo"),"outputTo is required; a builder must name its output directory"):ke(e,i.outputTo,I(n,"outputTo")),s={};if(i.fromPackages!==void 0&&(s.fromPackages=eo(e,i.fromPackages,I(n,"fromPackages"))),i.fromPackageRefs!==void 0&&(s.fromPackageRefs=ni(e,i.fromPackageRefs,I(n,"fromPackageRefs"))),i.localTgzPackages!==void 0){let l=ni(e,i.localTgzPackages,I(n,"localTgzPackages"));s.localTgzPackages=l?.map(p=>ii(e,p));}if(i.localStructureDefinitions!==void 0&&(s.localStructureDefinitions=Fc(e,i.localStructureDefinitions,I(n,"localStructureDefinitions"))),i.typeSchema!==void 0&&(s.typeSchema=Nc(e,i.typeSchema,I(n,"typeSchema"))),i.introspection!==void 0&&(s.introspection=ei(e,i.introspection,I(n,"introspection"),Ic)),i.typescript!==void 0&&(s.typescript=Ec(e,i.typescript,I(n,"typescript"))),i.python!==void 0&&(s.python=ei(e,i.python,I(n,"python"),vc)),i.csharp!==void 0&&(s.csharp=ei(e,i.csharp,I(n,"csharp"),Rc)),i.cleanOutput!==void 0&&(s.cleanOutput=Ze(e,i.cleanOutput,I(n,"cleanOutput"))),i.throwException!==void 0&&(s.throwException=Ze(e,i.throwException,I(n,"throwException"))),Kr.some(l=>i[l]!==void 0)||J(e,n,`no input configured; set at least one of ${Kr.join(", ")} or the builder generates nothing`),ti.some(l=>i[l]!==void 0)||J(e,n,`no output generator configured; set at least one of ${ti.join(", ")} or the builder writes nothing`),!(r===void 0||o===void 0))return {...s,name:r,outputTo:ii(e,o)}},_c=(e,t,n)=>{let i=ie(e,t,n);if(!i)return;ge(e,i,yc,n);let r={};return i.registry!==void 0&&(r.registry=ke(e,i.registry,I(n,"registry"))),i.ignorePackageIndex!==void 0&&(r.ignorePackageIndex=Ze(e,i.ignorePackageIndex,I(n,"ignorePackageIndex"))),i.dropCanonicalManagerCache!==void 0&&(r.dropCanonicalManagerCache=Ze(e,i.dropCanonicalManagerCache,I(n,"dropCanonicalManagerCache"))),i.throwException!==void 0&&(r.throwException=Ze(e,i.throwException,I(n,"throwException"))),i.forceDependencies!==void 0&&(r.forceDependencies=Xr(e,i.forceDependencies,I(n,"forceDependencies"))),r},to=(e,t)=>{let n={issues:[],configDir:w.dirname(w.resolve(t))},i=ie(n,e,"");if(!i)throw new Xe(n.issues);ge(n,i,gc,""),i.version===void 0?J(n,"version",`version is required; expected ${gt}`):typeof i.version!="number"?J(n,"version",`expected the number ${gt}, got ${yt(i.version)}`):i.version!==gt&&J(n,"version",`unsupported config version ${i.version}; this build understands ${gt}`);let r=i.options===void 0?void 0:_c(n,i.options,"options"),o=[];if(i.builders===void 0)J(n,"builders","builders is required and must list at least one builder");else {let a=Cn(n,i.builders,"builders");a&&a.length===0&&J(n,"builders","must list at least one builder"),a?.forEach((c,l)=>{let p=Oc(n,c,`builders[${l}]`);p&&o.push(p);});}let s=new Set;if(o.forEach((a,c)=>{s.has(a.name)&&J(n,`builders[${c}].name`,`duplicate builder name "${a.name}"; names must be unique`),s.add(a.name);}),o.forEach((a,c)=>{for(let l of o.slice(0,c)){let p=$c(l.outputTo,a.outputTo);p&&J(n,`builders[${c}].outputTo`,`${p} the output directory of builder "${l.name}"; output directories must not overlap`);}}),n.issues.length>0)throw new Xe(n.issues);return {version:gt,options:r,builders:o}},Mc=e=>(t,n)=>{let i=n.dependencies;if(!Zr(i))return;let r=false,o={...i};for(let[s,a]of Object.entries(e))s in o&&o[s]!==a&&(o[s]=a,r=true);if(r)return {...n,dependencies:o}},Dc=e=>new xn(e),Bc=async(e,t,n,i)=>{let r={registry:t.registry,dropCache:t.dropCanonicalManagerCache,patches:t.forceDependencies?{packageJson:[Mc(t.forceDependencies)]}:void 0};t.ignorePackageIndex!==void 0&&(r.packageIndex=t.ignorePackageIndex?"regenerate":"use");try{let o=n({canonicalManager:r,logger:i});for(let c of e.fromPackages??[])o.fromPackage(c.name,c.version);for(let c of e.fromPackageRefs??[])o.fromPackageRef(c);for(let c of e.localTgzPackages??[])o.localTgzPackage(c);for(let c of e.localStructureDefinitions??[])o.localStructureDefinitions(c);e.typeSchema&&o.typeSchema(e.typeSchema),e.introspection&&o.introspection(e.introspection),e.typescript&&o.typescript(e.typescript),e.python&&o.python(e.python),e.csharp&&o.csharp(e.csharp),o.outputTo(e.outputTo),e.cleanOutput!==void 0&&o.cleanOutput(e.cleanOutput);let s=e.throwException??t.throwException;s!==void 0&&o.throwException(s);let a=await o.generate();return {name:e.name,success:a.success,outputDir:e.outputTo,errors:a.errors,report:a}}catch(o){return {name:e.name,success:false,outputDir:e.outputTo,errors:[o instanceof Error?o.message:String(o)]}}},no=async(e,t={})=>{let n=t.createBuilder??Dc,i=e.options??{},r=[];for(let o of e.builders)r.push(await Bc(o,i,n,t.logger));return {success:r.every(o=>o.success),builders:r}},jc=e=>{let t=[];for(let n of e.fromPackages??[])t.push(`package ${n.name}@${n.version}`);for(let n of e.fromPackageRefs??[])t.push(`package ref ${n}`);for(let n of e.localTgzPackages??[])t.push(`local tgz ${n}`);for(let n of e.localStructureDefinitions??[])t.push(`local StructureDefinitions ${n.package.name}@${n.package.version} from ${n.path}`);return t},io=e=>{let t=e.options??{},n=[`Generate plan (${e.builders.length} builder(s)):`],i=[];t.registry&&i.push(`registry: ${t.registry}`),t.ignorePackageIndex!==void 0&&i.push(`ignorePackageIndex: ${t.ignorePackageIndex}`),t.dropCanonicalManagerCache!==void 0&&i.push(`dropCanonicalManagerCache: ${t.dropCanonicalManagerCache}`),t.throwException!==void 0&&i.push(`throwException: ${t.throwException}`);for(let[r,o]of Object.entries(t.forceDependencies??{}))i.push(`forceDependencies: ${r} -> ${o}`);return i.length>0&&n.push(" options:",...i.map(r=>` ${r}`)),e.builders.forEach((r,o)=>{let s=ti.filter(c=>r[c]!==void 0);n.push(` ${o+1}. ${r.name}`);for(let c of jc(r))n.push(` input: ${c}`);n.push(` generators: ${s.length>0?s.join(", "):"none"}`),r.typeSchema&&n.push(` typeSchema: ${Object.keys(r.typeSchema).join(", ")}`),n.push(` outputTo: ${r.outputTo}`);let a=r.cleanOutput??true;n.push(` cleanOutput: ${a}${r.cleanOutput===void 0?" (default)":""}${a?" \u2014 removes outputTo before generation":""}`);}),n.join(`
|
|
19
|
+
`)};var Ac=async e=>{let t;try{t=await readFile(e,"utf-8");}catch(n){throw new Error(`Cannot read config file ${e}: ${n instanceof Error?n.message:n}`)}try{return JSON.parse(t)}catch(n){throw new Error(`Config file ${e} is not valid JSON: ${n instanceof Error?n.message:n}`)}},Vc=e=>{for(let t of e.builders){if(t.success){St(`${t.name}: generated into ${t.outputDir}`);continue}console.error(`${t.name}: FAILED`),be(t.errors.length>0?t.errors:["generation reported no details"]);}},wc=async(e,t={})=>{let n=pi({prefix:"generate"}),i=w.resolve(e.config),r;try{let s=to(await Ac(i),i);if(e.dryRun)return console.log(io(s)),n.info("Dry run: nothing was generated"),0;r=await no(s,{logger:n,...t});}catch(s){return s instanceof Xe?n.error(s.message):n.error(s instanceof Error?s.message:String(s)),1}if(Vc(r),r.success)return 0;let o=r.builders.filter(s=>!s.success).map(s=>s.name);return n.error(`${o.length} of ${r.builders.length} builder(s) failed: ${o.join(", ")}`),1},oo={command:"generate",describe:"Generate code from a JSON configuration file",builder:{config:{alias:"c",type:"string",demandOption:true,describe:"Path to the JSON generation config. Relative paths inside it resolve against its directory"},"dry-run":{type:"boolean",default:false,describe:"Validate the config and print the resolved plan without generating anything"}},handler:async e=>{let t=await wc({config:e.config,dryRun:e.dryRun});t!==0&&process.exit(t);}};var so={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 e=>{let t=Q({prefix:"TypeSchema"});try{t.info("Generating TypeSchema from FHIR packages"),t.info(`Packages: ${e.packages.join(", ")}`),t.info(`Output: ${e.output}`);let n=e.singleFile?"ndjson":e.format;t.debug(`Format: ${n}${e.singleFile&&e.format==="json"?" (forced from json due to singleFile)":""}`),e.treeshake&&e.treeshake.length>0&&t.info(`Treeshaking enabled for ResourceTypes: ${e.treeshake.join(", ")}`),e.singleFile&&t.info("Single file output enabled (NDJSON format)"),e.registry&&t.info(`Using custom registry: ${e.registry}`);let i=Date.now(),r=e.packages.map(p=>{if(p.includes("@")){let d=p.lastIndexOf("@");return {name:p.slice(0,d),version:p.slice(d+1)||"latest"}}return {name:p,version:"latest"}});t.info(`Processing packages: ${r.map(p=>`${p.name}@${p.version}`).join(", ")}`);let o=await Zi(r,{logger:t,registry:e.registry,focusedPackages:r}),{schemas:s}=await tn(o,void 0,t);if(s.length===0)throw new Error("No schemas were generated from the specified packages");let a=e.output;if(!a)throw new Error("Output format not specified");await mkdir(dirname(a),{recursive:!0});let c;n==="json"?c=JSON.stringify(s,null,2):c=s.map(p=>JSON.stringify(p)).join(`
|
|
20
|
+
`),await writeFile(a,c,"utf-8");let l=Date.now()-i;if(St(`Generated ${s.length} TypeSchema definitions`,l,{schemas:s.length}),t.info(`Output: ${a}`),e.verbose){t.debug("Generated schemas:");let p=s.map(d=>`${d.identifier?.name||"Unknown"} (${d.identifier?.kind||"unknown"})`);be(p);}}catch(n){t.error(`Failed to generate TypeSchema: ${n instanceof Error?n.message:String(n)}`),process.exit(1);}}};var oi=Q({prefix:"typeschema"}),ao={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:e=>e.command(so).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:e=>{if(!e.subcommand&&e._.length===1){oi.info("Available typeschema subcommands:"),be(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
|
|
10
21
|
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
|
|
11
|
-
Examples:`),
|
|
12
|
-
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};var
|
|
22
|
+
Examples:`),be(["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}e.subcommand&&!["generate","validate","merge"].includes(e.subcommand)&&(oi.error(`Unknown typeschema subcommand: ${e.subcommand}`),oi.info("Available typeschema subcommands:"),be(["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(`
|
|
23
|
+
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};var si=Q({prefix:"cli"});async function Wc(e){let t=e.logLevel??(e.debug||e.verbose?"DEBUG":"INFO");si=Q({prefix:"cli",level:t});}function qc(){return Hc(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Wc).command(ao).command(oo).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}).demandCommand(0).middleware(e=>{e._.length===0&&(ci("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code from a JSON configuration file"),console.log(`
|
|
13
24
|
Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
|
|
14
|
-
Quick examples:`),console.log(" atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson"),console.log(`
|
|
15
|
-
Use 'atomic-codegen --help' to see all options.`),process.exit(0));}).help().version(
|
|
25
|
+
Quick examples:`),console.log(" atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson"),console.log(" atomic-codegen generate --config ./codegen.json"),console.log(`
|
|
26
|
+
Use 'atomic-codegen --help' to see all options.`),process.exit(0));}).help().version(di.version).example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").example("$0 generate --config ./codegen.json","Run the generation pipelines described by a config file").fail((e,t,n)=>{si.error(t?t.message:e),si.error("Use --help for usage information"),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function co(){await qc().parseAsync();}co().catch(e=>{console.error("CLI Error:",e instanceof Error?e.message:e),process.exit(1);});
|