@atomic-ehr/codegen 0.0.1-canary.20251009074815.3e20aa6 → 0.0.1-canary.20251009083957.bf76104
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +6 -6
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import Pr from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';import'ora';import y from'picocolors';import*as F from'fs';import {existsSync,mkdirSync}from'fs';import*as q from'path';import {dirname,resolve,join,relative}from'path';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as ct from'@atomic-ehr/fhirschema';import {mkdir,writeFile,readFile,readdir,stat,unlink,access,rm}from'fs/promises';var Ce=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Ht=Object.prototype.hasOwnProperty;var Ut=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var W=(s,e)=>()=>(s&&(e=s(s=0)),e);var Fe=(s,e)=>{for(var t in e)Ce(s,t,{get:e[t],enumerable:true});},
|
|
2
|
+
import Pr from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';import'ora';import y from'picocolors';import*as F from'fs';import {existsSync,mkdirSync}from'fs';import*as q from'path';import {dirname,resolve,join,relative}from'path';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as ct from'@atomic-ehr/fhirschema';import {mkdir,writeFile,readFile,readdir,stat,unlink,access,rm}from'fs/promises';var Ce=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var Ht=Object.prototype.hasOwnProperty;var Ut=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var W=(s,e)=>()=>(s&&(e=s(s=0)),e);var Fe=(s,e)=>{for(var t in e)Ce(s,t,{get:e[t],enumerable:true});},_t=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Gt(e))!Ht.call(s,i)&&i!==t&&Ce(s,i,{get:()=>e[i],enumerable:!(r=At(e,i))||r.enumerable});return s};var ke=s=>_t(Ce({},"__esModule",{value:true}),s);var S,ce,A,E,le,pe,G=W(()=>{S=class extends Error{constructor(t,r,i){super(t);this.phase=r;this.context=i;this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}timestamp;errorId;generateErrorId(){return `${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let t=[`\u274C ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];return this.context&&Object.keys(this.context).length>0&&(t.push(""),t.push("\u{1F4CD} Context:"),Object.entries(this.context).forEach(([r,i])=>{t.push(` ${r}: ${this.formatContextValue(i)}`);})),t.join(`
|
|
3
3
|
`)}formatContextValue(t){if(t==null)return String(t);if(typeof t=="string")return `"${t}"`;if(typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return "[Object]"}return String(t)}getSeverity(){return "error"}isRecoverable(){return false}getDocumentationLinks(){return ["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}},ce=class extends S{constructor(t,r,i,n){super(t,"validation",{schemaName:r.identifier?.name||"unknown",schemaKind:r.identifier?.kind||"unknown",schemaPackage:r.identifier?.package||"unknown",validationErrors:i,userContext:n});this.schema=r;this.validationErrors=i;this.userContext=n;}getSuggestions(){let t=[];t.push("Verify the schema follows the TypeSchema specification"),t.push("Check that all required fields are present and properly typed");for(let r of this.validationErrors)r.includes("identifier.name")&&(t.push("\u2728 Add a valid identifier.name field to your schema"),t.push('\u{1F4A1} Example: identifier: { name: "Patient", kind: "resource" }')),r.includes("identifier.kind")&&(t.push('\u{1F3AF} Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),t.push("\u{1F4DA} Check FHIR specification for the correct kind value")),r.includes("circular")&&(t.push("\u{1F504} Remove circular references between schemas"),t.push("\u{1F4A1} Use forward declarations for recursive types"),t.push("\u{1F50D} Look for schemas that reference each other in a loop")),r.includes("fields")&&(t.push("\u{1F4DD} Check that all fields have proper type definitions"),t.push("\u{1F527} Ensure field types reference valid TypeSchema identifiers"));return this.userContext?.isBeginnerMode&&(t.push(""),t.push("\u{1F393} Beginner Tips:"),t.push("\u{1F4D6} Start with the Quick Start guide: docs/getting-started/quick-start.md"),t.push("\u{1F50D} Use --verbose flag for detailed error information"),t.push("\u{1F9EA} Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length&&t.push(`\u2705 Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)),this.userContext?.isBeginnerMode||(t.push(""),t.push("\u{1F527} Advanced Debugging:"),t.push("\u{1F575}\uFE0F Enable schema validation debugging"),t.push("\u{1F4CA} Check schema statistics and complexity metrics"),t.push("\u26A1 Consider schema preprocessing if dealing with complex inheritance")),t}isRecoverable(){return this.validationErrors.every(t=>!t.includes("circular")&&!t.includes("corruption"))}},A=class extends S{constructor(t,r,i,n){super(t,"generation",{templateName:r,contextKeys:Object.keys(i),availableTemplates:n?.availableTemplates?.length||0,debugInfo:n});this.templateName=r;this.templateContext=i;this.debugInfo=n;}getSuggestions(){let t=[];if(this.debugInfo?.availableTemplates?.length&&!this.debugInfo.availableTemplates.includes(this.templateName)){t.push(`\u274C Template '${this.templateName}' not found`),t.push("\u{1F4C2} Available templates:"),this.debugInfo.availableTemplates.forEach(i=>{t.push(` \u2022 ${i}`);});let r=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);r.length>0&&(t.push("\u{1F914} Did you mean:"),r.forEach(i=>{t.push(` \u2022 ${i}`);}));}if(this.debugInfo?.missingVariables?.length){t.push("\u{1F4DD} Missing template variables:"),this.debugInfo.missingVariables.forEach(i=>{t.push(` \u2022 ${i}`);}),t.push("\u{1F4A1} Add these variables to your template context");let r=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach(i=>{let n=r.filter(o=>this.levenshteinDistance(i.toLowerCase(),o.toLowerCase())<=2);n.length>0&&t.push(` Similar to: ${n.join(", ")}`);});}if(this.debugInfo?.lineNumber&&(t.push(`\u{1F41B} Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber&&t.push(` Column: ${this.debugInfo.columnNumber}`),this.debugInfo.templateSource)){let i=this.debugInfo.templateSource.split(`
|
|
4
4
|
`)[this.debugInfo.lineNumber-1];i&&t.push(` Code: ${i.trim()}`);}return t.push("\u{1F527} Template debugging steps:"),t.push(" \u2022 Enable template debugging: { debug: true }"),t.push(" \u2022 Verify template file exists and has correct syntax"),t.push(" \u2022 Check template variable names match context keys"),t.push(" \u2022 Ensure template engine is properly configured"),t}findSimilarTemplates(t,r){return r.filter(i=>{let n=this.levenshteinDistance(t.toLowerCase(),i.toLowerCase());return n<=2&&n>0}).slice(0,3).sort((i,n)=>this.levenshteinDistance(t.toLowerCase(),i.toLowerCase())-this.levenshteinDistance(t.toLowerCase(),n.toLowerCase()))}levenshteinDistance(t,r){let i=Array(r.length+1).fill(null).map(()=>Array(t.length+1).fill(0));for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=0;n<=r.length;n++)i[n][0]=n;for(let n=1;n<=r.length;n++)for(let o=1;o<=t.length;o++){let c=t[o-1]===r[n-1]?0:1;i[n][o]=Math.min(i[n]?.[o-1]+1,i[n-1]?.[o]+1,i[n-1]?.[o-1]+c);}return i[r.length]?.[t.length]}isRecoverable(){return true}},E=class extends S{constructor(t,r,i,n,o){super(t,"writing",{operation:r,filePath:i,originalErrorMessage:n?.message,originalErrorCode:n?.code,recoveryOptions:o});this.operation=r;this.filePath=i;this.originalError=n;this.recoveryOptions=o;}getSuggestions(){let t=[],r=this.originalError?.code;switch(this.operation){case "create":case "write":t.push("\u{1F4C1} File writing troubleshooting:"),t.push(" \u2022 Check if the output directory exists"),t.push(" \u2022 Verify write permissions for the target directory"),t.push(" \u2022 Ensure no other process has the file locked"),this.filePath.includes(" ")&&t.push(" \u2022 File path contains spaces - check path escaping"),this.recoveryOptions?.alternativePaths?.length&&(t.push("\u{1F504} Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach(i=>{t.push(` \u2022 ${i}`);}));break;case "read":t.push("\u{1F4D6} File reading troubleshooting:"),t.push(" \u2022 Verify the file exists at the specified path"),t.push(" \u2022 Check file read permissions"),t.push(" \u2022 Ensure file is not corrupted");break;case "delete":t.push("\u{1F5D1}\uFE0F File deletion troubleshooting:"),t.push(" \u2022 Check if file is locked by another process"),t.push(" \u2022 Verify delete permissions for the directory"),t.push(" \u2022 Ensure file exists before attempting deletion");break}switch(r){case "EACCES":t.push("\u{1F510} Permission Error:"),t.push(" \u2022 Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix?t.push(` \u2022 Fix command: ${this.recoveryOptions.permissionFix}`):t.push(` \u2022 Try: chmod 755 "${this.filePath}"`),t.push(" \u2022 Consider running with elevated permissions"),t.push(" \u2022 Check directory ownership and permissions");break;case "ENOSPC":if(t.push("\u{1F4BE} Disk Space Error:"),t.push(" \u2022 Insufficient disk space available"),t.push(" \u2022 Free up disk space and retry"),t.push(" \u2022 Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let i=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);t.push(` \u2022 Required space: ~${i}MB`);}break;case "ENOENT":t.push("\u{1F4C2} File Not Found:"),t.push(" \u2022 File or directory does not exist"),t.push(" \u2022 Check the file path for typos"),t.push(" \u2022 Ensure parent directories exist"),t.push(` \u2022 Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case "EMFILE":case "ENFILE":t.push("\u{1F4CA} Too Many Open Files:"),t.push(" \u2022 System has reached file handle limit"),t.push(" \u2022 Close unused files and retry"),t.push(" \u2022 Consider processing files in smaller batches");break}return this.recoveryOptions?.canRetry&&(t.push(""),t.push("\u{1F504} Recovery Options:"),t.push(" \u2022 This operation can be retried safely"),t.push(" \u2022 Fix the underlying issue and run again")),t.push(""),t.push("\u{1F50D} General Debugging:"),t.push(" \u2022 Check system logs for more details"),t.push(" \u2022 Verify disk health if errors persist"),t.push(" \u2022 Test with a simpler file path"),t}isRecoverable(){return this.recoveryOptions?.canRetry||false}getRecoveryActions(){let t=[];switch(this.originalError?.code){case "EACCES":t.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:false,riskLevel:"medium"});break;case "ENOENT":t.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:true,riskLevel:"low"});break;case "ENOSPC":t.push({action:"Free up disk space",automatic:false,riskLevel:"low"});break}return t}},le=class extends S{constructor(t,r,i,n,o){super(t,"initialization",{configKey:r,providedValue:i,providedType:typeof i,expectedValue:n,validOptions:o});this.configKey=r;this.providedValue=i;this.expectedValue=n;this.validOptions=o;}getSuggestions(){let t=[];switch(t.push(`\u2699\uFE0F Configuration error for '${this.configKey}'`),t.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue&&t.push(` Expected: ${this.expectedValue}`),this.validOptions?.length&&(t.push(" Valid options:"),this.validOptions.forEach(r=>{t.push(` \u2022 ${JSON.stringify(r)}`);})),t.push(""),t.push("\u{1F527} Configuration fixes:"),t.push(` \u2022 Check the '${this.configKey}' value in your configuration`),t.push(" \u2022 Refer to the configuration documentation"),t.push(" \u2022 Use TypeScript for better config validation"),t.push(" \u2022 Check for typos in configuration keys"),this.configKey){case "outputDir":t.push(" \u2022 Ensure the output directory path exists"),t.push(" \u2022 Use absolute paths for better reliability");break;case "logger":t.push(" \u2022 Provide a valid logger instance"),t.push(" \u2022 Use createLogger() from utils/codegen-logger");break;case "validation":t.push(' \u2022 Set to true, false, or "strict"');break}return t}isRecoverable(){return true}},pe=class extends S{constructor(t,r){super(t,"generation",{errorCount:r.length,errorTypes:[...new Set(r.map(i=>i.constructor.name))],phases:[...new Set(r.map(i=>i.phase))]});this.errors=r;}getSuggestions(){let t=this.errors.flatMap(c=>c.getSuggestions()),r=[...new Set(t)],i=[];i.push(`\u{1F4CA} Batch operation failed with ${this.errors.length} errors:`);let n=new Map;this.errors.forEach(c=>{let a=c.constructor.name;n.has(a)||n.set(a,[]),n.get(a)?.push(c);}),i.push(""),i.push("\u{1F50D} Error breakdown:");for(let[c,a]of n)i.push(` \u2022 ${c}: ${a.length} occurrences`);i.push("\u{1F4A1} Most relevant suggestions:");let o=r.slice(0,8).map(c=>` ${c}`);return i.push(...o),i}getErrorBreakdown(){let t=[];return this.errors.forEach((r,i)=>{t.push(`${i+1}. ${r.constructor.name}: ${r.message}`),r.context?.schemaName&&t.push(` Schema: ${r.context.schemaName}`),r.context?.filename&&t.push(` File: ${r.context.filename}`),t.push("");}),t.join(`
|
|
5
|
-
`)}isRecoverable(){return this.errors.some(t=>t.isRecoverable())}getRecoverableErrors(){return this.errors.filter(t=>t.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter(t=>!t.isRecoverable())}};});var Ct={};Fe(Ct,{FileBuilder:()=>
|
|
5
|
+
`)}isRecoverable(){return this.errors.some(t=>t.isRecoverable())}getRecoverableErrors(){return this.errors.filter(t=>t.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter(t=>!t.isRecoverable())}};});var Ct={};Fe(Ct,{FileBuilder:()=>ze});var ze,Ft=W(()=>{G();ze=class{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:true,formatting:{indentSize:2,useTabs:false,maxLineLength:100},encoding:"utf-8"};constructor(e){this.config=e;}withContent(e){return this.content=typeof e=="string"?e:e(),this}withTemplate(e,t){if(!this.config.templateEngine)throw new A(`Template engine is required for template rendering. Template: '${e}'`,e,t);this.options.template=e;try{this.content=this.config.templateEngine.render(e,{...t,imports:this.imports,exports:this.exports,filename:this.config.filename});}catch{throw new A(`Failed to render template '${e}'`,e,t,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(e){return this.content+=e,this}prependContent(e){return this.content=e+this.content,this}withImports(e){this.imports.clear();for(let[t,r]of e)this.imports.set(t,r);return this}addImport(e,t){return this.imports.set(e,t),this}addImports(e,t){for(let r of e)this.imports.set(r,t);return this}withExports(e){this.exports.clear();for(let t of e)this.exports.add(t);return this}addExport(e){return this.exports.add(e),this}addExports(e){for(let t of e)this.exports.add(t);return this}withMetadata(e,t){return this.metadata.set(e,t),this}withOptions(e){return this.options={...this.options,...e},this}onBeforeSave(e){return this.beforeSaveHooks.push(e),this}onAfterSave(e){return this.afterSaveHooks.push(e),this}onError(e){return this.errorHooks.push(e),this}build(){let e=this.buildFinalContent();return {filename:this.config.filename,content:e,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let e=this.build();try{for(let i of this.beforeSaveHooks)await i(e);this.options.validation!=="none"&&await this.validateContent(e.content);let t=await this.config.fileManager.writeFile(this.config.filename,e.content,{encoding:this.options.encoding}),r={size:t.size,generationTime:0,writeTime:t.writeTime};for(let i of this.afterSaveHooks)await i(t.path,r);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),t.path}catch(t){for(let r of this.errorHooks)try{await r(t instanceof Error?t:new Error(String(t)),e);}catch(i){this.config.logger.warn(`Error hook failed: ${i instanceof Error?i.message:String(i)}`);}throw t}}buildFinalContent(){let e=[];this.imports.size>0&&this.options.importStrategy!=="none"&&(e.push(this.generateImportStatements()),e.push("")),this.content&&e.push(this.content),this.exports.size>0&&!this.content.includes("export")&&(e.push(""),e.push(this.generateExportStatements()));let t=e.join(`
|
|
6
6
|
`);return this.options.prettify&&(t=this.prettifyContent(t)),t}generateImportStatements(){let e=[],t=new Map;for(let[r,i]of this.imports){let n=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,i):i;t.has(n)||t.set(n,[]),t.get(n)?.push(r);}for(let[r,i]of t)if(i.length===1)e.push(`import type { ${i[0]} } from '${r}';`);else {let n=i.sort();if(n.length<=3)e.push(`import type { ${n.join(", ")} } from '${r}';`);else {e.push("import type {");let o=" ";n.forEach((c,a)=>{let l=a===n.length-1;e.push(`${o}${c}${l?"":","}`);}),e.push(`} from '${r}';`);}}return e.join(`
|
|
7
7
|
`)}generateExportStatements(){return Array.from(this.exports).sort().map(t=>`export { ${t} };`).join(`
|
|
8
8
|
`)}prettifyContent(e){return e.replace(/\n{3,}/g,`
|
|
@@ -11,7 +11,7 @@ import Pr from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';imp
|
|
|
11
11
|
`).replace(/\n{3,}/g,`
|
|
12
12
|
|
|
13
13
|
`).trim()}
|
|
14
|
-
`}generateSimpleExports(e){e.push("// Exports");let t=Array.from(this.exports.entries());this.sortFunction?t=t.sort(this.sortFunction):t=t.sort(([i],[n])=>i.localeCompare(n));let r=new Map;for(let[i,n]of t)r.has(n)||r.set(n,[]),r.get(n)?.push(i);for(let[i,n]of r){let o=n.sort();o.length===1?e.push(`export type { ${o[0]} } from './${i}';`):o.length<=3?e.push(`export type { ${o.join(", ")} } from './${i}';`):(e.push("export type {"),o.forEach((c,a)=>{let l=a===o.length-1;e.push(` ${c}${l?"":","}`);}),e.push(`} from './${i}';`));}}generateGroupedExports(e){if(!this.groupingFunction)return;let t=new Map;for(let[i,n]of this.exports){let o=this.groupingFunction(i);t.has(o)||t.set(o,new Map);let c=t.get(o);c.has(n)||c.set(n,[]),c.get(n)?.push(i);}let r=Array.from(t.entries()).sort();for(let[i,n]of r){e.push(`// ${i}`);for(let[o,c]of n){let a=c.sort();a.length===1?e.push(`export type { ${a[0]} } from './${o}';`):e.push(`export type { ${a.join(", ")} } from './${o}';`);}e.push("");}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}};});var J=class s{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let i=this.options.timestamp?`${y.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${y.cyan(`[${this.options.prefix}]`)} `:"";return `${i}${r(e)} ${n}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e))return;(s.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,y.green));}error(e,t){this.isSuppressed(3)||(console.error(this.formatMessage("",e,y.red)),t&&this.options.verbose&&(console.error(y.red(` ${t.message}`)),t.stack&&console.error(y.gray(t.stack))));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,y.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,y.blue));}debug(e){this.options.verbose&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,y.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,y.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,y.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${y.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${y.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${i}${t(e)}`);}dim(e){this.plain(e,y.gray);}child(e){return new s({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},P=new J;function K(s){P.success(s);}function b(s,e){P.error(s,e);}function $e(s){P.warn(s);}function Z(s){P.info(s);}function Re(s){P.step(s);}function tt(s){P.dim(s);}function Ie(s){P.configure(s);}function w(s={}){return new J(s)}function Ee(s){console.log(),console.log(y.cyan(y.bold(`\u2501\u2501\u2501 ${s} \u2501\u2501\u2501`)));}function Pe(s,e,t){let r=s;e&&(r+=` ${y.gray(`(${e}ms)`)}`),K(r),t&&Object.entries(t).forEach(([i,n])=>{tt(` ${i}: ${n}`);});}function M(s,e="\u2022"){s.forEach(t=>{console.log(y.gray(` ${e} ${t}`));});}var rt=s=>`${s.name}#${s.version}`,it=s=>`${s.name}@${s.version}`,Me=(s,e)=>(e||(e={name:"undefined",version:"undefined"}),{...s,package_meta:s.package_meta||e,name:s.name,url:s.url,base:s.base}),Y=s=>s?.kind==="nested",nt=s=>s?.kind==="profile",st=s=>s?.identifier.kind!=="value-set",L=s=>s?.identifier.kind==="resource"||s?.identifier.kind==="complex-type"||s?.identifier.kind==="logical",ot=s=>s?.identifier.kind==="complex-type",Ne=s=>s?.identifier.kind==="resource",at=s=>s?.identifier.kind==="logical",Q=s=>s?.identifier.kind==="profile";function Oe(s){return s?.identifier.kind==="binding"}var $=s=>s?s.choices===void 0:false;var j=async(s,e)=>{let t=await s.packages(),r={},i=[];for(let d of t){let h=await s.search({package:d}),x={};for(let m of h){let C=m.url;C&&(x[C]=m,r[C]=m);}i.push({package_meta:d,index:x});}let n={},o={},c={},a={},[l,p]=[0,0];for(let d of i){let h=d.package_meta;for(let[x,m]of Object.entries(d.index)){let C=x;if(m.resourceType==="StructureDefinition"){let k=m;n[C]=k;try{let T=Me(ct.translate(k),h);c[T.url]=T,a[T.name]=T.url,l++;}catch(T){e?.warn(`Failed to convert StructureDefinition ${k.name||k.id}: ${T instanceof Error?T.message:String(T)}`),p++;}}m.resourceType==="ValueSet"&&(m.package_meta||(m.package_meta=h),o[m.url]=m);}e?.success(`FHIR Schema conversion for '${rt(h)}' completed: ${l} successful, ${p} failed`);}let u={};for(let d of Object.values(c))d.kind==="complex-type"&&(u[d.url]=d);let g=d=>{let h=c[d];if(h===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${d}'`);let x=[h];for(;h?.base;)if(h=c[h.base]||c[a[h.base]],x.push(h),h===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${d}'`);return x};return {...s,appendFs(d){let h=Me(d);c[h.url]=h,a[h.name]=h.url;},resolveFs:d=>c[d],resolveFsGenealogy:g,resolveFsSpecializations:d=>g(d).filter(h=>h.derivation==="specialization"),ensureCanonicalUrl:d=>a[d]||d,allSd:()=>Object.values(n),resolveSd:d=>n[d],allFs:()=>Object.values(c),allVs:()=>Object.values(o),resolveVs:d=>o[d],complexTypeDict:()=>u,resolveAny:d=>r[d]}};var De=(s,e)=>{let[t,...r]=e;return t===void 0?[]:s.map(i=>{if(!i.elements)return;let n=i.elements?.[t];for(let o of r)n=n?.elements?.[o];return n}).filter(i=>i!==void 0)};function Be(s){let e=s.reverse().reduce((t,r)=>({...t,...r}),{});return e.elements=void 0,e}function Le(s){let e=s.split("|")[0];return e||s}function _t(s){return s.split("|")[1]}function qt(s){return s.derivation==="constraint"?"profile":s.kind==="primitive-type"?"primitive-type":s.kind==="complex-type"?"complex-type":(s.kind==="resource","resource")}function N(s){return {kind:qt(s),package:s.package_meta.name,version:s.package_meta.version,name:s.name,url:s.url}}var Wt=s=>{let e=s.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):s};function X(s,e){let t=Le(e),r=Wt(t),i={package_meta:{name:"missing_valuesets",version:_t(t)||"0.0.0"},id:e},n=s.resolveVs(t)||i,o=n?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(n.id)?n.id:r;return {kind:"value-set",package:n.package_meta.name,version:n.package_meta.version,name:o,url:t}}function ee(s,e,t){let r=e.join("."),[i,n,o]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[s.package_meta,`${s.name}.${r}_binding`,`${s.url}#${r}_binding`];return {kind:"binding",package:i.name,version:i.version,name:n,url:o}}function te(s,e,t,r){var i={};if(e.derivation==="constraint"){let a=s.resolveFsSpecializations(e.url).map(l=>re(s,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())i[l.identifier.name]=l.identifier.url;}let n=t.join("."),o=i[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:o}}function lt(s,e,t){let r=[];for(let[i,n]of Object.entries(t)){let o=[...e,i];V(n)&&r.push([o,n]),n.elements&&r.push(...lt(s,o,n.elements));}return r}function Jt(s,e,t,r,i){let n={};for(let[o,c]of Object.entries(r)){let a=[...t,o];V(c)?n[o]=ne(s,e,a,c,i):n[o]=ie(s,e,a,c,i);}return n}function re(s,e,t){if(!e.elements)return;let r=lt(e,[],e.elements).filter(([n,o])=>o.elements&&Object.keys(o.elements).length>0),i=[];for(let[n,o]of r){let c=te(s,e,n,t),a;o.type==="BackboneElement"||!o.type?a="BackboneElement":a=o.type;let l={kind:"complex-type",package:e.package_meta.name,version:e.package_meta.version,name:a,url:s.ensureCanonicalUrl(a)},p=Jt(s,e,n,o.elements,t),u={identifier:c,base:l,fields:p};i.push(u);}return i.sort((n,o)=>n.identifier.url.localeCompare(o.identifier.url)),i.length===0?void 0:i}function je(s){let e=[];for(let t of s){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function pt(s,e,t){let r=t[t.length-1],i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.required||[];if(!o.elements)return [];let c=o;for(let a of i)c=c?.elements?.[a];return c?.required||[]});return new Set(n).has(r)}function ut(s,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.excluded||[];if(!o.elements)return [];let c=o;for(let a of i)c=c?.elements?.[a];return c?.excluded||[]});return new Set(n).has(r)}var Kt=(s,e,t)=>{if(s.refers)return s.refers.map(r=>{let i=e.ensureCanonicalUrl(r),n=e.resolveFs(i);return N(n)})};function Ve(s,e,t,r){if(t.elementReference){let i=t.elementReference.filter((n,o)=>o%2===1).map(n=>n).filter(n=>n!=="elements");if(i.length>0)return te(s,e,i,r)}if(t.type){let i=t.type.match(/^[a-z]/)?"primitive-type":"complex-type",n=s.ensureCanonicalUrl(t.type),o=s.resolveFs(n);if(!o)throw new Error(`Could not resolve field '${t.type}'`);return {kind:i,package:o.package_meta.name,version:o.package_meta.version,name:t.type,url:n}}}var ie=(s,e,t,r,i)=>{let n,o;return r.binding&&(n=ee(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(o=Ae(s,r,i))),{type:Ve(s,e,r,i),required:pt(s,e,t),excluded:ut(s,e,t),reference:Kt(r,s,e.package_meta),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:o}};function V(s){let e=s.type==="BackboneElement",t=s.type==="Element"&&s.elements!==void 0&&Object.keys(s.elements).length>0,r=s.type===void 0&&s.choiceOf===void 0&&s.elements!==void 0&&Object.keys(s.elements).length>0;return e||t||r}function ne(s,e,t,r,i){return {type:te(s,e,t,i),array:r.array||false,required:pt(s,e,t),excluded:ut(s,e,t)}}function Ge(s,e,t){let r=Le(e)||e,i=s.resolveVs(r);if(i)return Zt(s,i)}function Zt(s,e,t){if(e.expansion?.contains)return e.expansion.contains;let r=[];if(e.compose?.include){for(let i of e.compose.include)if(i.concept)for(let n of i.concept)r.push({system:i.system,code:n.code,display:n.display});else if(i.system&&!i.filter)try{let n=s.resolveAny(i.system);if(n?.concept){let o=(c,a)=>{for(let l of c)r.push({system:a,code:l.code,display:l.display}),l.concept&&o(l.concept,a);};o(n.concept,i.system);}}catch{}}return r.length>0?r:void 0}var dt=100;function Ae(s,e,t){if(!e.binding)return;let r=e.binding.strength,i=e.binding.valueSet;if(!i||!(r==="required"||r==="extensible"&&(e.type==="code"||e.type==="Coding")||r==="preferred"&&(e.type==="code"||e.type==="Coding")))return;let o=Ge(s,i);if(!o||o.length===0)return;let c=o.map(a=>a.code).filter(a=>a&&typeof a=="string"&&a.trim().length>0);if(c.length>dt){t?.dry_warn(`Value set ${i} has ${c.length} which is more than ${dt} codes, which may cause issues with code generation.`);return}return c.length>0?c:void 0}function Yt(s,e,t,r,i){if(!r.binding?.valueSet)return;let n=ee(e,t,r.binding.bindingName),o=Ve(s,e,r,i),c=X(s,r.binding.valueSet),a=[];o&&a.push(o),a.push(c);let l=Ae(s,r,i);return {identifier:n,type:o,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function gt(s,e,t){let r=new Set;if(!e.elements)return [];let i=[];function n(a,l){for(let[p,u]of Object.entries(a)){let g=[...l,p],f=g.join(".");if(!r.has(f)){if(r.add(f),u.binding){let d=Yt(s,e,g,u,t);d&&i.push(d);}u.elements&&n(u.elements,g);}}}n(e.elements,[]),i.sort((a,l)=>a.identifier.name.localeCompare(l.identifier.name));let o=[],c=new Set;for(let a of i)c.has(a.identifier.url)||(c.add(a.identifier.url),o.push(a));return o}function ft(s,e,t,r,i){if(!r)return;let n=s.resolveFsGenealogy(e.url),o={};for(let[a,l]of Object.entries(r)){let p=[...t,a],u=De(n,p),g=Be(u);o[a]={elem:l,elemSnapshot:g,path:p};}for(let[a,{elem:l,elemSnapshot:p,path:u}]of Object.entries(o))for(let g of l?.choices||[])if(!o[g]){let f=[...t,g],d=De(n,f),h=Be(d);o[g]={elem:void 0,elemSnapshot:h,path:f};}let c={};for(let[a,{elem:l,elemSnapshot:p,path:u}]of Object.entries(o))V(p)?c[a]=ne(s,e,u,p,i):c[a]=ie(s,e,u,p,i);return c}function ht(s){let e=[];for(let t of Object.values(s))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Qt(s){let e=new Set,t=[];for(let r of s){let i=r.url;e.has(i)||(e.add(i),t.push(r));}return t.sort((r,i)=>r.name.localeCompare(i.name)),t}function Xt(s,e){return !!(s.base==="Extension"||s.base==="http://hl7.org/fhir/StructureDefinition/Extension"||s.url?.includes("/extension/")||s.url?.includes("-extension")||s.name?.toLowerCase().includes("extension")||s.type==="Extension")}async function se(s,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=X(s,e.url),i=Ge(s,e.url);return {identifier:r,description:e.description,concept:i,compose:i?void 0:e.compose}}async function er(s,e,t){try{let r=N(s),i;if(s.base&&s.base!=="Extension"){let c=s.base.includes("/")?s.base:`http://hl7.org/fhir/StructureDefinition/${s.base}`;i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:s.base.split("/").pop()||s.base,url:c};}else i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let n={identifier:r,base:i,description:s.description,dependencies:[],metadata:{isExtension:!0}};if(i&&n.dependencies.push(i),s.elements){let c=ft(e,s,[],s.elements,t);c&&Object.keys(c).length>0&&(n.fields=c,n.dependencies.push(...ht(c)));}let o=re(e,s,t);return o&&o.length>0&&(n.nested=o,n.dependencies.push(...je(o))),n.dependencies=Qt(n.dependencies),n.dependencies=n.dependencies.filter(c=>c.url!==r.url),n}catch(r){return console.warn(`Failed to transform extension ${s.name}: ${r}`),null}}function tr(s,e,t,r){let i=[];e&&i.push(e),t&&i.push(...ht(t)),r&&i.push(...je(r));let n={};for(let a of i)a.url!==s.url&&(n[a.url]=a);let o=new Set(r?.map(a=>a.identifier.url)),c=Object.values(n).filter(a=>nt(s)||!Y(a)?true:!o.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function rr(s,e,t){let r=N(e),i;if(e.base&&e.type!=="Element"){let p=s.resolveFs(s.ensureCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for '${e.url}'`);i=N(p);}let n=ft(s,e,[],e.elements,t),o=re(s,e,t),c=tr(r,i,n,o),a={identifier:r,base:i,fields:n,nested:o,description:e.description,dependencies:c},l=gt(s,e,t);return [a,...l]}async function oe(s,e,t){let r=[];N(e);if(Xt(e)){let n=await er(e,s,t);return n&&r.push(n),r}return rr(s,e,t)}var R=class{cache=new Map;config;cacheDir;constructor(e){this.config={enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,...e},this.config.enablePersistence&&this.config.cacheDir&&(this.cacheDir=this.config.cacheDir);}async set(e){let t=this.generateKey(e.identifier);this.cache.set(t,e),this.config.enablePersistence&&this.cacheDir&&await this.persistSchema(e);}get(e){let t=this.generateKey(e);return this.cache.get(t)||null}getByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return t;return null}has(e){let t=this.generateKey(e);return this.cache.has(t)}hasByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return true;return false}delete(e){let t=this.generateKey(e);return this.cache.delete(t)}deleteByUrl(e){for(let[t,r]of this.cache.entries())if(r.identifier.url===e)return this.cache.delete(t);return false}getByPackage(e){let t=[];for(let r of this.cache.values())r.identifier.package===e&&t.push(r);return t}getByKind(e){let t=[];for(let r of this.cache.values())r.identifier.kind===e&&t.push(r);return t}setMany(e){for(let t of e)this.set(t);}clear(){this.cache.clear();}generateKey(e){return `${e.package}:${e.version}:${e.kind}:${e.name}`}async initialize(){this.config.enablePersistence&&this.cacheDir&&(existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true}),await this.loadFromDisk());}async loadFromDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t){let i=join(this.cacheDir,r),n=await stat(i);if(this.config.maxAge&&Date.now()-n.mtimeMs>this.config.maxAge){await unlink(i);continue}try{let o=await readFile(i,"utf-8"),c=JSON.parse(o);if(this.config.validateCached&&!c.schema?.identifier)continue;let a=this.generateKey(c.schema.identifier);this.cache.set(a,c.schema);}catch(o){console.warn(`Failed to load cached schema from ${r}:`,o);}}}catch(e){console.warn("Failed to load cached schemas from disk:",e);}}async persistSchema(e){if(!this.cacheDir)return;existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true});let t={schema:e,timestamp:Date.now(),version:e.identifier.version},r=`${e.identifier.package}-${e.identifier.version}-${e.identifier.kind}-${e.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),i=join(this.cacheDir,r);try{await writeFile(i,JSON.stringify(t,null,2),"utf-8");}catch(n){console.warn(`Failed to persist schema to ${i}:`,n);}}async clearDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t)await unlink(join(this.cacheDir,r));}catch(e){console.warn("Failed to clear cache directory:",e);}}};var I=class{manager;options;cacheConfig;cache;logger;constructor(e={},t){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=t,this.logger=e.logger||w({verbose:this.options.verbose,prefix:"TypeSchema"});}async initializeCache(){this.cacheConfig&&!this.cache&&(this.cache=new R(this.cacheConfig),await this.cache.initialize());}async registerFromPackageMetas(e){let t=e.map(r=>`${r.name}${r.version}`);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),j(this.manager)}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=this.applyStructureDefinitionTreeshaking(e),r=[],i=0,n=0;for(let o of t)try{let c=ct.translate(o);r.push(c),i++,this.logger?.debug(`Converted StructureDefinition: ${o.name||o.id} (${o.resourceType})`);}catch(c){n++,this.logger?.warn(`Failed to convert StructureDefinition ${o.name||o.id}: ${c instanceof Error?c.message:String(c)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${i}/${t.length} successful, ${n} failed`),r}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await j(this.manager,t),i=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,o=0;for(let c of e)try{let a=await se(r,c,t);a&&(i.push(a),n++,this.logger?.debug(`Converted ValueSet: ${c.name||c.id}`));}catch(a){o++,this.logger?.warn(`Failed to convert ValueSet ${c.name||c.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger?.success(`ValueSet conversion completed: ${n}/${e.length} successful, ${o} failed`);}return i}async generateFromPackage(e,t,r){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??false)){let l=this.cache.getByPackage(e);if(l.length>0)return this.logger?.info(`Using cached TypeSchemas for package: ${e} (${l.length} schemas)`),l}let i={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([i]),o=await this.generateValueSetSchemas(n.allVs(),r),a=[...(await Promise.all(n.allFs().map(async l=>await oe(n,l,r)))).flat(),...o];if(this.cache)for(let l of a)await this.cache.set(l);return a}applyStructureDefinitionTreeshaking(e){let t=this.options.treeshake;if(!t||t.length===0)return e;this.logger?.info(`Applying treeshaking filter for ResourceTypes: ${t.join(", ")}`);let r=new Map,i=new Map,n=new Map;for(let p of e){let u=p.name||p.id;u&&(r.set(u,p),i.set(u,new Set),n.set(u,new Set));}for(let p of e){let u=p.name||p.id;if(!u)continue;let{realDeps:g,refTargets:f}=this.extractStructureDefinitionDependenciesWithReferences(p);i.set(u,new Set(g)),n.set(u,new Set(f));}let o=new Set;for(let p of t)r.has(p)?o.add(p):this.logger?.warn(`ResourceType '${p}' not found in structure definitions`);let c=(p,u=new Set)=>{if(u.has(p)||!i.has(p))return;u.add(p);let g=i.get(p)||new Set;for(let f of Array.from(g))r.has(f)&&(o.add(f),c(f,u));};for(let p of Array.from(o))c(p);let a=e.filter(p=>{let u=p.name||p.id;return u&&o.has(u)}),l=new Set;for(let p of e){let u=p.name||p.id;u&&!o.has(u)&&Array.from(n.values()).some(f=>f.has(u))&&l.add(u);}return l.size>0&&this.logger?.info(`Excluded reference-only targets: ${Array.from(l).join(", ")}`),this.logger?.success(`Treeshaking completed: kept ${a.length}/${e.length} structure definitions`),a}extractStructureDefinitionDependenciesWithReferences(e){let t=new Set,r=new Set;if(e.baseDefinition){let i=this.extractResourceNameFromUrl(e.baseDefinition);i&&t.add(i);}if(e.snapshot?.element||e.differential?.element){let i=e.snapshot?.element||e.differential?.element;for(let n of i)if(n.type)for(let o of n.type){if(o.code&&(t.add(o.code),o.code==="Reference"&&o.targetProfile))for(let c of o.targetProfile){let a=this.extractResourceNameFromUrl(c);a&&r.add(a);}if(o.profile)for(let c of o.profile){let a=this.extractResourceNameFromUrl(c);a&&t.add(a);}}}return {realDeps:Array.from(t),refTargets:Array.from(r)}}extractResourceNameFromUrl(e){let t=e.match(/\/([^/]+)$/);return t?t[1]??null:null}};var D=class{options;constructor(e={}){this.options={format:"auto",validate:true,strict:false,...e};}async parseFromFile(e){let t=await readFile(e,"utf-8"),r=this.options.format==="auto"?this.detectFormat(t,e):this.options.format;return this.parseFromString(t,r)}async parseFromString(e,t){let r=t||this.detectFormat(e),i;return r==="ndjson"?i=this.parseNDJSON(e):i=this.parseJSON(e),this.options.validate&&this.validateSchemas(i),i}async parseFromFiles(e){let t=[];for(let r of e){let i=await this.parseFromFile(r);t.push(...i);}return t}parseSchema(e){if(!e.identifier)throw new Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(e.identifier))throw new Error("TypeSchema identifier is invalid");return e}findByIdentifier(e,t){return e.filter(r=>this.matchesIdentifier(r.identifier,t))}findByUrl(e,t){return e.find(r=>r.identifier.url===t)}findByKind(e,t){return e.filter(r=>r.identifier.kind===t)}findByPackage(e,t){return e.filter(r=>r.identifier.package===t)}detectFormat(e,t){if(t){if(t.endsWith(".ndjson"))return "ndjson";if(t.endsWith(".json"))return "json"}let r=e.trim();if(r.includes(`
|
|
14
|
+
`}generateSimpleExports(e){e.push("// Exports");let t=Array.from(this.exports.entries());this.sortFunction?t=t.sort(this.sortFunction):t=t.sort(([i],[n])=>i.localeCompare(n));let r=new Map;for(let[i,n]of t)r.has(n)||r.set(n,[]),r.get(n)?.push(i);for(let[i,n]of r){let o=n.sort();o.length===1?e.push(`export type { ${o[0]} } from './${i}';`):o.length<=3?e.push(`export type { ${o.join(", ")} } from './${i}';`):(e.push("export type {"),o.forEach((c,a)=>{let l=a===o.length-1;e.push(` ${c}${l?"":","}`);}),e.push(`} from './${i}';`));}}generateGroupedExports(e){if(!this.groupingFunction)return;let t=new Map;for(let[i,n]of this.exports){let o=this.groupingFunction(i);t.has(o)||t.set(o,new Map);let c=t.get(o);c.has(n)||c.set(n,[]),c.get(n)?.push(i);}let r=Array.from(t.entries()).sort();for(let[i,n]of r){e.push(`// ${i}`);for(let[o,c]of n){let a=c.sort();a.length===1?e.push(`export type { ${a[0]} } from './${o}';`):e.push(`export type { ${a.join(", ")} } from './${o}';`);}e.push("");}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}};});var J=class s{options;dryWarnSet=new Set;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}static consoleLevelsMap={1:console.log,2:console.warn,3:console.error,0:console.log,4:()=>{}};formatMessage(e,t,r){let i=this.options.timestamp?`${y.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${y.cyan(`[${this.options.prefix}]`)} `:"";return `${i}${r(e)} ${n}${t}`}isSuppressed(e){return this.options.suppressLoggingLevel==="all"||this.options.suppressLoggingLevel?.includes(e)||false}tryWriteToConsole(e,t){if(this.isSuppressed(e))return;(s.consoleLevelsMap[e]||console.log)(t);}success(e){this.tryWriteToConsole(1,this.formatMessage("",e,y.green));}error(e,t){this.isSuppressed(3)||(console.error(this.formatMessage("",e,y.red)),t&&this.options.verbose&&(console.error(y.red(` ${t.message}`)),t.stack&&console.error(y.gray(t.stack))));}warn(e){this.tryWriteToConsole(2,this.formatMessage("!",e,y.yellow));}dry_warn(e){this.dryWarnSet.has(e)||(this.warn(e),this.dryWarnSet.add(e));}info(e){this.tryWriteToConsole(1,this.formatMessage("i",e,y.blue));}debug(e){this.options.verbose&&this.tryWriteToConsole(0,this.formatMessage("\u{1F41B}",e,y.magenta));}step(e){this.tryWriteToConsole(1,this.formatMessage("\u{1F680}",e,y.cyan));}progress(e){this.tryWriteToConsole(1,this.formatMessage("\u23F3",e,y.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${y.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${y.cyan(`[${this.options.prefix}]`)} `:"";this.tryWriteToConsole(1,`${r}${i}${t(e)}`);}dim(e){this.plain(e,y.gray);}child(e){return new s({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},P=new J;function K(s){P.success(s);}function b(s,e){P.error(s,e);}function $e(s){P.warn(s);}function Z(s){P.info(s);}function Re(s){P.step(s);}function tt(s){P.dim(s);}function Ie(s){P.configure(s);}function w(s={}){return new J(s)}function Ee(s){console.log(),console.log(y.cyan(y.bold(`\u2501\u2501\u2501 ${s} \u2501\u2501\u2501`)));}function Pe(s,e,t){let r=s;e&&(r+=` ${y.gray(`(${e}ms)`)}`),K(r),t&&Object.entries(t).forEach(([i,n])=>{tt(` ${i}: ${n}`);});}function M(s,e="\u2022"){s.forEach(t=>{console.log(y.gray(` ${e} ${t}`));});}var rt=s=>`${s.name}#${s.version}`,it=s=>`${s.name}@${s.version}`,Me=(s,e)=>(e||(e={name:"undefined",version:"undefined"}),{...s,package_meta:s.package_meta||e,name:s.name,url:s.url,base:s.base}),Y=s=>s?.kind==="nested",nt=s=>s?.kind==="profile",st=s=>s?.identifier.kind!=="value-set",L=s=>s?.identifier.kind==="resource"||s?.identifier.kind==="complex-type"||s?.identifier.kind==="logical",ot=s=>s?.identifier.kind==="complex-type",Ne=s=>s?.identifier.kind==="resource",at=s=>s?.identifier.kind==="logical",Q=s=>s?.identifier.kind==="profile";function Oe(s){return s?.identifier.kind==="binding"}var $=s=>s?s.choices===void 0:false;var j=async(s,e)=>{let t=await s.packages(),r={},i=[];for(let d of t){let h=await s.search({package:d}),x={};for(let m of h){let C=m.url;C&&(x[C]=m,r[C]=m);}i.push({package_meta:d,index:x});}let n={},o={},c={},a={},[l,p]=[0,0];for(let d of i){let h=d.package_meta;for(let[x,m]of Object.entries(d.index)){let C=x;if(m.resourceType==="StructureDefinition"){let k=m;n[C]=k;try{let T=Me(ct.translate(k),h);c[T.url]=T,a[T.name]=T.url,l++;}catch(T){e?.warn(`Failed to convert StructureDefinition ${k.name||k.id}: ${T instanceof Error?T.message:String(T)}`),p++;}}m.resourceType==="ValueSet"&&(m.package_meta||(m.package_meta=h),o[m.url]=m);}e?.success(`FHIR Schema conversion for '${rt(h)}' completed: ${l} successful, ${p} failed`);}let u={};for(let d of Object.values(c))d.kind==="complex-type"&&(u[d.url]=d);let g=d=>{let h=c[d];if(h===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${d}'`);let x=[h];for(;h?.base;)if(h=c[h.base]||c[a[h.base]],x.push(h),h===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${d}'`);return x};return {...s,appendFs(d){let h=Me(d);c[h.url]=h,a[h.name]=h.url;},resolveFs:d=>c[d],resolveFsGenealogy:g,resolveFsSpecializations:d=>g(d).filter(h=>h.derivation==="specialization"),ensureCanonicalUrl:d=>a[d]||d,allSd:()=>Object.values(n),resolveSd:d=>n[d],allFs:()=>Object.values(c),allVs:()=>Object.values(o),resolveVs:d=>o[d],complexTypeDict:()=>u,resolveAny:d=>r[d]}};var De=(s,e)=>{let[t,...r]=e;return t===void 0?[]:s.map(i=>{if(!i.elements)return;let n=i.elements?.[t];for(let o of r)n=n?.elements?.[o];return n}).filter(i=>i!==void 0)};function Be(s){let e=s.reverse().reduce((t,r)=>({...t,...r}),{});return e.elements=void 0,e}function Le(s){let e=s.split("|")[0];return e||s}function zt(s){return s.split("|")[1]}function qt(s){return s.derivation==="constraint"?"profile":s.kind==="primitive-type"?"primitive-type":s.kind==="complex-type"?"complex-type":(s.kind==="resource","resource")}function N(s){return {kind:qt(s),package:s.package_meta.name,version:s.package_meta.version,name:s.name,url:s.url}}var Wt=s=>{let e=s.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):s};function X(s,e){let t=Le(e),r=Wt(t),i={package_meta:{name:"missing_valuesets",version:zt(t)||"0.0.0"},id:e},n=s.resolveVs(t)||i,o=n?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(n.id)?n.id:r;return {kind:"value-set",package:n.package_meta.name,version:n.package_meta.version,name:o,url:t}}function ee(s,e,t){let r=e.join("."),[i,n,o]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[s.package_meta,`${s.name}.${r}_binding`,`${s.url}#${r}_binding`];return {kind:"binding",package:i.name,version:i.version,name:n,url:o}}function te(s,e,t,r){var i={};if(e.derivation==="constraint"){let a=s.resolveFsSpecializations(e.url).map(l=>re(s,l,r)).filter(l=>l!==void 0).flat();for(let l of a.reverse())i[l.identifier.name]=l.identifier.url;}let n=t.join("."),o=i[n]??`${e.url}#${n}`;return {kind:"nested",package:e.package_meta.name,version:e.package_meta.version,name:n,url:o}}function lt(s,e,t){let r=[];for(let[i,n]of Object.entries(t)){let o=[...e,i];V(n)&&r.push([o,n]),n.elements&&r.push(...lt(s,o,n.elements));}return r}function Jt(s,e,t,r,i){let n={};for(let[o,c]of Object.entries(r)){let a=[...t,o];V(c)?n[o]=ne(s,e,a,c,i):n[o]=ie(s,e,a,c,i);}return n}function re(s,e,t){if(!e.elements)return;let r=lt(e,[],e.elements).filter(([n,o])=>o.elements&&Object.keys(o.elements).length>0),i=[];for(let[n,o]of r){let c=te(s,e,n,t),a;o.type==="BackboneElement"||!o.type?a="BackboneElement":a=o.type;let l={kind:"complex-type",package:e.package_meta.name,version:e.package_meta.version,name:a,url:s.ensureCanonicalUrl(a)},p=Jt(s,e,n,o.elements,t),u={identifier:c,base:l,fields:p};i.push(u);}return i.sort((n,o)=>n.identifier.url.localeCompare(o.identifier.url)),i.length===0?void 0:i}function je(s){let e=[];for(let t of s){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function pt(s,e,t){let r=t[t.length-1],i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.required||[];if(!o.elements)return [];let c=o;for(let a of i)c=c?.elements?.[a];return c?.required||[]});return new Set(n).has(r)}function ut(s,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.excluded||[];if(!o.elements)return [];let c=o;for(let a of i)c=c?.elements?.[a];return c?.excluded||[]});return new Set(n).has(r)}var Kt=(s,e,t)=>{if(s.refers)return s.refers.map(r=>{let i=e.ensureCanonicalUrl(r),n=e.resolveFs(i);return N(n)})};function Ve(s,e,t,r){if(t.elementReference){let i=t.elementReference.filter((n,o)=>o%2===1).map(n=>n).filter(n=>n!=="elements");if(i.length>0)return te(s,e,i,r)}if(t.type){let i=t.type.match(/^[a-z]/)?"primitive-type":"complex-type",n=s.ensureCanonicalUrl(t.type),o=s.resolveFs(n);if(!o)throw new Error(`Could not resolve field '${t.type}'`);return {kind:i,package:o.package_meta.name,version:o.package_meta.version,name:t.type,url:n}}}var ie=(s,e,t,r,i)=>{let n,o;return r.binding&&(n=ee(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(o=Ae(s,r,i))),{type:Ve(s,e,r,i),required:pt(s,e,t),excluded:ut(s,e,t),reference:Kt(r,s,e.package_meta),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:n,enum:o}};function V(s){let e=s.type==="BackboneElement",t=s.type==="Element"&&s.elements!==void 0&&Object.keys(s.elements).length>0,r=s.type===void 0&&s.choiceOf===void 0&&s.elements!==void 0&&Object.keys(s.elements).length>0;return e||t||r}function ne(s,e,t,r,i){return {type:te(s,e,t,i),array:r.array||false,required:pt(s,e,t),excluded:ut(s,e,t)}}function Ge(s,e,t){let r=Le(e)||e,i=s.resolveVs(r);if(i)return Zt(s,i)}function Zt(s,e,t){if(e.expansion?.contains)return e.expansion.contains;let r=[];if(e.compose?.include){for(let i of e.compose.include)if(i.concept)for(let n of i.concept)r.push({system:i.system,code:n.code,display:n.display});else if(i.system&&!i.filter)try{let n=s.resolveAny(i.system);if(n?.concept){let o=(c,a)=>{for(let l of c)r.push({system:a,code:l.code,display:l.display}),l.concept&&o(l.concept,a);};o(n.concept,i.system);}}catch{}}return r.length>0?r:void 0}var dt=100;function Ae(s,e,t){if(!e.binding)return;let r=e.binding.strength,i=e.binding.valueSet;if(!i||!(r==="required"||r==="extensible"&&(e.type==="code"||e.type==="Coding")||r==="preferred"&&(e.type==="code"||e.type==="Coding")))return;let o=Ge(s,i);if(!o||o.length===0)return;let c=o.map(a=>a.code).filter(a=>a&&typeof a=="string"&&a.trim().length>0);if(c.length>dt){t?.dry_warn(`Value set ${i} has ${c.length} which is more than ${dt} codes, which may cause issues with code generation.`);return}return c.length>0?c:void 0}function Yt(s,e,t,r,i){if(!r.binding?.valueSet)return;let n=ee(e,t,r.binding.bindingName),o=Ve(s,e,r,i),c=X(s,r.binding.valueSet),a=[];o&&a.push(o),a.push(c);let l=Ae(s,r,i);return {identifier:n,type:o,valueset:c,strength:r.binding.strength,enum:l,dependencies:a}}function gt(s,e,t){let r=new Set;if(!e.elements)return [];let i=[];function n(a,l){for(let[p,u]of Object.entries(a)){let g=[...l,p],f=g.join(".");if(!r.has(f)){if(r.add(f),u.binding){let d=Yt(s,e,g,u,t);d&&i.push(d);}u.elements&&n(u.elements,g);}}}n(e.elements,[]),i.sort((a,l)=>a.identifier.name.localeCompare(l.identifier.name));let o=[],c=new Set;for(let a of i)c.has(a.identifier.url)||(c.add(a.identifier.url),o.push(a));return o}function ft(s,e,t,r,i){if(!r)return;let n=s.resolveFsGenealogy(e.url),o={};for(let[a,l]of Object.entries(r)){let p=[...t,a],u=De(n,p),g=Be(u);o[a]={elem:l,elemSnapshot:g,path:p};}for(let[a,{elem:l,elemSnapshot:p,path:u}]of Object.entries(o))for(let g of l?.choices||[])if(!o[g]){let f=[...t,g],d=De(n,f),h=Be(d);o[g]={elem:void 0,elemSnapshot:h,path:f};}let c={};for(let[a,{elem:l,elemSnapshot:p,path:u}]of Object.entries(o))V(p)?c[a]=ne(s,e,u,p,i):c[a]=ie(s,e,u,p,i);return c}function ht(s){let e=[];for(let t of Object.values(s))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Qt(s){let e=new Set,t=[];for(let r of s){let i=r.url;e.has(i)||(e.add(i),t.push(r));}return t.sort((r,i)=>r.name.localeCompare(i.name)),t}function Xt(s,e){return !!(s.base==="Extension"||s.base==="http://hl7.org/fhir/StructureDefinition/Extension"||s.url?.includes("/extension/")||s.url?.includes("-extension")||s.name?.toLowerCase().includes("extension")||s.type==="Extension")}async function se(s,e,t){if(!e.url)throw new Error("ValueSet URL is required");let r=X(s,e.url),i=Ge(s,e.url);return {identifier:r,description:e.description,concept:i,compose:i?void 0:e.compose}}async function er(s,e,t){try{let r=N(s),i;if(s.base&&s.base!=="Extension"){let c=s.base.includes("/")?s.base:`http://hl7.org/fhir/StructureDefinition/${s.base}`;i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:s.base.split("/").pop()||s.base,url:c};}else i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let n={identifier:r,base:i,description:s.description,dependencies:[],metadata:{isExtension:!0}};if(i&&n.dependencies.push(i),s.elements){let c=ft(e,s,[],s.elements,t);c&&Object.keys(c).length>0&&(n.fields=c,n.dependencies.push(...ht(c)));}let o=re(e,s,t);return o&&o.length>0&&(n.nested=o,n.dependencies.push(...je(o))),n.dependencies=Qt(n.dependencies),n.dependencies=n.dependencies.filter(c=>c.url!==r.url),n}catch(r){return console.warn(`Failed to transform extension ${s.name}: ${r}`),null}}function tr(s,e,t,r){let i=[];e&&i.push(e),t&&i.push(...ht(t)),r&&i.push(...je(r));let n={};for(let a of i)a.url!==s.url&&(n[a.url]=a);let o=new Set(r?.map(a=>a.identifier.url)),c=Object.values(n).filter(a=>nt(s)||!Y(a)?true:!o.has(a.url)).sort((a,l)=>a.url.localeCompare(l.url));return c.length>0?c:void 0}function rr(s,e,t){let r=N(e),i;if(e.base&&e.type!=="Element"){let p=s.resolveFs(s.ensureCanonicalUrl(e.base));if(!p)throw new Error(`Base resource not found '${e.base}' for '${e.url}'`);i=N(p);}let n=ft(s,e,[],e.elements,t),o=re(s,e,t),c=tr(r,i,n,o),a={identifier:r,base:i,fields:n,nested:o,description:e.description,dependencies:c},l=gt(s,e,t);return [a,...l]}async function oe(s,e,t){let r=[];N(e);if(Xt(e)){let n=await er(e,s,t);return n&&r.push(n),r}return rr(s,e,t)}var R=class{cache=new Map;config;cacheDir;constructor(e){this.config={enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,...e},this.config.enablePersistence&&this.config.cacheDir&&(this.cacheDir=this.config.cacheDir);}async set(e){let t=this.generateKey(e.identifier);this.cache.set(t,e),this.config.enablePersistence&&this.cacheDir&&await this.persistSchema(e);}get(e){let t=this.generateKey(e);return this.cache.get(t)||null}getByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return t;return null}has(e){let t=this.generateKey(e);return this.cache.has(t)}hasByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return true;return false}delete(e){let t=this.generateKey(e);return this.cache.delete(t)}deleteByUrl(e){for(let[t,r]of this.cache.entries())if(r.identifier.url===e)return this.cache.delete(t);return false}getByPackage(e){let t=[];for(let r of this.cache.values())r.identifier.package===e&&t.push(r);return t}getByKind(e){let t=[];for(let r of this.cache.values())r.identifier.kind===e&&t.push(r);return t}setMany(e){for(let t of e)this.set(t);}clear(){this.cache.clear();}generateKey(e){return `${e.package}:${e.version}:${e.kind}:${e.name}`}async initialize(){this.config.enablePersistence&&this.cacheDir&&(existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true}),await this.loadFromDisk());}async loadFromDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t){let i=join(this.cacheDir,r),n=await stat(i);if(this.config.maxAge&&Date.now()-n.mtimeMs>this.config.maxAge){await unlink(i);continue}try{let o=await readFile(i,"utf-8"),c=JSON.parse(o);if(this.config.validateCached&&!c.schema?.identifier)continue;let a=this.generateKey(c.schema.identifier);this.cache.set(a,c.schema);}catch(o){console.warn(`Failed to load cached schema from ${r}:`,o);}}}catch(e){console.warn("Failed to load cached schemas from disk:",e);}}async persistSchema(e){if(!this.cacheDir)return;existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true});let t={schema:e,timestamp:Date.now(),version:e.identifier.version},r=`${e.identifier.package}-${e.identifier.version}-${e.identifier.kind}-${e.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),i=join(this.cacheDir,r);try{await writeFile(i,JSON.stringify(t,null,2),"utf-8");}catch(n){console.warn(`Failed to persist schema to ${i}:`,n);}}async clearDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t)await unlink(join(this.cacheDir,r));}catch(e){console.warn("Failed to clear cache directory:",e);}}};var I=class{manager;options;cacheConfig;cache;logger;constructor(e={},t){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=t,this.logger=e.logger||w({verbose:this.options.verbose,prefix:"TypeSchema"});}async initializeCache(){this.cacheConfig&&!this.cache&&(this.cache=new R(this.cacheConfig),await this.cache.initialize());}async registerFromPackageMetas(e){let t=e.map(r=>`${r.name}${r.version}`);return this.logger?.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),j(this.manager)}generateFhirSchemas(e){this.logger?.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=this.applyStructureDefinitionTreeshaking(e),r=[],i=0,n=0;for(let o of t)try{let c=ct.translate(o);r.push(c),i++,this.logger?.debug(`Converted StructureDefinition: ${o.name||o.id} (${o.resourceType})`);}catch(c){n++,this.logger?.warn(`Failed to convert StructureDefinition ${o.name||o.id}: ${c instanceof Error?c.message:String(c)}`);}return this.logger?.success(`FHIR Schema conversion completed: ${i}/${t.length} successful, ${n} failed`),r}async generateValueSetSchemas(e,t){e.length>0&&this.logger?.debug(`${e.length} ValueSets available for enum extraction`);let r=await j(this.manager,t),i=[];if(e.length>0){this.logger?.progress(`Converting ${e.length} ValueSets to TypeSchema`);let n=0,o=0;for(let c of e)try{let a=await se(r,c,t);a&&(i.push(a),n++,this.logger?.debug(`Converted ValueSet: ${c.name||c.id}`));}catch(a){o++,this.logger?.warn(`Failed to convert ValueSet ${c.name||c.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger?.success(`ValueSet conversion completed: ${n}/${e.length} successful, ${o} failed`);}return i}async generateFromPackage(e,t,r){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??false)){let l=this.cache.getByPackage(e);if(l.length>0)return this.logger?.info(`Using cached TypeSchemas for package: ${e} (${l.length} schemas)`),l}let i={name:e,version:t||"latest"},n=await this.registerFromPackageMetas([i]),o=await this.generateValueSetSchemas(n.allVs(),r),a=[...(await Promise.all(n.allFs().map(async l=>await oe(n,l,r)))).flat(),...o];if(this.cache)for(let l of a)await this.cache.set(l);return a}applyStructureDefinitionTreeshaking(e){let t=this.options.treeshake;if(!t||t.length===0)return e;this.logger?.info(`Applying treeshaking filter for ResourceTypes: ${t.join(", ")}`);let r=new Map,i=new Map,n=new Map;for(let p of e){let u=p.name||p.id;u&&(r.set(u,p),i.set(u,new Set),n.set(u,new Set));}for(let p of e){let u=p.name||p.id;if(!u)continue;let{realDeps:g,refTargets:f}=this.extractStructureDefinitionDependenciesWithReferences(p);i.set(u,new Set(g)),n.set(u,new Set(f));}let o=new Set;for(let p of t)r.has(p)?o.add(p):this.logger?.warn(`ResourceType '${p}' not found in structure definitions`);let c=(p,u=new Set)=>{if(u.has(p)||!i.has(p))return;u.add(p);let g=i.get(p)||new Set;for(let f of Array.from(g))r.has(f)&&(o.add(f),c(f,u));};for(let p of Array.from(o))c(p);let a=e.filter(p=>{let u=p.name||p.id;return u&&o.has(u)}),l=new Set;for(let p of e){let u=p.name||p.id;u&&!o.has(u)&&Array.from(n.values()).some(f=>f.has(u))&&l.add(u);}return l.size>0&&this.logger?.info(`Excluded reference-only targets: ${Array.from(l).join(", ")}`),this.logger?.success(`Treeshaking completed: kept ${a.length}/${e.length} structure definitions`),a}extractStructureDefinitionDependenciesWithReferences(e){let t=new Set,r=new Set;if(e.baseDefinition){let i=this.extractResourceNameFromUrl(e.baseDefinition);i&&t.add(i);}if(e.snapshot?.element||e.differential?.element){let i=e.snapshot?.element||e.differential?.element;for(let n of i)if(n.type)for(let o of n.type){if(o.code&&(t.add(o.code),o.code==="Reference"&&o.targetProfile))for(let c of o.targetProfile){let a=this.extractResourceNameFromUrl(c);a&&r.add(a);}if(o.profile)for(let c of o.profile){let a=this.extractResourceNameFromUrl(c);a&&t.add(a);}}}return {realDeps:Array.from(t),refTargets:Array.from(r)}}extractResourceNameFromUrl(e){let t=e.match(/\/([^/]+)$/);return t?t[1]??null:null}};var D=class{options;constructor(e={}){this.options={format:"auto",validate:true,strict:false,...e};}async parseFromFile(e){let t=await readFile(e,"utf-8"),r=this.options.format==="auto"?this.detectFormat(t,e):this.options.format;return this.parseFromString(t,r)}async parseFromString(e,t){let r=t||this.detectFormat(e),i;return r==="ndjson"?i=this.parseNDJSON(e):i=this.parseJSON(e),this.options.validate&&this.validateSchemas(i),i}async parseFromFiles(e){let t=[];for(let r of e){let i=await this.parseFromFile(r);t.push(...i);}return t}parseSchema(e){if(!e.identifier)throw new Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(e.identifier))throw new Error("TypeSchema identifier is invalid");return e}findByIdentifier(e,t){return e.filter(r=>this.matchesIdentifier(r.identifier,t))}findByUrl(e,t){return e.find(r=>r.identifier.url===t)}findByKind(e,t){return e.filter(r=>r.identifier.kind===t)}findByPackage(e,t){return e.filter(r=>r.identifier.package===t)}detectFormat(e,t){if(t){if(t.endsWith(".ndjson"))return "ndjson";if(t.endsWith(".json"))return "json"}let r=e.trim();if(r.includes(`
|
|
15
15
|
`)){let i=r.split(`
|
|
16
16
|
`).filter(n=>n.trim());if(i.length>1)try{return i[0]&&JSON.parse(i[0]),"ndjson"}catch{}}return "json"}parseNDJSON(e){let t=[],r=e.split(`
|
|
17
17
|
`).filter(i=>i.trim());for(let i of r)try{let n=JSON.parse(i);t.push(this.parseSchema(n));}catch(n){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${n}`)}return t}parseJSON(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(r=>this.parseSchema(r)):[this.parseSchema(t)]}catch(t){throw new Error(`Failed to parse JSON: ${t}`)}}validateSchemas(e){for(let t of e){if(!t.identifier)throw new Error("Schema missing identifier");if(!this.isValidIdentifier(t.identifier))throw new Error(`Invalid identifier in schema: ${JSON.stringify(t.identifier)}`)}}isValidIdentifier(e){return typeof e=="object"&&e!==null&&typeof e.kind=="string"&&typeof e.package=="string"&&typeof e.version=="string"&&typeof e.name=="string"&&typeof e.url=="string"}matchesIdentifier(e,t){return (!t.kind||e.kind===t.kind)&&(!t.package||e.package===t.package)&&(!t.version||e.version===t.version)&&(!t.name||e.name===t.name)&&(!t.url||e.url===t.url)}};var vt=async(s,e)=>{let t=[];for(let r of s.allFs())t.push(...await oe(s,r,e));for(let r of s.allVs())t.push(await se(s,r));return t};var xt=s=>{let e={};for(let t of s){let r=t.identifier.package;e[r]||(e[r]=[]),e[r].push(t);}for(let[t,r]of Object.entries(e))r.sort((i,n)=>i.identifier.name.localeCompare(n.identifier.name));return e},cr=s=>{let e=s.filter(Ne),t=[];for(let n of e)n.base&&t.push({parent:n.base,child:n.identifier});let r=[...t],i=n=>{let o=t.filter(a=>a.parent.name===n.name).map(a=>a.child),c=[];for(let a of o)c.push(...i(a));return [...o,...c]};for(let n of t){let o=i(n.child);for(let c of o)t.some(a=>a.parent.name===n.parent.name&&a.child.name===c.name)||r.push({parent:n.parent,child:c});}return r},Tt=s=>{let e={},t=p=>{let u=p.identifier.url;e[u]||(e[u]={}),e[u][p.identifier.package]=p;};for(let p of s)t(p);let r=cr(s),i=p=>e[p.url]?.[p.package],n=p=>r.filter(u=>u.parent.name===p.name).map(u=>u.child),o=p=>{let u=[],g=p;for(;g;){u.push(g);let f=g.base;if(f===void 0)break;let d=i(f);if(!d)throw new Error(`Failed to resolve base type: ${u.map(h=>`${h.identifier.url} (${h.identifier.kind})`).join(", ")}`);g=d;}return u};return {_schemaIndex:e,_relations:r,collectComplexTypes:()=>s.filter(ot),collectResources:()=>s.filter(Ne),collectLogicalModels:()=>s.filter(at),collectProfiles:()=>s.filter(Q),resolve:i,resourceChildren:n,hierarchy:o,findLastSpecialization:p=>{let u=i(p);if(!u)return p;let g=o(u).find(f=>f.identifier.kind!=="profile");if(!g)throw new Error(`No non-constraint schema found in hierarchy for ${p.name}`);return g.identifier},flatProfile:p=>{let u=o(p),g=u.filter(m=>m.identifier.kind==="profile"),f=u.find(m=>m.identifier.kind!=="profile");if(!f)throw new Error(`No non-constraint schema found in hierarchy for ${p.identifier.name}`);let d={};for(let m of g.slice().reverse()){let C=m;if(C.fields)for(let[k,T]of Object.entries(C.fields))d[k]?d[k]={...d[k],...T}:d[k]={...T};}let h={};for(let m of g.flatMap(C=>C.dependencies??[]))h[m.url]=m;let x=Object.values(h);return {...p,base:f.identifier,fields:d,dependencies:x}},isWithMetaField:p=>o(p).filter(L).some(u=>(console.log(u.fields?.meta),u.fields?.meta!==void 0))}};G();var ue=class{constructor(e){this.options=e;}handleError(e,t){e instanceof S?this.handleGeneratorError(e,t):this.handleUnknownError(e,t);}handleBatchErrors(e){let t=e.filter(i=>i instanceof S),r=e.filter(i=>!(i instanceof S));t.length>0&&this.reportBatchErrors(t),r.forEach(i=>{this.handleUnknownError(i);});}handleGeneratorError(e,t){switch(this.options.outputFormat){case "json":this.reportErrorAsJson(e);break;case "structured":this.reportErrorStructured(e);break;default:this.reportErrorToConsole(e);}}handleUnknownError(e,t){this.options.logger.error("Unexpected error occurred:",e),this.options.verbose&&(this.options.logger.error(`
|
|
@@ -34,11 +34,11 @@ ${i}`:r}filterAndSortSchemas(e){return this.collectedValueSets=this.collectValue
|
|
|
34
34
|
`)||"",i=[];return this.options.includeDocuments&&(i.push("/**"),i.push(` * ${e.identifier.name} value set`),e.description&&i.push(` * ${e.description}`),e.valueset?.url&&i.push(` * @see ${e.valueset.url}`),e.identifier.package&&i.push(` * @package ${e.identifier.package}`),i.push(" * @generated This file is auto-generated. Do not edit manually."),i.push(" */"),i.push("")),i.push(`export const ${t}Values = [`),r&&i.push(r),i.push("] as const;"),i.push(""),i.push(`export type ${t} = typeof ${t}Values[number];`),this.tsOptions.includeValueSetHelpers&&(i.push(""),i.push(`export const isValid${t} = (value: string): value is ${t} =>`),i.push(` ${t}Values.includes(value as ${t});`)),i.join(`
|
|
35
35
|
`)}async generateValueSetFiles(){if(!(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)){for(let[e,t]of this.collectedValueSets){let r=this.generateValueSetFile(t),i=`valuesets/${e}.ts`;await this.fileManager.writeFile(i,r),this.logger.info(`Generated value set: ${i}`);}await this.generateValueSetIndexFile();}}async generateValueSetIndexFile(){let e=[];this.tsOptions.includeDocuments&&(e.push("/**"),e.push(" * FHIR Value Sets"),e.push(" * This file re-exports all generated value sets."),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push(""));let t=Array.from(this.collectedValueSets.keys()).sort();for(let i of t)e.push(`export * from './${i}.js';`);let r=e.join(`
|
|
36
36
|
`);await this.fileManager.writeFile("valuesets/index.ts",r),this.logger.info(`Generated valuesets/index.ts with ${this.collectedValueSets.size} value sets`);}async generateMainIndexFile(){if(!this.options.generateIndex)return;let e=[];this.tsOptions.includeDocuments&&(e.push("/**"),e.push(" * FHIR R4 TypeScript Types"),e.push(" * Generated from FHIR StructureDefinitions"),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push("")),e.push('export * from "./utilities";'),this.tsOptions.generateValueSets&&this.collectedValueSets.size>0&&(e.push(""),e.push("// Value Sets"),e.push('export * from "./valuesets/index";'));let t=e.join(`
|
|
37
|
-
`);await this.fileManager.writeFile("index.ts",t),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`);}};var Mt=s=>s.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),U=s=>Mt(s).map(e=>e.toLowerCase()).join("-"),mr=s=>{if(s.length===0)throw new Error("Empty string");return s[0]?.toUpperCase()+s.substring(1).toLowerCase()};var
|
|
37
|
+
`);await this.fileManager.writeFile("index.ts",t),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`);}};var Mt=s=>s.split(/(?<=[a-z])(?=[A-Z])|[-_.\s]/).filter(Boolean),U=s=>Mt(s).map(e=>e.toLowerCase()).join("-"),mr=s=>{if(s.length===0)throw new Error("Empty string");return s[0]?.toUpperCase()+s.substring(1).toLowerCase()};var _=s=>Mt(s).map(mr).join("");var ye=s=>!s||s.length===0?s:s.charAt(0).toUpperCase()+s.slice(1),Nt=s=>s.map(e=>ye(e));var Ke=class{opts;currentDir;currentFileDescriptor;writtenFilesSet=new Set;constructor(e){this.opts=e,this.currentDir=e.outputDir;}logger(){return this.opts.logger}cd(e,t){this.currentDir=e.startsWith("/")?q.join(this.opts.outputDir,e):q.join(this.currentDir,e),F.existsSync(this.currentDir)||F.mkdirSync(this.currentDir,{recursive:true}),this.logger()?.debug(`cd '${this.currentDir}'`),t();}cat(e,t){if(this.currentFileDescriptor)throw new Error("Can't open file in file");if(e.includes("/"))throw new Error(`Change file path separatly: ${e}`);let r=`${this.currentDir}/${e}`;try{this.currentFileDescriptor=F.openSync(r,"w"),this.writtenFilesSet.add(e),this.logger()?.debug(`cat > '${r}'`),t();}finally{this.currentFileDescriptor&&F.closeSync(this.currentFileDescriptor),this.currentFileDescriptor=void 0;}}write(e){if(!this.currentFileDescriptor)throw new Error("No file opened");F.writeSync(this.currentFileDescriptor,e);}generate(e){throw new Error("Not implemented")}writtenFiles(){return Array.from(this.writtenFilesSet)}},be=class extends Ke{currentIndent=0;indent(){this.currentIndent+=this.opts.tabSize;}deindent(){this.currentIndent-=this.opts.tabSize;}writeIndent(){this.write(" ".repeat(this.currentIndent));}line(...e){e.length===0?this.write(`
|
|
38
38
|
`):(this.writeIndent(),this.write(`${e.join(" ")}
|
|
39
39
|
`));}lineSM(...e){this.writeIndent(),this.write(`${e.join(" ")};
|
|
40
40
|
`);}comment(...e){let t=e.join(" ").split(`
|
|
41
|
-
`);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/orgs/atomic-ehr/repositories","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>this.comment(e)),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var Ot={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"},yr=s=>U(s),Dt=s=>s.kind==="profile"?`${v(s)}_profile`:z(s.name),br=s=>`${Dt(s)}.ts`,Ze=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),Se(t)},v=s=>{if(s.kind==="nested"){let e=s.url,t=Ze(e,false);if(!t)return "";let[r,i]=t.split("#"),n=Nt((i??"").split(".")).join("");return Se([r,n].join(""))}return Se(s.name)},B=s=>Se(s),Se=s=>(new Set(["abstract","any","as","async","await","boolean","bigint","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","extern","false","finally","for","function","from","get","goto","if","implements","import","in","infer","instanceof","interface","keyof","let","module","namespace","never","new","null","number","object","of","override","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","this","throw","true","try","type","typeof","unknown","var","void","while"]).has(s)&&(s=`${s}_`),s.replace(/[- ]/g,"_")),ve=class extends be{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.map(r=>({identifier:r.identifier,tsPackageName:Dt(r.identifier),resourceName:v(r.identifier)})).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${r.resourceName} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],r=[];for(let i of e.dependencies)["complex-type","resource","logical"].includes(i.kind)?t.push({tsPackage:`../${U(i.package)}/${z(i.name)}`,name:ye(i.name)}):Y(i)?t.push({tsPackage:`../${U(i.package)}/${z(Ze(i.url)??"")}`,name:v(i)}):r.push(i);t.sort((i,n)=>i.name.localeCompare(n.name));for(let i of t)this.tsImportType(i.tsPackage,i.name);for(let i of r)this.debugComment("skip:",i);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${U(r.package)}/${z(r.name)}`,name:ye(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e,t){t.type.kind==="primitive-type"&&this.lineSM(`_${B(e)}?: Element`);}generateType(e,t){var r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=v(t.identifier));let i=Ze(t.base?.url),n=i&&`extends ${i}`;this.debugComment(t.identifier),this.curlyBlock(["export","interface",r,n],()=>{if(!t.fields)return;if(t.identifier.kind==="resource"){let c=[t.identifier];c.push(...e.resourceChildren(t.identifier)),this.lineSM(`resourceType: ${c.map(a=>`"${a.name}"`).join(" | ")}`),this.line();}let o=Object.entries(t.fields).sort((c,a)=>c[0].localeCompare(a[0]));for(let[c,a]of o){if(!$(a))continue;this.debugComment(c,":",a);let l=B(c),p=a.required?"":"?",u=a.array?"[]":"";if(a.type===void 0)continue;let g=a.type.name;a.type.kind==="nested"&&(g=v(a.type)),a.type.kind==="primitive-type"&&(g=Ot[a.type.name]??"string"),t.identifier.name==="Reference"&&l==="reference"&&(g="`${T}/${string}`"),a.reference?.length&&(g=`Reference<${a.reference.map(d=>`"${d.name}"`).join(" | ")}>`),a.enum&&(g=a.enum.map(f=>`"${f}"`).join(" | ")),this.lineSM(`${l}${p}:`,`${g}${u}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(c,a);}});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r);}generateProfileType(e,t){let r=v(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{if(this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line(),!!st(t))for(let[i,n]of Object.entries(t.fields??{})){if(!$(n))continue;this.debugComment(i,n);let o=B(i),c;if(n.type.kind==="nested")c=v(n.type);else if(n.enum)c=n.enum.map(a=>`'${a}'`).join(" | ");else if(n.reference&&n.reference.length>0){let a=e.findLastSpecialization(t.identifier),l=e.resolve(a);if(!L(l))throw new Error(`Invalid specialization for ${t.identifier}`);let p=l.fields?.[i];if(p===void 0||!$(p))throw new Error(`Invalid field declaration for ${i}`);let u=(p.reference??[]).map(f=>f.name),g=n.reference.map(f=>{let d=e.findLastSpecialization(f);return d.name!==f.name?`"${d.name}" /*${f.name}*/`:`'${f.name}'`}).join(" | ");u.length===1&&u[0]==="Resource"&&g!=='"Resource"'?c=`Reference<"Resource" /* ${g} */ >`:c=`Reference<${g}>`;}else c=Ot[n.type.name]??n.type.name;this.lineSM(`${o}${n.required?"":"?"}: ${c}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=v(e.base),r=v(e.identifier),i=Object.entries(e.fields||{}).filter(([n,o])=>o&&$(o)&&o.type!==void 0).map(([n])=>B(n));this.curlyBlock([`export const attach_${r} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),i.forEach(n=>{this.line(`${n}:`,`profile.${n},`);});});}),this.line();}generateExtractProfile(e,t){let r=v(t.base),i=v(t.identifier),n=Object.entries(t.fields||{}).filter(([a,l])=>$(l)&&l.type!==void 0).map(([a])=>a),o=e.resolve(e.findLastSpecialization(t.identifier));if(!L(o))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${r} =`,`(resource: ${r}): ${i}`,"=>"],()=>{n.forEach(a=>{let l=B(a),p=t.fields?.[a],u=o.fields?.[a];if(!$(p)||!$(u))return;p.required&&!u.required&&this.curlyBlock([`if (resource.${l} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let g=p?.reference?.map(d=>d.name),f=u?.reference?.map(d=>d.name);if(g&&f&&g.length!==f.length){let d=`reference_pred_${l}`;this.curlyBlock(["const",d,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{f.forEach(x=>{this.line(`|| ref.reference?.startsWith('${x}/')`);}),this.line(";");});});let h=p?.required?"":`!resource.${l} || `;p.array?h+=`resource.${l}.every( (ref) => ${d}(ref) )`:h+=`${d}(resource.${l})`,this.curlyBlock(["if (",h,")"],()=>{this.lineSM(`throw new Error("'${a}' has different references in profile and specialization")`);}),this.line(),c[a]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(a=>{let l=B(a);c[a]?this.line(`${l}:`,`resource.${l} as ${i}['${l}'],`):this.line(`${l}:`,`resource.${l},`);});});});}generateResourceModule(e,t){this.cat(`${br(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.generateType(e,t);else if(Q(t)){let r=e.flatProfile(t);this.generateDependenciesImports(r),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectProfiles().filter(i=>e.isWithMetaField(i))],r=xt(t);this.cd("/",()=>{for(let[i,n]of Object.entries(r)){let o=yr(i);this.cd(o,()=>{for(let c of n)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(n);});}});}};var xr=s=>{let e=()=>s.writtenFiles().map(t=>({path:q.normalize(q.join(s.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),content:"",exports:[],size:0,timestamp:new Date}));return {generate:async t=>{let r=Tt(t);return s.generate(r),e()},setOutputDir:t=>s.opts.outputDir=t,build:async t=>e()}},_=class{schemas=[];options;generators=new Map;cache;pendingOperations=[];typeSchemaGenerator;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||w({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new R(this.typeSchemaConfig));}fromPackage(e,t){return this.packages.push(it({name:e,version:t||"latest"})),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new H({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}typescript2(e){let t={outputDir:q.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},r={logger:this.logger,...t,...e},i=xr(new ve(r));return this.generators.set("typescript2",i),this.logger.debug(`Configured TypeScript2 generator (${JSON.stringify(r,void 0,2)})`),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose:e}),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};if(this.logger.debug(`Starting generation with ${this.generators.size} generators`),this.options.cleanOutput){this.logger.info(`Cleaning output directory: ${this.options.outputDir}`);try{F.rmSync(this.options.outputDir,{recursive:!0,force:!0}),F.mkdirSync(this.options.outputDir,{recursive:!0});}catch(r){this.logger.warn(`Error cleaning output directory: ${r instanceof Error?r.message:String(r)}`);}}try{this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:"tmp/fhir"});await r.init();let i=await j(r,this.logger),n=await vt(i,this.logger);this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,n),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r));}return {...t,success:t.errors.length===0,duration:performance.now()-e}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new I({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new D({format:"auto"}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async executeGenerators(e,t){for(let[r,i]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{let n=await i.generate(t);e.filesGenerated.push(...n.map(o=>o.path||o.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`);}}}};var Ye={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Te=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Qe=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},Xe=class{validator=new Qe;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Ye}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
|
|
41
|
+
`);for(let r of t)this.line(this.opts.commentLinePrefix,r);}debugComment(...e){this.opts.withDebugComment&&(e=e.map(t=>typeof t=="string"?t:JSON.stringify(t,null,2)),this.comment(...e));}disclaimer(){return ["WARNING: This file is autogenerated by @atomic-ehr/codegen.","GitHub: https://github.com/orgs/atomic-ehr/repositories","Any manual changes made to this file may be overwritten."]}generateDisclaimer(){this.disclaimer().forEach(e=>this.comment(e)),this.line();}indentBlock(e){this.indent(),e(),this.deindent();}curlyBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} {`),this.indent(),t(),this.deindent(),this.line(`}${r?.filter(Boolean).join(" ")??""}`);}squareBlock(e,t,r){this.line(`${e.filter(Boolean).join(" ")} [`),this.indent(),t(),this.deindent(),this.line(`]${r?.filter(Boolean).join(" ")??""}`);}};var Ot={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"},yr=s=>U(s),Dt=s=>s.kind==="profile"?`${v(s)}_profile`:_(s.name),br=s=>`${Dt(s)}.ts`,Ze=(s,e=true)=>{if(!s)return;let t=s.split("/").pop();if(t&&(e&&t.includes("#")&&(t=t.split("#")[0]),!!t))return /^\d/.test(t)&&(t=`number_${t}`),Se(t)},v=s=>{if(s.kind==="nested"){let e=s.url,t=Ze(e,false);if(!t)return "";let[r,i]=t.split("#"),n=Nt((i??"").split(".")).join("");return Se([r,n].join(""))}return Se(s.name)},B=s=>Se(s),Se=s=>(new Set(["abstract","any","as","async","await","boolean","bigint","break","case","catch","class","const","constructor","continue","debugger","declare","default","delete","do","else","enum","export","extends","extern","false","finally","for","function","from","get","goto","if","implements","import","in","infer","instanceof","interface","keyof","let","module","namespace","never","new","null","number","object","of","override","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","this","throw","true","try","type","typeof","unknown","var","void","while"]).has(s)&&(s=`${s}_`),s.replace(/[- ]/g,"_")),ve=class extends be{tsImportType(e,...t){this.lineSM(`import type { ${t.join(", ")} } from "${e}"`);}generateFhirPackageIndexFile(e){this.cat("index.ts",()=>{let t=e.map(r=>({identifier:r.identifier,tsPackageName:Dt(r.identifier),resourceName:v(r.identifier)})).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));t=Array.from(new Map(t.map(r=>[r.resourceName.toLowerCase(),r])).values()).sort((r,i)=>r.resourceName.localeCompare(i.resourceName));for(let r of t)this.debugComment(r.identifier),this.lineSM(`export type { ${r.resourceName} } from "./${r.tsPackageName}"`);});}generateDependenciesImports(e){if(e.dependencies){let t=[],r=[];for(let i of e.dependencies)["complex-type","resource","logical"].includes(i.kind)?t.push({tsPackage:`../${U(i.package)}/${_(i.name)}`,name:ye(i.name)}):Y(i)?t.push({tsPackage:`../${U(i.package)}/${_(Ze(i.url)??"")}`,name:v(i)}):r.push(i);t.sort((i,n)=>i.name.localeCompare(n.name));for(let i of t)this.tsImportType(i.tsPackage,i.name);for(let i of r)this.debugComment("skip:",i);this.line();}}generateComplexTypeReexports(e){let t=e.dependencies?.filter(r=>["complex-type"].includes(r.kind)).map(r=>({tsPackage:`../${U(r.package)}/${_(r.name)}`,name:ye(r.name)}));if(t&&t.length>0){for(let r of t)this.lineSM(`export type { ${r.name} } from "${r.tsPackage}"`);this.line();}}addFieldExtension(e,t){t.type.kind==="primitive-type"&&this.lineSM(`_${B(e)}?: Element`);}generateType(e,t){var r;t.identifier.name==="Reference"?r="Reference<T extends string = string>":(t.identifier.kind,r=v(t.identifier));let i=Ze(t.base?.url),n=i&&`extends ${i}`;this.debugComment(t.identifier),this.curlyBlock(["export","interface",r,n],()=>{if(!t.fields)return;if(t.identifier.kind==="resource"){let c=[t.identifier];c.push(...e.resourceChildren(t.identifier)),this.lineSM(`resourceType: ${c.map(a=>`"${a.name}"`).join(" | ")}`),this.line();}let o=Object.entries(t.fields).sort((c,a)=>c[0].localeCompare(a[0]));for(let[c,a]of o){if(!$(a))continue;this.debugComment(c,":",a);let l=B(c),p=a.required?"":"?",u=a.array?"[]":"";if(a.type===void 0)continue;let g=a.type.name;a.type.kind==="nested"&&(g=v(a.type)),a.type.kind==="primitive-type"&&(g=Ot[a.type.name]??"string"),t.identifier.name==="Reference"&&l==="reference"&&(g="`${T}/${string}`"),a.reference?.length&&(g=`Reference<${a.reference.map(d=>`"${d.name}"`).join(" | ")}>`),a.enum&&(g=a.enum.map(f=>`"${f}"`).join(" | ")),this.lineSM(`${l}${p}:`,`${g}${u}`),["resource","complex-type"].includes(t.identifier.kind)&&this.addFieldExtension(c,a);}});}generateNestedTypes(e,t){if(t.nested)for(let r of t.nested)this.generateType(e,r);}generateProfileType(e,t){let r=v(t.identifier);this.debugComment("identifier",t.identifier),this.debugComment("base",t.base),this.curlyBlock(["export","interface",r],()=>{if(this.lineSM(`__profileUrl: "${t.identifier.url}"`),this.line(),!!st(t))for(let[i,n]of Object.entries(t.fields??{})){if(!$(n))continue;this.debugComment(i,n);let o=B(i),c;if(n.type.kind==="nested")c=v(n.type);else if(n.enum)c=n.enum.map(a=>`'${a}'`).join(" | ");else if(n.reference&&n.reference.length>0){let a=e.findLastSpecialization(t.identifier),l=e.resolve(a);if(!L(l))throw new Error(`Invalid specialization for ${t.identifier}`);let p=l.fields?.[i];if(p===void 0||!$(p))throw new Error(`Invalid field declaration for ${i}`);let u=(p.reference??[]).map(f=>f.name),g=n.reference.map(f=>{let d=e.findLastSpecialization(f);return d.name!==f.name?`"${d.name}" /*${f.name}*/`:`'${f.name}'`}).join(" | ");u.length===1&&u[0]==="Resource"&&g!=='"Resource"'?c=`Reference<"Resource" /* ${g} */ >`:c=`Reference<${g}>`;}else c=Ot[n.type.name]??n.type.name;this.lineSM(`${o}${n.required?"":"?"}: ${c}${n.array?"[]":""}`);}}),this.line();}generateAttachProfile(e){let t=v(e.base),r=v(e.identifier),i=Object.entries(e.fields||{}).filter(([n,o])=>o&&$(o)&&o.type!==void 0).map(([n])=>B(n));this.curlyBlock([`export const attach_${r}_to_${t} =`,`(resource: ${t}, profile: ${r}): ${t}`,"=>"],()=>{this.curlyBlock(["return"],()=>{this.line("...resource,"),this.curlyBlock(["meta:"],()=>{this.line(`profile: ['${e.identifier.url}']`);},[","]),i.forEach(n=>{this.line(`${n}:`,`profile.${n},`);});});}),this.line();}generateExtractProfile(e,t){let r=v(t.base),i=v(t.identifier),n=Object.entries(t.fields||{}).filter(([a,l])=>$(l)&&l.type!==void 0).map(([a])=>a),o=e.resolve(e.findLastSpecialization(t.identifier));if(!L(o))throw new Error(`Specialization not found for ${t.identifier.url}`);let c={};this.curlyBlock([`export const extract_${i}_from_${r} =`,`(resource: ${r}): ${i}`,"=>"],()=>{n.forEach(a=>{let l=B(a),p=t.fields?.[a],u=o.fields?.[a];if(!$(p)||!$(u))return;p.required&&!u.required&&this.curlyBlock([`if (resource.${l} === undefined)`],()=>this.lineSM(`throw new Error("'${l}' is required for ${t.identifier.url}")`));let g=p?.reference?.map(d=>d.name),f=u?.reference?.map(d=>d.name);if(g&&f&&g.length!==f.length){let d=`reference_is_valid_${l}`;this.curlyBlock(["const",d,"=","(ref?: Reference)","=>"],()=>{this.line("return !ref"),this.indentBlock(()=>{f.forEach(x=>{this.line(`|| ref.reference?.startsWith('${x}/')`);}),this.line(";");});});let h=p?.required?"":`!resource.${l} || `;p.array?h+=`resource.${l}.every( (ref) => ${d}(ref) )`:h+=`!${d}(resource.${l})`,this.curlyBlock(["if (",h,")"],()=>{this.lineSM(`throw new Error("'${a}' has different references in profile and specialization")`);}),this.line(),c[a]=true;}}),this.curlyBlock(["return"],()=>{this.line(`__profileUrl: '${t.identifier.url}',`),n.forEach(a=>{let l=B(a);c[a]?this.line(`${l}:`,`resource.${l} as ${i}['${l}'],`):this.line(`${l}:`,`resource.${l},`);});});});}generateResourceModule(e,t){this.cat(`${br(t.identifier)}`,()=>{if(this.generateDisclaimer(),["complex-type","resource","logical"].includes(t.identifier.kind))this.generateDependenciesImports(t),this.generateComplexTypeReexports(t),this.generateNestedTypes(e,t),this.generateType(e,t);else if(Q(t)){let r=e.flatProfile(t);this.generateDependenciesImports(r),this.generateProfileType(e,r),this.generateAttachProfile(r),this.generateExtractProfile(e,r);}else throw new Error(`Profile generation not implemented for kind: ${t.identifier.kind}`)});}generate(e){let t=[...e.collectComplexTypes(),...e.collectResources(),...e.collectProfiles().filter(i=>e.isWithMetaField(i))],r=xt(t);this.cd("/",()=>{for(let[i,n]of Object.entries(r)){let o=yr(i);this.cd(o,()=>{for(let c of n)this.generateResourceModule(e,c);this.generateFhirPackageIndexFile(n);});}});}};var xr=s=>{let e=()=>s.writtenFiles().map(t=>({path:q.normalize(q.join(s.opts.outputDir,t)),filename:t.replace(/^.*[\\/]/,""),content:"",exports:[],size:0,timestamp:new Date}));return {generate:async t=>{let r=Tt(t);return s.generate(r),e()},setOutputDir:t=>s.opts.outputDir=t,build:async t=>e()}},z=class{schemas=[];options;generators=new Map;cache;pendingOperations=[];typeSchemaGenerator;logger;packages=[];progressCallback;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,cache:e.cache??true,cleanOutput:e.cleanOutput??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null,throwException:e.throwException||false},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||w({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new R(this.typeSchemaConfig));}fromPackage(e,t){return this.packages.push(it({name:e,version:t||"latest"})),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new H({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}typescript2(e){let t={outputDir:q.join(this.options.outputDir,"/types"),tabSize:4,withDebugComment:false,commentLinePrefix:"//"},r={logger:this.logger,...t,...e},i=xr(new ve(r));return this.generators.set("typescript2",i),this.logger.debug(`Configured TypeScript2 generator (${JSON.stringify(r,void 0,2)})`),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this.logger?.configure({verbose:e}),this}throwException(e=true){return this.options.throwException=e,this}cleanOutput(e=true){return this.options.cleanOutput=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};if(this.logger.debug(`Starting generation with ${this.generators.size} generators`),this.options.cleanOutput){this.logger.info(`Cleaning output directory: ${this.options.outputDir}`);try{F.rmSync(this.options.outputDir,{recursive:!0,force:!0}),F.mkdirSync(this.options.outputDir,{recursive:!0});}catch(r){this.logger.warn(`Error cleaning output directory: ${r instanceof Error?r.message:String(r)}`);}}try{this.logger.info("Initialize Canonical Manager");let r=CanonicalManager({packages:this.packages,workingDir:"tmp/fhir"});await r.init();let i=await j(r,this.logger),n=await vt(i,this.logger);this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t,n),this.logger.info("Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r));}return {...t,success:t.errors.length===0,duration:performance.now()-e}}async build(){let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new I({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new D({format:"auto"}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async executeGenerators(e,t){for(let[r,i]of this.generators.entries()){this.logger.info(`Generating ${r}...`);try{let n=await i.generate(t);e.filesGenerated.push(...n.map(o=>o.path||o.filename)),this.logger.info(`Generating ${r} finished successfully`);}catch(n){e.errors.push(`${r} generator failed: ${n instanceof Error?n.message:String(n)}`);}}}};var Ye={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,cleanOutput:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},Te=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Qe=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},Xe=class{validator=new Qe;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...Ye}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
|
|
42
42
|
`);throw new Error(`Configuration validation failed:
|
|
43
43
|
${i}`)}return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of Te){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...Ye,...e,typescript:{...Ye.typescript,...e.typescript}}}},Cr=new Xe;async function we(s){return Cr.autoload(s)}var Lt={command:"generate",describe:"Generate code based on configuration file settings",builder:s=>s.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async s=>{if(s._.length>1){let o=s._.slice(1).join(" ");b(`Invalid syntax: 'atomic-codegen generate ${o}'
|
|
44
44
|
|
|
@@ -61,7 +61,7 @@ export default defineConfig({
|
|
|
61
61
|
typescript: {
|
|
62
62
|
generateIndex: true
|
|
63
63
|
}
|
|
64
|
-
});`),process.exit(1);}let r=await we(e),i=s.verbose??r.verbose??false,n=w({verbose:i,prefix:"Generate"});try{Re("Starting generation from config"),i&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let o=new
|
|
64
|
+
});`),process.exit(1);}let r=await we(e),i=s.verbose??r.verbose??false,n=w({verbose:i,prefix:"Generate"});try{Re("Starting generation from config"),i&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let o=new z({outputDir:r.outputDir||"./generated",verbose:i,overwrite:r.overwrite??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let a of r.packages){let[l,p]=a.includes("@")?a.split("@"):[a,void 0];o.fromPackage(l,p);}}else if(r.files&&r.files.length>0){n.info(`Loading files from config: ${r.files.join(", ")}`);for(let a of r.files)o.fromFiles(a);}else throw new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript&&(i&&(n.info("Configuring TypeScript generation from config"),n.debug(`Module format: ${r.typescript.moduleFormat||"esm"}`),n.debug(`Generate index: ${r.typescript.generateIndex??!0}`),n.debug(`Include docs: ${r.typescript.includeDocuments??!1}`),n.debug(`Naming convention: ${r.typescript.namingConvention||"PascalCase"}`)),o.typescript(r.typescript)),!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");i&&o.onProgress((a,l,p,u)=>{let g=Math.round(l/p*100);n.progress(`[${a}] ${g}% - ${u||"Processing..."}`);}),n.step("Executing generation...");let c=await o.generate();if(c.success){if(K(`Generated ${c.filesGenerated.length} files in ${c.duration.toFixed(2)}ms`),n.dim(`Output directory: ${c.outputDir}`),c.warnings.length>0)for(let a of c.warnings)$e(a);}else {b(`Generation failed with ${c.errors.length} errors`);for(let a of c.errors)n.dim(` ${a}`);process.exit(1);}}catch(o){b("Generation failed with unexpected error",o instanceof Error?o:new Error(String(o))),process.exit(1);}}};async function $r(s){for(let e of Te){let t=resolve(s,e);if(existsSync(t))return t}return null}var jt={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:true,demandOption:true,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:true,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:false,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:false,describe:"Enable verbose output"}},handler:async s=>{let e=w({verbose:s.verbose,prefix:"TypeSchema"});try{let t=await we(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${s.packages.join(", ")}`),e.info(`Output: ${s.output}`);let r=s.singleFile!==void 0?s.singleFile:t.typeSchema?.singleFile??!1,i=r?"ndjson":s.format;e.debug(`Format: ${i}${r&&s.format==="json"?" (forced from json due to singleFile)":""}`);let n=s.treeshake&&s.treeshake.length>0?s.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let o=Date.now(),c=new I({verbose:s.verbose,treeshake:n}),a=[];for(let g of s.packages){let[f,d]=g.includes("@")?g.split("@"):[g,void 0];e.progress(`Processing package: ${f}${d?`@${d}`:""}`);let h=await c.generateFromPackage(f,d,e);a.push(...h);}if(a.length===0)throw new Error("No schemas were generated from the specified packages");let l=s.output;await mkdir(dirname(l),{recursive:!0});let p;i==="json"?p=JSON.stringify(a,null,2):p=a.map(g=>JSON.stringify(g)).join(`
|
|
65
65
|
`),await writeFile(l,p,"utf-8");let u=Date.now()-o;if(Pe(`Generated ${a.length} TypeSchema definitions`,u,{schemas:a.length}),e.dim(`Output: ${l}`),s.verbose){e.debug("Generated schemas:");let g=a.map(f=>`${f.identifier?.name||"Unknown"} (${f.identifier?.kind||"unknown"})`);M(g);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var Vt={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:s=>s.command(jt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:s=>{if(!s.subcommand&&s._.length===1){Z("Available typeschema subcommands:"),M(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
|
|
66
66
|
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
|
|
67
67
|
Examples:`),M(["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}s.subcommand&&!["generate","validate","merge"].includes(s.subcommand)&&(b(`Unknown typeschema subcommand: ${s.subcommand}
|
package/dist/index.js
CHANGED
|
@@ -5490,7 +5490,7 @@ var TypeScript = class extends Writer {
|
|
|
5490
5490
|
}).map(([fieldName]) => tsFieldName(fieldName));
|
|
5491
5491
|
this.curlyBlock(
|
|
5492
5492
|
[
|
|
5493
|
-
`export const attach_${tsProfileName} =`,
|
|
5493
|
+
`export const attach_${tsProfileName}_to_${tsBaseResourceName} =`,
|
|
5494
5494
|
`(resource: ${tsBaseResourceName}, profile: ${tsProfileName}): ${tsBaseResourceName}`,
|
|
5495
5495
|
"=>"
|
|
5496
5496
|
],
|
|
@@ -5520,7 +5520,7 @@ var TypeScript = class extends Writer {
|
|
|
5520
5520
|
const shouldCast = {};
|
|
5521
5521
|
this.curlyBlock(
|
|
5522
5522
|
[
|
|
5523
|
-
`export const extract_${tsBaseResourceName} =`,
|
|
5523
|
+
`export const extract_${tsProfileName}_from_${tsBaseResourceName} =`,
|
|
5524
5524
|
`(resource: ${tsBaseResourceName}): ${tsProfileName}`,
|
|
5525
5525
|
"=>"
|
|
5526
5526
|
],
|
|
@@ -5541,7 +5541,7 @@ var TypeScript = class extends Writer {
|
|
|
5541
5541
|
const pRefs = pField?.reference?.map((ref) => ref.name);
|
|
5542
5542
|
const rRefs = rField?.reference?.map((ref) => ref.name);
|
|
5543
5543
|
if (pRefs && rRefs && pRefs.length !== rRefs.length) {
|
|
5544
|
-
const predName = `
|
|
5544
|
+
const predName = `reference_is_valid_${tsField}`;
|
|
5545
5545
|
this.curlyBlock(["const", predName, "=", "(ref?: Reference)", "=>"], () => {
|
|
5546
5546
|
this.line("return !ref");
|
|
5547
5547
|
this.indentBlock(() => {
|
|
@@ -5555,7 +5555,7 @@ var TypeScript = class extends Writer {
|
|
|
5555
5555
|
if (pField.array) {
|
|
5556
5556
|
cond += `resource.${tsField}.every( (ref) => ${predName}(ref) )`;
|
|
5557
5557
|
} else {
|
|
5558
|
-
cond +=
|
|
5558
|
+
cond += `!${predName}(resource.${tsField})`;
|
|
5559
5559
|
}
|
|
5560
5560
|
this.curlyBlock(["if (", cond, ")"], () => {
|
|
5561
5561
|
this.lineSM(
|