@atomic-ehr/codegen 0.0.1-canary.20250831211734.bb1536b → 0.0.1-canary.20250923152114.2852906

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as b6}from"node:module";var w6=Object.create;var{getPrototypeOf:T6,defineProperty:V0,getOwnPropertyNames:$1,getOwnPropertyDescriptor:I6}=Object,X1=Object.prototype.hasOwnProperty;var S0=(D,F,u)=>{u=D!=null?w6(T6(D)):{};let E=F||!D||!D.__esModule?V0(u,"default",{value:D,enumerable:!0}):u;for(let B of $1(D))if(!X1.call(E,B))V0(E,B,{get:()=>D[B],enumerable:!0});return E},C1=new WeakMap,UF=(D)=>{var F=C1.get(D),u;if(F)return F;if(F=V0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")$1(D).map((E)=>!X1.call(F,E)&&V0(F,E,{get:()=>D[E],enumerable:!(u=I6(D,E))||u.enumerable}));return C1.set(D,F),F},LF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var NF=(D,F)=>{for(var u in F)V0(D,u,{get:F[u],enumerable:!0,configurable:!0,set:(E)=>F[u]=()=>E})};var Z1=(D,F)=>()=>(D&&(F=D(D=0)),F);var jF=b6(import.meta.url);var H1=LF((XE,G1)=>{G1.exports=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g}});var m1=LF((tE,g1)=>{g1.exports=function D(F){if(F===void 0)F=2;if(F>=Error.stackTraceLimit)throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+F+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var u=Error.prepareStackTrace;Error.prepareStackTrace=function(B,C){return C};var E=new Error().stack;if(Error.prepareStackTrace=u,E!==null&&typeof E==="object")return E[F]?E[F].getFileName():void 0}});var B2=LF((GC,E2)=>{var r0=process||{},x3=r0.argv||[],s0=r0.env||{},h8=!(!!s0.NO_COLOR||x3.includes("--no-color"))&&(!!s0.FORCE_COLOR||x3.includes("--color")||r0.platform==="win32"||(r0.stdout||{}).isTTY&&s0.TERM!=="dumb"||!!s0.CI),p8=(D,F,u=D)=>(E)=>{let B=""+E,C=B.indexOf(F,D.length);return~C?D+g8(B,F,u,C)+F:D+B+F},g8=(D,F,u,E)=>{let B="",C=0;do B+=D.substring(C,E)+u,C=E+F.length,E=D.indexOf(F,C);while(~E);return B+D.substring(C)},P3=(D=h8)=>{let F=D?p8:()=>String;return{isColorSupported:D,reset:F("\x1B[0m","\x1B[0m"),bold:F("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:F("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:F("\x1B[3m","\x1B[23m"),underline:F("\x1B[4m","\x1B[24m"),inverse:F("\x1B[7m","\x1B[27m"),hidden:F("\x1B[8m","\x1B[28m"),strikethrough:F("\x1B[9m","\x1B[29m"),black:F("\x1B[30m","\x1B[39m"),red:F("\x1B[31m","\x1B[39m"),green:F("\x1B[32m","\x1B[39m"),yellow:F("\x1B[33m","\x1B[39m"),blue:F("\x1B[34m","\x1B[39m"),magenta:F("\x1B[35m","\x1B[39m"),cyan:F("\x1B[36m","\x1B[39m"),white:F("\x1B[37m","\x1B[39m"),gray:F("\x1B[90m","\x1B[39m"),bgBlack:F("\x1B[40m","\x1B[49m"),bgRed:F("\x1B[41m","\x1B[49m"),bgGreen:F("\x1B[42m","\x1B[49m"),bgYellow:F("\x1B[43m","\x1B[49m"),bgBlue:F("\x1B[44m","\x1B[49m"),bgMagenta:F("\x1B[45m","\x1B[49m"),bgCyan:F("\x1B[46m","\x1B[49m"),bgWhite:F("\x1B[47m","\x1B[49m"),blackBright:F("\x1B[90m","\x1B[39m"),redBright:F("\x1B[91m","\x1B[39m"),greenBright:F("\x1B[92m","\x1B[39m"),yellowBright:F("\x1B[93m","\x1B[39m"),blueBright:F("\x1B[94m","\x1B[39m"),magentaBright:F("\x1B[95m","\x1B[39m"),cyanBright:F("\x1B[96m","\x1B[39m"),whiteBright:F("\x1B[97m","\x1B[39m"),bgBlackBright:F("\x1B[100m","\x1B[49m"),bgRedBright:F("\x1B[101m","\x1B[49m"),bgGreenBright:F("\x1B[102m","\x1B[49m"),bgYellowBright:F("\x1B[103m","\x1B[49m"),bgBlueBright:F("\x1B[104m","\x1B[49m"),bgMagentaBright:F("\x1B[105m","\x1B[49m"),bgCyanBright:F("\x1B[106m","\x1B[49m"),bgWhiteBright:F("\x1B[107m","\x1B[49m")}};E2.exports=P3();E2.exports.createColors=P3});var ND,l2,qF,X0,c2,o2;var P0=Z1(()=>{ND=class ND extends Error{phase;context;timestamp;errorId;constructor(D,F,u){super(D);this.phase=F;this.context=u;if(this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}generateErrorId(){return`${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let D=[`❌ ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];if(this.context&&Object.keys(this.context).length>0)D.push(""),D.push("\uD83D\uDCCD Context:"),Object.entries(this.context).forEach(([F,u])=>{D.push(` ${F}: ${this.formatContextValue(u)}`)});return D.join(`
3
- `)}formatContextValue(D){if(D===null||D===void 0)return String(D);if(typeof D==="string")return`"${D}"`;if(typeof D==="object")try{return JSON.stringify(D,null,2)}catch{return"[Object]"}return String(D)}getSeverity(){return"error"}isRecoverable(){return!1}getDocumentationLinks(){return["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}};l2=class l2 extends ND{schema;validationErrors;userContext;constructor(D,F,u,E){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:u,userContext:E});this.schema=F;this.validationErrors=u;this.userContext=E}getSuggestions(){let D=[];D.push("Verify the schema follows the TypeSchema specification"),D.push("Check that all required fields are present and properly typed");for(let F of this.validationErrors){if(F.includes("identifier.name"))D.push("✨ Add a valid identifier.name field to your schema"),D.push('\uD83D\uDCA1 Example: identifier: { name: "Patient", kind: "resource" }');if(F.includes("identifier.kind"))D.push('\uD83C\uDFAF Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),D.push("\uD83D\uDCDA Check FHIR specification for the correct kind value");if(F.includes("circular"))D.push("\uD83D\uDD04 Remove circular references between schemas"),D.push("\uD83D\uDCA1 Use forward declarations for recursive types"),D.push("\uD83D\uDD0D Look for schemas that reference each other in a loop");if(F.includes("fields"))D.push("\uD83D\uDCDD Check that all fields have proper type definitions"),D.push("\uD83D\uDD27 Ensure field types reference valid TypeSchema identifiers")}if(this.userContext?.isBeginnerMode){if(D.push(""),D.push("\uD83C\uDF93 Beginner Tips:"),D.push("\uD83D\uDCD6 Start with the Quick Start guide: docs/getting-started/quick-start.md"),D.push("\uD83D\uDD0D Use --verbose flag for detailed error information"),D.push("\uD83E\uDDEA Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length)D.push(`✅ Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)}if(!this.userContext?.isBeginnerMode)D.push(""),D.push("\uD83D\uDD27 Advanced Debugging:"),D.push("\uD83D\uDD75️ Enable schema validation debugging"),D.push("\uD83D\uDCCA Check schema statistics and complexity metrics"),D.push("⚡ Consider schema preprocessing if dealing with complex inheritance");return D}isRecoverable(){return this.validationErrors.every((D)=>!D.includes("circular")&&!D.includes("corruption"))}};qF=class qF extends ND{templateName;templateContext;debugInfo;constructor(D,F,u,E){super(D,"generation",{templateName:F,contextKeys:Object.keys(u),availableTemplates:E?.availableTemplates?.length||0,debugInfo:E});this.templateName=F;this.templateContext=u;this.debugInfo=E}getSuggestions(){let D=[];if(this.debugInfo?.availableTemplates?.length){if(!this.debugInfo.availableTemplates.includes(this.templateName)){D.push(`❌ Template '${this.templateName}' not found`),D.push("\uD83D\uDCC2 Available templates:"),this.debugInfo.availableTemplates.forEach((u)=>{D.push(` • ${u}`)});let F=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);if(F.length>0)D.push("\uD83E\uDD14 Did you mean:"),F.forEach((u)=>{D.push(` • ${u}`)})}}if(this.debugInfo?.missingVariables?.length){D.push("\uD83D\uDCDD Missing template variables:"),this.debugInfo.missingVariables.forEach((u)=>{D.push(` • ${u}`)}),D.push("\uD83D\uDCA1 Add these variables to your template context");let F=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach((u)=>{let E=F.filter((B)=>this.levenshteinDistance(u.toLowerCase(),B.toLowerCase())<=2);if(E.length>0)D.push(` Similar to: ${E.join(", ")}`)})}if(this.debugInfo?.lineNumber){if(D.push(`\uD83D\uDC1B Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber)D.push(` Column: ${this.debugInfo.columnNumber}`);if(this.debugInfo.templateSource){let u=this.debugInfo.templateSource.split(`
4
- `)[this.debugInfo.lineNumber-1];if(u)D.push(` Code: ${u.trim()}`)}}return D.push("\uD83D\uDD27 Template debugging steps:"),D.push(" • Enable template debugging: { debug: true }"),D.push(" • Verify template file exists and has correct syntax"),D.push(" • Check template variable names match context keys"),D.push(" • Ensure template engine is properly configured"),D}findSimilarTemplates(D,F){return F.filter((u)=>{let E=this.levenshteinDistance(D.toLowerCase(),u.toLowerCase());return E<=2&&E>0}).slice(0,3).sort((u,E)=>this.levenshteinDistance(D.toLowerCase(),u.toLowerCase())-this.levenshteinDistance(D.toLowerCase(),E.toLowerCase()))}levenshteinDistance(D,F){let u=Array(F.length+1).fill(null).map(()=>Array(D.length+1).fill(0));for(let E=0;E<=D.length;E++)u[0][E]=E;for(let E=0;E<=F.length;E++)u[E][0]=E;for(let E=1;E<=F.length;E++)for(let B=1;B<=D.length;B++){let C=D[B-1]===F[E-1]?0:1;u[E][B]=Math.min(u[E]?.[B-1]+1,u[E-1]?.[B]+1,u[E-1]?.[B-1]+C)}return u[F.length]?.[D.length]}isRecoverable(){return!0}};X0=class X0 extends ND{operation;filePath;originalError;recoveryOptions;constructor(D,F,u,E,B){super(D,"writing",{operation:F,filePath:u,originalErrorMessage:E?.message,originalErrorCode:E?.code,recoveryOptions:B});this.operation=F;this.filePath=u;this.originalError=E;this.recoveryOptions=B}getSuggestions(){let D=[],F=this.originalError?.code;switch(this.operation){case"create":case"write":if(D.push("\uD83D\uDCC1 File writing troubleshooting:"),D.push(" • Check if the output directory exists"),D.push(" • Verify write permissions for the target directory"),D.push(" • Ensure no other process has the file locked"),this.filePath.includes(" "))D.push(" • File path contains spaces - check path escaping");if(this.recoveryOptions?.alternativePaths?.length)D.push("\uD83D\uDD04 Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach((u)=>{D.push(` • ${u}`)});break;case"read":D.push("\uD83D\uDCD6 File reading troubleshooting:"),D.push(" • Verify the file exists at the specified path"),D.push(" • Check file read permissions"),D.push(" • Ensure file is not corrupted");break;case"delete":D.push("\uD83D\uDDD1️ File deletion troubleshooting:"),D.push(" • Check if file is locked by another process"),D.push(" • Verify delete permissions for the directory"),D.push(" • Ensure file exists before attempting deletion");break}switch(F){case"EACCES":if(D.push("\uD83D\uDD10 Permission Error:"),D.push(" • Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix)D.push(` • Fix command: ${this.recoveryOptions.permissionFix}`);else D.push(` • Try: chmod 755 "${this.filePath}"`);D.push(" • Consider running with elevated permissions"),D.push(" • Check directory ownership and permissions");break;case"ENOSPC":if(D.push("\uD83D\uDCBE Disk Space Error:"),D.push(" • Insufficient disk space available"),D.push(" • Free up disk space and retry"),D.push(" • Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let u=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);D.push(` • Required space: ~${u}MB`)}break;case"ENOENT":D.push("\uD83D\uDCC2 File Not Found:"),D.push(" • File or directory does not exist"),D.push(" • Check the file path for typos"),D.push(" • Ensure parent directories exist"),D.push(` • Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case"EMFILE":case"ENFILE":D.push("\uD83D\uDCCA Too Many Open Files:"),D.push(" • System has reached file handle limit"),D.push(" • Close unused files and retry"),D.push(" • Consider processing files in smaller batches");break}if(this.recoveryOptions?.canRetry)D.push(""),D.push("\uD83D\uDD04 Recovery Options:"),D.push(" • This operation can be retried safely"),D.push(" • Fix the underlying issue and run again");return D.push(""),D.push("\uD83D\uDD0D General Debugging:"),D.push(" • Check system logs for more details"),D.push(" • Verify disk health if errors persist"),D.push(" • Test with a simpler file path"),D}isRecoverable(){return this.recoveryOptions?.canRetry||!1}getRecoveryActions(){let D=[];switch(this.originalError?.code){case"EACCES":D.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:!1,riskLevel:"medium"});break;case"ENOENT":D.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:!0,riskLevel:"low"});break;case"ENOSPC":D.push({action:"Free up disk space",automatic:!1,riskLevel:"low"});break}return D}};c2=class c2 extends ND{configKey;providedValue;expectedValue;validOptions;constructor(D,F,u,E,B){super(D,"initialization",{configKey:F,providedValue:u,providedType:typeof u,expectedValue:E,validOptions:B});this.configKey=F;this.providedValue=u;this.expectedValue=E;this.validOptions=B}getSuggestions(){let D=[];if(D.push(`⚙️ Configuration error for '${this.configKey}'`),D.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue)D.push(` Expected: ${this.expectedValue}`);if(this.validOptions?.length)D.push(" Valid options:"),this.validOptions.forEach((F)=>{D.push(` • ${JSON.stringify(F)}`)});switch(D.push(""),D.push("\uD83D\uDD27 Configuration fixes:"),D.push(` • Check the '${this.configKey}' value in your configuration`),D.push(" • Refer to the configuration documentation"),D.push(" • Use TypeScript for better config validation"),D.push(" • Check for typos in configuration keys"),this.configKey){case"outputDir":D.push(" • Ensure the output directory path exists"),D.push(" • Use absolute paths for better reliability");break;case"logger":D.push(" • Provide a valid logger instance"),D.push(" • Use createLogger() from utils/codegen-logger");break;case"validation":D.push(' • Set to true, false, or "strict"');break}return D}isRecoverable(){return!0}};o2=class o2 extends ND{errors;constructor(D,F){super(D,"generation",{errorCount:F.length,errorTypes:[...new Set(F.map((u)=>u.constructor.name))],phases:[...new Set(F.map((u)=>u.phase))]});this.errors=F}getSuggestions(){let D=this.errors.flatMap((C)=>C.getSuggestions()),F=[...new Set(D)],u=[];u.push(`\uD83D\uDCCA Batch operation failed with ${this.errors.length} errors:`);let E=new Map;this.errors.forEach((C)=>{let $=C.constructor.name;if(!E.has($))E.set($,[]);E.get($)?.push(C)}),u.push(""),u.push("\uD83D\uDD0D Error breakdown:");for(let[C,$]of E)u.push(` • ${C}: ${$.length} occurrences`);u.push("\uD83D\uDCA1 Most relevant suggestions:");let B=F.slice(0,8).map((C)=>` ${C}`);return u.push(...B),u}getErrorBreakdown(){let D=[];return this.errors.forEach((F,u)=>{if(D.push(`${u+1}. ${F.constructor.name}: ${F.message}`),F.context?.schemaName)D.push(` Schema: ${F.context.schemaName}`);if(F.context?.filename)D.push(` File: ${F.context.filename}`);D.push("")}),D.join(`
5
- `)}isRecoverable(){return this.errors.some((D)=>D.isRecoverable())}getRecoverableErrors(){return this.errors.filter((D)=>D.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter((D)=>!D.isRecoverable())}}});var W6={};NF(W6,{FileBuilder:()=>J6});class J6{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:!0,formatting:{indentSize:2,useTabs:!1,maxLineLength:100},encoding:"utf-8"};constructor(D){this.config=D}withContent(D){return this.content=typeof D==="string"?D:D(),this}withTemplate(D,F){if(!this.config.templateEngine)throw new qF(`Template engine is required for template rendering. Template: '${D}'`,D,F);this.options.template=D;try{this.content=this.config.templateEngine.render(D,{...F,imports:this.imports,exports:this.exports,filename:this.config.filename})}catch(u){throw new qF(`Failed to render template '${D}'`,D,F,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(D){return this.content+=D,this}prependContent(D){return this.content=D+this.content,this}withImports(D){this.imports.clear();for(let[F,u]of D)this.imports.set(F,u);return this}addImport(D,F){return this.imports.set(D,F),this}addImports(D,F){for(let u of D)this.imports.set(u,F);return this}withExports(D){this.exports.clear();for(let F of D)this.exports.add(F);return this}addExport(D){return this.exports.add(D),this}addExports(D){for(let F of D)this.exports.add(F);return this}withMetadata(D,F){return this.metadata.set(D,F),this}withOptions(D){return this.options={...this.options,...D},this}onBeforeSave(D){return this.beforeSaveHooks.push(D),this}onAfterSave(D){return this.afterSaveHooks.push(D),this}onError(D){return this.errorHooks.push(D),this}build(){let D=this.buildFinalContent();return{filename:this.config.filename,content:D,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let D=this.build();try{for(let E of this.beforeSaveHooks)await E(D);if(this.options.validation!=="none")await this.validateContent(D.content);let F=await this.config.fileManager.writeFile(this.config.filename,D.content,{encoding:this.options.encoding}),u={size:F.size,generationTime:0,writeTime:F.writeTime};for(let E of this.afterSaveHooks)await E(F.path,u);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),F.path}catch(F){for(let u of this.errorHooks)try{await u(F instanceof Error?F:new Error(String(F)),D)}catch(E){this.config.logger.warn(`Error hook failed: ${E instanceof Error?E.message:String(E)}`)}throw F}}buildFinalContent(){let D=[];if(this.imports.size>0&&this.options.importStrategy!=="none")D.push(this.generateImportStatements()),D.push("");if(this.content)D.push(this.content);if(this.exports.size>0&&!this.content.includes("export"))D.push(""),D.push(this.generateExportStatements());let F=D.join(`
2
+ import{createRequire as T6}from"node:module";var N6=Object.create;var{getPrototypeOf:j6,defineProperty:M0,getOwnPropertyNames:e2,getOwnPropertyDescriptor:w6}=Object,D1=Object.prototype.hasOwnProperty;var b0=(D,F,u)=>{u=D!=null?N6(j6(D)):{};let E=F||!D||!D.__esModule?M0(u,"default",{value:D,enumerable:!0}):u;for(let B of e2(D))if(!D1.call(E,B))M0(E,B,{get:()=>D[B],enumerable:!0});return E},a2=new WeakMap,MF=(D)=>{var F=a2.get(D),u;if(F)return F;if(F=M0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")e2(D).map((E)=>!D1.call(F,E)&&M0(F,E,{get:()=>D[E],enumerable:!(u=w6(D,E))||u.enumerable}));return a2.set(D,F),F},qF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var _F=(D,F)=>{for(var u in F)M0(D,u,{get:F[u],enumerable:!0,configurable:!0,set:(E)=>F[u]=()=>E})};var F1=(D,F)=>()=>(D&&(F=D(D=0)),F);var KF=T6(import.meta.url);var z1=qF((XE,Q1)=>{Q1.exports=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g}});var f1=qF((tE,v1)=>{v1.exports=function(F){if(F===void 0)F=2;if(F>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+F+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var u=Error.prepareStackTrace;Error.prepareStackTrace=function(B,C){return C};var E=Error().stack;if(Error.prepareStackTrace=u,E!==null&&typeof E==="object")return E[F]?E[F].getFileName():void 0}});var aF=qF((GC,rF)=>{var i0=process||{},L3=i0.argv||[],n0=i0.env||{},y8=!(!!n0.NO_COLOR||L3.includes("--no-color"))&&(!!n0.FORCE_COLOR||L3.includes("--color")||i0.platform==="win32"||(i0.stdout||{}).isTTY&&n0.TERM!=="dumb"||!!n0.CI),h8=(D,F,u=D)=>(E)=>{let B=""+E,C=B.indexOf(F,D.length);return~C?D+d8(B,F,u,C)+F:D+B+F},d8=(D,F,u,E)=>{let B="",C=0;do B+=D.substring(C,E)+u,C=E+F.length,E=D.indexOf(F,C);while(~E);return B+D.substring(C)},N3=(D=y8)=>{let F=D?h8:()=>String;return{isColorSupported:D,reset:F("\x1B[0m","\x1B[0m"),bold:F("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:F("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:F("\x1B[3m","\x1B[23m"),underline:F("\x1B[4m","\x1B[24m"),inverse:F("\x1B[7m","\x1B[27m"),hidden:F("\x1B[8m","\x1B[28m"),strikethrough:F("\x1B[9m","\x1B[29m"),black:F("\x1B[30m","\x1B[39m"),red:F("\x1B[31m","\x1B[39m"),green:F("\x1B[32m","\x1B[39m"),yellow:F("\x1B[33m","\x1B[39m"),blue:F("\x1B[34m","\x1B[39m"),magenta:F("\x1B[35m","\x1B[39m"),cyan:F("\x1B[36m","\x1B[39m"),white:F("\x1B[37m","\x1B[39m"),gray:F("\x1B[90m","\x1B[39m"),bgBlack:F("\x1B[40m","\x1B[49m"),bgRed:F("\x1B[41m","\x1B[49m"),bgGreen:F("\x1B[42m","\x1B[49m"),bgYellow:F("\x1B[43m","\x1B[49m"),bgBlue:F("\x1B[44m","\x1B[49m"),bgMagenta:F("\x1B[45m","\x1B[49m"),bgCyan:F("\x1B[46m","\x1B[49m"),bgWhite:F("\x1B[47m","\x1B[49m"),blackBright:F("\x1B[90m","\x1B[39m"),redBright:F("\x1B[91m","\x1B[39m"),greenBright:F("\x1B[92m","\x1B[39m"),yellowBright:F("\x1B[93m","\x1B[39m"),blueBright:F("\x1B[94m","\x1B[39m"),magentaBright:F("\x1B[95m","\x1B[39m"),cyanBright:F("\x1B[96m","\x1B[39m"),whiteBright:F("\x1B[97m","\x1B[39m"),bgBlackBright:F("\x1B[100m","\x1B[49m"),bgRedBright:F("\x1B[101m","\x1B[49m"),bgGreenBright:F("\x1B[102m","\x1B[49m"),bgYellowBright:F("\x1B[103m","\x1B[49m"),bgBlueBright:F("\x1B[104m","\x1B[49m"),bgMagentaBright:F("\x1B[105m","\x1B[49m"),bgCyanBright:F("\x1B[106m","\x1B[49m"),bgWhiteBright:F("\x1B[107m","\x1B[49m")}};rF.exports=N3();rF.exports.createColors=N3});var ND,k2,YF,X0,y2,h2;var I0=F1(()=>{ND=class ND extends Error{phase;context;timestamp;errorId;constructor(D,F,u){super(D);this.phase=F;this.context=u;if(this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}generateErrorId(){return`${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let D=[`❌ ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];if(this.context&&Object.keys(this.context).length>0)D.push(""),D.push("\uD83D\uDCCD Context:"),Object.entries(this.context).forEach(([F,u])=>{D.push(` ${F}: ${this.formatContextValue(u)}`)});return D.join(`
3
+ `)}formatContextValue(D){if(D===null||D===void 0)return String(D);if(typeof D==="string")return`"${D}"`;if(typeof D==="object")try{return JSON.stringify(D,null,2)}catch{return"[Object]"}return String(D)}getSeverity(){return"error"}isRecoverable(){return!1}getDocumentationLinks(){return["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}};k2=class k2 extends ND{schema;validationErrors;userContext;constructor(D,F,u,E){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:u,userContext:E});this.schema=F;this.validationErrors=u;this.userContext=E}getSuggestions(){let D=[];D.push("Verify the schema follows the TypeSchema specification"),D.push("Check that all required fields are present and properly typed");for(let F of this.validationErrors){if(F.includes("identifier.name"))D.push("✨ Add a valid identifier.name field to your schema"),D.push('\uD83D\uDCA1 Example: identifier: { name: "Patient", kind: "resource" }');if(F.includes("identifier.kind"))D.push('\uD83C\uDFAF Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),D.push("\uD83D\uDCDA Check FHIR specification for the correct kind value");if(F.includes("circular"))D.push("\uD83D\uDD04 Remove circular references between schemas"),D.push("\uD83D\uDCA1 Use forward declarations for recursive types"),D.push("\uD83D\uDD0D Look for schemas that reference each other in a loop");if(F.includes("fields"))D.push("\uD83D\uDCDD Check that all fields have proper type definitions"),D.push("\uD83D\uDD27 Ensure field types reference valid TypeSchema identifiers")}if(this.userContext?.isBeginnerMode){if(D.push(""),D.push("\uD83C\uDF93 Beginner Tips:"),D.push("\uD83D\uDCD6 Start with the Quick Start guide: docs/getting-started/quick-start.md"),D.push("\uD83D\uDD0D Use --verbose flag for detailed error information"),D.push("\uD83E\uDDEA Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length)D.push(`✅ Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)}if(!this.userContext?.isBeginnerMode)D.push(""),D.push("\uD83D\uDD27 Advanced Debugging:"),D.push("\uD83D\uDD75️ Enable schema validation debugging"),D.push("\uD83D\uDCCA Check schema statistics and complexity metrics"),D.push("⚡ Consider schema preprocessing if dealing with complex inheritance");return D}isRecoverable(){return this.validationErrors.every((D)=>!D.includes("circular")&&!D.includes("corruption"))}};YF=class YF extends ND{templateName;templateContext;debugInfo;constructor(D,F,u,E){super(D,"generation",{templateName:F,contextKeys:Object.keys(u),availableTemplates:E?.availableTemplates?.length||0,debugInfo:E});this.templateName=F;this.templateContext=u;this.debugInfo=E}getSuggestions(){let D=[];if(this.debugInfo?.availableTemplates?.length){if(!this.debugInfo.availableTemplates.includes(this.templateName)){D.push(`❌ Template '${this.templateName}' not found`),D.push("\uD83D\uDCC2 Available templates:"),this.debugInfo.availableTemplates.forEach((u)=>{D.push(` • ${u}`)});let F=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);if(F.length>0)D.push("\uD83E\uDD14 Did you mean:"),F.forEach((u)=>{D.push(` • ${u}`)})}}if(this.debugInfo?.missingVariables?.length){D.push("\uD83D\uDCDD Missing template variables:"),this.debugInfo.missingVariables.forEach((u)=>{D.push(` • ${u}`)}),D.push("\uD83D\uDCA1 Add these variables to your template context");let F=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach((u)=>{let E=F.filter((B)=>this.levenshteinDistance(u.toLowerCase(),B.toLowerCase())<=2);if(E.length>0)D.push(` Similar to: ${E.join(", ")}`)})}if(this.debugInfo?.lineNumber){if(D.push(`\uD83D\uDC1B Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber)D.push(` Column: ${this.debugInfo.columnNumber}`);if(this.debugInfo.templateSource){let u=this.debugInfo.templateSource.split(`
4
+ `)[this.debugInfo.lineNumber-1];if(u)D.push(` Code: ${u.trim()}`)}}return D.push("\uD83D\uDD27 Template debugging steps:"),D.push(" • Enable template debugging: { debug: true }"),D.push(" • Verify template file exists and has correct syntax"),D.push(" • Check template variable names match context keys"),D.push(" • Ensure template engine is properly configured"),D}findSimilarTemplates(D,F){return F.filter((u)=>{let E=this.levenshteinDistance(D.toLowerCase(),u.toLowerCase());return E<=2&&E>0}).slice(0,3).sort((u,E)=>this.levenshteinDistance(D.toLowerCase(),u.toLowerCase())-this.levenshteinDistance(D.toLowerCase(),E.toLowerCase()))}levenshteinDistance(D,F){let u=Array(F.length+1).fill(null).map(()=>Array(D.length+1).fill(0));for(let E=0;E<=D.length;E++)u[0][E]=E;for(let E=0;E<=F.length;E++)u[E][0]=E;for(let E=1;E<=F.length;E++)for(let B=1;B<=D.length;B++){let C=D[B-1]===F[E-1]?0:1;u[E][B]=Math.min(u[E]?.[B-1]+1,u[E-1]?.[B]+1,u[E-1]?.[B-1]+C)}return u[F.length]?.[D.length]}isRecoverable(){return!0}};X0=class X0 extends ND{operation;filePath;originalError;recoveryOptions;constructor(D,F,u,E,B){super(D,"writing",{operation:F,filePath:u,originalErrorMessage:E?.message,originalErrorCode:E?.code,recoveryOptions:B});this.operation=F;this.filePath=u;this.originalError=E;this.recoveryOptions=B}getSuggestions(){let D=[],F=this.originalError?.code;switch(this.operation){case"create":case"write":if(D.push("\uD83D\uDCC1 File writing troubleshooting:"),D.push(" • Check if the output directory exists"),D.push(" • Verify write permissions for the target directory"),D.push(" • Ensure no other process has the file locked"),this.filePath.includes(" "))D.push(" • File path contains spaces - check path escaping");if(this.recoveryOptions?.alternativePaths?.length)D.push("\uD83D\uDD04 Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach((u)=>{D.push(` • ${u}`)});break;case"read":D.push("\uD83D\uDCD6 File reading troubleshooting:"),D.push(" • Verify the file exists at the specified path"),D.push(" • Check file read permissions"),D.push(" • Ensure file is not corrupted");break;case"delete":D.push("\uD83D\uDDD1️ File deletion troubleshooting:"),D.push(" • Check if file is locked by another process"),D.push(" • Verify delete permissions for the directory"),D.push(" • Ensure file exists before attempting deletion");break}switch(F){case"EACCES":if(D.push("\uD83D\uDD10 Permission Error:"),D.push(" • Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix)D.push(` • Fix command: ${this.recoveryOptions.permissionFix}`);else D.push(` • Try: chmod 755 "${this.filePath}"`);D.push(" • Consider running with elevated permissions"),D.push(" • Check directory ownership and permissions");break;case"ENOSPC":if(D.push("\uD83D\uDCBE Disk Space Error:"),D.push(" • Insufficient disk space available"),D.push(" • Free up disk space and retry"),D.push(" • Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let u=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);D.push(` • Required space: ~${u}MB`)}break;case"ENOENT":D.push("\uD83D\uDCC2 File Not Found:"),D.push(" • File or directory does not exist"),D.push(" • Check the file path for typos"),D.push(" • Ensure parent directories exist"),D.push(` • Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case"EMFILE":case"ENFILE":D.push("\uD83D\uDCCA Too Many Open Files:"),D.push(" • System has reached file handle limit"),D.push(" • Close unused files and retry"),D.push(" • Consider processing files in smaller batches");break}if(this.recoveryOptions?.canRetry)D.push(""),D.push("\uD83D\uDD04 Recovery Options:"),D.push(" • This operation can be retried safely"),D.push(" • Fix the underlying issue and run again");return D.push(""),D.push("\uD83D\uDD0D General Debugging:"),D.push(" • Check system logs for more details"),D.push(" • Verify disk health if errors persist"),D.push(" • Test with a simpler file path"),D}isRecoverable(){return this.recoveryOptions?.canRetry||!1}getRecoveryActions(){let D=[];switch(this.originalError?.code){case"EACCES":D.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:!1,riskLevel:"medium"});break;case"ENOENT":D.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:!0,riskLevel:"low"});break;case"ENOSPC":D.push({action:"Free up disk space",automatic:!1,riskLevel:"low"});break}return D}};y2=class y2 extends ND{configKey;providedValue;expectedValue;validOptions;constructor(D,F,u,E,B){super(D,"initialization",{configKey:F,providedValue:u,providedType:typeof u,expectedValue:E,validOptions:B});this.configKey=F;this.providedValue=u;this.expectedValue=E;this.validOptions=B}getSuggestions(){let D=[];if(D.push(`⚙️ Configuration error for '${this.configKey}'`),D.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue)D.push(` Expected: ${this.expectedValue}`);if(this.validOptions?.length)D.push(" Valid options:"),this.validOptions.forEach((F)=>{D.push(` • ${JSON.stringify(F)}`)});switch(D.push(""),D.push("\uD83D\uDD27 Configuration fixes:"),D.push(` • Check the '${this.configKey}' value in your configuration`),D.push(" • Refer to the configuration documentation"),D.push(" • Use TypeScript for better config validation"),D.push(" • Check for typos in configuration keys"),this.configKey){case"outputDir":D.push(" • Ensure the output directory path exists"),D.push(" • Use absolute paths for better reliability");break;case"logger":D.push(" • Provide a valid logger instance"),D.push(" • Use createLogger() from utils/codegen-logger");break;case"validation":D.push(' • Set to true, false, or "strict"');break}return D}isRecoverable(){return!0}};h2=class h2 extends ND{errors;constructor(D,F){super(D,"generation",{errorCount:F.length,errorTypes:[...new Set(F.map((u)=>u.constructor.name))],phases:[...new Set(F.map((u)=>u.phase))]});this.errors=F}getSuggestions(){let D=this.errors.flatMap((C)=>C.getSuggestions()),F=[...new Set(D)],u=[];u.push(`\uD83D\uDCCA Batch operation failed with ${this.errors.length} errors:`);let E=new Map;this.errors.forEach((C)=>{let $=C.constructor.name;if(!E.has($))E.set($,[]);E.get($)?.push(C)}),u.push(""),u.push("\uD83D\uDD0D Error breakdown:");for(let[C,$]of E)u.push(` • ${C}: ${$.length} occurrences`);u.push("\uD83D\uDCA1 Most relevant suggestions:");let B=F.slice(0,8).map((C)=>` ${C}`);return u.push(...B),u}getErrorBreakdown(){let D=[];return this.errors.forEach((F,u)=>{if(D.push(`${u+1}. ${F.constructor.name}: ${F.message}`),F.context?.schemaName)D.push(` Schema: ${F.context.schemaName}`);if(F.context?.filename)D.push(` File: ${F.context.filename}`);D.push("")}),D.join(`
5
+ `)}isRecoverable(){return this.errors.some((D)=>D.isRecoverable())}getRecoverableErrors(){return this.errors.filter((D)=>D.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter((D)=>!D.isRecoverable())}}});var Y6={};_F(Y6,{FileBuilder:()=>O6});class O6{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:!0,formatting:{indentSize:2,useTabs:!1,maxLineLength:100},encoding:"utf-8"};constructor(D){this.config=D}withContent(D){return this.content=typeof D==="string"?D:D(),this}withTemplate(D,F){if(!this.config.templateEngine)throw new YF(`Template engine is required for template rendering. Template: '${D}'`,D,F);this.options.template=D;try{this.content=this.config.templateEngine.render(D,{...F,imports:this.imports,exports:this.exports,filename:this.config.filename})}catch(u){throw new YF(`Failed to render template '${D}'`,D,F,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(D){return this.content+=D,this}prependContent(D){return this.content=D+this.content,this}withImports(D){this.imports.clear();for(let[F,u]of D)this.imports.set(F,u);return this}addImport(D,F){return this.imports.set(D,F),this}addImports(D,F){for(let u of D)this.imports.set(u,F);return this}withExports(D){this.exports.clear();for(let F of D)this.exports.add(F);return this}addExport(D){return this.exports.add(D),this}addExports(D){for(let F of D)this.exports.add(F);return this}withMetadata(D,F){return this.metadata.set(D,F),this}withOptions(D){return this.options={...this.options,...D},this}onBeforeSave(D){return this.beforeSaveHooks.push(D),this}onAfterSave(D){return this.afterSaveHooks.push(D),this}onError(D){return this.errorHooks.push(D),this}build(){let D=this.buildFinalContent();return{filename:this.config.filename,content:D,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let D=this.build();try{for(let E of this.beforeSaveHooks)await E(D);if(this.options.validation!=="none")await this.validateContent(D.content);let F=await this.config.fileManager.writeFile(this.config.filename,D.content,{encoding:this.options.encoding}),u={size:F.size,generationTime:0,writeTime:F.writeTime};for(let E of this.afterSaveHooks)await E(F.path,u);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),F.path}catch(F){for(let u of this.errorHooks)try{await u(F instanceof Error?F:Error(String(F)),D)}catch(E){this.config.logger.warn(`Error hook failed: ${E instanceof Error?E.message:String(E)}`)}throw F}}buildFinalContent(){let D=[];if(this.imports.size>0&&this.options.importStrategy!=="none")D.push(this.generateImportStatements()),D.push("");if(this.content)D.push(this.content);if(this.exports.size>0&&!this.content.includes("export"))D.push(""),D.push(this.generateExportStatements());let F=D.join(`
6
6
  `);if(this.options.prettify)F=this.prettifyContent(F);return F}generateImportStatements(){let D=[],F=new Map;for(let[u,E]of this.imports){let B=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,E):E;if(!F.has(B))F.set(B,[]);F.get(B)?.push(u)}for(let[u,E]of F)if(E.length===1)D.push(`import type { ${E[0]} } from '${u}';`);else{let B=E.sort();if(B.length<=3)D.push(`import type { ${B.join(", ")} } from '${u}';`);else{D.push("import type {");let C="\t";B.forEach(($,X)=>{let Q=X===B.length-1;D.push(`${C}${$}${Q?"":","}`)}),D.push(`} from '${u}';`)}}return D.join(`
7
7
  `)}generateExportStatements(){return Array.from(this.exports).sort().map((F)=>`export { ${F} };`).join(`
8
8
  `)}prettifyContent(D){return D.replace(/\n{3,}/g,`
9
9
 
10
- `).replace(/\t/g,this.options.formatting?.useTabs?"\t":" ".repeat(this.options.formatting?.indentSize||2)).trim()}async validateContent(D){if(this.options.validation==="none")return;let F=[],u=(D.match(/\{/g)||[]).length,E=(D.match(/\}/g)||[]).length;if(u!==E)F.push(`Unmatched braces: ${u} open, ${E} close`);let B=(D.match(/\(/g)||[]).length,C=(D.match(/\)/g)||[]).length;if(B!==C)F.push(`Unmatched parentheses: ${B} open, ${C} close`);if(this.config.filename.endsWith(".ts")||this.config.filename.endsWith(".tsx")){if(D.includes("interface")&&!D.match(/interface\s+\w+\s*\{/))F.push("Invalid interface syntax detected")}if(F.length>0&&this.options.validation==="strict")throw new X0(`Content validation failed for ${this.config.filename}: ${F.join(", ")}`,"write",this.config.filename);else if(F.length>0)this.config.logger.warn(`Validation issues in ${this.config.filename}: ${F.join(", ")}`)}getContent(){return this.content}getImports(){return new Map(this.imports)}getExports(){return new Set(this.exports)}}var A6=Z1(()=>{P0()});var G6={};NF(G6,{DirectoryBuilder:()=>e2});class e2{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=!1;constructor(D){this.config=D}withSubdirectory(D){let F=`${this.config.path}/${D}`,u=new e2({path:F,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${D}`)});return this.subdirectories.set(D,u),u}withFiles(D){for(let[F,u]of Object.entries(D))this.files.set(F,u);return this}withFile(D,F){return this.files.set(D,F),this}withIndex(D){return this.indexBuilder=D,this}clean(){return this.shouldClean=!0,this}async ensure(){return await this.config.fileManager.ensureDirectory(this.config.path),this}async save(){let D=[];if(this.shouldClean)await this.config.fileManager.cleanDirectory(this.config.path);await this.ensure();let F=Array.from(this.files.entries()).map(async([u,E])=>{try{let B=await E.save();return D.push(B),B}catch(B){throw this.config.logger.error(`Failed to save file ${u}:`,B instanceof Error?B:void 0),B}});await Promise.all(F);for(let[u,E]of this.subdirectories)try{let B=await E.save();D.push(...B)}catch(B){throw this.config.logger.error(`Failed to save subdirectory ${u}:`,B instanceof Error?B:void 0),B}if(this.indexBuilder)try{let u=await this.indexBuilder.save();D.push(u)}catch(u){throw this.config.logger.error("Failed to save index file:",u instanceof Error?u:void 0),u}return this.config.logger.info(`Saved directory ${this.config.path} with ${D.length} files`),D}getFileList(){let D=[];for(let F of this.files.keys())D.push(`${this.config.path}/${F}`);for(let[F,u]of this.subdirectories){let E=u.getFileList();D.push(...E)}if(this.indexBuilder)D.push(`${this.config.path}/index.ts`);return D.sort()}getStats(){let D=this.files.size;for(let F of this.subdirectories.values())D+=F.getStats().totalFiles;if(this.indexBuilder)D+=1;return{fileCount:this.files.size,subdirectoryCount:this.subdirectories.size,hasIndex:!!this.indexBuilder,totalFiles:D}}async wouldOverwrite(){let D=[];for(let F of this.files.keys()){let u=`${this.config.path}/${F}`;if(await this.config.fileManager.wouldOverwrite(u))D.push(u)}for(let F of this.subdirectories.values()){let u=await F.wouldOverwrite();D.push(...u)}if(this.indexBuilder){let F=`${this.config.path}/index.ts`;if(await this.config.fileManager.wouldOverwrite(F))D.push(F)}return D}getPath(){return this.config.path}getFiles(){return new Map(this.files)}getSubdirectories(){return new Map(this.subdirectories)}getIndexBuilder(){return this.indexBuilder}}var q6={};NF(q6,{IndexBuilder:()=>H6});class H6{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(D){this.config=D}withExports(D,F){for(let u of D)this.exports.set(u,F);return this}withExport(D,F){return this.exports.set(D,F),this}withNamespaces(D){for(let[F,u]of Object.entries(D))this.namespaces.set(F,u);return this}withNamespace(D,F){return this.namespaces.set(D,F),this}withReExports(D){for(let F of D)this.reExports.set(F,F);return this}withReExport(D){return this.reExports.set(D,D),this}withHeader(D){return this.header=D,this}withFooter(D){return this.footer=D,this}groupBy(D){return this.groupingFunction=D,this}sortBy(D){return this.sortFunction=D,this}async autoDiscover(D){return this.config.logger.debug(`Auto-discovering exports in ${this.config.directory}`),this.config.logger.warn("Auto-discovery not yet implemented - manually add exports"),this}async save(){let D=this.generateContent(),F=`${this.config.directory}/index.ts`,u=await this.config.fileManager.writeFile(F,D);return this.config.logger.debug(`Generated index file: ${F}`),u.path}build(){return this.generateContent()}generateContent(){let D=[];if(this.header)D.push(this.header),D.push("");if(this.reExports.size>0){D.push("// Re-exports");for(let u of this.reExports.values())D.push(`export * from './${u}';`);D.push("")}if(this.exports.size>0){if(this.groupingFunction)this.generateGroupedExports(D);else this.generateSimpleExports(D);D.push("")}if(this.namespaces.size>0){D.push("// Namespace exports");let u=Array.from(this.namespaces.entries()).sort();for(let[E,B]of u)D.push(`export * as ${E} from './${B}';`);D.push("")}if(this.footer)D.push(this.footer);return`${D.join(`
10
+ `).replace(/\t/g,this.options.formatting?.useTabs?"\t":" ".repeat(this.options.formatting?.indentSize||2)).trim()}async validateContent(D){if(this.options.validation==="none")return;let F=[],u=(D.match(/\{/g)||[]).length,E=(D.match(/\}/g)||[]).length;if(u!==E)F.push(`Unmatched braces: ${u} open, ${E} close`);let B=(D.match(/\(/g)||[]).length,C=(D.match(/\)/g)||[]).length;if(B!==C)F.push(`Unmatched parentheses: ${B} open, ${C} close`);if(this.config.filename.endsWith(".ts")||this.config.filename.endsWith(".tsx")){if(D.includes("interface")&&!D.match(/interface\s+\w+\s*\{/))F.push("Invalid interface syntax detected")}if(F.length>0&&this.options.validation==="strict")throw new X0(`Content validation failed for ${this.config.filename}: ${F.join(", ")}`,"write",this.config.filename);else if(F.length>0)this.config.logger.warn(`Validation issues in ${this.config.filename}: ${F.join(", ")}`)}getContent(){return this.content}getImports(){return new Map(this.imports)}getExports(){return new Set(this.exports)}}var J6=F1(()=>{I0()});var W6={};_F(W6,{DirectoryBuilder:()=>o2});class o2{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=!1;constructor(D){this.config=D}withSubdirectory(D){let F=`${this.config.path}/${D}`,u=new o2({path:F,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${D}`)});return this.subdirectories.set(D,u),u}withFiles(D){for(let[F,u]of Object.entries(D))this.files.set(F,u);return this}withFile(D,F){return this.files.set(D,F),this}withIndex(D){return this.indexBuilder=D,this}clean(){return this.shouldClean=!0,this}async ensure(){return await this.config.fileManager.ensureDirectory(this.config.path),this}async save(){let D=[];if(this.shouldClean)await this.config.fileManager.cleanDirectory(this.config.path);await this.ensure();let F=Array.from(this.files.entries()).map(async([u,E])=>{try{let B=await E.save();return D.push(B),B}catch(B){throw this.config.logger.error(`Failed to save file ${u}:`,B instanceof Error?B:void 0),B}});await Promise.all(F);for(let[u,E]of this.subdirectories)try{let B=await E.save();D.push(...B)}catch(B){throw this.config.logger.error(`Failed to save subdirectory ${u}:`,B instanceof Error?B:void 0),B}if(this.indexBuilder)try{let u=await this.indexBuilder.save();D.push(u)}catch(u){throw this.config.logger.error("Failed to save index file:",u instanceof Error?u:void 0),u}return this.config.logger.info(`Saved directory ${this.config.path} with ${D.length} files`),D}getFileList(){let D=[];for(let F of this.files.keys())D.push(`${this.config.path}/${F}`);for(let[F,u]of this.subdirectories){let E=u.getFileList();D.push(...E)}if(this.indexBuilder)D.push(`${this.config.path}/index.ts`);return D.sort()}getStats(){let D=this.files.size;for(let F of this.subdirectories.values())D+=F.getStats().totalFiles;if(this.indexBuilder)D+=1;return{fileCount:this.files.size,subdirectoryCount:this.subdirectories.size,hasIndex:!!this.indexBuilder,totalFiles:D}}async wouldOverwrite(){let D=[];for(let F of this.files.keys()){let u=`${this.config.path}/${F}`;if(await this.config.fileManager.wouldOverwrite(u))D.push(u)}for(let F of this.subdirectories.values()){let u=await F.wouldOverwrite();D.push(...u)}if(this.indexBuilder){let F=`${this.config.path}/index.ts`;if(await this.config.fileManager.wouldOverwrite(F))D.push(F)}return D}getPath(){return this.config.path}getFiles(){return new Map(this.files)}getSubdirectories(){return new Map(this.subdirectories)}getIndexBuilder(){return this.indexBuilder}}var G6={};_F(G6,{IndexBuilder:()=>A6});class A6{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(D){this.config=D}withExports(D,F){for(let u of D)this.exports.set(u,F);return this}withExport(D,F){return this.exports.set(D,F),this}withNamespaces(D){for(let[F,u]of Object.entries(D))this.namespaces.set(F,u);return this}withNamespace(D,F){return this.namespaces.set(D,F),this}withReExports(D){for(let F of D)this.reExports.set(F,F);return this}withReExport(D){return this.reExports.set(D,D),this}withHeader(D){return this.header=D,this}withFooter(D){return this.footer=D,this}groupBy(D){return this.groupingFunction=D,this}sortBy(D){return this.sortFunction=D,this}async autoDiscover(D){return this.config.logger.debug(`Auto-discovering exports in ${this.config.directory}`),this.config.logger.warn("Auto-discovery not yet implemented - manually add exports"),this}async save(){let D=this.generateContent(),F=`${this.config.directory}/index.ts`,u=await this.config.fileManager.writeFile(F,D);return this.config.logger.debug(`Generated index file: ${F}`),u.path}build(){return this.generateContent()}generateContent(){let D=[];if(this.header)D.push(this.header),D.push("");if(this.reExports.size>0){D.push("// Re-exports");for(let u of this.reExports.values())D.push(`export * from './${u}';`);D.push("")}if(this.exports.size>0){if(this.groupingFunction)this.generateGroupedExports(D);else this.generateSimpleExports(D);D.push("")}if(this.namespaces.size>0){D.push("// Namespace exports");let u=Array.from(this.namespaces.entries()).sort();for(let[E,B]of u)D.push(`export * as ${E} from './${B}';`);D.push("")}if(this.footer)D.push(this.footer);return`${D.join(`
11
11
  `).replace(/\n{3,}/g,`
12
12
 
13
13
  `).trim()}
14
- `}generateSimpleExports(D){D.push("// Exports");let F=Array.from(this.exports.entries());if(this.sortFunction)F=F.sort(this.sortFunction);else F=F.sort(([E],[B])=>E.localeCompare(B));let u=new Map;for(let[E,B]of F){if(!u.has(B))u.set(B,[]);u.get(B)?.push(E)}for(let[E,B]of u){let C=B.sort();if(C.length===1)D.push(`export type { ${C[0]} } from './${E}';`);else if(C.length<=3)D.push(`export type { ${C.join(", ")} } from './${E}';`);else D.push("export type {"),C.forEach(($,X)=>{let Q=X===C.length-1;D.push(` ${$}${Q?"":","}`)}),D.push(`} from './${E}';`)}}generateGroupedExports(D){if(!this.groupingFunction)return;let F=new Map;for(let[E,B]of this.exports){let C=this.groupingFunction(E);if(!F.has(C))F.set(C,new Map);let $=F.get(C);if(!$.has(B))$.set(B,[]);$.get(B)?.push(E)}let u=Array.from(F.entries()).sort();for(let[E,B]of u){D.push(`// ${E}`);for(let[C,$]of B){let X=$.sort();if(X.length===1)D.push(`export type { ${X[0]} } from './${C}';`);else D.push(`export type { ${X.join(", ")} } from './${C}';`)}D.push("")}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}}import{notStrictEqual as J8,strictEqual as W8}from"assert";var x6={right:v6,center:k6};class z1{constructor(D){var F;this.width=D.width,this.wrap=(F=D.wrap)!==null&&F!==void 0?F:!0,this.rows=[]}span(...D){let F=this.div(...D);F.span=!0}resetOutput(){this.rows=[]}div(...D){if(D.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...D)&&typeof D[0]==="string")return this.applyLayoutDSL(D[0]);let F=D.map((u)=>{if(typeof u==="string")return this.colFromString(u);return u});return this.rows.push(F),F}shouldApplyLayoutDSL(...D){return D.length===1&&typeof D[0]==="string"&&/[\t\n]/.test(D[0])}applyLayoutDSL(D){let F=D.split(`
14
+ `}generateSimpleExports(D){D.push("// Exports");let F=Array.from(this.exports.entries());if(this.sortFunction)F=F.sort(this.sortFunction);else F=F.sort(([E],[B])=>E.localeCompare(B));let u=new Map;for(let[E,B]of F){if(!u.has(B))u.set(B,[]);u.get(B)?.push(E)}for(let[E,B]of u){let C=B.sort();if(C.length===1)D.push(`export type { ${C[0]} } from './${E}';`);else if(C.length<=3)D.push(`export type { ${C.join(", ")} } from './${E}';`);else D.push("export type {"),C.forEach(($,X)=>{let Q=X===C.length-1;D.push(` ${$}${Q?"":","}`)}),D.push(`} from './${E}';`)}}generateGroupedExports(D){if(!this.groupingFunction)return;let F=new Map;for(let[E,B]of this.exports){let C=this.groupingFunction(E);if(!F.has(C))F.set(C,new Map);let $=F.get(C);if(!$.has(B))$.set(B,[]);$.get(B)?.push(E)}let u=Array.from(F.entries()).sort();for(let[E,B]of u){D.push(`// ${E}`);for(let[C,$]of B){let X=$.sort();if(X.length===1)D.push(`export type { ${X[0]} } from './${C}';`);else D.push(`export type { ${X.join(", ")} } from './${C}';`)}D.push("")}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}}import{notStrictEqual as O8,strictEqual as Y8}from"assert";var I6={right:P6,center:S6};class E1{constructor(D){var F;this.width=D.width,this.wrap=(F=D.wrap)!==null&&F!==void 0?F:!0,this.rows=[]}span(...D){let F=this.div(...D);F.span=!0}resetOutput(){this.rows=[]}div(...D){if(D.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...D)&&typeof D[0]==="string")return this.applyLayoutDSL(D[0]);let F=D.map((u)=>{if(typeof u==="string")return this.colFromString(u);return u});return this.rows.push(F),F}shouldApplyLayoutDSL(...D){return D.length===1&&typeof D[0]==="string"&&/[\t\n]/.test(D[0])}applyLayoutDSL(D){let F=D.split(`
15
15
  `).map((E)=>E.split("\t")),u=0;return F.forEach((E)=>{if(E.length>1&&WD.stringWidth(E[0])>u)u=Math.min(Math.floor(this.width*0.5),WD.stringWidth(E[0]))}),F.forEach((E)=>{this.div(...E.map((B,C)=>{return{text:B.trim(),padding:this.measurePadding(B),width:C===0&&E.length>1?u:void 0}}))}),this.rows[this.rows.length-1]}colFromString(D){return{text:D,padding:this.measurePadding(D)}}measurePadding(D){let F=WD.stripAnsi(D);return[0,F.match(/\s*$/)[0].length,0,F.match(/^\s*/)[0].length]}toString(){let D=[];return this.rows.forEach((F)=>{this.rowToString(F,D)}),D.filter((F)=>!F.hidden).map((F)=>F.text).join(`
16
- `)}rowToString(D,F){return this.rasterize(D).forEach((u,E)=>{let B="";u.forEach((C,$)=>{let{width:X}=D[$],Q=this.negatePadding(D[$]),z=C;if(Q>WD.stringWidth(C))z+=" ".repeat(Q-WD.stringWidth(C));if(D[$].align&&D[$].align!=="left"&&this.wrap){let W=x6[D[$].align];if(z=W(z,Q),WD.stringWidth(z)<Q)z+=" ".repeat((X||0)-WD.stringWidth(z)-1)}let Y=D[$].padding||[0,0,0,0];if(Y[3])B+=" ".repeat(Y[3]);if(B+=Q1(D[$],z,"| "),B+=z,B+=Q1(D[$],z," |"),Y[1])B+=" ".repeat(Y[1]);if(E===0&&F.length>0)B=this.renderInline(B,F[F.length-1])}),F.push({text:B.replace(/ +$/,""),span:D.span})}),F}renderInline(D,F){let u=D.match(/^ */),E=u?u[0].length:0,B=F.text,C=WD.stringWidth(B.trimRight());if(!F.span)return D;if(!this.wrap)return F.hidden=!0,B+D;if(E<C)return D;return F.hidden=!0,B.trimRight()+" ".repeat(E-C)+D.trimLeft()}rasterize(D){let F=[],u=this.columnWidths(D),E;return D.forEach((B,C)=>{if(B.width=u[C],this.wrap)E=WD.wrap(B.text,this.negatePadding(B),{hard:!0}).split(`
16
+ `)}rowToString(D,F){return this.rasterize(D).forEach((u,E)=>{let B="";u.forEach((C,$)=>{let{width:X}=D[$],Q=this.negatePadding(D[$]),z=C;if(Q>WD.stringWidth(C))z+=" ".repeat(Q-WD.stringWidth(C));if(D[$].align&&D[$].align!=="left"&&this.wrap){let W=I6[D[$].align];if(z=W(z,Q),WD.stringWidth(z)<Q)z+=" ".repeat((X||0)-WD.stringWidth(z)-1)}let Y=D[$].padding||[0,0,0,0];if(Y[3])B+=" ".repeat(Y[3]);if(B+=u1(D[$],z,"| "),B+=z,B+=u1(D[$],z," |"),Y[1])B+=" ".repeat(Y[1]);if(E===0&&F.length>0)B=this.renderInline(B,F[F.length-1])}),F.push({text:B.replace(/ +$/,""),span:D.span})}),F}renderInline(D,F){let u=D.match(/^ */),E=u?u[0].length:0,B=F.text,C=WD.stringWidth(B.trimRight());if(!F.span)return D;if(!this.wrap)return F.hidden=!0,B+D;if(E<C)return D;return F.hidden=!0,B.trimRight()+" ".repeat(E-C)+D.trimLeft()}rasterize(D){let F=[],u=this.columnWidths(D),E;return D.forEach((B,C)=>{if(B.width=u[C],this.wrap)E=WD.wrap(B.text,this.negatePadding(B),{hard:!0}).split(`
17
17
  `);else E=B.text.split(`
18
- `);if(B.border)E.unshift("."+"-".repeat(this.negatePadding(B)+2)+"."),E.push("'"+"-".repeat(this.negatePadding(B)+2)+"'");if(B.padding)E.unshift(...new Array(B.padding[0]||0).fill("")),E.push(...new Array(B.padding[2]||0).fill(""));E.forEach(($,X)=>{if(!F[X])F.push([]);let Q=F[X];for(let z=0;z<C;z++)if(Q[z]===void 0)Q.push("");Q.push($)})}),F}negatePadding(D){let F=D.width||0;if(D.padding)F-=(D.padding[3]||0)+(D.padding[1]||0);if(D.border)F-=4;return F}columnWidths(D){if(!this.wrap)return D.map((C)=>{return C.width||WD.stringWidth(C.text)});let F=D.length,u=this.width,E=D.map((C)=>{if(C.width)return F--,u-=C.width,C.width;return}),B=F?Math.floor(u/F):0;return E.map((C,$)=>{if(C===void 0)return Math.max(B,P6(D[$]));return C})}}function Q1(D,F,u){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return u;return" "}return""}function P6(D){let F=D.padding||[],u=1+(F[3]||0)+(F[1]||0);if(D.border)return u+4;return u}function S6(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function v6(D,F){D=D.trim();let u=WD.stringWidth(D);if(u<F)return" ".repeat(F-u)+D;return D}function k6(D,F){D=D.trim();let u=WD.stringWidth(D);if(u>=F)return D;return" ".repeat(F-u>>1)+D}var WD;function O1(D,F){return WD=F,new z1({width:(D===null||D===void 0?void 0:D.width)||S6(),wrap:D===null||D===void 0?void 0:D.wrap})}function wF({onlyFirst:D=!1}={}){let u=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(u,D?void 0:"g")}var f6=wF();function lD(D){if(typeof D!=="string")throw new TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(f6,"")}function Y1(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function J1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function W1(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function y6(D){if(!Number.isSafeInteger(D))throw new TypeError(`Expected a code point, got \`${typeof D}\`.`)}function A1(D,{ambiguousAsWide:F=!1}={}){if(y6(D),J1(D)||W1(D)||F&&Y1(D))return 2;return 1}var q1=S0(H1(),1),d6=new Intl.Segmenter,h6=/^\p{Default_Ignorable_Code_Point}$/u;function RD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:u=!0,countAnsiEscapeCodes:E=!1}=F;if(!E)D=lD(D);if(D.length===0)return 0;let B=0,C={ambiguousAsWide:!u};for(let{segment:$}of d6.segment(D)){let X=$.codePointAt(0);if(X<=31||X>=127&&X<=159)continue;if(X>=8203&&X<=8207||X===65279)continue;if(X>=768&&X<=879||X>=6832&&X<=6911||X>=7616&&X<=7679||X>=8400&&X<=8447||X>=65056&&X<=65071)continue;if(X>=55296&&X<=57343)continue;if(X>=65024&&X<=65039)continue;if(h6.test($))continue;if(q1.default().test($)){B+=2;continue}B+=A1(X,C)}return B}var M1=(D=0)=>(F)=>`\x1B[${F+D}m`,_1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,K1=(D=0)=>(F,u,E)=>`\x1B[${38+D};2;${F};${u};${E}m`,r={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},OE=Object.keys(r.modifier),p6=Object.keys(r.color),g6=Object.keys(r.bgColor),YE=[...p6,...g6];function m6(){let D=new Map;for(let[F,u]of Object.entries(r)){for(let[E,B]of Object.entries(u))r[E]={open:`\x1B[${B[0]}m`,close:`\x1B[${B[1]}m`},u[E]=r[E],D.set(B[0],B[1]);Object.defineProperty(r,F,{value:u,enumerable:!1})}return Object.defineProperty(r,"codes",{value:D,enumerable:!1}),r.color.close="\x1B[39m",r.bgColor.close="\x1B[49m",r.color.ansi=M1(),r.color.ansi256=_1(),r.color.ansi16m=K1(),r.bgColor.ansi=M1(10),r.bgColor.ansi256=_1(10),r.bgColor.ansi16m=K1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,u,E)=>{if(F===u&&u===E){if(F<8)return 16;if(F>248)return 231;return Math.round((F-8)/247*24)+232}return 16+36*Math.round(F/255*5)+6*Math.round(u/255*5)+Math.round(E/255*5)},enumerable:!1},hexToRgb:{value:(F)=>{let u=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!u)return[0,0,0];let[E]=u;if(E.length===3)E=[...E].map((C)=>C+C).join("");let B=Number.parseInt(E,16);return[B>>16&255,B>>8&255,B&255]},enumerable:!1},hexToAnsi256:{value:(F)=>r.rgbToAnsi256(...r.hexToRgb(F)),enumerable:!1},ansi256ToAnsi:{value:(F)=>{if(F<8)return 30+F;if(F<16)return 90+(F-8);let u,E,B;if(F>=232)u=((F-232)*10+8)/255,E=u,B=u;else{F-=16;let X=F%36;u=Math.floor(F/36)/5,E=Math.floor(X/6)/5,B=X%6/5}let C=Math.max(u,E,B)*2;if(C===0)return 30;let $=30+(Math.round(B)<<2|Math.round(E)<<1|Math.round(u));if(C===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,u,E)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,u,E)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var l6=m6(),V1=l6;var k0=new Set(["\x1B","›"]),c6=39,IF="\x07",L1="[",o6="]",N1="m",v0=`${o6}8;;`,R1=(D)=>`${k0.values().next().value}${L1}${D}${N1}`,U1=(D)=>`${k0.values().next().value}${v0}${D}${IF}`,n6=(D)=>D.split(" ").map((F)=>RD(F)),TF=(D,F,u)=>{let E=[...F],B=!1,C=!1,$=RD(lD(D.at(-1)));for(let[X,Q]of E.entries()){let z=RD(Q);if($+z<=u)D[D.length-1]+=Q;else D.push(Q),$=0;if(k0.has(Q))B=!0,C=E.slice(X+1,X+1+v0.length).join("")===v0;if(B){if(C){if(Q===IF)B=!1,C=!1}else if(Q===N1)B=!1;continue}if($+=z,$===u&&X<E.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},i6=(D)=>{let F=D.split(" "),u=F.length;while(u>0){if(RD(F[u-1])>0)break;u--}if(u===F.length)return D;return F.slice(0,u).join(" ")+F.slice(u).join("")},t6=(D,F,u={})=>{if(u.trim!==!1&&D.trim()==="")return"";let E="",B,C,$=n6(D),X=[""];for(let[W,J]of D.split(" ").entries()){if(u.trim!==!1)X[X.length-1]=X.at(-1).trimStart();let q=RD(X.at(-1));if(W!==0){if(q>=F&&(u.wordWrap===!1||u.trim===!1))X.push(""),q=0;if(q>0||u.trim===!1)X[X.length-1]+=" ",q++}if(u.hard&&$[W]>F){let M=F-q,G=1+Math.floor(($[W]-M-1)/F);if(Math.floor(($[W]-1)/F)<G)X.push("");TF(X,J,F);continue}if(q+$[W]>F&&q>0&&$[W]>0){if(u.wordWrap===!1&&q<F){TF(X,J,F);continue}X.push("")}if(q+$[W]>F&&u.wordWrap===!1){TF(X,J,F);continue}X[X.length-1]+=J}if(u.trim!==!1)X=X.map((W)=>i6(W));let Q=X.join(`
19
- `),z=[...Q],Y=0;for(let[W,J]of z.entries()){if(E+=J,k0.has(J)){let{groups:M}=new RegExp(`(?:\\${L1}(?<code>\\d+)m|\\${v0}(?<uri>.*)${IF})`).exec(Q.slice(Y))||{groups:{}};if(M.code!==void 0){let G=Number.parseFloat(M.code);B=G===c6?void 0:G}else if(M.uri!==void 0)C=M.uri.length===0?void 0:M.uri}let q=V1.codes.get(Number(B));if(z[W+1]===`
20
- `){if(C)E+=U1("");if(B&&q)E+=R1(q)}else if(J===`
21
- `){if(B&&q)E+=R1(B);if(C)E+=U1(C)}Y+=J.length}return E};function bF(D,F,u){return String(D).normalize().replaceAll(`\r
18
+ `);if(B.border)E.unshift("."+"-".repeat(this.negatePadding(B)+2)+"."),E.push("'"+"-".repeat(this.negatePadding(B)+2)+"'");if(B.padding)E.unshift(...Array(B.padding[0]||0).fill("")),E.push(...Array(B.padding[2]||0).fill(""));E.forEach(($,X)=>{if(!F[X])F.push([]);let Q=F[X];for(let z=0;z<C;z++)if(Q[z]===void 0)Q.push("");Q.push($)})}),F}negatePadding(D){let F=D.width||0;if(D.padding)F-=(D.padding[3]||0)+(D.padding[1]||0);if(D.border)F-=4;return F}columnWidths(D){if(!this.wrap)return D.map((C)=>{return C.width||WD.stringWidth(C.text)});let F=D.length,u=this.width,E=D.map((C)=>{if(C.width)return F--,u-=C.width,C.width;return}),B=F?Math.floor(u/F):0;return E.map((C,$)=>{if(C===void 0)return Math.max(B,b6(D[$]));return C})}}function u1(D,F,u){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return u;return" "}return""}function b6(D){let F=D.padding||[],u=1+(F[3]||0)+(F[1]||0);if(D.border)return u+4;return u}function x6(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function P6(D,F){D=D.trim();let u=WD.stringWidth(D);if(u<F)return" ".repeat(F-u)+D;return D}function S6(D,F){D=D.trim();let u=WD.stringWidth(D);if(u>=F)return D;return" ".repeat(F-u>>1)+D}var WD;function B1(D,F){return WD=F,new E1({width:(D===null||D===void 0?void 0:D.width)||x6(),wrap:D===null||D===void 0?void 0:D.wrap})}function VF({onlyFirst:D=!1}={}){let u=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(u,D?void 0:"g")}var v6=VF();function mD(D){if(typeof D!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(v6,"")}function C1(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function $1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function X1(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function f6(D){if(!Number.isSafeInteger(D))throw TypeError(`Expected a code point, got \`${typeof D}\`.`)}function Z1(D,{ambiguousAsWide:F=!1}={}){if(f6(D),$1(D)||X1(D)||F&&C1(D))return 2;return 1}var O1=b0(z1(),1),k6=new Intl.Segmenter,y6=/^\p{Default_Ignorable_Code_Point}$/u;function RD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:u=!0,countAnsiEscapeCodes:E=!1}=F;if(!E)D=mD(D);if(D.length===0)return 0;let B=0,C={ambiguousAsWide:!u};for(let{segment:$}of k6.segment(D)){let X=$.codePointAt(0);if(X<=31||X>=127&&X<=159)continue;if(X>=8203&&X<=8207||X===65279)continue;if(X>=768&&X<=879||X>=6832&&X<=6911||X>=7616&&X<=7679||X>=8400&&X<=8447||X>=65056&&X<=65071)continue;if(X>=55296&&X<=57343)continue;if(X>=65024&&X<=65039)continue;if(y6.test($))continue;if(O1.default().test($)){B+=2;continue}B+=Z1(X,C)}return B}var Y1=(D=0)=>(F)=>`\x1B[${F+D}m`,J1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,W1=(D=0)=>(F,u,E)=>`\x1B[${38+D};2;${F};${u};${E}m`,r={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},OE=Object.keys(r.modifier),h6=Object.keys(r.color),d6=Object.keys(r.bgColor),YE=[...h6,...d6];function p6(){let D=new Map;for(let[F,u]of Object.entries(r)){for(let[E,B]of Object.entries(u))r[E]={open:`\x1B[${B[0]}m`,close:`\x1B[${B[1]}m`},u[E]=r[E],D.set(B[0],B[1]);Object.defineProperty(r,F,{value:u,enumerable:!1})}return Object.defineProperty(r,"codes",{value:D,enumerable:!1}),r.color.close="\x1B[39m",r.bgColor.close="\x1B[49m",r.color.ansi=Y1(),r.color.ansi256=J1(),r.color.ansi16m=W1(),r.bgColor.ansi=Y1(10),r.bgColor.ansi256=J1(10),r.bgColor.ansi16m=W1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,u,E)=>{if(F===u&&u===E){if(F<8)return 16;if(F>248)return 231;return Math.round((F-8)/247*24)+232}return 16+36*Math.round(F/255*5)+6*Math.round(u/255*5)+Math.round(E/255*5)},enumerable:!1},hexToRgb:{value:(F)=>{let u=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!u)return[0,0,0];let[E]=u;if(E.length===3)E=[...E].map((C)=>C+C).join("");let B=Number.parseInt(E,16);return[B>>16&255,B>>8&255,B&255]},enumerable:!1},hexToAnsi256:{value:(F)=>r.rgbToAnsi256(...r.hexToRgb(F)),enumerable:!1},ansi256ToAnsi:{value:(F)=>{if(F<8)return 30+F;if(F<16)return 90+(F-8);let u,E,B;if(F>=232)u=((F-232)*10+8)/255,E=u,B=u;else{F-=16;let X=F%36;u=Math.floor(F/36)/5,E=Math.floor(X/6)/5,B=X%6/5}let C=Math.max(u,E,B)*2;if(C===0)return 30;let $=30+(Math.round(B)<<2|Math.round(E)<<1|Math.round(u));if(C===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,u,E)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,u,E)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var g6=p6(),A1=g6;var P0=new Set(["\x1B","›"]),m6=39,UF="\x07",M1="[",l6="]",q1="m",x0=`${l6}8;;`,G1=(D)=>`${P0.values().next().value}${M1}${D}${q1}`,H1=(D)=>`${P0.values().next().value}${x0}${D}${UF}`,c6=(D)=>D.split(" ").map((F)=>RD(F)),RF=(D,F,u)=>{let E=[...F],B=!1,C=!1,$=RD(mD(D.at(-1)));for(let[X,Q]of E.entries()){let z=RD(Q);if($+z<=u)D[D.length-1]+=Q;else D.push(Q),$=0;if(P0.has(Q))B=!0,C=E.slice(X+1,X+1+x0.length).join("")===x0;if(B){if(C){if(Q===UF)B=!1,C=!1}else if(Q===q1)B=!1;continue}if($+=z,$===u&&X<E.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},o6=(D)=>{let F=D.split(" "),u=F.length;while(u>0){if(RD(F[u-1])>0)break;u--}if(u===F.length)return D;return F.slice(0,u).join(" ")+F.slice(u).join("")},n6=(D,F,u={})=>{if(u.trim!==!1&&D.trim()==="")return"";let E="",B,C,$=c6(D),X=[""];for(let[W,J]of D.split(" ").entries()){if(u.trim!==!1)X[X.length-1]=X.at(-1).trimStart();let M=RD(X.at(-1));if(W!==0){if(M>=F&&(u.wordWrap===!1||u.trim===!1))X.push(""),M=0;if(M>0||u.trim===!1)X[X.length-1]+=" ",M++}if(u.hard&&$[W]>F){let q=F-M,G=1+Math.floor(($[W]-q-1)/F);if(Math.floor(($[W]-1)/F)<G)X.push("");RF(X,J,F);continue}if(M+$[W]>F&&M>0&&$[W]>0){if(u.wordWrap===!1&&M<F){RF(X,J,F);continue}X.push("")}if(M+$[W]>F&&u.wordWrap===!1){RF(X,J,F);continue}X[X.length-1]+=J}if(u.trim!==!1)X=X.map((W)=>o6(W));let Q=X.join(`
19
+ `),z=[...Q],Y=0;for(let[W,J]of z.entries()){if(E+=J,P0.has(J)){let{groups:q}=new RegExp(`(?:\\${M1}(?<code>\\d+)m|\\${x0}(?<uri>.*)${UF})`).exec(Q.slice(Y))||{groups:{}};if(q.code!==void 0){let G=Number.parseFloat(q.code);B=G===m6?void 0:G}else if(q.uri!==void 0)C=q.uri.length===0?void 0:q.uri}let M=A1.codes.get(Number(B));if(z[W+1]===`
20
+ `){if(C)E+=H1("");if(B&&M)E+=G1(M)}else if(J===`
21
+ `){if(B&&M)E+=G1(B);if(C)E+=H1(C)}Y+=J.length}return E};function LF(D,F,u){return String(D).normalize().replaceAll(`\r
22
22
  `,`
23
23
  `).split(`
24
- `).map((E)=>t6(E,F,u)).join(`
25
- `)}function xF(D){return O1(D,{stringWidth:RD,stripAnsi:lD,wrap:bF})}import{dirname as j1,resolve as w1}from"path";import{readdirSync as s6,statSync as r6}from"fs";function PF(D,F){let u=w1(".",D),E;if(!r6(u).isDirectory())u=j1(u);while(!0){if(E=F(u,s6(u)),E)return w1(u,E);if(u=j1(E=u),E===u)break}}import{inspect as A8}from"util";import{fileURLToPath as c1}from"url";import{format as D8}from"util";import{normalize as F8,resolve as u8}from"path";function cD(D){if(!(D!==D.toLowerCase()&&D!==D.toUpperCase()))D=D.toLowerCase();if(D.indexOf("-")===-1&&D.indexOf("_")===-1)return D;else{let u="",E=!1,B=D.match(/^-+/);for(let C=B?B[0].length:0;C<D.length;C++){let $=D.charAt(C);if(E)E=!1,$=$.toUpperCase();if(C!==0&&($==="-"||$==="_"))E=!0;else if($!=="-"&&$!=="_")u+=$}return u}}function f0(D,F){let u=D.toLowerCase();F=F||"-";let E="";for(let B=0;B<D.length;B++){let C=u.charAt(B),$=D.charAt(B);if(C!==$&&B>0)E+=`${F}${u.charAt(B)}`;else E+=$}return E}function y0(D){if(D===null||D===void 0)return!1;if(typeof D==="number")return!0;if(/^0x[0-9a-f]+$/i.test(D))return!0;if(/^0[^.]/.test(D))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(D)}function T1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,u=null,E=null,B=null,C=[];for(let $=0;$<D.length;$++){if(u=E,E=D.charAt($),E===" "&&!B){if(u!==" ")F++;continue}if(E===B)B=null;else if((E==="'"||E==='"')&&!B)B=E;if(!C[F])C[F]="";C[F]+=E}return C}var qD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(qD||(qD={}));var bD;class vF{constructor(D){bD=D}parse(D,F){let u=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},F),E=T1(D),B=typeof D==="string",C=a6(Object.assign(Object.create(null),u.alias)),$=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},u.configuration),X=Object.assign(Object.create(null),u.default),Q=u.configObjects||[],z=u.envPrefix,Y=$["populate--"],W=Y?"--":"_",J=Object.create(null),q=Object.create(null),M=u.__||bD.format,G={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},T=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,p=new RegExp("^--"+$["negation-prefix"]+"(.+)");if([].concat(u.array||[]).filter(Boolean).forEach(function(O){let H=typeof O==="object"?O.key:O,K=Object.keys(O).map(function(_){return{boolean:"bools",string:"strings",number:"numbers"}[_]}).filter(Boolean).pop();if(K)G[K][H]=!0;G.arrays[H]=!0,G.keys.push(H)}),[].concat(u.boolean||[]).filter(Boolean).forEach(function(O){G.bools[O]=!0,G.keys.push(O)}),[].concat(u.string||[]).filter(Boolean).forEach(function(O){G.strings[O]=!0,G.keys.push(O)}),[].concat(u.number||[]).filter(Boolean).forEach(function(O){G.numbers[O]=!0,G.keys.push(O)}),[].concat(u.count||[]).filter(Boolean).forEach(function(O){G.counts[O]=!0,G.keys.push(O)}),[].concat(u.normalize||[]).filter(Boolean).forEach(function(O){G.normalize[O]=!0,G.keys.push(O)}),typeof u.narg==="object")Object.entries(u.narg).forEach(([O,H])=>{if(typeof H==="number")G.nargs[O]=H,G.keys.push(O)});if(typeof u.coerce==="object")Object.entries(u.coerce).forEach(([O,H])=>{if(typeof H==="function")G.coercions[O]=H,G.keys.push(O)});if(typeof u.config!=="undefined"){if(Array.isArray(u.config)||typeof u.config==="string")[].concat(u.config).filter(Boolean).forEach(function(O){G.configs[O]=!0});else if(typeof u.config==="object")Object.entries(u.config).forEach(([O,H])=>{if(typeof H==="boolean"||typeof H==="function")G.configs[O]=H})}K0(u.key,C,u.default,G.arrays),Object.keys(X).forEach(function(O){(G.aliases[O]||[]).forEach(function(H){X[H]=X[O]})});let g=null;RF();let QD=[],V=Object.assign(Object.create(null),{_:[]}),L={};for(let O=0;O<E.length;O++){let H=E[O],K=H.replace(/^-{3,}/,"---"),_,A,I,U,P,XD;if(H!=="--"&&/^-/.test(H)&&n(H))k(H);else if(K.match(/^---+(=|$)/)){k(H);continue}else if(H.match(/^--.+=/)||!$["short-option-groups"]&&H.match(/^-.+=/)){if(U=H.match(/^--?([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)if(S(U[1],G.arrays))O=t(O,U[1],E,U[2]);else if(S(U[1],G.nargs)!==!1)O=d(O,U[1],E,U[2]);else l(U[1],U[2],!0)}else if(H.match(p)&&$["boolean-negation"]){if(U=H.match(p),U!==null&&Array.isArray(U)&&U.length>=2)A=U[1],l(A,S(A,G.arrays)?[!1]:!1)}else if(H.match(/^--.+/)||!$["short-option-groups"]&&H.match(/^-[^-]+/)){if(U=H.match(/^--?(.+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],S(A,G.arrays))O=t(O,A,E);else if(S(A,G.nargs)!==!1)O=d(O,A,E);else if(P=E[O+1],P!==void 0&&(!P.match(/^-/)||P.match(T))&&!S(A,G.bools)&&!S(A,G.counts))l(A,P),O++;else if(/^(true|false)$/.test(P))l(A,P),O++;else l(A,m(A))}else if(H.match(/^-.\..+=/)){if(U=H.match(/^-([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)l(U[1],U[2])}else if(H.match(/^-.\..+/)&&!H.match(T)){if(P=E[O+1],U=H.match(/^-(.\..+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],P!==void 0&&!P.match(/^-/)&&!S(A,G.bools)&&!S(A,G.counts))l(A,P),O++;else l(A,m(A))}else if(H.match(/^-[^-]+/)&&!H.match(T)){I=H.slice(1,-1).split(""),_=!1;for(let OD=0;OD<I.length;OD++){if(P=H.slice(OD+2),I[OD+1]&&I[OD+1]==="="){if(XD=H.slice(OD+3),A=I[OD],S(A,G.arrays))O=t(O,A,E,XD);else if(S(A,G.nargs)!==!1)O=d(O,A,E,XD);else l(A,XD);_=!0;break}if(P==="-"){l(I[OD],P);continue}if(/[A-Za-z]/.test(I[OD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)&&S(P,G.bools)===!1){l(I[OD],P),_=!0;break}if(I[OD+1]&&I[OD+1].match(/\W/)){l(I[OD],P),_=!0;break}else l(I[OD],m(I[OD]))}if(A=H.slice(-1)[0],!_&&A!=="-")if(S(A,G.arrays))O=t(O,A,E);else if(S(A,G.nargs)!==!1)O=d(O,A,E);else if(P=E[O+1],P!==void 0&&(!/^(-|--)[^-]/.test(P)||P.match(T))&&!S(A,G.bools)&&!S(A,G.counts))l(A,P),O++;else if(/^(true|false)$/.test(P))l(A,P),O++;else l(A,m(A))}else if(H.match(/^-[0-9]$/)&&H.match(T)&&S(H.slice(1),G.bools))A=H.slice(1),l(A,m(A));else if(H==="--"){QD=E.slice(O+1);break}else if($["halt-at-non-option"]){QD=E.slice(O);break}else k(H)}if(uD(V,!0),uD(V,!1),b(V),o(),vD(V,G.aliases,X,!0),c(V),$["set-placeholder-key"])ED(V);if(Object.keys(G.counts).forEach(function(O){if(!i(V,O.split(".")))l(O,0)}),Y&&QD.length)V[W]=[];if(QD.forEach(function(O){V[W].push(O)}),$["camel-case-expansion"]&&$["strip-dashed"])Object.keys(V).filter((O)=>O!=="--"&&O.includes("-")).forEach((O)=>{delete V[O]});if($["strip-aliased"])[].concat(...Object.keys(C).map((O)=>C[O])).forEach((O)=>{if($["camel-case-expansion"]&&O.includes("-"))delete V[O.split(".").map((H)=>cD(H)).join(".")];delete V[O]});function k(O){let H=R("_",O);if(typeof H==="string"||typeof H==="number")V._.push(H)}function d(O,H,K,_){let A,I=S(H,G.nargs);if(I=typeof I!=="number"||isNaN(I)?1:I,I===0){if(!CD(_))g=Error(M("Argument unexpected for: %s",H));return l(H,m(H)),O}let U=CD(_)?0:1;if($["nargs-eats-options"]){if(K.length-(O+1)+U<I)g=Error(M("Not enough arguments following: %s",H));U=I}else{for(A=O+1;A<K.length;A++)if(!K[A].match(/^-[^0-9]/)||K[A].match(T)||n(K[A]))U++;else break;if(U<I)g=Error(M("Not enough arguments following: %s",H))}let P=Math.min(U,I);if(!CD(_)&&P>0)l(H,_),P--;for(A=O+1;A<P+O+1;A++)l(H,K[A]);return O+P}function t(O,H,K,_){let A=[],I=_||K[O+1],U=S(H,G.nargs);if(S(H,G.bools)&&!/^(true|false)$/.test(I))A.push(!0);else if(CD(I)||CD(_)&&/^-/.test(I)&&!T.test(I)&&!n(I)){if(X[H]!==void 0){let P=X[H];A=Array.isArray(P)?P:[P]}}else{if(!CD(_))A.push(w(H,_,!0));for(let P=O+1;P<K.length;P++){if(!$["greedy-arrays"]&&A.length>0||U&&typeof U==="number"&&A.length>=U)break;if(I=K[P],/^-/.test(I)&&!T.test(I)&&!n(I))break;O=P,A.push(w(H,I,B))}}if(typeof U==="number"&&(U&&A.length<U||isNaN(U)&&A.length===0))g=Error(M("Not enough arguments following: %s",H));return l(H,A),O}function l(O,H,K=B){if(/-/.test(O)&&$["camel-case-expansion"]){let I=O.split(".").map(function(U){return cD(U)}).join(".");jD(O,I)}let _=w(O,H,K),A=O.split(".");if(ID(V,A,_),G.aliases[O])G.aliases[O].forEach(function(I){let U=I.split(".");ID(V,U,_)});if(A.length>1&&$["dot-notation"])(G.aliases[A[0]]||[]).forEach(function(I){let U=I.split("."),P=[].concat(A);if(P.shift(),U=U.concat(P),!(G.aliases[O]||[]).includes(U.join(".")))ID(V,U,_)});if(S(O,G.normalize)&&!S(O,G.arrays))[O].concat(G.aliases[O]||[]).forEach(function(U){Object.defineProperty(L,U,{enumerable:!0,get(){return H},set(P){H=typeof P==="string"?bD.normalize(P):P}})})}function jD(O,H){if(!(G.aliases[O]&&G.aliases[O].length))G.aliases[O]=[H],J[H]=!0;if(!(G.aliases[H]&&G.aliases[H].length))jD(H,O)}function w(O,H,K){if(K)H=e6(H);if(S(O,G.bools)||S(O,G.counts)){if(typeof H==="string")H=H==="true"}let _=Array.isArray(H)?H.map(function(A){return R(O,A)}):R(O,H);if(S(O,G.counts)&&(CD(_)||typeof _==="boolean"))_=SF();if(S(O,G.normalize)&&S(O,G.arrays))if(Array.isArray(H))_=H.map((A)=>{return bD.normalize(A)});else _=bD.normalize(H);return _}function R(O,H){if(!$["parse-positional-numbers"]&&O==="_")return H;if(!S(O,G.strings)&&!S(O,G.bools)&&!Array.isArray(H)){if(y0(H)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${H}`)))||!CD(H)&&S(O,G.numbers))H=Number(H)}return H}function b(O){let H=Object.create(null);vD(H,G.aliases,X),Object.keys(G.configs).forEach(function(K){let _=O[K]||H[K];if(_)try{let A=null,I=bD.resolve(bD.cwd(),_),U=G.configs[K];if(typeof U==="function"){try{A=U(I)}catch(P){A=P}if(A instanceof Error){g=A;return}}else A=bD.require(I);y(A)}catch(A){if(A.name==="PermissionDenied")g=A;else if(O[K])g=Error(M("Invalid JSON config file: %s",_))}})}function y(O,H){Object.keys(O).forEach(function(K){let _=O[K],A=H?H+"."+K:K;if(typeof _==="object"&&_!==null&&!Array.isArray(_)&&$["dot-notation"])y(_,A);else if(!i(V,A.split("."))||S(A,G.arrays)&&$["combine-arrays"])l(A,_)})}function o(){if(typeof Q!=="undefined")Q.forEach(function(O){y(O)})}function uD(O,H){if(typeof z==="undefined")return;let K=typeof z==="string"?z:"",_=bD.env();Object.keys(_).forEach(function(A){if(K===""||A.lastIndexOf(K,0)===0){let I=A.split("__").map(function(U,P){if(P===0)U=U.substring(K.length);return cD(U)});if((H&&G.configs[I.join(".")]||!H)&&!i(O,I))l(I.join("."),_[A])}})}function c(O){let H,K=new Set;Object.keys(O).forEach(function(_){if(!K.has(_)){if(H=S(_,G.coercions),typeof H==="function")try{let A=R(_,H(O[_]));[].concat(G.aliases[_]||[],_).forEach((I)=>{K.add(I),O[I]=A})}catch(A){g=A}}})}function ED(O){return G.keys.forEach((H)=>{if(~H.indexOf("."))return;if(typeof O[H]==="undefined")O[H]=void 0}),O}function vD(O,H,K,_=!1){Object.keys(K).forEach(function(A){if(!i(O,A.split("."))){if(ID(O,A.split("."),K[A]),_)q[A]=!0;(H[A]||[]).forEach(function(I){if(i(O,I.split(".")))return;ID(O,I.split("."),K[A])})}})}function i(O,H){let K=O;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(A){K=K[A]||{}});let _=H[H.length-1];if(typeof K!=="object")return!1;else return _ in K}function ID(O,H,K){let _=O;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(XD){if(XD=I1(XD),typeof _==="object"&&_[XD]===void 0)_[XD]={};if(typeof _[XD]!=="object"||Array.isArray(_[XD])){if(Array.isArray(_[XD]))_[XD].push({});else _[XD]=[_[XD],{}];_=_[XD][_[XD].length-1]}else _=_[XD]});let A=I1(H[H.length-1]),I=S(H.join("."),G.arrays),U=Array.isArray(K),P=$["duplicate-arguments-array"];if(!P&&S(A,G.nargs)){if(P=!0,!CD(_[A])&&G.nargs[A]===1||Array.isArray(_[A])&&_[A].length===G.nargs[A])_[A]=void 0}if(K===SF())_[A]=SF(_[A]);else if(Array.isArray(_[A]))if(P&&I&&U)_[A]=$["flatten-duplicate-arrays"]?_[A].concat(K):(Array.isArray(_[A][0])?_[A]:[_[A]]).concat([K]);else if(!P&&Boolean(I)===Boolean(U))_[A]=K;else _[A]=_[A].concat([K]);else if(_[A]===void 0&&I)_[A]=U?K:[K];else if(P&&!(_[A]===void 0||S(A,G.counts)||S(A,G.bools)))_[A]=[_[A],K];else _[A]=K}function K0(...O){O.forEach(function(H){Object.keys(H||{}).forEach(function(K){if(G.aliases[K])return;G.aliases[K]=[].concat(C[K]||[]),G.aliases[K].concat(K).forEach(function(_){if(/-/.test(_)&&$["camel-case-expansion"]){let A=cD(_);if(A!==K&&G.aliases[K].indexOf(A)===-1)G.aliases[K].push(A),J[A]=!0}}),G.aliases[K].concat(K).forEach(function(_){if(_.length>1&&/[A-Z]/.test(_)&&$["camel-case-expansion"]){let A=f0(_,"-");if(A!==K&&G.aliases[K].indexOf(A)===-1)G.aliases[K].push(A),J[A]=!0}}),G.aliases[K].forEach(function(_){G.aliases[_]=[K].concat(G.aliases[K].filter(function(A){return _!==A}))})})})}function S(O,H){let K=[].concat(G.aliases[O]||[],O),_=Object.keys(H),A=K.find((I)=>_.includes(I));return A?H[A]:!1}function Q0(O){let H=Object.keys(G);return[].concat(H.map((_)=>G[_])).some(function(_){return Array.isArray(_)?_.includes(O):_[O]})}function B1(O,...H){return[].concat(...H).some(function(_){let A=O.match(_);return A&&Q0(A[1])})}function v(O){if(O.match(T)||!O.match(/^-[^-]+/))return!1;let H=!0,K,_=O.slice(1).split("");for(let A=0;A<_.length;A++){if(K=O.slice(A+2),!Q0(_[A])){H=!1;break}if(_[A+1]&&_[A+1]==="="||K==="-"||/[A-Za-z]/.test(_[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(K)||_[A+1]&&_[A+1].match(/\W/))break}return H}function n(O){return $["unknown-options-as-args"]&&BD(O)}function BD(O){if(O=O.replace(/^-{3,}/,"--"),O.match(T))return!1;if(v(O))return!1;return!B1(O,/^-+([^=]+?)=[\s\S]*$/,p,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function m(O){if(!S(O,G.bools)&&!S(O,G.counts)&&`${O}`in X)return X[O];else return zD(e(O))}function zD(O){return{[qD.BOOLEAN]:!0,[qD.STRING]:"",[qD.NUMBER]:void 0,[qD.ARRAY]:[]}[O]}function e(O){let H=qD.BOOLEAN;if(S(O,G.strings))H=qD.STRING;else if(S(O,G.numbers))H=qD.NUMBER;else if(S(O,G.bools))H=qD.BOOLEAN;else if(S(O,G.arrays))H=qD.ARRAY;return H}function CD(O){return O===void 0}function RF(){Object.keys(G.counts).find((O)=>{if(S(O,G.arrays))return g=Error(M("Invalid configuration: %s, opts.count excludes opts.array.",O)),!0;else if(S(O,G.nargs))return g=Error(M("Invalid configuration: %s, opts.count excludes opts.narg.",O)),!0;return!1})}return{aliases:Object.assign({},G.aliases),argv:Object.assign(L,V),configuration:$,defaulted:Object.assign({},q),error:g,newAliases:Object.assign({},J)}}}function a6(D){let F=[],u=Object.create(null),E=!0;Object.keys(D).forEach(function(B){F.push([].concat(D[B],B))});while(E){E=!1;for(let B=0;B<F.length;B++)for(let C=B+1;C<F.length;C++)if(F[B].filter(function(X){return F[C].indexOf(X)!==-1}).length){F[B]=F[B].concat(F[C]),F.splice(C,1),E=!0;break}}return F.forEach(function(B){B=B.filter(function($,X,Q){return Q.indexOf($)===X});let C=B.pop();if(C!==void 0&&typeof C==="string")u[C]=B}),u}function SF(D){return D!==void 0?D+1:1}function I1(D){if(D==="__proto__")return"___proto___";return D}function e6(D){return typeof D==="string"&&(D[0]==="'"||D[0]==='"')&&D[D.length-1]===D[0]?D.substring(1,D.length-1):D}import{readFileSync as E8}from"fs";import{createRequire as b1}from"node:module";var kF,fF,yF,x1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,P1=(fF=(kF=process===null||process===void 0?void 0:process.versions)===null||kF===void 0?void 0:kF.node)!==null&&fF!==void 0?fF:(yF=process===null||process===void 0?void 0:process.version)===null||yF===void 0?void 0:yF.slice(1);if(P1){if(Number(P1.match(/^([^.]+)/)[1])<x1)throw Error(`yargs parser supports a minimum Node.js version of ${x1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var B8=process?process.env:{},S1=b1?b1(import.meta.url):void 0,v1=new vF({cwd:process.cwd,env:()=>{return B8},format:D8,normalize:F8,resolve:u8,require:(D)=>{if(typeof S1!=="undefined")return S1(D);else if(D.match(/\.json$/))return JSON.parse(E8(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),R0=function D(F,u){return v1.parse(F.slice(),u).argv};R0.detailed=function(D,F){return v1.parse(D.slice(),F)};R0.camelCase=cD;R0.decamelize=f0;R0.looksLikeNumber=y0;var dF=R0;import{basename as G8,dirname as H8,extname as q8,relative as M8,resolve as l1,join as _8}from"path";function k1(){if(C8())return 0;return 1}function C8(){return $8()&&!process.defaultApp}function $8(){return!!process.versions.electron}function hF(D){return D.slice(k1()+1)}function f1(){return process.argv[k1()]}import{readFileSync as X8,statSync as Z8,writeFile as Q8}from"fs";import{format as z8}from"util";import{resolve as O8}from"path";var y1={fs:{readFileSync:X8,writeFile:Q8},format:z8,resolve:O8,exists:(D)=>{try{return Z8(D).isFile()}catch(F){return!1}}};var UD;class d1{constructor(D){D=D||{},this.directory=D.directory||"./locales",this.updateFiles=typeof D.updateFiles==="boolean"?D.updateFiles:!0,this.locale=D.locale||"en",this.fallbackToLanguage=typeof D.fallbackToLanguage==="boolean"?D.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...D){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let F=D.shift(),u=function(){};if(typeof D[D.length-1]==="function")u=D.pop();if(u=u||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][F]&&this.updateFiles)this.cache[this.locale][F]=F,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:u});else u();return UD.format.apply(UD.format,[this.cache[this.locale][F]||F].concat(D))}__n(){let D=Array.prototype.slice.call(arguments),F=D.shift(),u=D.shift(),E=D.shift(),B=function(){};if(typeof D[D.length-1]==="function")B=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let C=E===1?F:u;if(this.cache[this.locale][F])C=this.cache[this.locale][F][E===1?"one":"other"];if(!this.cache[this.locale][F]&&this.updateFiles)this.cache[this.locale][F]={one:F,other:u},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:B});else B();let $=[C];if(~C.indexOf("%d"))$.push(E);return UD.format.apply(UD.format,$.concat(D))}setLocale(D){this.locale=D}getLocale(){return this.locale}updateLocale(D){if(!this.cache[this.locale])this._readLocaleFile();for(let F in D)if(Object.prototype.hasOwnProperty.call(D,F))this.cache[this.locale][F]=D[F]}_taggedLiteral(D,...F){let u="";return D.forEach(function(E,B){let C=F[B+1];if(u+=E,typeof C!=="undefined")u+="%s"}),this.__.apply(this,[u].concat([].slice.call(F,1)))}_enqueueWrite(D){if(this.writeQueue.push(D),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let D=this,F=this.writeQueue[0],u=F.directory,E=F.locale,B=F.cb,C=this._resolveLocaleFile(u,E),$=JSON.stringify(this.cache[E],null,2);UD.fs.writeFile(C,$,"utf-8",function(X){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();B(X)})}_readLocaleFile(){let D={},F=this._resolveLocaleFile(this.directory,this.locale);try{if(UD.fs.readFileSync)D=JSON.parse(UD.fs.readFileSync(F,"utf-8"))}catch(u){if(u instanceof SyntaxError)u.message="syntax error in "+F;if(u.code==="ENOENT")D={};else throw u}this.cache[this.locale]=D}_resolveLocaleFile(D,F){let u=UD.resolve(D,"./",F+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(u)&&~F.lastIndexOf("_")){let E=UD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(E))u=E}return u}_fileExistsSync(D){return UD.exists(D)}}function h1(D,F){UD=F;let u=new d1(D);return{__:u.__.bind(u),__n:u.__n.bind(u),setLocale:u.setLocale.bind(u),getLocale:u.getLocale.bind(u),updateLocale:u.updateLocale.bind(u),locale:u.locale}}var Y8=(D)=>{return h1(D,y1)},p1=Y8;var o1=S0(m1(),1);import{createRequire as K8}from"node:module";import{readFileSync as V8,readdirSync as R8}from"node:fs";var pF=c1(import.meta.url),U8=pF.substring(0,pF.lastIndexOf("node_modules")),L8=K8(import.meta.url),gF={assert:{notStrictEqual:J8,strictEqual:W8},cliui:xF,findUp:PF,getEnv:(D)=>{return process.env[D]},inspect:A8,getProcessArgvBin:f1,mainFilename:U8||process.cwd(),Parser:dF,path:{basename:G8,dirname:H8,extname:q8,relative:M8,resolve:l1,join:_8},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(D,F)=>process.emitWarning(D,F),execPath:()=>process.execPath,exit:(D)=>{process.exit(D)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns!=="undefined"?process.stdout.columns:null},readFileSync:V8,readdirSync:R8,require:L8,getCallerFile:()=>{let D=o1.default(3);return D.match(/^file:\/\//)?c1(D):D},stringWidth:RD,y18n:p1({directory:l1(pF,"../../../locales"),updateFiles:!1})};function YD(D,F,u,E){u.assert.notStrictEqual(D,F,E)}function mF(D,F){F.assert.strictEqual(typeof D,"string")}function z0(D){return Object.keys(D)}function s(D){return!!D&&!!D.then&&typeof D.then==="function"}class DD extends Error{constructor(D){super(D||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,DD)}}function kD(D){let u=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),E=/\.*[\][<>]/g,B=u.shift();if(!B)throw new Error(`No command found in: ${D}`);let C={cmd:B.replace(E,""),demanded:[],optional:[]};return u.forEach(($,X)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&X===u.length-1)Q=!0;if(/^\[/.test($))C.optional.push({cmd:$.replace(E,"").split("|"),variadic:Q});else C.demanded.push({cmd:$.replace(E,"").split("|"),variadic:Q})}),C}var N8=["first","second","third","fourth","fifth","sixth"];function N(D,F,u){function E(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[kD(`cmd ${D}`),F,u]}try{let B=0,[C,$,X]=E(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=X||Q.length;if(z<C.demanded.length)throw new DD(`Not enough arguments provided. Expected ${C.demanded.length} but received ${Q.length}.`);let Y=C.demanded.length+C.optional.length;if(z>Y)throw new DD(`Too many arguments provided. Expected max ${Y} but received ${z}.`);C.demanded.forEach((W)=>{let J=Q.shift(),q=n1(J);if(W.cmd.filter((G)=>G===q||G==="*").length===0)i1(q,W.cmd,B);B+=1}),C.optional.forEach((W)=>{if(Q.length===0)return;let J=Q.shift(),q=n1(J);if(W.cmd.filter((G)=>G===q||G==="*").length===0)i1(q,W.cmd,B);B+=1})}catch(B){console.warn(B.stack)}}function n1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function i1(D,F,u){throw new DD(`Invalid ${N8[u]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class lF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,u=!0,E=!1){if(N("<array|function> [boolean] [boolean] [boolean]",[D,F,u],arguments.length),Array.isArray(D)){for(let B=0;B<D.length;B++){if(typeof D[B]!=="function")throw Error("middleware must be a function");let C=D[B];C.applyBeforeValidation=F,C.global=u}Array.prototype.push.apply(this.globalMiddleware,D)}else if(typeof D==="function"){let B=D;B.applyBeforeValidation=F,B.global=u,B.mutates=E,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let u=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((E)=>{let B=[...u[F]||[],F];if(!E.option)return!0;else return!B.includes(E.option)}),D.option=F,this.addMiddleware(D,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let D=this.frozens.pop();if(D!==void 0)this.globalMiddleware=D}reset(){this.globalMiddleware=this.globalMiddleware.filter((D)=>D.global)}}function t1(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function oD(D,F,u,E){return u.reduce((B,C)=>{if(C.applyBeforeValidation!==E)return B;if(C.mutates){if(C.applied)return B;C.applied=!0}if(s(B))return B.then(($)=>Promise.all([$,C($,F)])).then(([$,X])=>Object.assign($,X));else{let $=C(B,F);return s($)?$.then((X)=>Object.assign(B,X)):Object.assign(B,$)}},D)}function nD(D,F,u=(E)=>{throw E}){try{let E=j8(D)?D():D;return s(E)?E.then((B)=>F(B)):F(E)}catch(E){return u(E)}}function j8(D){return typeof D==="function"}var O0=/(^\*)|(^\$0)/;class r1{constructor(D,F,u,E){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=E,this.usage=D,this.globalMiddleware=u,this.validation=F}addDirectory(D,F,u,E){E=E||{},this.requireCache.add(u);let B=this.shim.path.resolve(this.shim.path.dirname(u),D),C=this.shim.readdirSync(B,{recursive:E.recurse?!0:!1});if(!Array.isArray(E.extensions))E.extensions=["js"];let $=typeof E.visit==="function"?E.visit:(X)=>X;for(let X of C){let Q=X.toString();if(E.exclude){let Y=!1;if(typeof E.exclude==="function")Y=E.exclude(Q);else Y=E.exclude.test(Q);if(Y)continue}if(E.include){let Y=!1;if(typeof E.include==="function")Y=E.include(Q);else Y=E.include.test(Q);if(!Y)continue}let z=!1;for(let Y of E.extensions)if(Q.endsWith(Y))z=!0;if(z){let Y=this.shim.path.join(B,Q),W=F(Y),J=Object.create(null,Object.getOwnPropertyDescriptors({...W}));if($(J,Y,Q)){if(this.requireCache.has(Y))continue;else this.requireCache.add(Y);if(!J.command)J.command=this.shim.path.basename(Y,this.shim.path.extname(Y));this.addHandler(J)}}}}addHandler(D,F,u,E,B,C){let $=[],X=t1(B);if(E=E||(()=>{}),Array.isArray(D))if(w8(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(I8(D)){let Q=Array.isArray(D.command)||typeof D.command==="string"?D.command:null;if(Q===null)throw new Error(`No command name given for module: ${this.shim.inspect(D)}`);if(D.aliases)Q=[].concat(Q).concat(D.aliases);this.addHandler(Q,this.extractDesc(D),D.builder,D.handler,D.middlewares,D.deprecated);return}else if(s1(u)){this.addHandler([D].concat($),F,u.builder,u.handler,u.middlewares,u.deprecated);return}if(typeof D==="string"){let Q=kD(D);$=$.map((W)=>kD(W).cmd);let z=!1,Y=[Q.cmd].concat($).filter((W)=>{if(O0.test(W))return z=!0,!1;return!0});if(Y.length===0&&z)Y.push("$0");if(z)Q.cmd=Y[0],$=Y.slice(1),D=D.replace(O0,Q.cmd);if($.forEach((W)=>{this.aliasMap[W]=Q.cmd}),F!==!1)this.usage.command(D,F,z,$,C);if(this.handlers[Q.cmd]={original:D,description:F,handler:E,builder:u||{},middlewares:X,deprecated:C,demanded:Q.demanded,optional:Q.optional},z)this.defaultCommand=this.handlers[Q.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(D,F,u,E,B,C){let $=this.handlers[D]||this.handlers[this.aliasMap[D]]||this.defaultCommand,X=F.getInternalMethods().getContext(),Q=X.commands.slice(),z=!D;if(D)X.commands.push(D),X.fullCommands.push($.original);let Y=this.applyBuilderUpdateUsageAndParse(z,$,F,u.aliases,Q,E,B,C);return s(Y)?Y.then((W)=>this.applyMiddlewareAndGetResult(z,$,W.innerArgv,X,B,W.aliases,F)):this.applyMiddlewareAndGetResult(z,$,Y.innerArgv,X,B,Y.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,u,E,B,C,$,X){let Q=F.builder,z=u;if(d0(Q)){u.getInternalMethods().getUsageInstance().freeze();let Y=Q(u.getInternalMethods().reset(E),X);if(s(Y))return Y.then((W)=>{return z=e1(W)?W:u,this.parseAndUpdateUsage(D,F,z,B,C,$)})}else if(T8(Q))u.getInternalMethods().getUsageInstance().freeze(),z=u.getInternalMethods().reset(E),Object.keys(F.builder).forEach((Y)=>{z.option(Y,Q[Y])});return this.parseAndUpdateUsage(D,F,z,B,C,$)}parseAndUpdateUsage(D,F,u,E,B,C){if(D)u.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(u))u.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(E,F),F.description);let $=u.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,B,C);return s($)?$.then((X)=>({aliases:u.parsed.aliases,innerArgv:X})):{aliases:u.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let u=O0.test(F.original)?F.original.replace(O0,"").trim():F.original,E=D.filter((B)=>{return!O0.test(B)});return E.push(u),`$0 ${E.join(" ")}`}handleValidationAndGetResult(D,F,u,E,B,C,$,X){if(!C.getInternalMethods().getHasOutput()){let Q=C.getInternalMethods().runValidation(B,X,C.parsed.error,D);u=nD(u,(z)=>{return Q(z),z})}if(F.handler&&!C.getInternalMethods().getHasOutput()){C.getInternalMethods().setHasOutput();let Q=!!C.getOptions().configuration["populate--"];if(C.getInternalMethods().postProcess(u,Q,!1,!1),u=oD(u,C,$,!1),u=nD(u,(z)=>{let Y=F.handler(z);return s(Y)?Y.then(()=>z):z}),!D)C.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(u)&&!C.getInternalMethods().hasParseCallback())u.catch((z)=>{try{C.getInternalMethods().getUsageInstance().fail(null,z)}catch(Y){}})}if(!D)E.commands.pop(),E.fullCommands.pop();return u}applyMiddlewareAndGetResult(D,F,u,E,B,C,$){let X={};if(B)return u;if(!$.getInternalMethods().getHasOutput())X=this.populatePositionals(F,u,E,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=oD(u,$,Q,!0);return s(z)?z.then((Y)=>this.handleValidationAndGetResult(D,F,Y,E,C,$,Q,X)):this.handleValidationAndGetResult(D,F,z,E,C,$,Q,X)}populatePositionals(D,F,u,E){F._=F._.slice(u.commands.length);let B=D.demanded.slice(0),C=D.optional.slice(0),$={};this.validation.positionalCount(B.length,F._.length);while(B.length){let X=B.shift();this.populatePositional(X,F,$)}while(C.length){let X=C.shift();this.populatePositional(X,F,$)}return F._=u.commands.concat(F._.map((X)=>""+X)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),E),$}populatePositional(D,F,u){let E=D.cmd[0];if(D.variadic)u[E]=F._.splice(0).map(String);else if(F._.length)u[E]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},u=kD(D);return u.demanded.forEach((E)=>{let[B,...C]=E.cmd;if(E.variadic)F.array.push(B),F.default[B]=[];F.alias[B]=C,F.demand[B]=!0}),u.optional.forEach((E)=>{let[B,...C]=E.cmd;if(E.variadic)F.array.push(B),F.default[B]=[];F.alias[B]=C}),F}postProcessPositionals(D,F,u,E){let B=Object.assign({},E.getOptions());B.default=Object.assign(u.default,B.default);for(let Q of Object.keys(u.alias))B.alias[Q]=(B.alias[Q]||[]).concat(u.alias[Q]);B.array=B.array.concat(u.array),B.config={};let C=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(B.configuration["unknown-options-as-args"])B.key[Q]=!0;C.push(`--${Q}`),C.push(z)})}),!C.length)return;let $=Object.assign({},B.configuration,{"populate--":!1}),X=this.shim.Parser.detailed(C,Object.assign({},B,{configuration:$}));if(X.error)E.getInternalMethods().getUsageInstance().fail(X.error.message,X.error);else{let Q=Object.keys(F);Object.keys(F).forEach((z)=>{Q.push(...X.aliases[z])}),Object.keys(X.argv).forEach((z)=>{if(Q.includes(z)){if(!F[z])F[z]=X.argv[z];if(!this.isInConfigs(E,z)&&!this.isDefaulted(E,z)&&Object.prototype.hasOwnProperty.call(D,z)&&Object.prototype.hasOwnProperty.call(X.argv,z)&&(Array.isArray(D[z])||Array.isArray(X.argv[z])))D[z]=[].concat(D[z],X.argv[z]);else D[z]=X.argv[z]}})}}isDefaulted(D,F){let{default:u}=D.getOptions();return Object.prototype.hasOwnProperty.call(u,F)||Object.prototype.hasOwnProperty.call(u,this.shim.Parser.camelCase(F))}isInConfigs(D,F){let{configObjects:u}=D.getOptions();return u.some((E)=>Object.prototype.hasOwnProperty.call(E,F))||u.some((E)=>Object.prototype.hasOwnProperty.call(E,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let u=O0.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");D.getInternalMethods().getUsageInstance().usage(u,this.defaultCommand.description)}let F=this.defaultCommand.builder;if(d0(F))return F(D,!0);else if(!s1(F))Object.keys(F).forEach((u)=>{D.option(u,F[u])});return}extractDesc({describe:D,description:F,desc:u}){for(let E of[D,F,u]){if(typeof E==="string"||E===!1)return E;YD(E,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let D=this.frozens.pop();YD(D,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=D}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function a1(D,F,u,E){return new r1(D,F,u,E)}function s1(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function w8(D){return D.every((F)=>typeof F==="string")}function d0(D){return typeof D==="function"}function T8(D){return typeof D==="object"}function I8(D){return typeof D==="object"&&!Array.isArray(D)}function fD(D={},F=()=>!0){let u={};return z0(D).forEach((E)=>{if(F(E,D[E]))u[E]=D[E]}),u}function yD(D){if(typeof process==="undefined")return;[process.stdout,process.stderr].forEach((F)=>{let u=F;if(u._handle&&u.isTTY&&typeof u._handle.setBlocking==="function")u._handle.setBlocking(D)})}function b8(D){return typeof D==="boolean"}function F3(D,F){let u=F.y18n.__,E={},B=[];E.failFn=function w(R){B.push(R)};let C=null,$=null,X=!0;E.showHelpOnFail=function w(R=!0,b){let[y,o]=typeof R==="string"?[!0,R]:[R,b];if(D.getInternalMethods().isGlobalContext())$=o;return C=o,X=y,E};let Q=!1;E.fail=function w(R,b){let y=D.getInternalMethods().getLoggerInstance();if(B.length)for(let o=B.length-1;o>=0;--o){let uD=B[o];if(b8(uD)){if(b)throw b;else if(R)throw Error(R)}else uD(R,b,E)}else{if(D.getExitProcess())yD(!0);if(!Q){if(Q=!0,X)D.showHelp("error"),y.error();if(R||b)y.error(R||b);let o=C||$;if(o){if(R||b)y.error("");y.error(o)}}if(b=b||new DD(R),D.getExitProcess())return D.exit(1);else if(D.getInternalMethods().hasParseCallback())return D.exit(1,b);else throw b}};let z=[],Y=!1;E.usage=(w,R)=>{if(w===null)return Y=!0,z=[],E;return Y=!1,z.push([w,R||""]),E},E.getUsage=()=>{return z},E.getUsageDisabled=()=>{return Y},E.getPositionalGroupName=()=>{return u("Positionals:")};let W=[];E.example=(w,R)=>{W.push([w,R||""])};let J=[];E.command=function w(R,b,y,o,uD=!1){if(y)J=J.map((c)=>{return c[2]=!1,c});J.push([R,b||"",y,o,uD])},E.getCommands=()=>J;let q={};E.describe=function w(R,b){if(Array.isArray(R))R.forEach((y)=>{E.describe(y,b)});else if(typeof R==="object")Object.keys(R).forEach((y)=>{E.describe(y,R[y])});else q[R]=b},E.getDescriptions=()=>q;let M=[];E.epilog=(w)=>{M.push(w)};let G=!1,T;E.wrap=(w)=>{G=!0,T=w},E.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!G)T=t(),G=!0;return T};let p="__yargsString__:";E.deferY18nLookup=(w)=>p+w,E.help=function w(){if(V)return V;QD();let R=D.customScriptName?D.$0:F.path.basename(D.$0),b=D.getDemandedOptions(),y=D.getDemandedCommands(),o=D.getDeprecatedOptions(),uD=D.getGroups(),c=D.getOptions(),ED=[];ED=ED.concat(Object.keys(q)),ED=ED.concat(Object.keys(b)),ED=ED.concat(Object.keys(y)),ED=ED.concat(Object.keys(c.default)),ED=ED.filter(k),ED=Object.keys(ED.reduce((v,n)=>{if(n!=="_")v[n]=!0;return v},{}));let vD=E.getWrap(),i=F.cliui({width:vD,wrap:!!vD});if(!Y){if(z.length)z.forEach((v)=>{if(i.div({text:`${v[0].replace(/\$0/g,R)}`}),v[1])i.div({text:`${v[1]}`,padding:[1,0,0,0]})}),i.div();else if(J.length){let v=null;if(y._)v=`${R} <${u("command")}>
24
+ `).map((E)=>n6(E,F,u)).join(`
25
+ `)}function NF(D){return B1(D,{stringWidth:RD,stripAnsi:mD,wrap:LF})}import{dirname as _1,resolve as K1}from"path";import{readdirSync as i6,statSync as t6}from"fs";function jF(D,F){let u=K1(".",D),E;if(!t6(u).isDirectory())u=_1(u);while(!0){if(E=F(u,i6(u)),E)return K1(u,E);if(u=_1(E=u),E===u)break}}import{inspect as J8}from"util";import{fileURLToPath as y1}from"url";import{format as a6}from"util";import{normalize as e6,resolve as D8}from"path";function lD(D){if(!(D!==D.toLowerCase()&&D!==D.toUpperCase()))D=D.toLowerCase();if(D.indexOf("-")===-1&&D.indexOf("_")===-1)return D;else{let u="",E=!1,B=D.match(/^-+/);for(let C=B?B[0].length:0;C<D.length;C++){let $=D.charAt(C);if(E)E=!1,$=$.toUpperCase();if(C!==0&&($==="-"||$==="_"))E=!0;else if($!=="-"&&$!=="_")u+=$}return u}}function S0(D,F){let u=D.toLowerCase();F=F||"-";let E="";for(let B=0;B<D.length;B++){let C=u.charAt(B),$=D.charAt(B);if(C!==$&&B>0)E+=`${F}${u.charAt(B)}`;else E+=$}return E}function v0(D){if(D===null||D===void 0)return!1;if(typeof D==="number")return!0;if(/^0x[0-9a-f]+$/i.test(D))return!0;if(/^0[^.]/.test(D))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(D)}function V1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,u=null,E=null,B=null,C=[];for(let $=0;$<D.length;$++){if(u=E,E=D.charAt($),E===" "&&!B){if(u!==" ")F++;continue}if(E===B)B=null;else if((E==="'"||E==='"')&&!B)B=E;if(!C[F])C[F]="";C[F]+=E}return C}var MD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(MD||(MD={}));var bD;class TF{constructor(D){bD=D}parse(D,F){let u=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},F),E=V1(D),B=typeof D==="string",C=s6(Object.assign(Object.create(null),u.alias)),$=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},u.configuration),X=Object.assign(Object.create(null),u.default),Q=u.configObjects||[],z=u.envPrefix,Y=$["populate--"],W=Y?"--":"_",J=Object.create(null),M=Object.create(null),q=u.__||bD.format,G={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},T=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,p=new RegExp("^--"+$["negation-prefix"]+"(.+)");if([].concat(u.array||[]).filter(Boolean).forEach(function(O){let H=typeof O==="object"?O.key:O,K=Object.keys(O).map(function(_){return{boolean:"bools",string:"strings",number:"numbers"}[_]}).filter(Boolean).pop();if(K)G[K][H]=!0;G.arrays[H]=!0,G.keys.push(H)}),[].concat(u.boolean||[]).filter(Boolean).forEach(function(O){G.bools[O]=!0,G.keys.push(O)}),[].concat(u.string||[]).filter(Boolean).forEach(function(O){G.strings[O]=!0,G.keys.push(O)}),[].concat(u.number||[]).filter(Boolean).forEach(function(O){G.numbers[O]=!0,G.keys.push(O)}),[].concat(u.count||[]).filter(Boolean).forEach(function(O){G.counts[O]=!0,G.keys.push(O)}),[].concat(u.normalize||[]).filter(Boolean).forEach(function(O){G.normalize[O]=!0,G.keys.push(O)}),typeof u.narg==="object")Object.entries(u.narg).forEach(([O,H])=>{if(typeof H==="number")G.nargs[O]=H,G.keys.push(O)});if(typeof u.coerce==="object")Object.entries(u.coerce).forEach(([O,H])=>{if(typeof H==="function")G.coercions[O]=H,G.keys.push(O)});if(typeof u.config<"u"){if(Array.isArray(u.config)||typeof u.config==="string")[].concat(u.config).filter(Boolean).forEach(function(O){G.configs[O]=!0});else if(typeof u.config==="object")Object.entries(u.config).forEach(([O,H])=>{if(typeof H==="boolean"||typeof H==="function")G.configs[O]=H})}H0(u.key,C,u.default,G.arrays),Object.keys(X).forEach(function(O){(G.aliases[O]||[]).forEach(function(H){X[H]=X[O]})});let g=null;HF();let QD=[],V=Object.assign(Object.create(null),{_:[]}),L={};for(let O=0;O<E.length;O++){let H=E[O],K=H.replace(/^-{3,}/,"---"),_,A,I,U,P,XD;if(H!=="--"&&/^-/.test(H)&&n(H))f(H);else if(K.match(/^---+(=|$)/)){f(H);continue}else if(H.match(/^--.+=/)||!$["short-option-groups"]&&H.match(/^-.+=/)){if(U=H.match(/^--?([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)if(S(U[1],G.arrays))O=t(O,U[1],E,U[2]);else if(S(U[1],G.nargs)!==!1)O=h(O,U[1],E,U[2]);else l(U[1],U[2],!0)}else if(H.match(p)&&$["boolean-negation"]){if(U=H.match(p),U!==null&&Array.isArray(U)&&U.length>=2)A=U[1],l(A,S(A,G.arrays)?[!1]:!1)}else if(H.match(/^--.+/)||!$["short-option-groups"]&&H.match(/^-[^-]+/)){if(U=H.match(/^--?(.+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],S(A,G.arrays))O=t(O,A,E);else if(S(A,G.nargs)!==!1)O=h(O,A,E);else if(P=E[O+1],P!==void 0&&(!P.match(/^-/)||P.match(T))&&!S(A,G.bools)&&!S(A,G.counts))l(A,P),O++;else if(/^(true|false)$/.test(P))l(A,P),O++;else l(A,m(A))}else if(H.match(/^-.\..+=/)){if(U=H.match(/^-([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)l(U[1],U[2])}else if(H.match(/^-.\..+/)&&!H.match(T)){if(P=E[O+1],U=H.match(/^-(.\..+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],P!==void 0&&!P.match(/^-/)&&!S(A,G.bools)&&!S(A,G.counts))l(A,P),O++;else l(A,m(A))}else if(H.match(/^-[^-]+/)&&!H.match(T)){I=H.slice(1,-1).split(""),_=!1;for(let OD=0;OD<I.length;OD++){if(P=H.slice(OD+2),I[OD+1]&&I[OD+1]==="="){if(XD=H.slice(OD+3),A=I[OD],S(A,G.arrays))O=t(O,A,E,XD);else if(S(A,G.nargs)!==!1)O=h(O,A,E,XD);else l(A,XD);_=!0;break}if(P==="-"){l(I[OD],P);continue}if(/[A-Za-z]/.test(I[OD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)&&S(P,G.bools)===!1){l(I[OD],P),_=!0;break}if(I[OD+1]&&I[OD+1].match(/\W/)){l(I[OD],P),_=!0;break}else l(I[OD],m(I[OD]))}if(A=H.slice(-1)[0],!_&&A!=="-")if(S(A,G.arrays))O=t(O,A,E);else if(S(A,G.nargs)!==!1)O=h(O,A,E);else if(P=E[O+1],P!==void 0&&(!/^(-|--)[^-]/.test(P)||P.match(T))&&!S(A,G.bools)&&!S(A,G.counts))l(A,P),O++;else if(/^(true|false)$/.test(P))l(A,P),O++;else l(A,m(A))}else if(H.match(/^-[0-9]$/)&&H.match(T)&&S(H.slice(1),G.bools))A=H.slice(1),l(A,m(A));else if(H==="--"){QD=E.slice(O+1);break}else if($["halt-at-non-option"]){QD=E.slice(O);break}else f(H)}if(uD(V,!0),uD(V,!1),b(V),o(),xD(V,G.aliases,X,!0),c(V),$["set-placeholder-key"])ED(V);if(Object.keys(G.counts).forEach(function(O){if(!i(V,O.split(".")))l(O,0)}),Y&&QD.length)V[W]=[];if(QD.forEach(function(O){V[W].push(O)}),$["camel-case-expansion"]&&$["strip-dashed"])Object.keys(V).filter((O)=>O!=="--"&&O.includes("-")).forEach((O)=>{delete V[O]});if($["strip-aliased"])[].concat(...Object.keys(C).map((O)=>C[O])).forEach((O)=>{if($["camel-case-expansion"]&&O.includes("-"))delete V[O.split(".").map((H)=>lD(H)).join(".")];delete V[O]});function f(O){let H=R("_",O);if(typeof H==="string"||typeof H==="number")V._.push(H)}function h(O,H,K,_){let A,I=S(H,G.nargs);if(I=typeof I!=="number"||isNaN(I)?1:I,I===0){if(!CD(_))g=Error(q("Argument unexpected for: %s",H));return l(H,m(H)),O}let U=CD(_)?0:1;if($["nargs-eats-options"]){if(K.length-(O+1)+U<I)g=Error(q("Not enough arguments following: %s",H));U=I}else{for(A=O+1;A<K.length;A++)if(!K[A].match(/^-[^0-9]/)||K[A].match(T)||n(K[A]))U++;else break;if(U<I)g=Error(q("Not enough arguments following: %s",H))}let P=Math.min(U,I);if(!CD(_)&&P>0)l(H,_),P--;for(A=O+1;A<P+O+1;A++)l(H,K[A]);return O+P}function t(O,H,K,_){let A=[],I=_||K[O+1],U=S(H,G.nargs);if(S(H,G.bools)&&!/^(true|false)$/.test(I))A.push(!0);else if(CD(I)||CD(_)&&/^-/.test(I)&&!T.test(I)&&!n(I)){if(X[H]!==void 0){let P=X[H];A=Array.isArray(P)?P:[P]}}else{if(!CD(_))A.push(w(H,_,!0));for(let P=O+1;P<K.length;P++){if(!$["greedy-arrays"]&&A.length>0||U&&typeof U==="number"&&A.length>=U)break;if(I=K[P],/^-/.test(I)&&!T.test(I)&&!n(I))break;O=P,A.push(w(H,I,B))}}if(typeof U==="number"&&(U&&A.length<U||isNaN(U)&&A.length===0))g=Error(q("Not enough arguments following: %s",H));return l(H,A),O}function l(O,H,K=B){if(/-/.test(O)&&$["camel-case-expansion"]){let I=O.split(".").map(function(U){return lD(U)}).join(".");jD(O,I)}let _=w(O,H,K),A=O.split(".");if(ID(V,A,_),G.aliases[O])G.aliases[O].forEach(function(I){let U=I.split(".");ID(V,U,_)});if(A.length>1&&$["dot-notation"])(G.aliases[A[0]]||[]).forEach(function(I){let U=I.split("."),P=[].concat(A);if(P.shift(),U=U.concat(P),!(G.aliases[O]||[]).includes(U.join(".")))ID(V,U,_)});if(S(O,G.normalize)&&!S(O,G.arrays))[O].concat(G.aliases[O]||[]).forEach(function(U){Object.defineProperty(L,U,{enumerable:!0,get(){return H},set(P){H=typeof P==="string"?bD.normalize(P):P}})})}function jD(O,H){if(!(G.aliases[O]&&G.aliases[O].length))G.aliases[O]=[H],J[H]=!0;if(!(G.aliases[H]&&G.aliases[H].length))jD(H,O)}function w(O,H,K){if(K)H=r6(H);if(S(O,G.bools)||S(O,G.counts)){if(typeof H==="string")H=H==="true"}let _=Array.isArray(H)?H.map(function(A){return R(O,A)}):R(O,H);if(S(O,G.counts)&&(CD(_)||typeof _==="boolean"))_=wF();if(S(O,G.normalize)&&S(O,G.arrays))if(Array.isArray(H))_=H.map((A)=>{return bD.normalize(A)});else _=bD.normalize(H);return _}function R(O,H){if(!$["parse-positional-numbers"]&&O==="_")return H;if(!S(O,G.strings)&&!S(O,G.bools)&&!Array.isArray(H)){if(v0(H)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${H}`)))||!CD(H)&&S(O,G.numbers))H=Number(H)}return H}function b(O){let H=Object.create(null);xD(H,G.aliases,X),Object.keys(G.configs).forEach(function(K){let _=O[K]||H[K];if(_)try{let A=null,I=bD.resolve(bD.cwd(),_),U=G.configs[K];if(typeof U==="function"){try{A=U(I)}catch(P){A=P}if(A instanceof Error){g=A;return}}else A=bD.require(I);y(A)}catch(A){if(A.name==="PermissionDenied")g=A;else if(O[K])g=Error(q("Invalid JSON config file: %s",_))}})}function y(O,H){Object.keys(O).forEach(function(K){let _=O[K],A=H?H+"."+K:K;if(typeof _==="object"&&_!==null&&!Array.isArray(_)&&$["dot-notation"])y(_,A);else if(!i(V,A.split("."))||S(A,G.arrays)&&$["combine-arrays"])l(A,_)})}function o(){if(typeof Q<"u")Q.forEach(function(O){y(O)})}function uD(O,H){if(typeof z>"u")return;let K=typeof z==="string"?z:"",_=bD.env();Object.keys(_).forEach(function(A){if(K===""||A.lastIndexOf(K,0)===0){let I=A.split("__").map(function(U,P){if(P===0)U=U.substring(K.length);return lD(U)});if((H&&G.configs[I.join(".")]||!H)&&!i(O,I))l(I.join("."),_[A])}})}function c(O){let H,K=new Set;Object.keys(O).forEach(function(_){if(!K.has(_)){if(H=S(_,G.coercions),typeof H==="function")try{let A=R(_,H(O[_]));[].concat(G.aliases[_]||[],_).forEach((I)=>{K.add(I),O[I]=A})}catch(A){g=A}}})}function ED(O){return G.keys.forEach((H)=>{if(~H.indexOf("."))return;if(typeof O[H]>"u")O[H]=void 0}),O}function xD(O,H,K,_=!1){Object.keys(K).forEach(function(A){if(!i(O,A.split("."))){if(ID(O,A.split("."),K[A]),_)M[A]=!0;(H[A]||[]).forEach(function(I){if(i(O,I.split(".")))return;ID(O,I.split("."),K[A])})}})}function i(O,H){let K=O;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(A){K=K[A]||{}});let _=H[H.length-1];if(typeof K!=="object")return!1;else return _ in K}function ID(O,H,K){let _=O;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(XD){if(XD=R1(XD),typeof _==="object"&&_[XD]===void 0)_[XD]={};if(typeof _[XD]!=="object"||Array.isArray(_[XD])){if(Array.isArray(_[XD]))_[XD].push({});else _[XD]=[_[XD],{}];_=_[XD][_[XD].length-1]}else _=_[XD]});let A=R1(H[H.length-1]),I=S(H.join("."),G.arrays),U=Array.isArray(K),P=$["duplicate-arguments-array"];if(!P&&S(A,G.nargs)){if(P=!0,!CD(_[A])&&G.nargs[A]===1||Array.isArray(_[A])&&_[A].length===G.nargs[A])_[A]=void 0}if(K===wF())_[A]=wF(_[A]);else if(Array.isArray(_[A]))if(P&&I&&U)_[A]=$["flatten-duplicate-arrays"]?_[A].concat(K):(Array.isArray(_[A][0])?_[A]:[_[A]]).concat([K]);else if(!P&&Boolean(I)===Boolean(U))_[A]=K;else _[A]=_[A].concat([K]);else if(_[A]===void 0&&I)_[A]=U?K:[K];else if(P&&!(_[A]===void 0||S(A,G.counts)||S(A,G.bools)))_[A]=[_[A],K];else _[A]=K}function H0(...O){O.forEach(function(H){Object.keys(H||{}).forEach(function(K){if(G.aliases[K])return;G.aliases[K]=[].concat(C[K]||[]),G.aliases[K].concat(K).forEach(function(_){if(/-/.test(_)&&$["camel-case-expansion"]){let A=lD(_);if(A!==K&&G.aliases[K].indexOf(A)===-1)G.aliases[K].push(A),J[A]=!0}}),G.aliases[K].concat(K).forEach(function(_){if(_.length>1&&/[A-Z]/.test(_)&&$["camel-case-expansion"]){let A=S0(_,"-");if(A!==K&&G.aliases[K].indexOf(A)===-1)G.aliases[K].push(A),J[A]=!0}}),G.aliases[K].forEach(function(_){G.aliases[_]=[K].concat(G.aliases[K].filter(function(A){return _!==A}))})})})}function S(O,H){let K=[].concat(G.aliases[O]||[],O),_=Object.keys(H),A=K.find((I)=>_.includes(I));return A?H[A]:!1}function Q0(O){let H=Object.keys(G);return[].concat(H.map((_)=>G[_])).some(function(_){return Array.isArray(_)?_.includes(O):_[O]})}function r2(O,...H){return[].concat(...H).some(function(_){let A=O.match(_);return A&&Q0(A[1])})}function v(O){if(O.match(T)||!O.match(/^-[^-]+/))return!1;let H=!0,K,_=O.slice(1).split("");for(let A=0;A<_.length;A++){if(K=O.slice(A+2),!Q0(_[A])){H=!1;break}if(_[A+1]&&_[A+1]==="="||K==="-"||/[A-Za-z]/.test(_[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(K)||_[A+1]&&_[A+1].match(/\W/))break}return H}function n(O){return $["unknown-options-as-args"]&&BD(O)}function BD(O){if(O=O.replace(/^-{3,}/,"--"),O.match(T))return!1;if(v(O))return!1;return!r2(O,/^-+([^=]+?)=[\s\S]*$/,p,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function m(O){if(!S(O,G.bools)&&!S(O,G.counts)&&`${O}`in X)return X[O];else return zD(e(O))}function zD(O){return{[MD.BOOLEAN]:!0,[MD.STRING]:"",[MD.NUMBER]:void 0,[MD.ARRAY]:[]}[O]}function e(O){let H=MD.BOOLEAN;if(S(O,G.strings))H=MD.STRING;else if(S(O,G.numbers))H=MD.NUMBER;else if(S(O,G.bools))H=MD.BOOLEAN;else if(S(O,G.arrays))H=MD.ARRAY;return H}function CD(O){return O===void 0}function HF(){Object.keys(G.counts).find((O)=>{if(S(O,G.arrays))return g=Error(q("Invalid configuration: %s, opts.count excludes opts.array.",O)),!0;else if(S(O,G.nargs))return g=Error(q("Invalid configuration: %s, opts.count excludes opts.narg.",O)),!0;return!1})}return{aliases:Object.assign({},G.aliases),argv:Object.assign(L,V),configuration:$,defaulted:Object.assign({},M),error:g,newAliases:Object.assign({},J)}}}function s6(D){let F=[],u=Object.create(null),E=!0;Object.keys(D).forEach(function(B){F.push([].concat(D[B],B))});while(E){E=!1;for(let B=0;B<F.length;B++)for(let C=B+1;C<F.length;C++)if(F[B].filter(function(X){return F[C].indexOf(X)!==-1}).length){F[B]=F[B].concat(F[C]),F.splice(C,1),E=!0;break}}return F.forEach(function(B){B=B.filter(function($,X,Q){return Q.indexOf($)===X});let C=B.pop();if(C!==void 0&&typeof C==="string")u[C]=B}),u}function wF(D){return D!==void 0?D+1:1}function R1(D){if(D==="__proto__")return"___proto___";return D}function r6(D){return typeof D==="string"&&(D[0]==="'"||D[0]==='"')&&D[D.length-1]===D[0]?D.substring(1,D.length-1):D}import{readFileSync as F8}from"fs";import{createRequire as U1}from"node:module";var IF,bF,xF,L1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,N1=(bF=(IF=process===null||process===void 0?void 0:process.versions)===null||IF===void 0?void 0:IF.node)!==null&&bF!==void 0?bF:(xF=process===null||process===void 0?void 0:process.version)===null||xF===void 0?void 0:xF.slice(1);if(N1){if(Number(N1.match(/^([^.]+)/)[1])<L1)throw Error(`yargs parser supports a minimum Node.js version of ${L1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var u8=process?process.env:{},j1=U1?U1(import.meta.url):void 0,w1=new TF({cwd:process.cwd,env:()=>{return u8},format:a6,normalize:e6,resolve:D8,require:(D)=>{if(typeof j1<"u")return j1(D);else if(D.match(/\.json$/))return JSON.parse(F8(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),q0=function(F,u){return w1.parse(F.slice(),u).argv};q0.detailed=function(D,F){return w1.parse(D.slice(),F)};q0.camelCase=lD;q0.decamelize=S0;q0.looksLikeNumber=v0;var PF=q0;import{basename as W8,dirname as A8,extname as G8,relative as H8,resolve as k1,join as M8}from"path";function T1(){if(E8())return 0;return 1}function E8(){return B8()&&!process.defaultApp}function B8(){return!!process.versions.electron}function SF(D){return D.slice(T1()+1)}function I1(){return process.argv[T1()]}import{readFileSync as C8,statSync as $8,writeFile as X8}from"fs";import{format as Z8}from"util";import{resolve as Q8}from"path";var b1={fs:{readFileSync:C8,writeFile:X8},format:Z8,resolve:Q8,exists:(D)=>{try{return $8(D).isFile()}catch(F){return!1}}};var UD;class x1{constructor(D){D=D||{},this.directory=D.directory||"./locales",this.updateFiles=typeof D.updateFiles==="boolean"?D.updateFiles:!0,this.locale=D.locale||"en",this.fallbackToLanguage=typeof D.fallbackToLanguage==="boolean"?D.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...D){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let F=D.shift(),u=function(){};if(typeof D[D.length-1]==="function")u=D.pop();if(u=u||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][F]&&this.updateFiles)this.cache[this.locale][F]=F,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:u});else u();return UD.format.apply(UD.format,[this.cache[this.locale][F]||F].concat(D))}__n(){let D=Array.prototype.slice.call(arguments),F=D.shift(),u=D.shift(),E=D.shift(),B=function(){};if(typeof D[D.length-1]==="function")B=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let C=E===1?F:u;if(this.cache[this.locale][F])C=this.cache[this.locale][F][E===1?"one":"other"];if(!this.cache[this.locale][F]&&this.updateFiles)this.cache[this.locale][F]={one:F,other:u},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:B});else B();let $=[C];if(~C.indexOf("%d"))$.push(E);return UD.format.apply(UD.format,$.concat(D))}setLocale(D){this.locale=D}getLocale(){return this.locale}updateLocale(D){if(!this.cache[this.locale])this._readLocaleFile();for(let F in D)if(Object.prototype.hasOwnProperty.call(D,F))this.cache[this.locale][F]=D[F]}_taggedLiteral(D,...F){let u="";return D.forEach(function(E,B){let C=F[B+1];if(u+=E,typeof C<"u")u+="%s"}),this.__.apply(this,[u].concat([].slice.call(F,1)))}_enqueueWrite(D){if(this.writeQueue.push(D),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let D=this,F=this.writeQueue[0],u=F.directory,E=F.locale,B=F.cb,C=this._resolveLocaleFile(u,E),$=JSON.stringify(this.cache[E],null,2);UD.fs.writeFile(C,$,"utf-8",function(X){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();B(X)})}_readLocaleFile(){let D={},F=this._resolveLocaleFile(this.directory,this.locale);try{if(UD.fs.readFileSync)D=JSON.parse(UD.fs.readFileSync(F,"utf-8"))}catch(u){if(u instanceof SyntaxError)u.message="syntax error in "+F;if(u.code==="ENOENT")D={};else throw u}this.cache[this.locale]=D}_resolveLocaleFile(D,F){let u=UD.resolve(D,"./",F+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(u)&&~F.lastIndexOf("_")){let E=UD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(E))u=E}return u}_fileExistsSync(D){return UD.exists(D)}}function P1(D,F){UD=F;let u=new x1(D);return{__:u.__.bind(u),__n:u.__n.bind(u),setLocale:u.setLocale.bind(u),getLocale:u.getLocale.bind(u),updateLocale:u.updateLocale.bind(u),locale:u.locale}}var z8=(D)=>{return P1(D,b1)},S1=z8;var h1=b0(f1(),1);import{createRequire as q8}from"node:module";import{readFileSync as _8,readdirSync as K8}from"node:fs";var vF=y1(import.meta.url),V8=vF.substring(0,vF.lastIndexOf("node_modules")),R8=q8(import.meta.url),fF={assert:{notStrictEqual:O8,strictEqual:Y8},cliui:NF,findUp:jF,getEnv:(D)=>{return process.env[D]},inspect:J8,getProcessArgvBin:I1,mainFilename:V8||process.cwd(),Parser:PF,path:{basename:W8,dirname:A8,extname:G8,relative:H8,resolve:k1,join:M8},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(D,F)=>process.emitWarning(D,F),execPath:()=>process.execPath,exit:(D)=>{process.exit(D)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:_8,readdirSync:K8,require:R8,getCallerFile:()=>{let D=h1.default(3);return D.match(/^file:\/\//)?y1(D):D},stringWidth:RD,y18n:S1({directory:k1(vF,"../../../locales"),updateFiles:!1})};function YD(D,F,u,E){u.assert.notStrictEqual(D,F,E)}function kF(D,F){F.assert.strictEqual(typeof D,"string")}function z0(D){return Object.keys(D)}function s(D){return!!D&&!!D.then&&typeof D.then==="function"}class DD extends Error{constructor(D){super(D||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,DD)}}function PD(D){let u=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),E=/\.*[\][<>]/g,B=u.shift();if(!B)throw Error(`No command found in: ${D}`);let C={cmd:B.replace(E,""),demanded:[],optional:[]};return u.forEach(($,X)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&X===u.length-1)Q=!0;if(/^\[/.test($))C.optional.push({cmd:$.replace(E,"").split("|"),variadic:Q});else C.demanded.push({cmd:$.replace(E,"").split("|"),variadic:Q})}),C}var U8=["first","second","third","fourth","fifth","sixth"];function N(D,F,u){function E(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[PD(`cmd ${D}`),F,u]}try{let B=0,[C,$,X]=E(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=X||Q.length;if(z<C.demanded.length)throw new DD(`Not enough arguments provided. Expected ${C.demanded.length} but received ${Q.length}.`);let Y=C.demanded.length+C.optional.length;if(z>Y)throw new DD(`Too many arguments provided. Expected max ${Y} but received ${z}.`);C.demanded.forEach((W)=>{let J=Q.shift(),M=d1(J);if(W.cmd.filter((G)=>G===M||G==="*").length===0)p1(M,W.cmd,B);B+=1}),C.optional.forEach((W)=>{if(Q.length===0)return;let J=Q.shift(),M=d1(J);if(W.cmd.filter((G)=>G===M||G==="*").length===0)p1(M,W.cmd,B);B+=1})}catch(B){console.warn(B.stack)}}function d1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function p1(D,F,u){throw new DD(`Invalid ${U8[u]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class yF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,u=!0,E=!1){if(N("<array|function> [boolean] [boolean] [boolean]",[D,F,u],arguments.length),Array.isArray(D)){for(let B=0;B<D.length;B++){if(typeof D[B]!=="function")throw Error("middleware must be a function");let C=D[B];C.applyBeforeValidation=F,C.global=u}Array.prototype.push.apply(this.globalMiddleware,D)}else if(typeof D==="function"){let B=D;B.applyBeforeValidation=F,B.global=u,B.mutates=E,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let u=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((E)=>{let B=[...u[F]||[],F];if(!E.option)return!0;else return!B.includes(E.option)}),D.option=F,this.addMiddleware(D,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let D=this.frozens.pop();if(D!==void 0)this.globalMiddleware=D}reset(){this.globalMiddleware=this.globalMiddleware.filter((D)=>D.global)}}function g1(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function cD(D,F,u,E){return u.reduce((B,C)=>{if(C.applyBeforeValidation!==E)return B;if(C.mutates){if(C.applied)return B;C.applied=!0}if(s(B))return B.then(($)=>Promise.all([$,C($,F)])).then(([$,X])=>Object.assign($,X));else{let $=C(B,F);return s($)?$.then((X)=>Object.assign(B,X)):Object.assign(B,$)}},D)}function oD(D,F,u=(E)=>{throw E}){try{let E=L8(D)?D():D;return s(E)?E.then((B)=>F(B)):F(E)}catch(E){return u(E)}}function L8(D){return typeof D==="function"}var O0=/(^\*)|(^\$0)/;class l1{constructor(D,F,u,E){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=E,this.usage=D,this.globalMiddleware=u,this.validation=F}addDirectory(D,F,u,E){E=E||{},this.requireCache.add(u);let B=this.shim.path.resolve(this.shim.path.dirname(u),D),C=this.shim.readdirSync(B,{recursive:E.recurse?!0:!1});if(!Array.isArray(E.extensions))E.extensions=["js"];let $=typeof E.visit==="function"?E.visit:(X)=>X;for(let X of C){let Q=X.toString();if(E.exclude){let Y=!1;if(typeof E.exclude==="function")Y=E.exclude(Q);else Y=E.exclude.test(Q);if(Y)continue}if(E.include){let Y=!1;if(typeof E.include==="function")Y=E.include(Q);else Y=E.include.test(Q);if(!Y)continue}let z=!1;for(let Y of E.extensions)if(Q.endsWith(Y))z=!0;if(z){let Y=this.shim.path.join(B,Q),W=F(Y),J=Object.create(null,Object.getOwnPropertyDescriptors({...W}));if($(J,Y,Q)){if(this.requireCache.has(Y))continue;else this.requireCache.add(Y);if(!J.command)J.command=this.shim.path.basename(Y,this.shim.path.extname(Y));this.addHandler(J)}}}}addHandler(D,F,u,E,B,C){let $=[],X=g1(B);if(E=E||(()=>{}),Array.isArray(D))if(N8(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(w8(D)){let Q=Array.isArray(D.command)||typeof D.command==="string"?D.command:null;if(Q===null)throw Error(`No command name given for module: ${this.shim.inspect(D)}`);if(D.aliases)Q=[].concat(Q).concat(D.aliases);this.addHandler(Q,this.extractDesc(D),D.builder,D.handler,D.middlewares,D.deprecated);return}else if(m1(u)){this.addHandler([D].concat($),F,u.builder,u.handler,u.middlewares,u.deprecated);return}if(typeof D==="string"){let Q=PD(D);$=$.map((W)=>PD(W).cmd);let z=!1,Y=[Q.cmd].concat($).filter((W)=>{if(O0.test(W))return z=!0,!1;return!0});if(Y.length===0&&z)Y.push("$0");if(z)Q.cmd=Y[0],$=Y.slice(1),D=D.replace(O0,Q.cmd);if($.forEach((W)=>{this.aliasMap[W]=Q.cmd}),F!==!1)this.usage.command(D,F,z,$,C);if(this.handlers[Q.cmd]={original:D,description:F,handler:E,builder:u||{},middlewares:X,deprecated:C,demanded:Q.demanded,optional:Q.optional},z)this.defaultCommand=this.handlers[Q.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(D,F,u,E,B,C){let $=this.handlers[D]||this.handlers[this.aliasMap[D]]||this.defaultCommand,X=F.getInternalMethods().getContext(),Q=X.commands.slice(),z=!D;if(D)X.commands.push(D),X.fullCommands.push($.original);let Y=this.applyBuilderUpdateUsageAndParse(z,$,F,u.aliases,Q,E,B,C);return s(Y)?Y.then((W)=>this.applyMiddlewareAndGetResult(z,$,W.innerArgv,X,B,W.aliases,F)):this.applyMiddlewareAndGetResult(z,$,Y.innerArgv,X,B,Y.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,u,E,B,C,$,X){let Q=F.builder,z=u;if(f0(Q)){u.getInternalMethods().getUsageInstance().freeze();let Y=Q(u.getInternalMethods().reset(E),X);if(s(Y))return Y.then((W)=>{return z=o1(W)?W:u,this.parseAndUpdateUsage(D,F,z,B,C,$)})}else if(j8(Q))u.getInternalMethods().getUsageInstance().freeze(),z=u.getInternalMethods().reset(E),Object.keys(F.builder).forEach((Y)=>{z.option(Y,Q[Y])});return this.parseAndUpdateUsage(D,F,z,B,C,$)}parseAndUpdateUsage(D,F,u,E,B,C){if(D)u.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(u))u.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(E,F),F.description);let $=u.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,B,C);return s($)?$.then((X)=>({aliases:u.parsed.aliases,innerArgv:X})):{aliases:u.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let u=O0.test(F.original)?F.original.replace(O0,"").trim():F.original,E=D.filter((B)=>{return!O0.test(B)});return E.push(u),`$0 ${E.join(" ")}`}handleValidationAndGetResult(D,F,u,E,B,C,$,X){if(!C.getInternalMethods().getHasOutput()){let Q=C.getInternalMethods().runValidation(B,X,C.parsed.error,D);u=oD(u,(z)=>{return Q(z),z})}if(F.handler&&!C.getInternalMethods().getHasOutput()){C.getInternalMethods().setHasOutput();let Q=!!C.getOptions().configuration["populate--"];if(C.getInternalMethods().postProcess(u,Q,!1,!1),u=cD(u,C,$,!1),u=oD(u,(z)=>{let Y=F.handler(z);return s(Y)?Y.then(()=>z):z}),!D)C.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(u)&&!C.getInternalMethods().hasParseCallback())u.catch((z)=>{try{C.getInternalMethods().getUsageInstance().fail(null,z)}catch(Y){}})}if(!D)E.commands.pop(),E.fullCommands.pop();return u}applyMiddlewareAndGetResult(D,F,u,E,B,C,$){let X={};if(B)return u;if(!$.getInternalMethods().getHasOutput())X=this.populatePositionals(F,u,E,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=cD(u,$,Q,!0);return s(z)?z.then((Y)=>this.handleValidationAndGetResult(D,F,Y,E,C,$,Q,X)):this.handleValidationAndGetResult(D,F,z,E,C,$,Q,X)}populatePositionals(D,F,u,E){F._=F._.slice(u.commands.length);let B=D.demanded.slice(0),C=D.optional.slice(0),$={};this.validation.positionalCount(B.length,F._.length);while(B.length){let X=B.shift();this.populatePositional(X,F,$)}while(C.length){let X=C.shift();this.populatePositional(X,F,$)}return F._=u.commands.concat(F._.map((X)=>""+X)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),E),$}populatePositional(D,F,u){let E=D.cmd[0];if(D.variadic)u[E]=F._.splice(0).map(String);else if(F._.length)u[E]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},u=PD(D);return u.demanded.forEach((E)=>{let[B,...C]=E.cmd;if(E.variadic)F.array.push(B),F.default[B]=[];F.alias[B]=C,F.demand[B]=!0}),u.optional.forEach((E)=>{let[B,...C]=E.cmd;if(E.variadic)F.array.push(B),F.default[B]=[];F.alias[B]=C}),F}postProcessPositionals(D,F,u,E){let B=Object.assign({},E.getOptions());B.default=Object.assign(u.default,B.default);for(let Q of Object.keys(u.alias))B.alias[Q]=(B.alias[Q]||[]).concat(u.alias[Q]);B.array=B.array.concat(u.array),B.config={};let C=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(B.configuration["unknown-options-as-args"])B.key[Q]=!0;C.push(`--${Q}`),C.push(z)})}),!C.length)return;let $=Object.assign({},B.configuration,{"populate--":!1}),X=this.shim.Parser.detailed(C,Object.assign({},B,{configuration:$}));if(X.error)E.getInternalMethods().getUsageInstance().fail(X.error.message,X.error);else{let Q=Object.keys(F);Object.keys(F).forEach((z)=>{Q.push(...X.aliases[z])}),Object.keys(X.argv).forEach((z)=>{if(Q.includes(z)){if(!F[z])F[z]=X.argv[z];if(!this.isInConfigs(E,z)&&!this.isDefaulted(E,z)&&Object.prototype.hasOwnProperty.call(D,z)&&Object.prototype.hasOwnProperty.call(X.argv,z)&&(Array.isArray(D[z])||Array.isArray(X.argv[z])))D[z]=[].concat(D[z],X.argv[z]);else D[z]=X.argv[z]}})}}isDefaulted(D,F){let{default:u}=D.getOptions();return Object.prototype.hasOwnProperty.call(u,F)||Object.prototype.hasOwnProperty.call(u,this.shim.Parser.camelCase(F))}isInConfigs(D,F){let{configObjects:u}=D.getOptions();return u.some((E)=>Object.prototype.hasOwnProperty.call(E,F))||u.some((E)=>Object.prototype.hasOwnProperty.call(E,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let u=O0.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");D.getInternalMethods().getUsageInstance().usage(u,this.defaultCommand.description)}let F=this.defaultCommand.builder;if(f0(F))return F(D,!0);else if(!m1(F))Object.keys(F).forEach((u)=>{D.option(u,F[u])});return}extractDesc({describe:D,description:F,desc:u}){for(let E of[D,F,u]){if(typeof E==="string"||E===!1)return E;YD(E,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let D=this.frozens.pop();YD(D,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=D}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function c1(D,F,u,E){return new l1(D,F,u,E)}function m1(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function N8(D){return D.every((F)=>typeof F==="string")}function f0(D){return typeof D==="function"}function j8(D){return typeof D==="object"}function w8(D){return typeof D==="object"&&!Array.isArray(D)}function SD(D={},F=()=>!0){let u={};return z0(D).forEach((E)=>{if(F(E,D[E]))u[E]=D[E]}),u}function vD(D){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((F)=>{let u=F;if(u._handle&&u.isTTY&&typeof u._handle.setBlocking==="function")u._handle.setBlocking(D)})}function T8(D){return typeof D==="boolean"}function i1(D,F){let u=F.y18n.__,E={},B=[];E.failFn=function(R){B.push(R)};let C=null,$=null,X=!0;E.showHelpOnFail=function(R=!0,b){let[y,o]=typeof R==="string"?[!0,R]:[R,b];if(D.getInternalMethods().isGlobalContext())$=o;return C=o,X=y,E};let Q=!1;E.fail=function(R,b){let y=D.getInternalMethods().getLoggerInstance();if(B.length)for(let o=B.length-1;o>=0;--o){let uD=B[o];if(T8(uD)){if(b)throw b;else if(R)throw Error(R)}else uD(R,b,E)}else{if(D.getExitProcess())vD(!0);if(!Q){if(Q=!0,X)D.showHelp("error"),y.error();if(R||b)y.error(R||b);let o=C||$;if(o){if(R||b)y.error("");y.error(o)}}if(b=b||new DD(R),D.getExitProcess())return D.exit(1);else if(D.getInternalMethods().hasParseCallback())return D.exit(1,b);else throw b}};let z=[],Y=!1;E.usage=(w,R)=>{if(w===null)return Y=!0,z=[],E;return Y=!1,z.push([w,R||""]),E},E.getUsage=()=>{return z},E.getUsageDisabled=()=>{return Y},E.getPositionalGroupName=()=>{return u("Positionals:")};let W=[];E.example=(w,R)=>{W.push([w,R||""])};let J=[];E.command=function(R,b,y,o,uD=!1){if(y)J=J.map((c)=>{return c[2]=!1,c});J.push([R,b||"",y,o,uD])},E.getCommands=()=>J;let M={};E.describe=function(R,b){if(Array.isArray(R))R.forEach((y)=>{E.describe(y,b)});else if(typeof R==="object")Object.keys(R).forEach((y)=>{E.describe(y,R[y])});else M[R]=b},E.getDescriptions=()=>M;let q=[];E.epilog=(w)=>{q.push(w)};let G=!1,T;E.wrap=(w)=>{G=!0,T=w},E.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!G)T=t(),G=!0;return T};let p="__yargsString__:";E.deferY18nLookup=(w)=>p+w,E.help=function(){if(V)return V;QD();let R=D.customScriptName?D.$0:F.path.basename(D.$0),b=D.getDemandedOptions(),y=D.getDemandedCommands(),o=D.getDeprecatedOptions(),uD=D.getGroups(),c=D.getOptions(),ED=[];ED=ED.concat(Object.keys(M)),ED=ED.concat(Object.keys(b)),ED=ED.concat(Object.keys(y)),ED=ED.concat(Object.keys(c.default)),ED=ED.filter(f),ED=Object.keys(ED.reduce((v,n)=>{if(n!=="_")v[n]=!0;return v},{}));let xD=E.getWrap(),i=F.cliui({width:xD,wrap:!!xD});if(!Y){if(z.length)z.forEach((v)=>{if(i.div({text:`${v[0].replace(/\$0/g,R)}`}),v[1])i.div({text:`${v[1]}`,padding:[1,0,0,0]})}),i.div();else if(J.length){let v=null;if(y._)v=`${R} <${u("command")}>
26
26
  `;else v=`${R} [${u("command")}]
27
- `;i.div(`${v}`)}}if(J.length>1||J.length===1&&!J[0][2]){i.div(u("Commands:"));let v=D.getInternalMethods().getContext(),n=v.commands.length?`${v.commands.join(" ")} `:"";if(D.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)J=J.sort((m,zD)=>m[0].localeCompare(zD[0]));let BD=R?`${R} `:"";J.forEach((m)=>{let zD=`${BD}${n}${m[0].replace(/^\$0 ?/,"")}`;i.span({text:zD,padding:[0,2,0,2],width:g(J,vD,`${R}${n}`)+4},{text:m[1]});let e=[];if(m[2])e.push(`[${u("default")}]`);if(m[3]&&m[3].length)e.push(`[${u("aliases:")} ${m[3].join(", ")}]`);if(m[4])if(typeof m[4]==="string")e.push(`[${u("deprecated: %s",m[4])}]`);else e.push(`[${u("deprecated")}]`);if(e.length)i.div({text:e.join(" "),padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}let ID=(Object.keys(c.alias)||[]).concat(Object.keys(D.parsed.newAliases)||[]);ED=ED.filter((v)=>!D.parsed.newAliases[v]&&ID.every((n)=>(c.alias[n]||[]).indexOf(v)===-1));let K0=u("Options:");if(!uD[K0])uD[K0]=[];L(ED,c.alias,uD,K0);let S=(v)=>/^--/.test(h0(v)),Q0=Object.keys(uD).filter((v)=>uD[v].length>0).map((v)=>{let n=uD[v].filter(k).map((BD)=>{if(ID.includes(BD))return BD;for(let m=0,zD;(zD=ID[m])!==void 0;m++)if((c.alias[zD]||[]).includes(BD))return zD;return BD});return{groupName:v,normalizedKeys:n}}).filter(({normalizedKeys:v})=>v.length>0).map(({groupName:v,normalizedKeys:n})=>{let BD=n.reduce((m,zD)=>{return m[zD]=[zD].concat(c.alias[zD]||[]).map((e)=>{if(v===E.getPositionalGroupName())return e;else return(/^[0-9]$/.test(e)?c.boolean.includes(zD)?"-":"--":e.length>1?"--":"-")+e}).sort((e,CD)=>S(e)===S(CD)?0:S(e)?1:-1).join(", "),m},{});return{groupName:v,normalizedKeys:n,switches:BD}});if(Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).some(({normalizedKeys:v,switches:n})=>!v.every((BD)=>S(n[BD]))))Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).forEach(({normalizedKeys:v,switches:n})=>{v.forEach((BD)=>{if(S(n[BD]))n[BD]=x8(n[BD],4)})});if(Q0.forEach(({groupName:v,normalizedKeys:n,switches:BD})=>{i.div(v),n.forEach((m)=>{let zD=BD[m],e=q[m]||"",CD=null;if(e.includes(p))e=u(e.substring(p.length));if(c.boolean.includes(m))CD=`[${u("boolean")}]`;if(c.count.includes(m))CD=`[${u("count")}]`;if(c.string.includes(m))CD=`[${u("string")}]`;if(c.normalize.includes(m))CD=`[${u("string")}]`;if(c.array.includes(m))CD=`[${u("array")}]`;if(c.number.includes(m))CD=`[${u("number")}]`;let RF=(K)=>typeof K==="string"?`[${u("deprecated: %s",K)}]`:`[${u("deprecated")}]`,O=[m in o?RF(o[m]):null,CD,m in b?`[${u("required")}]`:null,c.choices&&c.choices[m]?`[${u("choices:")} ${E.stringifiedValues(c.choices[m])}]`:null,d(c.default[m],c.defaultDescription[m])].filter(Boolean).join(" ");i.span({text:h0(zD),padding:[0,2,0,2+D3(zD)],width:g(BD,vD)+4},e);let H=D.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(O&&!H)i.div({text:O,padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}),W.length)i.div(u("Examples:")),W.forEach((v)=>{v[0]=v[0].replace(/\$0/g,R)}),W.forEach((v)=>{if(v[1]==="")i.div({text:v[0],padding:[0,2,0,2]});else i.div({text:v[0],padding:[0,2,0,2],width:g(W,vD)+4},{text:v[1]})}),i.div();if(M.length>0){let v=M.map((n)=>n.replace(/\$0/g,R)).join(`
27
+ `;i.div(`${v}`)}}if(J.length>1||J.length===1&&!J[0][2]){i.div(u("Commands:"));let v=D.getInternalMethods().getContext(),n=v.commands.length?`${v.commands.join(" ")} `:"";if(D.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)J=J.sort((m,zD)=>m[0].localeCompare(zD[0]));let BD=R?`${R} `:"";J.forEach((m)=>{let zD=`${BD}${n}${m[0].replace(/^\$0 ?/,"")}`;i.span({text:zD,padding:[0,2,0,2],width:g(J,xD,`${R}${n}`)+4},{text:m[1]});let e=[];if(m[2])e.push(`[${u("default")}]`);if(m[3]&&m[3].length)e.push(`[${u("aliases:")} ${m[3].join(", ")}]`);if(m[4])if(typeof m[4]==="string")e.push(`[${u("deprecated: %s",m[4])}]`);else e.push(`[${u("deprecated")}]`);if(e.length)i.div({text:e.join(" "),padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}let ID=(Object.keys(c.alias)||[]).concat(Object.keys(D.parsed.newAliases)||[]);ED=ED.filter((v)=>!D.parsed.newAliases[v]&&ID.every((n)=>(c.alias[n]||[]).indexOf(v)===-1));let H0=u("Options:");if(!uD[H0])uD[H0]=[];L(ED,c.alias,uD,H0);let S=(v)=>/^--/.test(k0(v)),Q0=Object.keys(uD).filter((v)=>uD[v].length>0).map((v)=>{let n=uD[v].filter(f).map((BD)=>{if(ID.includes(BD))return BD;for(let m=0,zD;(zD=ID[m])!==void 0;m++)if((c.alias[zD]||[]).includes(BD))return zD;return BD});return{groupName:v,normalizedKeys:n}}).filter(({normalizedKeys:v})=>v.length>0).map(({groupName:v,normalizedKeys:n})=>{let BD=n.reduce((m,zD)=>{return m[zD]=[zD].concat(c.alias[zD]||[]).map((e)=>{if(v===E.getPositionalGroupName())return e;else return(/^[0-9]$/.test(e)?c.boolean.includes(zD)?"-":"--":e.length>1?"--":"-")+e}).sort((e,CD)=>S(e)===S(CD)?0:S(e)?1:-1).join(", "),m},{});return{groupName:v,normalizedKeys:n,switches:BD}});if(Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).some(({normalizedKeys:v,switches:n})=>!v.every((BD)=>S(n[BD]))))Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).forEach(({normalizedKeys:v,switches:n})=>{v.forEach((BD)=>{if(S(n[BD]))n[BD]=I8(n[BD],4)})});if(Q0.forEach(({groupName:v,normalizedKeys:n,switches:BD})=>{i.div(v),n.forEach((m)=>{let zD=BD[m],e=M[m]||"",CD=null;if(e.includes(p))e=u(e.substring(p.length));if(c.boolean.includes(m))CD=`[${u("boolean")}]`;if(c.count.includes(m))CD=`[${u("count")}]`;if(c.string.includes(m))CD=`[${u("string")}]`;if(c.normalize.includes(m))CD=`[${u("string")}]`;if(c.array.includes(m))CD=`[${u("array")}]`;if(c.number.includes(m))CD=`[${u("number")}]`;let HF=(K)=>typeof K==="string"?`[${u("deprecated: %s",K)}]`:`[${u("deprecated")}]`,O=[m in o?HF(o[m]):null,CD,m in b?`[${u("required")}]`:null,c.choices&&c.choices[m]?`[${u("choices:")} ${E.stringifiedValues(c.choices[m])}]`:null,h(c.default[m],c.defaultDescription[m])].filter(Boolean).join(" ");i.span({text:k0(zD),padding:[0,2,0,2+n1(zD)],width:g(BD,xD)+4},e);let H=D.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(O&&!H)i.div({text:O,padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}),W.length)i.div(u("Examples:")),W.forEach((v)=>{v[0]=v[0].replace(/\$0/g,R)}),W.forEach((v)=>{if(v[1]==="")i.div({text:v[0],padding:[0,2,0,2]});else i.div({text:v[0],padding:[0,2,0,2],width:g(W,xD)+4},{text:v[1]})}),i.div();if(q.length>0){let v=q.map((n)=>n.replace(/\$0/g,R)).join(`
28
28
  `);i.div(`${v}
29
- `)}return i.toString().replace(/\s*$/,"")};function g(w,R,b){let y=0;if(!Array.isArray(w))w=Object.values(w).map((o)=>[o]);if(w.forEach((o)=>{y=Math.max(F.stringWidth(b?`${b} ${h0(o[0])}`:h0(o[0]))+D3(o[0]),y)}),R)y=Math.min(y,parseInt((R*0.5).toString(),10));return y}function QD(){let w=D.getDemandedOptions(),R=D.getOptions();(Object.keys(R.alias)||[]).forEach((b)=>{R.alias[b].forEach((y)=>{if(q[y])E.describe(b,q[y]);if(y in w)D.demandOption(b,w[y]);if(R.boolean.includes(y))D.boolean(b);if(R.count.includes(y))D.count(b);if(R.string.includes(y))D.string(b);if(R.normalize.includes(y))D.normalize(b);if(R.array.includes(y))D.array(b);if(R.number.includes(y))D.number(b)})})}let V;E.cacheHelpMessage=function(){V=this.help()},E.clearCachedHelpMessage=function(){V=void 0},E.hasCachedHelpMessage=function(){return!!V};function L(w,R,b,y){let o=[],uD=null;return Object.keys(b).forEach((c)=>{o=o.concat(b[c])}),w.forEach((c)=>{if(uD=[c].concat(R[c]),!uD.some((ED)=>o.indexOf(ED)!==-1))b[y].push(c)}),o}function k(w){return D.getOptions().hiddenOptions.indexOf(w)<0||D.parsed.argv[D.getOptions().showHiddenOpt]}E.showHelp=(w)=>{let R=D.getInternalMethods().getLoggerInstance();if(!w)w="error";(typeof w==="function"?w:R[w])(E.help())},E.functionDescription=(w)=>{return["(",w.name?F.Parser.decamelize(w.name,"-"):u("generated-value"),")"].join("")},E.stringifiedValues=function w(R,b){let y="",o=b||", ",uD=[].concat(R);if(!R||!uD.length)return y;return uD.forEach((c)=>{if(y.length)y+=o;y+=JSON.stringify(c)}),y};function d(w,R){let b=`[${u("default:")} `;if(w===void 0&&!R)return null;if(R)b+=R;else switch(typeof w){case"string":b+=`"${w}"`;break;case"object":b+=JSON.stringify(w);break;default:b+=w}return`${b}]`}function t(){if(F.process.stdColumns)return Math.min(80,F.process.stdColumns);else return 80}let l=null;E.version=(w)=>{l=w},E.showVersion=(w)=>{let R=D.getInternalMethods().getLoggerInstance();if(!w)w="error";(typeof w==="function"?w:R[w])(l)},E.reset=function w(R){return C=null,Q=!1,z=[],Y=!1,M=[],W=[],J=[],q=fD(q,(b)=>!R[b]),E};let jD=[];return E.freeze=function w(){jD.push({failMessage:C,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:M,examples:W,commands:J,descriptions:q})},E.unfreeze=function w(R=!1){let b=jD.pop();if(!b)return;if(R)q={...b.descriptions,...q},J=[...b.commands,...J],z=[...b.usages,...z],W=[...b.examples,...W],M=[...b.epilogs,...M];else({failMessage:C,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:M,examples:W,commands:J,descriptions:q}=b)},E}function cF(D){return typeof D==="object"}function x8(D,F){return cF(D)?{text:D.text,indentation:D.indentation+F}:{text:D,indentation:F}}function D3(D){return cF(D)?D.indentation:0}function h0(D){return cF(D)?D.text:D}var u3=`###-begin-{{app_name}}-completions-###
29
+ `)}return i.toString().replace(/\s*$/,"")};function g(w,R,b){let y=0;if(!Array.isArray(w))w=Object.values(w).map((o)=>[o]);if(w.forEach((o)=>{y=Math.max(F.stringWidth(b?`${b} ${k0(o[0])}`:k0(o[0]))+n1(o[0]),y)}),R)y=Math.min(y,parseInt((R*0.5).toString(),10));return y}function QD(){let w=D.getDemandedOptions(),R=D.getOptions();(Object.keys(R.alias)||[]).forEach((b)=>{R.alias[b].forEach((y)=>{if(M[y])E.describe(b,M[y]);if(y in w)D.demandOption(b,w[y]);if(R.boolean.includes(y))D.boolean(b);if(R.count.includes(y))D.count(b);if(R.string.includes(y))D.string(b);if(R.normalize.includes(y))D.normalize(b);if(R.array.includes(y))D.array(b);if(R.number.includes(y))D.number(b)})})}let V;E.cacheHelpMessage=function(){V=this.help()},E.clearCachedHelpMessage=function(){V=void 0},E.hasCachedHelpMessage=function(){return!!V};function L(w,R,b,y){let o=[],uD=null;return Object.keys(b).forEach((c)=>{o=o.concat(b[c])}),w.forEach((c)=>{if(uD=[c].concat(R[c]),!uD.some((ED)=>o.indexOf(ED)!==-1))b[y].push(c)}),o}function f(w){return D.getOptions().hiddenOptions.indexOf(w)<0||D.parsed.argv[D.getOptions().showHiddenOpt]}E.showHelp=(w)=>{let R=D.getInternalMethods().getLoggerInstance();if(!w)w="error";(typeof w==="function"?w:R[w])(E.help())},E.functionDescription=(w)=>{return["(",w.name?F.Parser.decamelize(w.name,"-"):u("generated-value"),")"].join("")},E.stringifiedValues=function(R,b){let y="",o=b||", ",uD=[].concat(R);if(!R||!uD.length)return y;return uD.forEach((c)=>{if(y.length)y+=o;y+=JSON.stringify(c)}),y};function h(w,R){let b=`[${u("default:")} `;if(w===void 0&&!R)return null;if(R)b+=R;else switch(typeof w){case"string":b+=`"${w}"`;break;case"object":b+=JSON.stringify(w);break;default:b+=w}return`${b}]`}function t(){if(F.process.stdColumns)return Math.min(80,F.process.stdColumns);else return 80}let l=null;E.version=(w)=>{l=w},E.showVersion=(w)=>{let R=D.getInternalMethods().getLoggerInstance();if(!w)w="error";(typeof w==="function"?w:R[w])(l)},E.reset=function(R){return C=null,Q=!1,z=[],Y=!1,q=[],W=[],J=[],M=SD(M,(b)=>!R[b]),E};let jD=[];return E.freeze=function(){jD.push({failMessage:C,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:q,examples:W,commands:J,descriptions:M})},E.unfreeze=function(R=!1){let b=jD.pop();if(!b)return;if(R)M={...b.descriptions,...M},J=[...b.commands,...J],z=[...b.usages,...z],W=[...b.examples,...W],q=[...b.epilogs,...q];else({failMessage:C,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:q,examples:W,commands:J,descriptions:M}=b)},E}function hF(D){return typeof D==="object"}function I8(D,F){return hF(D)?{text:D.text,indentation:D.indentation+F}:{text:D,indentation:F}}function n1(D){return hF(D)?D.indentation:0}function k0(D){return hF(D)?D.text:D}var t1=`###-begin-{{app_name}}-completions-###
30
30
  #
31
31
  # yargs command completion script
32
32
  #
@@ -55,7 +55,7 @@ _{{app_name}}_yargs_completions()
55
55
  }
56
56
  complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
57
57
  ###-end-{{app_name}}-completions-###
58
- `,E3=`#compdef {{app_name}}
58
+ `,s1=`#compdef {{app_name}}
59
59
  ###-begin-{{app_name}}-completions-###
60
60
  #
61
61
  # yargs command completion script
@@ -82,18 +82,18 @@ else
82
82
  compdef _{{app_name}}_yargs_completions {{app_name}}
83
83
  fi
84
84
  ###-end-{{app_name}}-completions-###
85
- `;class B3{constructor(D,F,u,E){var B,C,$;this.yargs=D,this.usage=F,this.command=u,this.shim=E,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=($=((B=this.shim.getEnv("SHELL"))===null||B===void 0?void 0:B.includes("zsh"))||((C=this.shim.getEnv("ZSH_NAME"))===null||C===void 0?void 0:C.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,u,E){let B=this.command.getCommandHandlers();for(let $=0,X=D.length;$<X;++$)if(B[D[$]]&&B[D[$]].builder){let Q=B[D[$]].builder;if(d0(Q)){this.indexAfterLastReset=$+1;let z=this.yargs.getInternalMethods().reset();return Q(z,!0),z.argv}}let C=[];this.commandCompletions(C,D,u),this.optionCompletions(C,D,F,u),this.choicesFromOptionsCompletions(C,D,F,u),this.choicesFromPositionalsCompletions(C,D,F,u),E(null,C)}commandCompletions(D,F,u){let E=this.yargs.getInternalMethods().getContext().commands;if(!u.match(/^-/)&&E[E.length-1]!==u&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((B)=>{let C=kD(B[0]).cmd;if(F.indexOf(C)===-1)if(!this.zshShell)D.push(C);else{let $=B[1]||"";D.push(C.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,u,E){if((E.match(/^-/)||E===""&&D.length===0)&&!this.previousArgHasChoices(F)){let B=this.yargs.getOptions(),C=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(B.key).forEach(($)=>{let X=!!B.configuration["boolean-negation"]&&B.boolean.includes($);if(!C.includes($)&&!B.hiddenOptions.includes($)&&!this.argsContainKey(F,$,X))this.completeOptionKey($,D,E,X&&!!B.default[$])})}}choicesFromOptionsCompletions(D,F,u,E){if(this.previousArgHasChoices(F)){let B=this.getPreviousArgChoices(F);if(B&&B.length>0)D.push(...B.map((C)=>C.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,u,E){if(E===""&&D.length>0&&this.previousArgHasChoices(F))return;let B=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],C=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=B[u._.length-C-1];if(!$)return;let X=this.yargs.getOptions().choices[$]||[];for(let Q of X)if(Q.startsWith(E))D.push(Q.replace(/:/g,"\\:"))}getPreviousArgChoices(D){if(D.length<1)return;let F=D[D.length-1],u="";if(!F.startsWith("-")&&D.length>1)u=F,F=D[D.length-2];if(!F.startsWith("-"))return;let E=F.replace(/^-+/,""),B=this.yargs.getOptions(),C=[E,...this.yargs.getAliases()[E]||[]],$;for(let X of C)if(Object.prototype.hasOwnProperty.call(B.key,X)&&Array.isArray(B.choices[X])){$=B.choices[X];break}if($)return $.filter((X)=>!u||X.startsWith(u))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,u){let E=(B)=>D.indexOf((/^[^0-9]$/.test(B)?"-":"--")+B)!==-1;if(E(F))return!0;if(u&&E(`no-${F}`))return!0;if(this.aliases){for(let B of this.aliases[F])if(E(B))return!0}return!1}completeOptionKey(D,F,u,E){var B,C,$,X;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),q=(C=(B=this===null||this===void 0?void 0:this.aliases)===null||B===void 0?void 0:B[D])===null||C===void 0?void 0:C.find((T)=>{let p=J[T];return typeof p==="string"&&p.length>0}),M=q?J[q]:void 0,G=(X=($=J[D])!==null&&$!==void 0?$:M)!==null&&X!==void 0?X:"";Q=`${D.replace(/:/g,"\\:")}:${G.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let z=(J)=>/^--/.test(J),Y=(J)=>/^[^0-9]$/.test(J),W=!z(u)&&Y(D)?"-":"--";if(F.push(W+Q),E)F.push(W+"no-"+Q)}customCompletion(D,F,u,E){if(YD(this.customCompletionFunction,null,this.shim),S8(this.customCompletionFunction)){let B=this.customCompletionFunction(u,F);if(s(B))return B.then((C)=>{this.shim.process.nextTick(()=>{E(null,C)})}).catch((C)=>{this.shim.process.nextTick(()=>{E(C,void 0)})});return E(null,B)}else if(v8(this.customCompletionFunction))return this.customCompletionFunction(u,F,(B=E)=>this.defaultCompletion(D,F,u,B),(B)=>{E(null,B)});else return this.customCompletionFunction(u,F,(B)=>{E(null,B)})}getCompletion(D,F){let u=D.length?D[D.length-1]:"",E=this.yargs.parse(D,!0),B=this.customCompletionFunction?(C)=>this.customCompletion(D,C,u,F):(C)=>this.defaultCompletion(D,C,u,F);return s(E)?E.then(B):B(E)}generateCompletionScript(D,F){let u=this.zshShell?E3:u3,E=this.shim.path.basename(D);if(D.match(/\.js$/))D=`./${D}`;return u=u.replace(/{{app_name}}/g,E),u=u.replace(/{{completion_command}}/g,F),u.replace(/{{app_path}}/g,D)}registerFunction(D){this.customCompletionFunction=D}setParsed(D){this.aliases=D.aliases}}function C3(D,F,u,E){return new B3(D,F,u,E)}function S8(D){return D.length<3}function v8(D){return D.length>3}function $3(D,F){if(D.length===0)return F.length;if(F.length===0)return D.length;let u=[],E;for(E=0;E<=F.length;E++)u[E]=[E];let B;for(B=0;B<=D.length;B++)u[0][B]=B;for(E=1;E<=F.length;E++)for(B=1;B<=D.length;B++)if(F.charAt(E-1)===D.charAt(B-1))u[E][B]=u[E-1][B-1];else if(E>1&&B>1&&F.charAt(E-2)===D.charAt(B-1)&&F.charAt(E-1)===D.charAt(B-2))u[E][B]=u[E-2][B-2]+1;else u[E][B]=Math.min(u[E-1][B-1]+1,Math.min(u[E][B-1]+1,u[E-1][B]+1));return u[F.length][D.length]}var X3=["$0","--","_"];function Z3(D,F,u){let E=u.y18n.__,B=u.y18n.__n,C={};C.nonOptionCount=function Y(W){let J=D.getDemandedCommands(),M=W._.length+(W["--"]?W["--"].length:0)-D.getInternalMethods().getContext().commands.length;if(J._&&(M<J._.min||M>J._.max)){if(M<J._.min)if(J._.minMsg!==void 0)F.fail(J._.minMsg?J._.minMsg.replace(/\$0/g,M.toString()).replace(/\$1/,J._.min.toString()):null);else F.fail(B("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",M,M.toString(),J._.min.toString()));else if(M>J._.max)if(J._.maxMsg!==void 0)F.fail(J._.maxMsg?J._.maxMsg.replace(/\$0/g,M.toString()).replace(/\$1/,J._.max.toString()):null);else F.fail(B("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",M,M.toString(),J._.max.toString()))}},C.positionalCount=function Y(W,J){if(J<W)F.fail(B("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",J,J+"",W+""))},C.requiredArguments=function Y(W,J){let q=null;for(let M of Object.keys(J))if(!Object.prototype.hasOwnProperty.call(W,M)||typeof W[M]==="undefined")q=q||{},q[M]=J[M];if(q){let M=[];for(let T of Object.keys(q)){let p=q[T];if(p&&M.indexOf(p)<0)M.push(p)}let G=M.length?`
86
- ${M.join(`
87
- `)}`:"";F.fail(B("Missing required argument: %s","Missing required arguments: %s",Object.keys(q).length,Object.keys(q).join(", ")+G))}},C.unknownArguments=function Y(W,J,q,M,G=!0){var T;let p=D.getInternalMethods().getCommandInstance().getCommands(),g=[],QD=D.getInternalMethods().getContext();if(Object.keys(W).forEach((V)=>{if(!X3.includes(V)&&!Object.prototype.hasOwnProperty.call(q,V)&&!Object.prototype.hasOwnProperty.call(D.getInternalMethods().getParseContext(),V)&&!C.isValidAndSomeAliasIsNotNew(V,J))g.push(V)}),G&&(QD.commands.length>0||p.length>0||M))W._.slice(QD.commands.length).forEach((V)=>{if(!p.includes(""+V))g.push(""+V)});if(G){let L=((T=D.getDemandedCommands()._)===null||T===void 0?void 0:T.max)||0,k=QD.commands.length+L;if(k<W._.length)W._.slice(k).forEach((d)=>{if(d=String(d),!QD.commands.includes(d)&&!g.includes(d))g.push(d)})}if(g.length)F.fail(B("Unknown argument: %s","Unknown arguments: %s",g.length,g.map((V)=>V.trim()?V:`"${V}"`).join(", ")))},C.unknownCommands=function Y(W){let J=D.getInternalMethods().getCommandInstance().getCommands(),q=[],M=D.getInternalMethods().getContext();if(M.commands.length>0||J.length>0)W._.slice(M.commands.length).forEach((G)=>{if(!J.includes(""+G))q.push(""+G)});if(q.length>0)return F.fail(B("Unknown command: %s","Unknown commands: %s",q.length,q.join(", "))),!0;else return!1},C.isValidAndSomeAliasIsNotNew=function Y(W,J){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;let q=D.parsed.newAliases;return[W,...J[W]].some((M)=>!Object.prototype.hasOwnProperty.call(q,M)||!q[W])},C.limitedChoices=function Y(W){let J=D.getOptions(),q={};if(!Object.keys(J.choices).length)return;Object.keys(W).forEach((T)=>{if(X3.indexOf(T)===-1&&Object.prototype.hasOwnProperty.call(J.choices,T))[].concat(W[T]).forEach((p)=>{if(J.choices[T].indexOf(p)===-1&&p!==void 0)q[T]=(q[T]||[]).concat(p)})});let M=Object.keys(q);if(!M.length)return;let G=E("Invalid values:");M.forEach((T)=>{G+=`
88
- ${E("Argument: %s, Given: %s, Choices: %s",T,F.stringifiedValues(q[T]),F.stringifiedValues(J.choices[T]))}`}),F.fail(G)};let $={};C.implies=function Y(W,J){if(N("<string|object> [array|number|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{C.implies(q,W[q])});else{if(D.global(W),!$[W])$[W]=[];if(Array.isArray(J))J.forEach((q)=>C.implies(W,q));else YD(J,void 0,u),$[W].push(J)}},C.getImplied=function Y(){return $};function X(Y,W){let J=Number(W);if(W=isNaN(J)?W:J,typeof W==="number")W=Y._.length>=W;else if(W.match(/^--no-.+/))W=W.match(/^--no-(.+)/)[1],W=!Object.prototype.hasOwnProperty.call(Y,W);else W=Object.prototype.hasOwnProperty.call(Y,W);return W}C.implications=function Y(W){let J=[];if(Object.keys($).forEach((q)=>{let M=q;($[q]||[]).forEach((G)=>{let T=M,p=G;if(T=X(W,T),G=X(W,G),T&&!G)J.push(` ${M} -> ${p}`)})}),J.length){let q=`${E("Implications failed:")}
89
- `;J.forEach((M)=>{q+=M}),F.fail(q)}};let Q={};C.conflicts=function Y(W,J){if(N("<string|object> [array|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{C.conflicts(q,W[q])});else{if(D.global(W),!Q[W])Q[W]=[];if(Array.isArray(J))J.forEach((q)=>C.conflicts(W,q));else Q[W].push(J)}},C.getConflicting=()=>Q,C.conflicting=function Y(W){if(Object.keys(W).forEach((J)=>{if(Q[J])Q[J].forEach((q)=>{if(q&&W[J]!==void 0&&W[q]!==void 0)F.fail(E("Arguments %s and %s are mutually exclusive",J,q))})}),D.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(Q).forEach((J)=>{Q[J].forEach((q)=>{if(q&&W[u.Parser.camelCase(J)]!==void 0&&W[u.Parser.camelCase(q)]!==void 0)F.fail(E("Arguments %s and %s are mutually exclusive",J,q))})})},C.recommendCommands=function Y(W,J){J=J.sort((T,p)=>p.length-T.length);let M=null,G=1/0;for(let T=0,p;(p=J[T])!==void 0;T++){let g=$3(W,p);if(g<=3&&g<G)G=g,M=p}if(M)F.fail(E("Did you mean %s?",M))},C.reset=function Y(W){return $=fD($,(J)=>!W[J]),Q=fD(Q,(J)=>!W[J]),C};let z=[];return C.freeze=function Y(){z.push({implied:$,conflicting:Q})},C.unfreeze=function Y(){let W=z.pop();YD(W,void 0,u),{implied:$,conflicting:Q}=W},C}var oF=[],U0;function L0(D,F,u,E){U0=E;let B={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return B;let C=/\.json|\..*rc$/.test(D.extends),$=null;if(!C)try{$=import.meta.resolve(D.extends)}catch(X){return D}else $=f8(F,D.extends);k8($),oF.push($),B=C?JSON.parse(U0.readFileSync($,"utf8")):E.require(D.extends),delete D.extends,B=L0(B,U0.path.dirname($),u,U0)}return oF=[],u?Q3(B,D):Object.assign({},B,D)}function k8(D){if(oF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function f8(D,F){return U0.path.resolve(D,F)}function Q3(D,F){let u={};function E(B){return B&&typeof B==="object"&&!Array.isArray(B)}Object.assign(u,D);for(let B of Object.keys(F))if(E(F[B])&&E(u[B]))u[B]=Q3(D[B],F[B]);else u[B]=F[B];return u}var j=function(D,F,u,E,B){if(E==="m")throw new TypeError("Private method is not writable");if(E==="a"&&!B)throw new TypeError("Private accessor was defined without a setter");if(typeof F==="function"?D!==F||!B:!F.has(D))throw new TypeError("Cannot write private member to an object whose class did not declare it");return E==="a"?B.call(D,u):B?B.value=u:F.set(D,u),u},Z=function(D,F,u,E){if(u==="a"&&!E)throw new TypeError("Private accessor was defined without a getter");if(typeof F==="function"?D!==F||!E:!F.has(D))throw new TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?E:u==="a"?E.call(D):E?E.value:F.get(D)},FD,iD,N0,JD,AD,p0,dD,tD,g0,MD,m0,_D,wD,GD,KD,l0,sD,ZD,x,c0,o0,HD,rD,Y0,aD,hD,n0,f,eD,D0,F0,h,i0,TD,a;function T3(D){return(F=[],u=D.process.cwd(),E)=>{let B=new I3(F,u,E,D);return Object.defineProperty(B,"argv",{get:()=>{return B.parse()},enumerable:!0}),B.help(),B.version(),B}}var z3=Symbol("copyDoubleDash"),O3=Symbol("copyDoubleDash"),nF=Symbol("deleteFromParserHintObject"),Y3=Symbol("emitWarning"),J3=Symbol("freeze"),W3=Symbol("getDollarZero"),u0=Symbol("getParserConfiguration"),A3=Symbol("getUsageConfiguration"),iF=Symbol("guessLocale"),G3=Symbol("guessVersion"),H3=Symbol("parsePositionalNumbers"),tF=Symbol("pkgUp"),pD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),sF=Symbol("populateParserHintArrayDictionary"),rF=Symbol("populateParserHintDictionary"),aF=Symbol("sanitizeKey"),eF=Symbol("setKey"),D2=Symbol("unfreeze"),q3=Symbol("validateAsync"),M3=Symbol("getCommandInstance"),_3=Symbol("getContext"),K3=Symbol("getHasOutput"),V3=Symbol("getLoggerInstance"),R3=Symbol("getParseContext"),U3=Symbol("getUsageInstance"),L3=Symbol("getValidationInstance"),t0=Symbol("hasParseCallback"),N3=Symbol("isGlobalContext"),E0=Symbol("postProcess"),j3=Symbol("rebase"),F2=Symbol("reset"),j0=Symbol("runYargsParserAndExecuteCommands"),u2=Symbol("runValidation"),w3=Symbol("setHasOutput"),B0=Symbol("kTrackManuallySetKeys"),y8="en_US";class I3{constructor(D=[],F,u,E){this.customScriptName=!1,this.parsed=!1,FD.set(this,void 0),iD.set(this,void 0),N0.set(this,{commands:[],fullCommands:[]}),JD.set(this,null),AD.set(this,null),p0.set(this,"show-hidden"),dD.set(this,null),tD.set(this,!0),g0.set(this,{}),MD.set(this,!0),m0.set(this,[]),_D.set(this,void 0),wD.set(this,{}),GD.set(this,!1),KD.set(this,null),l0.set(this,!0),sD.set(this,void 0),ZD.set(this,""),x.set(this,void 0),c0.set(this,void 0),o0.set(this,{}),HD.set(this,null),rD.set(this,null),Y0.set(this,{}),aD.set(this,{}),hD.set(this,void 0),n0.set(this,!1),f.set(this,void 0),eD.set(this,!1),D0.set(this,!1),F0.set(this,!1),h.set(this,void 0),i0.set(this,{}),TD.set(this,null),a.set(this,void 0),j(this,f,E,"f"),j(this,hD,D,"f"),j(this,iD,F,"f"),j(this,c0,u,"f"),j(this,_D,new lF(this),"f"),this.$0=this[W3](),this[F2](),j(this,FD,Z(this,FD,"f"),"f"),j(this,h,Z(this,h,"f"),"f"),j(this,a,Z(this,a,"f"),"f"),j(this,x,Z(this,x,"f"),"f"),Z(this,x,"f").showHiddenOpt=Z(this,p0,"f"),j(this,sD,this[O3](),"f"),Z(this,f,"f").y18n.setLocale(y8)}addHelpOpt(D,F){if(N("[string|boolean] [string]",[D,F],arguments.length),Z(this,KD,"f"))this[nF](Z(this,KD,"f")),j(this,KD,null,"f");if(D===!1&&F===void 0)return this;return j(this,KD,typeof D==="string"?D:"help","f"),this.boolean(Z(this,KD,"f")),this.describe(Z(this,KD,"f"),F||Z(this,h,"f").deferY18nLookup("Show help")),this}help(D,F){return this.addHelpOpt(D,F)}addShowHiddenOpt(D,F){if(N("[string|boolean] [string]",[D,F],arguments.length),D===!1&&F===void 0)return this;let u=typeof D==="string"?D:Z(this,p0,"f");return this.boolean(u),this.describe(u,F||Z(this,h,"f").deferY18nLookup("Show hidden options")),Z(this,x,"f").showHiddenOpt=u,this}showHidden(D,F){return this.addShowHiddenOpt(D,F)}alias(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[sF](this.alias.bind(this),"alias",D,F),this}array(D){return N("<array|string>",[D],arguments.length),this[pD]("array",D),this[B0](D),this}boolean(D){return N("<array|string>",[D],arguments.length),this[pD]("boolean",D),this[B0](D),this}check(D,F){return N("<function> [boolean]",[D,F],arguments.length),this.middleware((u,E)=>{return nD(()=>{return D(u,E.getOptions())},(B)=>{if(!B)Z(this,h,"f").fail(Z(this,f,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof B==="string"||B instanceof Error)Z(this,h,"f").fail(B.toString(),B);return u},(B)=>{return Z(this,h,"f").fail(B.message?B.message:B.toString(),B),u})},!1,F),this}choices(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[sF](this.choices.bind(this),"choices",D,F),this}coerce(D,F){if(N("<object|string|array> [function]",[D,F],arguments.length),Array.isArray(D)){if(!F)throw new DD("coerce callback must be provided");for(let E of D)this.coerce(E,F);return this}else if(typeof D==="object"){for(let E of Object.keys(D))this.coerce(E,D[E]);return this}if(!F)throw new DD("coerce callback must be provided");let u=D;return Z(this,x,"f").key[u]=!0,Z(this,_D,"f").addCoerceMiddleware((E,B)=>{var C;let $=(C=B.getAliases()[u])!==null&&C!==void 0?C:[],X=[u,...$].filter((Q)=>Object.prototype.hasOwnProperty.call(E,Q));if(X.length===0)return E;return nD(()=>{return F(E[X[0]])},(Q)=>{return X.forEach((z)=>{E[z]=Q}),E},(Q)=>{throw new DD(Q.message)})},u),this}conflicts(D,F){return N("<string|object> [string|array]",[D,F],arguments.length),Z(this,a,"f").conflicts(D,F),this}config(D="config",F,u){if(N("[object|string] [string|function] [function]",[D,F,u],arguments.length),typeof D==="object"&&!Array.isArray(D))return D=L0(D,Z(this,iD,"f"),this[u0]()["deep-merge-config"]||!1,Z(this,f,"f")),Z(this,x,"f").configObjects=(Z(this,x,"f").configObjects||[]).concat(D),this;if(typeof F==="function")u=F,F=void 0;return this.describe(D,F||Z(this,h,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(D)?D:[D]).forEach((E)=>{Z(this,x,"f").config[E]=u||!0}),this}completion(D,F,u){if(N("[string] [string|boolean|function] [function]",[D,F,u],arguments.length),typeof F==="function")u=F,F=void 0;if(j(this,AD,D||Z(this,AD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(Z(this,AD,"f"),F),u)Z(this,JD,"f").registerFunction(u);return this}command(D,F,u,E,B,C){return N("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,u,E,B,C],arguments.length),Z(this,FD,"f").addHandler(D,F,u,E,B,C),this}commands(D,F,u,E,B,C){return this.command(D,F,u,E,B,C)}commandDir(D,F){N("<string> [object]",[D,F],arguments.length);let u=Z(this,c0,"f")||Z(this,f,"f").require;return Z(this,FD,"f").addDirectory(D,u,Z(this,f,"f").getCallerFile(),F),this}count(D){return N("<array|string>",[D],arguments.length),this[pD]("count",D),this[B0](D),this}default(D,F,u){if(N("<object|string|array> [*] [string]",[D,F,u],arguments.length),u)mF(D,Z(this,f,"f")),Z(this,x,"f").defaultDescription[D]=u;if(typeof F==="function"){if(mF(D,Z(this,f,"f")),!Z(this,x,"f").defaultDescription[D])Z(this,x,"f").defaultDescription[D]=Z(this,h,"f").functionDescription(F);F=F.call()}return this[J0](this.default.bind(this),"default",D,F),this}defaults(D,F,u){return this.default(D,F,u)}demandCommand(D=1,F,u,E){if(N("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,u,E],arguments.length),typeof F!=="number")u=F,F=1/0;return this.global("_",!1),Z(this,x,"f").demandedCommands._={min:D,max:F,minMsg:u,maxMsg:E},this}demand(D,F,u){if(Array.isArray(F))F.forEach((E)=>{YD(u,!0,Z(this,f,"f")),this.demandOption(E,u)}),F=1/0;else if(typeof F!=="number")u=F,F=1/0;if(typeof D==="number")YD(u,!0,Z(this,f,"f")),this.demandCommand(D,F,u,u);else if(Array.isArray(D))D.forEach((E)=>{YD(u,!0,Z(this,f,"f")),this.demandOption(E,u)});else if(typeof u==="string")this.demandOption(D,u);else if(u===!0||typeof u==="undefined")this.demandOption(D);return this}demandOption(D,F){return N("<object|string|array> [string]",[D,F],arguments.length),this[J0](this.demandOption.bind(this),"demandedOptions",D,F),this}deprecateOption(D,F){return N("<string> [string|boolean]",[D,F],arguments.length),Z(this,x,"f").deprecatedOptions[D]=F,this}describe(D,F){return N("<object|string|array> [string]",[D,F],arguments.length),this[eF](D,!0),Z(this,h,"f").describe(D,F),this}detectLocale(D){return N("<boolean>",[D],arguments.length),j(this,tD,D,"f"),this}env(D){if(N("[string|boolean]",[D],arguments.length),D===!1)delete Z(this,x,"f").envPrefix;else Z(this,x,"f").envPrefix=D||"";return this}epilogue(D){return N("<string>",[D],arguments.length),Z(this,h,"f").epilog(D),this}epilog(D){return this.epilogue(D)}example(D,F){if(N("<string|array> [string]",[D,F],arguments.length),Array.isArray(D))D.forEach((u)=>this.example(...u));else Z(this,h,"f").example(D,F);return this}exit(D,F){if(j(this,GD,!0,"f"),j(this,dD,F,"f"),Z(this,MD,"f"))Z(this,f,"f").process.exit(D)}exitProcess(D=!0){return N("[boolean]",[D],arguments.length),j(this,MD,D,"f"),this}fail(D){if(N("<function|boolean>",[D],arguments.length),typeof D==="boolean"&&D!==!1)throw new DD("Invalid first argument. Expected function or boolean 'false'");return Z(this,h,"f").failFn(D),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(D,F){if(N("<array> [function]",[D,F],arguments.length),!F)return new Promise((u,E)=>{Z(this,JD,"f").getCompletion(D,(B,C)=>{if(B)E(B);else u(C)})});else return Z(this,JD,"f").getCompletion(D,F)}getDemandedOptions(){return N([],0),Z(this,x,"f").demandedOptions}getDemandedCommands(){return N([],0),Z(this,x,"f").demandedCommands}getDeprecatedOptions(){return N([],0),Z(this,x,"f").deprecatedOptions}getDetectLocale(){return Z(this,tD,"f")}getExitProcess(){return Z(this,MD,"f")}getGroups(){return Object.assign({},Z(this,wD,"f"),Z(this,aD,"f"))}getHelp(){if(j(this,GD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[j0](Z(this,hD,"f"),void 0,void 0,0,!0);if(s(F))return F.then(()=>{return Z(this,h,"f").help()})}let D=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(D))return D.then(()=>{return Z(this,h,"f").help()})}return Promise.resolve(Z(this,h,"f").help())}getOptions(){return Z(this,x,"f")}getStrict(){return Z(this,eD,"f")}getStrictCommands(){return Z(this,D0,"f")}getStrictOptions(){return Z(this,F0,"f")}global(D,F){if(N("<string|array> [boolean]",[D,F],arguments.length),D=[].concat(D),F!==!1)Z(this,x,"f").local=Z(this,x,"f").local.filter((u)=>D.indexOf(u)===-1);else D.forEach((u)=>{if(!Z(this,x,"f").local.includes(u))Z(this,x,"f").local.push(u)});return this}group(D,F){N("<string|array> <string>",[D,F],arguments.length);let u=Z(this,aD,"f")[F]||Z(this,wD,"f")[F];if(Z(this,aD,"f")[F])delete Z(this,aD,"f")[F];let E={};return Z(this,wD,"f")[F]=(u||[]).concat(D).filter((B)=>{if(E[B])return!1;return E[B]=!0}),this}hide(D){return N("<string>",[D],arguments.length),Z(this,x,"f").hiddenOptions.push(D),this}implies(D,F){return N("<string|object> [number|string|array]",[D,F],arguments.length),Z(this,a,"f").implies(D,F),this}locale(D){if(N("[string]",[D],arguments.length),D===void 0)return this[iF](),Z(this,f,"f").y18n.getLocale();return j(this,tD,!1,"f"),Z(this,f,"f").y18n.setLocale(D),this}middleware(D,F,u){return Z(this,_D,"f").addMiddleware(D,!!F,u)}nargs(D,F){return N("<string|object|array> [number]",[D,F],arguments.length),this[J0](this.nargs.bind(this),"narg",D,F),this}normalize(D){return N("<array|string>",[D],arguments.length),this[pD]("normalize",D),this}number(D){return N("<array|string>",[D],arguments.length),this[pD]("number",D),this[B0](D),this}option(D,F){if(N("<string|object> [object]",[D,F],arguments.length),typeof D==="object")Object.keys(D).forEach((u)=>{this.options(u,D[u])});else{if(typeof F!=="object")F={};if(this[B0](D),Z(this,TD,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[Y3](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
90
- `),void 0,"versionWarning");if(Z(this,x,"f").key[D]=!0,F.alias)this.alias(D,F.alias);let u=F.deprecate||F.deprecated;if(u)this.deprecateOption(D,u);let E=F.demand||F.required||F.require;if(E)this.demand(D,E);if(F.demandOption)this.demandOption(D,typeof F.demandOption==="string"?F.demandOption:void 0);if(F.conflicts)this.conflicts(D,F.conflicts);if("default"in F)this.default(D,F.default);if(F.implies!==void 0)this.implies(D,F.implies);if(F.nargs!==void 0)this.nargs(D,F.nargs);if(F.config)this.config(D,F.configParser);if(F.normalize)this.normalize(D);if(F.choices)this.choices(D,F.choices);if(F.coerce)this.coerce(D,F.coerce);if(F.group)this.group(D,F.group);if(F.boolean||F.type==="boolean"){if(this.boolean(D),F.alias)this.boolean(F.alias)}if(F.array||F.type==="array"){if(this.array(D),F.alias)this.array(F.alias)}if(F.number||F.type==="number"){if(this.number(D),F.alias)this.number(F.alias)}if(F.string||F.type==="string"){if(this.string(D),F.alias)this.string(F.alias)}if(F.count||F.type==="count")this.count(D);if(typeof F.global==="boolean")this.global(D,F.global);if(F.defaultDescription)Z(this,x,"f").defaultDescription[D]=F.defaultDescription;if(F.skipValidation)this.skipValidation(D);let B=F.describe||F.description||F.desc,C=Z(this,h,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(C,D)||typeof B==="string")this.describe(D,B);if(F.hidden)this.hide(D);if(F.requiresArg)this.requiresArg(D)}return this}options(D,F){return this.option(D,F)}parse(D,F,u){if(N("[string|array] [function|boolean|object] [function]",[D,F,u],arguments.length),this[J3](),typeof D==="undefined")D=Z(this,hD,"f");if(typeof F==="object")j(this,rD,F,"f"),F=u;if(typeof F==="function")j(this,HD,F,"f"),F=!1;if(!F)j(this,hD,D,"f");if(Z(this,HD,"f"))j(this,MD,!1,"f");let E=this[j0](D,!!F),B=this.parsed;if(Z(this,JD,"f").setParsed(this.parsed),s(E))return E.then((C)=>{if(Z(this,HD,"f"))Z(this,HD,"f").call(this,Z(this,dD,"f"),C,Z(this,ZD,"f"));return C}).catch((C)=>{if(Z(this,HD,"f"))Z(this,HD,"f")(C,this.parsed.argv,Z(this,ZD,"f"));throw C}).finally(()=>{this[D2](),this.parsed=B});else{if(Z(this,HD,"f"))Z(this,HD,"f").call(this,Z(this,dD,"f"),E,Z(this,ZD,"f"));this[D2](),this.parsed=B}return E}parseAsync(D,F,u){let E=this.parse(D,F,u);return!s(E)?Promise.resolve(E):E}parseSync(D,F,u){let E=this.parse(D,F,u);if(s(E))throw new DD(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return E}parserConfiguration(D){return N("<object>",[D],arguments.length),j(this,o0,D,"f"),this}pkgConf(D,F){N("<string> [string]",[D,F],arguments.length);let u=null,E=this[tF](F||Z(this,iD,"f"));if(E[D]&&typeof E[D]==="object")u=L0(E[D],F||Z(this,iD,"f"),this[u0]()["deep-merge-config"]||!1,Z(this,f,"f")),Z(this,x,"f").configObjects=(Z(this,x,"f").configObjects||[]).concat(u);return this}positional(D,F){N("<string> <object>",[D,F],arguments.length);let u=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];F=fD(F,(C,$)=>{if(C==="type"&&!["string","number","boolean"].includes($))return!1;return u.includes(C)});let E=Z(this,N0,"f").fullCommands[Z(this,N0,"f").fullCommands.length-1],B=E?Z(this,FD,"f").cmdToParseOptions(E):{array:[],alias:{},default:{},demand:{}};return z0(B).forEach((C)=>{let $=B[C];if(Array.isArray($)){if($.indexOf(D)!==-1)F[C]=!0}else if($[D]&&!(C in F))F[C]=$[D]}),this.group(D,Z(this,h,"f").getPositionalGroupName()),this.option(D,F)}recommendCommands(D=!0){return N("[boolean]",[D],arguments.length),j(this,n0,D,"f"),this}required(D,F,u){return this.demand(D,F,u)}require(D,F,u){return this.demand(D,F,u)}requiresArg(D){if(N("<array|string|object> [number]",[D],arguments.length),typeof D==="string"&&Z(this,x,"f").narg[D])return this;else this[J0](this.requiresArg.bind(this),"narg",D,NaN);return this}showCompletionScript(D,F){return N("[string] [string]",[D,F],arguments.length),D=D||this.$0,Z(this,sD,"f").log(Z(this,JD,"f").generateCompletionScript(D,F||Z(this,AD,"f")||"completion")),this}showHelp(D){if(N("[string|function]",[D],arguments.length),j(this,GD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let u=this[j0](Z(this,hD,"f"),void 0,void 0,0,!0);if(s(u))return u.then(()=>{Z(this,h,"f").showHelp(D)}),this}let F=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(F))return F.then(()=>{Z(this,h,"f").showHelp(D)}),this}return Z(this,h,"f").showHelp(D),this}scriptName(D){return this.customScriptName=!0,this.$0=D,this}showHelpOnFail(D,F){return N("[boolean|string] [string]",[D,F],arguments.length),Z(this,h,"f").showHelpOnFail(D,F),this}showVersion(D){return N("[string|function]",[D],arguments.length),Z(this,h,"f").showVersion(D),this}skipValidation(D){return N("<array|string>",[D],arguments.length),this[pD]("skipValidation",D),this}strict(D){return N("[boolean]",[D],arguments.length),j(this,eD,D!==!1,"f"),this}strictCommands(D){return N("[boolean]",[D],arguments.length),j(this,D0,D!==!1,"f"),this}strictOptions(D){return N("[boolean]",[D],arguments.length),j(this,F0,D!==!1,"f"),this}string(D){return N("<array|string>",[D],arguments.length),this[pD]("string",D),this[B0](D),this}terminalWidth(){return N([],0),Z(this,f,"f").process.stdColumns}updateLocale(D){return this.updateStrings(D)}updateStrings(D){return N("<object>",[D],arguments.length),j(this,tD,!1,"f"),Z(this,f,"f").y18n.updateLocale(D),this}usage(D,F,u,E){if(N("<string|null|undefined> [string|boolean] [function|object] [function]",[D,F,u,E],arguments.length),F!==void 0)if(YD(D,null,Z(this,f,"f")),(D||"").match(/^\$0( |$)/))return this.command(D,F,u,E);else throw new DD(".usage() description must start with $0 if being used as alias for .command()");else return Z(this,h,"f").usage(D),this}usageConfiguration(D){return N("<object>",[D],arguments.length),j(this,i0,D,"f"),this}version(D,F,u){if(N("[boolean|string] [string] [string]",[D,F,u],arguments.length),Z(this,TD,"f"))this[nF](Z(this,TD,"f")),Z(this,h,"f").version(void 0),j(this,TD,null,"f");if(arguments.length===0)u=this[G3](),D="version";else if(arguments.length===1){if(D===!1)return this;u=D,D="version"}else if(arguments.length===2)u=F,F=void 0;return j(this,TD,typeof D==="string"?D:"version","f"),F=F||Z(this,h,"f").deferY18nLookup("Show version number"),Z(this,h,"f").version(u||void 0),this.boolean(Z(this,TD,"f")),this.describe(Z(this,TD,"f"),F),this}wrap(D){return N("<number|null|undefined>",[D],arguments.length),Z(this,h,"f").wrap(D),this}[(FD=new WeakMap,iD=new WeakMap,N0=new WeakMap,JD=new WeakMap,AD=new WeakMap,p0=new WeakMap,dD=new WeakMap,tD=new WeakMap,g0=new WeakMap,MD=new WeakMap,m0=new WeakMap,_D=new WeakMap,wD=new WeakMap,GD=new WeakMap,KD=new WeakMap,l0=new WeakMap,sD=new WeakMap,ZD=new WeakMap,x=new WeakMap,c0=new WeakMap,o0=new WeakMap,HD=new WeakMap,rD=new WeakMap,Y0=new WeakMap,aD=new WeakMap,hD=new WeakMap,n0=new WeakMap,f=new WeakMap,eD=new WeakMap,D0=new WeakMap,F0=new WeakMap,h=new WeakMap,i0=new WeakMap,TD=new WeakMap,a=new WeakMap,z3)](D){if(!D._||!D["--"])return D;D._.push.apply(D._,D["--"]);try{delete D["--"]}catch(F){}return D}[O3](){return{log:(...D)=>{if(!this[t0]())console.log(...D);if(j(this,GD,!0,"f"),Z(this,ZD,"f").length)j(this,ZD,Z(this,ZD,"f")+`
91
- `,"f");j(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")},error:(...D)=>{if(!this[t0]())console.error(...D);if(j(this,GD,!0,"f"),Z(this,ZD,"f").length)j(this,ZD,Z(this,ZD,"f")+`
92
- `,"f");j(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")}}}[nF](D){z0(Z(this,x,"f")).forEach((F)=>{if(((E)=>E==="configObjects")(F))return;let u=Z(this,x,"f")[F];if(Array.isArray(u)){if(u.includes(D))u.splice(u.indexOf(D),1)}else if(typeof u==="object")delete u[D]}),delete Z(this,h,"f").getDescriptions()[D]}[Y3](D,F,u){if(!Z(this,g0,"f")[u])Z(this,f,"f").process.emitWarning(D,F),Z(this,g0,"f")[u]=!0}[J3](){Z(this,m0,"f").push({options:Z(this,x,"f"),configObjects:Z(this,x,"f").configObjects.slice(0),exitProcess:Z(this,MD,"f"),groups:Z(this,wD,"f"),strict:Z(this,eD,"f"),strictCommands:Z(this,D0,"f"),strictOptions:Z(this,F0,"f"),completionCommand:Z(this,AD,"f"),output:Z(this,ZD,"f"),exitError:Z(this,dD,"f"),hasOutput:Z(this,GD,"f"),parsed:this.parsed,parseFn:Z(this,HD,"f"),parseContext:Z(this,rD,"f")}),Z(this,h,"f").freeze(),Z(this,a,"f").freeze(),Z(this,FD,"f").freeze(),Z(this,_D,"f").freeze()}[W3](){let D="",F;if(/\b(node|iojs|electron)(\.exe)?$/.test(Z(this,f,"f").process.argv()[0]))F=Z(this,f,"f").process.argv().slice(1,2);else F=Z(this,f,"f").process.argv().slice(0,1);if(D=F.map((u)=>{let E=this[j3](Z(this,iD,"f"),u);return u.match(/^(\/|([a-zA-Z]:)?\\)/)&&E.length<u.length?E:u}).join(" ").trim(),Z(this,f,"f").getEnv("_")&&Z(this,f,"f").getProcessArgvBin()===Z(this,f,"f").getEnv("_"))D=Z(this,f,"f").getEnv("_").replace(`${Z(this,f,"f").path.dirname(Z(this,f,"f").process.execPath())}/`,"");return D}[u0](){return Z(this,o0,"f")}[A3](){return Z(this,i0,"f")}[iF](){if(!Z(this,tD,"f"))return;let D=Z(this,f,"f").getEnv("LC_ALL")||Z(this,f,"f").getEnv("LC_MESSAGES")||Z(this,f,"f").getEnv("LANG")||Z(this,f,"f").getEnv("LANGUAGE")||"en_US";this.locale(D.replace(/[.:].*/,""))}[G3](){return this[tF]().version||"unknown"}[H3](D){let F=D["--"]?D["--"]:D._;for(let u=0,E;(E=F[u])!==void 0;u++)if(Z(this,f,"f").Parser.looksLikeNumber(E)&&Number.isSafeInteger(Math.floor(parseFloat(`${E}`))))F[u]=Number(E);return D}[tF](D){let F=D||"*";if(Z(this,Y0,"f")[F])return Z(this,Y0,"f")[F];let u={};try{let E=D||Z(this,f,"f").mainFilename;if(Z(this,f,"f").path.extname(E))E=Z(this,f,"f").path.dirname(E);let B=Z(this,f,"f").findUp(E,(C,$)=>{if($.includes("package.json"))return"package.json";else return});YD(B,void 0,Z(this,f,"f")),u=JSON.parse(Z(this,f,"f").readFileSync(B,"utf8"))}catch(E){}return Z(this,Y0,"f")[F]=u||{},Z(this,Y0,"f")[F]}[pD](D,F){F=[].concat(F),F.forEach((u)=>{u=this[aF](u),Z(this,x,"f")[D].push(u)})}[J0](D,F,u,E){this[rF](D,F,u,E,(B,C,$)=>{Z(this,x,"f")[B][C]=$})}[sF](D,F,u,E){this[rF](D,F,u,E,(B,C,$)=>{Z(this,x,"f")[B][C]=(Z(this,x,"f")[B][C]||[]).concat($)})}[rF](D,F,u,E,B){if(Array.isArray(u))u.forEach((C)=>{D(C,E)});else if(((C)=>typeof C==="object")(u))for(let C of z0(u))D(C,u[C]);else B(F,this[aF](u),E)}[aF](D){if(D==="__proto__")return"___proto___";return D}[eF](D,F){return this[J0](this[eF].bind(this),"key",D,F),this}[D2](){var D,F,u,E,B,C,$,X,Q,z,Y,W;let J=Z(this,m0,"f").pop();YD(J,void 0,Z(this,f,"f"));let q;D=this,F=this,u=this,E=this,B=this,C=this,$=this,X=this,Q=this,z=this,Y=this,W=this,{options:{set value(M){j(D,x,M,"f")}}.value,configObjects:q,exitProcess:{set value(M){j(F,MD,M,"f")}}.value,groups:{set value(M){j(u,wD,M,"f")}}.value,output:{set value(M){j(E,ZD,M,"f")}}.value,exitError:{set value(M){j(B,dD,M,"f")}}.value,hasOutput:{set value(M){j(C,GD,M,"f")}}.value,parsed:this.parsed,strict:{set value(M){j($,eD,M,"f")}}.value,strictCommands:{set value(M){j(X,D0,M,"f")}}.value,strictOptions:{set value(M){j(Q,F0,M,"f")}}.value,completionCommand:{set value(M){j(z,AD,M,"f")}}.value,parseFn:{set value(M){j(Y,HD,M,"f")}}.value,parseContext:{set value(M){j(W,rD,M,"f")}}.value}=J,Z(this,x,"f").configObjects=q,Z(this,h,"f").unfreeze(),Z(this,a,"f").unfreeze(),Z(this,FD,"f").unfreeze(),Z(this,_D,"f").unfreeze()}[q3](D,F){return nD(F,(u)=>{return D(u),u})}getInternalMethods(){return{getCommandInstance:this[M3].bind(this),getContext:this[_3].bind(this),getHasOutput:this[K3].bind(this),getLoggerInstance:this[V3].bind(this),getParseContext:this[R3].bind(this),getParserConfiguration:this[u0].bind(this),getUsageConfiguration:this[A3].bind(this),getUsageInstance:this[U3].bind(this),getValidationInstance:this[L3].bind(this),hasParseCallback:this[t0].bind(this),isGlobalContext:this[N3].bind(this),postProcess:this[E0].bind(this),reset:this[F2].bind(this),runValidation:this[u2].bind(this),runYargsParserAndExecuteCommands:this[j0].bind(this),setHasOutput:this[w3].bind(this)}}[M3](){return Z(this,FD,"f")}[_3](){return Z(this,N0,"f")}[K3](){return Z(this,GD,"f")}[V3](){return Z(this,sD,"f")}[R3](){return Z(this,rD,"f")||{}}[U3](){return Z(this,h,"f")}[L3](){return Z(this,a,"f")}[t0](){return!!Z(this,HD,"f")}[N3](){return Z(this,l0,"f")}[E0](D,F,u,E){if(u)return D;if(s(D))return D;if(!F)D=this[z3](D);if(this[u0]()["parse-positional-numbers"]||this[u0]()["parse-positional-numbers"]===void 0)D=this[H3](D);if(E)D=oD(D,this,Z(this,_D,"f").getMiddleware(),!1);return D}[F2](D={}){j(this,x,Z(this,x,"f")||{},"f");let F={};F.local=Z(this,x,"f").local||[],F.configObjects=Z(this,x,"f").configObjects||[];let u={};F.local.forEach((C)=>{u[C]=!0,(D[C]||[]).forEach(($)=>{u[$]=!0})}),Object.assign(Z(this,aD,"f"),Object.keys(Z(this,wD,"f")).reduce((C,$)=>{let X=Z(this,wD,"f")[$].filter((Q)=>!(Q in u));if(X.length>0)C[$]=X;return C},{})),j(this,wD,{},"f");let E=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],B=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(E.forEach((C)=>{F[C]=(Z(this,x,"f")[C]||[]).filter(($)=>!u[$])}),B.forEach((C)=>{F[C]=fD(Z(this,x,"f")[C],($)=>!u[$])}),F.envPrefix=Z(this,x,"f").envPrefix,j(this,x,F,"f"),j(this,h,Z(this,h,"f")?Z(this,h,"f").reset(u):F3(this,Z(this,f,"f")),"f"),j(this,a,Z(this,a,"f")?Z(this,a,"f").reset(u):Z3(this,Z(this,h,"f"),Z(this,f,"f")),"f"),j(this,FD,Z(this,FD,"f")?Z(this,FD,"f").reset():a1(Z(this,h,"f"),Z(this,a,"f"),Z(this,_D,"f"),Z(this,f,"f")),"f"),!Z(this,JD,"f"))j(this,JD,C3(this,Z(this,h,"f"),Z(this,FD,"f"),Z(this,f,"f")),"f");return Z(this,_D,"f").reset(),j(this,AD,null,"f"),j(this,ZD,"","f"),j(this,dD,null,"f"),j(this,GD,!1,"f"),this.parsed=!1,this}[j3](D,F){return Z(this,f,"f").path.relative(D,F)}[j0](D,F,u,E=0,B=!1){var C,$,X,Q;let z=!!u||B;D=D||Z(this,hD,"f"),Z(this,x,"f").__=Z(this,f,"f").y18n.__,Z(this,x,"f").configuration=this[u0]();let Y=!!Z(this,x,"f").configuration["populate--"],W=Object.assign({},Z(this,x,"f").configuration,{"populate--":!0}),J=Z(this,f,"f").Parser.detailed(D,Object.assign({},Z(this,x,"f"),{configuration:{"parse-positional-numbers":!1,...W}})),q=Object.assign(J.argv,Z(this,rD,"f")),M=void 0,G=J.aliases,T=!1,p=!1;if(Object.keys(q).forEach((g)=>{if(g===Z(this,KD,"f")&&q[g])T=!0;else if(g===Z(this,TD,"f")&&q[g])p=!0}),q.$0=this.$0,this.parsed=J,E===0)Z(this,h,"f").clearCachedHelpMessage();try{if(this[iF](),F)return this[E0](q,Y,!!u,!1);if(Z(this,KD,"f")){if([Z(this,KD,"f")].concat(G[Z(this,KD,"f")]||[]).filter((k)=>k.length>1).includes(""+q._[q._.length-1]))q._.pop(),T=!0}j(this,l0,!1,"f");let g=Z(this,FD,"f").getCommands(),QD=((C=Z(this,JD,"f"))===null||C===void 0?void 0:C.completionKey)?[($=Z(this,JD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(X=Z(this,JD,"f"))===null||X===void 0?void 0:X.completionKey])!==null&&Q!==void 0?Q:[]].some((L)=>Object.prototype.hasOwnProperty.call(q,L)):!1,V=T||QD||B;if(q._.length){if(g.length){let L;for(let k=E||0,d;q._[k]!==void 0;k++)if(d=String(q._[k]),g.includes(d)&&d!==Z(this,AD,"f")){let t=Z(this,FD,"f").runCommand(d,this,J,k+1,B,T||p||B);return this[E0](t,Y,!!u,!1)}else if(!L&&d!==Z(this,AD,"f")){L=d;break}if(!Z(this,FD,"f").hasDefaultCommand()&&Z(this,n0,"f")&&L&&!V)Z(this,a,"f").recommendCommands(L,g)}if(Z(this,AD,"f")&&q._.includes(Z(this,AD,"f"))&&!QD){if(Z(this,MD,"f"))yD(!0);this.showCompletionScript(),this.exit(0)}}if(Z(this,FD,"f").hasDefaultCommand()&&!V){let L=Z(this,FD,"f").runCommand(null,this,J,0,B,T||p||B);return this[E0](L,Y,!!u,!1)}if(QD){if(Z(this,MD,"f"))yD(!0);D=[].concat(D);let L=D.slice(D.indexOf(`--${Z(this,JD,"f").completionKey}`)+1);return Z(this,JD,"f").getCompletion(L,(k,d)=>{if(k)throw new DD(k.message);(d||[]).forEach((t)=>{Z(this,sD,"f").log(t)}),this.exit(0)}),this[E0](q,!Y,!!u,!1)}if(!Z(this,GD,"f")){if(T){if(Z(this,MD,"f"))yD(!0);z=!0,this.showHelp((L)=>{Z(this,sD,"f").log(L),this.exit(0)})}else if(p){if(Z(this,MD,"f"))yD(!0);z=!0,Z(this,h,"f").showVersion("log"),this.exit(0)}}if(!z&&Z(this,x,"f").skipValidation.length>0)z=Object.keys(q).some((L)=>Z(this,x,"f").skipValidation.indexOf(L)>=0&&q[L]===!0);if(!z){if(J.error)throw new DD(J.error.message);if(!QD){let L=this[u2](G,{},J.error);if(!u)M=oD(q,this,Z(this,_D,"f").getMiddleware(),!0);if(M=this[q3](L,M!==null&&M!==void 0?M:q),s(M)&&!u)M=M.then(()=>{return oD(q,this,Z(this,_D,"f").getMiddleware(),!1)})}}}catch(g){if(g instanceof DD)Z(this,h,"f").fail(g.message,g);else throw g}return this[E0](M!==null&&M!==void 0?M:q,Y,!!u,!0)}[u2](D,F,u,E){let B={...this.getDemandedOptions()};return(C)=>{if(u)throw new DD(u.message);Z(this,a,"f").nonOptionCount(C),Z(this,a,"f").requiredArguments(C,B);let $=!1;if(Z(this,D0,"f"))$=Z(this,a,"f").unknownCommands(C);if(Z(this,eD,"f")&&!$)Z(this,a,"f").unknownArguments(C,D,F,!!E);else if(Z(this,F0,"f"))Z(this,a,"f").unknownArguments(C,D,{},!1,!1);Z(this,a,"f").limitedChoices(C),Z(this,a,"f").implications(C),Z(this,a,"f").conflicting(C)}}[w3](){j(this,GD,!0,"f")}[B0](D){if(typeof D==="string")Z(this,x,"f").key[D]=!0;else for(let F of D)Z(this,x,"f").key[F]=!0}}function e1(D){return!!D&&typeof D.getInternalMethods==="function"}var d8=T3(gF),b3=d8;import{performance as S3}from"node:perf_hooks";var gD=S0(B2(),1);class m8{total;message;current=0;barLength=30;startTime=S3.now();constructor(D,F){this.total=D;this.message=F}update(D,F){this.current=Math.min(D,this.total),this.render(F)}increment(D){this.update(this.current+1,D)}complete(D){this.current=this.total,this.render();let F=Math.round(S3.now()-this.startTime);console.log(gD.default.green(`✅ ${D||this.message} ${gD.default.gray(`(${F}ms)`)}`))}render(D){let F=Math.round(this.current/this.total*100),u=Math.round(this.current/this.total*this.barLength),E=this.barLength-u,B=gD.default.green("█".repeat(u))+gD.default.gray("░".repeat(E)),C=`${this.current}/${this.total}`,$=D?gD.default.gray(` ${D}`):"";if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(`${this.message} ${B} ${gD.default.cyan(C)} ${gD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
93
- `)}}var $D=S0(B2(),1);class a0{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,u){let E=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",B=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${E}${u(D)} ${B}${F}`}success(D){console.log(this.formatMessage("✅",D,$D.default.green))}error(D,F){if(console.error(this.formatMessage("❌",D,$D.default.red)),F&&this.options.verbose){if(console.error($D.default.red(` ${F.message}`)),F.stack)console.error($D.default.gray(F.stack))}}warn(D){console.warn(this.formatMessage("⚠️",D,$D.default.yellow))}info(D){console.log(this.formatMessage("ℹ️",D,$D.default.blue))}debug(D){if(this.options.verbose)console.log(this.formatMessage("\uD83D\uDC1B",D,$D.default.magenta))}step(D){console.log(this.formatMessage("\uD83D\uDE80",D,$D.default.cyan))}progress(D){console.log(this.formatMessage("⏳",D,$D.default.blue))}plain(D,F=(u)=>u){let u=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${u}${E}${F(D)}`)}dim(D){this.plain(D,$D.default.gray)}child(D){return new a0({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${D}`:D})}configure(D){this.options={...this.options,...D}}}var C0=new a0;function e0(D){C0.success(D)}function VD(D,F){C0.error(D,F)}function C2(D){C0.warn(D)}function DF(D){C0.info(D)}function $2(D){C0.step(D)}function v3(D){C0.dim(D)}function X2(D){C0.configure(D)}function LD(D={}){return new a0(D)}function Z2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function Q2(D,F,u){let E=D;if(F)E+=` ${$D.default.gray(`(${F}ms)`)}`;if(e0(E),u)Object.entries(u).forEach(([B,C])=>{v3(` ${B}: ${C}`)})}function $0(D,F="•"){D.forEach((u)=>{console.log($D.default.gray(` ${F} ${u}`))})}import{existsSync as mu}from"node:fs";import{resolve as lu}from"node:path";import{existsSync as FF,mkdirSync as k3}from"node:fs";import{readdir as f3,readFile as l8,stat as c8,unlink as y3,writeFile as o8}from"node:fs/promises";import{join as z2}from"node:path";class mD{cache=new Map;config;cacheDir;constructor(D){if(this.config={enablePersistence:!0,cacheDir:".typeschema-cache",maxAge:86400000,validateCached:!0,...D},this.config.enablePersistence&&this.config.cacheDir)this.cacheDir=this.config.cacheDir}async set(D){let F=this.generateKey(D.identifier);if(this.cache.set(F,D),this.config.enablePersistence&&this.cacheDir)await this.persistSchema(D)}get(D){let F=this.generateKey(D);return this.cache.get(F)||null}getByUrl(D){for(let F of this.cache.values())if(F.identifier.url===D)return F;return null}has(D){let F=this.generateKey(D);return this.cache.has(F)}hasByUrl(D){for(let F of this.cache.values())if(F.identifier.url===D)return!0;return!1}delete(D){let F=this.generateKey(D);return this.cache.delete(F)}deleteByUrl(D){for(let[F,u]of this.cache.entries())if(u.identifier.url===D)return this.cache.delete(F);return!1}getByPackage(D){let F=[];for(let u of this.cache.values())if(u.identifier.package===D)F.push(u);return F}getByKind(D){let F=[];for(let u of this.cache.values())if(u.identifier.kind===D)F.push(u);return F}setMany(D){for(let F of D)this.set(F)}clear(){this.cache.clear()}generateKey(D){return`${D.package}:${D.version}:${D.kind}:${D.name}`}async initialize(){if(this.config.enablePersistence&&this.cacheDir){if(!FF(this.cacheDir))k3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!FF(this.cacheDir))return;try{let F=(await f3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F){let E=z2(this.cacheDir,u),B=await c8(E);if(this.config.maxAge){if(Date.now()-B.mtimeMs>this.config.maxAge){await y3(E);continue}}try{let C=await l8(E,"utf-8"),$=JSON.parse(C);if(this.config.validateCached){if(!$.schema?.identifier)continue}let X=this.generateKey($.schema.identifier);this.cache.set(X,$.schema)}catch(C){console.warn(`Failed to load cached schema from ${u}:`,C)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!FF(this.cacheDir))k3(this.cacheDir,{recursive:!0});let F={schema:D,timestamp:Date.now(),version:D.identifier.version},u=`${D.identifier.package}-${D.identifier.version}-${D.identifier.kind}-${D.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),E=z2(this.cacheDir,u);try{await o8(E,JSON.stringify(F,null,2),"utf-8")}catch(B){console.warn(`Failed to persist schema to ${E}:`,B)}}async clearDisk(){if(!this.cacheDir||!FF(this.cacheDir))return;try{let F=(await f3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F)await y3(z2(this.cacheDir,u))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as n8}from"crypto";var O2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return n8("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:O2,get:(B)=>D[B],set:(B,C)=>{if(D[B]=C,C.url){if(!F[C.url])F[C.url]=[];let $=F[C.url];if($&&!$.includes(B))$.push(B)}},has:(B)=>(B in D),clear:()=>{Object.keys(D).forEach((B)=>delete D[B]),Object.keys(F).forEach((B)=>delete F[B])},size:()=>Object.keys(D).length,getIdsByUrl:(B)=>F[B]||[],createReference:(B,C)=>({id:B,resourceType:C.resourceType}),getAllReferences:()=>D}};import*as j2 from"path";import*as s3 from"fs/promises";var d3="https://fs.get-ig.org/pkgs/";import*as uF from"fs/promises";import*as h3 from"path";var A0=async(D)=>{try{return await uF.access(D),!0}catch{return!1}},G0=async(D)=>{try{await uF.mkdir(D,{recursive:!0})}catch{}},EF=async(D)=>{let F=h3.join(D,".index.json");return A0(F)};import{exec as i8}from"child_process";import{promisify as t8}from"util";var p3=t8(i8);async function Y2(){try{return await p3("bun --version"),"bun"}catch{try{return await p3("npm --version"),"npm"}catch{return null}}}import*as m3 from"fs/promises";import*as l3 from"path";import{exec as s8}from"child_process";import{promisify as r8}from"util";var g3=r8(s8),J2=async(D,F,u)=>{await G0(F);let E=l3.join(F,"package.json");if(!await A0(E))await m3.writeFile(E,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let B=await Y2();if(!B)throw new Error("No package manager found. Please install npm or bun.");for(let C of D)try{if(B==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},X=u?`cd ${F} && bun add ${C} --registry ${u}`:`cd ${F} && bun add ${C}`;await g3(X,{env:$,maxBuffer:10485760})}else{let $=u?`cd ${F} && npm add ${C} --registry ${u}`:`cd ${F} && npm add ${C}`;await g3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${C}:`,$),$}};var BF=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as CF from"fs/promises";import*as G2 from"path";import*as W2 from"fs/promises";import*as A2 from"path";import{createHash as c3}from"crypto";var w0=async(D)=>{try{let F=A2.join(D,"package-lock.json");try{let u=await W2.readFile(F,"utf-8");return c3("sha256").update(u).digest("hex")}catch{let u=A2.join(D,"bun.lock"),E=await W2.readFile(u,"utf-8");return c3("sha256").update(E).digest("hex")}}catch{return null}};var H2=async(D,F,u)=>{let E=await w0(u),B={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:E||void 0},C=G2.join(F,"index.json");await CF.writeFile(C,JSON.stringify(B,null,2))},q2=async(D)=>{try{let F=G2.join(D,"index.json"),u=await CF.readFile(F,"utf-8");return JSON.parse(u)}catch{return null}};var o3=(D)=>{if(!D||typeof D!=="object")return!1;if(!D.filename||typeof D.filename!=="string")return!1;if(!D.resourceType||typeof D.resourceType!=="string")return!1;if(!D.id||typeof D.id!=="string")return!1;let F=["url","version","kind","type"];for(let u of F)if(D[u]!==void 0&&typeof D[u]!=="string")return!1;return!0},n3=(D)=>{if(!D||typeof D!=="object")return!1;if(!D["index-version"]||typeof D["index-version"]!=="number")return!1;if(!Array.isArray(D.files))return!1;return D.files.every((F)=>o3(F))},M2=(D,F)=>{try{let u=JSON.parse(D);if(!n3(u))return null;return u}catch{return null}};import*as i3 from"fs/promises";import*as _2 from"path";var $F=async(D,F,u)=>{let E=_2.join(D,".index.json");try{let B=await i3.readFile(E,"utf-8"),C=M2(B,E);if(!C)return;for(let $ of C.files){if(!$.url)continue;let X=_2.join(D,$.filename),Q=u.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:X});u.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:X,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:C["index-version"],url:$.url,version:$.version,kind:$.kind,type:$.type,package:{name:F.name,version:F.version}};if(!u.entries[$.url])u.entries[$.url]=[];let Y=u.entries[$.url];if(Y)Y.push(z)}}catch{}};import*as t3 from"fs/promises";import*as XF from"path";var ZF=async(D,F)=>{try{let u=XF.join(D,"package.json"),E=await t3.readFile(u,"utf-8"),B=JSON.parse(E),C={id:{name:B.name,version:B.version},path:D,canonical:B.canonical,fhirVersions:B.fhirVersions};F.packages[B.name]=C,await $F(D,B,F);let $=XF.join(D,"examples");if(await A0(XF.join($,".index.json")))await $F($,B,F)}catch{}};import*as K2 from"fs/promises";import*as V2 from"path";var R2=async(D,F)=>{try{let u=await K2.readdir(D,{withFileTypes:!0});for(let E of u){if(!E.isDirectory())continue;let B=V2.join(D,E.name);if(E.name.startsWith("@")){let C=await K2.readdir(B,{withFileTypes:!0});for(let $ of C){if(!$.isDirectory())continue;let X=V2.join(B,$.name);if(await EF(X))await ZF(X,F)}}else if(await EF(B))await ZF(B,F)}}catch{}};var U2=async(D,F,u,E)=>{if(F.package)try{return await E(D,{package:F.package.name,version:F.package.version})}catch{}return null};var L2={str:["structure"],struct:["structure"],def:["definition"],pati:["patient"],obs:["observation"],org:["organization"],pract:["practitioner"],med:["medication","medicinal"],req:["request"],resp:["response"],ref:["reference"],val:["value"],code:["codesystem","code"],cs:["codesystem"],vs:["valueset"],sd:["structuredefinition"]};var N2=(D,F)=>{if(F.length===0)return D;let u=F.map((E)=>E.toLowerCase());return D.filter((E)=>{if(!E.url)return!1;let C=[E.url.toLowerCase(),E.type?.toLowerCase()||"",E.resourceType?.toLowerCase()||""].join(" ");return u.every(($)=>{let X=C.split(/[\/\-_\.\s]+/);if(X.some((Y)=>Y.startsWith($)))return!0;let z=L2[$]||[];for(let Y of z)if(X.some((W)=>W.startsWith(Y)))return!0;return C.includes($)})})};var xD=(D)=>{let{packages:F,workingDir:u}=D,E=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:d3,B=j2.join(u,"node_modules"),C=j2.join(u,".fcm","cache"),$=BF(),X=!1,Q=new Map,z=()=>{if(!X)throw new Error("CanonicalManager not initialized. Call init() first.")},Y=async()=>{if(X)return;await G0(u),await G0(C);let V=await w0(u),L=await q2(C);if(L&&L.packageLockHash===V&&V!==null)$.entries=L.entries,$.packages=L.packages,Object.entries(L.references).forEach(([d,t])=>{$.referenceManager.set(d,t)});else{if(L&&L.packageLockHash!==V)console.log("Package dependencies have changed, rebuilding index...");await J2(F,u,E),$=BF(),await R2(B,$),await H2($,C,u)}X=!0},W=async()=>{$.entries={},$.packages={},$.referenceManager.clear(),Q.clear(),X=!1},J=async()=>{return z(),Object.values($.packages).map((V)=>V.id)},q=async(V,L)=>{if(z(),L?.sourceContext){let t=await U2(V,L.sourceContext,$,q);if(t)return t}let k=$.entries[V]||[];if(k.length===0)throw new Error(`Cannot resolve canonical URL: ${V}`);let d=[...k];if(L?.package)d=d.filter((t)=>t.package?.name===L.package);if(L?.version)d=d.filter((t)=>t.version===L.version);if(d.length===0)throw new Error(`No matching resource found for ${V} with given options`);return d[0]},M=async(V,L)=>{let k=await q(V,L);return G(k)},G=async(V)=>{z();let L=$.referenceManager.get(V.id);if(!L)throw new Error(`Invalid reference ID: ${V.id}`);try{let k=await s3.readFile(L.filePath,"utf-8");return{...JSON.parse(k),id:V.id,resourceType:V.resourceType}}catch(k){throw new Error(`Failed to read resource: ${k}`)}},T=async(V)=>{z();let L=[];if(V.url)L=$.entries[V.url]||[];else for(let k of Object.values($.entries))L.push(...k);if(V.kind!==void 0)L=L.filter((k)=>k.kind===V.kind);if(V.type!==void 0)L=L.filter((k)=>k.type===V.type);if(V.version!==void 0)L=L.filter((k)=>k.version===V.version);if(V.package){let k=V.package;L=L.filter((d)=>d.package?.name===k.name&&d.package?.version===k.version)}return L};return{init:Y,destroy:W,packages:J,resolveEntry:q,resolve:M,read:G,searchEntries:T,search:async(V)=>{let L=await T(V);return await Promise.all(L.map((d)=>G(d)))},smartSearch:async(V,L)=>{z();let k=await T({kind:L?.kind,package:L?.package});if(L?.resourceType)k=k.filter((d)=>d.resourceType===L.resourceType);if(L?.type)k=k.filter((d)=>d.type===L.type);return N2(k,V)},getSearchParametersForResource:async(V)=>{if(z(),Q.has(V))return Q.get(V);let k=(await T({})).filter((t)=>t.resourceType==="SearchParameter"),d=[];for(let t of k){let l=await G(t),jD=l.base||[];if(Array.isArray(jD)&&jD.includes(V))d.push(l)}return d.sort((t,l)=>{let jD=t.code||"",w=l.code||"";return jD.localeCompare(w)}),Q.set(V,d),d}}};function w2(D){let E=D.path.split(".").slice(1).map(($)=>({el:$}));if(E.length===0)return[];let B=E.length-1,C={};if(D.slicing){if(C.slicing={...D.slicing},D.min!==void 0)C.slicing.min=D.min;if(D.max&&D.max!=="*")C.slicing.max=parseInt(D.max)}if(D.sliceName){if(C.slice={},D.min!==void 0)C.slice.min=D.min;if(D.max&&D.max!=="*")C.slice.max=parseInt(D.max);C.sliceName=D.sliceName}return E[B]={...E[B],...C},E}function T2(D,F){let u=[],E=Math.min(D.length,F.length);for(let B=0;B<E;B++)if(D[B].el===F[B].el)u.push({el:D[B].el});else break;return u}function I2(D,F){let u=[];for(let E=0;E<F.length;E++)if(E<D.length&&D[E].el===F[E].el)u.push({...D[E],...F[E],...D[E].slicing&&!F[E].slicing&&{slicing:D[E].slicing}});else u.push(F[E]);return u}function a8(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function r3(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function e8(D,F,u,E){let B=[];for(let C=D-1;C>=F;C--){let $=u[C];if($.sliceName)B.push(r3($));B.push({type:"exit",el:$.el})}if(F>0){let C=u[F-1],$=E[F-1];if(a8(C,$))B.push(r3(C))}return B}function Du(D,F,u,E){let B=[];if(D>0&&D<=F){let C=u[D-1]||{},$=E[D-1];if($.sliceName&&(!C.sliceName||C.sliceName!==$.sliceName))B.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return B}for(let C=D;C<F;C++){let $=E[C];if(B.push({type:"enter",el:$.el}),$.sliceName)B.push({type:"enter-slice",sliceName:$.sliceName})}return B}function QF(D,F){let u=D.length,E=F.length,C=T2(D,F).length,$=e8(u,C,D,F),X=Du(C,E,D,F);return[...$,...X]}function e3(D,F){if(!D)return;return D.find((u)=>u.url===F)}function a3(D){return{Instant:"instant",Time:"time",Date:"date",DateTime:"dateTime",Decimal:"decimal",Boolean:"boolean",Integer:"integer",String:"string",Uri:"uri",Base64Binary:"base64Binary",Code:"code",Id:"id",Oid:"oid",UnsignedInt:"unsignedInt",PositiveInt:"positiveInt",Markdown:"markdown",Url:"url",Canonical:"canonical",Uuid:"uuid"}[D]||D}function Fu(D){let F={};for(let[u,E]of Object.entries(D))if(typeof u==="string"&&u.startsWith("pattern")){let B=a3(u.replace(/^pattern/,""));F.pattern={type:B,value:E}}else if(typeof u==="string"&&u.startsWith("fixed")){let B=a3(u.replace(/^fixed/,""));F.pattern={type:B,value:E}}else F[u]=E;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function uu(D){let F=[];for(let u of D)if(u.targetProfile){let E=Array.isArray(u.targetProfile)?u.targetProfile:[u.targetProfile];F.push(...E)}return F.length>0?[...new Set(F)].sort():void 0}function Eu(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let u=uu(D.type);return{...D,type:[{code:"Reference"}],...u&&{refers:u}}}return D}function Bu(D,F){let u=(C)=>{let $={strength:C.strength,...C.valueSet&&{valueSet:C.valueSet}},X=e3(C.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(X?.valueString)$.bindingName=X.valueString;return $};if(D.choices){let{binding:C,...$}=D;return $}if(D.choiceOf&&F.snapshot){let C=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((X)=>X.path===C);if($?.binding)return{...D,binding:u($.binding)}}if(D.binding?.valueSet)return{...D,binding:u(D.binding)};let{binding:E,...B}=D;return B}function Cu(D){if(!D.constraint||D.constraint.length===0)return D;let F={};for(let u of D.constraint)F[u.key]={expression:u.expression,human:u.human,severity:u.severity};return{...D,constraint:F}}function $u(D,F){if(!D.type||D.type.length===0)return D;let u=D.type[0]?.extension?.[0];if(u?.url==="http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"&&u.valueUrl)return{...D,type:u.valueUrl};let E=D.type[0].code,B={...D,type:E};if(F.kind==="logical"){let C=e3(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(C?.valueCanonical)B.defaultType=C.valueCanonical}return B}function Xu(D){if(D.type?.[0]?.code!=="Extension")return D;let u=D.type[0]?.profile?.[0];if(!u)return D;return{...D,url:u,...D.min&&{min:D.min},...D.max&&D.max!=="*"&&{max:parseInt(D.max)}}}function Zu(D){if(D.url)return D;let F=D.max==="*"||D.min&&D.min>=2||D.max&&parseInt(D.max)>=2,u=D.min===1,E={...D};if(delete E.min,delete E.max,F){if(E.array=!0,D.min&&D.min>0)E.min=D.min;if(D.max&&D.max!=="*")E.max=parseInt(D.max)}if(u)E._required=!0;return E}function Qu(D,F){let u=D.substring(1).split("."),E=[F.url];for(let B of u.slice(1))E.push("elements",B);return E}function zu(D,F){if(!D.contentReference)return D;let{contentReference:u,...E}=D;return{...E,elementReference:Qu(u,F)}}function Ou(D){let{path:F,slicing:u,sliceName:E,id:B,mapping:C,example:$,alias:X,condition:Q,comment:z,definition:Y,requirements:W,extension:J,...q}=D;return q}function b2(D,F){let u=Eu(D);return u=Ou(u),u=Bu(u,F),u=Cu(u),u=zu(u,F),u=Xu(u),u=Zu(u),u=$u(u,F),u=Fu(u),u}function x2(D){if(D.path.endsWith("[x]"))return!0;if(D.type&&D.type.length>1)return new Set(D.type.map((u)=>u.code)).size>1;return!1}function D6(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function F6(D){let F=D.split("/");return F[F.length-1]}function P2(D){let F=D.path.replace(/\[x\]$/,""),u=F.split(".").pop()||"";if(!D.type)return[];let E=[],B=D.type.map((z)=>u+D6(F6(z.code))),{type:C,binding:$,...X}=D,Q={...X,path:F,choices:B};E.push(Q);for(let z of D.type){let Y=D6(F6(z.code)),W={...D,path:F+Y,type:[z],choiceOf:u};if(D.binding)delete W.binding;E.push(W)}return E}function u6(D,F){let u=D[D.length-1],E=D.slice(0,-1),B=E[E.length-1],C=F(B,u);return[...E.slice(0,-1),C]}function Yu(D,F){if(!D.discriminator)return{};let u={};for(let E of D.discriminator){if(!E.type||!["pattern","value",void 0].includes(E.type))continue;let B=E.path.trim();if(B==="$this"){if(F.pattern?.value)Object.assign(u,F.pattern.value)}else{let C=B.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let Y=z.replace("pattern","").toLowerCase();if(C.length===1&&C[0]===Y)u[Y]=F[z]}let X=["elements"];for(let z of C)if(X.push(z),C.indexOf(z)<C.length-1)X.push("elements");X.push("pattern");let Q=F;for(let z of X)Q=Q?.[z];if(Q?.value!==void 0){let z=u;for(let Y=0;Y<C.length-1;Y++){if(!z[C[Y]])z[C[Y]]={};z=z[C[Y]]}z[C[C.length-1]]=Q.value}}}return u}function Ju(D,F,u){let E={match:F,schema:D};if(u?.min!==void 0&&u.min!==0)E.min=u.min;if(u?.max!==void 0)E.max=u.max;return E}function Wu(D,F,u){let E=F.slicing||D.slicing||{},B=Yu(E,u),C=Ju(u,B,D.slice);if(!F.slicing)F.slicing={};if(D.slicing)F.slicing={...F.slicing,...D.slicing};if(!F.slicing.slices)F.slicing.slices={};return F.slicing.slices[D.sliceName]=C,F}function Au(D){if(!D.slicing?.slices)return{};let F={};for(let[u,E]of Object.entries(D.slicing.slices)){let{match:B,schema:C,...$}=E,{slicing:X,elements:Q,type:z,min:Y,...W}=C||{},J={};if(B?.url)J.url=B.url;if($.min!==void 0&&$.min!==0)J.min=$.min;if($.max!==void 0)J.max=$.max;if(Object.assign(J,W),Y!==void 0&&Y!==0&&J.min===void 0)J.min=Y;F[u]=J}return F}function Gu(D,F,u){let E={...F};if(D==="extension")E.extensions=Au(u);if(!E.elements)E.elements={};let B=u.choiceOf||D,{_required:C,...$}=u;if(E.elements[D]=$,C){if(!E.required)E.required=[];if(!E.required.includes(B))E.required.push(B)}return E}function zF(D,F,u){let E=[...D];for(let B=0;B<F.length;B++){let C=F[B],X=F[B+1]?.type==="enter"?{}:u;switch(C.type){case"enter":E.push(X);break;case"enter-slice":E.push(X);break;case"exit":E=u6(E,(Q,z)=>Gu(C.el,Q,z));break;case"exit-slice":E=u6(E,(Q,z)=>Wu(C,Q,z));break}}return E}function E6(D,F){let u={};if(u.name=D.name,u.type=D.type,D.url)u.url=D.url;if(D.version)u.version=D.version;if(D.description)u.description=D.description;if(D.package_name)u.package_name=D.package_name;if(D.package_version)u.package_version=D.package_version;if(D.package_id)u.package_id=D.package_id;if(u.kind=D.kind,D.derivation)u.derivation=D.derivation;if(D.baseDefinition&&D.type!=="Element")u.base=D.baseDefinition;if(D.abstract)u.abstract=D.abstract;if(u.class=Hu(D),F?.package_meta)u.package_meta=F.package_meta;return u}function Hu(D){if(D.kind==="resource"&&D.derivation==="constraint")return"profile";if(D.type==="Extension")return"extension";return D.kind||"unknown"}function qu(D){return(D.differential?.element||[]).filter((u)=>u.path.includes("."))}function B6(D){let u=Object.entries(D).sort((B,C)=>{let $=B[1].index??1/0,X=C[1].index??1/0;return $-X}),E={};for(let[B,C]of u)if(C.elements)E[B]={...C,elements:B6(C.elements)};else E[B]=C;return E}function T0(D,F=new WeakSet){if(Array.isArray(D))return D.map((u)=>T0(u,F));if(D&&typeof D==="object"){if(F.has(D))return"[Circular Reference]";F.add(D);let u={},E=Object.keys(D);for(let B of E)if(B==="elements"&&D[B])u[B]=B6(T0(D[B],F));else if(B==="required"&&Array.isArray(D[B]))u[B]=[...D[B]].sort();else u[B]=T0(D[B],F);return u}return D}function S2(D,F){if(D.kind==="primitive-type")return T0(E6(D,F));let u=E6(D,F),E=qu(D),B=[u],C=[],$=[...E],X=0;while($.length>0){let z=$.shift();if(x2(z)){let G=P2(z);$.unshift(...G),X++;continue}let Y=w2(z),W=I2(C,Y),J=QF(C,W),M={...b2(z,D),index:X++};B=zF(B,J,M),C=W}let Q=QF(C,[]);if(B=zF(B,Q,{index:X}),B.length!==1)throw new Error(`Invalid stack state: expected 1 element, got ${B.length}`);return T0(B[0])}function OF(D){if(!D)return;return D.split("|")[0]}function Mu(D){if(D.derivation==="constraint"){if(D.base&&(D.type==="Resource"||D.kind==="resource"||D.kind==="complex-type"))return"profile";return"profile"}if(D.kind)switch(D.kind){case"primitive-type":return"primitive-type";case"complex-type":return"complex-type";case"resource":return"resource"}return"resource"}function PD(D,F){return{kind:Mu(D),package:F?.name||D.package_name||"undefined",version:F?.version||D.package_version||"undefined",name:D.name,url:D.url}}function H0(D,F,u){let E=F.join(".");return{kind:"nested",package:u?.name||D.package_name||"undefined",version:u?.version||D.package_version||"undefined",name:E,url:`${D.url}#${E}`}}function q0(D,F,u){let E=OF(D)||D,B="unknown",C=E.split("/"),$=C[C.length-1];if($&&$.length>0)B=$.split(/[-_]/).map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("");if(B==="unknown"&&F?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(F.id))B=F.id;return{kind:"value-set",package:u?.name||F?.package_name||"undefined",version:u?.version||F?.package_version||"undefined",name:B,url:E}}function I0(D,F,u,E){let B=F.join("."),C=u||`${D.name}.${B}_binding`;return{kind:"binding",package:E?.name||D.package_name||"undefined",version:E?.version||D.package_version||"undefined",name:C,url:u?`urn:fhir:binding:${C}`:`${D.url}#${B}_binding`}}async function C6(D,F,u){let E=PD(D,u);if(E.kind!=="profile")throw new Error(`Expected profile, got ${E.kind} for ${D.name}`);let B;if(D.base){let Y=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,W=D.base.split("/").pop()||D.base,J=await _u(Y,F),q=Y.startsWith("http://hl7.org/fhir/");B={kind:J,package:q?"hl7.fhir.r4.core":u?.name||D.package_name||"undefined",version:q?"4.0.1":u?.version||D.package_version||"undefined",name:W,url:Y}}let C={identifier:E,base:B,dependencies:B?[B]:[]};if(D.description)C.description=D.description;let $=Ku(D,u);if(Object.keys($).length>0)C.metadata=$;if(D.elements){let Y=await YF(D,[],D.elements,F,u);if(Object.keys(Y).length>0)C.fields=Y}let X=await Vu(D,F);if(Object.keys(X).length>0)C.constraints=X;let Q=await Ru(D,F);if(Q.length>0)C.extensions=Q;let z=Uu(D);if(z.length>0)C.validation=z;return C}async function _u(D,F){try{let u=await F.resolve(D);if(u){if(u.derivation==="constraint")return"profile";if(u.kind==="resource")return"resource";if(u.kind==="complex-type")return"complex-type"}}catch(u){console.warn(`Could not resolve base schema ${D}:`,u)}if(D.includes("StructureDefinition/")&&!D.startsWith("http://hl7.org/fhir/StructureDefinition/"))return"profile";return"resource"}function Ku(D,F){let u={};if(D.publisher)u.publisher=D.publisher;if(D.contact)u.contact=D.contact;if(D.copyright)u.copyright=D.copyright;if(D.purpose)u.purpose=D.purpose;if(D.experimental!==void 0)u.experimental=D.experimental;if(D.date)u.date=D.date;if(D.jurisdiction)u.jurisdiction=D.jurisdiction;if(F?.name)u.package=F.name;else if(D.package_name)u.package=D.package_name;return u}async function Vu(D,F){let u={};if(!D.elements)return u;for(let[E,B]of Object.entries(D.elements)){let C={};if(B.min!==void 0)C.min=B.min;if(B.max!==void 0)C.max=String(B.max);if(B.mustSupport)C.mustSupport=!0;if(B.fixedValue!==void 0)C.fixedValue=B.fixedValue;if(B.patternValue!==void 0)C.patternValue=B.patternValue;if(B.binding)C.binding={strength:B.binding.strength,valueSet:B.binding.valueSet??""};if(B.type&&Array.isArray(B.type)&&B.type.length>0)C.types=B.type.map(($)=>{let X={code:$.code};if($.profile)X.profile=$.profile;if($.targetProfile)X.targetProfile=$.targetProfile;return X});if(B.slicing)C.slicing={discriminator:B.slicing.discriminator??[],rules:String(B.slicing),ordered:B.slicing.ordered};if(Object.keys(C).length>0)u[E]=C}return u}async function Ru(D,F){let u=[];if(!D.elements)return u;for(let[E,B]of Object.entries(D.elements))if(E.includes("extension")&&B.type&&Array.isArray(B.type)){for(let C of B.type)if(C.code==="Extension"&&C.profile)u.push({path:E,profile:C.profile,min:B.min,max:String(B.max),mustSupport:B.mustSupport})}return u}function Uu(D){let F=[];if(!D.elements)return F;for(let[u,E]of Object.entries(D.elements))if(E.constraint&&Array.isArray(E.constraint))for(let B of E.constraint)F.push({path:u,key:B.key,severity:B.severity,human:B.human,expression:B.expression});return F}function v2(D,F,u){let E=[],B=D.elements;for(let C of F)if(B=B?.[C],!B)break;if(B)E.push(B);return E}function k2(D){if(D.length===0)return{};let F={...D[0]};for(let u=D.length-1;u>=0;u--){let E=D[u],B=["choices","short","index","elements","required","excluded","binding","refers","elementReference","mustSupport","slices","slicing","url","extensions"];for(let[C,$]of Object.entries(E))if(!B.includes(C)&&$!==void 0)F[C]=$}for(let u of["choices","binding","refers","elementReference"])if(D[0]&&D[0][u]!==void 0)F[u]=D[0][u];return F}function f2(D,F,u){if(F.length===0)return!1;let E=F[F.length-1],B=F.slice(0,-1),C=D;for(let $ of B)if(C=C.elements?.[$],!C)break;if(C?.required?.includes(E))return!0;if(B.length===0&&E&&D.required?.includes(E))return!0;return!1}function y2(D,F,u){if(F.length===0)return!1;let E=F[F.length-1],B=F.slice(0,-1),C=D;for(let $ of B)if(C=C.elements?.[$],!C)break;if(C?.excluded?.includes(E))return!0;if(B.length===0&&E&&D.excluded?.includes(E))return!0;return!1}async function Lu(D,F,u){if(!D.refers||D.refers.length===0)return;let E=[];for(let B of D.refers)try{let C=await F.resolve(B);if(C)E.push(PD(C,u))}catch{}return E}function d2(D,F,u,E,B){if(u.elementReference){let C=u.elementReference.filter(($,X)=>X%2===1).map(($)=>$).filter(($)=>$!=="elements");if(C.length>0)return H0(D,C,B)}if(u.type){let C=u.type.includes("/")?u.type:`http://hl7.org/fhir/StructureDefinition/${u.type}`,$=u.type.match(/^[a-z]/)?"primitive-type":"complex-type",X=C.startsWith("http://hl7.org/fhir/");return{kind:$,package:X?"hl7.fhir.r4.core":B?.name||"undefined",version:X?"4.0.1":B?.version||"undefined",name:u.type,url:C}}return}async function b0(D,F,u,E,B){let C={array:u.array||!1,required:f2(D,F,E),excluded:y2(D,F,E)},$=d2(D,F,u,E,B);if($)C.type=$;if(u.min!==void 0)C.min=u.min;if(u.max!==void 0)C.max=u.max;if(u.choices)C.choices=u.choices;if(u.choiceOf)C.choiceOf=u.choiceOf;if(u.binding){if(C.binding=I0(D,F,u.binding.bindingName,B),u.binding.strength==="required"&&u.type==="code"){let Q=await JF(u,E);if(Q&&Q.length>0)C.enum=Q}}let X=await Lu(u,E,B);if(X)C.reference=X;return Nu(C)}function Nu(D){let F={};for(let[u,E]of Object.entries(D))if(E!==void 0&&E!==null){if(Array.isArray(E)&&E.length===0)continue;F[u]=E}return F}function M0(D){return D.type==="BackboneElement"||D.elements&&Object.keys(D.elements).length>0||!1}function x0(D,F,u,E,B){return{type:H0(D,F,B),array:u.array||!1,required:f2(D,F,E),excluded:y2(D,F,E)}}async function $6(D,F){try{let u=OF(D)||D,E=await F.resolve(u);if(!E)return;if(E.expansion?.contains)return E.expansion.contains.map((C)=>({system:C.system,code:C.code,display:C.display}));let B=[];if(E.compose?.include){for(let C of E.compose.include)if(C.concept)for(let $ of C.concept)B.push({system:C.system,code:$.code,display:$.display});else if(C.system&&!C.filter)try{let $=await F.resolve(C.system);if($?.concept){let X=(Q,z)=>{for(let Y of Q)if(B.push({system:z,code:Y.code,display:Y.display}),Y.concept)X(Y.concept,z)};X($.concept,C.system)}}catch{}}return B.length>0?B:void 0}catch{return}}async function JF(D,F){if(!D.binding)return;let{strength:u,valueSet:E}=D.binding;if(!E)return;if(!(u==="required"||u==="extensible"&&(D.type==="code"||D.type==="Coding")||u==="preferred"&&(D.type==="code"||D.type==="Coding")))return;if(!F.resolve)return;try{let C=await $6(E,F);if(!C||C.length===0)return;let $=C.map((X)=>X.code).filter((X)=>X&&typeof X==="string"&&X.trim().length>0);return $.length>0&&$.length<=100?$:void 0}catch(C){console.debug(`Failed to extract enum values for ${E}: ${C}`);return}}async function X6(D,F,u,E,B){if(!u.binding?.valueSet)return;let C=I0(D,F,u.binding.bindingName,B),$=d2(D,F,u,E,B),X=q0(u.binding.valueSet,void 0,B),Q={identifier:C,type:$,valueset:X,strength:u.binding.strength,dependencies:[]};if($)Q.dependencies.push($);Q.dependencies.push(X);let z=await JF(u,E);if(z)Q.enum=z;return Q}async function WF(D,F,u){let E=[],B=new Set;async function C(Q,z){for(let[Y,W]of Object.entries(Q)){let J=[...z,Y],q=J.join(".");if(B.has(q))continue;if(B.add(q),W.binding){let M=await X6(D,J,W,F,u);if(M)E.push(M)}if(W.elements)await C(W.elements,J)}}if(D.elements)await C(D.elements,[]);E.sort((Q,z)=>Q.identifier.name.localeCompare(z.identifier.name));let $=[],X=new Set;for(let Q of E)if(!X.has(Q.identifier.url))X.add(Q.identifier.url),$.push(Q);return $}function h2(D,F,u){let E=[];for(let[B,C]of Object.entries(u)){let $=[...F,B];if(M0(C))E.push([$,C]);if(C.elements)E.push(...h2(D,$,C.elements))}return E}async function ju(D,F,u,E,B){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$];if(M0(X))C[$]=x0(D,Q,X,E,B);else C[$]=await b0(D,Q,X,E,B)}return C}async function AF(D,F,u){if(!D.elements)return[];let E=[],C=h2(D,[],D.elements).filter(([$,X])=>X.elements&&Object.keys(X.elements).length>0);for(let[$,X]of C){let Q=H0(D,$,u),z;if(X.type==="BackboneElement"||!X.type)z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:X.type,url:`http://hl7.org/fhir/StructureDefinition/${X.type}`};let Y=await ju(D,$,X.elements,F,u),W={identifier:Q,base:z,fields:Y};E.push(W)}return E.sort(($,X)=>$.identifier.url.localeCompare(X.identifier.url)),E}function GF(D){let F=[];for(let u of D){if(F.push(u.identifier),u.base)F.push(u.base);for(let E of Object.values(u.fields)){if("type"in E&&E.type)F.push(E.type);if("binding"in E&&E.binding)F.push(E.binding)}}return F}async function YF(D,F,u,E,B){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$],z=v2(D,Q,E),Y=z.length>0?k2(z):X;if(M0(Y))C[$]=x0(D,Q,Y,E,B);else C[$]=await b0(D,Q,Y,E,B)}return C}function Z6(D){let F=[];for(let u of Object.values(D)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding)}return F}function Q6(D){let F=new Set,u=[];for(let E of D){let B=E.url;if(!F.has(B))F.add(B),u.push(E)}return u.sort((E,B)=>E.name.localeCompare(B.name)),u}function wu(D,F){if(D.base==="Extension"||D.base==="http://hl7.org/fhir/StructureDefinition/Extension")return!0;if(D.url?.includes("/extension/")||D.url?.includes("-extension"))return!0;if(D.name?.toLowerCase().includes("extension"))return!0;if(D.type==="Extension")return!0;return!1}async function Tu(D,F,u){try{let E=PD(D,u);E.kind="value-set";let B={identifier:E,description:D.description};if(D.elements){let C=[];for(let[$,X]of Object.entries(D.elements))if("code"in X&&X.code)C.push({code:X.code,display:X.short||X.definition,system:X.system});if(C.length>0)B.concept=C}return B}catch(E){return console.warn(`Failed to transform value set ${D.name}: ${E}`),null}}async function Iu(D,F,u){try{let E=PD(D,u),B;if(D.base&&D.base!=="Extension"){let X=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,Q=D.base.split("/").pop()||D.base;B={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:Q,url:X}}else B={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let C={identifier:E,base:B,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(B)C.dependencies.push(B);if(D.elements){let X=await YF(D,[],D.elements,F,u);if(Object.keys(X).length>0)C.fields=X,C.dependencies.push(...Z6(X))}let $=await AF(D,F,u);if($.length>0)C.nested=$,C.dependencies.push(...GF($));return C.dependencies=Q6(C.dependencies),C.dependencies=C.dependencies.filter((X)=>X.url!==E.url),C}catch(E){return console.warn(`Failed to transform extension ${D.name}: ${E}`),null}}async function HF(D,F,u){let E=[];if(!u&&(D.package_name||D.package_id))u={name:D.package_name||D.package_id||"undefined",version:D.package_version||"undefined"};let B=PD(D,u);if(B.kind==="profile"){let z=await C6(D,F,u);E.push(z);let Y=await WF(D,F,u);return E.push(...Y),E}if(B.kind==="value-set"||D.kind==="value-set"){let z=await Tu(D,F,u);if(z)E.push(z);return E}if(wu(D,B)){let z=await Iu(D,F,u);if(z)E.push(z);return E}let C;if(D.base&&D.type!=="Element"){let z=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,Y=D.base.split("/").pop()||D.base,J=new Set(["Element","BackboneElement","Quantity","Duration","Distance","Count","Age","Address","Annotation","Attachment","CodeableConcept","Coding","ContactPoint","HumanName","Identifier","Period","Range","Ratio","Reference","Timing","Money","SampledData","Signature","ContactDetail","Contributor","DataRequirement","Expression","ParameterDefinition","RelatedArtifact","TriggerDefinition","UsageContext","Dosage","Meta","Extension"]).has(Y)?"complex-type":"resource",q=z.startsWith("http://hl7.org/fhir/");C={kind:J,package:q?"hl7.fhir.r4.core":u?.name||D.package_name||"undefined",version:q?"4.0.1":u?.version||D.package_version||"undefined",name:Y,url:z}}let $={identifier:B,dependencies:[]},X=[];if(C)$.base=C,X.push(C);if(D.description)$.description=D.description;if(D.kind!=="primitive-type"&&D.elements){let z=await YF(D,[],D.elements,F,u);if(Object.keys(z).length>0)$.fields=z;X.push(...Z6(z));let Y=await AF(D,F,u);if(Y.length>0)$.nested=Y,X.push(...GF(Y))}$.dependencies=X,$.dependencies=Q6($.dependencies),$.dependencies=$.dependencies.filter((z)=>z.url!==B.url),E.push($);let Q=await WF(D,F,u);return E.push(...Q),E}async function p2(D,F,u){let E=[];for(let B of D){let C=await HF(B,F,u);E.push(...C)}return E}async function bu(D,F){try{let u=await F.resolve(D);if(!u||u.resourceType!=="CodeSystem")return;let E=[],B=(C,$)=>{for(let X of C)if(E.push({system:$,code:X.code,display:X.display}),X.concept)B(X.concept,$)};if(u.concept)B(u.concept,D);return E}catch{return}}async function z6(D,F){let u=[];if(D.concept){for(let E of D.concept)u.push({system:D.system,code:E.code,display:E.display});return u}if(D.system&&!D.filter){let E=await bu(D.system,F);if(E)u.push(...E)}if(D.valueSet)for(let E of D.valueSet)try{let B=await F.resolve(E);if(B){let C=await O6(B,F);if(C)u.push(...C)}}catch{}return u}async function O6(D,F){try{let u=[];if(D.compose){if(D.compose.include)for(let E of D.compose.include){let B=await z6(E,F);u.push(...B)}if(D.compose.exclude){let E=new Set;for(let B of D.compose.exclude){let C=await z6(B,F);for(let $ of C)E.add(`${$.system}|${$.code}`)}return u.filter((B)=>!E.has(`${B.system}|${B.code}`))}}return u.length>0?u:void 0}catch(u){console.error("Error extracting ValueSet concepts:",u);return}}async function g2(D,F,u){let B={identifier:q0(D.url,D,u)};if(D.description)B.description=D.description;let C=await O6(D,F);if(C&&C.length>0)B.concept=C;else if(D.compose)B.compose=D.compose;if(D.compose){let $=[],X=(Q)=>{for(let z of Q){if(z.system)$.push({kind:"value-set",package:u?.name||"undefined",version:u?.version||"undefined",name:z.system.split("/").pop()||"unknown",url:z.system});if(z.valueSet)for(let Y of z.valueSet)$.push(q0(Y,void 0,u))}};if(D.compose.include)X(D.compose.include);if(D.compose.exclude)X(D.compose.exclude)}return B}class SD{manager;options;cache=null;cacheConfig;logger;constructor(D={},F){this.options={resourceTypes:[],maxDepth:10,verbose:!1,...D},this.manager=xD({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=F,this.logger=D.logger||LD({verbose:this.options.verbose,prefix:"TypeSchema"})}async initializeCache(){if(this.cacheConfig&&!this.cache)this.cache=new mD(this.cacheConfig),await this.cache.initialize()}async generateFromPackage(D,F){await this.initializeCache();let u=this.cacheConfig?.forceRegenerate??!1;if(this.cache&&!u){let M=this.cache.getByPackage(D);if(M.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${D} (${M.length} schemas)`),M}this.logger.step(`Loading FHIR package: ${D}${F?`@${F}`:""}`),this.manager=xD({packages:[`${D}${F?`@${F}`:""}`],workingDir:"tmp/fhir"}),await this.manager.init();let E=await this.manager.search({}),B=E.filter((M)=>M.resourceType==="StructureDefinition"),C=E.filter((M)=>M.resourceType==="ValueSet");this.logger.info(`Found ${B.length} StructureDefinitions and ${C.length} ValueSets in package`),this.logger.progress(`Converting ${B.length} StructureDefinitions to FHIRSchemas`);let $=this.applyStructureDefinitionTreeshaking(B),X=[],Q=0,z=0;for(let M of $)try{let G=S2(M);X.push(G),Q++,this.logger.debug(`Converted StructureDefinition: ${M.name||M.id} (${M.resourceType})`)}catch(G){z++,this.logger.warn(`Failed to convert StructureDefinition ${M.name||M.id}: ${G instanceof Error?G.message:String(G)}`)}if(this.logger.success(`Schema conversion completed: ${Q}/${$.length} successful, ${z} failed`),C.length>0)this.logger.debug(`${C.length} ValueSets available for enum extraction`);let Y={name:D,version:F||"latest"},W=[];if(C.length>0){this.logger.progress(`Converting ${C.length} ValueSets to TypeSchema`);let M=0,G=0;for(let T of C)try{let p=await g2(T,this.manager,Y);if(p)W.push(p),M++,this.logger.debug(`Converted ValueSet: ${T.name||T.id}`)}catch(p){G++,this.logger.warn(`Failed to convert ValueSet ${T.name||T.id}: ${p instanceof Error?p.message:String(p)}`)}this.logger.success(`ValueSet conversion completed: ${M}/${C.length} successful, ${G} failed`)}let q=[...await this.generateFromSchemas(X,Y),...W];if(this.cache&&q.length>0){this.logger.info(`Caching ${q.length} generated schemas for package: ${D}`);for(let M of q)await this.cache.set(M);this.logger.success(`Cached ${q.length} TypeSchemas for package: ${D}`)}return q}async generateFromSchema(D,F){return this.logger.info("Transforming FHIR schema to TypeSchema"),HF(D,this.manager,F)}async generateFromSchemas(D,F){this.logger.info(`Transforming ${D.length} FHIR schemas to TypeSchema`);let u=await p2(D,this.manager,F),E=[],B=this.groupTypeSchemas(u);if(E.push(...B.resources),E.push(...B.complexTypes),E.push(...B.primitives),B.profiles.length>0){this.logger.info(`Enhancing ${B.profiles.length} profiles`);let C=await this.enhanceProfiles(B.profiles);E.push(...C)}if(B.extensions.length>0){this.logger.info(`Enhancing ${B.extensions.length} extensions`);let C=await this.enhanceExtensions(B.extensions);E.push(...C)}if(B.valueSets.length>0){this.logger.info(`Enhancing ${B.valueSets.length} value sets`);let C=await this.enhanceValueSets(B.valueSets);E.push(...C)}if(B.codeSystems.length>0){this.logger.info(`Enhancing ${B.codeSystems.length} code systems`);let C=await this.enhanceCodeSystems(B.codeSystems);E.push(...C)}return this.logger.success(`Generated ${E.length} enhanced FHIR type schemas: ${B.resources.length} resources, ${B.complexTypes.length} complex types, ${B.primitives.length} primitives`),E}groupTypeSchemas(D){let F={resources:[],complexTypes:[],primitives:[],profiles:[],extensions:[],valueSets:[],codeSystems:[]};for(let u of D)switch(u.identifier.kind){case"resource":F.resources.push(u);break;case"complex-type":F.complexTypes.push(u);break;case"primitive-type":F.primitives.push(u);break;case"binding":if("metadata"in u&&u.metadata?.isExtension)F.extensions.push(u);else F.complexTypes.push(u);break;case"value-set":F.valueSets.push(u);break;default:if("metadata"in u&&u.metadata?.isCodeSystem)F.codeSystems.push(u);else F.complexTypes.push(u);break}return F}async enhanceProfiles(D){return D}async enhanceExtensions(D){return D}async enhanceValueSets(D){return D}async enhanceCodeSystems(D){return D}applyStructureDefinitionTreeshaking(D){let F=this.options.treeshake;if(!F||F.length===0)return D;this.logger.info(`Applying treeshaking filter for ResourceTypes: ${F.join(", ")}`);let u=new Map,E=new Map,B=new Map;for(let z of D){let Y=z.name||z.id;if(Y)u.set(Y,z),E.set(Y,new Set),B.set(Y,new Set)}for(let z of D){let Y=z.name||z.id;if(!Y)continue;let{realDeps:W,refTargets:J}=this.extractStructureDefinitionDependenciesWithReferences(z);E.set(Y,new Set(W)),B.set(Y,new Set(J))}let C=new Set;for(let z of F)if(u.has(z))C.add(z);else this.logger.warn(`ResourceType '${z}' not found in structure definitions`);let $=(z,Y=new Set)=>{if(Y.has(z)||!E.has(z))return;Y.add(z);let W=E.get(z)||new Set;for(let J of Array.from(W))if(u.has(J))C.add(J),$(J,Y)};for(let z of Array.from(C))$(z);let X=D.filter((z)=>{let Y=z.name||z.id;return Y&&C.has(Y)}),Q=new Set;for(let z of D){let Y=z.name||z.id;if(Y&&!C.has(Y)){if(Array.from(B.values()).some((J)=>J.has(Y)))Q.add(Y)}}if(Q.size>0)this.logger.info(`Excluded reference-only targets: ${Array.from(Q).join(", ")}`);return this.logger.success(`Treeshaking completed: kept ${X.length}/${D.length} structure definitions`),X}extractStructureDefinitionDependenciesWithReferences(D){let F=new Set,u=new Set;if(D.baseDefinition){let E=this.extractResourceNameFromUrl(D.baseDefinition);if(E)F.add(E)}if(D.snapshot?.element||D.differential?.element){let E=D.snapshot?.element||D.differential?.element;for(let B of E)if(B.type)for(let C of B.type){if(C.code){if(F.add(C.code),C.code==="Reference"&&C.targetProfile)for(let $ of C.targetProfile){let X=this.extractResourceNameFromUrl($);if(X)u.add(X)}}if(C.profile)for(let $ of C.profile){let X=this.extractResourceNameFromUrl($);if(X)F.add(X)}}}return{realDeps:Array.from(F),refTargets:Array.from(u)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as xu}from"node:fs/promises";class _0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await xu(D,"utf-8"),u=this.options.format==="auto"?this.detectFormat(F,D):this.options.format;return this.parseFromString(F,u)}async parseFromString(D,F){let u=F||this.detectFormat(D),E;if(u==="ndjson")E=this.parseNDJSON(D);else E=this.parseJSON(D);if(this.options.validate)this.validateSchemas(E);return E}async parseFromFiles(D){let F=[];for(let u of D){let E=await this.parseFromFile(u);F.push(...E)}return F}parseSchema(D){if(!D.identifier)throw new Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(D.identifier))throw new Error("TypeSchema identifier is invalid");return D}findByIdentifier(D,F){return D.filter((u)=>this.matchesIdentifier(u.identifier,F))}findByUrl(D,F){return D.find((u)=>u.identifier.url===F)}findByKind(D,F){return D.filter((u)=>u.identifier.kind===F)}findByPackage(D,F){return D.filter((u)=>u.identifier.package===F)}getDependencies(D){let F=[];if("base"in D&&D.base)F.push(D.base);if("dependencies"in D&&D.dependencies)F.push(...D.dependencies);if("fields"in D&&D.fields)for(let u of Object.values(D.fields)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding);if("reference"in u&&u.reference)F.push(...u.reference)}if("nested"in D&&D.nested)for(let u of D.nested){F.push(u.identifier),F.push(u.base);for(let E of Object.values(u.fields)){if("type"in E&&E.type)F.push(E.type);if("binding"in E&&E.binding)F.push(E.binding);if("reference"in E&&E.reference)F.push(...E.reference)}}if("valueset"in D){let u=D;if(F.push(u.valueset),u.type)F.push(u.type)}return this.deduplicateDependencies(F)}resolveDependencies(D,F){let u=this.getDependencies(F),E=[];for(let B of u){let C=this.findByUrl(D,B.url);if(C)E.push(C)}return E}detectFormat(D,F){if(F){if(F.endsWith(".ndjson"))return"ndjson";if(F.endsWith(".json"))return"json"}let u=D.trim();if(u.includes(`
85
+ `;class r1{constructor(D,F,u,E){var B,C,$;this.yargs=D,this.usage=F,this.command=u,this.shim=E,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=($=((B=this.shim.getEnv("SHELL"))===null||B===void 0?void 0:B.includes("zsh"))||((C=this.shim.getEnv("ZSH_NAME"))===null||C===void 0?void 0:C.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,u,E){let B=this.command.getCommandHandlers();for(let $=0,X=D.length;$<X;++$)if(B[D[$]]&&B[D[$]].builder){let Q=B[D[$]].builder;if(f0(Q)){this.indexAfterLastReset=$+1;let z=this.yargs.getInternalMethods().reset();return Q(z,!0),z.argv}}let C=[];this.commandCompletions(C,D,u),this.optionCompletions(C,D,F,u),this.choicesFromOptionsCompletions(C,D,F,u),this.choicesFromPositionalsCompletions(C,D,F,u),E(null,C)}commandCompletions(D,F,u){let E=this.yargs.getInternalMethods().getContext().commands;if(!u.match(/^-/)&&E[E.length-1]!==u&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((B)=>{let C=PD(B[0]).cmd;if(F.indexOf(C)===-1)if(!this.zshShell)D.push(C);else{let $=B[1]||"";D.push(C.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,u,E){if((E.match(/^-/)||E===""&&D.length===0)&&!this.previousArgHasChoices(F)){let B=this.yargs.getOptions(),C=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(B.key).forEach(($)=>{let X=!!B.configuration["boolean-negation"]&&B.boolean.includes($);if(!C.includes($)&&!B.hiddenOptions.includes($)&&!this.argsContainKey(F,$,X))this.completeOptionKey($,D,E,X&&!!B.default[$])})}}choicesFromOptionsCompletions(D,F,u,E){if(this.previousArgHasChoices(F)){let B=this.getPreviousArgChoices(F);if(B&&B.length>0)D.push(...B.map((C)=>C.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,u,E){if(E===""&&D.length>0&&this.previousArgHasChoices(F))return;let B=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],C=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=B[u._.length-C-1];if(!$)return;let X=this.yargs.getOptions().choices[$]||[];for(let Q of X)if(Q.startsWith(E))D.push(Q.replace(/:/g,"\\:"))}getPreviousArgChoices(D){if(D.length<1)return;let F=D[D.length-1],u="";if(!F.startsWith("-")&&D.length>1)u=F,F=D[D.length-2];if(!F.startsWith("-"))return;let E=F.replace(/^-+/,""),B=this.yargs.getOptions(),C=[E,...this.yargs.getAliases()[E]||[]],$;for(let X of C)if(Object.prototype.hasOwnProperty.call(B.key,X)&&Array.isArray(B.choices[X])){$=B.choices[X];break}if($)return $.filter((X)=>!u||X.startsWith(u))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,u){let E=(B)=>D.indexOf((/^[^0-9]$/.test(B)?"-":"--")+B)!==-1;if(E(F))return!0;if(u&&E(`no-${F}`))return!0;if(this.aliases){for(let B of this.aliases[F])if(E(B))return!0}return!1}completeOptionKey(D,F,u,E){var B,C,$,X;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),M=(C=(B=this===null||this===void 0?void 0:this.aliases)===null||B===void 0?void 0:B[D])===null||C===void 0?void 0:C.find((T)=>{let p=J[T];return typeof p==="string"&&p.length>0}),q=M?J[M]:void 0,G=(X=($=J[D])!==null&&$!==void 0?$:q)!==null&&X!==void 0?X:"";Q=`${D.replace(/:/g,"\\:")}:${G.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let z=(J)=>/^--/.test(J),Y=(J)=>/^[^0-9]$/.test(J),W=!z(u)&&Y(D)?"-":"--";if(F.push(W+Q),E)F.push(W+"no-"+Q)}customCompletion(D,F,u,E){if(YD(this.customCompletionFunction,null,this.shim),x8(this.customCompletionFunction)){let B=this.customCompletionFunction(u,F);if(s(B))return B.then((C)=>{this.shim.process.nextTick(()=>{E(null,C)})}).catch((C)=>{this.shim.process.nextTick(()=>{E(C,void 0)})});return E(null,B)}else if(P8(this.customCompletionFunction))return this.customCompletionFunction(u,F,(B=E)=>this.defaultCompletion(D,F,u,B),(B)=>{E(null,B)});else return this.customCompletionFunction(u,F,(B)=>{E(null,B)})}getCompletion(D,F){let u=D.length?D[D.length-1]:"",E=this.yargs.parse(D,!0),B=this.customCompletionFunction?(C)=>this.customCompletion(D,C,u,F):(C)=>this.defaultCompletion(D,C,u,F);return s(E)?E.then(B):B(E)}generateCompletionScript(D,F){let u=this.zshShell?s1:t1,E=this.shim.path.basename(D);if(D.match(/\.js$/))D=`./${D}`;return u=u.replace(/{{app_name}}/g,E),u=u.replace(/{{completion_command}}/g,F),u.replace(/{{app_path}}/g,D)}registerFunction(D){this.customCompletionFunction=D}setParsed(D){this.aliases=D.aliases}}function a1(D,F,u,E){return new r1(D,F,u,E)}function x8(D){return D.length<3}function P8(D){return D.length>3}function e1(D,F){if(D.length===0)return F.length;if(F.length===0)return D.length;let u=[],E;for(E=0;E<=F.length;E++)u[E]=[E];let B;for(B=0;B<=D.length;B++)u[0][B]=B;for(E=1;E<=F.length;E++)for(B=1;B<=D.length;B++)if(F.charAt(E-1)===D.charAt(B-1))u[E][B]=u[E-1][B-1];else if(E>1&&B>1&&F.charAt(E-2)===D.charAt(B-1)&&F.charAt(E-1)===D.charAt(B-2))u[E][B]=u[E-2][B-2]+1;else u[E][B]=Math.min(u[E-1][B-1]+1,Math.min(u[E][B-1]+1,u[E-1][B]+1));return u[F.length][D.length]}var D3=["$0","--","_"];function F3(D,F,u){let E=u.y18n.__,B=u.y18n.__n,C={};C.nonOptionCount=function(W){let J=D.getDemandedCommands(),q=W._.length+(W["--"]?W["--"].length:0)-D.getInternalMethods().getContext().commands.length;if(J._&&(q<J._.min||q>J._.max)){if(q<J._.min)if(J._.minMsg!==void 0)F.fail(J._.minMsg?J._.minMsg.replace(/\$0/g,q.toString()).replace(/\$1/,J._.min.toString()):null);else F.fail(B("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",q,q.toString(),J._.min.toString()));else if(q>J._.max)if(J._.maxMsg!==void 0)F.fail(J._.maxMsg?J._.maxMsg.replace(/\$0/g,q.toString()).replace(/\$1/,J._.max.toString()):null);else F.fail(B("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",q,q.toString(),J._.max.toString()))}},C.positionalCount=function(W,J){if(J<W)F.fail(B("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",J,J+"",W+""))},C.requiredArguments=function(W,J){let M=null;for(let q of Object.keys(J))if(!Object.prototype.hasOwnProperty.call(W,q)||typeof W[q]>"u")M=M||{},M[q]=J[q];if(M){let q=[];for(let T of Object.keys(M)){let p=M[T];if(p&&q.indexOf(p)<0)q.push(p)}let G=q.length?`
86
+ ${q.join(`
87
+ `)}`:"";F.fail(B("Missing required argument: %s","Missing required arguments: %s",Object.keys(M).length,Object.keys(M).join(", ")+G))}},C.unknownArguments=function(W,J,M,q,G=!0){var T;let p=D.getInternalMethods().getCommandInstance().getCommands(),g=[],QD=D.getInternalMethods().getContext();if(Object.keys(W).forEach((V)=>{if(!D3.includes(V)&&!Object.prototype.hasOwnProperty.call(M,V)&&!Object.prototype.hasOwnProperty.call(D.getInternalMethods().getParseContext(),V)&&!C.isValidAndSomeAliasIsNotNew(V,J))g.push(V)}),G&&(QD.commands.length>0||p.length>0||q))W._.slice(QD.commands.length).forEach((V)=>{if(!p.includes(""+V))g.push(""+V)});if(G){let L=((T=D.getDemandedCommands()._)===null||T===void 0?void 0:T.max)||0,f=QD.commands.length+L;if(f<W._.length)W._.slice(f).forEach((h)=>{if(h=String(h),!QD.commands.includes(h)&&!g.includes(h))g.push(h)})}if(g.length)F.fail(B("Unknown argument: %s","Unknown arguments: %s",g.length,g.map((V)=>V.trim()?V:`"${V}"`).join(", ")))},C.unknownCommands=function(W){let J=D.getInternalMethods().getCommandInstance().getCommands(),M=[],q=D.getInternalMethods().getContext();if(q.commands.length>0||J.length>0)W._.slice(q.commands.length).forEach((G)=>{if(!J.includes(""+G))M.push(""+G)});if(M.length>0)return F.fail(B("Unknown command: %s","Unknown commands: %s",M.length,M.join(", "))),!0;else return!1},C.isValidAndSomeAliasIsNotNew=function(W,J){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;let M=D.parsed.newAliases;return[W,...J[W]].some((q)=>!Object.prototype.hasOwnProperty.call(M,q)||!M[W])},C.limitedChoices=function(W){let J=D.getOptions(),M={};if(!Object.keys(J.choices).length)return;Object.keys(W).forEach((T)=>{if(D3.indexOf(T)===-1&&Object.prototype.hasOwnProperty.call(J.choices,T))[].concat(W[T]).forEach((p)=>{if(J.choices[T].indexOf(p)===-1&&p!==void 0)M[T]=(M[T]||[]).concat(p)})});let q=Object.keys(M);if(!q.length)return;let G=E("Invalid values:");q.forEach((T)=>{G+=`
88
+ ${E("Argument: %s, Given: %s, Choices: %s",T,F.stringifiedValues(M[T]),F.stringifiedValues(J.choices[T]))}`}),F.fail(G)};let $={};C.implies=function(W,J){if(N("<string|object> [array|number|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((M)=>{C.implies(M,W[M])});else{if(D.global(W),!$[W])$[W]=[];if(Array.isArray(J))J.forEach((M)=>C.implies(W,M));else YD(J,void 0,u),$[W].push(J)}},C.getImplied=function(){return $};function X(Y,W){let J=Number(W);if(W=isNaN(J)?W:J,typeof W==="number")W=Y._.length>=W;else if(W.match(/^--no-.+/))W=W.match(/^--no-(.+)/)[1],W=!Object.prototype.hasOwnProperty.call(Y,W);else W=Object.prototype.hasOwnProperty.call(Y,W);return W}C.implications=function(W){let J=[];if(Object.keys($).forEach((M)=>{let q=M;($[M]||[]).forEach((G)=>{let T=q,p=G;if(T=X(W,T),G=X(W,G),T&&!G)J.push(` ${q} -> ${p}`)})}),J.length){let M=`${E("Implications failed:")}
89
+ `;J.forEach((q)=>{M+=q}),F.fail(M)}};let Q={};C.conflicts=function(W,J){if(N("<string|object> [array|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((M)=>{C.conflicts(M,W[M])});else{if(D.global(W),!Q[W])Q[W]=[];if(Array.isArray(J))J.forEach((M)=>C.conflicts(W,M));else Q[W].push(J)}},C.getConflicting=()=>Q,C.conflicting=function(W){if(Object.keys(W).forEach((J)=>{if(Q[J])Q[J].forEach((M)=>{if(M&&W[J]!==void 0&&W[M]!==void 0)F.fail(E("Arguments %s and %s are mutually exclusive",J,M))})}),D.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(Q).forEach((J)=>{Q[J].forEach((M)=>{if(M&&W[u.Parser.camelCase(J)]!==void 0&&W[u.Parser.camelCase(M)]!==void 0)F.fail(E("Arguments %s and %s are mutually exclusive",J,M))})})},C.recommendCommands=function(W,J){J=J.sort((T,p)=>p.length-T.length);let q=null,G=1/0;for(let T=0,p;(p=J[T])!==void 0;T++){let g=e1(W,p);if(g<=3&&g<G)G=g,q=p}if(q)F.fail(E("Did you mean %s?",q))},C.reset=function(W){return $=SD($,(J)=>!W[J]),Q=SD(Q,(J)=>!W[J]),C};let z=[];return C.freeze=function(){z.push({implied:$,conflicting:Q})},C.unfreeze=function(){let W=z.pop();YD(W,void 0,u),{implied:$,conflicting:Q}=W},C}var dF=[],_0;function K0(D,F,u,E){_0=E;let B={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return B;let C=/\.json|\..*rc$/.test(D.extends),$=null;if(!C)try{$=import.meta.resolve(D.extends)}catch(X){return D}else $=v8(F,D.extends);S8($),dF.push($),B=C?JSON.parse(_0.readFileSync($,"utf8")):E.require(D.extends),delete D.extends,B=K0(B,_0.path.dirname($),u,_0)}return dF=[],u?u3(B,D):Object.assign({},B,D)}function S8(D){if(dF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function v8(D,F){return _0.path.resolve(D,F)}function u3(D,F){let u={};function E(B){return B&&typeof B==="object"&&!Array.isArray(B)}Object.assign(u,D);for(let B of Object.keys(F))if(E(F[B])&&E(u[B]))u[B]=u3(D[B],F[B]);else u[B]=F[B];return u}var j=function(D,F,u,E,B){if(E==="m")throw TypeError("Private method is not writable");if(E==="a"&&!B)throw TypeError("Private accessor was defined without a setter");if(typeof F==="function"?D!==F||!B:!F.has(D))throw TypeError("Cannot write private member to an object whose class did not declare it");return E==="a"?B.call(D,u):B?B.value=u:F.set(D,u),u},Z=function(D,F,u,E){if(u==="a"&&!E)throw TypeError("Private accessor was defined without a getter");if(typeof F==="function"?D!==F||!E:!F.has(D))throw TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?E:u==="a"?E.call(D):E?E.value:F.get(D)},FD,nD,V0,JD,AD,y0,fD,iD,h0,qD,d0,_D,wD,GD,KD,p0,tD,ZD,x,g0,m0,HD,sD,Y0,rD,kD,l0,k,aD,eD,D0,d,c0,TD,a;function V3(D){return(F=[],u=D.process.cwd(),E)=>{let B=new R3(F,u,E,D);return Object.defineProperty(B,"argv",{get:()=>{return B.parse()},enumerable:!0}),B.help(),B.version(),B}}var E3=Symbol("copyDoubleDash"),B3=Symbol("copyDoubleDash"),pF=Symbol("deleteFromParserHintObject"),C3=Symbol("emitWarning"),$3=Symbol("freeze"),X3=Symbol("getDollarZero"),F0=Symbol("getParserConfiguration"),Z3=Symbol("getUsageConfiguration"),gF=Symbol("guessLocale"),Q3=Symbol("guessVersion"),z3=Symbol("parsePositionalNumbers"),mF=Symbol("pkgUp"),yD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),lF=Symbol("populateParserHintArrayDictionary"),cF=Symbol("populateParserHintDictionary"),oF=Symbol("sanitizeKey"),nF=Symbol("setKey"),iF=Symbol("unfreeze"),O3=Symbol("validateAsync"),Y3=Symbol("getCommandInstance"),J3=Symbol("getContext"),W3=Symbol("getHasOutput"),A3=Symbol("getLoggerInstance"),G3=Symbol("getParseContext"),H3=Symbol("getUsageInstance"),M3=Symbol("getValidationInstance"),o0=Symbol("hasParseCallback"),q3=Symbol("isGlobalContext"),u0=Symbol("postProcess"),_3=Symbol("rebase"),tF=Symbol("reset"),R0=Symbol("runYargsParserAndExecuteCommands"),sF=Symbol("runValidation"),K3=Symbol("setHasOutput"),E0=Symbol("kTrackManuallySetKeys"),f8="en_US";class R3{constructor(D=[],F,u,E){this.customScriptName=!1,this.parsed=!1,FD.set(this,void 0),nD.set(this,void 0),V0.set(this,{commands:[],fullCommands:[]}),JD.set(this,null),AD.set(this,null),y0.set(this,"show-hidden"),fD.set(this,null),iD.set(this,!0),h0.set(this,{}),qD.set(this,!0),d0.set(this,[]),_D.set(this,void 0),wD.set(this,{}),GD.set(this,!1),KD.set(this,null),p0.set(this,!0),tD.set(this,void 0),ZD.set(this,""),x.set(this,void 0),g0.set(this,void 0),m0.set(this,{}),HD.set(this,null),sD.set(this,null),Y0.set(this,{}),rD.set(this,{}),kD.set(this,void 0),l0.set(this,!1),k.set(this,void 0),aD.set(this,!1),eD.set(this,!1),D0.set(this,!1),d.set(this,void 0),c0.set(this,{}),TD.set(this,null),a.set(this,void 0),j(this,k,E,"f"),j(this,kD,D,"f"),j(this,nD,F,"f"),j(this,g0,u,"f"),j(this,_D,new yF(this),"f"),this.$0=this[X3](),this[tF](),j(this,FD,Z(this,FD,"f"),"f"),j(this,d,Z(this,d,"f"),"f"),j(this,a,Z(this,a,"f"),"f"),j(this,x,Z(this,x,"f"),"f"),Z(this,x,"f").showHiddenOpt=Z(this,y0,"f"),j(this,tD,this[B3](),"f"),Z(this,k,"f").y18n.setLocale(f8)}addHelpOpt(D,F){if(N("[string|boolean] [string]",[D,F],arguments.length),Z(this,KD,"f"))this[pF](Z(this,KD,"f")),j(this,KD,null,"f");if(D===!1&&F===void 0)return this;return j(this,KD,typeof D==="string"?D:"help","f"),this.boolean(Z(this,KD,"f")),this.describe(Z(this,KD,"f"),F||Z(this,d,"f").deferY18nLookup("Show help")),this}help(D,F){return this.addHelpOpt(D,F)}addShowHiddenOpt(D,F){if(N("[string|boolean] [string]",[D,F],arguments.length),D===!1&&F===void 0)return this;let u=typeof D==="string"?D:Z(this,y0,"f");return this.boolean(u),this.describe(u,F||Z(this,d,"f").deferY18nLookup("Show hidden options")),Z(this,x,"f").showHiddenOpt=u,this}showHidden(D,F){return this.addShowHiddenOpt(D,F)}alias(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[lF](this.alias.bind(this),"alias",D,F),this}array(D){return N("<array|string>",[D],arguments.length),this[yD]("array",D),this[E0](D),this}boolean(D){return N("<array|string>",[D],arguments.length),this[yD]("boolean",D),this[E0](D),this}check(D,F){return N("<function> [boolean]",[D,F],arguments.length),this.middleware((u,E)=>{return oD(()=>{return D(u,E.getOptions())},(B)=>{if(!B)Z(this,d,"f").fail(Z(this,k,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof B==="string"||B instanceof Error)Z(this,d,"f").fail(B.toString(),B);return u},(B)=>{return Z(this,d,"f").fail(B.message?B.message:B.toString(),B),u})},!1,F),this}choices(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[lF](this.choices.bind(this),"choices",D,F),this}coerce(D,F){if(N("<object|string|array> [function]",[D,F],arguments.length),Array.isArray(D)){if(!F)throw new DD("coerce callback must be provided");for(let E of D)this.coerce(E,F);return this}else if(typeof D==="object"){for(let E of Object.keys(D))this.coerce(E,D[E]);return this}if(!F)throw new DD("coerce callback must be provided");let u=D;return Z(this,x,"f").key[u]=!0,Z(this,_D,"f").addCoerceMiddleware((E,B)=>{var C;let $=(C=B.getAliases()[u])!==null&&C!==void 0?C:[],X=[u,...$].filter((Q)=>Object.prototype.hasOwnProperty.call(E,Q));if(X.length===0)return E;return oD(()=>{return F(E[X[0]])},(Q)=>{return X.forEach((z)=>{E[z]=Q}),E},(Q)=>{throw new DD(Q.message)})},u),this}conflicts(D,F){return N("<string|object> [string|array]",[D,F],arguments.length),Z(this,a,"f").conflicts(D,F),this}config(D="config",F,u){if(N("[object|string] [string|function] [function]",[D,F,u],arguments.length),typeof D==="object"&&!Array.isArray(D))return D=K0(D,Z(this,nD,"f"),this[F0]()["deep-merge-config"]||!1,Z(this,k,"f")),Z(this,x,"f").configObjects=(Z(this,x,"f").configObjects||[]).concat(D),this;if(typeof F==="function")u=F,F=void 0;return this.describe(D,F||Z(this,d,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(D)?D:[D]).forEach((E)=>{Z(this,x,"f").config[E]=u||!0}),this}completion(D,F,u){if(N("[string] [string|boolean|function] [function]",[D,F,u],arguments.length),typeof F==="function")u=F,F=void 0;if(j(this,AD,D||Z(this,AD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(Z(this,AD,"f"),F),u)Z(this,JD,"f").registerFunction(u);return this}command(D,F,u,E,B,C){return N("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,u,E,B,C],arguments.length),Z(this,FD,"f").addHandler(D,F,u,E,B,C),this}commands(D,F,u,E,B,C){return this.command(D,F,u,E,B,C)}commandDir(D,F){N("<string> [object]",[D,F],arguments.length);let u=Z(this,g0,"f")||Z(this,k,"f").require;return Z(this,FD,"f").addDirectory(D,u,Z(this,k,"f").getCallerFile(),F),this}count(D){return N("<array|string>",[D],arguments.length),this[yD]("count",D),this[E0](D),this}default(D,F,u){if(N("<object|string|array> [*] [string]",[D,F,u],arguments.length),u)kF(D,Z(this,k,"f")),Z(this,x,"f").defaultDescription[D]=u;if(typeof F==="function"){if(kF(D,Z(this,k,"f")),!Z(this,x,"f").defaultDescription[D])Z(this,x,"f").defaultDescription[D]=Z(this,d,"f").functionDescription(F);F=F.call()}return this[J0](this.default.bind(this),"default",D,F),this}defaults(D,F,u){return this.default(D,F,u)}demandCommand(D=1,F,u,E){if(N("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,u,E],arguments.length),typeof F!=="number")u=F,F=1/0;return this.global("_",!1),Z(this,x,"f").demandedCommands._={min:D,max:F,minMsg:u,maxMsg:E},this}demand(D,F,u){if(Array.isArray(F))F.forEach((E)=>{YD(u,!0,Z(this,k,"f")),this.demandOption(E,u)}),F=1/0;else if(typeof F!=="number")u=F,F=1/0;if(typeof D==="number")YD(u,!0,Z(this,k,"f")),this.demandCommand(D,F,u,u);else if(Array.isArray(D))D.forEach((E)=>{YD(u,!0,Z(this,k,"f")),this.demandOption(E,u)});else if(typeof u==="string")this.demandOption(D,u);else if(u===!0||typeof u>"u")this.demandOption(D);return this}demandOption(D,F){return N("<object|string|array> [string]",[D,F],arguments.length),this[J0](this.demandOption.bind(this),"demandedOptions",D,F),this}deprecateOption(D,F){return N("<string> [string|boolean]",[D,F],arguments.length),Z(this,x,"f").deprecatedOptions[D]=F,this}describe(D,F){return N("<object|string|array> [string]",[D,F],arguments.length),this[nF](D,!0),Z(this,d,"f").describe(D,F),this}detectLocale(D){return N("<boolean>",[D],arguments.length),j(this,iD,D,"f"),this}env(D){if(N("[string|boolean]",[D],arguments.length),D===!1)delete Z(this,x,"f").envPrefix;else Z(this,x,"f").envPrefix=D||"";return this}epilogue(D){return N("<string>",[D],arguments.length),Z(this,d,"f").epilog(D),this}epilog(D){return this.epilogue(D)}example(D,F){if(N("<string|array> [string]",[D,F],arguments.length),Array.isArray(D))D.forEach((u)=>this.example(...u));else Z(this,d,"f").example(D,F);return this}exit(D,F){if(j(this,GD,!0,"f"),j(this,fD,F,"f"),Z(this,qD,"f"))Z(this,k,"f").process.exit(D)}exitProcess(D=!0){return N("[boolean]",[D],arguments.length),j(this,qD,D,"f"),this}fail(D){if(N("<function|boolean>",[D],arguments.length),typeof D==="boolean"&&D!==!1)throw new DD("Invalid first argument. Expected function or boolean 'false'");return Z(this,d,"f").failFn(D),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(D,F){if(N("<array> [function]",[D,F],arguments.length),!F)return new Promise((u,E)=>{Z(this,JD,"f").getCompletion(D,(B,C)=>{if(B)E(B);else u(C)})});else return Z(this,JD,"f").getCompletion(D,F)}getDemandedOptions(){return N([],0),Z(this,x,"f").demandedOptions}getDemandedCommands(){return N([],0),Z(this,x,"f").demandedCommands}getDeprecatedOptions(){return N([],0),Z(this,x,"f").deprecatedOptions}getDetectLocale(){return Z(this,iD,"f")}getExitProcess(){return Z(this,qD,"f")}getGroups(){return Object.assign({},Z(this,wD,"f"),Z(this,rD,"f"))}getHelp(){if(j(this,GD,!0,"f"),!Z(this,d,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[R0](Z(this,kD,"f"),void 0,void 0,0,!0);if(s(F))return F.then(()=>{return Z(this,d,"f").help()})}let D=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(D))return D.then(()=>{return Z(this,d,"f").help()})}return Promise.resolve(Z(this,d,"f").help())}getOptions(){return Z(this,x,"f")}getStrict(){return Z(this,aD,"f")}getStrictCommands(){return Z(this,eD,"f")}getStrictOptions(){return Z(this,D0,"f")}global(D,F){if(N("<string|array> [boolean]",[D,F],arguments.length),D=[].concat(D),F!==!1)Z(this,x,"f").local=Z(this,x,"f").local.filter((u)=>D.indexOf(u)===-1);else D.forEach((u)=>{if(!Z(this,x,"f").local.includes(u))Z(this,x,"f").local.push(u)});return this}group(D,F){N("<string|array> <string>",[D,F],arguments.length);let u=Z(this,rD,"f")[F]||Z(this,wD,"f")[F];if(Z(this,rD,"f")[F])delete Z(this,rD,"f")[F];let E={};return Z(this,wD,"f")[F]=(u||[]).concat(D).filter((B)=>{if(E[B])return!1;return E[B]=!0}),this}hide(D){return N("<string>",[D],arguments.length),Z(this,x,"f").hiddenOptions.push(D),this}implies(D,F){return N("<string|object> [number|string|array]",[D,F],arguments.length),Z(this,a,"f").implies(D,F),this}locale(D){if(N("[string]",[D],arguments.length),D===void 0)return this[gF](),Z(this,k,"f").y18n.getLocale();return j(this,iD,!1,"f"),Z(this,k,"f").y18n.setLocale(D),this}middleware(D,F,u){return Z(this,_D,"f").addMiddleware(D,!!F,u)}nargs(D,F){return N("<string|object|array> [number]",[D,F],arguments.length),this[J0](this.nargs.bind(this),"narg",D,F),this}normalize(D){return N("<array|string>",[D],arguments.length),this[yD]("normalize",D),this}number(D){return N("<array|string>",[D],arguments.length),this[yD]("number",D),this[E0](D),this}option(D,F){if(N("<string|object> [object]",[D,F],arguments.length),typeof D==="object")Object.keys(D).forEach((u)=>{this.options(u,D[u])});else{if(typeof F!=="object")F={};if(this[E0](D),Z(this,TD,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[C3](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
90
+ `),void 0,"versionWarning");if(Z(this,x,"f").key[D]=!0,F.alias)this.alias(D,F.alias);let u=F.deprecate||F.deprecated;if(u)this.deprecateOption(D,u);let E=F.demand||F.required||F.require;if(E)this.demand(D,E);if(F.demandOption)this.demandOption(D,typeof F.demandOption==="string"?F.demandOption:void 0);if(F.conflicts)this.conflicts(D,F.conflicts);if("default"in F)this.default(D,F.default);if(F.implies!==void 0)this.implies(D,F.implies);if(F.nargs!==void 0)this.nargs(D,F.nargs);if(F.config)this.config(D,F.configParser);if(F.normalize)this.normalize(D);if(F.choices)this.choices(D,F.choices);if(F.coerce)this.coerce(D,F.coerce);if(F.group)this.group(D,F.group);if(F.boolean||F.type==="boolean"){if(this.boolean(D),F.alias)this.boolean(F.alias)}if(F.array||F.type==="array"){if(this.array(D),F.alias)this.array(F.alias)}if(F.number||F.type==="number"){if(this.number(D),F.alias)this.number(F.alias)}if(F.string||F.type==="string"){if(this.string(D),F.alias)this.string(F.alias)}if(F.count||F.type==="count")this.count(D);if(typeof F.global==="boolean")this.global(D,F.global);if(F.defaultDescription)Z(this,x,"f").defaultDescription[D]=F.defaultDescription;if(F.skipValidation)this.skipValidation(D);let B=F.describe||F.description||F.desc,C=Z(this,d,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(C,D)||typeof B==="string")this.describe(D,B);if(F.hidden)this.hide(D);if(F.requiresArg)this.requiresArg(D)}return this}options(D,F){return this.option(D,F)}parse(D,F,u){if(N("[string|array] [function|boolean|object] [function]",[D,F,u],arguments.length),this[$3](),typeof D>"u")D=Z(this,kD,"f");if(typeof F==="object")j(this,sD,F,"f"),F=u;if(typeof F==="function")j(this,HD,F,"f"),F=!1;if(!F)j(this,kD,D,"f");if(Z(this,HD,"f"))j(this,qD,!1,"f");let E=this[R0](D,!!F),B=this.parsed;if(Z(this,JD,"f").setParsed(this.parsed),s(E))return E.then((C)=>{if(Z(this,HD,"f"))Z(this,HD,"f").call(this,Z(this,fD,"f"),C,Z(this,ZD,"f"));return C}).catch((C)=>{if(Z(this,HD,"f"))Z(this,HD,"f")(C,this.parsed.argv,Z(this,ZD,"f"));throw C}).finally(()=>{this[iF](),this.parsed=B});else{if(Z(this,HD,"f"))Z(this,HD,"f").call(this,Z(this,fD,"f"),E,Z(this,ZD,"f"));this[iF](),this.parsed=B}return E}parseAsync(D,F,u){let E=this.parse(D,F,u);return!s(E)?Promise.resolve(E):E}parseSync(D,F,u){let E=this.parse(D,F,u);if(s(E))throw new DD(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return E}parserConfiguration(D){return N("<object>",[D],arguments.length),j(this,m0,D,"f"),this}pkgConf(D,F){N("<string> [string]",[D,F],arguments.length);let u=null,E=this[mF](F||Z(this,nD,"f"));if(E[D]&&typeof E[D]==="object")u=K0(E[D],F||Z(this,nD,"f"),this[F0]()["deep-merge-config"]||!1,Z(this,k,"f")),Z(this,x,"f").configObjects=(Z(this,x,"f").configObjects||[]).concat(u);return this}positional(D,F){N("<string> <object>",[D,F],arguments.length);let u=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];F=SD(F,(C,$)=>{if(C==="type"&&!["string","number","boolean"].includes($))return!1;return u.includes(C)});let E=Z(this,V0,"f").fullCommands[Z(this,V0,"f").fullCommands.length-1],B=E?Z(this,FD,"f").cmdToParseOptions(E):{array:[],alias:{},default:{},demand:{}};return z0(B).forEach((C)=>{let $=B[C];if(Array.isArray($)){if($.indexOf(D)!==-1)F[C]=!0}else if($[D]&&!(C in F))F[C]=$[D]}),this.group(D,Z(this,d,"f").getPositionalGroupName()),this.option(D,F)}recommendCommands(D=!0){return N("[boolean]",[D],arguments.length),j(this,l0,D,"f"),this}required(D,F,u){return this.demand(D,F,u)}require(D,F,u){return this.demand(D,F,u)}requiresArg(D){if(N("<array|string|object> [number]",[D],arguments.length),typeof D==="string"&&Z(this,x,"f").narg[D])return this;else this[J0](this.requiresArg.bind(this),"narg",D,NaN);return this}showCompletionScript(D,F){return N("[string] [string]",[D,F],arguments.length),D=D||this.$0,Z(this,tD,"f").log(Z(this,JD,"f").generateCompletionScript(D,F||Z(this,AD,"f")||"completion")),this}showHelp(D){if(N("[string|function]",[D],arguments.length),j(this,GD,!0,"f"),!Z(this,d,"f").hasCachedHelpMessage()){if(!this.parsed){let u=this[R0](Z(this,kD,"f"),void 0,void 0,0,!0);if(s(u))return u.then(()=>{Z(this,d,"f").showHelp(D)}),this}let F=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(F))return F.then(()=>{Z(this,d,"f").showHelp(D)}),this}return Z(this,d,"f").showHelp(D),this}scriptName(D){return this.customScriptName=!0,this.$0=D,this}showHelpOnFail(D,F){return N("[boolean|string] [string]",[D,F],arguments.length),Z(this,d,"f").showHelpOnFail(D,F),this}showVersion(D){return N("[string|function]",[D],arguments.length),Z(this,d,"f").showVersion(D),this}skipValidation(D){return N("<array|string>",[D],arguments.length),this[yD]("skipValidation",D),this}strict(D){return N("[boolean]",[D],arguments.length),j(this,aD,D!==!1,"f"),this}strictCommands(D){return N("[boolean]",[D],arguments.length),j(this,eD,D!==!1,"f"),this}strictOptions(D){return N("[boolean]",[D],arguments.length),j(this,D0,D!==!1,"f"),this}string(D){return N("<array|string>",[D],arguments.length),this[yD]("string",D),this[E0](D),this}terminalWidth(){return N([],0),Z(this,k,"f").process.stdColumns}updateLocale(D){return this.updateStrings(D)}updateStrings(D){return N("<object>",[D],arguments.length),j(this,iD,!1,"f"),Z(this,k,"f").y18n.updateLocale(D),this}usage(D,F,u,E){if(N("<string|null|undefined> [string|boolean] [function|object] [function]",[D,F,u,E],arguments.length),F!==void 0)if(YD(D,null,Z(this,k,"f")),(D||"").match(/^\$0( |$)/))return this.command(D,F,u,E);else throw new DD(".usage() description must start with $0 if being used as alias for .command()");else return Z(this,d,"f").usage(D),this}usageConfiguration(D){return N("<object>",[D],arguments.length),j(this,c0,D,"f"),this}version(D,F,u){if(N("[boolean|string] [string] [string]",[D,F,u],arguments.length),Z(this,TD,"f"))this[pF](Z(this,TD,"f")),Z(this,d,"f").version(void 0),j(this,TD,null,"f");if(arguments.length===0)u=this[Q3](),D="version";else if(arguments.length===1){if(D===!1)return this;u=D,D="version"}else if(arguments.length===2)u=F,F=void 0;return j(this,TD,typeof D==="string"?D:"version","f"),F=F||Z(this,d,"f").deferY18nLookup("Show version number"),Z(this,d,"f").version(u||void 0),this.boolean(Z(this,TD,"f")),this.describe(Z(this,TD,"f"),F),this}wrap(D){return N("<number|null|undefined>",[D],arguments.length),Z(this,d,"f").wrap(D),this}[(FD=new WeakMap,nD=new WeakMap,V0=new WeakMap,JD=new WeakMap,AD=new WeakMap,y0=new WeakMap,fD=new WeakMap,iD=new WeakMap,h0=new WeakMap,qD=new WeakMap,d0=new WeakMap,_D=new WeakMap,wD=new WeakMap,GD=new WeakMap,KD=new WeakMap,p0=new WeakMap,tD=new WeakMap,ZD=new WeakMap,x=new WeakMap,g0=new WeakMap,m0=new WeakMap,HD=new WeakMap,sD=new WeakMap,Y0=new WeakMap,rD=new WeakMap,kD=new WeakMap,l0=new WeakMap,k=new WeakMap,aD=new WeakMap,eD=new WeakMap,D0=new WeakMap,d=new WeakMap,c0=new WeakMap,TD=new WeakMap,a=new WeakMap,E3)](D){if(!D._||!D["--"])return D;D._.push.apply(D._,D["--"]);try{delete D["--"]}catch(F){}return D}[B3](){return{log:(...D)=>{if(!this[o0]())console.log(...D);if(j(this,GD,!0,"f"),Z(this,ZD,"f").length)j(this,ZD,Z(this,ZD,"f")+`
91
+ `,"f");j(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")},error:(...D)=>{if(!this[o0]())console.error(...D);if(j(this,GD,!0,"f"),Z(this,ZD,"f").length)j(this,ZD,Z(this,ZD,"f")+`
92
+ `,"f");j(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")}}}[pF](D){z0(Z(this,x,"f")).forEach((F)=>{if(((E)=>E==="configObjects")(F))return;let u=Z(this,x,"f")[F];if(Array.isArray(u)){if(u.includes(D))u.splice(u.indexOf(D),1)}else if(typeof u==="object")delete u[D]}),delete Z(this,d,"f").getDescriptions()[D]}[C3](D,F,u){if(!Z(this,h0,"f")[u])Z(this,k,"f").process.emitWarning(D,F),Z(this,h0,"f")[u]=!0}[$3](){Z(this,d0,"f").push({options:Z(this,x,"f"),configObjects:Z(this,x,"f").configObjects.slice(0),exitProcess:Z(this,qD,"f"),groups:Z(this,wD,"f"),strict:Z(this,aD,"f"),strictCommands:Z(this,eD,"f"),strictOptions:Z(this,D0,"f"),completionCommand:Z(this,AD,"f"),output:Z(this,ZD,"f"),exitError:Z(this,fD,"f"),hasOutput:Z(this,GD,"f"),parsed:this.parsed,parseFn:Z(this,HD,"f"),parseContext:Z(this,sD,"f")}),Z(this,d,"f").freeze(),Z(this,a,"f").freeze(),Z(this,FD,"f").freeze(),Z(this,_D,"f").freeze()}[X3](){let D="",F;if(/\b(node|iojs|electron)(\.exe)?$/.test(Z(this,k,"f").process.argv()[0]))F=Z(this,k,"f").process.argv().slice(1,2);else F=Z(this,k,"f").process.argv().slice(0,1);if(D=F.map((u)=>{let E=this[_3](Z(this,nD,"f"),u);return u.match(/^(\/|([a-zA-Z]:)?\\)/)&&E.length<u.length?E:u}).join(" ").trim(),Z(this,k,"f").getEnv("_")&&Z(this,k,"f").getProcessArgvBin()===Z(this,k,"f").getEnv("_"))D=Z(this,k,"f").getEnv("_").replace(`${Z(this,k,"f").path.dirname(Z(this,k,"f").process.execPath())}/`,"");return D}[F0](){return Z(this,m0,"f")}[Z3](){return Z(this,c0,"f")}[gF](){if(!Z(this,iD,"f"))return;let D=Z(this,k,"f").getEnv("LC_ALL")||Z(this,k,"f").getEnv("LC_MESSAGES")||Z(this,k,"f").getEnv("LANG")||Z(this,k,"f").getEnv("LANGUAGE")||"en_US";this.locale(D.replace(/[.:].*/,""))}[Q3](){return this[mF]().version||"unknown"}[z3](D){let F=D["--"]?D["--"]:D._;for(let u=0,E;(E=F[u])!==void 0;u++)if(Z(this,k,"f").Parser.looksLikeNumber(E)&&Number.isSafeInteger(Math.floor(parseFloat(`${E}`))))F[u]=Number(E);return D}[mF](D){let F=D||"*";if(Z(this,Y0,"f")[F])return Z(this,Y0,"f")[F];let u={};try{let E=D||Z(this,k,"f").mainFilename;if(Z(this,k,"f").path.extname(E))E=Z(this,k,"f").path.dirname(E);let B=Z(this,k,"f").findUp(E,(C,$)=>{if($.includes("package.json"))return"package.json";else return});YD(B,void 0,Z(this,k,"f")),u=JSON.parse(Z(this,k,"f").readFileSync(B,"utf8"))}catch(E){}return Z(this,Y0,"f")[F]=u||{},Z(this,Y0,"f")[F]}[yD](D,F){F=[].concat(F),F.forEach((u)=>{u=this[oF](u),Z(this,x,"f")[D].push(u)})}[J0](D,F,u,E){this[cF](D,F,u,E,(B,C,$)=>{Z(this,x,"f")[B][C]=$})}[lF](D,F,u,E){this[cF](D,F,u,E,(B,C,$)=>{Z(this,x,"f")[B][C]=(Z(this,x,"f")[B][C]||[]).concat($)})}[cF](D,F,u,E,B){if(Array.isArray(u))u.forEach((C)=>{D(C,E)});else if(((C)=>typeof C==="object")(u))for(let C of z0(u))D(C,u[C]);else B(F,this[oF](u),E)}[oF](D){if(D==="__proto__")return"___proto___";return D}[nF](D,F){return this[J0](this[nF].bind(this),"key",D,F),this}[iF](){var D,F,u,E,B,C,$,X,Q,z,Y,W;let J=Z(this,d0,"f").pop();YD(J,void 0,Z(this,k,"f"));let M;D=this,F=this,u=this,E=this,B=this,C=this,$=this,X=this,Q=this,z=this,Y=this,W=this,{options:{set value(q){j(D,x,q,"f")}}.value,configObjects:M,exitProcess:{set value(q){j(F,qD,q,"f")}}.value,groups:{set value(q){j(u,wD,q,"f")}}.value,output:{set value(q){j(E,ZD,q,"f")}}.value,exitError:{set value(q){j(B,fD,q,"f")}}.value,hasOutput:{set value(q){j(C,GD,q,"f")}}.value,parsed:this.parsed,strict:{set value(q){j($,aD,q,"f")}}.value,strictCommands:{set value(q){j(X,eD,q,"f")}}.value,strictOptions:{set value(q){j(Q,D0,q,"f")}}.value,completionCommand:{set value(q){j(z,AD,q,"f")}}.value,parseFn:{set value(q){j(Y,HD,q,"f")}}.value,parseContext:{set value(q){j(W,sD,q,"f")}}.value}=J,Z(this,x,"f").configObjects=M,Z(this,d,"f").unfreeze(),Z(this,a,"f").unfreeze(),Z(this,FD,"f").unfreeze(),Z(this,_D,"f").unfreeze()}[O3](D,F){return oD(F,(u)=>{return D(u),u})}getInternalMethods(){return{getCommandInstance:this[Y3].bind(this),getContext:this[J3].bind(this),getHasOutput:this[W3].bind(this),getLoggerInstance:this[A3].bind(this),getParseContext:this[G3].bind(this),getParserConfiguration:this[F0].bind(this),getUsageConfiguration:this[Z3].bind(this),getUsageInstance:this[H3].bind(this),getValidationInstance:this[M3].bind(this),hasParseCallback:this[o0].bind(this),isGlobalContext:this[q3].bind(this),postProcess:this[u0].bind(this),reset:this[tF].bind(this),runValidation:this[sF].bind(this),runYargsParserAndExecuteCommands:this[R0].bind(this),setHasOutput:this[K3].bind(this)}}[Y3](){return Z(this,FD,"f")}[J3](){return Z(this,V0,"f")}[W3](){return Z(this,GD,"f")}[A3](){return Z(this,tD,"f")}[G3](){return Z(this,sD,"f")||{}}[H3](){return Z(this,d,"f")}[M3](){return Z(this,a,"f")}[o0](){return!!Z(this,HD,"f")}[q3](){return Z(this,p0,"f")}[u0](D,F,u,E){if(u)return D;if(s(D))return D;if(!F)D=this[E3](D);if(this[F0]()["parse-positional-numbers"]||this[F0]()["parse-positional-numbers"]===void 0)D=this[z3](D);if(E)D=cD(D,this,Z(this,_D,"f").getMiddleware(),!1);return D}[tF](D={}){j(this,x,Z(this,x,"f")||{},"f");let F={};F.local=Z(this,x,"f").local||[],F.configObjects=Z(this,x,"f").configObjects||[];let u={};F.local.forEach((C)=>{u[C]=!0,(D[C]||[]).forEach(($)=>{u[$]=!0})}),Object.assign(Z(this,rD,"f"),Object.keys(Z(this,wD,"f")).reduce((C,$)=>{let X=Z(this,wD,"f")[$].filter((Q)=>!(Q in u));if(X.length>0)C[$]=X;return C},{})),j(this,wD,{},"f");let E=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],B=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(E.forEach((C)=>{F[C]=(Z(this,x,"f")[C]||[]).filter(($)=>!u[$])}),B.forEach((C)=>{F[C]=SD(Z(this,x,"f")[C],($)=>!u[$])}),F.envPrefix=Z(this,x,"f").envPrefix,j(this,x,F,"f"),j(this,d,Z(this,d,"f")?Z(this,d,"f").reset(u):i1(this,Z(this,k,"f")),"f"),j(this,a,Z(this,a,"f")?Z(this,a,"f").reset(u):F3(this,Z(this,d,"f"),Z(this,k,"f")),"f"),j(this,FD,Z(this,FD,"f")?Z(this,FD,"f").reset():c1(Z(this,d,"f"),Z(this,a,"f"),Z(this,_D,"f"),Z(this,k,"f")),"f"),!Z(this,JD,"f"))j(this,JD,a1(this,Z(this,d,"f"),Z(this,FD,"f"),Z(this,k,"f")),"f");return Z(this,_D,"f").reset(),j(this,AD,null,"f"),j(this,ZD,"","f"),j(this,fD,null,"f"),j(this,GD,!1,"f"),this.parsed=!1,this}[_3](D,F){return Z(this,k,"f").path.relative(D,F)}[R0](D,F,u,E=0,B=!1){var C,$,X,Q;let z=!!u||B;D=D||Z(this,kD,"f"),Z(this,x,"f").__=Z(this,k,"f").y18n.__,Z(this,x,"f").configuration=this[F0]();let Y=!!Z(this,x,"f").configuration["populate--"],W=Object.assign({},Z(this,x,"f").configuration,{"populate--":!0}),J=Z(this,k,"f").Parser.detailed(D,Object.assign({},Z(this,x,"f"),{configuration:{"parse-positional-numbers":!1,...W}})),M=Object.assign(J.argv,Z(this,sD,"f")),q=void 0,G=J.aliases,T=!1,p=!1;if(Object.keys(M).forEach((g)=>{if(g===Z(this,KD,"f")&&M[g])T=!0;else if(g===Z(this,TD,"f")&&M[g])p=!0}),M.$0=this.$0,this.parsed=J,E===0)Z(this,d,"f").clearCachedHelpMessage();try{if(this[gF](),F)return this[u0](M,Y,!!u,!1);if(Z(this,KD,"f")){if([Z(this,KD,"f")].concat(G[Z(this,KD,"f")]||[]).filter((f)=>f.length>1).includes(""+M._[M._.length-1]))M._.pop(),T=!0}j(this,p0,!1,"f");let g=Z(this,FD,"f").getCommands(),QD=((C=Z(this,JD,"f"))===null||C===void 0?void 0:C.completionKey)?[($=Z(this,JD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(X=Z(this,JD,"f"))===null||X===void 0?void 0:X.completionKey])!==null&&Q!==void 0?Q:[]].some((L)=>Object.prototype.hasOwnProperty.call(M,L)):!1,V=T||QD||B;if(M._.length){if(g.length){let L;for(let f=E||0,h;M._[f]!==void 0;f++)if(h=String(M._[f]),g.includes(h)&&h!==Z(this,AD,"f")){let t=Z(this,FD,"f").runCommand(h,this,J,f+1,B,T||p||B);return this[u0](t,Y,!!u,!1)}else if(!L&&h!==Z(this,AD,"f")){L=h;break}if(!Z(this,FD,"f").hasDefaultCommand()&&Z(this,l0,"f")&&L&&!V)Z(this,a,"f").recommendCommands(L,g)}if(Z(this,AD,"f")&&M._.includes(Z(this,AD,"f"))&&!QD){if(Z(this,qD,"f"))vD(!0);this.showCompletionScript(),this.exit(0)}}if(Z(this,FD,"f").hasDefaultCommand()&&!V){let L=Z(this,FD,"f").runCommand(null,this,J,0,B,T||p||B);return this[u0](L,Y,!!u,!1)}if(QD){if(Z(this,qD,"f"))vD(!0);D=[].concat(D);let L=D.slice(D.indexOf(`--${Z(this,JD,"f").completionKey}`)+1);return Z(this,JD,"f").getCompletion(L,(f,h)=>{if(f)throw new DD(f.message);(h||[]).forEach((t)=>{Z(this,tD,"f").log(t)}),this.exit(0)}),this[u0](M,!Y,!!u,!1)}if(!Z(this,GD,"f")){if(T){if(Z(this,qD,"f"))vD(!0);z=!0,this.showHelp((L)=>{Z(this,tD,"f").log(L),this.exit(0)})}else if(p){if(Z(this,qD,"f"))vD(!0);z=!0,Z(this,d,"f").showVersion("log"),this.exit(0)}}if(!z&&Z(this,x,"f").skipValidation.length>0)z=Object.keys(M).some((L)=>Z(this,x,"f").skipValidation.indexOf(L)>=0&&M[L]===!0);if(!z){if(J.error)throw new DD(J.error.message);if(!QD){let L=this[sF](G,{},J.error);if(!u)q=cD(M,this,Z(this,_D,"f").getMiddleware(),!0);if(q=this[O3](L,q!==null&&q!==void 0?q:M),s(q)&&!u)q=q.then(()=>{return cD(M,this,Z(this,_D,"f").getMiddleware(),!1)})}}}catch(g){if(g instanceof DD)Z(this,d,"f").fail(g.message,g);else throw g}return this[u0](q!==null&&q!==void 0?q:M,Y,!!u,!0)}[sF](D,F,u,E){let B={...this.getDemandedOptions()};return(C)=>{if(u)throw new DD(u.message);Z(this,a,"f").nonOptionCount(C),Z(this,a,"f").requiredArguments(C,B);let $=!1;if(Z(this,eD,"f"))$=Z(this,a,"f").unknownCommands(C);if(Z(this,aD,"f")&&!$)Z(this,a,"f").unknownArguments(C,D,F,!!E);else if(Z(this,D0,"f"))Z(this,a,"f").unknownArguments(C,D,{},!1,!1);Z(this,a,"f").limitedChoices(C),Z(this,a,"f").implications(C),Z(this,a,"f").conflicting(C)}}[K3](){j(this,GD,!0,"f")}[E0](D){if(typeof D==="string")Z(this,x,"f").key[D]=!0;else for(let F of D)Z(this,x,"f").key[F]=!0}}function o1(D){return!!D&&typeof D.getInternalMethods==="function"}var k8=V3(fF),U3=k8;import{performance as j3}from"node:perf_hooks";var hD=b0(aF(),1);class p8{total;message;current=0;barLength=30;startTime=j3.now();constructor(D,F){this.total=D;this.message=F}update(D,F){this.current=Math.min(D,this.total),this.render(F)}increment(D){this.update(this.current+1,D)}complete(D){this.current=this.total,this.render();let F=Math.round(j3.now()-this.startTime);console.log(hD.default.green(`✅ ${D||this.message} ${hD.default.gray(`(${F}ms)`)}`))}render(D){let F=Math.round(this.current/this.total*100),u=Math.round(this.current/this.total*this.barLength),E=this.barLength-u,B=hD.default.green("█".repeat(u))+hD.default.gray("░".repeat(E)),C=`${this.current}/${this.total}`,$=D?hD.default.gray(` ${D}`):"";if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(`${this.message} ${B} ${hD.default.cyan(C)} ${hD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
93
+ `)}}var $D=b0(aF(),1);class t0{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,u){let E=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",B=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${E}${u(D)} ${B}${F}`}success(D){console.log(this.formatMessage("✅",D,$D.default.green))}error(D,F){if(console.error(this.formatMessage("❌",D,$D.default.red)),F&&this.options.verbose){if(console.error($D.default.red(` ${F.message}`)),F.stack)console.error($D.default.gray(F.stack))}}warn(D){console.warn(this.formatMessage("⚠️",D,$D.default.yellow))}info(D){console.log(this.formatMessage("ℹ️",D,$D.default.blue))}debug(D){if(this.options.verbose)console.log(this.formatMessage("\uD83D\uDC1B",D,$D.default.magenta))}step(D){console.log(this.formatMessage("\uD83D\uDE80",D,$D.default.cyan))}progress(D){console.log(this.formatMessage("⏳",D,$D.default.blue))}plain(D,F=(u)=>u){let u=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${u}${E}${F(D)}`)}dim(D){this.plain(D,$D.default.gray)}child(D){return new t0({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${D}`:D})}configure(D){this.options={...this.options,...D}}}var B0=new t0;function s0(D){B0.success(D)}function VD(D,F){B0.error(D,F)}function eF(D){B0.warn(D)}function r0(D){B0.info(D)}function D2(D){B0.step(D)}function w3(D){B0.dim(D)}function F2(D){B0.configure(D)}function LD(D={}){return new t0(D)}function u2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function E2(D,F,u){let E=D;if(F)E+=` ${$D.default.gray(`(${F}ms)`)}`;if(s0(E),u)Object.entries(u).forEach(([B,C])=>{w3(` ${B}: ${C}`)})}function C0(D,F="•"){D.forEach((u)=>{console.log($D.default.gray(` ${F} ${u}`))})}import{existsSync as mu}from"node:fs";import{resolve as lu}from"node:path";import{existsSync as a0,mkdirSync as T3}from"node:fs";import{readdir as I3,readFile as g8,stat as m8,unlink as b3,writeFile as l8}from"node:fs/promises";import{join as B2}from"node:path";class $0{cache=new Map;config;cacheDir;constructor(D){if(this.config={enablePersistence:!0,cacheDir:".typeschema-cache",maxAge:86400000,validateCached:!0,...D},this.config.enablePersistence&&this.config.cacheDir)this.cacheDir=this.config.cacheDir}async set(D){let F=this.generateKey(D.identifier);if(this.cache.set(F,D),this.config.enablePersistence&&this.cacheDir)await this.persistSchema(D)}get(D){let F=this.generateKey(D);return this.cache.get(F)||null}getByUrl(D){for(let F of this.cache.values())if(F.identifier.url===D)return F;return null}has(D){let F=this.generateKey(D);return this.cache.has(F)}hasByUrl(D){for(let F of this.cache.values())if(F.identifier.url===D)return!0;return!1}delete(D){let F=this.generateKey(D);return this.cache.delete(F)}deleteByUrl(D){for(let[F,u]of this.cache.entries())if(u.identifier.url===D)return this.cache.delete(F);return!1}getByPackage(D){let F=[];for(let u of this.cache.values())if(u.identifier.package===D)F.push(u);return F}getByKind(D){let F=[];for(let u of this.cache.values())if(u.identifier.kind===D)F.push(u);return F}setMany(D){for(let F of D)this.set(F)}clear(){this.cache.clear()}generateKey(D){return`${D.package}:${D.version}:${D.kind}:${D.name}`}async initialize(){if(this.config.enablePersistence&&this.cacheDir){if(!a0(this.cacheDir))T3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await I3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F){let E=B2(this.cacheDir,u),B=await m8(E);if(this.config.maxAge){if(Date.now()-B.mtimeMs>this.config.maxAge){await b3(E);continue}}try{let C=await g8(E,"utf-8"),$=JSON.parse(C);if(this.config.validateCached){if(!$.schema?.identifier)continue}let X=this.generateKey($.schema.identifier);this.cache.set(X,$.schema)}catch(C){console.warn(`Failed to load cached schema from ${u}:`,C)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!a0(this.cacheDir))T3(this.cacheDir,{recursive:!0});let F={schema:D,timestamp:Date.now(),version:D.identifier.version},u=`${D.identifier.package}-${D.identifier.version}-${D.identifier.kind}-${D.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),E=B2(this.cacheDir,u);try{await l8(E,JSON.stringify(F,null,2),"utf-8")}catch(B){console.warn(`Failed to persist schema to ${E}:`,B)}}async clearDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await I3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F)await b3(B2(this.cacheDir,u))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as c8}from"crypto";var C2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return c8("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:C2,get:(B)=>D[B],set:(B,C)=>{if(D[B]=C,C.url){if(!F[C.url])F[C.url]=[];let $=F[C.url];if($&&!$.includes(B))$.push(B)}},has:(B)=>(B in D),clear:()=>{Object.keys(D).forEach((B)=>delete D[B]),Object.keys(F).forEach((B)=>delete F[B])},size:()=>Object.keys(D).length,getIdsByUrl:(B)=>F[B]||[],createReference:(B,C)=>({id:B,resourceType:C.resourceType}),getAllReferences:()=>D}};import*as K2 from"path";import*as m3 from"fs/promises";var x3="https://fs.get-ig.org/pkgs/";import*as e0 from"fs/promises";import*as P3 from"path";var A0=async(D)=>{try{return await e0.access(D),!0}catch{return!1}},G0=async(D)=>{try{await e0.mkdir(D,{recursive:!0})}catch{}},DF=async(D)=>{let F=P3.join(D,".index.json");return A0(F)};import{exec as o8}from"child_process";import{promisify as n8}from"util";var S3=n8(o8);async function $2(){try{return await S3("bun --version"),"bun"}catch{try{return await S3("npm --version"),"npm"}catch{return null}}}import*as f3 from"fs/promises";import*as k3 from"path";import{exec as i8}from"child_process";import{promisify as t8}from"util";var v3=t8(i8),X2=async(D,F,u)=>{await G0(F);let E=k3.join(F,"package.json");if(!await A0(E))await f3.writeFile(E,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let B=await $2();if(!B)throw Error("No package manager found. Please install npm or bun.");for(let C of D)try{if(B==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},X=u?`cd ${F} && bun add ${C} --registry ${u}`:`cd ${F} && bun add ${C}`;await v3(X,{env:$,maxBuffer:10485760})}else{let $=u?`cd ${F} && npm add ${C} --registry ${u}`:`cd ${F} && npm add ${C}`;await v3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${C}:`,$),$}};var FF=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as uF from"fs/promises";import*as z2 from"path";import*as Z2 from"fs/promises";import*as Q2 from"path";import{createHash as y3}from"crypto";var U0=async(D)=>{try{let F=Q2.join(D,"package-lock.json");try{let u=await Z2.readFile(F,"utf-8");return y3("sha256").update(u).digest("hex")}catch{let u=Q2.join(D,"bun.lock"),E=await Z2.readFile(u,"utf-8");return y3("sha256").update(E).digest("hex")}}catch{return null}};var O2=async(D,F,u)=>{let E=await U0(u),B={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:E||void 0},C=z2.join(F,"index.json");await uF.writeFile(C,JSON.stringify(B,null,2))},Y2=async(D)=>{try{let F=z2.join(D,"index.json"),u=await uF.readFile(F,"utf-8");return JSON.parse(u)}catch{return null}};var h3=(D)=>{if(!D||typeof D!=="object")return!1;if(!D.filename||typeof D.filename!=="string")return!1;if(!D.resourceType||typeof D.resourceType!=="string")return!1;if(!D.id||typeof D.id!=="string")return!1;let F=["url","version","kind","type"];for(let u of F)if(D[u]!==void 0&&typeof D[u]!=="string")return!1;return!0},d3=(D)=>{if(!D||typeof D!=="object")return!1;if(!D["index-version"]||typeof D["index-version"]!=="number")return!1;if(!Array.isArray(D.files))return!1;return D.files.every((F)=>h3(F))},J2=(D,F)=>{try{let u=JSON.parse(D);if(!d3(u))return null;return u}catch{return null}};import*as p3 from"fs/promises";import*as W2 from"path";var EF=async(D,F,u)=>{let E=W2.join(D,".index.json");try{let B=await p3.readFile(E,"utf-8"),C=J2(B,E);if(!C)return;for(let $ of C.files){if(!$.url)continue;let X=W2.join(D,$.filename),Q=u.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:X});u.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:X,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:C["index-version"],url:$.url,version:$.version,kind:$.kind,type:$.type,package:{name:F.name,version:F.version}};if(!u.entries[$.url])u.entries[$.url]=[];let Y=u.entries[$.url];if(Y)Y.push(z)}}catch{}};import*as g3 from"fs/promises";import*as BF from"path";var CF=async(D,F)=>{try{let u=BF.join(D,"package.json"),E=await g3.readFile(u,"utf-8"),B=JSON.parse(E),C={id:{name:B.name,version:B.version},path:D,canonical:B.canonical,fhirVersions:B.fhirVersions};F.packages[B.name]=C,await EF(D,B,F);let $=BF.join(D,"examples");if(await A0(BF.join($,".index.json")))await EF($,B,F)}catch{}};import*as A2 from"fs/promises";import*as G2 from"path";var H2=async(D,F)=>{try{let u=await A2.readdir(D,{withFileTypes:!0});for(let E of u){if(!E.isDirectory())continue;let B=G2.join(D,E.name);if(E.name.startsWith("@")){let C=await A2.readdir(B,{withFileTypes:!0});for(let $ of C){if(!$.isDirectory())continue;let X=G2.join(B,$.name);if(await DF(X))await CF(X,F)}}else if(await DF(B))await CF(B,F)}}catch{}};var M2=async(D,F,u,E)=>{if(F.package)try{return await E(D,{package:F.package.name,version:F.package.version})}catch{}return null};var q2={str:["structure"],struct:["structure"],def:["definition"],pati:["patient"],obs:["observation"],org:["organization"],pract:["practitioner"],med:["medication","medicinal"],req:["request"],resp:["response"],ref:["reference"],val:["value"],code:["codesystem","code"],cs:["codesystem"],vs:["valueset"],sd:["structuredefinition"]};var _2=(D,F)=>{if(F.length===0)return D;let u=F.map((E)=>E.toLowerCase());return D.filter((E)=>{if(!E.url)return!1;let C=[E.url.toLowerCase(),E.type?.toLowerCase()||"",E.resourceType?.toLowerCase()||""].join(" ");return u.every(($)=>{let X=C.split(/[\/\-_\.\s]+/);if(X.some((Y)=>Y.startsWith($)))return!0;let z=q2[$]||[];for(let Y of z)if(X.some((W)=>W.startsWith(Y)))return!0;return C.includes($)})})};var dD=(D)=>{let{packages:F,workingDir:u}=D,E=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:x3,B=K2.join(u,"node_modules"),C=K2.join(u,".fcm","cache"),$=FF(),X=!1,Q=new Map,z=()=>{if(!X)throw Error("CanonicalManager not initialized. Call init() first.")},Y=async()=>{if(X)return;await G0(u),await G0(C);let V=await U0(u),L=await Y2(C);if(L&&L.packageLockHash===V&&V!==null)$.entries=L.entries,$.packages=L.packages,Object.entries(L.references).forEach(([h,t])=>{$.referenceManager.set(h,t)});else{if(L&&L.packageLockHash!==V)console.log("Package dependencies have changed, rebuilding index...");await X2(F,u,E),$=FF(),await H2(B,$),await O2($,C,u)}X=!0},W=async()=>{$.entries={},$.packages={},$.referenceManager.clear(),Q.clear(),X=!1},J=async()=>{return z(),Object.values($.packages).map((V)=>V.id)},M=async(V,L)=>{if(z(),L?.sourceContext){let t=await M2(V,L.sourceContext,$,M);if(t)return t}let f=$.entries[V]||[];if(f.length===0)throw Error(`Cannot resolve canonical URL: ${V}`);let h=[...f];if(L?.package)h=h.filter((t)=>t.package?.name===L.package);if(L?.version)h=h.filter((t)=>t.version===L.version);if(h.length===0)throw Error(`No matching resource found for ${V} with given options`);return h[0]},q=async(V,L)=>{let f=await M(V,L);return G(f)},G=async(V)=>{z();let L=$.referenceManager.get(V.id);if(!L)throw Error(`Invalid reference ID: ${V.id}`);try{let f=await m3.readFile(L.filePath,"utf-8");return{...JSON.parse(f),id:V.id,resourceType:V.resourceType}}catch(f){throw Error(`Failed to read resource: ${f}`)}},T=async(V)=>{z();let L=[];if(V.url)L=$.entries[V.url]||[];else for(let f of Object.values($.entries))L.push(...f);if(V.kind!==void 0)L=L.filter((f)=>f.kind===V.kind);if(V.type!==void 0)L=L.filter((f)=>f.type===V.type);if(V.version!==void 0)L=L.filter((f)=>f.version===V.version);if(V.package){let f=V.package;L=L.filter((h)=>h.package?.name===f.name&&h.package?.version===f.version)}return L};return{init:Y,destroy:W,packages:J,resolveEntry:M,resolve:q,read:G,searchEntries:T,search:async(V)=>{let L=await T(V);return await Promise.all(L.map((h)=>G(h)))},smartSearch:async(V,L)=>{z();let f=await T({kind:L?.kind,package:L?.package});if(L?.resourceType)f=f.filter((h)=>h.resourceType===L.resourceType);if(L?.type)f=f.filter((h)=>h.type===L.type);return _2(f,V)},getSearchParametersForResource:async(V)=>{if(z(),Q.has(V))return Q.get(V);let f=(await T({})).filter((t)=>t.resourceType==="SearchParameter"),h=[];for(let t of f){let l=await G(t),jD=l.base||[];if(Array.isArray(jD)&&jD.includes(V))h.push(l)}return h.sort((t,l)=>{let jD=t.code||"",w=l.code||"";return jD.localeCompare(w)}),Q.set(V,h),h}}};function V2(D){let E=D.path.split(".").slice(1).map(($)=>({el:$}));if(E.length===0)return[];let B=E.length-1,C={};if(D.slicing){if(C.slicing={...D.slicing},D.min!==void 0)C.slicing.min=D.min;if(D.max&&D.max!=="*")C.slicing.max=parseInt(D.max)}if(D.sliceName){if(C.slice={},D.min!==void 0)C.slice.min=D.min;if(D.max&&D.max!=="*")C.slice.max=parseInt(D.max);C.sliceName=D.sliceName}return E[B]={...E[B],...C},E}function R2(D,F){let u=[],E=Math.min(D.length,F.length);for(let B=0;B<E;B++)if(D[B].el===F[B].el)u.push({el:D[B].el});else break;return u}function U2(D,F){let u=[];for(let E=0;E<F.length;E++)if(E<D.length&&D[E].el===F[E].el)u.push({...D[E],...F[E],...D[E].slicing&&!F[E].slicing&&{slicing:D[E].slicing}});else u.push(F[E]);return u}function s8(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function l3(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function r8(D,F,u,E){let B=[];for(let C=D-1;C>=F;C--){let $=u[C];if($.sliceName)B.push(l3($));B.push({type:"exit",el:$.el})}if(F>0){let C=u[F-1],$=E[F-1];if(s8(C,$))B.push(l3(C))}return B}function a8(D,F,u,E){let B=[];if(D>0&&D<=F){let C=u[D-1]||{},$=E[D-1];if($.sliceName&&(!C.sliceName||C.sliceName!==$.sliceName))B.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return B}for(let C=D;C<F;C++){let $=E[C];if(B.push({type:"enter",el:$.el}),$.sliceName)B.push({type:"enter-slice",sliceName:$.sliceName})}return B}function $F(D,F){let u=D.length,E=F.length,C=R2(D,F).length,$=r8(u,C,D,F),X=a8(C,E,D,F);return[...$,...X]}function o3(D,F){if(!D)return;return D.find((u)=>u.url===F)}function c3(D){return{Instant:"instant",Time:"time",Date:"date",DateTime:"dateTime",Decimal:"decimal",Boolean:"boolean",Integer:"integer",String:"string",Uri:"uri",Base64Binary:"base64Binary",Code:"code",Id:"id",Oid:"oid",UnsignedInt:"unsignedInt",PositiveInt:"positiveInt",Markdown:"markdown",Url:"url",Canonical:"canonical",Uuid:"uuid"}[D]||D}function e8(D){let F={};for(let[u,E]of Object.entries(D))if(typeof u==="string"&&u.startsWith("pattern")){let B=c3(u.replace(/^pattern/,""));F.pattern={type:B,value:E}}else if(typeof u==="string"&&u.startsWith("fixed")){let B=c3(u.replace(/^fixed/,""));F.pattern={type:B,value:E}}else F[u]=E;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function Du(D){let F=[];for(let u of D)if(u.targetProfile){let E=Array.isArray(u.targetProfile)?u.targetProfile:[u.targetProfile];F.push(...E)}return F.length>0?[...new Set(F)].sort():void 0}function Fu(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let u=Du(D.type);return{...D,type:[{code:"Reference"}],...u&&{refers:u}}}return D}function uu(D,F){let u=(C)=>{let $={strength:C.strength,...C.valueSet&&{valueSet:C.valueSet}},X=o3(C.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(X?.valueString)$.bindingName=X.valueString;return $};if(D.choices){let{binding:C,...$}=D;return $}if(D.choiceOf&&F.snapshot){let C=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((X)=>X.path===C);if($?.binding)return{...D,binding:u($.binding)}}if(D.binding?.valueSet)return{...D,binding:u(D.binding)};let{binding:E,...B}=D;return B}function Eu(D){if(!D.constraint||D.constraint.length===0)return D;let F={};for(let u of D.constraint)F[u.key]={expression:u.expression,human:u.human,severity:u.severity};return{...D,constraint:F}}function Bu(D,F){if(!D.type||D.type.length===0)return D;let u=D.type[0]?.extension?.[0];if(u?.url==="http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"&&u.valueUrl)return{...D,type:u.valueUrl};let E=D.type[0].code,B={...D,type:E};if(F.kind==="logical"){let C=o3(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(C?.valueCanonical)B.defaultType=C.valueCanonical}return B}function Cu(D){if(D.type?.[0]?.code!=="Extension")return D;let u=D.type[0]?.profile?.[0];if(!u)return D;return{...D,url:u,...D.min&&{min:D.min},...D.max&&D.max!=="*"&&{max:parseInt(D.max)}}}function $u(D){if(D.url)return D;let F=D.max==="*"||D.min&&D.min>=2||D.max&&parseInt(D.max)>=2,u=D.min===1,E={...D};if(delete E.min,delete E.max,F){if(E.array=!0,D.min&&D.min>0)E.min=D.min;if(D.max&&D.max!=="*")E.max=parseInt(D.max)}if(u)E._required=!0;return E}function Xu(D,F){let u=D.substring(1).split("."),E=[F.url];for(let B of u.slice(1))E.push("elements",B);return E}function Zu(D,F){if(!D.contentReference)return D;let{contentReference:u,...E}=D;return{...E,elementReference:Xu(u,F)}}function Qu(D){let{path:F,slicing:u,sliceName:E,id:B,mapping:C,example:$,alias:X,condition:Q,comment:z,definition:Y,requirements:W,extension:J,...M}=D;return M}function L2(D,F){let u=Fu(D);return u=Qu(u),u=uu(u,F),u=Eu(u),u=Zu(u,F),u=Cu(u),u=$u(u),u=Bu(u,F),u=e8(u),u}function N2(D){if(D.path.endsWith("[x]"))return!0;if(D.type&&D.type.length>1)return new Set(D.type.map((u)=>u.code)).size>1;return!1}function n3(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function i3(D){let F=D.split("/");return F[F.length-1]}function j2(D){let F=D.path.replace(/\[x\]$/,""),u=F.split(".").pop()||"";if(!D.type)return[];let E=[],B=D.type.map((z)=>u+n3(i3(z.code))),{type:C,binding:$,...X}=D,Q={...X,path:F,choices:B};E.push(Q);for(let z of D.type){let Y=n3(i3(z.code)),W={...D,path:F+Y,type:[z],choiceOf:u};if(D.binding)delete W.binding;E.push(W)}return E}function t3(D,F){let u=D[D.length-1],E=D.slice(0,-1),B=E[E.length-1],C=F(B,u);return[...E.slice(0,-1),C]}function zu(D,F){if(!D.discriminator)return{};let u={};for(let E of D.discriminator){if(!E.type||!["pattern","value",void 0].includes(E.type))continue;let B=E.path.trim();if(B==="$this"){if(F.pattern?.value)Object.assign(u,F.pattern.value)}else{let C=B.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let Y=z.replace("pattern","").toLowerCase();if(C.length===1&&C[0]===Y)u[Y]=F[z]}let X=["elements"];for(let z of C)if(X.push(z),C.indexOf(z)<C.length-1)X.push("elements");X.push("pattern");let Q=F;for(let z of X)Q=Q?.[z];if(Q?.value!==void 0){let z=u;for(let Y=0;Y<C.length-1;Y++){if(!z[C[Y]])z[C[Y]]={};z=z[C[Y]]}z[C[C.length-1]]=Q.value}}}return u}function Ou(D,F,u){let E={match:F,schema:D};if(u?.min!==void 0&&u.min!==0)E.min=u.min;if(u?.max!==void 0)E.max=u.max;return E}function Yu(D,F,u){let E=F.slicing||D.slicing||{},B=zu(E,u),C=Ou(u,B,D.slice);if(!F.slicing)F.slicing={};if(D.slicing)F.slicing={...F.slicing,...D.slicing};if(!F.slicing.slices)F.slicing.slices={};return F.slicing.slices[D.sliceName]=C,F}function Ju(D){if(!D.slicing?.slices)return{};let F={};for(let[u,E]of Object.entries(D.slicing.slices)){let{match:B,schema:C,...$}=E,{slicing:X,elements:Q,type:z,min:Y,...W}=C||{},J={};if(B?.url)J.url=B.url;if($.min!==void 0&&$.min!==0)J.min=$.min;if($.max!==void 0)J.max=$.max;if(Object.assign(J,W),Y!==void 0&&Y!==0&&J.min===void 0)J.min=Y;F[u]=J}return F}function Wu(D,F,u){let E={...F};if(D==="extension")E.extensions=Ju(u);if(!E.elements)E.elements={};let B=u.choiceOf||D,{_required:C,...$}=u;if(E.elements[D]=$,C){if(!E.required)E.required=[];if(!E.required.includes(B))E.required.push(B)}return E}function XF(D,F,u){let E=[...D];for(let B=0;B<F.length;B++){let C=F[B],X=F[B+1]?.type==="enter"?{}:u;switch(C.type){case"enter":E.push(X);break;case"enter-slice":E.push(X);break;case"exit":E=t3(E,(Q,z)=>Wu(C.el,Q,z));break;case"exit-slice":E=t3(E,(Q,z)=>Yu(C,Q,z));break}}return E}function s3(D,F){let u={};if(u.name=D.name,u.type=D.type,D.url)u.url=D.url;if(D.version)u.version=D.version;if(D.description)u.description=D.description;if(D.package_name)u.package_name=D.package_name;if(D.package_version)u.package_version=D.package_version;if(D.package_id)u.package_id=D.package_id;if(u.kind=D.kind,D.derivation)u.derivation=D.derivation;if(D.baseDefinition&&D.type!=="Element")u.base=D.baseDefinition;if(D.abstract)u.abstract=D.abstract;if(u.class=Au(D),F?.package_meta)u.package_meta=F.package_meta;return u}function Au(D){if(D.kind==="resource"&&D.derivation==="constraint")return"profile";if(D.type==="Extension")return"extension";return D.kind||"unknown"}function Gu(D){return(D.differential?.element||[]).filter((u)=>u.path.includes("."))}function r3(D){let u=Object.entries(D).sort((B,C)=>{let $=B[1].index??1/0,X=C[1].index??1/0;return $-X}),E={};for(let[B,C]of u)if(C.elements)E[B]={...C,elements:r3(C.elements)};else E[B]=C;return E}function L0(D,F=new WeakSet){if(Array.isArray(D))return D.map((u)=>L0(u,F));if(D&&typeof D==="object"){if(F.has(D))return"[Circular Reference]";F.add(D);let u={},E=Object.keys(D);for(let B of E)if(B==="elements"&&D[B])u[B]=r3(L0(D[B],F));else if(B==="required"&&Array.isArray(D[B]))u[B]=[...D[B]].sort();else u[B]=L0(D[B],F);return u}return D}function w2(D,F){if(D.kind==="primitive-type")return L0(s3(D,F));let u=s3(D,F),E=Gu(D),B=[u],C=[],$=[...E],X=0;while($.length>0){let z=$.shift();if(N2(z)){let G=j2(z);$.unshift(...G),X++;continue}let Y=V2(z),W=U2(C,Y),J=$F(C,W),q={...L2(z,D),index:X++};B=XF(B,J,q),C=W}let Q=$F(C,[]);if(B=XF(B,Q,{index:X}),B.length!==1)throw Error(`Invalid stack state: expected 1 element, got ${B.length}`);return L0(B[0])}function T2(D){if(!D)return;return D.split("|")[0]}function Hu(D){if(D.derivation==="constraint"){if(D.base&&(D.type==="Resource"||D.kind==="resource"||D.kind==="complex-type"))return"profile";return"profile"}if(D.kind)switch(D.kind){case"primitive-type":return"primitive-type";case"complex-type":return"complex-type";case"resource":return"resource"}return"resource"}function pD(D,F){return{kind:Hu(D),package:F?.name||D.package_name||"undefined",version:F?.version||D.package_version||"undefined",name:D.name,url:D.url}}function N0(D,F,u){let E=F.join(".");return{kind:"nested",package:u?.name||D.package_name||"undefined",version:u?.version||D.package_version||"undefined",name:E,url:`${D.url}#${E}`}}function j0(D,F,u){let E=T2(D)||D,B="unknown",C=E.split("/"),$=C[C.length-1];if($&&$.length>0)B=$.split(/[-_]/).map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("");if(B==="unknown"&&F?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(F.id))B=F.id;return{kind:"value-set",package:u?.name||F?.package_name||"undefined",version:u?.version||F?.package_version||"undefined",name:B,url:E}}function ZF(D,F,u,E){let B=F.join("."),C=u||`${D.name}.${B}_binding`;return{kind:"binding",package:E?.name||D.package_name||"undefined",version:E?.version||D.package_version||"undefined",name:C,url:u?`urn:fhir:binding:${C}`:`${D.url}#${B}_binding`}}async function a3(D,F,u){let E=pD(D,u);if(E.kind!=="profile")throw Error(`Expected profile, got ${E.kind} for ${D.name}`);let B;if(D.base){let Y=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,W=D.base.split("/").pop()||D.base,J=await Mu(Y,F),M=Y.startsWith("http://hl7.org/fhir/");B={kind:J,package:M?"hl7.fhir.r4.core":u?.name||D.package_name||"undefined",version:M?"4.0.1":u?.version||D.package_version||"undefined",name:W,url:Y}}let C={identifier:E,base:B,dependencies:B?[B]:[]};if(D.description)C.description=D.description;let $=qu(D,u);if(Object.keys($).length>0)C.metadata=$;if(D.elements){let Y=await QF(D,[],D.elements,F,u);if(Object.keys(Y).length>0)C.fields=Y}let X=await _u(D,F);if(Object.keys(X).length>0)C.constraints=X;let Q=await Ku(D,F);if(Q.length>0)C.extensions=Q;let z=Vu(D);if(z.length>0)C.validation=z;return C}async function Mu(D,F){try{let u=await F.resolve(D);if(u){if(u.derivation==="constraint")return"profile";if(u.kind==="resource")return"resource";if(u.kind==="complex-type")return"complex-type"}}catch(u){console.warn(`Could not resolve base schema ${D}:`,u)}if(D.includes("StructureDefinition/")&&!D.startsWith("http://hl7.org/fhir/StructureDefinition/"))return"profile";return"resource"}function qu(D,F){let u={};if(D.publisher)u.publisher=D.publisher;if(D.contact)u.contact=D.contact;if(D.copyright)u.copyright=D.copyright;if(D.purpose)u.purpose=D.purpose;if(D.experimental!==void 0)u.experimental=D.experimental;if(D.date)u.date=D.date;if(D.jurisdiction)u.jurisdiction=D.jurisdiction;if(F?.name)u.package=F.name;else if(D.package_name)u.package=D.package_name;return u}async function _u(D,F){let u={};if(!D.elements)return u;for(let[E,B]of Object.entries(D.elements)){let C={};if(B.min!==void 0)C.min=B.min;if(B.max!==void 0)C.max=String(B.max);if(B.mustSupport)C.mustSupport=!0;if(B.fixedValue!==void 0)C.fixedValue=B.fixedValue;if(B.patternValue!==void 0)C.patternValue=B.patternValue;if(B.binding)C.binding={strength:B.binding.strength,valueSet:B.binding.valueSet??""};if(B.type&&Array.isArray(B.type)&&B.type.length>0)C.types=B.type.map(($)=>{let X={code:$.code};if($.profile)X.profile=$.profile;if($.targetProfile)X.targetProfile=$.targetProfile;return X});if(B.slicing)C.slicing={discriminator:B.slicing.discriminator??[],rules:String(B.slicing),ordered:B.slicing.ordered};if(Object.keys(C).length>0)u[E]=C}return u}async function Ku(D,F){let u=[];if(!D.elements)return u;for(let[E,B]of Object.entries(D.elements))if(E.includes("extension")&&B.type&&Array.isArray(B.type)){for(let C of B.type)if(C.code==="Extension"&&C.profile)u.push({path:E,profile:C.profile,min:B.min,max:String(B.max),mustSupport:B.mustSupport})}return u}function Vu(D){let F=[];if(!D.elements)return F;for(let[u,E]of Object.entries(D.elements))if(E.constraint&&Array.isArray(E.constraint))for(let B of E.constraint)F.push({path:u,key:B.key,severity:B.severity,human:B.human,expression:B.expression});return F}function e3(D,F,u){let E=[],B=D.elements;for(let C of F)if(B=B?.[C],!B)break;if(B)E.push(B);return E}function D6(D){if(D.length===0)return{};let F={...D[0]};for(let u=D.length-1;u>=0;u--){let E=D[u],B=["choices","short","index","elements","required","excluded","binding","refers","elementReference","mustSupport","slices","slicing","url","extensions"];for(let[C,$]of Object.entries(E))if(!B.includes(C)&&$!==void 0)F[C]=$}for(let u of["choices","binding","refers","elementReference"])if(D[0]&&D[0][u]!==void 0)F[u]=D[0][u];return F}function F6(D,F,u){if(F.length===0)return!1;let E=F[F.length-1],B=F.slice(0,-1),C=D;for(let $ of B)if(C=C.elements?.[$],!C)break;if(C?.required?.includes(E))return!0;if(B.length===0&&E&&D.required?.includes(E))return!0;return!1}function u6(D,F,u){if(F.length===0)return!1;let E=F[F.length-1],B=F.slice(0,-1),C=D;for(let $ of B)if(C=C.elements?.[$],!C)break;if(C?.excluded?.includes(E))return!0;if(B.length===0&&E&&D.excluded?.includes(E))return!0;return!1}async function Ru(D,F,u){if(!D.refers||D.refers.length===0)return;let E=[];for(let B of D.refers)try{let C=await F.resolve(B);if(C)E.push(pD(C,u))}catch{}return E}function I2(D,F,u,E,B){if(u.elementReference){let C=u.elementReference.filter(($,X)=>X%2===1).map(($)=>$).filter(($)=>$!=="elements");if(C.length>0)return N0(D,C,B)}if(u.type){let C=u.type.includes("/")?u.type:`http://hl7.org/fhir/StructureDefinition/${u.type}`,$=u.type.match(/^[a-z]/)?"primitive-type":"complex-type",X=C.startsWith("http://hl7.org/fhir/");return{kind:$,package:X?"hl7.fhir.r4.core":B?.name||"undefined",version:X?"4.0.1":B?.version||"undefined",name:u.type,url:C}}return}async function zF(D,F,u,E,B){let C={array:u.array||!1,required:F6(D,F,E),excluded:u6(D,F,E)},$=I2(D,F,u,E,B);if($)C.type=$;if(u.min!==void 0)C.min=u.min;if(u.max!==void 0)C.max=u.max;if(u.choices)C.choices=u.choices;if(u.choiceOf)C.choiceOf=u.choiceOf;if(u.binding){if(C.binding=ZF(D,F,u.binding.bindingName,B),u.binding.strength==="required"&&u.type==="code"){let Q=await b2(u,E);if(Q&&Q.length>0)C.enum=Q}}let X=await Ru(u,E,B);if(X)C.reference=X;return Uu(C)}function Uu(D){let F={};for(let[u,E]of Object.entries(D))if(E!==void 0&&E!==null){if(Array.isArray(E)&&E.length===0)continue;F[u]=E}return F}function w0(D){return D.type==="BackboneElement"||D.elements&&Object.keys(D.elements).length>0||!1}function OF(D,F,u,E,B){return{type:N0(D,F,B),array:u.array||!1,required:F6(D,F,E),excluded:u6(D,F,E)}}async function Lu(D,F){try{let u=T2(D)||D,E=await F.resolve(u);if(!E)return;if(E.expansion?.contains)return E.expansion.contains.map((C)=>({system:C.system,code:C.code,display:C.display}));let B=[];if(E.compose?.include){for(let C of E.compose.include)if(C.concept)for(let $ of C.concept)B.push({system:C.system,code:$.code,display:$.display});else if(C.system&&!C.filter)try{let $=await F.resolve(C.system);if($?.concept){let X=(Q,z)=>{for(let Y of Q)if(B.push({system:z,code:Y.code,display:Y.display}),Y.concept)X(Y.concept,z)};X($.concept,C.system)}}catch{}}return B.length>0?B:void 0}catch{return}}async function b2(D,F){if(!D.binding)return;let{strength:u,valueSet:E}=D.binding;if(!E)return;if(!(u==="required"||u==="extensible"&&(D.type==="code"||D.type==="Coding")||u==="preferred"&&(D.type==="code"||D.type==="Coding")))return;if(!F.resolve)return;try{let C=await Lu(E,F);if(!C||C.length===0)return;let $=C.map((X)=>X.code).filter((X)=>X&&typeof X==="string"&&X.trim().length>0);return $.length>0&&$.length<=100?$:void 0}catch(C){console.debug(`Failed to extract enum values for ${E}: ${C}`);return}}async function Nu(D,F,u,E,B){if(!u.binding?.valueSet)return;let C=ZF(D,F,u.binding.bindingName,B),$=I2(D,F,u,E,B),X=j0(u.binding.valueSet,void 0,B),Q={identifier:C,type:$,valueset:X,strength:u.binding.strength,dependencies:[]};if($)Q.dependencies.push($);Q.dependencies.push(X);let z=await b2(u,E);if(z)Q.enum=z;return Q}async function x2(D,F,u){let E=[],B=new Set;async function C(Q,z){for(let[Y,W]of Object.entries(Q)){let J=[...z,Y],M=J.join(".");if(B.has(M))continue;if(B.add(M),W.binding){let q=await Nu(D,J,W,F,u);if(q)E.push(q)}if(W.elements)await C(W.elements,J)}}if(D.elements)await C(D.elements,[]);E.sort((Q,z)=>Q.identifier.name.localeCompare(z.identifier.name));let $=[],X=new Set;for(let Q of E)if(!X.has(Q.identifier.url))X.add(Q.identifier.url),$.push(Q);return $}function E6(D,F,u){let E=[];for(let[B,C]of Object.entries(u)){let $=[...F,B];if(w0(C))E.push([$,C]);if(C.elements)E.push(...E6(D,$,C.elements))}return E}async function ju(D,F,u,E,B){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$];if(w0(X))C[$]=OF(D,Q,X,E,B);else C[$]=await zF(D,Q,X,E,B)}return C}async function P2(D,F,u){if(!D.elements)return[];let E=[],C=E6(D,[],D.elements).filter(([$,X])=>X.elements&&Object.keys(X.elements).length>0);for(let[$,X]of C){let Q=N0(D,$,u),z;if(X.type==="BackboneElement"||!X.type)z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:X.type,url:`http://hl7.org/fhir/StructureDefinition/${X.type}`};let Y=await ju(D,$,X.elements,F,u),W={identifier:Q,base:z,fields:Y};E.push(W)}return E.sort(($,X)=>$.identifier.url.localeCompare(X.identifier.url)),E}function S2(D){let F=[];for(let u of D){if(F.push(u.identifier),u.base)F.push(u.base);for(let E of Object.values(u.fields)){if("type"in E&&E.type)F.push(E.type);if("binding"in E&&E.binding)F.push(E.binding)}}return F}async function QF(D,F,u,E,B){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$],z=e3(D,Q,E),Y=z.length>0?D6(z):X;if(w0(Y))C[$]=OF(D,Q,Y,E,B);else C[$]=await zF(D,Q,Y,E,B)}return C}function B6(D){let F=[];for(let u of Object.values(D)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding)}return F}function C6(D){let F=new Set,u=[];for(let E of D){let B=E.url;if(!F.has(B))F.add(B),u.push(E)}return u.sort((E,B)=>E.name.localeCompare(B.name)),u}function wu(D,F){if(D.base==="Extension"||D.base==="http://hl7.org/fhir/StructureDefinition/Extension")return!0;if(D.url?.includes("/extension/")||D.url?.includes("-extension"))return!0;if(D.name?.toLowerCase().includes("extension"))return!0;if(D.type==="Extension")return!0;return!1}async function Tu(D,F,u){try{let E=pD(D,u);E.kind="value-set";let B={identifier:E,description:D.description};if(D.elements){let C=[];for(let[$,X]of Object.entries(D.elements))if("code"in X&&X.code)C.push({code:X.code,display:X.short||X.definition,system:X.system});if(C.length>0)B.concept=C}return B}catch(E){return console.warn(`Failed to transform value set ${D.name}: ${E}`),null}}async function Iu(D,F,u){try{let E=pD(D,u),B;if(D.base&&D.base!=="Extension"){let X=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,Q=D.base.split("/").pop()||D.base;B={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:Q,url:X}}else B={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let C={identifier:E,base:B,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(B)C.dependencies.push(B);if(D.elements){let X=await QF(D,[],D.elements,F,u);if(Object.keys(X).length>0)C.fields=X,C.dependencies.push(...B6(X))}let $=await P2(D,F,u);if($.length>0)C.nested=$,C.dependencies.push(...S2($));return C.dependencies=C6(C.dependencies),C.dependencies=C.dependencies.filter((X)=>X.url!==E.url),C}catch(E){return console.warn(`Failed to transform extension ${D.name}: ${E}`),null}}async function v2(D,F,u){let E=[];if(!u&&(D.package_name||D.package_id))u={name:D.package_name||D.package_id||"undefined",version:D.package_version||"undefined"};let B=pD(D,u);if(B.kind==="profile"){let z=await a3(D,F,u);E.push(z);let Y=await x2(D,F,u);return E.push(...Y),E}if(B.kind==="value-set"||D.kind==="value-set"){let z=await Tu(D,F,u);if(z)E.push(z);return E}if(wu(D,B)){let z=await Iu(D,F,u);if(z)E.push(z);return E}let C;if(D.base&&D.type!=="Element"){let z=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,Y=D.base.split("/").pop()||D.base,J=new Set(["Element","BackboneElement","Quantity","Duration","Distance","Count","Age","Address","Annotation","Attachment","CodeableConcept","Coding","ContactPoint","HumanName","Identifier","Period","Range","Ratio","Reference","Timing","Money","SampledData","Signature","ContactDetail","Contributor","DataRequirement","Expression","ParameterDefinition","RelatedArtifact","TriggerDefinition","UsageContext","Dosage","Meta","Extension"]).has(Y)?"complex-type":"resource",M=z.startsWith("http://hl7.org/fhir/");C={kind:J,package:M?"hl7.fhir.r4.core":u?.name||D.package_name||"undefined",version:M?"4.0.1":u?.version||D.package_version||"undefined",name:Y,url:z}}let $={identifier:B,dependencies:[]},X=[];if(C)$.base=C,X.push(C);if(D.description)$.description=D.description;if(D.kind!=="primitive-type"&&D.elements){let z=await QF(D,[],D.elements,F,u);if(Object.keys(z).length>0)$.fields=z;X.push(...B6(z));let Y=await P2(D,F,u);if(Y.length>0)$.nested=Y,X.push(...S2(Y))}$.dependencies=X,$.dependencies=C6($.dependencies),$.dependencies=$.dependencies.filter((z)=>z.url!==B.url),E.push($);let Q=await x2(D,F,u);return E.push(...Q),E}async function $6(D,F,u){let E=[];for(let B of D){let C=await v2(B,F,u);E.push(...C)}return E}async function bu(D,F){try{let u=await F.resolve(D);if(!u||u.resourceType!=="CodeSystem")return;let E=[],B=(C,$)=>{for(let X of C)if(E.push({system:$,code:X.code,display:X.display}),X.concept)B(X.concept,$)};if(u.concept)B(u.concept,D);return E}catch{return}}async function X6(D,F){let u=[];if(D.concept){for(let E of D.concept)u.push({system:D.system,code:E.code,display:E.display});return u}if(D.system&&!D.filter){let E=await bu(D.system,F);if(E)u.push(...E)}if(D.valueSet)for(let E of D.valueSet)try{let B=await F.resolve(E);if(B){let C=await Z6(B,F);if(C)u.push(...C)}}catch{}return u}async function Z6(D,F){try{let u=[];if(D.compose){if(D.compose.include)for(let E of D.compose.include){let B=await X6(E,F);u.push(...B)}if(D.compose.exclude){let E=new Set;for(let B of D.compose.exclude){let C=await X6(B,F);for(let $ of C)E.add(`${$.system}|${$.code}`)}return u.filter((B)=>!E.has(`${B.system}|${B.code}`))}}return u.length>0?u:void 0}catch(u){console.error("Error extracting ValueSet concepts:",u);return}}async function Q6(D,F,u){let B={identifier:j0(D.url,D,u)};if(D.description)B.description=D.description;let C=await Z6(D,F);if(C&&C.length>0)B.concept=C;else if(D.compose)B.compose=D.compose;if(D.compose){let $=[],X=(Q)=>{for(let z of Q){if(z.system)$.push({kind:"value-set",package:u?.name||"undefined",version:u?.version||"undefined",name:z.system.split("/").pop()||"unknown",url:z.system});if(z.valueSet)for(let Y of z.valueSet)$.push(j0(Y,void 0,u))}};if(D.compose.include)X(D.compose.include);if(D.compose.exclude)X(D.compose.exclude)}return B}class gD{manager;options;cacheConfig;cache;logger;constructor(D={},F){this.options={verbose:!1,...D},this.manager=dD({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=F,this.logger=D.logger||LD({verbose:this.options.verbose,prefix:"TypeSchema"})}async initializeCache(){if(this.cacheConfig&&!this.cache)this.cache=new $0(this.cacheConfig),await this.cache.initialize()}async generateFromPackage(D,F){await this.initializeCache();let u=this.cacheConfig?.forceRegenerate??!1;if(this.cache&&!u){let q=this.cache.getByPackage(D);if(q.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${D} (${q.length} schemas)`),q}this.logger.step(`Loading FHIR package: ${D}${F?`@${F}`:""}`),this.manager=dD({packages:[`${D}${F?`@${F}`:""}`],workingDir:"tmp/fhir"}),await this.manager.init();let E=await this.manager.search({}),B=E.filter((q)=>q.resourceType==="StructureDefinition"),C=E.filter((q)=>q.resourceType==="ValueSet");this.logger.info(`Found ${B.length} StructureDefinitions and ${C.length} ValueSets in package`),this.logger.progress(`Converting ${B.length} StructureDefinitions to FHIRSchemas`);let $=this.applyStructureDefinitionTreeshaking(B),X=[],Q=0,z=0;for(let q of $)try{let G=w2(q);X.push(G),Q++,this.logger.debug(`Converted StructureDefinition: ${q.name||q.id} (${q.resourceType})`)}catch(G){z++,this.logger.warn(`Failed to convert StructureDefinition ${q.name||q.id}: ${G instanceof Error?G.message:String(G)}`)}if(this.logger.success(`Schema conversion completed: ${Q}/${$.length} successful, ${z} failed`),C.length>0)this.logger.debug(`${C.length} ValueSets available for enum extraction`);let Y={name:D,version:F||"latest"},W=[];if(C.length>0){this.logger.progress(`Converting ${C.length} ValueSets to TypeSchema`);let q=0,G=0;for(let T of C)try{let p=await Q6(T,this.manager,Y);if(p)W.push(p),q++,this.logger.debug(`Converted ValueSet: ${T.name||T.id}`)}catch(p){G++,this.logger.warn(`Failed to convert ValueSet ${T.name||T.id}: ${p instanceof Error?p.message:String(p)}`)}this.logger.success(`ValueSet conversion completed: ${q}/${C.length} successful, ${G} failed`)}let M=[...await this.generateFromSchemas(X,Y),...W];if(this.cache&&M.length>0){this.logger.info(`Caching ${M.length} generated schemas for package: ${D}`);for(let q of M)await this.cache.set(q);this.logger.success(`Cached ${M.length} TypeSchemas for package: ${D}`)}return M}async generateFromFhirSchema(D,F){return this.logger.info("Transforming FHIR schema to TypeSchema"),v2(D,this.manager,F)}async generateFromSchemas(D,F){this.logger.info(`Transforming ${D.length} FHIR schemas to TypeSchema`);let u=await $6(D,this.manager,F),E=[],B=this.groupTypeSchemas(u);if(E.push(...B.resources),E.push(...B.complexTypes),E.push(...B.primitives),B.profiles.length>0){this.logger.info(`Enhancing ${B.profiles.length} profiles`);let C=await this.enhanceProfiles(B.profiles);E.push(...C)}if(B.extensions.length>0){this.logger.info(`Enhancing ${B.extensions.length} extensions`);let C=await this.enhanceExtensions(B.extensions);E.push(...C)}if(B.valueSets.length>0){this.logger.info(`Enhancing ${B.valueSets.length} value sets`);let C=await this.enhanceValueSets(B.valueSets);E.push(...C)}if(B.codeSystems.length>0){this.logger.info(`Enhancing ${B.codeSystems.length} code systems`);let C=await this.enhanceCodeSystems(B.codeSystems);E.push(...C)}return this.logger.success(`Generated ${E.length} enhanced FHIR type schemas: ${B.resources.length} resources, ${B.complexTypes.length} complex types, ${B.primitives.length} primitives`),E}groupTypeSchemas(D){let F={resources:[],complexTypes:[],primitives:[],profiles:[],extensions:[],valueSets:[],codeSystems:[]};for(let u of D)switch(u.identifier.kind){case"resource":F.resources.push(u);break;case"complex-type":F.complexTypes.push(u);break;case"primitive-type":F.primitives.push(u);break;case"binding":if("metadata"in u&&u.metadata?.isExtension)F.extensions.push(u);else F.complexTypes.push(u);break;case"value-set":F.valueSets.push(u);break;default:if("metadata"in u&&u.metadata?.isCodeSystem)F.codeSystems.push(u);else F.complexTypes.push(u);break}return F}async enhanceProfiles(D){return D}async enhanceExtensions(D){return D}async enhanceValueSets(D){return D}async enhanceCodeSystems(D){return D}applyStructureDefinitionTreeshaking(D){let F=this.options.treeshake;if(!F||F.length===0)return D;this.logger.info(`Applying treeshaking filter for ResourceTypes: ${F.join(", ")}`);let u=new Map,E=new Map,B=new Map;for(let z of D){let Y=z.name||z.id;if(Y)u.set(Y,z),E.set(Y,new Set),B.set(Y,new Set)}for(let z of D){let Y=z.name||z.id;if(!Y)continue;let{realDeps:W,refTargets:J}=this.extractStructureDefinitionDependenciesWithReferences(z);E.set(Y,new Set(W)),B.set(Y,new Set(J))}let C=new Set;for(let z of F)if(u.has(z))C.add(z);else this.logger.warn(`ResourceType '${z}' not found in structure definitions`);let $=(z,Y=new Set)=>{if(Y.has(z)||!E.has(z))return;Y.add(z);let W=E.get(z)||new Set;for(let J of Array.from(W))if(u.has(J))C.add(J),$(J,Y)};for(let z of Array.from(C))$(z);let X=D.filter((z)=>{let Y=z.name||z.id;return Y&&C.has(Y)}),Q=new Set;for(let z of D){let Y=z.name||z.id;if(Y&&!C.has(Y)){if(Array.from(B.values()).some((J)=>J.has(Y)))Q.add(Y)}}if(Q.size>0)this.logger.info(`Excluded reference-only targets: ${Array.from(Q).join(", ")}`);return this.logger.success(`Treeshaking completed: kept ${X.length}/${D.length} structure definitions`),X}extractStructureDefinitionDependenciesWithReferences(D){let F=new Set,u=new Set;if(D.baseDefinition){let E=this.extractResourceNameFromUrl(D.baseDefinition);if(E)F.add(E)}if(D.snapshot?.element||D.differential?.element){let E=D.snapshot?.element||D.differential?.element;for(let B of E)if(B.type)for(let C of B.type){if(C.code){if(F.add(C.code),C.code==="Reference"&&C.targetProfile)for(let $ of C.targetProfile){let X=this.extractResourceNameFromUrl($);if(X)u.add(X)}}if(C.profile)for(let $ of C.profile){let X=this.extractResourceNameFromUrl($);if(X)F.add(X)}}}return{realDeps:Array.from(F),refTargets:Array.from(u)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as xu}from"node:fs/promises";class T0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await xu(D,"utf-8"),u=this.options.format==="auto"?this.detectFormat(F,D):this.options.format;return this.parseFromString(F,u)}async parseFromString(D,F){let u=F||this.detectFormat(D),E;if(u==="ndjson")E=this.parseNDJSON(D);else E=this.parseJSON(D);if(this.options.validate)this.validateSchemas(E);return E}async parseFromFiles(D){let F=[];for(let u of D){let E=await this.parseFromFile(u);F.push(...E)}return F}parseSchema(D){if(!D.identifier)throw Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(D.identifier))throw Error("TypeSchema identifier is invalid");return D}findByIdentifier(D,F){return D.filter((u)=>this.matchesIdentifier(u.identifier,F))}findByUrl(D,F){return D.find((u)=>u.identifier.url===F)}findByKind(D,F){return D.filter((u)=>u.identifier.kind===F)}findByPackage(D,F){return D.filter((u)=>u.identifier.package===F)}getDependencies(D){let F=[];if("base"in D&&D.base)F.push(D.base);if("dependencies"in D&&D.dependencies)F.push(...D.dependencies);if("fields"in D&&D.fields)for(let u of Object.values(D.fields)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding);if("reference"in u&&u.reference)F.push(...u.reference)}if("nested"in D&&D.nested)for(let u of D.nested){F.push(u.identifier),F.push(u.base);for(let E of Object.values(u.fields)){if("type"in E&&E.type)F.push(E.type);if("binding"in E&&E.binding)F.push(E.binding);if("reference"in E&&E.reference)F.push(...E.reference)}}if("valueset"in D){let u=D;if(F.push(u.valueset),u.type)F.push(u.type)}return this.deduplicateDependencies(F)}resolveDependencies(D,F){let u=this.getDependencies(F),E=[];for(let B of u){let C=this.findByUrl(D,B.url);if(C)E.push(C)}return E}detectFormat(D,F){if(F){if(F.endsWith(".ndjson"))return"ndjson";if(F.endsWith(".json"))return"json"}let u=D.trim();if(u.includes(`
94
94
  `)){let E=u.split(`
95
95
  `).filter((B)=>B.trim());if(E.length>1)try{if(E[0])JSON.parse(E[0]);return"ndjson"}catch{}}return"json"}parseNDJSON(D){let F=[],u=D.split(`
96
- `).filter((E)=>E.trim());for(let E of u)try{let B=JSON.parse(E);F.push(this.parseSchema(B))}catch(B){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${B}`)}return F}parseJSON(D){try{let F=JSON.parse(D);if(Array.isArray(F))return F.map((u)=>this.parseSchema(u));else return[this.parseSchema(F)]}catch(F){throw new Error(`Failed to parse JSON: ${F}`)}}validateSchemas(D){for(let F of D){if(!F.identifier)throw new Error("Schema missing identifier");if(!this.isValidIdentifier(F.identifier))throw new Error(`Invalid identifier in schema: ${JSON.stringify(F.identifier)}`)}}isValidIdentifier(D){return typeof D==="object"&&D!==null&&typeof D.kind==="string"&&typeof D.package==="string"&&typeof D.version==="string"&&typeof D.name==="string"&&typeof D.url==="string"}matchesIdentifier(D,F){return(!F.kind||D.kind===F.kind)&&(!F.package||D.package===F.package)&&(!F.version||D.version===F.version)&&(!F.name||D.name===F.name)&&(!F.url||D.url===F.url)}deduplicateDependencies(D){let F=new Set,u=[];for(let E of D)if(!F.has(E.url))F.add(E.url),u.push(E);return u.sort((E,B)=>E.name.localeCompare(B.name))}}function m2(D){return D.identifier.kind==="binding"}P0();class n2{options;constructor(D){this.options=D}handleError(D,F){if(D instanceof ND)this.handleGeneratorError(D,F);else this.handleUnknownError(D,F)}handleBatchErrors(D){let F=D.filter((E)=>E instanceof ND),u=D.filter((E)=>!(E instanceof ND));if(F.length>0)this.reportBatchErrors(F);u.forEach((E)=>{this.handleUnknownError(E)})}handleGeneratorError(D,F){switch(this.options.outputFormat){case"json":this.reportErrorAsJson(D);break;case"structured":this.reportErrorStructured(D);break;default:this.reportErrorToConsole(D)}}handleUnknownError(D,F){if(this.options.logger.error("Unexpected error occurred:",D),this.options.verbose){if(console.error(`
96
+ `).filter((E)=>E.trim());for(let E of u)try{let B=JSON.parse(E);F.push(this.parseSchema(B))}catch(B){if(this.options.strict)throw Error(`Failed to parse NDJSON line: ${B}`)}return F}parseJSON(D){try{let F=JSON.parse(D);if(Array.isArray(F))return F.map((u)=>this.parseSchema(u));else return[this.parseSchema(F)]}catch(F){throw Error(`Failed to parse JSON: ${F}`)}}validateSchemas(D){for(let F of D){if(!F.identifier)throw Error("Schema missing identifier");if(!this.isValidIdentifier(F.identifier))throw Error(`Invalid identifier in schema: ${JSON.stringify(F.identifier)}`)}}isValidIdentifier(D){return typeof D==="object"&&D!==null&&typeof D.kind==="string"&&typeof D.package==="string"&&typeof D.version==="string"&&typeof D.name==="string"&&typeof D.url==="string"}matchesIdentifier(D,F){return(!F.kind||D.kind===F.kind)&&(!F.package||D.package===F.package)&&(!F.version||D.version===F.version)&&(!F.name||D.name===F.name)&&(!F.url||D.url===F.url)}deduplicateDependencies(D){let F=new Set,u=[];for(let E of D)if(!F.has(E.url))F.add(E.url),u.push(E);return u.sort((E,B)=>E.name.localeCompare(B.name))}}function f2(D){return D.identifier.kind==="binding"}I0();class d2{options;constructor(D){this.options=D}handleError(D,F){if(D instanceof ND)this.handleGeneratorError(D,F);else this.handleUnknownError(D,F)}handleBatchErrors(D){let F=D.filter((E)=>E instanceof ND),u=D.filter((E)=>!(E instanceof ND));if(F.length>0)this.reportBatchErrors(F);u.forEach((E)=>{this.handleUnknownError(E)})}handleGeneratorError(D,F){switch(this.options.outputFormat){case"json":this.reportErrorAsJson(D);break;case"structured":this.reportErrorStructured(D);break;default:this.reportErrorToConsole(D)}}handleUnknownError(D,F){if(this.options.logger.error("Unexpected error occurred:",D),this.options.verbose){if(console.error(`
97
97
  \uD83D\uDEA8 Unexpected Error Details:`),console.error(` Type: ${D.constructor.name}`),console.error(` Message: ${D.message}`),D.stack)console.error(` Stack: ${D.stack}`);if(F?.schema)console.error(` Schema: ${F.schema.identifier.name}`);if(F?.filename)console.error(` File: ${F.filename}`)}console.error(`
98
98
  \uD83D\uDCA1 General troubleshooting suggestions:`),console.error(" • Run with --verbose flag for more details"),console.error(" • Check your input files for corruption"),console.error(" • Update to the latest version of atomic-codegen"),console.error(" • Report this issue at: https://github.com/atomic-ehr/codegen/issues")}reportErrorToConsole(D){if("getFormattedMessage"in D)console.error(D.getFormattedMessage());else{console.error(`
99
99
  ❌ ${D.constructor.name}: ${D.message}`);let F=D.getSuggestions();if(F.length>0)console.error(`
@@ -101,11 +101,11 @@ ${M.join(`
101
101
  \uD83D\uDD0D Debug Information:`),console.error(JSON.stringify(D.context,null,2))}reportErrorAsJson(D){let F={type:D.constructor.name,message:D.message,phase:D.phase,context:D.context,suggestions:D.getSuggestions(),timestamp:new Date().toISOString()};console.error(JSON.stringify(F,null,2))}reportErrorStructured(D){let F={error:{type:D.constructor.name,message:D.message,phase:D.phase},context:D.context,suggestions:D.getSuggestions(),actions:this.getRecoveryActions(D)};console.error("---"),console.error("Error Report:"),console.error(JSON.stringify(F,null,2)),console.error("---")}reportBatchErrors(D){console.error(`
102
102
  ❌ ${D.length} errors occurred during generation:`);let F=new Map;D.forEach((u)=>{let E=u.constructor.name;if(!F.has(E))F.set(E,[]);F.get(E)?.push(u)});for(let[u,E]of F){console.error(`
103
103
  \uD83D\uDCCB ${u} (${E.length} occurrences):`),E.forEach((C,$)=>{if(console.error(` ${$+1}. ${C.message}`),C.context?.schemaName)console.error(` Schema: ${C.context.schemaName}`)});let B=this.getCommonSuggestions(E);if(B.length>0)console.error(`
104
- \uD83D\uDCA1 Common suggestions:`),B.forEach((C)=>{console.error(` • ${C}`)})}}getCommonSuggestions(D){let F=D.flatMap((B)=>B.getSuggestions()),u=new Map;F.forEach((B)=>{u.set(B,(u.get(B)||0)+1)});let E=Math.ceil(D.length/2);return Array.from(u.entries()).filter(([B,C])=>C>=E).map(([B,C])=>B).slice(0,5)}getRecoveryActions(D){if("getRecoveryActions"in D)return D.getRecoveryActions();return[{action:"Review error message and suggestions above"},{action:"Check input files and configuration"},{action:"Try with --verbose flag for more information"}]}}class i2{errorHandler;constructor(D){this.errorHandler=D}async withErrorBoundary(D,F){try{return await D()}catch(u){throw this.errorHandler.handleError(u instanceof Error?u:new Error(String(u)),F),u}}async withBatchErrorBoundary(D,F){let u=[],E=[];for(let B of D)try{let C=await B();u.push(C)}catch(C){E.push(C instanceof Error?C:new Error(String(C)))}if(E.length>0)throw this.errorHandler.handleBatchErrors(E),new o2(`${E.length} operations failed`,E.filter((B)=>B instanceof ND));return u}}P0();P0();import{access as t2,mkdir as Pu,rm as Su,stat as Y6,writeFile as vu}from"node:fs/promises";import{dirname as s2,join as Z0,relative as ku}from"node:path";class r2{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,u={}){let E=performance.now(),B=Z0(this.options.outputDir,D),C=u.encoding||"utf-8",$=u.overwrite??this.options.overwrite;try{if(!$)try{await t2(B),this.logger.debug(`Skipping existing file: ${D}`);let z=await Y6(B);return{path:B,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(s2(B)),await vu(B,F,C);let X=performance.now()-E,Q=Buffer.byteLength(F,C);return this.logger.debug(`Written ${D} (${Q} bytes, ${X.toFixed(2)}ms)`),{path:B,size:Q,writeTime:X}}catch(X){throw new X0(`Failed to write file '${D}': ${X}`,"write",B,X instanceof Error?X:void 0,{canRetry:!0,alternativePaths:[Z0(process.cwd(),"backup-output",D)]})}}async writeBatch(D){this.logger.debug(`Writing batch of ${D.size} files`);let F=Array.from(D.entries()),u=[];for(let E=0;E<F.length;E+=this.options.batchSize){let C=F.slice(E,E+this.options.batchSize).map(([X,Q])=>this.writeFile(X,Q)),$=await Promise.all(C);if(u.push(...$),E+this.options.batchSize<F.length)await new Promise((X)=>setTimeout(X,10))}return u}async ensureDirectory(D){try{await Pu(D,{recursive:!0})}catch(F){throw new X0(`Failed to create directory '${D}': ${F}`,"create",D,F instanceof Error?F:void 0,{canRetry:!0,permissionFix:`chmod 755 "${s2(D)}"`})}}async cleanDirectory(D="."){let F=Z0(this.options.outputDir,D);try{await t2(F),this.logger.debug(`Cleaning directory: ${D}`),await Su(F,{recursive:!0,force:!0})}catch(u){if(u?.code!=="ENOENT")throw new X0(`Failed to clean directory '${D}': ${u}`,"delete",F,u instanceof Error?u:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let u=s2(Z0(this.options.outputDir,D)),E=Z0(this.options.outputDir,F),B=ku(u,E);if(!B.startsWith("."))B=`./${B}`;return B.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=Z0(this.options.outputDir,D);try{return await t2(F),!0}catch{return!1}}async getFileStats(D){let F=Z0(this.options.outputDir,D);try{return{size:(await Y6(F)).size,generationTime:0,writeTime:0}}catch{return null}}getOutputDirectory(){return this.options.outputDir}setBatchSize(D){this.options.batchSize=Math.max(1,Math.min(50,D))}getBatchSize(){return this.options.batchSize}}class D1{options;logger;fileManager;templateEngine;typeMapper;errorHandler;errorBoundary;progressCallback;generatedFiles=[];generationStartTime=0;cache=new Map;constructor(D){let F=this.validateConfiguration(D);if(!F.isValid)throw new c2(`Invalid generator configuration: ${F.errors.join(", ")}`,"configuration",D);if(this.options=this.mergeWithDefaults(D),this.logger=D.logger||LD({prefix:this.getLanguageName(),verbose:this.options.verbose||!1}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new n2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new i2(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),F.warnings.length>0)F.warnings.forEach((u)=>{this.logger.warn(`Configuration warning: ${u}`)})}getCapabilities(){return{language:this.getLanguageName(),fileExtensions:[this.getFileExtension()],supportsTemplates:!0,supportsCustomTypeMapping:!0,supportsIncrementalGeneration:!1,supportsValidation:!0,supportedSchemaKinds:["resource","complex-type","profile","logical"],version:"1.0.0"}}createFileManager(){return new r2({outputDir:this.options.outputDir,logger:this.logger.child("FileManager"),overwrite:this.options.overwrite})}createTemplateEngine(){return}async generate(D){return this.errorBoundary.withErrorBoundary(async()=>{this.generationStartTime=performance.now(),this.generatedFiles=[],this.logger.info(`Starting ${this.getLanguageName()} generation for ${D.length} schemas`),this.reportProgress("validation",0,D.length,"Validating schemas..."),await this.validateSchemas(D),this.reportProgress("generation",0,D.length,"Processing schemas...");let F=this.filterAndSortSchemas(D);this.logger.debug(`Filtered to ${F.length} schemas for generation`),await this.generateFiles(F),await this.runPostGenerationHooks(),this.reportProgress("complete",D.length,D.length,"Generation complete");let u=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${u.toFixed(2)}ms (avg ${(u/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(D){let F=this.fileManager.writeFile,u=new Map;this.fileManager.writeFile=async(E,B)=>{let C={path:`${this.options.outputDir}/${E}`,size:Buffer.byteLength(B,"utf-8"),writeTime:0};return u.set(E,C),C};try{let E=await this.generate(D);return E.forEach((B)=>{let C=u.get(B.filename);if(C)B.path=C.path,B.size=C.size}),E}finally{this.fileManager.writeFile=F}}file(D){if(!this.templateEngine)throw new Error("Template engine is required for fluent file generation. Override createTemplateEngine() in your generator.");let{FileBuilder:F}=(A6(),UF(W6));return new F({filename:this.ensureFileExtension(D),fileManager:this.fileManager,templateEngine:this.templateEngine,typeMapper:this.typeMapper,logger:this.logger.child("FileBuilder")})}directory(D){let{DirectoryBuilder:F}=UF(G6);return new F({path:D,fileManager:this.fileManager,logger:this.logger.child("DirectoryBuilder")})}index(D="."){if(!this.templateEngine)throw new Error("Template engine is required for index file generation. Override createTemplateEngine() in your generator.");let{IndexBuilder:F}=UF(q6);return new F({directory:D,fileManager:this.fileManager,templateEngine:this.templateEngine,logger:this.logger.child("IndexBuilder")})}onProgress(D){return this.progressCallback=D,this}validateConfiguration(D){let F=[],u=[],E=[];if(!D.outputDir)F.push("outputDir is required"),E.push("Provide a valid output directory path");if(D.outputDir&&typeof D.outputDir!=="string")F.push("outputDir must be a string");if(D.overwrite!==void 0&&typeof D.overwrite!=="boolean")F.push("overwrite must be a boolean");if(D.validate!==void 0&&typeof D.validate!=="boolean")F.push("validate must be a boolean");if(D.outputDir&&!jF("node:path").isAbsolute(D.outputDir))u.push("Using relative path for outputDir - consider using absolute path"),E.push("Use path.resolve() to convert to absolute path");if(D.validate===!1)u.push("Validation is disabled - this may lead to invalid generated code"),E.push("Consider enabling validation for better code quality");return{isValid:F.length===0,errors:F,warnings:u,suggestions:E}}mergeWithDefaults(D){return{overwrite:!0,validate:!0,verbose:!1,beginnerMode:!1,errorFormat:"console",...D}}async validateSchemas(D){if(!this.options.validate){this.logger.debug("Schema validation disabled");return}this.logger.info(`\uD83D\uDD0D Starting schema validation for ${D.length} schemas`),this.logger.debug("Schema validation enabled - performing comprehensive validation");let F=D.map((u)=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(u),this.reportProgress("validation",D.indexOf(u)+1,D.length,`Validated ${u.identifier?.name||"schema"}`)},{schema:u,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${D.length} schemas`)}async validateSchema(D){let F=[],u=D.identifier?.name||"unknown";if(this.logger.debug(`\uD83D\uDD0D Validating schema: ${u} (kind: ${D.identifier?.kind})`),!D.identifier)F.push("Schema missing identifier"),this.logger.warn(`❌ Schema missing identifier: ${JSON.stringify(D,null,2).substring(0,200)}...`);else{if(!D.identifier.name)F.push("Schema identifier missing name");if(!D.identifier.kind)F.push("Schema identifier missing kind");else{let E=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];if(!E.includes(D.identifier.kind))F.push(`Schema identifier.kind must be one of: ${E.join(", ")}`)}}if("fields"in D&&D.fields)for(let[E,B]of Object.entries(D.fields)){if(!E.trim())F.push("Field name cannot be empty");if(!B)F.push(`Field '${E}' is null or undefined`)}if(await this.detectCircularReferences(D))this.logger.warn(`⚠️ Circular reference detected in schema '${u}' - this may be expected for FHIR primitive types`);if(F.length>0)throw this.logger.error(`❌ Schema validation failed for '${u}': ${F.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(D,null,2)}`),new l2(`Schema validation failed for '${D.identifier?.name||"unknown"}'`,D,F);this.logger.debug(`✅ Schema validation passed for '${u}'`)}async detectCircularReferences(D){let F=new Set,u=new Set;return((B)=>{let C=B.identifier?.name;if(!C)return!1;if(u.has(C))return!0;if(F.has(C))return!1;if(u.add(C),"fields"in B&&B.fields){for(let $ of Object.values(B.fields))if($?.type?.name===C)return!0}return u.delete(C),F.add(C),!1})(D)}async generateFiles(D){let F=D.map((u,E)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let B=await this.generateFileForSchema(u,E,D.length);return this.generatedFiles.push(B),B},{schema:u,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`)}async generateFileForSchema(D,F,u){let E=performance.now(),B={schema:D,typeMapper:this.typeMapper,filename:this.typeMapper.formatFileName(D.identifier?.name||"unknown"),language:this.getLanguageName(),timestamp:new Date().toISOString(),imports:new Map,exports:new Set},C=await this.generateSchemaContent(D,B);if(this.options.validate)await this.validateContent(C,B);let $=B.filename+this.getFileExtension(),X=await this.fileManager.writeFile($,C),Q=performance.now()-E;return this.reportProgress("writing",F+1,u,`Generated ${$} (${X.size} bytes)`),{path:X.path,filename:$,content:C,exports:this.extractExports(C),size:X.size,timestamp:new Date,metadata:{generationTime:Q,schemaCount:1,templateName:B.templateName?.toString(),warnings:[]}}}ensureFileExtension(D){let F=this.getFileExtension();return D.endsWith(F)?D:`${D}${F}`}extractExports(D){let F=[],u=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=u.exec(D))!==null)if(E[1]){let C=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...C)}let B=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((E=B.exec(D))!==null)if(E[1])F.push(E[1]);return[...new Set(F)]}reportProgress(D,F,u,E,B){if(this.progressCallback)this.progressCallback(D,F,u,E,B);if(E&&this.options.verbose)this.logger.debug(`[${D}] ${E} (${F}/${u})`)}async runPostGenerationHooks(){}getCachedOrCompute(D,F){if(this.cache.has(D))return this.cache.get(D);let u=F();if(u instanceof Promise)return u.then((E)=>{return this.cache.set(D,E),E});else return this.cache.set(D,u),u}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((u,E)=>u+E.size,0),F=performance.now()-this.generationStartTime;return{filesGenerated:this.generatedFiles.length,totalSize:D,averageFileSize:this.generatedFiles.length>0?D/this.generatedFiles.length:0,generationTime:F,averageTimePerFile:this.generatedFiles.length>0?F/this.generatedFiles.length:0,cacheHitRate:0}}}class F1{options;constructor(D={}){this.options={generateNullable:!0,strictTypes:!0,customMappings:{},preferArraySyntax:!0,namingConvention:"PascalCase",...D}}mapType(D){if(typeof D==="string")return this.mapPrimitive(D);if(D&&typeof D==="object")switch(D.kind||D.type){case"primitive-type":return this.mapPrimitive(D.name);case"reference":return this.mapReference(D.targets||[]);case"array":{let u=this.mapType(D.element);return this.mapArray(u)}case"enum":case"coded":return this.mapEnum(D.values||[],D.name);case"complex-type":case"resource":return this.mapComplexType(D);default:return this.mapUnknownType(D)}return this.mapUnknownType(D)}mapComplexType(D){return{name:this.formatTypeName(D.name||"Unknown"),isPrimitive:!1,importPath:this.calculateImportPath(D),nullable:!D.required&&this.options.generateNullable,metadata:{kind:D.kind,package:D.package}}}mapUnknownType(D){return{name:"unknown",isPrimitive:!0,nullable:!0,metadata:{originalType:D,warning:"unmapped_type"}}}calculateImportPath(D){if(!D.name)return;return`./${this.formatFileName(D.name)}`}applyNamingConvention(D){switch(this.options.namingConvention){case"camelCase":return M6(D);case"PascalCase":return fu(D);case"snake_case":return _6(D);case"kebab-case":return yu(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function M6(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}function fu(D){let F=M6(D);return F.charAt(0).toUpperCase()+F.slice(1)}function _6(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function yu(D){return _6(D).replace(/_/g,"-")}class u1 extends F1{tsOptions;constructor(D={}){super(D);this.tsOptions={...this.options,preferUnknown:!0,useBrandedTypes:!1,preferUndefined:!0,moduleFormat:"esm",...D}}getLanguageName(){return"TypeScript"}mapPrimitive(D){let F=this.getCustomMapping(D);if(F)return{name:F,isPrimitive:!0,nullable:!1};let E={string:"string",integer:"number",decimal:"number",boolean:"boolean",dateTime:"string",date:"string",time:"string",instant:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",base64Binary:"string",code:"string",id:"string",markdown:"string",unsignedInt:"number",positiveInt:"number",xhtml:"string",json:"unknown"}[D];if(!E)return console.warn(`Unknown FHIR primitive type: ${D}`),{name:this.tsOptions.preferUnknown?"unknown":"any",isPrimitive:!0,nullable:!1,metadata:{warning:"unmapped_primitive",originalType:D}};if(this.tsOptions.useBrandedTypes&&D!==E)return{name:`${E} & { readonly __brand: '${D}' }`,isPrimitive:!1,importPath:"./brands",nullable:!1,metadata:{isBranded:!0,originalFhirType:D}};return{name:E,isPrimitive:!0,nullable:!1}}mapReference(D){if(!D||D.length===0)return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:["unknown"],nullable:!1};if(D.length===1){let u=D[0]?.name||"unknown";return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[u==="unknown"?"unknown":`'${u}'`],nullable:!1,metadata:{referencedType:u,referencedSchema:D[0]}}}return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[D.map((u)=>{let E=u.name||"unknown";return E==="unknown"?"unknown":`'${E}'`}).join(" | ")],nullable:!1,metadata:{referencedTypes:D.map((u)=>u.name||"unknown"),referencedSchemas:D}}}mapArray(D){if(this.options.preferArraySyntax)return{name:`${D.name}[]`,isPrimitive:D.isPrimitive,importPath:D.importPath,isArray:!0,nullable:!1,metadata:{elementType:D,arrayStyle:"suffix"}};else return{name:"Array",isPrimitive:!1,generics:[D.name],isArray:!0,nullable:!1,metadata:{elementType:D,arrayStyle:"generic"}}}mapOptional(D,F){if(F||!this.shouldBeNullable(F))return D;let u=this.tsOptions.preferUndefined?"undefined":"null";return{...D,name:`${D.name} | ${u}`,nullable:!0,metadata:{...D.metadata,nullabilityType:u,wasOptional:!0}}}mapEnum(D,F){let u=F?this.formatTypeName(F):"CodedValue";return{name:D.map((B)=>`'${B}'`).join(" | "),isPrimitive:!1,nullable:!1,metadata:{enumName:u,values:D,isUnionType:!0}}}formatTypeName(D){return this.applyNamingConvention(D)}formatFieldName(D){return du(D)}formatFileName(D){return this.applyNamingConvention(D)}generateInterfaceField(D,F,u){return`${this.formatFieldName(D)}${u?"":"?"}: ${F.name};`}generateImportStatement(D){if(!D.importPath||D.isPrimitive)return;if(this.tsOptions.moduleFormat==="esm")return`import type { ${D.name} } from '${D.importPath}';`;else return`const { ${D.name} } = require('${D.importPath}');`}getRequiredImports(D){let F=new Set;for(let u of D){let E=this.generateImportStatement(u);if(E)F.add(E)}return Array.from(F).sort()}}function du(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}class MF extends D1{profilesByPackage=new Map;resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return"TypeScript"}getFileExtension(){return".ts"}createTypeMapper(){let D=this.options;return new u1({namingConvention:(D.namingConvention??"PascalCase")==="PascalCase"?"PascalCase":"camelCase",moduleFormat:D.moduleFormat==="cjs"?"commonjs":"esm",preferUndefined:!0,...D.typeMapperOptions})}async generateSchemaContent(D,F){if(this.shouldSkipSchema(D))return"";if(D.identifier.kind==="resource")this.resourceTypes.add(this.typeMapper.formatTypeName(D.identifier.name));if(D.identifier.name==="Reference")return this.generateReferenceInterface(D);let u=this.generateTypeScriptInterface(D),E="";if("nested"in D&&D.nested&&Array.isArray(D.nested))E=D.nested.map((C)=>this.generateNestedTypeInterface(D.identifier.name,C)).join(`
104
+ \uD83D\uDCA1 Common suggestions:`),B.forEach((C)=>{console.error(` • ${C}`)})}}getCommonSuggestions(D){let F=D.flatMap((B)=>B.getSuggestions()),u=new Map;F.forEach((B)=>{u.set(B,(u.get(B)||0)+1)});let E=Math.ceil(D.length/2);return Array.from(u.entries()).filter(([B,C])=>C>=E).map(([B,C])=>B).slice(0,5)}getRecoveryActions(D){if("getRecoveryActions"in D)return D.getRecoveryActions();return[{action:"Review error message and suggestions above"},{action:"Check input files and configuration"},{action:"Try with --verbose flag for more information"}]}}class p2{errorHandler;constructor(D){this.errorHandler=D}async withErrorBoundary(D,F){try{return await D()}catch(u){throw this.errorHandler.handleError(u instanceof Error?u:Error(String(u)),F),u}}async withBatchErrorBoundary(D,F){let u=[],E=[];for(let B of D)try{let C=await B();u.push(C)}catch(C){E.push(C instanceof Error?C:Error(String(C)))}if(E.length>0)throw this.errorHandler.handleBatchErrors(E),new h2(`${E.length} operations failed`,E.filter((B)=>B instanceof ND));return u}}I0();I0();import{access as g2,mkdir as Pu,rm as Su,stat as z6,writeFile as vu}from"node:fs/promises";import{dirname as m2,join as Z0,relative as fu}from"node:path";class l2{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,u={}){let E=performance.now(),B=Z0(this.options.outputDir,D),C=u.encoding||"utf-8",$=u.overwrite??this.options.overwrite;try{if(!$)try{await g2(B),this.logger.debug(`Skipping existing file: ${D}`);let z=await z6(B);return{path:B,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(m2(B)),await vu(B,F,C);let X=performance.now()-E,Q=Buffer.byteLength(F,C);return this.logger.debug(`Written ${D} (${Q} bytes, ${X.toFixed(2)}ms)`),{path:B,size:Q,writeTime:X}}catch(X){throw new X0(`Failed to write file '${D}': ${X}`,"write",B,X instanceof Error?X:void 0,{canRetry:!0,alternativePaths:[Z0(process.cwd(),"backup-output",D)]})}}async writeBatch(D){this.logger.debug(`Writing batch of ${D.size} files`);let F=Array.from(D.entries()),u=[];for(let E=0;E<F.length;E+=this.options.batchSize){let C=F.slice(E,E+this.options.batchSize).map(([X,Q])=>this.writeFile(X,Q)),$=await Promise.all(C);if(u.push(...$),E+this.options.batchSize<F.length)await new Promise((X)=>setTimeout(X,10))}return u}async ensureDirectory(D){try{await Pu(D,{recursive:!0})}catch(F){throw new X0(`Failed to create directory '${D}': ${F}`,"create",D,F instanceof Error?F:void 0,{canRetry:!0,permissionFix:`chmod 755 "${m2(D)}"`})}}async cleanDirectory(D="."){let F=Z0(this.options.outputDir,D);try{await g2(F),this.logger.debug(`Cleaning directory: ${D}`),await Su(F,{recursive:!0,force:!0})}catch(u){if(u?.code!=="ENOENT")throw new X0(`Failed to clean directory '${D}': ${u}`,"delete",F,u instanceof Error?u:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let u=m2(Z0(this.options.outputDir,D)),E=Z0(this.options.outputDir,F),B=fu(u,E);if(!B.startsWith("."))B=`./${B}`;return B.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=Z0(this.options.outputDir,D);try{return await g2(F),!0}catch{return!1}}async getFileStats(D){let F=Z0(this.options.outputDir,D);try{return{size:(await z6(F)).size,generationTime:0,writeTime:0}}catch{return null}}getOutputDirectory(){return this.options.outputDir}setBatchSize(D){this.options.batchSize=Math.max(1,Math.min(50,D))}getBatchSize(){return this.options.batchSize}}class n2{options;logger;fileManager;templateEngine;typeMapper;errorHandler;errorBoundary;progressCallback;generatedFiles=[];generationStartTime=0;cache=new Map;constructor(D){let F=this.validateConfiguration(D);if(!F.isValid)throw new y2(`Invalid generator configuration: ${F.errors.join(", ")}`,"configuration",D);if(this.options=this.mergeWithDefaults(D),this.logger=D.logger||LD({prefix:this.getLanguageName(),verbose:this.options.verbose||!1}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new d2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new p2(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),F.warnings.length>0)F.warnings.forEach((u)=>{this.logger.warn(`Configuration warning: ${u}`)})}getCapabilities(){return{language:this.getLanguageName(),fileExtensions:[this.getFileExtension()],supportsTemplates:!0,supportsCustomTypeMapping:!0,supportsIncrementalGeneration:!1,supportsValidation:!0,supportedSchemaKinds:["resource","complex-type","profile","logical"],version:"1.0.0"}}createFileManager(){return new l2({outputDir:this.options.outputDir,logger:this.logger.child("FileManager"),overwrite:this.options.overwrite})}createTemplateEngine(){return}async generate(D){return this.errorBoundary.withErrorBoundary(async()=>{this.generationStartTime=performance.now(),this.generatedFiles=[],this.logger.info(`Starting ${this.getLanguageName()} generation for ${D.length} schemas`),this.reportProgress("validation",0,D.length,"Validating schemas..."),await this.validateSchemas(D),this.reportProgress("generation",0,D.length,"Processing schemas...");let F=this.filterAndSortSchemas(D);this.logger.debug(`Filtered to ${F.length} schemas for generation`),await this.generateFiles(F),await this.runPostGenerationHooks(),this.reportProgress("complete",D.length,D.length,"Generation complete");let u=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${u.toFixed(2)}ms (avg ${(u/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(D){let F=this.fileManager.writeFile,u=new Map;this.fileManager.writeFile=async(E,B)=>{let C={path:`${this.options.outputDir}/${E}`,size:Buffer.byteLength(B,"utf-8"),writeTime:0};return u.set(E,C),C};try{let E=await this.generate(D);return E.forEach((B)=>{let C=u.get(B.filename);if(C)B.path=C.path,B.size=C.size}),E}finally{this.fileManager.writeFile=F}}file(D){if(!this.templateEngine)throw Error("Template engine is required for fluent file generation. Override createTemplateEngine() in your generator.");let{FileBuilder:F}=(J6(),MF(Y6));return new F({filename:this.ensureFileExtension(D),fileManager:this.fileManager,templateEngine:this.templateEngine,typeMapper:this.typeMapper,logger:this.logger.child("FileBuilder")})}directory(D){let{DirectoryBuilder:F}=MF(W6);return new F({path:D,fileManager:this.fileManager,logger:this.logger.child("DirectoryBuilder")})}index(D="."){if(!this.templateEngine)throw Error("Template engine is required for index file generation. Override createTemplateEngine() in your generator.");let{IndexBuilder:F}=MF(G6);return new F({directory:D,fileManager:this.fileManager,templateEngine:this.templateEngine,logger:this.logger.child("IndexBuilder")})}onProgress(D){return this.progressCallback=D,this}validateConfiguration(D){let F=[],u=[],E=[];if(!D.outputDir)F.push("outputDir is required"),E.push("Provide a valid output directory path");if(D.outputDir&&typeof D.outputDir!=="string")F.push("outputDir must be a string");if(D.overwrite!==void 0&&typeof D.overwrite!=="boolean")F.push("overwrite must be a boolean");if(D.validate!==void 0&&typeof D.validate!=="boolean")F.push("validate must be a boolean");if(D.outputDir&&!KF("node:path").isAbsolute(D.outputDir))u.push("Using relative path for outputDir - consider using absolute path"),E.push("Use path.resolve() to convert to absolute path");if(D.validate===!1)u.push("Validation is disabled - this may lead to invalid generated code"),E.push("Consider enabling validation for better code quality");return{isValid:F.length===0,errors:F,warnings:u,suggestions:E}}mergeWithDefaults(D){return{overwrite:!0,validate:!0,verbose:!1,beginnerMode:!1,errorFormat:"console",...D}}async validateSchemas(D){if(!this.options.validate){this.logger.debug("Schema validation disabled");return}this.logger.info(`\uD83D\uDD0D Starting schema validation for ${D.length} schemas`),this.logger.debug("Schema validation enabled - performing comprehensive validation");let F=D.map((u)=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(u),this.reportProgress("validation",D.indexOf(u)+1,D.length,`Validated ${u.identifier?.name||"schema"}`)},{schema:u,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${D.length} schemas`)}async validateSchema(D){let F=[],u=D.identifier?.name||"unknown";if(this.logger.debug(`\uD83D\uDD0D Validating schema: ${u} (kind: ${D.identifier?.kind})`),!D.identifier)F.push("Schema missing identifier"),this.logger.warn(`❌ Schema missing identifier: ${JSON.stringify(D,null,2).substring(0,200)}...`);else{if(!D.identifier.name)F.push("Schema identifier missing name");if(!D.identifier.kind)F.push("Schema identifier missing kind");else{let E=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];if(!E.includes(D.identifier.kind))F.push(`Schema identifier.kind must be one of: ${E.join(", ")}`)}}if("fields"in D&&D.fields)for(let[E,B]of Object.entries(D.fields)){if(!E.trim())F.push("Field name cannot be empty");if(!B)F.push(`Field '${E}' is null or undefined`)}if(await this.detectCircularReferences(D))this.logger.warn(`⚠️ Circular reference detected in schema '${u}' - this may be expected for FHIR primitive types`);if(F.length>0)throw this.logger.error(`❌ Schema validation failed for '${u}': ${F.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(D,null,2)}`),new k2(`Schema validation failed for '${D.identifier?.name||"unknown"}'`,D,F);this.logger.debug(`✅ Schema validation passed for '${u}'`)}async detectCircularReferences(D){let F=new Set,u=new Set;return((B)=>{let C=B.identifier?.name;if(!C)return!1;if(u.has(C))return!0;if(F.has(C))return!1;if(u.add(C),"fields"in B&&B.fields){for(let $ of Object.values(B.fields))if($?.type?.name===C)return!0}return u.delete(C),F.add(C),!1})(D)}async generateFiles(D){let F=D.map((u,E)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let B=await this.generateFileForSchema(u,E,D.length);return this.generatedFiles.push(B),B},{schema:u,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`)}async generateFileForSchema(D,F,u){let E=performance.now(),B={schema:D,typeMapper:this.typeMapper,filename:this.typeMapper.formatFileName(D.identifier?.name||"unknown"),language:this.getLanguageName(),timestamp:new Date().toISOString(),imports:new Map,exports:new Set},C=await this.generateSchemaContent(D,B);if(this.options.validate)await this.validateContent(C,B);let $=B.filename+this.getFileExtension(),X=await this.fileManager.writeFile($,C),Q=performance.now()-E;return this.reportProgress("writing",F+1,u,`Generated ${$} (${X.size} bytes)`),{path:X.path,filename:$,content:C,exports:this.extractExports(C),size:X.size,timestamp:new Date,metadata:{generationTime:Q,schemaCount:1,templateName:B.templateName?.toString(),warnings:[]}}}ensureFileExtension(D){let F=this.getFileExtension();return D.endsWith(F)?D:`${D}${F}`}extractExports(D){let F=[],u=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=u.exec(D))!==null)if(E[1]){let C=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...C)}let B=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((E=B.exec(D))!==null)if(E[1])F.push(E[1]);return[...new Set(F)]}reportProgress(D,F,u,E,B){if(this.progressCallback)this.progressCallback(D,F,u,E,B);if(E&&this.options.verbose)this.logger.debug(`[${D}] ${E} (${F}/${u})`)}async runPostGenerationHooks(){}getCachedOrCompute(D,F){if(this.cache.has(D))return this.cache.get(D);let u=F();if(u instanceof Promise)return u.then((E)=>{return this.cache.set(D,E),E});else return this.cache.set(D,u),u}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((u,E)=>u+E.size,0),F=performance.now()-this.generationStartTime;return{filesGenerated:this.generatedFiles.length,totalSize:D,averageFileSize:this.generatedFiles.length>0?D/this.generatedFiles.length:0,generationTime:F,averageTimePerFile:this.generatedFiles.length>0?F/this.generatedFiles.length:0,cacheHitRate:0}}}class i2{options;constructor(D={}){this.options={generateNullable:!0,strictTypes:!0,customMappings:{},preferArraySyntax:!0,namingConvention:"PascalCase",...D}}mapType(D){if(typeof D==="string")return this.mapPrimitive(D);if(D&&typeof D==="object")switch(D.kind||D.type){case"primitive-type":return this.mapPrimitive(D.name);case"reference":return this.mapReference(D.targets||[]);case"array":{let u=this.mapType(D.element);return this.mapArray(u)}case"enum":case"coded":return this.mapEnum(D.values||[],D.name);case"complex-type":case"resource":return this.mapComplexType(D);default:return this.mapUnknownType(D)}return this.mapUnknownType(D)}mapComplexType(D){return{name:this.formatTypeName(D.name||"Unknown"),isPrimitive:!1,importPath:this.calculateImportPath(D),nullable:!D.required&&this.options.generateNullable,metadata:{kind:D.kind,package:D.package}}}mapUnknownType(D){return{name:"unknown",isPrimitive:!0,nullable:!0,metadata:{originalType:D,warning:"unmapped_type"}}}calculateImportPath(D){if(!D.name)return;return`./${this.formatFileName(D.name)}`}applyNamingConvention(D){switch(this.options.namingConvention){case"camelCase":return H6(D);case"PascalCase":return ku(D);case"snake_case":return M6(D);case"kebab-case":return yu(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function H6(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}function ku(D){let F=H6(D);return F.charAt(0).toUpperCase()+F.slice(1)}function M6(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function yu(D){return M6(D).replace(/_/g,"-")}class t2 extends i2{tsOptions;constructor(D={}){super(D);this.tsOptions={...this.options,preferUnknown:!0,useBrandedTypes:!1,preferUndefined:!0,moduleFormat:"esm",...D}}getLanguageName(){return"TypeScript"}mapPrimitive(D){let F=this.getCustomMapping(D);if(F)return{name:F,isPrimitive:!0,nullable:!1};let E={string:"string",integer:"number",decimal:"number",boolean:"boolean",dateTime:"string",date:"string",time:"string",instant:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",base64Binary:"string",code:"string",id:"string",markdown:"string",unsignedInt:"number",positiveInt:"number",xhtml:"string",json:"unknown"}[D];if(!E)return console.warn(`Unknown FHIR primitive type: ${D}`),{name:this.tsOptions.preferUnknown?"unknown":"any",isPrimitive:!0,nullable:!1,metadata:{warning:"unmapped_primitive",originalType:D}};if(this.tsOptions.useBrandedTypes&&D!==E)return{name:`${E} & { readonly __brand: '${D}' }`,isPrimitive:!1,importPath:"./brands",nullable:!1,metadata:{isBranded:!0,originalFhirType:D}};return{name:E,isPrimitive:!0,nullable:!1}}mapReference(D){if(!D||D.length===0)return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:["unknown"],nullable:!1};if(D.length===1){let u=D[0]?.name||"unknown";return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[u==="unknown"?"unknown":`'${u}'`],nullable:!1,metadata:{referencedType:u,referencedSchema:D[0]}}}return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[D.map((u)=>{let E=u.name||"unknown";return E==="unknown"?"unknown":`'${E}'`}).join(" | ")],nullable:!1,metadata:{referencedTypes:D.map((u)=>u.name||"unknown"),referencedSchemas:D}}}mapArray(D){if(this.options.preferArraySyntax)return{name:`${D.name}[]`,isPrimitive:D.isPrimitive,importPath:D.importPath,isArray:!0,nullable:!1,metadata:{elementType:D,arrayStyle:"suffix"}};else return{name:"Array",isPrimitive:!1,generics:[D.name],isArray:!0,nullable:!1,metadata:{elementType:D,arrayStyle:"generic"}}}mapOptional(D,F){if(F||!this.shouldBeNullable(F))return D;let u=this.tsOptions.preferUndefined?"undefined":"null";return{...D,name:`${D.name} | ${u}`,nullable:!0,metadata:{...D.metadata,nullabilityType:u,wasOptional:!0}}}mapEnum(D,F){let u=F?this.formatTypeName(F):"CodedValue";return{name:D.map((B)=>`'${B}'`).join(" | "),isPrimitive:!1,nullable:!1,metadata:{enumName:u,values:D,isUnionType:!0}}}formatTypeName(D){return this.applyNamingConvention(D)}formatFieldName(D){return hu(D)}formatFileName(D){return this.applyNamingConvention(D)}generateInterfaceField(D,F,u){return`${this.formatFieldName(D)}${u?"":"?"}: ${F.name};`}generateImportStatement(D){if(!D.importPath||D.isPrimitive)return;if(this.tsOptions.moduleFormat==="esm")return`import type { ${D.name} } from '${D.importPath}';`;else return`const { ${D.name} } = require('${D.importPath}');`}getRequiredImports(D){let F=new Set;for(let u of D){let E=this.generateImportStatement(u);if(E)F.add(E)}return Array.from(F).sort()}}function hu(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}class JF extends n2{profilesByPackage=new Map;resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return"TypeScript"}getFileExtension(){return".ts"}createTypeMapper(){let D=this.options;return new t2({namingConvention:(D.namingConvention??"PascalCase")==="PascalCase"?"PascalCase":"camelCase",moduleFormat:D.moduleFormat==="cjs"?"commonjs":"esm",preferUndefined:!0,...D.typeMapperOptions})}async generateSchemaContent(D,F){if(this.shouldSkipSchema(D))return"";if(D.identifier.kind==="resource")this.resourceTypes.add(this.typeMapper.formatTypeName(D.identifier.name));if(D.identifier.name==="Reference")return this.generateReferenceInterface(D);let u=this.generateTypeScriptInterface(D),E="";if("nested"in D&&D.nested&&Array.isArray(D.nested))E=D.nested.map((C)=>this.generateNestedTypeInterface(D.identifier.name,C)).join(`
105
105
 
106
106
  `);if(E)return`${u}
107
107
 
108
- ${E}`;return u}filterAndSortSchemas(D){return this.collectedValueSets=this.collectValueSets(D),D.filter((F)=>!this.shouldSkipSchema(F))}async validateContent(D,F){let u=/export\s+(interface|class|type|enum)\s+\w+/.test(D),E=D.includes("{")&&D.includes("}");if(!u)throw new Error(`Generated content for ${F.schema.identifier.name} does not contain valid export statements`);if(!E)throw new Error(`Generated content for ${F.schema.identifier.name} has invalid syntax (missing braces)`)}async transformSchemas(D){let F=[];for(let u of D){let E=await this.transformSchema(u);if(E)F.push(E)}return F}async transformSchema(D){if(this.shouldSkipSchema(D))return;let F={schema:D,typeMapper:this.typeMapper,filename:this.getFilenameForSchema(D),language:"TypeScript",timestamp:new Date().toISOString()},u=await this.generateSchemaContent(D,F);if(!u.trim())return;let E=this.extractImportsFromContent(u,D),B=this.extractExportsFromContent(u,D),C=this.getFilenameForSchema(D);return{content:u,imports:E,exports:Array.from(B),filename:C}}shouldGenerateValueSet(D){if(!m2(D)||!D.enum||!Array.isArray(D.enum)||D.enum.length===0)return!1;switch(this.options.valueSetMode||"required-only"){case"all":return!0;case"required-only":return D.strength==="required";case"custom":return(this.options.valueSetStrengths||["required"]).includes(D.strength);default:return D.strength==="required"}}collectValueSets(D){let F=new Map;for(let u of D)if(this.shouldGenerateValueSet(u)&&m2(u)){let E=this.typeMapper.formatTypeName(u.identifier.name);F.set(E,u)}return F}shouldUseValueSetType(D){if(!D)return!1;if(!this.tsOptions.generateValueSets)return!1;let F=this.typeMapper.formatTypeName(D.name);return this.collectedValueSets.has(F)}getValueSetTypeName(D){return this.typeMapper.formatTypeName(D.name)}shouldUseInlineEnum(D){if(!D)return!1;if(this.tsOptions.generateValueSets)return!1;return D.enum&&Array.isArray(D.enum)&&D.enum.length>0}generateInlineEnumType(D){if(!D.enum||!Array.isArray(D.enum))return"string";return D.enum.map((u)=>`'${u}'`).join(" | ")}shouldSkipSchema(D){if(D.identifier.kind==="value-set"||D.identifier.kind==="binding"||D.identifier.kind==="primitive-type")return!0;if(!this.tsOptions.includeExtensions){let F=D.identifier.url;if(F&&F.includes("StructureDefinition/")){let u=F.split("StructureDefinition/")[1];if(u){let E=u.includes("-"),B=D.identifier.kind==="profile";if(E&&B)return!0}}}return!1}getFilenameForSchema(D){return`${this.typeMapper.formatFileName(D.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(D,F){let u=new Map,E=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,B;while((B=E.exec(D))!==null){let C=B[1],$=B[2];if(!C||!$)continue;let X=C.split(",").map((Q)=>Q.trim());for(let Q of X)u.set(Q,$)}return u}extractExportsFromContent(D,F){let u=new Set,E=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,B;while((B=E.exec(D))!==null)if(B[1])u.add(B[1]);return u.add(this.typeMapper.formatTypeName(F.identifier.name)),u}sanitizePackageName(D){return D.replace(/[^a-zA-Z0-9-_.]/g,"-")}generateReferenceInterface(D){let F=[],u=new Set;if("fields"in D&&D.fields)for(let[,E]of Object.entries(D.fields))this.collectFieldImports(E).forEach((C)=>u.add(C));if(F.push("import type { ResourceType } from './utilities.js';"),u.size>0){let E=Array.from(u).sort();for(let B of E)F.push(`import type { ${B} } from './${B}.js';`)}if(F.push(""),this.tsOptions.includeDocuments&&D.description){if(F.push("/**"),F.push(` * ${D.description}`),D.identifier.url)F.push(` * @see ${D.identifier.url}`);if(D.identifier.package)F.push(` * @package ${D.identifier.package}`);F.push(" * @template T - The resource type being referenced"),F.push(" */")}if(F.push("export interface Reference<T extends ResourceType = ResourceType> {"),"fields"in D&&D.fields)for(let[E,B]of Object.entries(D.fields))if(E==="type")F.push(" type?: T;");else{let C=this.generateFieldLines(E,B);for(let $ of C)if($)F.push(` ${$}`)}return F.push("}"),F.join(`
108
+ ${E}`;return u}filterAndSortSchemas(D){return this.collectedValueSets=this.collectValueSets(D),D.filter((F)=>!this.shouldSkipSchema(F))}async validateContent(D,F){let u=/export\s+(interface|class|type|enum)\s+\w+/.test(D),E=D.includes("{")&&D.includes("}");if(!u)throw Error(`Generated content for ${F.schema.identifier.name} does not contain valid export statements`);if(!E)throw Error(`Generated content for ${F.schema.identifier.name} has invalid syntax (missing braces)`)}async transformSchemas(D){let F=[];for(let u of D){let E=await this.transformSchema(u);if(E)F.push(E)}return F}async transformSchema(D){if(this.shouldSkipSchema(D))return;let F={schema:D,typeMapper:this.typeMapper,filename:this.getFilenameForSchema(D),language:"TypeScript",timestamp:new Date().toISOString()},u=await this.generateSchemaContent(D,F);if(!u.trim())return;let E=this.extractImportsFromContent(u,D),B=this.extractExportsFromContent(u,D),C=this.getFilenameForSchema(D);return{content:u,imports:E,exports:Array.from(B),filename:C}}shouldGenerateValueSet(D){if(!f2(D)||!D.enum||!Array.isArray(D.enum)||D.enum.length===0)return!1;switch(this.options.valueSetMode||"required-only"){case"all":return!0;case"required-only":return D.strength==="required";case"custom":return(this.options.valueSetStrengths||["required"]).includes(D.strength);default:return D.strength==="required"}}collectValueSets(D){let F=new Map;for(let u of D)if(this.shouldGenerateValueSet(u)&&f2(u)){let E=this.typeMapper.formatTypeName(u.identifier.name);F.set(E,u)}return F}shouldUseValueSetType(D){if(!D)return!1;if(!this.tsOptions.generateValueSets)return!1;let F=this.typeMapper.formatTypeName(D.name);return this.collectedValueSets.has(F)}getValueSetTypeName(D){return this.typeMapper.formatTypeName(D.name)}shouldUseInlineEnum(D){if(!D)return!1;if(this.tsOptions.generateValueSets)return!1;return D.enum&&Array.isArray(D.enum)&&D.enum.length>0}generateInlineEnumType(D){if(!D.enum||!Array.isArray(D.enum))return"string";return D.enum.map((u)=>`'${u}'`).join(" | ")}shouldSkipSchema(D){if(D.identifier.kind==="value-set"||D.identifier.kind==="binding"||D.identifier.kind==="primitive-type")return!0;if(!this.tsOptions.includeExtensions){let F=D.identifier.url;if(F&&F.includes("StructureDefinition/")){let u=F.split("StructureDefinition/")[1];if(u){let E=u.includes("-"),B=D.identifier.kind==="profile";if(E&&B)return!0}}}return!1}getFilenameForSchema(D){return`${this.typeMapper.formatFileName(D.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(D,F){let u=new Map,E=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,B;while((B=E.exec(D))!==null){let C=B[1],$=B[2];if(!C||!$)continue;let X=C.split(",").map((Q)=>Q.trim());for(let Q of X)u.set(Q,$)}return u}extractExportsFromContent(D,F){let u=new Set,E=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,B;while((B=E.exec(D))!==null)if(B[1])u.add(B[1]);return u.add(this.typeMapper.formatTypeName(F.identifier.name)),u}sanitizePackageName(D){return D.replace(/[^a-zA-Z0-9-_.]/g,"-")}generateReferenceInterface(D){let F=[],u=new Set;if("fields"in D&&D.fields)for(let[,E]of Object.entries(D.fields))this.collectFieldImports(E).forEach((C)=>u.add(C));if(F.push("import type { ResourceType } from './utilities.js';"),u.size>0){let E=Array.from(u).sort();for(let B of E)F.push(`import type { ${B} } from './${B}.js';`)}if(F.push(""),this.tsOptions.includeDocuments&&D.description){if(F.push("/**"),F.push(` * ${D.description}`),D.identifier.url)F.push(` * @see ${D.identifier.url}`);if(D.identifier.package)F.push(` * @package ${D.identifier.package}`);F.push(" * @template T - The resource type being referenced"),F.push(" */")}if(F.push("export interface Reference<T extends ResourceType = ResourceType> {"),"fields"in D&&D.fields)for(let[E,B]of Object.entries(D.fields))if(E==="type")F.push(" type?: T;");else{let C=this.generateFieldLines(E,B);for(let $ of C)if($)F.push(` ${$}`)}return F.push("}"),F.join(`
109
109
  `)}generateTypeScriptInterface(D){let F=[],u=this.typeMapper.formatTypeName(D.identifier.name),E=new Set,B=new Set;if("fields"in D&&D.fields)for(let[,C]of Object.entries(D.fields)){let $=this.collectFieldImports(C);for(let X of $)if(this.collectedValueSets.has(X))B.add(X);else E.add(X)}if("nested"in D&&D.nested&&Array.isArray(D.nested)){for(let C of D.nested)if(C.fields)for(let[,$]of Object.entries(C.fields)){let X=this.collectFieldImports($);for(let Q of X)if(this.collectedValueSets.has(Q))B.add(Q);else E.add(Q)}}if(E.size>0){let C=Array.from(E).sort();for(let $ of C)F.push(`import type { ${$} } from './${$}.js';`)}if(B.size>0){let $=Array.from(B).sort().join(", ");F.push(`import type { ${$} } from './valuesets/index.js';`)}if(E.size>0||B.size>0)F.push("");if(this.tsOptions.includeDocuments&&D.description){if(F.push("/**"),F.push(` * ${D.description}`),D.identifier.url)F.push(` * @see ${D.identifier.url}`);if(D.identifier.package)F.push(` * @package ${D.identifier.package}`);F.push(" */")}if(F.push(`export interface ${u} {`),D.identifier.kind==="resource")F.push(` resourceType: '${u}';`);if("fields"in D&&D.fields)for(let[C,$]of Object.entries(D.fields)){let X=this.generateFieldLines(C,$);for(let Q of X)if(Q)F.push(` ${Q}`)}return F.push("}"),F.join(`
110
110
  `)}collectFieldImports(D){let F=[];if("choices"in D&&D.choices&&Array.isArray(D.choices))return F;if(D.binding&&this.shouldUseValueSetType(D.binding)){let u=this.getValueSetTypeName(D.binding);return F.push(u),F}if("type"in D&&D.type){if(D.type.kind==="nested")return F;let u=this.typeMapper.mapType(D.type);if(!u.isPrimitive&&u.name!=="any"){if(!["string","number","boolean","Date","object","unknown","any"].includes(u.name))F.push(u.name)}}return[...new Set(F)]}extractReferenceTypes(D){let F=[];if(!Array.isArray(D))return F;for(let u of D){if(!u||typeof u!=="object")continue;if(u.kind==="resource"&&u.name){let E=this.typeMapper.formatTypeName(u.name);F.push(E)}}return[...new Set(F)]}generateNestedTypeInterface(D,F){let u=[],E=this.typeMapper.formatTypeName(`${D}${this.capitalizeFirst(F.identifier.name)}`);if(this.tsOptions.includeDocuments&&F.description){if(u.push("/**"),u.push(` * ${F.description}`),F.identifier.url)u.push(` * @see ${F.identifier.url}`);u.push(" */")}if(u.push(`export interface ${E} {`),F.fields)for(let[B,C]of Object.entries(F.fields)){let $=this.generateFieldLines(B,C);for(let X of $)if(X)u.push(` ${X}`)}return u.push("}"),u.join(`
111
111
  `)}capitalizeFirst(D){return D.charAt(0).toUpperCase()+D.slice(1)}generateFieldLines(D,F){if("choices"in F&&F.choices&&Array.isArray(F.choices))return[];let u=this.generateFieldLine(D,F);return u?[u]:[]}generateFieldLine(D,F){let u="any",E=!1,B=!1;if("type"in F&&F.type){if(F.binding&&this.shouldUseValueSetType(F.binding))u=this.getValueSetTypeName(F.binding);else if(F.binding&&this.shouldUseInlineEnum(F))u=this.generateInlineEnumType(F);else if(u=this.typeMapper.mapType(F.type).name,F.type.kind==="nested"){let Q=F.type.url?.split("#")||[];if(Q.length===2){let z=Q[0].split("/").pop()||"",Y=F.type.name;u=this.typeMapper.formatTypeName(`${z}${this.capitalizeFirst(Y)}`)}else u=this.typeMapper.formatTypeName(F.type.name)}else if(u==="Reference"&&F.reference&&Array.isArray(F.reference)){let Q=this.extractReferenceTypes(F.reference);if(Q.length>0)Q.forEach((Y)=>this.resourceTypes.add(Y)),u=`Reference<${Q.map((Y)=>`'${Y}'`).join(" | ")}>`}}if("required"in F)E=F.required;if("array"in F)B=F.array;return`${D}${E?"":"?"}: ${u}${B?"[]":""};`}extractExports(D){let F=[],u=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=u.exec(D))!==null)if(E[1]){let C=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...C)}let B=[/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+enum\s+(\w+)/g,/export\s+const\s+(\w+)/g,/export\s+function\s+(\w+)/g];for(let C of B){let $;while(($=C.exec(D))!==null)if($[1])F.push($[1])}return[...new Set(F)]}setOutputDir(D){this.options.outputDir=D}setOptions(D){this.options={...this.options,...D}}getOptions(){return{...this.options}}async generate(D){return await this.fileManager.cleanDirectory(),this.logger.debug("Cleaned output directory before generation"),super.generate(D)}async runPostGenerationHooks(){await super.runPostGenerationHooks(),await this.generateValueSetFiles(),await this.generateUtilitiesFile(),await this.generateMainIndexFile()}async generateUtilitiesFile(){if(this.resourceTypes.size===0){this.logger.warn("No resource types found, skipping utilities.ts generation");return}let D=[];D.push("/**"),D.push(" * FHIR Resource Type Utilities"),D.push(" * This file contains utility types for FHIR resources."),D.push(" * "),D.push(" * @generated This file is auto-generated. Do not edit manually."),D.push(" */"),D.push("");let F=Array.from(this.resourceTypes).sort();D.push("/**"),D.push(" * Union of all FHIR resource types in this package"),D.push(" */"),D.push("export type ResourceType =");for(let E=0;E<F.length;E++){let C=E===F.length-1?";":"";D.push(` | '${F[E]}'${C}`)}D.push(""),D.push("/**"),D.push(" * Helper type for creating typed References"),D.push(" * @example Reference<'Patient' | 'Practitioner'> - Reference that can point to Patient or Practitioner"),D.push(" */"),D.push("export type TypedReference<T extends ResourceType> = {"),D.push(" reference?: string;"),D.push(" type?: T;"),D.push(" identifier?: any; // Simplified for utility"),D.push(" display?: string;"),D.push("};");let u=D.join(`
@@ -113,9 +113,9 @@ ${E}`;return u}filterAndSortSchemas(D){return this.collectedValueSets=this.colle
113
113
  `)||"",E=[];if(this.options.includeDocuments){if(E.push("/**"),E.push(` * ${D.identifier.name} value set`),D.description)E.push(` * ${D.description}`);if(D.valueset?.url)E.push(` * @see ${D.valueset.url}`);if(D.identifier.package)E.push(` * @package ${D.identifier.package}`);E.push(" * @generated This file is auto-generated. Do not edit manually."),E.push(" */"),E.push("")}if(E.push(`export const ${F}Values = [`),u)E.push(u);if(E.push("] as const;"),E.push(""),E.push(`export type ${F} = typeof ${F}Values[number];`),this.tsOptions.includeValueSetHelpers)E.push(""),E.push(`export const isValid${F} = (value: string): value is ${F} =>`),E.push(` ${F}Values.includes(value as ${F});`);return E.join(`
114
114
  `)}async generateValueSetFiles(){if(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)return;for(let[D,F]of this.collectedValueSets){let u=this.generateValueSetFile(F),E=`valuesets/${D}.ts`;await this.fileManager.writeFile(E,u),this.logger.info(`Generated value set: ${E}`)}await this.generateValueSetIndexFile()}async generateValueSetIndexFile(){let D=[];if(this.tsOptions.includeDocuments)D.push("/**"),D.push(" * FHIR Value Sets"),D.push(" * This file re-exports all generated value sets."),D.push(" * "),D.push(" * @generated This file is auto-generated. Do not edit manually."),D.push(" */"),D.push("");let F=Array.from(this.collectedValueSets.keys()).sort();for(let E of F)D.push(`export * from './${E}.js';`);let u=D.join(`
115
115
  `);await this.fileManager.writeFile("valuesets/index.ts",u),this.logger.info(`Generated valuesets/index.ts with ${this.collectedValueSets.size} value sets`)}async generateMainIndexFile(){if(!this.options.generateIndex)return;let D=[];if(this.tsOptions.includeDocuments)D.push("/**"),D.push(" * FHIR R4 TypeScript Types"),D.push(" * Generated from FHIR StructureDefinitions"),D.push(" * "),D.push(" * @generated This file is auto-generated. Do not edit manually."),D.push(" */"),D.push("");if(D.push('export * from "./utilities.js";'),this.tsOptions.generateValueSets&&this.collectedValueSets.size>0)D.push(""),D.push("// Value Sets"),D.push('export * from "./valuesets/index.js";');let F=D.join(`
116
- `);await this.fileManager.writeFile("index.ts",F),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`)}}class _F{schemas=[];options;generators=new Map;progressCallback;cache;pendingOperations=[];typeSchemaGenerator;logger;typeSchemaConfig;constructor(D={}){if(this.options={outputDir:D.outputDir||"./generated",verbose:D.verbose??!1,overwrite:D.overwrite??!0,validate:D.validate??!0,cache:D.cache??!0,typeSchemaConfig:D.typeSchemaConfig},this.typeSchemaConfig=D.typeSchemaConfig,this.logger=D.logger||LD({verbose:this.options.verbose,prefix:"API"}),this.options.cache)this.cache=new mD(this.typeSchemaConfig)}fromPackage(D,F){this.logger.debug(`Loading from FHIR package: ${D}@${F||"latest"}`);let u=this.loadFromPackage(D,F);return this.pendingOperations.push(u),this}fromFiles(...D){this.logger.debug(`Loading from ${D.length} TypeSchema files`);let F=this.loadFromFiles(D);return this.pendingOperations.push(F),this}fromSchemas(D){return this.logger.debug(`Adding ${D.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...D],this}typescript(D={}){let F=`${this.options.outputDir}/types`,u=new MF({outputDir:F,moduleFormat:D.moduleFormat||"esm",generateIndex:D.generateIndex??!0,includeDocuments:D.includeDocuments??!0,namingConvention:D.namingConvention||"PascalCase",includeExtensions:D.includeExtensions??!1,includeProfiles:D.includeProfiles??!1,generateValueSets:D.generateValueSets??!1,includeValueSetHelpers:D.includeValueSetHelpers??!1,valueSetStrengths:D.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:D.valueSetMode??"required-only",valueSetDirectory:D.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:!0,overwrite:this.options.overwrite});return this.generators.set("typescript",u),this.logger.debug(`Configured TypeScript generator (${D.moduleFormat||"esm"})`),this}onProgress(D){return this.progressCallback=D,this}outputTo(D){this.logger.debug(`Setting output directory: ${D}`),this.options.outputDir=D;for(let F of this.generators.values())if(F.setOutputDir)F.setOutputDir(D);return this}verbose(D=!0){return this.options.verbose=D,this}validate(D=!0){return this.options.validate=D,this}async generate(){let D=performance.now(),F={success:!1,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{if(this.reportProgress("Loading",0,4,"Loading TypeSchema data..."),await this.resolveSchemas(),this.logger.debug(`Resolved ${this.schemas.length} schemas`),this.reportProgress("Validating",1,4,"Validating TypeSchema documents..."),this.options.validate)this.logger.debug("Starting schema validation"),await this.validateSchemas(F),this.logger.debug("Schema validation completed");this.reportProgress("Generating",2,4,"Generating code..."),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(F),this.reportProgress("Complete",4,4,"Generation completed successfully"),F.success=F.errors.length===0,this.logger.debug(`Generation completed: ${F.filesGenerated.length} files`)}catch(u){this.logger.error("Code generation failed",u instanceof Error?u:new Error(String(u))),F.errors.push(u instanceof Error?u.message:String(u)),F.success=!1}finally{F.duration=performance.now()-D}return F}async build(){await this.resolveSchemas();let D={};for(let[F,u]of this.generators.entries())if(u.build)D[F]=await u.build(this.schemas);return D}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return[...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromPackage(D,F){let u=new SD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);this.typeSchemaGenerator=u;let E=await u.generateFromPackage(D,F);if(this.schemas=[...this.schemas,...E],this.cache)this.cache.setMany(E)}async loadFromFiles(D){if(!this.typeSchemaGenerator)this.typeSchemaGenerator=new SD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);let u=await new _0({format:"auto",validate:this.options.validate}).parseFromFiles(D);if(this.schemas=[...this.schemas,...u],this.cache)this.cache.setMany(u)}async resolveSchemas(){if(this.pendingOperations.length>0)await Promise.all(this.pendingOperations),this.pendingOperations=[]}async validateSchemas(D){return}async executeGenerators(D){let F=this.generators.size,u=0;for(let[E,B]of this.generators.entries()){this.reportProgress("Generating",2+u/F,4,`Generating ${E}...`);try{let C=await B.generate(this.schemas);D.filesGenerated.push(...C.map(($)=>$.path||$.filename))}catch(C){D.errors.push(`${E} generator failed: ${C instanceof Error?C.message:String(C)}`)}u++}}reportProgress(D,F,u,E){if(this.progressCallback)this.progressCallback(D,F,u,E);if(this.options.verbose&&E)this.logger.debug(`[${D}] ${E}`)}}import{existsSync as hu}from"node:fs";import{readFile as pu}from"node:fs/promises";import{resolve as K6}from"node:path";var E1={outputDir:"./generated",verbose:!1,overwrite:!0,validate:!0,cache:!0,typescript:{moduleFormat:"esm",generateIndex:!0,includeDocuments:!1,namingConvention:"PascalCase",strictMode:!0,includeProfiles:!0,includeExtensions:!1,includeCodeSystems:!1,includeOperations:!1,generateValueSets:!1,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:!1,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:!0,includeDocumentation:!0,strictMode:!1,subfolder:"profiles"},generateBuilders:!1,builderOptions:{includeValidation:!0,includeFactoryMethods:!0,includeInterfaces:!0,generateNestedBuilders:!0,includeHelperMethods:!0,supportPartialBuild:!0,includeJSDoc:!0,generateFactories:!0,includeTypeGuards:!0,handleChoiceTypes:!0,generateArrayHelpers:!0},validatorOptions:{includeCardinality:!0,includeTypes:!0,includeConstraints:!0,includeInvariants:!1,validateRequired:!0,allowAdditional:!1,strictValidation:!1,collectMetrics:!1,generateAssertions:!0,generatePartialValidators:!0,optimizePerformance:!0,includeJSDoc:!0,generateCompositeValidators:!0},guardOptions:{includeRuntimeValidation:!0,includeErrorMessages:!0,treeShakeable:!0,targetTSVersion:"5.0",strictGuards:!1,includeNullChecks:!0,verbose:!1}},typeSchema:{enablePersistence:!0,cacheDir:".typeschema-cache",maxAge:86400000,validateCached:!0,forceRegenerate:!1,shareCache:!0,cacheKeyPrefix:"",treeshake:[],singleFile:!1,profiles:{autoDetect:!0}},packages:[],files:[],$schema:""},KF=["atomic-codegen.config.ts","atomic-codegen.config.js","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"];class V6{validate(D){let F={valid:!0,errors:[],warnings:[]};if(!D||typeof D!=="object")return F.valid=!1,F.errors.push({path:"root",message:"Configuration must be an object",value:D}),F;let u=D;if(u.outputDir!==void 0&&typeof u.outputDir!=="string")F.errors.push({path:"outputDir",message:"outputDir must be a string",value:u.outputDir});let E=["verbose","overwrite","validate","cache"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.errors.push({path:B,message:`${B} must be a boolean`,value:u[B]});if(u.typescript!==void 0){let B=this.validateTypeScriptConfig(u.typescript);F.errors.push(...B)}if(u.typeSchema!==void 0){let B=this.validateTypeSchemaConfig(u.typeSchema);F.errors.push(...B)}if(u.packages!==void 0)if(!Array.isArray(u.packages))F.errors.push({path:"packages",message:"packages must be an array",value:u.packages});else u.packages.forEach((B,C)=>{if(typeof B!=="string")F.errors.push({path:`packages[${C}]`,message:"package name must be a string",value:B})});if(u.files!==void 0)if(!Array.isArray(u.files))F.errors.push({path:"files",message:"files must be an array",value:u.files});else u.files.forEach((B,C)=>{if(typeof B!=="string")F.errors.push({path:`files[${C}]`,message:"file path must be a string",value:B})});if(F.valid=F.errors.length===0,F.valid)F.config=u;return F}validateTypeScriptConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript",message:"typescript config must be an object",value:D}),F;let u=D;if(u.moduleFormat!==void 0){if(!["esm","cjs"].includes(u.moduleFormat))F.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:u.moduleFormat})}if(u.namingConvention!==void 0){if(!["PascalCase","camelCase"].includes(u.namingConvention))F.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:u.namingConvention})}let E=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.${B}`,message:`${B} must be a boolean`,value:u[B]});if(u.validatorOptions!==void 0){let B=this.validateValidatorOptions(u.validatorOptions);F.push(...B)}if(u.guardOptions!==void 0){let B=this.validateGuardOptions(u.guardOptions);F.push(...B)}if(u.profileOptions!==void 0){let B=this.validateProfileOptions(u.profileOptions);F.push(...B)}return F}validateValidatorOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:D}),F;let u=D,E=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.validatorOptions.${B}`,message:`${B} must be a boolean`,value:u[B]});return F}validateGuardOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:D}),F;let u=D;if(u.targetTSVersion!==void 0){if(!["3.8","4.0","4.5","5.0"].includes(u.targetTSVersion))F.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:u.targetTSVersion})}let E=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.guardOptions.${B}`,message:`${B} must be a boolean`,value:u[B]});return F}validateProfileOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:D}),F;let u=D;if(u.generateKind!==void 0){if(!["interface","type","both"].includes(u.generateKind))F.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:u.generateKind})}if(u.subfolder!==void 0&&typeof u.subfolder!=="string")F.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:u.subfolder});let E=["includeConstraints","includeDocumentation","strictMode"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.profileOptions.${B}`,message:`${B} must be a boolean`,value:u[B]});return F}validateTypeSchemaConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typeSchema",message:"typeSchema config must be an object",value:D}),F;let u=D,E=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let C of E)if(u[C]!==void 0&&typeof u[C]!=="boolean")F.push({path:`typeSchema.${C}`,message:`${C} must be a boolean`,value:u[C]});let B=["cacheDir","cacheKeyPrefix"];for(let C of B)if(u[C]!==void 0&&typeof u[C]!=="string")F.push({path:`typeSchema.${C}`,message:`${C} must be a string`,value:u[C]});if(u.maxAge!==void 0){if(typeof u.maxAge!=="number"||u.maxAge<=0)F.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:u.maxAge})}if(u.profiles!==void 0)if(typeof u.profiles!=="object"||u.profiles===null)F.push({path:"typeSchema.profiles",message:"profiles must be an object",value:u.profiles});else{let C=u.profiles;if(C.autoDetect!==void 0&&typeof C.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:C.autoDetect})}return F}}class R6{validator=new V6;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...E1}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith(".js")){let B=await import(K6(D));F=B.default||B}else{let E=await pu(D,"utf-8");F=JSON.parse(E)}let u=this.validator.validate(F);if(!u.valid){let E=u.errors.map((B)=>`${B.path}: ${B.message}`).join(`
117
- `);throw new Error(`Configuration validation failed:
118
- ${E}`)}return this.mergeWithDefaults(u.config)}catch(F){if(F instanceof Error)throw new Error(`Failed to load config from ${D}: ${F.message}`);throw F}}async findConfigFile(D){for(let F of KF){let u=K6(D,F);if(hu(u))return u}return null}mergeWithDefaults(D){return{...E1,...D,typescript:{...E1.typescript,...D.typescript}}}}var gu=new R6;async function VF(D){return gu.autoload(D)}var U6={command:"generate",describe:"Generate code based on configuration file settings",builder:(D)=>D.option("verbose",{alias:"v",type:"boolean",default:!1,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async(D)=>{if(D._.length>1){let $=D._.slice(1).join(" ");VD(`Invalid syntax: 'atomic-codegen generate ${$}'
116
+ `);await this.fileManager.writeFile("index.ts",F),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`)}}class WF{schemas=[];options;generators=new Map;progressCallback;cache;pendingOperations=[];typeSchemaGenerator;logger;typeSchemaConfig;constructor(D={}){if(this.options={outputDir:D.outputDir||"./generated",verbose:D.verbose??!1,overwrite:D.overwrite??!0,validate:D.validate??!0,cache:D.cache??!0,typeSchemaConfig:D.typeSchemaConfig},this.typeSchemaConfig=D.typeSchemaConfig,this.logger=D.logger||LD({verbose:this.options.verbose,prefix:"API"}),this.options.cache)this.cache=new $0(this.typeSchemaConfig)}fromPackage(D,F){this.logger.debug(`Loading from FHIR package: ${D}@${F||"latest"}`);let u=this.loadFromPackage(D,F);return this.pendingOperations.push(u),this}fromFiles(...D){this.logger.debug(`Loading from ${D.length} TypeSchema files`);let F=this.loadFromFiles(D);return this.pendingOperations.push(F),this}fromSchemas(D){return this.logger.debug(`Adding ${D.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...D],this}typescript(D={}){let F=`${this.options.outputDir}/types`,u=new JF({outputDir:F,moduleFormat:D.moduleFormat||"esm",generateIndex:D.generateIndex??!0,includeDocuments:D.includeDocuments??!0,namingConvention:D.namingConvention||"PascalCase",includeExtensions:D.includeExtensions??!1,includeProfiles:D.includeProfiles??!1,generateValueSets:D.generateValueSets??!1,includeValueSetHelpers:D.includeValueSetHelpers??!1,valueSetStrengths:D.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:D.valueSetMode??"required-only",valueSetDirectory:D.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:!0,overwrite:this.options.overwrite});return this.generators.set("typescript",u),this.logger.debug(`Configured TypeScript generator (${D.moduleFormat||"esm"})`),this}onProgress(D){return this.progressCallback=D,this}outputTo(D){this.logger.debug(`Setting output directory: ${D}`),this.options.outputDir=D;for(let F of this.generators.values())if(F.setOutputDir)F.setOutputDir(D);return this}verbose(D=!0){return this.options.verbose=D,this}validate(D=!0){return this.options.validate=D,this}async generate(){let D=performance.now(),F={success:!1,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{if(this.reportProgress("Loading",0,4,"Loading TypeSchema data..."),await this.resolveSchemas(),this.logger.debug(`Resolved ${this.schemas.length} schemas`),this.reportProgress("Validating",1,4,"Validating TypeSchema documents..."),this.options.validate)this.logger.debug("Starting schema validation"),await this.validateSchemas(F),this.logger.debug("Schema validation completed");this.reportProgress("Generating",2,4,"Generating code..."),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(F),this.reportProgress("Complete",4,4,"Generation completed successfully"),F.success=F.errors.length===0,this.logger.debug(`Generation completed: ${F.filesGenerated.length} files`)}catch(u){this.logger.error("Code generation failed",u instanceof Error?u:Error(String(u))),F.errors.push(u instanceof Error?u.message:String(u)),F.success=!1}finally{F.duration=performance.now()-D}return F}async build(){await this.resolveSchemas();let D={};for(let[F,u]of this.generators.entries())if(u.build)D[F]=await u.build(this.schemas);return D}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return[...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromPackage(D,F){let u=new gD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);this.typeSchemaGenerator=u;let E=await u.generateFromPackage(D,F);if(this.schemas=[...this.schemas,...E],this.cache)this.cache.setMany(E)}async loadFromFiles(D){if(!this.typeSchemaGenerator)this.typeSchemaGenerator=new gD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);let u=await new T0({format:"auto",validate:this.options.validate}).parseFromFiles(D);if(this.schemas=[...this.schemas,...u],this.cache)this.cache.setMany(u)}async resolveSchemas(){if(this.pendingOperations.length>0)await Promise.all(this.pendingOperations),this.pendingOperations=[]}async validateSchemas(D){return}async executeGenerators(D){let F=this.generators.size,u=0;for(let[E,B]of this.generators.entries()){this.reportProgress("Generating",2+u/F,4,`Generating ${E}...`);try{let C=await B.generate(this.schemas);D.filesGenerated.push(...C.map(($)=>$.path||$.filename))}catch(C){D.errors.push(`${E} generator failed: ${C instanceof Error?C.message:String(C)}`)}u++}}reportProgress(D,F,u,E){if(this.progressCallback)this.progressCallback(D,F,u,E);if(this.options.verbose&&E)this.logger.debug(`[${D}] ${E}`)}}import{existsSync as du}from"node:fs";import{readFile as pu}from"node:fs/promises";import{resolve as q6}from"node:path";var s2={outputDir:"./generated",verbose:!1,overwrite:!0,validate:!0,cache:!0,typescript:{moduleFormat:"esm",generateIndex:!0,includeDocuments:!1,namingConvention:"PascalCase",strictMode:!0,includeProfiles:!0,includeExtensions:!1,includeCodeSystems:!1,includeOperations:!1,generateValueSets:!1,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:!1,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:!0,includeDocumentation:!0,strictMode:!1,subfolder:"profiles"},generateBuilders:!1,builderOptions:{includeValidation:!0,includeFactoryMethods:!0,includeInterfaces:!0,generateNestedBuilders:!0,includeHelperMethods:!0,supportPartialBuild:!0,includeJSDoc:!0,generateFactories:!0,includeTypeGuards:!0,handleChoiceTypes:!0,generateArrayHelpers:!0},validatorOptions:{includeCardinality:!0,includeTypes:!0,includeConstraints:!0,includeInvariants:!1,validateRequired:!0,allowAdditional:!1,strictValidation:!1,collectMetrics:!1,generateAssertions:!0,generatePartialValidators:!0,optimizePerformance:!0,includeJSDoc:!0,generateCompositeValidators:!0},guardOptions:{includeRuntimeValidation:!0,includeErrorMessages:!0,treeShakeable:!0,targetTSVersion:"5.0",strictGuards:!1,includeNullChecks:!0,verbose:!1}},typeSchema:{enablePersistence:!0,cacheDir:".typeschema-cache",maxAge:86400000,validateCached:!0,forceRegenerate:!1,shareCache:!0,cacheKeyPrefix:"",treeshake:[],singleFile:!1,profiles:{autoDetect:!0}},packages:[],files:[],$schema:""},AF=["atomic-codegen.config.ts","atomic-codegen.config.js","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"];class _6{validate(D){let F={valid:!0,errors:[],warnings:[]};if(!D||typeof D!=="object")return F.valid=!1,F.errors.push({path:"root",message:"Configuration must be an object",value:D}),F;let u=D;if(u.outputDir!==void 0&&typeof u.outputDir!=="string")F.errors.push({path:"outputDir",message:"outputDir must be a string",value:u.outputDir});let E=["verbose","overwrite","validate","cache"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.errors.push({path:B,message:`${B} must be a boolean`,value:u[B]});if(u.typescript!==void 0){let B=this.validateTypeScriptConfig(u.typescript);F.errors.push(...B)}if(u.typeSchema!==void 0){let B=this.validateTypeSchemaConfig(u.typeSchema);F.errors.push(...B)}if(u.packages!==void 0)if(!Array.isArray(u.packages))F.errors.push({path:"packages",message:"packages must be an array",value:u.packages});else u.packages.forEach((B,C)=>{if(typeof B!=="string")F.errors.push({path:`packages[${C}]`,message:"package name must be a string",value:B})});if(u.files!==void 0)if(!Array.isArray(u.files))F.errors.push({path:"files",message:"files must be an array",value:u.files});else u.files.forEach((B,C)=>{if(typeof B!=="string")F.errors.push({path:`files[${C}]`,message:"file path must be a string",value:B})});if(F.valid=F.errors.length===0,F.valid)F.config=u;return F}validateTypeScriptConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript",message:"typescript config must be an object",value:D}),F;let u=D;if(u.moduleFormat!==void 0){if(!["esm","cjs"].includes(u.moduleFormat))F.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:u.moduleFormat})}if(u.namingConvention!==void 0){if(!["PascalCase","camelCase"].includes(u.namingConvention))F.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:u.namingConvention})}let E=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.${B}`,message:`${B} must be a boolean`,value:u[B]});if(u.validatorOptions!==void 0){let B=this.validateValidatorOptions(u.validatorOptions);F.push(...B)}if(u.guardOptions!==void 0){let B=this.validateGuardOptions(u.guardOptions);F.push(...B)}if(u.profileOptions!==void 0){let B=this.validateProfileOptions(u.profileOptions);F.push(...B)}return F}validateValidatorOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:D}),F;let u=D,E=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.validatorOptions.${B}`,message:`${B} must be a boolean`,value:u[B]});return F}validateGuardOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:D}),F;let u=D;if(u.targetTSVersion!==void 0){if(!["3.8","4.0","4.5","5.0"].includes(u.targetTSVersion))F.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:u.targetTSVersion})}let E=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.guardOptions.${B}`,message:`${B} must be a boolean`,value:u[B]});return F}validateProfileOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:D}),F;let u=D;if(u.generateKind!==void 0){if(!["interface","type","both"].includes(u.generateKind))F.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:u.generateKind})}if(u.subfolder!==void 0&&typeof u.subfolder!=="string")F.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:u.subfolder});let E=["includeConstraints","includeDocumentation","strictMode"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typescript.profileOptions.${B}`,message:`${B} must be a boolean`,value:u[B]});return F}validateTypeSchemaConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typeSchema",message:"typeSchema config must be an object",value:D}),F;let u=D,E=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let C of E)if(u[C]!==void 0&&typeof u[C]!=="boolean")F.push({path:`typeSchema.${C}`,message:`${C} must be a boolean`,value:u[C]});let B=["cacheDir","cacheKeyPrefix"];for(let C of B)if(u[C]!==void 0&&typeof u[C]!=="string")F.push({path:`typeSchema.${C}`,message:`${C} must be a string`,value:u[C]});if(u.maxAge!==void 0){if(typeof u.maxAge!=="number"||u.maxAge<=0)F.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:u.maxAge})}if(u.profiles!==void 0)if(typeof u.profiles!=="object"||u.profiles===null)F.push({path:"typeSchema.profiles",message:"profiles must be an object",value:u.profiles});else{let C=u.profiles;if(C.autoDetect!==void 0&&typeof C.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:C.autoDetect})}return F}}class K6{validator=new _6;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...s2}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith(".js")){let B=await import(q6(D));F=B.default||B}else{let E=await pu(D,"utf-8");F=JSON.parse(E)}let u=this.validator.validate(F);if(!u.valid){let E=u.errors.map((B)=>`${B.path}: ${B.message}`).join(`
117
+ `);throw Error(`Configuration validation failed:
118
+ ${E}`)}return this.mergeWithDefaults(u.config)}catch(F){if(F instanceof Error)throw Error(`Failed to load config from ${D}: ${F.message}`);throw F}}async findConfigFile(D){for(let F of AF){let u=q6(D,F);if(du(u))return u}return null}mergeWithDefaults(D){return{...s2,...D,typescript:{...s2.typescript,...D.typescript}}}}var gu=new K6;async function GF(D){return gu.autoload(D)}var V6={command:"generate",describe:"Generate code based on configuration file settings",builder:(D)=>D.option("verbose",{alias:"v",type:"boolean",default:!1,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async(D)=>{if(D._.length>1){let $=D._.slice(1).join(" ");VD(`Invalid syntax: 'atomic-codegen generate ${$}'
119
119
 
120
120
  The CLI has been simplified and no longer uses subcommands.
121
121
 
@@ -123,7 +123,7 @@ The CLI has been simplified and no longer uses subcommands.
123
123
  `+`❌ Old: atomic-codegen generate typescript
124
124
 
125
125
  `+`All generation settings are now configured in your config file.
126
- Create an atomic-codegen.config.ts file to get started.`),process.exit(1)}let F=process.cwd(),u=await cu(F);if(!u){let $=KF.map((X)=>` - ${X}`).join(`
126
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1)}let F=process.cwd(),u=await cu(F);if(!u){let $=AF.map((X)=>` - ${X}`).join(`
127
127
  `);VD(`No configuration file found. Please create one of the following files in your project root:
128
128
  ${$}
129
129
 
@@ -136,13 +136,13 @@ export default defineConfig({
136
136
  typescript: {
137
137
  generateIndex: true
138
138
  }
139
- });`),process.exit(1)}let E=await VF(F),B=D.verbose??E.verbose??!1,C=LD({verbose:B,prefix:"Generate"});try{if($2("Starting generation from config"),B)C.info(`Config file: ${u}`),C.info(`Output directory: ${E.outputDir||"./generated"}`),C.info(`Packages: ${E.packages?.length||0}`),C.info(`Files: ${E.files?.length||0}`),C.info(`TypeScript generation: ${E.typescript?"enabled":"disabled"}`);let $=new _F({outputDir:E.outputDir||"./generated",verbose:B,overwrite:E.overwrite??!0,validate:E.validate??!0,cache:E.cache??!0,typeSchemaConfig:E.typeSchema,logger:C});if(E.packages&&E.packages.length>0){C.info(`Loading packages from config: ${E.packages.join(", ")}`);for(let Q of E.packages){let[z,Y]=Q.includes("@")?Q.split("@"):[Q,void 0];$.fromPackage(z,Y)}}else if(E.files&&E.files.length>0){C.info(`Loading files from config: ${E.files.join(", ")}`);for(let Q of E.files)$.fromFiles(Q)}else throw new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(E.typescript){if(B)C.info("Configuring TypeScript generation from config"),C.debug(`Module format: ${E.typescript.moduleFormat||"esm"}`),C.debug(`Generate index: ${E.typescript.generateIndex??!0}`),C.debug(`Include docs: ${E.typescript.includeDocuments??!1}`),C.debug(`Naming convention: ${E.typescript.namingConvention||"PascalCase"}`);$.typescript(E.typescript)}if(!E.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");if(B)$.onProgress((Q,z,Y,W)=>{let J=Math.round(z/Y*100);C.progress(`[${Q}] ${J}% - ${W||"Processing..."}`)});C.step("Executing generation...");let X=await $.generate();if(X.success){if(e0(`Generated ${X.filesGenerated.length} files in ${X.duration.toFixed(2)}ms`),C.dim(`Output directory: ${X.outputDir}`),X.warnings.length>0)for(let Q of X.warnings)C2(Q)}else{VD(`Generation failed with ${X.errors.length} errors`);for(let Q of X.errors)C.dim(` ${Q}`);process.exit(1)}}catch($){VD("Generation failed with unexpected error",$ instanceof Error?$:new Error(String($))),process.exit(1)}}};async function cu(D){for(let F of KF){let u=lu(D,F);if(mu(u))return u}return null}import{mkdir as ou,writeFile as nu}from"node:fs/promises";import{dirname as iu}from"node:path";var L6={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:!0,demandOption:!0,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:!0,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:!1,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:!1,describe:"Enable verbose output"}},handler:async(D)=>{let F=LD({verbose:D.verbose,prefix:"TypeSchema"});try{let u=await VF(process.cwd());F.step("Generating TypeSchema from FHIR packages"),F.info(`Packages: ${D.packages.join(", ")}`),F.info(`Output: ${D.output}`);let E=D.singleFile!==void 0?D.singleFile:u.typeSchema?.singleFile??!1,B=E?"ndjson":D.format;F.debug(`Format: ${B}${E&&D.format==="json"?" (forced from json due to singleFile)":""}`);let C=D.treeshake&&D.treeshake.length>0?D.treeshake:u.typeSchema?.treeshake;if(C&&C.length>0)F.info(`Treeshaking enabled for ResourceTypes: ${C.join(", ")}`);if(E)F.info("Single file output enabled (NDJSON format)");let $=Date.now(),X=new SD({verbose:D.verbose,treeshake:C}),Q=[];for(let J of D.packages){let[q,M]=J.includes("@")?J.split("@"):[J,void 0];F.progress(`Processing package: ${q}${M?`@${M}`:""}`);let G=await X.generateFromPackage(q,M);Q.push(...G)}if(Q.length===0)throw new Error("No schemas were generated from the specified packages");let z=D.output;await ou(iu(z),{recursive:!0});let Y;if(B==="json")Y=JSON.stringify(Q,null,2);else Y=Q.map((J)=>JSON.stringify(J)).join(`
140
- `);await nu(z,Y,"utf-8");let W=Date.now()-$;if(Q2(`Generated ${Q.length} TypeSchema definitions`,W,{schemas:Q.length}),F.dim(`Output: ${z}`),D.verbose){F.debug("Generated schemas:");let J=Q.map((q)=>`${q.identifier?.name||"Unknown"} (${q.identifier?.kind||"unknown"})`);$0(J)}}catch(u){F.error("Failed to generate TypeSchema",u instanceof Error?u:new Error(String(u))),process.exit(1)}}};var N6={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:(D)=>{return D.command(L6).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package")},handler:(D)=>{if(!D.subcommand&&D._.length===1){DF("Available typeschema subcommands:"),$0(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
139
+ });`),process.exit(1)}let E=await GF(F),B=D.verbose??E.verbose??!1,C=LD({verbose:B,prefix:"Generate"});try{if(D2("Starting generation from config"),B)C.info(`Config file: ${u}`),C.info(`Output directory: ${E.outputDir||"./generated"}`),C.info(`Packages: ${E.packages?.length||0}`),C.info(`Files: ${E.files?.length||0}`),C.info(`TypeScript generation: ${E.typescript?"enabled":"disabled"}`);let $=new WF({outputDir:E.outputDir||"./generated",verbose:B,overwrite:E.overwrite??!0,validate:E.validate??!0,cache:E.cache??!0,typeSchemaConfig:E.typeSchema,logger:C});if(E.packages&&E.packages.length>0){C.info(`Loading packages from config: ${E.packages.join(", ")}`);for(let Q of E.packages){let[z,Y]=Q.includes("@")?Q.split("@"):[Q,void 0];$.fromPackage(z,Y)}}else if(E.files&&E.files.length>0){C.info(`Loading files from config: ${E.files.join(", ")}`);for(let Q of E.files)$.fromFiles(Q)}else throw Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(E.typescript){if(B)C.info("Configuring TypeScript generation from config"),C.debug(`Module format: ${E.typescript.moduleFormat||"esm"}`),C.debug(`Generate index: ${E.typescript.generateIndex??!0}`),C.debug(`Include docs: ${E.typescript.includeDocuments??!1}`),C.debug(`Naming convention: ${E.typescript.namingConvention||"PascalCase"}`);$.typescript(E.typescript)}if(!E.typescript)throw Error("No generators configured. Please enable 'typescript' in your config file.");if(B)$.onProgress((Q,z,Y,W)=>{let J=Math.round(z/Y*100);C.progress(`[${Q}] ${J}% - ${W||"Processing..."}`)});C.step("Executing generation...");let X=await $.generate();if(X.success){if(s0(`Generated ${X.filesGenerated.length} files in ${X.duration.toFixed(2)}ms`),C.dim(`Output directory: ${X.outputDir}`),X.warnings.length>0)for(let Q of X.warnings)eF(Q)}else{VD(`Generation failed with ${X.errors.length} errors`);for(let Q of X.errors)C.dim(` ${Q}`);process.exit(1)}}catch($){VD("Generation failed with unexpected error",$ instanceof Error?$:Error(String($))),process.exit(1)}}};async function cu(D){for(let F of AF){let u=lu(D,F);if(mu(u))return u}return null}import{mkdir as ou,writeFile as nu}from"node:fs/promises";import{dirname as iu}from"node:path";var R6={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:!0,demandOption:!0,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:!0,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:!1,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:!1,describe:"Enable verbose output"}},handler:async(D)=>{let F=LD({verbose:D.verbose,prefix:"TypeSchema"});try{let u=await GF(process.cwd());F.step("Generating TypeSchema from FHIR packages"),F.info(`Packages: ${D.packages.join(", ")}`),F.info(`Output: ${D.output}`);let E=D.singleFile!==void 0?D.singleFile:u.typeSchema?.singleFile??!1,B=E?"ndjson":D.format;F.debug(`Format: ${B}${E&&D.format==="json"?" (forced from json due to singleFile)":""}`);let C=D.treeshake&&D.treeshake.length>0?D.treeshake:u.typeSchema?.treeshake;if(C&&C.length>0)F.info(`Treeshaking enabled for ResourceTypes: ${C.join(", ")}`);if(E)F.info("Single file output enabled (NDJSON format)");let $=Date.now(),X=new gD({verbose:D.verbose,treeshake:C}),Q=[];for(let J of D.packages){let[M,q]=J.includes("@")?J.split("@"):[J,void 0];F.progress(`Processing package: ${M}${q?`@${q}`:""}`);let G=await X.generateFromPackage(M,q);Q.push(...G)}if(Q.length===0)throw Error("No schemas were generated from the specified packages");let z=D.output;await ou(iu(z),{recursive:!0});let Y;if(B==="json")Y=JSON.stringify(Q,null,2);else Y=Q.map((J)=>JSON.stringify(J)).join(`
140
+ `);await nu(z,Y,"utf-8");let W=Date.now()-$;if(E2(`Generated ${Q.length} TypeSchema definitions`,W,{schemas:Q.length}),F.dim(`Output: ${z}`),D.verbose){F.debug("Generated schemas:");let J=Q.map((M)=>`${M.identifier?.name||"Unknown"} (${M.identifier?.kind||"unknown"})`);C0(J)}}catch(u){F.error("Failed to generate TypeSchema",u instanceof Error?u:Error(String(u))),process.exit(1)}}};var U6={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:(D)=>{return D.command(R6).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package")},handler:(D)=>{if(!D.subcommand&&D._.length===1){r0("Available typeschema subcommands:"),C0(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
141
141
  Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
142
- Examples:`),$0(["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}if(D.subcommand&&!["generate","validate","merge"].includes(D.subcommand))VD(`Unknown typeschema subcommand: ${D.subcommand}
143
- `),DF("Available typeschema subcommands:"),$0(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
144
- Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1)}};async function tu(D){X2({verbose:D.verbose||D.debug,timestamp:D.debug})}function su(){return b3(hF(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(tu).command(N6).command(U6).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:!1,global:!0}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:!1,global:!0}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:!0}).demandCommand(0).middleware((D)=>{if(D._.length===0)Z2("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
142
+ Examples:`),C0(["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}if(D.subcommand&&!["generate","validate","merge"].includes(D.subcommand))VD(`Unknown typeschema subcommand: ${D.subcommand}
143
+ `),r0("Available typeschema subcommands:"),C0(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
144
+ Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1)}};async function tu(D){F2({verbose:D.verbose||D.debug,timestamp:D.debug})}function su(){return U3(SF(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(tu).command(U6).command(V6).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:!1,global:!0}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:!1,global:!0}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:!0}).demandCommand(0).middleware((D)=>{if(D._.length===0)u2("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
145
145
  Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
146
146
  Quick examples:`),console.log(" atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson"),console.log(" atomic-codegen generate # Uses atomic-codegen.config.ts"),console.log(`
147
147
  Use 'atomic-codegen --help' to see all options.`),process.exit(0)}).help().version("0.1.0").example("$0 generate","Generate code using atomic-codegen.config.ts").example("$0 generate --verbose","Generate with detailed progress output").example("$0 --config custom-config.ts generate","Use custom configuration file").example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").fail((D,F,u)=>{if(F)VD(F.message,F);else VD(D);VD(`
148
- Use --help for usage information`),process.exit(1)}).wrap(Math.min(120,process.stdout.columns||80))}async function j6(){await su().parseAsync()}if(jF.main==jF.module)j6().catch((D)=>{console.error("CLI Error:",D instanceof Error?D.message:D),process.exit(1)});
148
+ Use --help for usage information`),process.exit(1)}).wrap(Math.min(120,process.stdout.columns||80))}async function L6(){await su().parseAsync()}if(KF.main==KF.module)L6().catch((D)=>{console.error("CLI Error:",D instanceof Error?D.message:D),process.exit(1)});