@atomic-ehr/codegen 0.0.1-canary.20250826204510.8c2fcc0 → 0.0.1-canary.20250830224431.6d211a5

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.
Files changed (108) hide show
  1. package/README.md +114 -33
  2. package/dist/api/builder.d.ts +5 -1
  3. package/dist/api/builder.js +5 -0
  4. package/dist/api/generators/base/BaseGenerator.d.ts +0 -1
  5. package/dist/api/generators/base/FileManager.d.ts +0 -1
  6. package/dist/api/generators/base/PythonTypeMapper.d.ts +0 -1
  7. package/dist/api/generators/base/TemplateEngine.d.ts +0 -1
  8. package/dist/api/generators/base/TypeMapper.d.ts +0 -1
  9. package/dist/api/generators/base/TypeScriptTypeMapper.d.ts +0 -1
  10. package/dist/api/generators/base/builders/DirectoryBuilder.d.ts +0 -1
  11. package/dist/api/generators/base/builders/FileBuilder.d.ts +0 -1
  12. package/dist/api/generators/base/builders/IndexBuilder.d.ts +0 -1
  13. package/dist/api/generators/base/enhanced-errors.d.ts +0 -1
  14. package/dist/api/generators/base/error-handler.d.ts +0 -1
  15. package/dist/api/generators/base/errors.d.ts +0 -1
  16. package/dist/api/generators/base/index.d.ts +0 -1
  17. package/dist/api/generators/base/types.d.ts +0 -1
  18. package/dist/api/generators/rest-client.d.ts +0 -1
  19. package/dist/api/generators/search-parameter-enhancer.d.ts +0 -1
  20. package/dist/api/generators/types.d.ts +0 -1
  21. package/dist/api/generators/typescript.d.ts +56 -1
  22. package/dist/api/generators/typescript.js +263 -33
  23. package/dist/api/generators/validation-generator.d.ts +0 -1
  24. package/dist/api/index.d.ts +0 -1
  25. package/dist/cli/commands/generate/typescript.d.ts +0 -1
  26. package/dist/cli/commands/generate.d.ts +0 -1
  27. package/dist/cli/commands/index.d.ts +0 -1
  28. package/dist/cli/commands/typeschema/generate.d.ts +0 -1
  29. package/dist/cli/commands/typeschema.d.ts +0 -1
  30. package/dist/cli/index.d.ts +0 -1
  31. package/dist/cli/index.js +46 -42
  32. package/dist/cli/utils/log.d.ts +0 -1
  33. package/dist/cli/utils/prompts.d.ts +0 -1
  34. package/dist/cli/utils/spinner.d.ts +0 -1
  35. package/dist/config.d.ts +10 -2
  36. package/dist/config.js +9 -1
  37. package/dist/index.d.ts +0 -1
  38. package/dist/logger.d.ts +0 -1
  39. package/dist/typeschema/cache.d.ts +0 -1
  40. package/dist/typeschema/core/binding.d.ts +0 -1
  41. package/dist/typeschema/core/binding.js +5 -3
  42. package/dist/typeschema/core/field-builder.d.ts +0 -1
  43. package/dist/typeschema/core/identifier.d.ts +0 -1
  44. package/dist/typeschema/core/nested-types.d.ts +0 -1
  45. package/dist/typeschema/core/transformer.d.ts +0 -1
  46. package/dist/typeschema/generator.d.ts +0 -1
  47. package/dist/typeschema/generator.js +30 -5
  48. package/dist/typeschema/index.d.ts +0 -1
  49. package/dist/typeschema/parser.d.ts +0 -1
  50. package/dist/typeschema/profile/processor.d.ts +0 -1
  51. package/dist/typeschema/schema.d.ts +0 -1
  52. package/dist/typeschema/type-schema.types.d.ts +0 -1
  53. package/dist/typeschema/types.d.ts +0 -1
  54. package/dist/typeschema/utils.d.ts +0 -1
  55. package/dist/typeschema/value-set/processor.d.ts +0 -1
  56. package/dist/utils/codegen-logger.d.ts +0 -1
  57. package/dist/utils.d.ts +0 -1
  58. package/package.json +1 -1
  59. package/dist/api/builder.d.ts.map +0 -1
  60. package/dist/api/generators/base/BaseGenerator.d.ts.map +0 -1
  61. package/dist/api/generators/base/FileManager.d.ts.map +0 -1
  62. package/dist/api/generators/base/PythonTypeMapper.d.ts.map +0 -1
  63. package/dist/api/generators/base/TemplateEngine.d.ts.map +0 -1
  64. package/dist/api/generators/base/TypeMapper.d.ts.map +0 -1
  65. package/dist/api/generators/base/TypeScriptTypeMapper.d.ts.map +0 -1
  66. package/dist/api/generators/base/builders/DirectoryBuilder.d.ts.map +0 -1
  67. package/dist/api/generators/base/builders/FileBuilder.d.ts.map +0 -1
  68. package/dist/api/generators/base/builders/IndexBuilder.d.ts.map +0 -1
  69. package/dist/api/generators/base/enhanced-errors.d.ts.map +0 -1
  70. package/dist/api/generators/base/error-handler.d.ts.map +0 -1
  71. package/dist/api/generators/base/errors.d.ts.map +0 -1
  72. package/dist/api/generators/base/index.d.ts.map +0 -1
  73. package/dist/api/generators/base/types.d.ts.map +0 -1
  74. package/dist/api/generators/rest-client.d.ts.map +0 -1
  75. package/dist/api/generators/search-parameter-enhancer.d.ts.map +0 -1
  76. package/dist/api/generators/types.d.ts.map +0 -1
  77. package/dist/api/generators/typescript.d.ts.map +0 -1
  78. package/dist/api/generators/validation-generator.d.ts.map +0 -1
  79. package/dist/api/index.d.ts.map +0 -1
  80. package/dist/cli/commands/generate/typescript.d.ts.map +0 -1
  81. package/dist/cli/commands/generate.d.ts.map +0 -1
  82. package/dist/cli/commands/index.d.ts.map +0 -1
  83. package/dist/cli/commands/typeschema/generate.d.ts.map +0 -1
  84. package/dist/cli/commands/typeschema.d.ts.map +0 -1
  85. package/dist/cli/index.d.ts.map +0 -1
  86. package/dist/cli/utils/log.d.ts.map +0 -1
  87. package/dist/cli/utils/prompts.d.ts.map +0 -1
  88. package/dist/cli/utils/spinner.d.ts.map +0 -1
  89. package/dist/config.d.ts.map +0 -1
  90. package/dist/index.d.ts.map +0 -1
  91. package/dist/logger.d.ts.map +0 -1
  92. package/dist/typeschema/cache.d.ts.map +0 -1
  93. package/dist/typeschema/core/binding.d.ts.map +0 -1
  94. package/dist/typeschema/core/field-builder.d.ts.map +0 -1
  95. package/dist/typeschema/core/identifier.d.ts.map +0 -1
  96. package/dist/typeschema/core/nested-types.d.ts.map +0 -1
  97. package/dist/typeschema/core/transformer.d.ts.map +0 -1
  98. package/dist/typeschema/generator.d.ts.map +0 -1
  99. package/dist/typeschema/index.d.ts.map +0 -1
  100. package/dist/typeschema/parser.d.ts.map +0 -1
  101. package/dist/typeschema/profile/processor.d.ts.map +0 -1
  102. package/dist/typeschema/schema.d.ts.map +0 -1
  103. package/dist/typeschema/type-schema.types.d.ts.map +0 -1
  104. package/dist/typeschema/types.d.ts.map +0 -1
  105. package/dist/typeschema/utils.d.ts.map +0 -1
  106. package/dist/typeschema/value-set/processor.d.ts.map +0 -1
  107. package/dist/utils/codegen-logger.d.ts.map +0 -1
  108. package/dist/utils.d.ts.map +0 -1
package/dist/cli/index.js CHANGED
@@ -1,32 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as P6}from"node:module";var b6=Object.create;var{getPrototypeOf:T6,defineProperty:R0,getOwnPropertyNames:Q1,getOwnPropertyDescriptor:x6}=Object,z1=Object.prototype.hasOwnProperty;var v0=(D,F,B)=>{B=D!=null?b6(T6(D)):{};let E=F||!D||!D.__esModule?R0(B,"default",{value:D,enumerable:!0}):B;for(let C of Q1(D))if(!z1.call(E,C))R0(E,C,{get:()=>D[C],enumerable:!0});return E},Z1=new WeakMap,IF=(D)=>{var F=Z1.get(D),B;if(F)return F;if(F=R0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")Q1(D).map((E)=>!z1.call(F,E)&&R0(F,E,{get:()=>D[E],enumerable:!(B=x6(D,E))||B.enumerable}));return Z1.set(D,F),F},bF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var TF=(D,F)=>{for(var B in F)R0(D,B,{get:F[B],enumerable:!0,configurable:!0,set:(E)=>F[B]=()=>E})};var O1=(D,F)=>()=>(D&&(F=D(D=0)),F);var xF=P6(import.meta.url);var _1=bF((QE,M1)=>{M1.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 o1=bF((rE,c1)=>{c1.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 B=Error.prepareStackTrace;Error.prepareStackTrace=function(C,u){return u};var E=new Error().stack;if(Error.prepareStackTrace=B,E!==null&&typeof E==="object")return E[F]?E[F].getFileName():void 0}});var Q2=bF((qu,Z2)=>{var a0=process||{},v3=a0.argv||[],r0=a0.env||{},p8=!(!!r0.NO_COLOR||v3.includes("--no-color"))&&(!!r0.FORCE_COLOR||v3.includes("--color")||a0.platform==="win32"||(a0.stdout||{}).isTTY&&r0.TERM!=="dumb"||!!r0.CI),m8=(D,F,B=D)=>(E)=>{let C=""+E,u=C.indexOf(F,D.length);return~u?D+l8(C,F,B,u)+F:D+C+F},l8=(D,F,B,E)=>{let C="",u=0;do C+=D.substring(u,E)+B,u=E+F.length,E=D.indexOf(F,u);while(~E);return C+D.substring(u)},k3=(D=p8)=>{let F=D?m8:()=>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")}};Z2.exports=k3();Z2.exports.createColors=k3});var ND,i2,VF,X0,t2,s2;var S0=O1(()=>{ND=class ND extends Error{phase;context;timestamp;errorId;constructor(D,F,B){super(D);this.phase=F;this.context=B;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,B])=>{D.push(` ${F}: ${this.formatContextValue(B)}`)});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`]}};i2=class i2 extends ND{schema;validationErrors;userContext;constructor(D,F,B,E){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:B,userContext:E});this.schema=F;this.validationErrors=B;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"))}};VF=class VF extends ND{templateName;templateContext;debugInfo;constructor(D,F,B,E){super(D,"generation",{templateName:F,contextKeys:Object.keys(B),availableTemplates:E?.availableTemplates?.length||0,debugInfo:E});this.templateName=F;this.templateContext=B;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((B)=>{D.push(` • ${B}`)});let F=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);if(F.length>0)D.push("\uD83E\uDD14 Did you mean:"),F.forEach((B)=>{D.push(` • ${B}`)})}}if(this.debugInfo?.missingVariables?.length){D.push("\uD83D\uDCDD Missing template variables:"),this.debugInfo.missingVariables.forEach((B)=>{D.push(` • ${B}`)}),D.push("\uD83D\uDCA1 Add these variables to your template context");let F=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach((B)=>{let E=F.filter((C)=>this.levenshteinDistance(B.toLowerCase(),C.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 B=this.debugInfo.templateSource.split(`
4
- `)[this.debugInfo.lineNumber-1];if(B)D.push(` Code: ${B.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((B)=>{let E=this.levenshteinDistance(D.toLowerCase(),B.toLowerCase());return E<=2&&E>0}).slice(0,3).sort((B,E)=>this.levenshteinDistance(D.toLowerCase(),B.toLowerCase())-this.levenshteinDistance(D.toLowerCase(),E.toLowerCase()))}levenshteinDistance(D,F){let B=Array(F.length+1).fill(null).map(()=>Array(D.length+1).fill(0));for(let E=0;E<=D.length;E++)B[0][E]=E;for(let E=0;E<=F.length;E++)B[E][0]=E;for(let E=1;E<=F.length;E++)for(let C=1;C<=D.length;C++){let u=D[C-1]===F[E-1]?0:1;B[E][C]=Math.min(B[E]?.[C-1]+1,B[E-1]?.[C]+1,B[E-1]?.[C-1]+u)}return B[F.length]?.[D.length]}isRecoverable(){return!0}};X0=class X0 extends ND{operation;filePath;originalError;recoveryOptions;constructor(D,F,B,E,C){super(D,"writing",{operation:F,filePath:B,originalErrorMessage:E?.message,originalErrorCode:E?.code,recoveryOptions:C});this.operation=F;this.filePath=B;this.originalError=E;this.recoveryOptions=C}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((B)=>{D.push(` • ${B}`)});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 B=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);D.push(` • Required space: ~${B}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}};t2=class t2 extends ND{configKey;providedValue;expectedValue;validOptions;constructor(D,F,B,E,C){super(D,"initialization",{configKey:F,providedValue:B,providedType:typeof B,expectedValue:E,validOptions:C});this.configKey=F;this.providedValue=B;this.expectedValue=E;this.validOptions=C}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}};s2=class s2 extends ND{errors;constructor(D,F){super(D,"generation",{errorCount:F.length,errorTypes:[...new Set(F.map((B)=>B.constructor.name))],phases:[...new Set(F.map((B)=>B.phase))]});this.errors=F}getSuggestions(){let D=this.errors.flatMap((u)=>u.getSuggestions()),F=[...new Set(D)],B=[];B.push(`\uD83D\uDCCA Batch operation failed with ${this.errors.length} errors:`);let E=new Map;this.errors.forEach((u)=>{let $=u.constructor.name;if(!E.has($))E.set($,[]);E.get($)?.push(u)}),B.push(""),B.push("\uD83D\uDD0D Error breakdown:");for(let[u,$]of E)B.push(` • ${u}: ${$.length} occurrences`);B.push("\uD83D\uDCA1 Most relevant suggestions:");let C=F.slice(0,8).map((u)=>` ${u}`);return B.push(...C),B}getErrorBreakdown(){let D=[];return this.errors.forEach((F,B)=>{if(D.push(`${B+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 G6={};TF(G6,{FileBuilder:()=>A6});class A6{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 VF(`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(B){throw new VF(`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,B]of D)this.imports.set(F,B);return this}addImport(D,F){return this.imports.set(D,F),this}addImports(D,F){for(let B of D)this.imports.set(B,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}),B={size:F.size,generationTime:0,writeTime:F.writeTime};for(let E of this.afterSaveHooks)await E(F.path,B);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),F.path}catch(F){for(let B of this.errorHooks)try{await B(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 f6}from"node:module";var S6=Object.create;var{getPrototypeOf:v6,defineProperty:U0,getOwnPropertyNames:O1,getOwnPropertyDescriptor:k6}=Object,Y1=Object.prototype.hasOwnProperty;var k0=(D,F,B)=>{B=D!=null?S6(v6(D)):{};let E=F||!D||!D.__esModule?U0(B,"default",{value:D,enumerable:!0}):B;for(let C of O1(D))if(!Y1.call(E,C))U0(E,C,{get:()=>D[C],enumerable:!0});return E},z1=new WeakMap,IF=(D)=>{var F=z1.get(D),B;if(F)return F;if(F=U0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")O1(D).map((E)=>!Y1.call(F,E)&&U0(F,E,{get:()=>D[E],enumerable:!(B=k6(D,E))||B.enumerable}));return z1.set(D,F),F},TF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var bF=(D,F)=>{for(var B in F)U0(D,B,{get:F[B],enumerable:!0,configurable:!0,set:(E)=>F[B]=()=>E})};var J1=(D,F)=>()=>(D&&(F=D(D=0)),F);var xF=f6(import.meta.url);var V1=TF((WE,K1)=>{K1.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 i1=TF((BC,n1)=>{n1.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 B=Error.prepareStackTrace;Error.prepareStackTrace=function(C,u){return u};var E=new Error().stack;if(Error.prepareStackTrace=B,E!==null&&typeof E==="object")return E[F]?E[F].getFileName():void 0}});var Q2=TF((R7,Z2)=>{var e0=process||{},f3=e0.argv||[],a0=e0.env||{},o8=!(!!a0.NO_COLOR||f3.includes("--no-color"))&&(!!a0.FORCE_COLOR||f3.includes("--color")||e0.platform==="win32"||(e0.stdout||{}).isTTY&&a0.TERM!=="dumb"||!!a0.CI),n8=(D,F,B=D)=>(E)=>{let C=""+E,u=C.indexOf(F,D.length);return~u?D+i8(C,F,B,u)+F:D+C+F},i8=(D,F,B,E)=>{let C="",u=0;do C+=D.substring(u,E)+B,u=E+F.length,E=D.indexOf(F,u);while(~E);return C+D.substring(u)},y3=(D=o8)=>{let F=D?n8:()=>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")}};Z2.exports=y3();Z2.exports.createColors=y3});var ND,s2,VF,X0,r2,a2;var v0=J1(()=>{ND=class ND extends Error{phase;context;timestamp;errorId;constructor(D,F,B){super(D);this.phase=F;this.context=B;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,B])=>{D.push(` ${F}: ${this.formatContextValue(B)}`)});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`]}};s2=class s2 extends ND{schema;validationErrors;userContext;constructor(D,F,B,E){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:B,userContext:E});this.schema=F;this.validationErrors=B;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"))}};VF=class VF extends ND{templateName;templateContext;debugInfo;constructor(D,F,B,E){super(D,"generation",{templateName:F,contextKeys:Object.keys(B),availableTemplates:E?.availableTemplates?.length||0,debugInfo:E});this.templateName=F;this.templateContext=B;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((B)=>{D.push(` • ${B}`)});let F=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);if(F.length>0)D.push("\uD83E\uDD14 Did you mean:"),F.forEach((B)=>{D.push(` • ${B}`)})}}if(this.debugInfo?.missingVariables?.length){D.push("\uD83D\uDCDD Missing template variables:"),this.debugInfo.missingVariables.forEach((B)=>{D.push(` • ${B}`)}),D.push("\uD83D\uDCA1 Add these variables to your template context");let F=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach((B)=>{let E=F.filter((C)=>this.levenshteinDistance(B.toLowerCase(),C.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 B=this.debugInfo.templateSource.split(`
4
+ `)[this.debugInfo.lineNumber-1];if(B)D.push(` Code: ${B.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((B)=>{let E=this.levenshteinDistance(D.toLowerCase(),B.toLowerCase());return E<=2&&E>0}).slice(0,3).sort((B,E)=>this.levenshteinDistance(D.toLowerCase(),B.toLowerCase())-this.levenshteinDistance(D.toLowerCase(),E.toLowerCase()))}levenshteinDistance(D,F){let B=Array(F.length+1).fill(null).map(()=>Array(D.length+1).fill(0));for(let E=0;E<=D.length;E++)B[0][E]=E;for(let E=0;E<=F.length;E++)B[E][0]=E;for(let E=1;E<=F.length;E++)for(let C=1;C<=D.length;C++){let u=D[C-1]===F[E-1]?0:1;B[E][C]=Math.min(B[E]?.[C-1]+1,B[E-1]?.[C]+1,B[E-1]?.[C-1]+u)}return B[F.length]?.[D.length]}isRecoverable(){return!0}};X0=class X0 extends ND{operation;filePath;originalError;recoveryOptions;constructor(D,F,B,E,C){super(D,"writing",{operation:F,filePath:B,originalErrorMessage:E?.message,originalErrorCode:E?.code,recoveryOptions:C});this.operation=F;this.filePath=B;this.originalError=E;this.recoveryOptions=C}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((B)=>{D.push(` • ${B}`)});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 B=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);D.push(` • Required space: ~${B}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}};r2=class r2 extends ND{configKey;providedValue;expectedValue;validOptions;constructor(D,F,B,E,C){super(D,"initialization",{configKey:F,providedValue:B,providedType:typeof B,expectedValue:E,validOptions:C});this.configKey=F;this.providedValue=B;this.expectedValue=E;this.validOptions=C}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}};a2=class a2 extends ND{errors;constructor(D,F){super(D,"generation",{errorCount:F.length,errorTypes:[...new Set(F.map((B)=>B.constructor.name))],phases:[...new Set(F.map((B)=>B.phase))]});this.errors=F}getSuggestions(){let D=this.errors.flatMap((u)=>u.getSuggestions()),F=[...new Set(D)],B=[];B.push(`\uD83D\uDCCA Batch operation failed with ${this.errors.length} errors:`);let E=new Map;this.errors.forEach((u)=>{let $=u.constructor.name;if(!E.has($))E.set($,[]);E.get($)?.push(u)}),B.push(""),B.push("\uD83D\uDD0D Error breakdown:");for(let[u,$]of E)B.push(` • ${u}: ${$.length} occurrences`);B.push("\uD83D\uDCA1 Most relevant suggestions:");let C=F.slice(0,8).map((u)=>` ${u}`);return B.push(...C),B}getErrorBreakdown(){let D=[];return this.errors.forEach((F,B)=>{if(D.push(`${B+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 _6={};bF(_6,{FileBuilder:()=>M6});class M6{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 VF(`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(B){throw new VF(`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,B]of D)this.imports.set(F,B);return this}addImport(D,F){return this.imports.set(D,F),this}addImports(D,F){for(let B of D)this.imports.set(B,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}),B={size:F.size,generationTime:0,writeTime:F.writeTime};for(let E of this.afterSaveHooks)await E(F.path,B);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),F.path}catch(F){for(let B of this.errorHooks)try{await B(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(`
6
6
  `);if(this.options.prettify)F=this.prettifyContent(F);return F}generateImportStatements(){let D=[],F=new Map;for(let[B,E]of this.imports){let C=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,E):E;if(!F.has(C))F.set(C,[]);F.get(C)?.push(B)}for(let[B,E]of F)if(E.length===1)D.push(`import type { ${E[0]} } from '${B}';`);else{let C=E.sort();if(C.length<=3)D.push(`import type { ${C.join(", ")} } from '${B}';`);else{D.push("import type {");let u="\t";C.forEach(($,X)=>{let Q=X===C.length-1;D.push(`${u}${$}${Q?"":","}`)}),D.push(`} from '${B}';`)}}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=[],B=(D.match(/\{/g)||[]).length,E=(D.match(/\}/g)||[]).length;if(B!==E)F.push(`Unmatched braces: ${B} open, ${E} close`);let C=(D.match(/\(/g)||[]).length,u=(D.match(/\)/g)||[]).length;if(C!==u)F.push(`Unmatched parentheses: ${C} open, ${u} 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 H6=O1(()=>{S0()});var q6={};TF(q6,{DirectoryBuilder:()=>E1});class E1{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=!1;constructor(D){this.config=D}withSubdirectory(D){let F=`${this.config.path}/${D}`,B=new E1({path:F,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${D}`)});return this.subdirectories.set(D,B),B}withFiles(D){for(let[F,B]of Object.entries(D))this.files.set(F,B);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([B,E])=>{try{let C=await E.save();return D.push(C),C}catch(C){throw this.config.logger.error(`Failed to save file ${B}:`,C instanceof Error?C:void 0),C}});await Promise.all(F);for(let[B,E]of this.subdirectories)try{let C=await E.save();D.push(...C)}catch(C){throw this.config.logger.error(`Failed to save subdirectory ${B}:`,C instanceof Error?C:void 0),C}if(this.indexBuilder)try{let B=await this.indexBuilder.save();D.push(B)}catch(B){throw this.config.logger.error("Failed to save index file:",B instanceof Error?B:void 0),B}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,B]of this.subdirectories){let E=B.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 B=`${this.config.path}/${F}`;if(await this.config.fileManager.wouldOverwrite(B))D.push(B)}for(let F of this.subdirectories.values()){let B=await F.wouldOverwrite();D.push(...B)}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 _6={};TF(_6,{IndexBuilder:()=>M6});class M6{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(D){this.config=D}withExports(D,F){for(let B of D)this.exports.set(B,F);return this}withExport(D,F){return this.exports.set(D,F),this}withNamespaces(D){for(let[F,B]of Object.entries(D))this.namespaces.set(F,B);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`,B=await this.config.fileManager.writeFile(F,D);return this.config.logger.debug(`Generated index file: ${F}`),B.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 B of this.reExports.values())D.push(`export * from './${B}';`);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 B=Array.from(this.namespaces.entries()).sort();for(let[E,C]of B)D.push(`export * as ${E} from './${C}';`);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=[],B=(D.match(/\{/g)||[]).length,E=(D.match(/\}/g)||[]).length;if(B!==E)F.push(`Unmatched braces: ${B} open, ${E} close`);let C=(D.match(/\(/g)||[]).length,u=(D.match(/\)/g)||[]).length;if(C!==u)F.push(`Unmatched parentheses: ${C} open, ${u} 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 K6=J1(()=>{v0()});var V6={};bF(V6,{DirectoryBuilder:()=>u1});class u1{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=!1;constructor(D){this.config=D}withSubdirectory(D){let F=`${this.config.path}/${D}`,B=new u1({path:F,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${D}`)});return this.subdirectories.set(D,B),B}withFiles(D){for(let[F,B]of Object.entries(D))this.files.set(F,B);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([B,E])=>{try{let C=await E.save();return D.push(C),C}catch(C){throw this.config.logger.error(`Failed to save file ${B}:`,C instanceof Error?C:void 0),C}});await Promise.all(F);for(let[B,E]of this.subdirectories)try{let C=await E.save();D.push(...C)}catch(C){throw this.config.logger.error(`Failed to save subdirectory ${B}:`,C instanceof Error?C:void 0),C}if(this.indexBuilder)try{let B=await this.indexBuilder.save();D.push(B)}catch(B){throw this.config.logger.error("Failed to save index file:",B instanceof Error?B:void 0),B}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,B]of this.subdirectories){let E=B.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 B=`${this.config.path}/${F}`;if(await this.config.fileManager.wouldOverwrite(B))D.push(B)}for(let F of this.subdirectories.values()){let B=await F.wouldOverwrite();D.push(...B)}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 U6={};bF(U6,{IndexBuilder:()=>R6});class R6{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(D){this.config=D}withExports(D,F){for(let B of D)this.exports.set(B,F);return this}withExport(D,F){return this.exports.set(D,F),this}withNamespaces(D){for(let[F,B]of Object.entries(D))this.namespaces.set(F,B);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`,B=await this.config.fileManager.writeFile(F,D);return this.config.logger.debug(`Generated index file: ${F}`),B.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 B of this.reExports.values())D.push(`export * from './${B}';`);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 B=Array.from(this.namespaces.entries()).sort();for(let[E,C]of B)D.push(`export * as ${E} from './${C}';`);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],[C])=>E.localeCompare(C));let B=new Map;for(let[E,C]of F){if(!B.has(C))B.set(C,[]);B.get(C)?.push(E)}for(let[E,C]of B){let u=C.sort();if(u.length===1)D.push(`export type { ${u[0]} } from './${E}';`);else if(u.length<=3)D.push(`export type { ${u.join(", ")} } from './${E}';`);else D.push("export type {"),u.forEach(($,X)=>{let Q=X===u.length-1;D.push(` ${$}${Q?"":","}`)}),D.push(`} from './${E}';`)}}generateGroupedExports(D){if(!this.groupingFunction)return;let F=new Map;for(let[E,C]of this.exports){let u=this.groupingFunction(E);if(!F.has(u))F.set(u,new Map);let $=F.get(u);if(!$.has(C))$.set(C,[]);$.get(C)?.push(E)}let B=Array.from(F.entries()).sort();for(let[E,C]of B){D.push(`// ${E}`);for(let[u,$]of C){let X=$.sort();if(X.length===1)D.push(`export type { ${X[0]} } from './${u}';`);else D.push(`export type { ${X.join(", ")} } from './${u}';`)}D.push("")}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}}import{notStrictEqual as A8,strictEqual as G8}from"assert";var S6={right:f6,center:y6};class J1{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((B)=>{if(typeof B==="string")return this.colFromString(B);return B});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],[C])=>E.localeCompare(C));let B=new Map;for(let[E,C]of F){if(!B.has(C))B.set(C,[]);B.get(C)?.push(E)}for(let[E,C]of B){let u=C.sort();if(u.length===1)D.push(`export type { ${u[0]} } from './${E}';`);else if(u.length<=3)D.push(`export type { ${u.join(", ")} } from './${E}';`);else D.push("export type {"),u.forEach(($,X)=>{let Q=X===u.length-1;D.push(` ${$}${Q?"":","}`)}),D.push(`} from './${E}';`)}}generateGroupedExports(D){if(!this.groupingFunction)return;let F=new Map;for(let[E,C]of this.exports){let u=this.groupingFunction(E);if(!F.has(u))F.set(u,new Map);let $=F.get(u);if(!$.has(C))$.set(C,[]);$.get(C)?.push(E)}let B=Array.from(F.entries()).sort();for(let[E,C]of B){D.push(`// ${E}`);for(let[u,$]of C){let X=$.sort();if(X.length===1)D.push(`export type { ${X[0]} } from './${u}';`);else D.push(`export type { ${X.join(", ")} } from './${u}';`)}D.push("")}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}}import{notStrictEqual as M8,strictEqual as _8}from"assert";var y6={right:g6,center:p6};class A1{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((B)=>{if(typeof B==="string")return this.colFromString(B);return B});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")),B=0;return F.forEach((E)=>{if(E.length>1&&AD.stringWidth(E[0])>B)B=Math.min(Math.floor(this.width*0.5),AD.stringWidth(E[0]))}),F.forEach((E)=>{this.div(...E.map((C,u)=>{return{text:C.trim(),padding:this.measurePadding(C),width:u===0&&E.length>1?B:void 0}}))}),this.rows[this.rows.length-1]}colFromString(D){return{text:D,padding:this.measurePadding(D)}}measurePadding(D){let F=AD.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((B,E)=>{let C="";B.forEach((u,$)=>{let{width:X}=D[$],Q=this.negatePadding(D[$]),z=u;if(Q>AD.stringWidth(u))z+=" ".repeat(Q-AD.stringWidth(u));if(D[$].align&&D[$].align!=="left"&&this.wrap){let W=S6[D[$].align];if(z=W(z,Q),AD.stringWidth(z)<Q)z+=" ".repeat((X||0)-AD.stringWidth(z)-1)}let Y=D[$].padding||[0,0,0,0];if(Y[3])C+=" ".repeat(Y[3]);if(C+=Y1(D[$],z,"| "),C+=z,C+=Y1(D[$],z," |"),Y[1])C+=" ".repeat(Y[1]);if(E===0&&F.length>0)C=this.renderInline(C,F[F.length-1])}),F.push({text:C.replace(/ +$/,""),span:D.span})}),F}renderInline(D,F){let B=D.match(/^ */),E=B?B[0].length:0,C=F.text,u=AD.stringWidth(C.trimRight());if(!F.span)return D;if(!this.wrap)return F.hidden=!0,C+D;if(E<u)return D;return F.hidden=!0,C.trimRight()+" ".repeat(E-u)+D.trimLeft()}rasterize(D){let F=[],B=this.columnWidths(D),E;return D.forEach((C,u)=>{if(C.width=B[u],this.wrap)E=AD.wrap(C.text,this.negatePadding(C),{hard:!0}).split(`
16
+ `)}rowToString(D,F){return this.rasterize(D).forEach((B,E)=>{let C="";B.forEach((u,$)=>{let{width:X}=D[$],Q=this.negatePadding(D[$]),z=u;if(Q>AD.stringWidth(u))z+=" ".repeat(Q-AD.stringWidth(u));if(D[$].align&&D[$].align!=="left"&&this.wrap){let W=y6[D[$].align];if(z=W(z,Q),AD.stringWidth(z)<Q)z+=" ".repeat((X||0)-AD.stringWidth(z)-1)}let Y=D[$].padding||[0,0,0,0];if(Y[3])C+=" ".repeat(Y[3]);if(C+=W1(D[$],z,"| "),C+=z,C+=W1(D[$],z," |"),Y[1])C+=" ".repeat(Y[1]);if(E===0&&F.length>0)C=this.renderInline(C,F[F.length-1])}),F.push({text:C.replace(/ +$/,""),span:D.span})}),F}renderInline(D,F){let B=D.match(/^ */),E=B?B[0].length:0,C=F.text,u=AD.stringWidth(C.trimRight());if(!F.span)return D;if(!this.wrap)return F.hidden=!0,C+D;if(E<u)return D;return F.hidden=!0,C.trimRight()+" ".repeat(E-u)+D.trimLeft()}rasterize(D){let F=[],B=this.columnWidths(D),E;return D.forEach((C,u)=>{if(C.width=B[u],this.wrap)E=AD.wrap(C.text,this.negatePadding(C),{hard:!0}).split(`
17
17
  `);else E=C.text.split(`
18
- `);if(C.border)E.unshift("."+"-".repeat(this.negatePadding(C)+2)+"."),E.push("'"+"-".repeat(this.negatePadding(C)+2)+"'");if(C.padding)E.unshift(...new Array(C.padding[0]||0).fill("")),E.push(...new Array(C.padding[2]||0).fill(""));E.forEach(($,X)=>{if(!F[X])F.push([]);let Q=F[X];for(let z=0;z<u;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((u)=>{return u.width||AD.stringWidth(u.text)});let F=D.length,B=this.width,E=D.map((u)=>{if(u.width)return F--,B-=u.width,u.width;return}),C=F?Math.floor(B/F):0;return E.map((u,$)=>{if(u===void 0)return Math.max(C,v6(D[$]));return u})}}function Y1(D,F,B){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return B;return" "}return""}function v6(D){let F=D.padding||[],B=1+(F[3]||0)+(F[1]||0);if(D.border)return B+4;return B}function k6(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function f6(D,F){D=D.trim();let B=AD.stringWidth(D);if(B<F)return" ".repeat(F-B)+D;return D}function y6(D,F){D=D.trim();let B=AD.stringWidth(D);if(B>=F)return D;return" ".repeat(F-B>>1)+D}var AD;function W1(D,F){return AD=F,new J1({width:(D===null||D===void 0?void 0:D.width)||k6(),wrap:D===null||D===void 0?void 0:D.wrap})}function PF({onlyFirst:D=!1}={}){let B=["[\\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(B,D?void 0:"g")}var d6=PF();function lD(D){if(typeof D!=="string")throw new TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(d6,"")}function A1(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 G1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function H1(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 h6(D){if(!Number.isSafeInteger(D))throw new TypeError(`Expected a code point, got \`${typeof D}\`.`)}function q1(D,{ambiguousAsWide:F=!1}={}){if(h6(D),G1(D)||H1(D)||F&&A1(D))return 2;return 1}var K1=v0(_1(),1),g6=new Intl.Segmenter,p6=/^\p{Default_Ignorable_Code_Point}$/u;function UD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:B=!0,countAnsiEscapeCodes:E=!1}=F;if(!E)D=lD(D);if(D.length===0)return 0;let C=0,u={ambiguousAsWide:!B};for(let{segment:$}of g6.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(p6.test($))continue;if(K1.default().test($)){C+=2;continue}C+=q1(X,u)}return C}var V1=(D=0)=>(F)=>`\x1B[${F+D}m`,R1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,U1=(D=0)=>(F,B,E)=>`\x1B[${38+D};2;${F};${B};${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]}},JE=Object.keys(r.modifier),m6=Object.keys(r.color),l6=Object.keys(r.bgColor),WE=[...m6,...l6];function c6(){let D=new Map;for(let[F,B]of Object.entries(r)){for(let[E,C]of Object.entries(B))r[E]={open:`\x1B[${C[0]}m`,close:`\x1B[${C[1]}m`},B[E]=r[E],D.set(C[0],C[1]);Object.defineProperty(r,F,{value:B,enumerable:!1})}return Object.defineProperty(r,"codes",{value:D,enumerable:!1}),r.color.close="\x1B[39m",r.bgColor.close="\x1B[49m",r.color.ansi=V1(),r.color.ansi256=R1(),r.color.ansi16m=U1(),r.bgColor.ansi=V1(10),r.bgColor.ansi256=R1(10),r.bgColor.ansi16m=U1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,B,E)=>{if(F===B&&B===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(B/255*5)+Math.round(E/255*5)},enumerable:!1},hexToRgb:{value:(F)=>{let B=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!B)return[0,0,0];let[E]=B;if(E.length===3)E=[...E].map((u)=>u+u).join("");let C=Number.parseInt(E,16);return[C>>16&255,C>>8&255,C&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 B,E,C;if(F>=232)B=((F-232)*10+8)/255,E=B,C=B;else{F-=16;let X=F%36;B=Math.floor(F/36)/5,E=Math.floor(X/6)/5,C=X%6/5}let u=Math.max(B,E,C)*2;if(u===0)return 30;let $=30+(Math.round(C)<<2|Math.round(E)<<1|Math.round(B));if(u===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,B,E)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,B,E)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var o6=c6(),L1=o6;var f0=new Set(["\x1B","›"]),n6=39,vF="\x07",w1="[",i6="]",I1="m",k0=`${i6}8;;`,N1=(D)=>`${f0.values().next().value}${w1}${D}${I1}`,j1=(D)=>`${f0.values().next().value}${k0}${D}${vF}`,t6=(D)=>D.split(" ").map((F)=>UD(F)),SF=(D,F,B)=>{let E=[...F],C=!1,u=!1,$=UD(lD(D.at(-1)));for(let[X,Q]of E.entries()){let z=UD(Q);if($+z<=B)D[D.length-1]+=Q;else D.push(Q),$=0;if(f0.has(Q))C=!0,u=E.slice(X+1,X+1+k0.length).join("")===k0;if(C){if(u){if(Q===vF)C=!1,u=!1}else if(Q===I1)C=!1;continue}if($+=z,$===B&&X<E.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},s6=(D)=>{let F=D.split(" "),B=F.length;while(B>0){if(UD(F[B-1])>0)break;B--}if(B===F.length)return D;return F.slice(0,B).join(" ")+F.slice(B).join("")},r6=(D,F,B={})=>{if(B.trim!==!1&&D.trim()==="")return"";let E="",C,u,$=t6(D),X=[""];for(let[W,J]of D.split(" ").entries()){if(B.trim!==!1)X[X.length-1]=X.at(-1).trimStart();let q=UD(X.at(-1));if(W!==0){if(q>=F&&(B.wordWrap===!1||B.trim===!1))X.push(""),q=0;if(q>0||B.trim===!1)X[X.length-1]+=" ",q++}if(B.hard&&$[W]>F){let _=F-q,H=1+Math.floor(($[W]-_-1)/F);if(Math.floor(($[W]-1)/F)<H)X.push("");SF(X,J,F);continue}if(q+$[W]>F&&q>0&&$[W]>0){if(B.wordWrap===!1&&q<F){SF(X,J,F);continue}X.push("")}if(q+$[W]>F&&B.wordWrap===!1){SF(X,J,F);continue}X[X.length-1]+=J}if(B.trim!==!1)X=X.map((W)=>s6(W));let Q=X.join(`
19
- `),z=[...Q],Y=0;for(let[W,J]of z.entries()){if(E+=J,f0.has(J)){let{groups:_}=new RegExp(`(?:\\${w1}(?<code>\\d+)m|\\${k0}(?<uri>.*)${vF})`).exec(Q.slice(Y))||{groups:{}};if(_.code!==void 0){let H=Number.parseFloat(_.code);C=H===n6?void 0:H}else if(_.uri!==void 0)u=_.uri.length===0?void 0:_.uri}let q=L1.codes.get(Number(C));if(z[W+1]===`
20
- `){if(u)E+=j1("");if(C&&q)E+=N1(q)}else if(J===`
21
- `){if(C&&q)E+=N1(C);if(u)E+=j1(u)}Y+=J.length}return E};function kF(D,F,B){return String(D).normalize().replaceAll(`\r
18
+ `);if(C.border)E.unshift("."+"-".repeat(this.negatePadding(C)+2)+"."),E.push("'"+"-".repeat(this.negatePadding(C)+2)+"'");if(C.padding)E.unshift(...new Array(C.padding[0]||0).fill("")),E.push(...new Array(C.padding[2]||0).fill(""));E.forEach(($,X)=>{if(!F[X])F.push([]);let Q=F[X];for(let z=0;z<u;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((u)=>{return u.width||AD.stringWidth(u.text)});let F=D.length,B=this.width,E=D.map((u)=>{if(u.width)return F--,B-=u.width,u.width;return}),C=F?Math.floor(B/F):0;return E.map((u,$)=>{if(u===void 0)return Math.max(C,d6(D[$]));return u})}}function W1(D,F,B){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return B;return" "}return""}function d6(D){let F=D.padding||[],B=1+(F[3]||0)+(F[1]||0);if(D.border)return B+4;return B}function h6(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function g6(D,F){D=D.trim();let B=AD.stringWidth(D);if(B<F)return" ".repeat(F-B)+D;return D}function p6(D,F){D=D.trim();let B=AD.stringWidth(D);if(B>=F)return D;return" ".repeat(F-B>>1)+D}var AD;function G1(D,F){return AD=F,new A1({width:(D===null||D===void 0?void 0:D.width)||h6(),wrap:D===null||D===void 0?void 0:D.wrap})}function PF({onlyFirst:D=!1}={}){let B=["[\\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(B,D?void 0:"g")}var m6=PF();function lD(D){if(typeof D!=="string")throw new TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(m6,"")}function H1(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 q1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function M1(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 l6(D){if(!Number.isSafeInteger(D))throw new TypeError(`Expected a code point, got \`${typeof D}\`.`)}function _1(D,{ambiguousAsWide:F=!1}={}){if(l6(D),q1(D)||M1(D)||F&&H1(D))return 2;return 1}var R1=k0(V1(),1),c6=new Intl.Segmenter,o6=/^\p{Default_Ignorable_Code_Point}$/u;function UD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:B=!0,countAnsiEscapeCodes:E=!1}=F;if(!E)D=lD(D);if(D.length===0)return 0;let C=0,u={ambiguousAsWide:!B};for(let{segment:$}of c6.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(o6.test($))continue;if(R1.default().test($)){C+=2;continue}C+=_1(X,u)}return C}var U1=(D=0)=>(F)=>`\x1B[${F+D}m`,L1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,N1=(D=0)=>(F,B,E)=>`\x1B[${38+D};2;${F};${B};${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]}},qE=Object.keys(r.modifier),n6=Object.keys(r.color),i6=Object.keys(r.bgColor),ME=[...n6,...i6];function t6(){let D=new Map;for(let[F,B]of Object.entries(r)){for(let[E,C]of Object.entries(B))r[E]={open:`\x1B[${C[0]}m`,close:`\x1B[${C[1]}m`},B[E]=r[E],D.set(C[0],C[1]);Object.defineProperty(r,F,{value:B,enumerable:!1})}return Object.defineProperty(r,"codes",{value:D,enumerable:!1}),r.color.close="\x1B[39m",r.bgColor.close="\x1B[49m",r.color.ansi=U1(),r.color.ansi256=L1(),r.color.ansi16m=N1(),r.bgColor.ansi=U1(10),r.bgColor.ansi256=L1(10),r.bgColor.ansi16m=N1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,B,E)=>{if(F===B&&B===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(B/255*5)+Math.round(E/255*5)},enumerable:!1},hexToRgb:{value:(F)=>{let B=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!B)return[0,0,0];let[E]=B;if(E.length===3)E=[...E].map((u)=>u+u).join("");let C=Number.parseInt(E,16);return[C>>16&255,C>>8&255,C&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 B,E,C;if(F>=232)B=((F-232)*10+8)/255,E=B,C=B;else{F-=16;let X=F%36;B=Math.floor(F/36)/5,E=Math.floor(X/6)/5,C=X%6/5}let u=Math.max(B,E,C)*2;if(u===0)return 30;let $=30+(Math.round(C)<<2|Math.round(E)<<1|Math.round(B));if(u===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,B,E)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,B,E)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var s6=t6(),j1=s6;var y0=new Set(["\x1B","›"]),r6=39,vF="\x07",T1="[",a6="]",b1="m",f0=`${a6}8;;`,w1=(D)=>`${y0.values().next().value}${T1}${D}${b1}`,I1=(D)=>`${y0.values().next().value}${f0}${D}${vF}`,e6=(D)=>D.split(" ").map((F)=>UD(F)),SF=(D,F,B)=>{let E=[...F],C=!1,u=!1,$=UD(lD(D.at(-1)));for(let[X,Q]of E.entries()){let z=UD(Q);if($+z<=B)D[D.length-1]+=Q;else D.push(Q),$=0;if(y0.has(Q))C=!0,u=E.slice(X+1,X+1+f0.length).join("")===f0;if(C){if(u){if(Q===vF)C=!1,u=!1}else if(Q===b1)C=!1;continue}if($+=z,$===B&&X<E.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},D8=(D)=>{let F=D.split(" "),B=F.length;while(B>0){if(UD(F[B-1])>0)break;B--}if(B===F.length)return D;return F.slice(0,B).join(" ")+F.slice(B).join("")},F8=(D,F,B={})=>{if(B.trim!==!1&&D.trim()==="")return"";let E="",C,u,$=e6(D),X=[""];for(let[W,J]of D.split(" ").entries()){if(B.trim!==!1)X[X.length-1]=X.at(-1).trimStart();let q=UD(X.at(-1));if(W!==0){if(q>=F&&(B.wordWrap===!1||B.trim===!1))X.push(""),q=0;if(q>0||B.trim===!1)X[X.length-1]+=" ",q++}if(B.hard&&$[W]>F){let M=F-q,G=1+Math.floor(($[W]-M-1)/F);if(Math.floor(($[W]-1)/F)<G)X.push("");SF(X,J,F);continue}if(q+$[W]>F&&q>0&&$[W]>0){if(B.wordWrap===!1&&q<F){SF(X,J,F);continue}X.push("")}if(q+$[W]>F&&B.wordWrap===!1){SF(X,J,F);continue}X[X.length-1]+=J}if(B.trim!==!1)X=X.map((W)=>D8(W));let Q=X.join(`
19
+ `),z=[...Q],Y=0;for(let[W,J]of z.entries()){if(E+=J,y0.has(J)){let{groups:M}=new RegExp(`(?:\\${T1}(?<code>\\d+)m|\\${f0}(?<uri>.*)${vF})`).exec(Q.slice(Y))||{groups:{}};if(M.code!==void 0){let G=Number.parseFloat(M.code);C=G===r6?void 0:G}else if(M.uri!==void 0)u=M.uri.length===0?void 0:M.uri}let q=j1.codes.get(Number(C));if(z[W+1]===`
20
+ `){if(u)E+=I1("");if(C&&q)E+=w1(q)}else if(J===`
21
+ `){if(C&&q)E+=w1(C);if(u)E+=I1(u)}Y+=J.length}return E};function kF(D,F,B){return String(D).normalize().replaceAll(`\r
22
22
  `,`
23
23
  `).split(`
24
- `).map((E)=>r6(E,F,B)).join(`
25
- `)}function fF(D){return W1(D,{stringWidth:UD,stripAnsi:lD,wrap:kF})}import{dirname as b1,resolve as T1}from"path";import{readdirSync as a6,statSync as e6}from"fs";function yF(D,F){let B=T1(".",D),E;if(!e6(B).isDirectory())B=b1(B);while(!0){if(E=F(B,a6(B)),E)return T1(B,E);if(B=b1(E=B),E===B)break}}import{inspect as H8}from"util";import{fileURLToPath as i1}from"url";import{format as B8}from"util";import{normalize as E8,resolve as C8}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 B="",E=!1,C=D.match(/^-+/);for(let u=C?C[0].length:0;u<D.length;u++){let $=D.charAt(u);if(E)E=!1,$=$.toUpperCase();if(u!==0&&($==="-"||$==="_"))E=!0;else if($!=="-"&&$!=="_")B+=$}return B}}function y0(D,F){let B=D.toLowerCase();F=F||"-";let E="";for(let C=0;C<D.length;C++){let u=B.charAt(C),$=D.charAt(C);if(u!==$&&C>0)E+=`${F}${B.charAt(C)}`;else E+=$}return E}function d0(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 x1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,B=null,E=null,C=null,u=[];for(let $=0;$<D.length;$++){if(B=E,E=D.charAt($),E===" "&&!C){if(B!==" ")F++;continue}if(E===C)C=null;else if((E==="'"||E==='"')&&!C)C=E;if(!u[F])u[F]="";u[F]+=E}return u}var MD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(MD||(MD={}));var TD;class hF{constructor(D){TD=D}parse(D,F){let B=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=x1(D),C=typeof D==="string",u=D8(Object.assign(Object.create(null),B.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},B.configuration),X=Object.assign(Object.create(null),B.default),Q=B.configObjects||[],z=B.envPrefix,Y=$["populate--"],W=Y?"--":"_",J=Object.create(null),q=Object.create(null),_=B.__||TD.format,H={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:[]},P=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,m=new RegExp("^--"+$["negation-prefix"]+"(.+)");if([].concat(B.array||[]).filter(Boolean).forEach(function(O){let G=typeof O==="object"?O.key:O,K=Object.keys(O).map(function(M){return{boolean:"bools",string:"strings",number:"numbers"}[M]}).filter(Boolean).pop();if(K)H[K][G]=!0;H.arrays[G]=!0,H.keys.push(G)}),[].concat(B.boolean||[]).filter(Boolean).forEach(function(O){H.bools[O]=!0,H.keys.push(O)}),[].concat(B.string||[]).filter(Boolean).forEach(function(O){H.strings[O]=!0,H.keys.push(O)}),[].concat(B.number||[]).filter(Boolean).forEach(function(O){H.numbers[O]=!0,H.keys.push(O)}),[].concat(B.count||[]).filter(Boolean).forEach(function(O){H.counts[O]=!0,H.keys.push(O)}),[].concat(B.normalize||[]).filter(Boolean).forEach(function(O){H.normalize[O]=!0,H.keys.push(O)}),typeof B.narg==="object")Object.entries(B.narg).forEach(([O,G])=>{if(typeof G==="number")H.nargs[O]=G,H.keys.push(O)});if(typeof B.coerce==="object")Object.entries(B.coerce).forEach(([O,G])=>{if(typeof G==="function")H.coercions[O]=G,H.keys.push(O)});if(typeof B.config!=="undefined"){if(Array.isArray(B.config)||typeof B.config==="string")[].concat(B.config).filter(Boolean).forEach(function(O){H.configs[O]=!0});else if(typeof B.config==="object")Object.entries(B.config).forEach(([O,G])=>{if(typeof G==="boolean"||typeof G==="function")H.configs[O]=G})}V0(B.key,u,B.default,H.arrays),Object.keys(X).forEach(function(O){(H.aliases[O]||[]).forEach(function(G){X[G]=X[O]})});let g=null;wF();let QD=[],V=Object.assign(Object.create(null),{_:[]}),L={};for(let O=0;O<E.length;O++){let G=E[O],K=G.replace(/^-{3,}/,"---"),M,A,I,U,x,XD;if(G!=="--"&&/^-/.test(G)&&n(G))k(G);else if(K.match(/^---+(=|$)/)){k(G);continue}else if(G.match(/^--.+=/)||!$["short-option-groups"]&&G.match(/^-.+=/)){if(U=G.match(/^--?([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)if(S(U[1],H.arrays))O=t(O,U[1],E,U[2]);else if(S(U[1],H.nargs)!==!1)O=d(O,U[1],E,U[2]);else l(U[1],U[2],!0)}else if(G.match(m)&&$["boolean-negation"]){if(U=G.match(m),U!==null&&Array.isArray(U)&&U.length>=2)A=U[1],l(A,S(A,H.arrays)?[!1]:!1)}else if(G.match(/^--.+/)||!$["short-option-groups"]&&G.match(/^-[^-]+/)){if(U=G.match(/^--?(.+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],S(A,H.arrays))O=t(O,A,E);else if(S(A,H.nargs)!==!1)O=d(O,A,E);else if(x=E[O+1],x!==void 0&&(!x.match(/^-/)||x.match(P))&&!S(A,H.bools)&&!S(A,H.counts))l(A,x),O++;else if(/^(true|false)$/.test(x))l(A,x),O++;else l(A,p(A))}else if(G.match(/^-.\..+=/)){if(U=G.match(/^-([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)l(U[1],U[2])}else if(G.match(/^-.\..+/)&&!G.match(P)){if(x=E[O+1],U=G.match(/^-(.\..+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],x!==void 0&&!x.match(/^-/)&&!S(A,H.bools)&&!S(A,H.counts))l(A,x),O++;else l(A,p(A))}else if(G.match(/^-[^-]+/)&&!G.match(P)){I=G.slice(1,-1).split(""),M=!1;for(let OD=0;OD<I.length;OD++){if(x=G.slice(OD+2),I[OD+1]&&I[OD+1]==="="){if(XD=G.slice(OD+3),A=I[OD],S(A,H.arrays))O=t(O,A,E,XD);else if(S(A,H.nargs)!==!1)O=d(O,A,E,XD);else l(A,XD);M=!0;break}if(x==="-"){l(I[OD],x);continue}if(/[A-Za-z]/.test(I[OD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(x)&&S(x,H.bools)===!1){l(I[OD],x),M=!0;break}if(I[OD+1]&&I[OD+1].match(/\W/)){l(I[OD],x),M=!0;break}else l(I[OD],p(I[OD]))}if(A=G.slice(-1)[0],!M&&A!=="-")if(S(A,H.arrays))O=t(O,A,E);else if(S(A,H.nargs)!==!1)O=d(O,A,E);else if(x=E[O+1],x!==void 0&&(!/^(-|--)[^-]/.test(x)||x.match(P))&&!S(A,H.bools)&&!S(A,H.counts))l(A,x),O++;else if(/^(true|false)$/.test(x))l(A,x),O++;else l(A,p(A))}else if(G.match(/^-[0-9]$/)&&G.match(P)&&S(G.slice(1),H.bools))A=G.slice(1),l(A,p(A));else if(G==="--"){QD=E.slice(O+1);break}else if($["halt-at-non-option"]){QD=E.slice(O);break}else k(G)}if(BD(V,!0),BD(V,!1),b(V),o(),vD(V,H.aliases,X,!0),c(V),$["set-placeholder-key"])ED(V);if(Object.keys(H.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(u).map((O)=>u[O])).forEach((O)=>{if($["camel-case-expansion"]&&O.includes("-"))delete V[O.split(".").map((G)=>cD(G)).join(".")];delete V[O]});function k(O){let G=R("_",O);if(typeof G==="string"||typeof G==="number")V._.push(G)}function d(O,G,K,M){let A,I=S(G,H.nargs);if(I=typeof I!=="number"||isNaN(I)?1:I,I===0){if(!uD(M))g=Error(_("Argument unexpected for: %s",G));return l(G,p(G)),O}let U=uD(M)?0:1;if($["nargs-eats-options"]){if(K.length-(O+1)+U<I)g=Error(_("Not enough arguments following: %s",G));U=I}else{for(A=O+1;A<K.length;A++)if(!K[A].match(/^-[^0-9]/)||K[A].match(P)||n(K[A]))U++;else break;if(U<I)g=Error(_("Not enough arguments following: %s",G))}let x=Math.min(U,I);if(!uD(M)&&x>0)l(G,M),x--;for(A=O+1;A<x+O+1;A++)l(G,K[A]);return O+x}function t(O,G,K,M){let A=[],I=M||K[O+1],U=S(G,H.nargs);if(S(G,H.bools)&&!/^(true|false)$/.test(I))A.push(!0);else if(uD(I)||uD(M)&&/^-/.test(I)&&!P.test(I)&&!n(I)){if(X[G]!==void 0){let x=X[G];A=Array.isArray(x)?x:[x]}}else{if(!uD(M))A.push(w(G,M,!0));for(let x=O+1;x<K.length;x++){if(!$["greedy-arrays"]&&A.length>0||U&&typeof U==="number"&&A.length>=U)break;if(I=K[x],/^-/.test(I)&&!P.test(I)&&!n(I))break;O=x,A.push(w(G,I,C))}}if(typeof U==="number"&&(U&&A.length<U||isNaN(U)&&A.length===0))g=Error(_("Not enough arguments following: %s",G));return l(G,A),O}function l(O,G,K=C){if(/-/.test(O)&&$["camel-case-expansion"]){let I=O.split(".").map(function(U){return cD(U)}).join(".");jD(O,I)}let M=w(O,G,K),A=O.split(".");if(bD(V,A,M),H.aliases[O])H.aliases[O].forEach(function(I){let U=I.split(".");bD(V,U,M)});if(A.length>1&&$["dot-notation"])(H.aliases[A[0]]||[]).forEach(function(I){let U=I.split("."),x=[].concat(A);if(x.shift(),U=U.concat(x),!(H.aliases[O]||[]).includes(U.join(".")))bD(V,U,M)});if(S(O,H.normalize)&&!S(O,H.arrays))[O].concat(H.aliases[O]||[]).forEach(function(U){Object.defineProperty(L,U,{enumerable:!0,get(){return G},set(x){G=typeof x==="string"?TD.normalize(x):x}})})}function jD(O,G){if(!(H.aliases[O]&&H.aliases[O].length))H.aliases[O]=[G],J[G]=!0;if(!(H.aliases[G]&&H.aliases[G].length))jD(G,O)}function w(O,G,K){if(K)G=F8(G);if(S(O,H.bools)||S(O,H.counts)){if(typeof G==="string")G=G==="true"}let M=Array.isArray(G)?G.map(function(A){return R(O,A)}):R(O,G);if(S(O,H.counts)&&(uD(M)||typeof M==="boolean"))M=dF();if(S(O,H.normalize)&&S(O,H.arrays))if(Array.isArray(G))M=G.map((A)=>{return TD.normalize(A)});else M=TD.normalize(G);return M}function R(O,G){if(!$["parse-positional-numbers"]&&O==="_")return G;if(!S(O,H.strings)&&!S(O,H.bools)&&!Array.isArray(G)){if(d0(G)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${G}`)))||!uD(G)&&S(O,H.numbers))G=Number(G)}return G}function b(O){let G=Object.create(null);vD(G,H.aliases,X),Object.keys(H.configs).forEach(function(K){let M=O[K]||G[K];if(M)try{let A=null,I=TD.resolve(TD.cwd(),M),U=H.configs[K];if(typeof U==="function"){try{A=U(I)}catch(x){A=x}if(A instanceof Error){g=A;return}}else A=TD.require(I);y(A)}catch(A){if(A.name==="PermissionDenied")g=A;else if(O[K])g=Error(_("Invalid JSON config file: %s",M))}})}function y(O,G){Object.keys(O).forEach(function(K){let M=O[K],A=G?G+"."+K:K;if(typeof M==="object"&&M!==null&&!Array.isArray(M)&&$["dot-notation"])y(M,A);else if(!i(V,A.split("."))||S(A,H.arrays)&&$["combine-arrays"])l(A,M)})}function o(){if(typeof Q!=="undefined")Q.forEach(function(O){y(O)})}function BD(O,G){if(typeof z==="undefined")return;let K=typeof z==="string"?z:"",M=TD.env();Object.keys(M).forEach(function(A){if(K===""||A.lastIndexOf(K,0)===0){let I=A.split("__").map(function(U,x){if(x===0)U=U.substring(K.length);return cD(U)});if((G&&H.configs[I.join(".")]||!G)&&!i(O,I))l(I.join("."),M[A])}})}function c(O){let G,K=new Set;Object.keys(O).forEach(function(M){if(!K.has(M)){if(G=S(M,H.coercions),typeof G==="function")try{let A=R(M,G(O[M]));[].concat(H.aliases[M]||[],M).forEach((I)=>{K.add(I),O[I]=A})}catch(A){g=A}}})}function ED(O){return H.keys.forEach((G)=>{if(~G.indexOf("."))return;if(typeof O[G]==="undefined")O[G]=void 0}),O}function vD(O,G,K,M=!1){Object.keys(K).forEach(function(A){if(!i(O,A.split("."))){if(bD(O,A.split("."),K[A]),M)q[A]=!0;(G[A]||[]).forEach(function(I){if(i(O,I.split(".")))return;bD(O,I.split("."),K[A])})}})}function i(O,G){let K=O;if(!$["dot-notation"])G=[G.join(".")];G.slice(0,-1).forEach(function(A){K=K[A]||{}});let M=G[G.length-1];if(typeof K!=="object")return!1;else return M in K}function bD(O,G,K){let M=O;if(!$["dot-notation"])G=[G.join(".")];G.slice(0,-1).forEach(function(XD){if(XD=P1(XD),typeof M==="object"&&M[XD]===void 0)M[XD]={};if(typeof M[XD]!=="object"||Array.isArray(M[XD])){if(Array.isArray(M[XD]))M[XD].push({});else M[XD]=[M[XD],{}];M=M[XD][M[XD].length-1]}else M=M[XD]});let A=P1(G[G.length-1]),I=S(G.join("."),H.arrays),U=Array.isArray(K),x=$["duplicate-arguments-array"];if(!x&&S(A,H.nargs)){if(x=!0,!uD(M[A])&&H.nargs[A]===1||Array.isArray(M[A])&&M[A].length===H.nargs[A])M[A]=void 0}if(K===dF())M[A]=dF(M[A]);else if(Array.isArray(M[A]))if(x&&I&&U)M[A]=$["flatten-duplicate-arrays"]?M[A].concat(K):(Array.isArray(M[A][0])?M[A]:[M[A]]).concat([K]);else if(!x&&Boolean(I)===Boolean(U))M[A]=K;else M[A]=M[A].concat([K]);else if(M[A]===void 0&&I)M[A]=U?K:[K];else if(x&&!(M[A]===void 0||S(A,H.counts)||S(A,H.bools)))M[A]=[M[A],K];else M[A]=K}function V0(...O){O.forEach(function(G){Object.keys(G||{}).forEach(function(K){if(H.aliases[K])return;H.aliases[K]=[].concat(u[K]||[]),H.aliases[K].concat(K).forEach(function(M){if(/-/.test(M)&&$["camel-case-expansion"]){let A=cD(M);if(A!==K&&H.aliases[K].indexOf(A)===-1)H.aliases[K].push(A),J[A]=!0}}),H.aliases[K].concat(K).forEach(function(M){if(M.length>1&&/[A-Z]/.test(M)&&$["camel-case-expansion"]){let A=y0(M,"-");if(A!==K&&H.aliases[K].indexOf(A)===-1)H.aliases[K].push(A),J[A]=!0}}),H.aliases[K].forEach(function(M){H.aliases[M]=[K].concat(H.aliases[K].filter(function(A){return M!==A}))})})})}function S(O,G){let K=[].concat(H.aliases[O]||[],O),M=Object.keys(G),A=K.find((I)=>M.includes(I));return A?G[A]:!1}function Q0(O){let G=Object.keys(H);return[].concat(G.map((M)=>H[M])).some(function(M){return Array.isArray(M)?M.includes(O):M[O]})}function X1(O,...G){return[].concat(...G).some(function(M){let A=O.match(M);return A&&Q0(A[1])})}function v(O){if(O.match(P)||!O.match(/^-[^-]+/))return!1;let G=!0,K,M=O.slice(1).split("");for(let A=0;A<M.length;A++){if(K=O.slice(A+2),!Q0(M[A])){G=!1;break}if(M[A+1]&&M[A+1]==="="||K==="-"||/[A-Za-z]/.test(M[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(K)||M[A+1]&&M[A+1].match(/\W/))break}return G}function n(O){return $["unknown-options-as-args"]&&CD(O)}function CD(O){if(O=O.replace(/^-{3,}/,"--"),O.match(P))return!1;if(v(O))return!1;return!X1(O,/^-+([^=]+?)=[\s\S]*$/,m,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function p(O){if(!S(O,H.bools)&&!S(O,H.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 G=MD.BOOLEAN;if(S(O,H.strings))G=MD.STRING;else if(S(O,H.numbers))G=MD.NUMBER;else if(S(O,H.bools))G=MD.BOOLEAN;else if(S(O,H.arrays))G=MD.ARRAY;return G}function uD(O){return O===void 0}function wF(){Object.keys(H.counts).find((O)=>{if(S(O,H.arrays))return g=Error(_("Invalid configuration: %s, opts.count excludes opts.array.",O)),!0;else if(S(O,H.nargs))return g=Error(_("Invalid configuration: %s, opts.count excludes opts.narg.",O)),!0;return!1})}return{aliases:Object.assign({},H.aliases),argv:Object.assign(L,V),configuration:$,defaulted:Object.assign({},q),error:g,newAliases:Object.assign({},J)}}}function D8(D){let F=[],B=Object.create(null),E=!0;Object.keys(D).forEach(function(C){F.push([].concat(D[C],C))});while(E){E=!1;for(let C=0;C<F.length;C++)for(let u=C+1;u<F.length;u++)if(F[C].filter(function(X){return F[u].indexOf(X)!==-1}).length){F[C]=F[C].concat(F[u]),F.splice(u,1),E=!0;break}}return F.forEach(function(C){C=C.filter(function($,X,Q){return Q.indexOf($)===X});let u=C.pop();if(u!==void 0&&typeof u==="string")B[u]=C}),B}function dF(D){return D!==void 0?D+1:1}function P1(D){if(D==="__proto__")return"___proto___";return D}function F8(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 u8}from"fs";import{createRequire as S1}from"node:module";var gF,pF,mF,v1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,k1=(pF=(gF=process===null||process===void 0?void 0:process.versions)===null||gF===void 0?void 0:gF.node)!==null&&pF!==void 0?pF:(mF=process===null||process===void 0?void 0:process.version)===null||mF===void 0?void 0:mF.slice(1);if(k1){if(Number(k1.match(/^([^.]+)/)[1])<v1)throw Error(`yargs parser supports a minimum Node.js version of ${v1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var $8=process?process.env:{},f1=S1?S1(import.meta.url):void 0,y1=new hF({cwd:process.cwd,env:()=>{return $8},format:B8,normalize:E8,resolve:C8,require:(D)=>{if(typeof f1!=="undefined")return f1(D);else if(D.match(/\.json$/))return JSON.parse(u8(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),U0=function D(F,B){return y1.parse(F.slice(),B).argv};U0.detailed=function(D,F){return y1.parse(D.slice(),F)};U0.camelCase=cD;U0.decamelize=y0;U0.looksLikeNumber=d0;var lF=U0;import{basename as q8,dirname as M8,extname as _8,relative as K8,resolve as n1,join as V8}from"path";function d1(){if(X8())return 0;return 1}function X8(){return Z8()&&!process.defaultApp}function Z8(){return!!process.versions.electron}function cF(D){return D.slice(d1()+1)}function h1(){return process.argv[d1()]}import{readFileSync as Q8,statSync as z8,writeFile as O8}from"fs";import{format as Y8}from"util";import{resolve as J8}from"path";var g1={fs:{readFileSync:Q8,writeFile:O8},format:Y8,resolve:J8,exists:(D)=>{try{return z8(D).isFile()}catch(F){return!1}}};var LD;class p1{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(),B=function(){};if(typeof D[D.length-1]==="function")B=D.pop();if(B=B||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:B});else B();return LD.format.apply(LD.format,[this.cache[this.locale][F]||F].concat(D))}__n(){let D=Array.prototype.slice.call(arguments),F=D.shift(),B=D.shift(),E=D.shift(),C=function(){};if(typeof D[D.length-1]==="function")C=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let u=E===1?F:B;if(this.cache[this.locale][F])u=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:B},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:C});else C();let $=[u];if(~u.indexOf("%d"))$.push(E);return LD.format.apply(LD.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 B="";return D.forEach(function(E,C){let u=F[C+1];if(B+=E,typeof u!=="undefined")B+="%s"}),this.__.apply(this,[B].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],B=F.directory,E=F.locale,C=F.cb,u=this._resolveLocaleFile(B,E),$=JSON.stringify(this.cache[E],null,2);LD.fs.writeFile(u,$,"utf-8",function(X){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();C(X)})}_readLocaleFile(){let D={},F=this._resolveLocaleFile(this.directory,this.locale);try{if(LD.fs.readFileSync)D=JSON.parse(LD.fs.readFileSync(F,"utf-8"))}catch(B){if(B instanceof SyntaxError)B.message="syntax error in "+F;if(B.code==="ENOENT")D={};else throw B}this.cache[this.locale]=D}_resolveLocaleFile(D,F){let B=LD.resolve(D,"./",F+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(B)&&~F.lastIndexOf("_")){let E=LD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(E))B=E}return B}_fileExistsSync(D){return LD.exists(D)}}function m1(D,F){LD=F;let B=new p1(D);return{__:B.__.bind(B),__n:B.__n.bind(B),setLocale:B.setLocale.bind(B),getLocale:B.getLocale.bind(B),updateLocale:B.updateLocale.bind(B),locale:B.locale}}var W8=(D)=>{return m1(D,g1)},l1=W8;var t1=v0(o1(),1);import{createRequire as R8}from"node:module";import{readFileSync as U8,readdirSync as L8}from"node:fs";var oF=i1(import.meta.url),N8=oF.substring(0,oF.lastIndexOf("node_modules")),j8=R8(import.meta.url),nF={assert:{notStrictEqual:A8,strictEqual:G8},cliui:fF,findUp:yF,getEnv:(D)=>{return process.env[D]},inspect:H8,getProcessArgvBin:h1,mainFilename:N8||process.cwd(),Parser:lF,path:{basename:q8,dirname:M8,extname:_8,relative:K8,resolve:n1,join:V8},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:U8,readdirSync:L8,require:j8,getCallerFile:()=>{let D=t1.default(3);return D.match(/^file:\/\//)?i1(D):D},stringWidth:UD,y18n:l1({directory:n1(oF,"../../../locales"),updateFiles:!1})};function YD(D,F,B,E){B.assert.notStrictEqual(D,F,E)}function iF(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 B=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),E=/\.*[\][<>]/g,C=B.shift();if(!C)throw new Error(`No command found in: ${D}`);let u={cmd:C.replace(E,""),demanded:[],optional:[]};return B.forEach(($,X)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&X===B.length-1)Q=!0;if(/^\[/.test($))u.optional.push({cmd:$.replace(E,"").split("|"),variadic:Q});else u.demanded.push({cmd:$.replace(E,"").split("|"),variadic:Q})}),u}var w8=["first","second","third","fourth","fifth","sixth"];function N(D,F,B){function E(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[kD(`cmd ${D}`),F,B]}try{let C=0,[u,$,X]=E(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=X||Q.length;if(z<u.demanded.length)throw new DD(`Not enough arguments provided. Expected ${u.demanded.length} but received ${Q.length}.`);let Y=u.demanded.length+u.optional.length;if(z>Y)throw new DD(`Too many arguments provided. Expected max ${Y} but received ${z}.`);u.demanded.forEach((W)=>{let J=Q.shift(),q=s1(J);if(W.cmd.filter((H)=>H===q||H==="*").length===0)r1(q,W.cmd,C);C+=1}),u.optional.forEach((W)=>{if(Q.length===0)return;let J=Q.shift(),q=s1(J);if(W.cmd.filter((H)=>H===q||H==="*").length===0)r1(q,W.cmd,C);C+=1})}catch(C){console.warn(C.stack)}}function s1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function r1(D,F,B){throw new DD(`Invalid ${w8[B]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class tF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,B=!0,E=!1){if(N("<array|function> [boolean] [boolean] [boolean]",[D,F,B],arguments.length),Array.isArray(D)){for(let C=0;C<D.length;C++){if(typeof D[C]!=="function")throw Error("middleware must be a function");let u=D[C];u.applyBeforeValidation=F,u.global=B}Array.prototype.push.apply(this.globalMiddleware,D)}else if(typeof D==="function"){let C=D;C.applyBeforeValidation=F,C.global=B,C.mutates=E,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let B=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((E)=>{let C=[...B[F]||[],F];if(!E.option)return!0;else return!C.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 a1(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function oD(D,F,B,E){return B.reduce((C,u)=>{if(u.applyBeforeValidation!==E)return C;if(u.mutates){if(u.applied)return C;u.applied=!0}if(s(C))return C.then(($)=>Promise.all([$,u($,F)])).then(([$,X])=>Object.assign($,X));else{let $=u(C,F);return s($)?$.then((X)=>Object.assign(C,X)):Object.assign(C,$)}},D)}function nD(D,F,B=(E)=>{throw E}){try{let E=I8(D)?D():D;return s(E)?E.then((C)=>F(C)):F(E)}catch(E){return B(E)}}function I8(D){return typeof D==="function"}var O0=/(^\*)|(^\$0)/;class D3{constructor(D,F,B,E){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=E,this.usage=D,this.globalMiddleware=B,this.validation=F}addDirectory(D,F,B,E){E=E||{},this.requireCache.add(B);let C=this.shim.path.resolve(this.shim.path.dirname(B),D),u=this.shim.readdirSync(C,{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 u){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(C,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,B,E,C,u){let $=[],X=a1(C);if(E=E||(()=>{}),Array.isArray(D))if(b8(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(x8(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(e1(B)){this.addHandler([D].concat($),F,B.builder,B.handler,B.middlewares,B.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,$,u);if(this.handlers[Q.cmd]={original:D,description:F,handler:E,builder:B||{},middlewares:X,deprecated:u,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,B,E,C,u){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,B.aliases,Q,E,C,u);return s(Y)?Y.then((W)=>this.applyMiddlewareAndGetResult(z,$,W.innerArgv,X,C,W.aliases,F)):this.applyMiddlewareAndGetResult(z,$,Y.innerArgv,X,C,Y.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,B,E,C,u,$,X){let Q=F.builder,z=B;if(h0(Q)){B.getInternalMethods().getUsageInstance().freeze();let Y=Q(B.getInternalMethods().reset(E),X);if(s(Y))return Y.then((W)=>{return z=B3(W)?W:B,this.parseAndUpdateUsage(D,F,z,C,u,$)})}else if(T8(Q))B.getInternalMethods().getUsageInstance().freeze(),z=B.getInternalMethods().reset(E),Object.keys(F.builder).forEach((Y)=>{z.option(Y,Q[Y])});return this.parseAndUpdateUsage(D,F,z,C,u,$)}parseAndUpdateUsage(D,F,B,E,C,u){if(D)B.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(B))B.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(E,F),F.description);let $=B.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,C,u);return s($)?$.then((X)=>({aliases:B.parsed.aliases,innerArgv:X})):{aliases:B.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let B=O0.test(F.original)?F.original.replace(O0,"").trim():F.original,E=D.filter((C)=>{return!O0.test(C)});return E.push(B),`$0 ${E.join(" ")}`}handleValidationAndGetResult(D,F,B,E,C,u,$,X){if(!u.getInternalMethods().getHasOutput()){let Q=u.getInternalMethods().runValidation(C,X,u.parsed.error,D);B=nD(B,(z)=>{return Q(z),z})}if(F.handler&&!u.getInternalMethods().getHasOutput()){u.getInternalMethods().setHasOutput();let Q=!!u.getOptions().configuration["populate--"];if(u.getInternalMethods().postProcess(B,Q,!1,!1),B=oD(B,u,$,!1),B=nD(B,(z)=>{let Y=F.handler(z);return s(Y)?Y.then(()=>z):z}),!D)u.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(B)&&!u.getInternalMethods().hasParseCallback())B.catch((z)=>{try{u.getInternalMethods().getUsageInstance().fail(null,z)}catch(Y){}})}if(!D)E.commands.pop(),E.fullCommands.pop();return B}applyMiddlewareAndGetResult(D,F,B,E,C,u,$){let X={};if(C)return B;if(!$.getInternalMethods().getHasOutput())X=this.populatePositionals(F,B,E,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=oD(B,$,Q,!0);return s(z)?z.then((Y)=>this.handleValidationAndGetResult(D,F,Y,E,u,$,Q,X)):this.handleValidationAndGetResult(D,F,z,E,u,$,Q,X)}populatePositionals(D,F,B,E){F._=F._.slice(B.commands.length);let C=D.demanded.slice(0),u=D.optional.slice(0),$={};this.validation.positionalCount(C.length,F._.length);while(C.length){let X=C.shift();this.populatePositional(X,F,$)}while(u.length){let X=u.shift();this.populatePositional(X,F,$)}return F._=B.commands.concat(F._.map((X)=>""+X)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),E),$}populatePositional(D,F,B){let E=D.cmd[0];if(D.variadic)B[E]=F._.splice(0).map(String);else if(F._.length)B[E]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},B=kD(D);return B.demanded.forEach((E)=>{let[C,...u]=E.cmd;if(E.variadic)F.array.push(C),F.default[C]=[];F.alias[C]=u,F.demand[C]=!0}),B.optional.forEach((E)=>{let[C,...u]=E.cmd;if(E.variadic)F.array.push(C),F.default[C]=[];F.alias[C]=u}),F}postProcessPositionals(D,F,B,E){let C=Object.assign({},E.getOptions());C.default=Object.assign(B.default,C.default);for(let Q of Object.keys(B.alias))C.alias[Q]=(C.alias[Q]||[]).concat(B.alias[Q]);C.array=C.array.concat(B.array),C.config={};let u=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(C.configuration["unknown-options-as-args"])C.key[Q]=!0;u.push(`--${Q}`),u.push(z)})}),!u.length)return;let $=Object.assign({},C.configuration,{"populate--":!1}),X=this.shim.Parser.detailed(u,Object.assign({},C,{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:B}=D.getOptions();return Object.prototype.hasOwnProperty.call(B,F)||Object.prototype.hasOwnProperty.call(B,this.shim.Parser.camelCase(F))}isInConfigs(D,F){let{configObjects:B}=D.getOptions();return B.some((E)=>Object.prototype.hasOwnProperty.call(E,F))||B.some((E)=>Object.prototype.hasOwnProperty.call(E,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let B=O0.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");D.getInternalMethods().getUsageInstance().usage(B,this.defaultCommand.description)}let F=this.defaultCommand.builder;if(h0(F))return F(D,!0);else if(!e1(F))Object.keys(F).forEach((B)=>{D.option(B,F[B])});return}extractDesc({describe:D,description:F,desc:B}){for(let E of[D,F,B]){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 F3(D,F,B,E){return new D3(D,F,B,E)}function e1(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function b8(D){return D.every((F)=>typeof F==="string")}function h0(D){return typeof D==="function"}function T8(D){return typeof D==="object"}function x8(D){return typeof D==="object"&&!Array.isArray(D)}function fD(D={},F=()=>!0){let B={};return z0(D).forEach((E)=>{if(F(E,D[E]))B[E]=D[E]}),B}function yD(D){if(typeof process==="undefined")return;[process.stdout,process.stderr].forEach((F)=>{let B=F;if(B._handle&&B.isTTY&&typeof B._handle.setBlocking==="function")B._handle.setBlocking(D)})}function P8(D){return typeof D==="boolean"}function C3(D,F){let B=F.y18n.__,E={},C=[];E.failFn=function w(R){C.push(R)};let u=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 u=o,X=y,E};let Q=!1;E.fail=function w(R,b){let y=D.getInternalMethods().getLoggerInstance();if(C.length)for(let o=C.length-1;o>=0;--o){let BD=C[o];if(P8(BD)){if(b)throw b;else if(R)throw Error(R)}else BD(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=u||$;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 B("Positionals:")};let W=[];E.example=(w,R)=>{W.push([w,R||""])};let J=[];E.command=function w(R,b,y,o,BD=!1){if(y)J=J.map((c)=>{return c[2]=!1,c});J.push([R,b||"",y,o,BD])},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 _=[];E.epilog=(w)=>{_.push(w)};let H=!1,P;E.wrap=(w)=>{H=!0,P=w},E.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!H)P=t(),H=!0;return P};let m="__yargsString__:";E.deferY18nLookup=(w)=>m+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(),BD=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} <${B("command")}>
24
+ `).map((E)=>F8(E,F,B)).join(`
25
+ `)}function fF(D){return G1(D,{stringWidth:UD,stripAnsi:lD,wrap:kF})}import{dirname as x1,resolve as P1}from"path";import{readdirSync as B8,statSync as E8}from"fs";function yF(D,F){let B=P1(".",D),E;if(!E8(B).isDirectory())B=x1(B);while(!0){if(E=F(B,B8(B)),E)return P1(B,E);if(B=x1(E=B),E===B)break}}import{inspect as K8}from"util";import{fileURLToPath as s1}from"url";import{format as $8}from"util";import{normalize as X8,resolve as Z8}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 B="",E=!1,C=D.match(/^-+/);for(let u=C?C[0].length:0;u<D.length;u++){let $=D.charAt(u);if(E)E=!1,$=$.toUpperCase();if(u!==0&&($==="-"||$==="_"))E=!0;else if($!=="-"&&$!=="_")B+=$}return B}}function d0(D,F){let B=D.toLowerCase();F=F||"-";let E="";for(let C=0;C<D.length;C++){let u=B.charAt(C),$=D.charAt(C);if(u!==$&&C>0)E+=`${F}${B.charAt(C)}`;else E+=$}return E}function h0(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 S1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,B=null,E=null,C=null,u=[];for(let $=0;$<D.length;$++){if(B=E,E=D.charAt($),E===" "&&!C){if(B!==" ")F++;continue}if(E===C)C=null;else if((E==="'"||E==='"')&&!C)C=E;if(!u[F])u[F]="";u[F]+=E}return u}var MD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(MD||(MD={}));var bD;class hF{constructor(D){bD=D}parse(D,F){let B=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=S1(D),C=typeof D==="string",u=C8(Object.assign(Object.create(null),B.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},B.configuration),X=Object.assign(Object.create(null),B.default),Q=B.configObjects||[],z=B.envPrefix,Y=$["populate--"],W=Y?"--":"_",J=Object.create(null),q=Object.create(null),M=B.__||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:[]},I=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,g=new RegExp("^--"+$["negation-prefix"]+"(.+)");if([].concat(B.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(B.boolean||[]).filter(Boolean).forEach(function(O){G.bools[O]=!0,G.keys.push(O)}),[].concat(B.string||[]).filter(Boolean).forEach(function(O){G.strings[O]=!0,G.keys.push(O)}),[].concat(B.number||[]).filter(Boolean).forEach(function(O){G.numbers[O]=!0,G.keys.push(O)}),[].concat(B.count||[]).filter(Boolean).forEach(function(O){G.counts[O]=!0,G.keys.push(O)}),[].concat(B.normalize||[]).filter(Boolean).forEach(function(O){G.normalize[O]=!0,G.keys.push(O)}),typeof B.narg==="object")Object.entries(B.narg).forEach(([O,H])=>{if(typeof H==="number")G.nargs[O]=H,G.keys.push(O)});if(typeof B.coerce==="object")Object.entries(B.coerce).forEach(([O,H])=>{if(typeof H==="function")G.coercions[O]=H,G.keys.push(O)});if(typeof B.config!=="undefined"){if(Array.isArray(B.config)||typeof B.config==="string")[].concat(B.config).filter(Boolean).forEach(function(O){G.configs[O]=!0});else if(typeof B.config==="object")Object.entries(B.config).forEach(([O,H])=>{if(typeof H==="boolean"||typeof H==="function")G.configs[O]=H})}R0(B.key,u,B.default,G.arrays),Object.keys(X).forEach(function(O){(G.aliases[O]||[]).forEach(function(H){X[H]=X[O]})});let p=null;wF();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,T,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(g)&&$["boolean-negation"]){if(U=H.match(g),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(I))&&!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(I)){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(I)){T=H.slice(1,-1).split(""),_=!1;for(let OD=0;OD<T.length;OD++){if(P=H.slice(OD+2),T[OD+1]&&T[OD+1]==="="){if(XD=H.slice(OD+3),A=T[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(T[OD],P);continue}if(/[A-Za-z]/.test(T[OD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)&&S(P,G.bools)===!1){l(T[OD],P),_=!0;break}if(T[OD+1]&&T[OD+1].match(/\W/)){l(T[OD],P),_=!0;break}else l(T[OD],m(T[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(I))&&!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(I)&&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(BD(V,!0),BD(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(u).map((O)=>u[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,T=S(H,G.nargs);if(T=typeof T!=="number"||isNaN(T)?1:T,T===0){if(!uD(_))p=Error(M("Argument unexpected for: %s",H));return l(H,m(H)),O}let U=uD(_)?0:1;if($["nargs-eats-options"]){if(K.length-(O+1)+U<T)p=Error(M("Not enough arguments following: %s",H));U=T}else{for(A=O+1;A<K.length;A++)if(!K[A].match(/^-[^0-9]/)||K[A].match(I)||n(K[A]))U++;else break;if(U<T)p=Error(M("Not enough arguments following: %s",H))}let P=Math.min(U,T);if(!uD(_)&&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=[],T=_||K[O+1],U=S(H,G.nargs);if(S(H,G.bools)&&!/^(true|false)$/.test(T))A.push(!0);else if(uD(T)||uD(_)&&/^-/.test(T)&&!I.test(T)&&!n(T)){if(X[H]!==void 0){let P=X[H];A=Array.isArray(P)?P:[P]}}else{if(!uD(_))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(T=K[P],/^-/.test(T)&&!I.test(T)&&!n(T))break;O=P,A.push(w(H,T,C))}}if(typeof U==="number"&&(U&&A.length<U||isNaN(U)&&A.length===0))p=Error(M("Not enough arguments following: %s",H));return l(H,A),O}function l(O,H,K=C){if(/-/.test(O)&&$["camel-case-expansion"]){let T=O.split(".").map(function(U){return cD(U)}).join(".");jD(O,T)}let _=w(O,H,K),A=O.split(".");if(TD(V,A,_),G.aliases[O])G.aliases[O].forEach(function(T){let U=T.split(".");TD(V,U,_)});if(A.length>1&&$["dot-notation"])(G.aliases[A[0]]||[]).forEach(function(T){let U=T.split("."),P=[].concat(A);if(P.shift(),U=U.concat(P),!(G.aliases[O]||[]).includes(U.join(".")))TD(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=u8(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)&&(uD(_)||typeof _==="boolean"))_=dF();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(h0(H)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${H}`)))||!uD(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,T=bD.resolve(bD.cwd(),_),U=G.configs[K];if(typeof U==="function"){try{A=U(T)}catch(P){A=P}if(A instanceof Error){p=A;return}}else A=bD.require(T);y(A)}catch(A){if(A.name==="PermissionDenied")p=A;else if(O[K])p=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 BD(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 T=A.split("__").map(function(U,P){if(P===0)U=U.substring(K.length);return cD(U)});if((H&&G.configs[T.join(".")]||!H)&&!i(O,T))l(T.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((T)=>{K.add(T),O[T]=A})}catch(A){p=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(TD(O,A.split("."),K[A]),_)q[A]=!0;(H[A]||[]).forEach(function(T){if(i(O,T.split(".")))return;TD(O,T.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 TD(O,H,K){let _=O;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(XD){if(XD=v1(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=v1(H[H.length-1]),T=S(H.join("."),G.arrays),U=Array.isArray(K),P=$["duplicate-arguments-array"];if(!P&&S(A,G.nargs)){if(P=!0,!uD(_[A])&&G.nargs[A]===1||Array.isArray(_[A])&&_[A].length===G.nargs[A])_[A]=void 0}if(K===dF())_[A]=dF(_[A]);else if(Array.isArray(_[A]))if(P&&T&&U)_[A]=$["flatten-duplicate-arrays"]?_[A].concat(K):(Array.isArray(_[A][0])?_[A]:[_[A]]).concat([K]);else if(!P&&Boolean(T)===Boolean(U))_[A]=K;else _[A]=_[A].concat([K]);else if(_[A]===void 0&&T)_[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 R0(...O){O.forEach(function(H){Object.keys(H||{}).forEach(function(K){if(G.aliases[K])return;G.aliases[K]=[].concat(u[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=d0(_,"-");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((T)=>_.includes(T));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 Q1(O,...H){return[].concat(...H).some(function(_){let A=O.match(_);return A&&Q0(A[1])})}function v(O){if(O.match(I)||!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"]&&CD(O)}function CD(O){if(O=O.replace(/^-{3,}/,"--"),O.match(I))return!1;if(v(O))return!1;return!Q1(O,/^-+([^=]+?)=[\s\S]*$/,g,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\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 uD(O){return O===void 0}function wF(){Object.keys(G.counts).find((O)=>{if(S(O,G.arrays))return p=Error(M("Invalid configuration: %s, opts.count excludes opts.array.",O)),!0;else if(S(O,G.nargs))return p=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:p,newAliases:Object.assign({},J)}}}function C8(D){let F=[],B=Object.create(null),E=!0;Object.keys(D).forEach(function(C){F.push([].concat(D[C],C))});while(E){E=!1;for(let C=0;C<F.length;C++)for(let u=C+1;u<F.length;u++)if(F[C].filter(function(X){return F[u].indexOf(X)!==-1}).length){F[C]=F[C].concat(F[u]),F.splice(u,1),E=!0;break}}return F.forEach(function(C){C=C.filter(function($,X,Q){return Q.indexOf($)===X});let u=C.pop();if(u!==void 0&&typeof u==="string")B[u]=C}),B}function dF(D){return D!==void 0?D+1:1}function v1(D){if(D==="__proto__")return"___proto___";return D}function u8(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 Q8}from"fs";import{createRequire as k1}from"node:module";var gF,pF,mF,f1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,y1=(pF=(gF=process===null||process===void 0?void 0:process.versions)===null||gF===void 0?void 0:gF.node)!==null&&pF!==void 0?pF:(mF=process===null||process===void 0?void 0:process.version)===null||mF===void 0?void 0:mF.slice(1);if(y1){if(Number(y1.match(/^([^.]+)/)[1])<f1)throw Error(`yargs parser supports a minimum Node.js version of ${f1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var z8=process?process.env:{},d1=k1?k1(import.meta.url):void 0,h1=new hF({cwd:process.cwd,env:()=>{return z8},format:$8,normalize:X8,resolve:Z8,require:(D)=>{if(typeof d1!=="undefined")return d1(D);else if(D.match(/\.json$/))return JSON.parse(Q8(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),L0=function D(F,B){return h1.parse(F.slice(),B).argv};L0.detailed=function(D,F){return h1.parse(D.slice(),F)};L0.camelCase=cD;L0.decamelize=d0;L0.looksLikeNumber=h0;var lF=L0;import{basename as V8,dirname as R8,extname as U8,relative as L8,resolve as t1,join as N8}from"path";function g1(){if(O8())return 0;return 1}function O8(){return Y8()&&!process.defaultApp}function Y8(){return!!process.versions.electron}function cF(D){return D.slice(g1()+1)}function p1(){return process.argv[g1()]}import{readFileSync as J8,statSync as W8,writeFile as A8}from"fs";import{format as G8}from"util";import{resolve as H8}from"path";var m1={fs:{readFileSync:J8,writeFile:A8},format:G8,resolve:H8,exists:(D)=>{try{return W8(D).isFile()}catch(F){return!1}}};var LD;class l1{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(),B=function(){};if(typeof D[D.length-1]==="function")B=D.pop();if(B=B||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:B});else B();return LD.format.apply(LD.format,[this.cache[this.locale][F]||F].concat(D))}__n(){let D=Array.prototype.slice.call(arguments),F=D.shift(),B=D.shift(),E=D.shift(),C=function(){};if(typeof D[D.length-1]==="function")C=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let u=E===1?F:B;if(this.cache[this.locale][F])u=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:B},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:C});else C();let $=[u];if(~u.indexOf("%d"))$.push(E);return LD.format.apply(LD.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 B="";return D.forEach(function(E,C){let u=F[C+1];if(B+=E,typeof u!=="undefined")B+="%s"}),this.__.apply(this,[B].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],B=F.directory,E=F.locale,C=F.cb,u=this._resolveLocaleFile(B,E),$=JSON.stringify(this.cache[E],null,2);LD.fs.writeFile(u,$,"utf-8",function(X){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();C(X)})}_readLocaleFile(){let D={},F=this._resolveLocaleFile(this.directory,this.locale);try{if(LD.fs.readFileSync)D=JSON.parse(LD.fs.readFileSync(F,"utf-8"))}catch(B){if(B instanceof SyntaxError)B.message="syntax error in "+F;if(B.code==="ENOENT")D={};else throw B}this.cache[this.locale]=D}_resolveLocaleFile(D,F){let B=LD.resolve(D,"./",F+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(B)&&~F.lastIndexOf("_")){let E=LD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(E))B=E}return B}_fileExistsSync(D){return LD.exists(D)}}function c1(D,F){LD=F;let B=new l1(D);return{__:B.__.bind(B),__n:B.__n.bind(B),setLocale:B.setLocale.bind(B),getLocale:B.getLocale.bind(B),updateLocale:B.updateLocale.bind(B),locale:B.locale}}var q8=(D)=>{return c1(D,m1)},o1=q8;var r1=k0(i1(),1);import{createRequire as j8}from"node:module";import{readFileSync as w8,readdirSync as I8}from"node:fs";var oF=s1(import.meta.url),T8=oF.substring(0,oF.lastIndexOf("node_modules")),b8=j8(import.meta.url),nF={assert:{notStrictEqual:M8,strictEqual:_8},cliui:fF,findUp:yF,getEnv:(D)=>{return process.env[D]},inspect:K8,getProcessArgvBin:p1,mainFilename:T8||process.cwd(),Parser:lF,path:{basename:V8,dirname:R8,extname:U8,relative:L8,resolve:t1,join:N8},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:w8,readdirSync:I8,require:b8,getCallerFile:()=>{let D=r1.default(3);return D.match(/^file:\/\//)?s1(D):D},stringWidth:UD,y18n:o1({directory:t1(oF,"../../../locales"),updateFiles:!1})};function YD(D,F,B,E){B.assert.notStrictEqual(D,F,E)}function iF(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 B=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),E=/\.*[\][<>]/g,C=B.shift();if(!C)throw new Error(`No command found in: ${D}`);let u={cmd:C.replace(E,""),demanded:[],optional:[]};return B.forEach(($,X)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&X===B.length-1)Q=!0;if(/^\[/.test($))u.optional.push({cmd:$.replace(E,"").split("|"),variadic:Q});else u.demanded.push({cmd:$.replace(E,"").split("|"),variadic:Q})}),u}var x8=["first","second","third","fourth","fifth","sixth"];function N(D,F,B){function E(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[kD(`cmd ${D}`),F,B]}try{let C=0,[u,$,X]=E(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=X||Q.length;if(z<u.demanded.length)throw new DD(`Not enough arguments provided. Expected ${u.demanded.length} but received ${Q.length}.`);let Y=u.demanded.length+u.optional.length;if(z>Y)throw new DD(`Too many arguments provided. Expected max ${Y} but received ${z}.`);u.demanded.forEach((W)=>{let J=Q.shift(),q=a1(J);if(W.cmd.filter((G)=>G===q||G==="*").length===0)e1(q,W.cmd,C);C+=1}),u.optional.forEach((W)=>{if(Q.length===0)return;let J=Q.shift(),q=a1(J);if(W.cmd.filter((G)=>G===q||G==="*").length===0)e1(q,W.cmd,C);C+=1})}catch(C){console.warn(C.stack)}}function a1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function e1(D,F,B){throw new DD(`Invalid ${x8[B]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class tF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,B=!0,E=!1){if(N("<array|function> [boolean] [boolean] [boolean]",[D,F,B],arguments.length),Array.isArray(D)){for(let C=0;C<D.length;C++){if(typeof D[C]!=="function")throw Error("middleware must be a function");let u=D[C];u.applyBeforeValidation=F,u.global=B}Array.prototype.push.apply(this.globalMiddleware,D)}else if(typeof D==="function"){let C=D;C.applyBeforeValidation=F,C.global=B,C.mutates=E,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let B=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((E)=>{let C=[...B[F]||[],F];if(!E.option)return!0;else return!C.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 D3(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function oD(D,F,B,E){return B.reduce((C,u)=>{if(u.applyBeforeValidation!==E)return C;if(u.mutates){if(u.applied)return C;u.applied=!0}if(s(C))return C.then(($)=>Promise.all([$,u($,F)])).then(([$,X])=>Object.assign($,X));else{let $=u(C,F);return s($)?$.then((X)=>Object.assign(C,X)):Object.assign(C,$)}},D)}function nD(D,F,B=(E)=>{throw E}){try{let E=P8(D)?D():D;return s(E)?E.then((C)=>F(C)):F(E)}catch(E){return B(E)}}function P8(D){return typeof D==="function"}var O0=/(^\*)|(^\$0)/;class B3{constructor(D,F,B,E){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=E,this.usage=D,this.globalMiddleware=B,this.validation=F}addDirectory(D,F,B,E){E=E||{},this.requireCache.add(B);let C=this.shim.path.resolve(this.shim.path.dirname(B),D),u=this.shim.readdirSync(C,{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 u){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(C,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,B,E,C,u){let $=[],X=D3(C);if(E=E||(()=>{}),Array.isArray(D))if(S8(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(k8(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(F3(B)){this.addHandler([D].concat($),F,B.builder,B.handler,B.middlewares,B.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,$,u);if(this.handlers[Q.cmd]={original:D,description:F,handler:E,builder:B||{},middlewares:X,deprecated:u,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,B,E,C,u){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,B.aliases,Q,E,C,u);return s(Y)?Y.then((W)=>this.applyMiddlewareAndGetResult(z,$,W.innerArgv,X,C,W.aliases,F)):this.applyMiddlewareAndGetResult(z,$,Y.innerArgv,X,C,Y.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,B,E,C,u,$,X){let Q=F.builder,z=B;if(g0(Q)){B.getInternalMethods().getUsageInstance().freeze();let Y=Q(B.getInternalMethods().reset(E),X);if(s(Y))return Y.then((W)=>{return z=C3(W)?W:B,this.parseAndUpdateUsage(D,F,z,C,u,$)})}else if(v8(Q))B.getInternalMethods().getUsageInstance().freeze(),z=B.getInternalMethods().reset(E),Object.keys(F.builder).forEach((Y)=>{z.option(Y,Q[Y])});return this.parseAndUpdateUsage(D,F,z,C,u,$)}parseAndUpdateUsage(D,F,B,E,C,u){if(D)B.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(B))B.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(E,F),F.description);let $=B.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,C,u);return s($)?$.then((X)=>({aliases:B.parsed.aliases,innerArgv:X})):{aliases:B.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let B=O0.test(F.original)?F.original.replace(O0,"").trim():F.original,E=D.filter((C)=>{return!O0.test(C)});return E.push(B),`$0 ${E.join(" ")}`}handleValidationAndGetResult(D,F,B,E,C,u,$,X){if(!u.getInternalMethods().getHasOutput()){let Q=u.getInternalMethods().runValidation(C,X,u.parsed.error,D);B=nD(B,(z)=>{return Q(z),z})}if(F.handler&&!u.getInternalMethods().getHasOutput()){u.getInternalMethods().setHasOutput();let Q=!!u.getOptions().configuration["populate--"];if(u.getInternalMethods().postProcess(B,Q,!1,!1),B=oD(B,u,$,!1),B=nD(B,(z)=>{let Y=F.handler(z);return s(Y)?Y.then(()=>z):z}),!D)u.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(B)&&!u.getInternalMethods().hasParseCallback())B.catch((z)=>{try{u.getInternalMethods().getUsageInstance().fail(null,z)}catch(Y){}})}if(!D)E.commands.pop(),E.fullCommands.pop();return B}applyMiddlewareAndGetResult(D,F,B,E,C,u,$){let X={};if(C)return B;if(!$.getInternalMethods().getHasOutput())X=this.populatePositionals(F,B,E,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=oD(B,$,Q,!0);return s(z)?z.then((Y)=>this.handleValidationAndGetResult(D,F,Y,E,u,$,Q,X)):this.handleValidationAndGetResult(D,F,z,E,u,$,Q,X)}populatePositionals(D,F,B,E){F._=F._.slice(B.commands.length);let C=D.demanded.slice(0),u=D.optional.slice(0),$={};this.validation.positionalCount(C.length,F._.length);while(C.length){let X=C.shift();this.populatePositional(X,F,$)}while(u.length){let X=u.shift();this.populatePositional(X,F,$)}return F._=B.commands.concat(F._.map((X)=>""+X)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),E),$}populatePositional(D,F,B){let E=D.cmd[0];if(D.variadic)B[E]=F._.splice(0).map(String);else if(F._.length)B[E]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},B=kD(D);return B.demanded.forEach((E)=>{let[C,...u]=E.cmd;if(E.variadic)F.array.push(C),F.default[C]=[];F.alias[C]=u,F.demand[C]=!0}),B.optional.forEach((E)=>{let[C,...u]=E.cmd;if(E.variadic)F.array.push(C),F.default[C]=[];F.alias[C]=u}),F}postProcessPositionals(D,F,B,E){let C=Object.assign({},E.getOptions());C.default=Object.assign(B.default,C.default);for(let Q of Object.keys(B.alias))C.alias[Q]=(C.alias[Q]||[]).concat(B.alias[Q]);C.array=C.array.concat(B.array),C.config={};let u=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(C.configuration["unknown-options-as-args"])C.key[Q]=!0;u.push(`--${Q}`),u.push(z)})}),!u.length)return;let $=Object.assign({},C.configuration,{"populate--":!1}),X=this.shim.Parser.detailed(u,Object.assign({},C,{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:B}=D.getOptions();return Object.prototype.hasOwnProperty.call(B,F)||Object.prototype.hasOwnProperty.call(B,this.shim.Parser.camelCase(F))}isInConfigs(D,F){let{configObjects:B}=D.getOptions();return B.some((E)=>Object.prototype.hasOwnProperty.call(E,F))||B.some((E)=>Object.prototype.hasOwnProperty.call(E,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let B=O0.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");D.getInternalMethods().getUsageInstance().usage(B,this.defaultCommand.description)}let F=this.defaultCommand.builder;if(g0(F))return F(D,!0);else if(!F3(F))Object.keys(F).forEach((B)=>{D.option(B,F[B])});return}extractDesc({describe:D,description:F,desc:B}){for(let E of[D,F,B]){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 E3(D,F,B,E){return new B3(D,F,B,E)}function F3(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function S8(D){return D.every((F)=>typeof F==="string")}function g0(D){return typeof D==="function"}function v8(D){return typeof D==="object"}function k8(D){return typeof D==="object"&&!Array.isArray(D)}function fD(D={},F=()=>!0){let B={};return z0(D).forEach((E)=>{if(F(E,D[E]))B[E]=D[E]}),B}function yD(D){if(typeof process==="undefined")return;[process.stdout,process.stderr].forEach((F)=>{let B=F;if(B._handle&&B.isTTY&&typeof B._handle.setBlocking==="function")B._handle.setBlocking(D)})}function f8(D){return typeof D==="boolean"}function $3(D,F){let B=F.y18n.__,E={},C=[];E.failFn=function w(R){C.push(R)};let u=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 u=o,X=y,E};let Q=!1;E.fail=function w(R,b){let y=D.getInternalMethods().getLoggerInstance();if(C.length)for(let o=C.length-1;o>=0;--o){let BD=C[o];if(f8(BD)){if(b)throw b;else if(R)throw Error(R)}else BD(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=u||$;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 B("Positionals:")};let W=[];E.example=(w,R)=>{W.push([w,R||""])};let J=[];E.command=function w(R,b,y,o,BD=!1){if(y)J=J.map((c)=>{return c[2]=!1,c});J.push([R,b||"",y,o,BD])},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,I;E.wrap=(w)=>{G=!0,I=w},E.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!G)I=t(),G=!0;return I};let g="__yargsString__:";E.deferY18nLookup=(w)=>g+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(),BD=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} <${B("command")}>
26
26
  `;else v=`${R} [${B("command")}]
27
- `;i.div(`${v}`)}}if(J.length>1||J.length===1&&!J[0][2]){i.div(B("Commands:"));let v=D.getInternalMethods().getContext(),n=v.commands.length?`${v.commands.join(" ")} `:"";if(D.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)J=J.sort((p,zD)=>p[0].localeCompare(zD[0]));let CD=R?`${R} `:"";J.forEach((p)=>{let zD=`${CD}${n}${p[0].replace(/^\$0 ?/,"")}`;i.span({text:zD,padding:[0,2,0,2],width:g(J,vD,`${R}${n}`)+4},{text:p[1]});let e=[];if(p[2])e.push(`[${B("default")}]`);if(p[3]&&p[3].length)e.push(`[${B("aliases:")} ${p[3].join(", ")}]`);if(p[4])if(typeof p[4]==="string")e.push(`[${B("deprecated: %s",p[4])}]`);else e.push(`[${B("deprecated")}]`);if(e.length)i.div({text:e.join(" "),padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}let bD=(Object.keys(c.alias)||[]).concat(Object.keys(D.parsed.newAliases)||[]);ED=ED.filter((v)=>!D.parsed.newAliases[v]&&bD.every((n)=>(c.alias[n]||[]).indexOf(v)===-1));let V0=B("Options:");if(!BD[V0])BD[V0]=[];L(ED,c.alias,BD,V0);let S=(v)=>/^--/.test(g0(v)),Q0=Object.keys(BD).filter((v)=>BD[v].length>0).map((v)=>{let n=BD[v].filter(k).map((CD)=>{if(bD.includes(CD))return CD;for(let p=0,zD;(zD=bD[p])!==void 0;p++)if((c.alias[zD]||[]).includes(CD))return zD;return CD});return{groupName:v,normalizedKeys:n}}).filter(({normalizedKeys:v})=>v.length>0).map(({groupName:v,normalizedKeys:n})=>{let CD=n.reduce((p,zD)=>{return p[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,uD)=>S(e)===S(uD)?0:S(e)?1:-1).join(", "),p},{});return{groupName:v,normalizedKeys:n,switches:CD}});if(Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).some(({normalizedKeys:v,switches:n})=>!v.every((CD)=>S(n[CD]))))Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).forEach(({normalizedKeys:v,switches:n})=>{v.forEach((CD)=>{if(S(n[CD]))n[CD]=S8(n[CD],4)})});if(Q0.forEach(({groupName:v,normalizedKeys:n,switches:CD})=>{i.div(v),n.forEach((p)=>{let zD=CD[p],e=q[p]||"",uD=null;if(e.includes(m))e=B(e.substring(m.length));if(c.boolean.includes(p))uD=`[${B("boolean")}]`;if(c.count.includes(p))uD=`[${B("count")}]`;if(c.string.includes(p))uD=`[${B("string")}]`;if(c.normalize.includes(p))uD=`[${B("string")}]`;if(c.array.includes(p))uD=`[${B("array")}]`;if(c.number.includes(p))uD=`[${B("number")}]`;let wF=(K)=>typeof K==="string"?`[${B("deprecated: %s",K)}]`:`[${B("deprecated")}]`,O=[p in o?wF(o[p]):null,uD,p in b?`[${B("required")}]`:null,c.choices&&c.choices[p]?`[${B("choices:")} ${E.stringifiedValues(c.choices[p])}]`:null,d(c.default[p],c.defaultDescription[p])].filter(Boolean).join(" ");i.span({text:g0(zD),padding:[0,2,0,2+E3(zD)],width:g(CD,vD)+4},e);let G=D.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(O&&!G)i.div({text:O,padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}),W.length)i.div(B("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(_.length>0){let v=_.map((n)=>n.replace(/\$0/g,R)).join(`
27
+ `;i.div(`${v}`)}}if(J.length>1||J.length===1&&!J[0][2]){i.div(B("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 CD=R?`${R} `:"";J.forEach((m)=>{let zD=`${CD}${n}${m[0].replace(/^\$0 ?/,"")}`;i.span({text:zD,padding:[0,2,0,2],width:p(J,vD,`${R}${n}`)+4},{text:m[1]});let e=[];if(m[2])e.push(`[${B("default")}]`);if(m[3]&&m[3].length)e.push(`[${B("aliases:")} ${m[3].join(", ")}]`);if(m[4])if(typeof m[4]==="string")e.push(`[${B("deprecated: %s",m[4])}]`);else e.push(`[${B("deprecated")}]`);if(e.length)i.div({text:e.join(" "),padding:[0,0,0,2],align:"right"});else i.div()}),i.div()}let TD=(Object.keys(c.alias)||[]).concat(Object.keys(D.parsed.newAliases)||[]);ED=ED.filter((v)=>!D.parsed.newAliases[v]&&TD.every((n)=>(c.alias[n]||[]).indexOf(v)===-1));let R0=B("Options:");if(!BD[R0])BD[R0]=[];L(ED,c.alias,BD,R0);let S=(v)=>/^--/.test(p0(v)),Q0=Object.keys(BD).filter((v)=>BD[v].length>0).map((v)=>{let n=BD[v].filter(k).map((CD)=>{if(TD.includes(CD))return CD;for(let m=0,zD;(zD=TD[m])!==void 0;m++)if((c.alias[zD]||[]).includes(CD))return zD;return CD});return{groupName:v,normalizedKeys:n}}).filter(({normalizedKeys:v})=>v.length>0).map(({groupName:v,normalizedKeys:n})=>{let CD=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,uD)=>S(e)===S(uD)?0:S(e)?1:-1).join(", "),m},{});return{groupName:v,normalizedKeys:n,switches:CD}});if(Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).some(({normalizedKeys:v,switches:n})=>!v.every((CD)=>S(n[CD]))))Q0.filter(({groupName:v})=>v!==E.getPositionalGroupName()).forEach(({normalizedKeys:v,switches:n})=>{v.forEach((CD)=>{if(S(n[CD]))n[CD]=y8(n[CD],4)})});if(Q0.forEach(({groupName:v,normalizedKeys:n,switches:CD})=>{i.div(v),n.forEach((m)=>{let zD=CD[m],e=q[m]||"",uD=null;if(e.includes(g))e=B(e.substring(g.length));if(c.boolean.includes(m))uD=`[${B("boolean")}]`;if(c.count.includes(m))uD=`[${B("count")}]`;if(c.string.includes(m))uD=`[${B("string")}]`;if(c.normalize.includes(m))uD=`[${B("string")}]`;if(c.array.includes(m))uD=`[${B("array")}]`;if(c.number.includes(m))uD=`[${B("number")}]`;let wF=(K)=>typeof K==="string"?`[${B("deprecated: %s",K)}]`:`[${B("deprecated")}]`,O=[m in o?wF(o[m]):null,uD,m in b?`[${B("required")}]`:null,c.choices&&c.choices[m]?`[${B("choices:")} ${E.stringifiedValues(c.choices[m])}]`:null,d(c.default[m],c.defaultDescription[m])].filter(Boolean).join(" ");i.span({text:p0(zD),padding:[0,2,0,2+u3(zD)],width:p(CD,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(B("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:p(W,vD)+4},{text:v[1]})}),i.div();if(M.length>0){let v=M.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} ${g0(o[0])}`:g0(o[0]))+E3(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=[],BD=null;return Object.keys(b).forEach((c)=>{o=o.concat(b[c])}),w.forEach((c)=>{if(BD=[c].concat(R[c]),!BD.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,"-"):B("generated-value"),")"].join("")},E.stringifiedValues=function w(R,b){let y="",o=b||", ",BD=[].concat(R);if(!R||!BD.length)return y;return BD.forEach((c)=>{if(y.length)y+=o;y+=JSON.stringify(c)}),y};function d(w,R){let b=`[${B("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 u=null,Q=!1,z=[],Y=!1,_=[],W=[],J=[],q=fD(q,(b)=>!R[b]),E};let jD=[];return E.freeze=function w(){jD.push({failMessage:u,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:_,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],_=[...b.epilogs,..._];else({failMessage:u,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:_,examples:W,commands:J,descriptions:q}=b)},E}function sF(D){return typeof D==="object"}function S8(D,F){return sF(D)?{text:D.text,indentation:D.indentation+F}:{text:D,indentation:F}}function E3(D){return sF(D)?D.indentation:0}function g0(D){return sF(D)?D.text:D}var u3=`###-begin-{{app_name}}-completions-###
29
+ `)}return i.toString().replace(/\s*$/,"")};function p(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} ${p0(o[0])}`:p0(o[0]))+u3(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=[],BD=null;return Object.keys(b).forEach((c)=>{o=o.concat(b[c])}),w.forEach((c)=>{if(BD=[c].concat(R[c]),!BD.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,"-"):B("generated-value"),")"].join("")},E.stringifiedValues=function w(R,b){let y="",o=b||", ",BD=[].concat(R);if(!R||!BD.length)return y;return BD.forEach((c)=>{if(y.length)y+=o;y+=JSON.stringify(c)}),y};function d(w,R){let b=`[${B("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 u=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:u,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:u,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:M,examples:W,commands:J,descriptions:q}=b)},E}function sF(D){return typeof D==="object"}function y8(D,F){return sF(D)?{text:D.text,indentation:D.indentation+F}:{text:D,indentation:F}}function u3(D){return sF(D)?D.indentation:0}function p0(D){return sF(D)?D.text:D}var X3=`###-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
- `,$3=`#compdef {{app_name}}
58
+ `,Z3=`#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 X3{constructor(D,F,B,E){var C,u,$;this.yargs=D,this.usage=F,this.command=B,this.shim=E,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=($=((C=this.shim.getEnv("SHELL"))===null||C===void 0?void 0:C.includes("zsh"))||((u=this.shim.getEnv("ZSH_NAME"))===null||u===void 0?void 0:u.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,B,E){let C=this.command.getCommandHandlers();for(let $=0,X=D.length;$<X;++$)if(C[D[$]]&&C[D[$]].builder){let Q=C[D[$]].builder;if(h0(Q)){this.indexAfterLastReset=$+1;let z=this.yargs.getInternalMethods().reset();return Q(z,!0),z.argv}}let u=[];this.commandCompletions(u,D,B),this.optionCompletions(u,D,F,B),this.choicesFromOptionsCompletions(u,D,F,B),this.choicesFromPositionalsCompletions(u,D,F,B),E(null,u)}commandCompletions(D,F,B){let E=this.yargs.getInternalMethods().getContext().commands;if(!B.match(/^-/)&&E[E.length-1]!==B&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((C)=>{let u=kD(C[0]).cmd;if(F.indexOf(u)===-1)if(!this.zshShell)D.push(u);else{let $=C[1]||"";D.push(u.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,B,E){if((E.match(/^-/)||E===""&&D.length===0)&&!this.previousArgHasChoices(F)){let C=this.yargs.getOptions(),u=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(C.key).forEach(($)=>{let X=!!C.configuration["boolean-negation"]&&C.boolean.includes($);if(!u.includes($)&&!C.hiddenOptions.includes($)&&!this.argsContainKey(F,$,X))this.completeOptionKey($,D,E,X&&!!C.default[$])})}}choicesFromOptionsCompletions(D,F,B,E){if(this.previousArgHasChoices(F)){let C=this.getPreviousArgChoices(F);if(C&&C.length>0)D.push(...C.map((u)=>u.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,B,E){if(E===""&&D.length>0&&this.previousArgHasChoices(F))return;let C=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],u=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=C[B._.length-u-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],B="";if(!F.startsWith("-")&&D.length>1)B=F,F=D[D.length-2];if(!F.startsWith("-"))return;let E=F.replace(/^-+/,""),C=this.yargs.getOptions(),u=[E,...this.yargs.getAliases()[E]||[]],$;for(let X of u)if(Object.prototype.hasOwnProperty.call(C.key,X)&&Array.isArray(C.choices[X])){$=C.choices[X];break}if($)return $.filter((X)=>!B||X.startsWith(B))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,B){let E=(C)=>D.indexOf((/^[^0-9]$/.test(C)?"-":"--")+C)!==-1;if(E(F))return!0;if(B&&E(`no-${F}`))return!0;if(this.aliases){for(let C of this.aliases[F])if(E(C))return!0}return!1}completeOptionKey(D,F,B,E){var C,u,$,X;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),q=(u=(C=this===null||this===void 0?void 0:this.aliases)===null||C===void 0?void 0:C[D])===null||u===void 0?void 0:u.find((P)=>{let m=J[P];return typeof m==="string"&&m.length>0}),_=q?J[q]:void 0,H=(X=($=J[D])!==null&&$!==void 0?$:_)!==null&&X!==void 0?X:"";Q=`${D.replace(/:/g,"\\:")}:${H.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let z=(J)=>/^--/.test(J),Y=(J)=>/^[^0-9]$/.test(J),W=!z(B)&&Y(D)?"-":"--";if(F.push(W+Q),E)F.push(W+"no-"+Q)}customCompletion(D,F,B,E){if(YD(this.customCompletionFunction,null,this.shim),k8(this.customCompletionFunction)){let C=this.customCompletionFunction(B,F);if(s(C))return C.then((u)=>{this.shim.process.nextTick(()=>{E(null,u)})}).catch((u)=>{this.shim.process.nextTick(()=>{E(u,void 0)})});return E(null,C)}else if(f8(this.customCompletionFunction))return this.customCompletionFunction(B,F,(C=E)=>this.defaultCompletion(D,F,B,C),(C)=>{E(null,C)});else return this.customCompletionFunction(B,F,(C)=>{E(null,C)})}getCompletion(D,F){let B=D.length?D[D.length-1]:"",E=this.yargs.parse(D,!0),C=this.customCompletionFunction?(u)=>this.customCompletion(D,u,B,F):(u)=>this.defaultCompletion(D,u,B,F);return s(E)?E.then(C):C(E)}generateCompletionScript(D,F){let B=this.zshShell?$3:u3,E=this.shim.path.basename(D);if(D.match(/\.js$/))D=`./${D}`;return B=B.replace(/{{app_name}}/g,E),B=B.replace(/{{completion_command}}/g,F),B.replace(/{{app_path}}/g,D)}registerFunction(D){this.customCompletionFunction=D}setParsed(D){this.aliases=D.aliases}}function Z3(D,F,B,E){return new X3(D,F,B,E)}function k8(D){return D.length<3}function f8(D){return D.length>3}function Q3(D,F){if(D.length===0)return F.length;if(F.length===0)return D.length;let B=[],E;for(E=0;E<=F.length;E++)B[E]=[E];let C;for(C=0;C<=D.length;C++)B[0][C]=C;for(E=1;E<=F.length;E++)for(C=1;C<=D.length;C++)if(F.charAt(E-1)===D.charAt(C-1))B[E][C]=B[E-1][C-1];else if(E>1&&C>1&&F.charAt(E-2)===D.charAt(C-1)&&F.charAt(E-1)===D.charAt(C-2))B[E][C]=B[E-2][C-2]+1;else B[E][C]=Math.min(B[E-1][C-1]+1,Math.min(B[E][C-1]+1,B[E-1][C]+1));return B[F.length][D.length]}var z3=["$0","--","_"];function O3(D,F,B){let E=B.y18n.__,C=B.y18n.__n,u={};u.nonOptionCount=function Y(W){let J=D.getDemandedCommands(),_=W._.length+(W["--"]?W["--"].length:0)-D.getInternalMethods().getContext().commands.length;if(J._&&(_<J._.min||_>J._.max)){if(_<J._.min)if(J._.minMsg!==void 0)F.fail(J._.minMsg?J._.minMsg.replace(/\$0/g,_.toString()).replace(/\$1/,J._.min.toString()):null);else F.fail(C("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",_,_.toString(),J._.min.toString()));else if(_>J._.max)if(J._.maxMsg!==void 0)F.fail(J._.maxMsg?J._.maxMsg.replace(/\$0/g,_.toString()).replace(/\$1/,J._.max.toString()):null);else F.fail(C("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",_,_.toString(),J._.max.toString()))}},u.positionalCount=function Y(W,J){if(J<W)F.fail(C("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+""))},u.requiredArguments=function Y(W,J){let q=null;for(let _ of Object.keys(J))if(!Object.prototype.hasOwnProperty.call(W,_)||typeof W[_]==="undefined")q=q||{},q[_]=J[_];if(q){let _=[];for(let P of Object.keys(q)){let m=q[P];if(m&&_.indexOf(m)<0)_.push(m)}let H=_.length?`
86
- ${_.join(`
87
- `)}`:"";F.fail(C("Missing required argument: %s","Missing required arguments: %s",Object.keys(q).length,Object.keys(q).join(", ")+H))}},u.unknownArguments=function Y(W,J,q,_,H=!0){var P;let m=D.getInternalMethods().getCommandInstance().getCommands(),g=[],QD=D.getInternalMethods().getContext();if(Object.keys(W).forEach((V)=>{if(!z3.includes(V)&&!Object.prototype.hasOwnProperty.call(q,V)&&!Object.prototype.hasOwnProperty.call(D.getInternalMethods().getParseContext(),V)&&!u.isValidAndSomeAliasIsNotNew(V,J))g.push(V)}),H&&(QD.commands.length>0||m.length>0||_))W._.slice(QD.commands.length).forEach((V)=>{if(!m.includes(""+V))g.push(""+V)});if(H){let L=((P=D.getDemandedCommands()._)===null||P===void 0?void 0:P.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(C("Unknown argument: %s","Unknown arguments: %s",g.length,g.map((V)=>V.trim()?V:`"${V}"`).join(", ")))},u.unknownCommands=function Y(W){let J=D.getInternalMethods().getCommandInstance().getCommands(),q=[],_=D.getInternalMethods().getContext();if(_.commands.length>0||J.length>0)W._.slice(_.commands.length).forEach((H)=>{if(!J.includes(""+H))q.push(""+H)});if(q.length>0)return F.fail(C("Unknown command: %s","Unknown commands: %s",q.length,q.join(", "))),!0;else return!1},u.isValidAndSomeAliasIsNotNew=function Y(W,J){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;let q=D.parsed.newAliases;return[W,...J[W]].some((_)=>!Object.prototype.hasOwnProperty.call(q,_)||!q[W])},u.limitedChoices=function Y(W){let J=D.getOptions(),q={};if(!Object.keys(J.choices).length)return;Object.keys(W).forEach((P)=>{if(z3.indexOf(P)===-1&&Object.prototype.hasOwnProperty.call(J.choices,P))[].concat(W[P]).forEach((m)=>{if(J.choices[P].indexOf(m)===-1&&m!==void 0)q[P]=(q[P]||[]).concat(m)})});let _=Object.keys(q);if(!_.length)return;let H=E("Invalid values:");_.forEach((P)=>{H+=`
88
- ${E("Argument: %s, Given: %s, Choices: %s",P,F.stringifiedValues(q[P]),F.stringifiedValues(J.choices[P]))}`}),F.fail(H)};let $={};u.implies=function Y(W,J){if(N("<string|object> [array|number|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{u.implies(q,W[q])});else{if(D.global(W),!$[W])$[W]=[];if(Array.isArray(J))J.forEach((q)=>u.implies(W,q));else YD(J,void 0,B),$[W].push(J)}},u.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}u.implications=function Y(W){let J=[];if(Object.keys($).forEach((q)=>{let _=q;($[q]||[]).forEach((H)=>{let P=_,m=H;if(P=X(W,P),H=X(W,H),P&&!H)J.push(` ${_} -> ${m}`)})}),J.length){let q=`${E("Implications failed:")}
89
- `;J.forEach((_)=>{q+=_}),F.fail(q)}};let Q={};u.conflicts=function Y(W,J){if(N("<string|object> [array|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{u.conflicts(q,W[q])});else{if(D.global(W),!Q[W])Q[W]=[];if(Array.isArray(J))J.forEach((q)=>u.conflicts(W,q));else Q[W].push(J)}},u.getConflicting=()=>Q,u.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[B.Parser.camelCase(J)]!==void 0&&W[B.Parser.camelCase(q)]!==void 0)F.fail(E("Arguments %s and %s are mutually exclusive",J,q))})})},u.recommendCommands=function Y(W,J){J=J.sort((P,m)=>m.length-P.length);let _=null,H=1/0;for(let P=0,m;(m=J[P])!==void 0;P++){let g=Q3(W,m);if(g<=3&&g<H)H=g,_=m}if(_)F.fail(E("Did you mean %s?",_))},u.reset=function Y(W){return $=fD($,(J)=>!W[J]),Q=fD(Q,(J)=>!W[J]),u};let z=[];return u.freeze=function Y(){z.push({implied:$,conflicting:Q})},u.unfreeze=function Y(){let W=z.pop();YD(W,void 0,B),{implied:$,conflicting:Q}=W},u}var rF=[],L0;function N0(D,F,B,E){L0=E;let C={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return C;let u=/\.json|\..*rc$/.test(D.extends),$=null;if(!u)try{$=import.meta.resolve(D.extends)}catch(X){return D}else $=d8(F,D.extends);y8($),rF.push($),C=u?JSON.parse(L0.readFileSync($,"utf8")):E.require(D.extends),delete D.extends,C=N0(C,L0.path.dirname($),B,L0)}return rF=[],B?Y3(C,D):Object.assign({},C,D)}function y8(D){if(rF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function d8(D,F){return L0.path.resolve(D,F)}function Y3(D,F){let B={};function E(C){return C&&typeof C==="object"&&!Array.isArray(C)}Object.assign(B,D);for(let C of Object.keys(F))if(E(F[C])&&E(B[C]))B[C]=Y3(D[C],F[C]);else B[C]=F[C];return B}var j=function(D,F,B,E,C){if(E==="m")throw new TypeError("Private method is not writable");if(E==="a"&&!C)throw new TypeError("Private accessor was defined without a setter");if(typeof F==="function"?D!==F||!C:!F.has(D))throw new TypeError("Cannot write private member to an object whose class did not declare it");return E==="a"?C.call(D,B):C?C.value=B:F.set(D,B),B},Z=function(D,F,B,E){if(B==="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 B==="m"?E:B==="a"?E.call(D):E?E.value:F.get(D)},FD,iD,j0,WD,GD,p0,dD,tD,m0,_D,l0,KD,wD,HD,VD,c0,sD,ZD,T,o0,n0,qD,rD,Y0,aD,hD,i0,f,eD,D0,F0,h,t0,ID,a;function x3(D){return(F=[],B=D.process.cwd(),E)=>{let C=new P3(F,B,E,D);return Object.defineProperty(C,"argv",{get:()=>{return C.parse()},enumerable:!0}),C.help(),C.version(),C}}var J3=Symbol("copyDoubleDash"),W3=Symbol("copyDoubleDash"),aF=Symbol("deleteFromParserHintObject"),A3=Symbol("emitWarning"),G3=Symbol("freeze"),H3=Symbol("getDollarZero"),B0=Symbol("getParserConfiguration"),q3=Symbol("getUsageConfiguration"),eF=Symbol("guessLocale"),M3=Symbol("guessVersion"),_3=Symbol("parsePositionalNumbers"),D2=Symbol("pkgUp"),gD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),F2=Symbol("populateParserHintArrayDictionary"),B2=Symbol("populateParserHintDictionary"),E2=Symbol("sanitizeKey"),C2=Symbol("setKey"),u2=Symbol("unfreeze"),K3=Symbol("validateAsync"),V3=Symbol("getCommandInstance"),R3=Symbol("getContext"),U3=Symbol("getHasOutput"),L3=Symbol("getLoggerInstance"),N3=Symbol("getParseContext"),j3=Symbol("getUsageInstance"),w3=Symbol("getValidationInstance"),s0=Symbol("hasParseCallback"),I3=Symbol("isGlobalContext"),E0=Symbol("postProcess"),b3=Symbol("rebase"),$2=Symbol("reset"),w0=Symbol("runYargsParserAndExecuteCommands"),X2=Symbol("runValidation"),T3=Symbol("setHasOutput"),C0=Symbol("kTrackManuallySetKeys"),h8="en_US";class P3{constructor(D=[],F,B,E){this.customScriptName=!1,this.parsed=!1,FD.set(this,void 0),iD.set(this,void 0),j0.set(this,{commands:[],fullCommands:[]}),WD.set(this,null),GD.set(this,null),p0.set(this,"show-hidden"),dD.set(this,null),tD.set(this,!0),m0.set(this,{}),_D.set(this,!0),l0.set(this,[]),KD.set(this,void 0),wD.set(this,{}),HD.set(this,!1),VD.set(this,null),c0.set(this,!0),sD.set(this,void 0),ZD.set(this,""),T.set(this,void 0),o0.set(this,void 0),n0.set(this,{}),qD.set(this,null),rD.set(this,null),Y0.set(this,{}),aD.set(this,{}),hD.set(this,void 0),i0.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),t0.set(this,{}),ID.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,o0,B,"f"),j(this,KD,new tF(this),"f"),this.$0=this[H3](),this[$2](),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,T,Z(this,T,"f"),"f"),Z(this,T,"f").showHiddenOpt=Z(this,p0,"f"),j(this,sD,this[W3](),"f"),Z(this,f,"f").y18n.setLocale(h8)}addHelpOpt(D,F){if(N("[string|boolean] [string]",[D,F],arguments.length),Z(this,VD,"f"))this[aF](Z(this,VD,"f")),j(this,VD,null,"f");if(D===!1&&F===void 0)return this;return j(this,VD,typeof D==="string"?D:"help","f"),this.boolean(Z(this,VD,"f")),this.describe(Z(this,VD,"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 B=typeof D==="string"?D:Z(this,p0,"f");return this.boolean(B),this.describe(B,F||Z(this,h,"f").deferY18nLookup("Show hidden options")),Z(this,T,"f").showHiddenOpt=B,this}showHidden(D,F){return this.addShowHiddenOpt(D,F)}alias(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[F2](this.alias.bind(this),"alias",D,F),this}array(D){return N("<array|string>",[D],arguments.length),this[gD]("array",D),this[C0](D),this}boolean(D){return N("<array|string>",[D],arguments.length),this[gD]("boolean",D),this[C0](D),this}check(D,F){return N("<function> [boolean]",[D,F],arguments.length),this.middleware((B,E)=>{return nD(()=>{return D(B,E.getOptions())},(C)=>{if(!C)Z(this,h,"f").fail(Z(this,f,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof C==="string"||C instanceof Error)Z(this,h,"f").fail(C.toString(),C);return B},(C)=>{return Z(this,h,"f").fail(C.message?C.message:C.toString(),C),B})},!1,F),this}choices(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[F2](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 B=D;return Z(this,T,"f").key[B]=!0,Z(this,KD,"f").addCoerceMiddleware((E,C)=>{var u;let $=(u=C.getAliases()[B])!==null&&u!==void 0?u:[],X=[B,...$].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)})},B),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,B){if(N("[object|string] [string|function] [function]",[D,F,B],arguments.length),typeof D==="object"&&!Array.isArray(D))return D=N0(D,Z(this,iD,"f"),this[B0]()["deep-merge-config"]||!1,Z(this,f,"f")),Z(this,T,"f").configObjects=(Z(this,T,"f").configObjects||[]).concat(D),this;if(typeof F==="function")B=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,T,"f").config[E]=B||!0}),this}completion(D,F,B){if(N("[string] [string|boolean|function] [function]",[D,F,B],arguments.length),typeof F==="function")B=F,F=void 0;if(j(this,GD,D||Z(this,GD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(Z(this,GD,"f"),F),B)Z(this,WD,"f").registerFunction(B);return this}command(D,F,B,E,C,u){return N("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,B,E,C,u],arguments.length),Z(this,FD,"f").addHandler(D,F,B,E,C,u),this}commands(D,F,B,E,C,u){return this.command(D,F,B,E,C,u)}commandDir(D,F){N("<string> [object]",[D,F],arguments.length);let B=Z(this,o0,"f")||Z(this,f,"f").require;return Z(this,FD,"f").addDirectory(D,B,Z(this,f,"f").getCallerFile(),F),this}count(D){return N("<array|string>",[D],arguments.length),this[gD]("count",D),this[C0](D),this}default(D,F,B){if(N("<object|string|array> [*] [string]",[D,F,B],arguments.length),B)iF(D,Z(this,f,"f")),Z(this,T,"f").defaultDescription[D]=B;if(typeof F==="function"){if(iF(D,Z(this,f,"f")),!Z(this,T,"f").defaultDescription[D])Z(this,T,"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,B){return this.default(D,F,B)}demandCommand(D=1,F,B,E){if(N("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,B,E],arguments.length),typeof F!=="number")B=F,F=1/0;return this.global("_",!1),Z(this,T,"f").demandedCommands._={min:D,max:F,minMsg:B,maxMsg:E},this}demand(D,F,B){if(Array.isArray(F))F.forEach((E)=>{YD(B,!0,Z(this,f,"f")),this.demandOption(E,B)}),F=1/0;else if(typeof F!=="number")B=F,F=1/0;if(typeof D==="number")YD(B,!0,Z(this,f,"f")),this.demandCommand(D,F,B,B);else if(Array.isArray(D))D.forEach((E)=>{YD(B,!0,Z(this,f,"f")),this.demandOption(E,B)});else if(typeof B==="string")this.demandOption(D,B);else if(B===!0||typeof B==="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,T,"f").deprecatedOptions[D]=F,this}describe(D,F){return N("<object|string|array> [string]",[D,F],arguments.length),this[C2](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,T,"f").envPrefix;else Z(this,T,"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((B)=>this.example(...B));else Z(this,h,"f").example(D,F);return this}exit(D,F){if(j(this,HD,!0,"f"),j(this,dD,F,"f"),Z(this,_D,"f"))Z(this,f,"f").process.exit(D)}exitProcess(D=!0){return N("[boolean]",[D],arguments.length),j(this,_D,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((B,E)=>{Z(this,WD,"f").getCompletion(D,(C,u)=>{if(C)E(C);else B(u)})});else return Z(this,WD,"f").getCompletion(D,F)}getDemandedOptions(){return N([],0),Z(this,T,"f").demandedOptions}getDemandedCommands(){return N([],0),Z(this,T,"f").demandedCommands}getDeprecatedOptions(){return N([],0),Z(this,T,"f").deprecatedOptions}getDetectLocale(){return Z(this,tD,"f")}getExitProcess(){return Z(this,_D,"f")}getGroups(){return Object.assign({},Z(this,wD,"f"),Z(this,aD,"f"))}getHelp(){if(j(this,HD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[w0](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,T,"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,T,"f").local=Z(this,T,"f").local.filter((B)=>D.indexOf(B)===-1);else D.forEach((B)=>{if(!Z(this,T,"f").local.includes(B))Z(this,T,"f").local.push(B)});return this}group(D,F){N("<string|array> <string>",[D,F],arguments.length);let B=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]=(B||[]).concat(D).filter((C)=>{if(E[C])return!1;return E[C]=!0}),this}hide(D){return N("<string>",[D],arguments.length),Z(this,T,"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[eF](),Z(this,f,"f").y18n.getLocale();return j(this,tD,!1,"f"),Z(this,f,"f").y18n.setLocale(D),this}middleware(D,F,B){return Z(this,KD,"f").addMiddleware(D,!!F,B)}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[gD]("normalize",D),this}number(D){return N("<array|string>",[D],arguments.length),this[gD]("number",D),this[C0](D),this}option(D,F){if(N("<string|object> [object]",[D,F],arguments.length),typeof D==="object")Object.keys(D).forEach((B)=>{this.options(B,D[B])});else{if(typeof F!=="object")F={};if(this[C0](D),Z(this,ID,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[A3](['"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,T,"f").key[D]=!0,F.alias)this.alias(D,F.alias);let B=F.deprecate||F.deprecated;if(B)this.deprecateOption(D,B);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,T,"f").defaultDescription[D]=F.defaultDescription;if(F.skipValidation)this.skipValidation(D);let C=F.describe||F.description||F.desc,u=Z(this,h,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(u,D)||typeof C==="string")this.describe(D,C);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,B){if(N("[string|array] [function|boolean|object] [function]",[D,F,B],arguments.length),this[G3](),typeof D==="undefined")D=Z(this,hD,"f");if(typeof F==="object")j(this,rD,F,"f"),F=B;if(typeof F==="function")j(this,qD,F,"f"),F=!1;if(!F)j(this,hD,D,"f");if(Z(this,qD,"f"))j(this,_D,!1,"f");let E=this[w0](D,!!F),C=this.parsed;if(Z(this,WD,"f").setParsed(this.parsed),s(E))return E.then((u)=>{if(Z(this,qD,"f"))Z(this,qD,"f").call(this,Z(this,dD,"f"),u,Z(this,ZD,"f"));return u}).catch((u)=>{if(Z(this,qD,"f"))Z(this,qD,"f")(u,this.parsed.argv,Z(this,ZD,"f"));throw u}).finally(()=>{this[u2](),this.parsed=C});else{if(Z(this,qD,"f"))Z(this,qD,"f").call(this,Z(this,dD,"f"),E,Z(this,ZD,"f"));this[u2](),this.parsed=C}return E}parseAsync(D,F,B){let E=this.parse(D,F,B);return!s(E)?Promise.resolve(E):E}parseSync(D,F,B){let E=this.parse(D,F,B);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,n0,D,"f"),this}pkgConf(D,F){N("<string> [string]",[D,F],arguments.length);let B=null,E=this[D2](F||Z(this,iD,"f"));if(E[D]&&typeof E[D]==="object")B=N0(E[D],F||Z(this,iD,"f"),this[B0]()["deep-merge-config"]||!1,Z(this,f,"f")),Z(this,T,"f").configObjects=(Z(this,T,"f").configObjects||[]).concat(B);return this}positional(D,F){N("<string> <object>",[D,F],arguments.length);let B=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];F=fD(F,(u,$)=>{if(u==="type"&&!["string","number","boolean"].includes($))return!1;return B.includes(u)});let E=Z(this,j0,"f").fullCommands[Z(this,j0,"f").fullCommands.length-1],C=E?Z(this,FD,"f").cmdToParseOptions(E):{array:[],alias:{},default:{},demand:{}};return z0(C).forEach((u)=>{let $=C[u];if(Array.isArray($)){if($.indexOf(D)!==-1)F[u]=!0}else if($[D]&&!(u in F))F[u]=$[D]}),this.group(D,Z(this,h,"f").getPositionalGroupName()),this.option(D,F)}recommendCommands(D=!0){return N("[boolean]",[D],arguments.length),j(this,i0,D,"f"),this}required(D,F,B){return this.demand(D,F,B)}require(D,F,B){return this.demand(D,F,B)}requiresArg(D){if(N("<array|string|object> [number]",[D],arguments.length),typeof D==="string"&&Z(this,T,"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,WD,"f").generateCompletionScript(D,F||Z(this,GD,"f")||"completion")),this}showHelp(D){if(N("[string|function]",[D],arguments.length),j(this,HD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let B=this[w0](Z(this,hD,"f"),void 0,void 0,0,!0);if(s(B))return B.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[gD]("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[gD]("string",D),this[C0](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,B,E){if(N("<string|null|undefined> [string|boolean] [function|object] [function]",[D,F,B,E],arguments.length),F!==void 0)if(YD(D,null,Z(this,f,"f")),(D||"").match(/^\$0( |$)/))return this.command(D,F,B,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,t0,D,"f"),this}version(D,F,B){if(N("[boolean|string] [string] [string]",[D,F,B],arguments.length),Z(this,ID,"f"))this[aF](Z(this,ID,"f")),Z(this,h,"f").version(void 0),j(this,ID,null,"f");if(arguments.length===0)B=this[M3](),D="version";else if(arguments.length===1){if(D===!1)return this;B=D,D="version"}else if(arguments.length===2)B=F,F=void 0;return j(this,ID,typeof D==="string"?D:"version","f"),F=F||Z(this,h,"f").deferY18nLookup("Show version number"),Z(this,h,"f").version(B||void 0),this.boolean(Z(this,ID,"f")),this.describe(Z(this,ID,"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,j0=new WeakMap,WD=new WeakMap,GD=new WeakMap,p0=new WeakMap,dD=new WeakMap,tD=new WeakMap,m0=new WeakMap,_D=new WeakMap,l0=new WeakMap,KD=new WeakMap,wD=new WeakMap,HD=new WeakMap,VD=new WeakMap,c0=new WeakMap,sD=new WeakMap,ZD=new WeakMap,T=new WeakMap,o0=new WeakMap,n0=new WeakMap,qD=new WeakMap,rD=new WeakMap,Y0=new WeakMap,aD=new WeakMap,hD=new WeakMap,i0=new WeakMap,f=new WeakMap,eD=new WeakMap,D0=new WeakMap,F0=new WeakMap,h=new WeakMap,t0=new WeakMap,ID=new WeakMap,a=new WeakMap,J3)](D){if(!D._||!D["--"])return D;D._.push.apply(D._,D["--"]);try{delete D["--"]}catch(F){}return D}[W3](){return{log:(...D)=>{if(!this[s0]())console.log(...D);if(j(this,HD,!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[s0]())console.error(...D);if(j(this,HD,!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")}}}[aF](D){z0(Z(this,T,"f")).forEach((F)=>{if(((E)=>E==="configObjects")(F))return;let B=Z(this,T,"f")[F];if(Array.isArray(B)){if(B.includes(D))B.splice(B.indexOf(D),1)}else if(typeof B==="object")delete B[D]}),delete Z(this,h,"f").getDescriptions()[D]}[A3](D,F,B){if(!Z(this,m0,"f")[B])Z(this,f,"f").process.emitWarning(D,F),Z(this,m0,"f")[B]=!0}[G3](){Z(this,l0,"f").push({options:Z(this,T,"f"),configObjects:Z(this,T,"f").configObjects.slice(0),exitProcess:Z(this,_D,"f"),groups:Z(this,wD,"f"),strict:Z(this,eD,"f"),strictCommands:Z(this,D0,"f"),strictOptions:Z(this,F0,"f"),completionCommand:Z(this,GD,"f"),output:Z(this,ZD,"f"),exitError:Z(this,dD,"f"),hasOutput:Z(this,HD,"f"),parsed:this.parsed,parseFn:Z(this,qD,"f"),parseContext:Z(this,rD,"f")}),Z(this,h,"f").freeze(),Z(this,a,"f").freeze(),Z(this,FD,"f").freeze(),Z(this,KD,"f").freeze()}[H3](){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((B)=>{let E=this[b3](Z(this,iD,"f"),B);return B.match(/^(\/|([a-zA-Z]:)?\\)/)&&E.length<B.length?E:B}).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}[B0](){return Z(this,n0,"f")}[q3](){return Z(this,t0,"f")}[eF](){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(/[.:].*/,""))}[M3](){return this[D2]().version||"unknown"}[_3](D){let F=D["--"]?D["--"]:D._;for(let B=0,E;(E=F[B])!==void 0;B++)if(Z(this,f,"f").Parser.looksLikeNumber(E)&&Number.isSafeInteger(Math.floor(parseFloat(`${E}`))))F[B]=Number(E);return D}[D2](D){let F=D||"*";if(Z(this,Y0,"f")[F])return Z(this,Y0,"f")[F];let B={};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 C=Z(this,f,"f").findUp(E,(u,$)=>{if($.includes("package.json"))return"package.json";else return});YD(C,void 0,Z(this,f,"f")),B=JSON.parse(Z(this,f,"f").readFileSync(C,"utf8"))}catch(E){}return Z(this,Y0,"f")[F]=B||{},Z(this,Y0,"f")[F]}[gD](D,F){F=[].concat(F),F.forEach((B)=>{B=this[E2](B),Z(this,T,"f")[D].push(B)})}[J0](D,F,B,E){this[B2](D,F,B,E,(C,u,$)=>{Z(this,T,"f")[C][u]=$})}[F2](D,F,B,E){this[B2](D,F,B,E,(C,u,$)=>{Z(this,T,"f")[C][u]=(Z(this,T,"f")[C][u]||[]).concat($)})}[B2](D,F,B,E,C){if(Array.isArray(B))B.forEach((u)=>{D(u,E)});else if(((u)=>typeof u==="object")(B))for(let u of z0(B))D(u,B[u]);else C(F,this[E2](B),E)}[E2](D){if(D==="__proto__")return"___proto___";return D}[C2](D,F){return this[J0](this[C2].bind(this),"key",D,F),this}[u2](){var D,F,B,E,C,u,$,X,Q,z,Y,W;let J=Z(this,l0,"f").pop();YD(J,void 0,Z(this,f,"f"));let q;D=this,F=this,B=this,E=this,C=this,u=this,$=this,X=this,Q=this,z=this,Y=this,W=this,{options:{set value(_){j(D,T,_,"f")}}.value,configObjects:q,exitProcess:{set value(_){j(F,_D,_,"f")}}.value,groups:{set value(_){j(B,wD,_,"f")}}.value,output:{set value(_){j(E,ZD,_,"f")}}.value,exitError:{set value(_){j(C,dD,_,"f")}}.value,hasOutput:{set value(_){j(u,HD,_,"f")}}.value,parsed:this.parsed,strict:{set value(_){j($,eD,_,"f")}}.value,strictCommands:{set value(_){j(X,D0,_,"f")}}.value,strictOptions:{set value(_){j(Q,F0,_,"f")}}.value,completionCommand:{set value(_){j(z,GD,_,"f")}}.value,parseFn:{set value(_){j(Y,qD,_,"f")}}.value,parseContext:{set value(_){j(W,rD,_,"f")}}.value}=J,Z(this,T,"f").configObjects=q,Z(this,h,"f").unfreeze(),Z(this,a,"f").unfreeze(),Z(this,FD,"f").unfreeze(),Z(this,KD,"f").unfreeze()}[K3](D,F){return nD(F,(B)=>{return D(B),B})}getInternalMethods(){return{getCommandInstance:this[V3].bind(this),getContext:this[R3].bind(this),getHasOutput:this[U3].bind(this),getLoggerInstance:this[L3].bind(this),getParseContext:this[N3].bind(this),getParserConfiguration:this[B0].bind(this),getUsageConfiguration:this[q3].bind(this),getUsageInstance:this[j3].bind(this),getValidationInstance:this[w3].bind(this),hasParseCallback:this[s0].bind(this),isGlobalContext:this[I3].bind(this),postProcess:this[E0].bind(this),reset:this[$2].bind(this),runValidation:this[X2].bind(this),runYargsParserAndExecuteCommands:this[w0].bind(this),setHasOutput:this[T3].bind(this)}}[V3](){return Z(this,FD,"f")}[R3](){return Z(this,j0,"f")}[U3](){return Z(this,HD,"f")}[L3](){return Z(this,sD,"f")}[N3](){return Z(this,rD,"f")||{}}[j3](){return Z(this,h,"f")}[w3](){return Z(this,a,"f")}[s0](){return!!Z(this,qD,"f")}[I3](){return Z(this,c0,"f")}[E0](D,F,B,E){if(B)return D;if(s(D))return D;if(!F)D=this[J3](D);if(this[B0]()["parse-positional-numbers"]||this[B0]()["parse-positional-numbers"]===void 0)D=this[_3](D);if(E)D=oD(D,this,Z(this,KD,"f").getMiddleware(),!1);return D}[$2](D={}){j(this,T,Z(this,T,"f")||{},"f");let F={};F.local=Z(this,T,"f").local||[],F.configObjects=Z(this,T,"f").configObjects||[];let B={};F.local.forEach((u)=>{B[u]=!0,(D[u]||[]).forEach(($)=>{B[$]=!0})}),Object.assign(Z(this,aD,"f"),Object.keys(Z(this,wD,"f")).reduce((u,$)=>{let X=Z(this,wD,"f")[$].filter((Q)=>!(Q in B));if(X.length>0)u[$]=X;return u},{})),j(this,wD,{},"f");let E=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],C=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(E.forEach((u)=>{F[u]=(Z(this,T,"f")[u]||[]).filter(($)=>!B[$])}),C.forEach((u)=>{F[u]=fD(Z(this,T,"f")[u],($)=>!B[$])}),F.envPrefix=Z(this,T,"f").envPrefix,j(this,T,F,"f"),j(this,h,Z(this,h,"f")?Z(this,h,"f").reset(B):C3(this,Z(this,f,"f")),"f"),j(this,a,Z(this,a,"f")?Z(this,a,"f").reset(B):O3(this,Z(this,h,"f"),Z(this,f,"f")),"f"),j(this,FD,Z(this,FD,"f")?Z(this,FD,"f").reset():F3(Z(this,h,"f"),Z(this,a,"f"),Z(this,KD,"f"),Z(this,f,"f")),"f"),!Z(this,WD,"f"))j(this,WD,Z3(this,Z(this,h,"f"),Z(this,FD,"f"),Z(this,f,"f")),"f");return Z(this,KD,"f").reset(),j(this,GD,null,"f"),j(this,ZD,"","f"),j(this,dD,null,"f"),j(this,HD,!1,"f"),this.parsed=!1,this}[b3](D,F){return Z(this,f,"f").path.relative(D,F)}[w0](D,F,B,E=0,C=!1){var u,$,X,Q;let z=!!B||C;D=D||Z(this,hD,"f"),Z(this,T,"f").__=Z(this,f,"f").y18n.__,Z(this,T,"f").configuration=this[B0]();let Y=!!Z(this,T,"f").configuration["populate--"],W=Object.assign({},Z(this,T,"f").configuration,{"populate--":!0}),J=Z(this,f,"f").Parser.detailed(D,Object.assign({},Z(this,T,"f"),{configuration:{"parse-positional-numbers":!1,...W}})),q=Object.assign(J.argv,Z(this,rD,"f")),_=void 0,H=J.aliases,P=!1,m=!1;if(Object.keys(q).forEach((g)=>{if(g===Z(this,VD,"f")&&q[g])P=!0;else if(g===Z(this,ID,"f")&&q[g])m=!0}),q.$0=this.$0,this.parsed=J,E===0)Z(this,h,"f").clearCachedHelpMessage();try{if(this[eF](),F)return this[E0](q,Y,!!B,!1);if(Z(this,VD,"f")){if([Z(this,VD,"f")].concat(H[Z(this,VD,"f")]||[]).filter((k)=>k.length>1).includes(""+q._[q._.length-1]))q._.pop(),P=!0}j(this,c0,!1,"f");let g=Z(this,FD,"f").getCommands(),QD=((u=Z(this,WD,"f"))===null||u===void 0?void 0:u.completionKey)?[($=Z(this,WD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(X=Z(this,WD,"f"))===null||X===void 0?void 0:X.completionKey])!==null&&Q!==void 0?Q:[]].some((L)=>Object.prototype.hasOwnProperty.call(q,L)):!1,V=P||QD||C;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,GD,"f")){let t=Z(this,FD,"f").runCommand(d,this,J,k+1,C,P||m||C);return this[E0](t,Y,!!B,!1)}else if(!L&&d!==Z(this,GD,"f")){L=d;break}if(!Z(this,FD,"f").hasDefaultCommand()&&Z(this,i0,"f")&&L&&!V)Z(this,a,"f").recommendCommands(L,g)}if(Z(this,GD,"f")&&q._.includes(Z(this,GD,"f"))&&!QD){if(Z(this,_D,"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,C,P||m||C);return this[E0](L,Y,!!B,!1)}if(QD){if(Z(this,_D,"f"))yD(!0);D=[].concat(D);let L=D.slice(D.indexOf(`--${Z(this,WD,"f").completionKey}`)+1);return Z(this,WD,"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,!!B,!1)}if(!Z(this,HD,"f")){if(P){if(Z(this,_D,"f"))yD(!0);z=!0,this.showHelp((L)=>{Z(this,sD,"f").log(L),this.exit(0)})}else if(m){if(Z(this,_D,"f"))yD(!0);z=!0,Z(this,h,"f").showVersion("log"),this.exit(0)}}if(!z&&Z(this,T,"f").skipValidation.length>0)z=Object.keys(q).some((L)=>Z(this,T,"f").skipValidation.indexOf(L)>=0&&q[L]===!0);if(!z){if(J.error)throw new DD(J.error.message);if(!QD){let L=this[X2](H,{},J.error);if(!B)_=oD(q,this,Z(this,KD,"f").getMiddleware(),!0);if(_=this[K3](L,_!==null&&_!==void 0?_:q),s(_)&&!B)_=_.then(()=>{return oD(q,this,Z(this,KD,"f").getMiddleware(),!1)})}}}catch(g){if(g instanceof DD)Z(this,h,"f").fail(g.message,g);else throw g}return this[E0](_!==null&&_!==void 0?_:q,Y,!!B,!0)}[X2](D,F,B,E){let C={...this.getDemandedOptions()};return(u)=>{if(B)throw new DD(B.message);Z(this,a,"f").nonOptionCount(u),Z(this,a,"f").requiredArguments(u,C);let $=!1;if(Z(this,D0,"f"))$=Z(this,a,"f").unknownCommands(u);if(Z(this,eD,"f")&&!$)Z(this,a,"f").unknownArguments(u,D,F,!!E);else if(Z(this,F0,"f"))Z(this,a,"f").unknownArguments(u,D,{},!1,!1);Z(this,a,"f").limitedChoices(u),Z(this,a,"f").implications(u),Z(this,a,"f").conflicting(u)}}[T3](){j(this,HD,!0,"f")}[C0](D){if(typeof D==="string")Z(this,T,"f").key[D]=!0;else for(let F of D)Z(this,T,"f").key[F]=!0}}function B3(D){return!!D&&typeof D.getInternalMethods==="function"}var g8=x3(nF),S3=g8;import{performance as f3}from"node:perf_hooks";var pD=v0(Q2(),1);class c8{total;message;current=0;barLength=30;startTime=f3.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(f3.now()-this.startTime);console.log(pD.default.green(`✅ ${D||this.message} ${pD.default.gray(`(${F}ms)`)}`))}render(D){let F=Math.round(this.current/this.total*100),B=Math.round(this.current/this.total*this.barLength),E=this.barLength-B,C=pD.default.green("█".repeat(B))+pD.default.gray("░".repeat(E)),u=`${this.current}/${this.total}`,$=D?pD.default.gray(` ${D}`):"";if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(`${this.message} ${C} ${pD.default.cyan(u)} ${pD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
93
- `)}}var $D=v0(Q2(),1);class e0{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,B){let E=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",C=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${E}${B(D)} ${C}${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=(B)=>B){let B=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${B}${E}${F(D)}`)}dim(D){this.plain(D,$D.default.gray)}child(D){return new e0({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${D}`:D})}configure(D){this.options={...this.options,...D}}}var u0=new e0;function DF(D){u0.success(D)}function RD(D,F){u0.error(D,F)}function z2(D){u0.warn(D)}function FF(D){u0.info(D)}function O2(D){u0.step(D)}function y3(D){u0.dim(D)}function Y2(D){u0.configure(D)}function JD(D={}){return new e0(D)}function J2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function W2(D,F,B){let E=D;if(F)E+=` ${$D.default.gray(`(${F}ms)`)}`;if(DF(E),B)Object.entries(B).forEach(([C,u])=>{y3(` ${C}: ${u}`)})}function $0(D,F="•"){D.forEach((B)=>{console.log($D.default.gray(` ${F} ${B}`))})}import{existsSync as cB}from"node:fs";import{resolve as oB}from"node:path";import{existsSync as BF,mkdirSync as d3}from"node:fs";import{readdir as h3,readFile as o8,stat as n8,unlink as g3,writeFile as i8}from"node:fs/promises";import{join as A2}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,B]of this.cache.entries())if(B.identifier.url===D)return this.cache.delete(F);return!1}getByPackage(D){let F=[];for(let B of this.cache.values())if(B.identifier.package===D)F.push(B);return F}getByKind(D){let F=[];for(let B of this.cache.values())if(B.identifier.kind===D)F.push(B);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(!BF(this.cacheDir))d3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!BF(this.cacheDir))return;try{let F=(await h3(this.cacheDir)).filter((B)=>B.endsWith(".typeschema.json"));for(let B of F){let E=A2(this.cacheDir,B),C=await n8(E);if(this.config.maxAge){if(Date.now()-C.mtimeMs>this.config.maxAge){await g3(E);continue}}try{let u=await o8(E,"utf-8"),$=JSON.parse(u);if(this.config.validateCached){if(!$.schema?.identifier)continue}let X=this.generateKey($.schema.identifier);this.cache.set(X,$.schema)}catch(u){console.warn(`Failed to load cached schema from ${B}:`,u)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!BF(this.cacheDir))d3(this.cacheDir,{recursive:!0});let F={schema:D,timestamp:Date.now(),version:D.identifier.version},B=`${D.identifier.package}-${D.identifier.version}-${D.identifier.kind}-${D.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),E=A2(this.cacheDir,B);try{await i8(E,JSON.stringify(F,null,2),"utf-8")}catch(C){console.warn(`Failed to persist schema to ${E}:`,C)}}async clearDisk(){if(!this.cacheDir||!BF(this.cacheDir))return;try{let F=(await h3(this.cacheDir)).filter((B)=>B.endsWith(".typeschema.json"));for(let B of F)await g3(A2(this.cacheDir,B))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as t8}from"crypto";var G2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return t8("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:G2,get:(C)=>D[C],set:(C,u)=>{if(D[C]=u,u.url){if(!F[u.url])F[u.url]=[];let $=F[u.url];if($&&!$.includes(C))$.push(C)}},has:(C)=>(C in D),clear:()=>{Object.keys(D).forEach((C)=>delete D[C]),Object.keys(F).forEach((C)=>delete F[C])},size:()=>Object.keys(D).length,getIdsByUrl:(C)=>F[C]||[],createReference:(C,u)=>({id:C,resourceType:u.resourceType}),getAllReferences:()=>D}};import*as x2 from"path";import*as e3 from"fs/promises";var p3="https://fs.get-ig.org/pkgs/";import*as EF from"fs/promises";import*as m3 from"path";var A0=async(D)=>{try{return await EF.access(D),!0}catch{return!1}},G0=async(D)=>{try{await EF.mkdir(D,{recursive:!0})}catch{}},CF=async(D)=>{let F=m3.join(D,".index.json");return A0(F)};import{exec as s8}from"child_process";import{promisify as r8}from"util";var l3=r8(s8);async function H2(){try{return await l3("bun --version"),"bun"}catch{try{return await l3("npm --version"),"npm"}catch{return null}}}import*as o3 from"fs/promises";import*as n3 from"path";import{exec as a8}from"child_process";import{promisify as e8}from"util";var c3=e8(a8),q2=async(D,F,B)=>{await G0(F);let E=n3.join(F,"package.json");if(!await A0(E))await o3.writeFile(E,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let C=await H2();if(!C)throw new Error("No package manager found. Please install npm or bun.");for(let u of D)try{if(C==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},X=B?`cd ${F} && bun add ${u} --registry ${B}`:`cd ${F} && bun add ${u}`;await c3(X,{env:$,maxBuffer:10485760})}else{let $=B?`cd ${F} && npm add ${u} --registry ${B}`:`cd ${F} && npm add ${u}`;await c3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${u}:`,$),$}};var uF=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as $F from"fs/promises";import*as K2 from"path";import*as M2 from"fs/promises";import*as _2 from"path";import{createHash as i3}from"crypto";var I0=async(D)=>{try{let F=_2.join(D,"package-lock.json");try{let B=await M2.readFile(F,"utf-8");return i3("sha256").update(B).digest("hex")}catch{let B=_2.join(D,"bun.lock"),E=await M2.readFile(B,"utf-8");return i3("sha256").update(E).digest("hex")}}catch{return null}};var V2=async(D,F,B)=>{let E=await I0(B),C={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:E||void 0},u=K2.join(F,"index.json");await $F.writeFile(u,JSON.stringify(C,null,2))},R2=async(D)=>{try{let F=K2.join(D,"index.json"),B=await $F.readFile(F,"utf-8");return JSON.parse(B)}catch{return null}};var t3=(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 B of F)if(D[B]!==void 0&&typeof D[B]!=="string")return!1;return!0},s3=(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)=>t3(F))},U2=(D,F)=>{try{let B=JSON.parse(D);if(!s3(B))return null;return B}catch{return null}};import*as r3 from"fs/promises";import*as L2 from"path";var XF=async(D,F,B)=>{let E=L2.join(D,".index.json");try{let C=await r3.readFile(E,"utf-8"),u=U2(C,E);if(!u)return;for(let $ of u.files){if(!$.url)continue;let X=L2.join(D,$.filename),Q=B.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:X});B.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:X,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:u["index-version"],url:$.url,version:$.version,kind:$.kind,type:$.type,package:{name:F.name,version:F.version}};if(!B.entries[$.url])B.entries[$.url]=[];let Y=B.entries[$.url];if(Y)Y.push(z)}}catch{}};import*as a3 from"fs/promises";import*as ZF from"path";var QF=async(D,F)=>{try{let B=ZF.join(D,"package.json"),E=await a3.readFile(B,"utf-8"),C=JSON.parse(E),u={id:{name:C.name,version:C.version},path:D,canonical:C.canonical,fhirVersions:C.fhirVersions};F.packages[C.name]=u,await XF(D,C,F);let $=ZF.join(D,"examples");if(await A0(ZF.join($,".index.json")))await XF($,C,F)}catch{}};import*as N2 from"fs/promises";import*as j2 from"path";var w2=async(D,F)=>{try{let B=await N2.readdir(D,{withFileTypes:!0});for(let E of B){if(!E.isDirectory())continue;let C=j2.join(D,E.name);if(E.name.startsWith("@")){let u=await N2.readdir(C,{withFileTypes:!0});for(let $ of u){if(!$.isDirectory())continue;let X=j2.join(C,$.name);if(await CF(X))await QF(X,F)}}else if(await CF(C))await QF(C,F)}}catch{}};var I2=async(D,F,B,E)=>{if(F.package)try{return await E(D,{package:F.package.name,version:F.package.version})}catch{}return null};var b2={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 T2=(D,F)=>{if(F.length===0)return D;let B=F.map((E)=>E.toLowerCase());return D.filter((E)=>{if(!E.url)return!1;let u=[E.url.toLowerCase(),E.type?.toLowerCase()||"",E.resourceType?.toLowerCase()||""].join(" ");return B.every(($)=>{let X=u.split(/[\/\-_\.\s]+/);if(X.some((Y)=>Y.startsWith($)))return!0;let z=b2[$]||[];for(let Y of z)if(X.some((W)=>W.startsWith(Y)))return!0;return u.includes($)})})};var xD=(D)=>{let{packages:F,workingDir:B}=D,E=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:p3,C=x2.join(B,"node_modules"),u=x2.join(B,".fcm","cache"),$=uF(),X=!1,Q=new Map,z=()=>{if(!X)throw new Error("CanonicalManager not initialized. Call init() first.")},Y=async()=>{if(X)return;await G0(B),await G0(u);let V=await I0(B),L=await R2(u);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 q2(F,B,E),$=uF(),await w2(C,$),await V2($,u,B)}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 I2(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]},_=async(V,L)=>{let k=await q(V,L);return H(k)},H=async(V)=>{z();let L=$.referenceManager.get(V.id);if(!L)throw new Error(`Invalid reference ID: ${V.id}`);try{let k=await e3.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}`)}},P=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:_,read:H,searchEntries:P,search:async(V)=>{let L=await P(V);return await Promise.all(L.map((d)=>H(d)))},smartSearch:async(V,L)=>{z();let k=await P({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 T2(k,V)},getSearchParametersForResource:async(V)=>{if(z(),Q.has(V))return Q.get(V);let k=(await P({})).filter((t)=>t.resourceType==="SearchParameter"),d=[];for(let t of k){let l=await H(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 P2(D){let E=D.path.split(".").slice(1).map(($)=>({el:$}));if(E.length===0)return[];let C=E.length-1,u={};if(D.slicing){if(u.slicing={...D.slicing},D.min!==void 0)u.slicing.min=D.min;if(D.max&&D.max!=="*")u.slicing.max=parseInt(D.max)}if(D.sliceName){if(u.slice={},D.min!==void 0)u.slice.min=D.min;if(D.max&&D.max!=="*")u.slice.max=parseInt(D.max);u.sliceName=D.sliceName}return E[C]={...E[C],...u},E}function S2(D,F){let B=[],E=Math.min(D.length,F.length);for(let C=0;C<E;C++)if(D[C].el===F[C].el)B.push({el:D[C].el});else break;return B}function v2(D,F){let B=[];for(let E=0;E<F.length;E++)if(E<D.length&&D[E].el===F[E].el)B.push({...D[E],...F[E],...D[E].slicing&&!F[E].slicing&&{slicing:D[E].slicing}});else B.push(F[E]);return B}function DB(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function D6(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function FB(D,F,B,E){let C=[];for(let u=D-1;u>=F;u--){let $=B[u];if($.sliceName)C.push(D6($));C.push({type:"exit",el:$.el})}if(F>0){let u=B[F-1],$=E[F-1];if(DB(u,$))C.push(D6(u))}return C}function BB(D,F,B,E){let C=[];if(D>0&&D<=F){let u=B[D-1]||{},$=E[D-1];if($.sliceName&&(!u.sliceName||u.sliceName!==$.sliceName))C.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return C}for(let u=D;u<F;u++){let $=E[u];if(C.push({type:"enter",el:$.el}),$.sliceName)C.push({type:"enter-slice",sliceName:$.sliceName})}return C}function zF(D,F){let B=D.length,E=F.length,u=S2(D,F).length,$=FB(B,u,D,F),X=BB(u,E,D,F);return[...$,...X]}function B6(D,F){if(!D)return;return D.find((B)=>B.url===F)}function F6(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 EB(D){let F={};for(let[B,E]of Object.entries(D))if(typeof B==="string"&&B.startsWith("pattern")){let C=F6(B.replace(/^pattern/,""));F.pattern={type:C,value:E}}else if(typeof B==="string"&&B.startsWith("fixed")){let C=F6(B.replace(/^fixed/,""));F.pattern={type:C,value:E}}else F[B]=E;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function CB(D){let F=[];for(let B of D)if(B.targetProfile){let E=Array.isArray(B.targetProfile)?B.targetProfile:[B.targetProfile];F.push(...E)}return F.length>0?[...new Set(F)].sort():void 0}function uB(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let B=CB(D.type);return{...D,type:[{code:"Reference"}],...B&&{refers:B}}}return D}function $B(D,F){let B=(u)=>{let $={strength:u.strength,...u.valueSet&&{valueSet:u.valueSet}},X=B6(u.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(X?.valueString)$.bindingName=X.valueString;return $};if(D.choices){let{binding:u,...$}=D;return $}if(D.choiceOf&&F.snapshot){let u=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((X)=>X.path===u);if($?.binding)return{...D,binding:B($.binding)}}if(D.binding?.valueSet)return{...D,binding:B(D.binding)};let{binding:E,...C}=D;return C}function XB(D){if(!D.constraint||D.constraint.length===0)return D;let F={};for(let B of D.constraint)F[B.key]={expression:B.expression,human:B.human,severity:B.severity};return{...D,constraint:F}}function ZB(D,F){if(!D.type||D.type.length===0)return D;let B=D.type[0]?.extension?.[0];if(B?.url==="http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"&&B.valueUrl)return{...D,type:B.valueUrl};let E=D.type[0].code,C={...D,type:E};if(F.kind==="logical"){let u=B6(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(u?.valueCanonical)C.defaultType=u.valueCanonical}return C}function QB(D){if(D.type?.[0]?.code!=="Extension")return D;let B=D.type[0]?.profile?.[0];if(!B)return D;return{...D,url:B,...D.min&&{min:D.min},...D.max&&D.max!=="*"&&{max:parseInt(D.max)}}}function zB(D){if(D.url)return D;let F=D.max==="*"||D.min&&D.min>=2||D.max&&parseInt(D.max)>=2,B=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(B)E._required=!0;return E}function OB(D,F){let B=D.substring(1).split("."),E=[F.url];for(let C of B.slice(1))E.push("elements",C);return E}function YB(D,F){if(!D.contentReference)return D;let{contentReference:B,...E}=D;return{...E,elementReference:OB(B,F)}}function JB(D){let{path:F,slicing:B,sliceName:E,id:C,mapping:u,example:$,alias:X,condition:Q,comment:z,definition:Y,requirements:W,extension:J,...q}=D;return q}function k2(D,F){let B=uB(D);return B=JB(B),B=$B(B,F),B=XB(B),B=YB(B,F),B=QB(B),B=zB(B),B=ZB(B,F),B=EB(B),B}function f2(D){if(D.path.endsWith("[x]"))return!0;if(D.type&&D.type.length>1)return new Set(D.type.map((B)=>B.code)).size>1;return!1}function E6(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function C6(D){let F=D.split("/");return F[F.length-1]}function y2(D){let F=D.path.replace(/\[x\]$/,""),B=F.split(".").pop()||"";if(!D.type)return[];let E=[],C=D.type.map((z)=>B+E6(C6(z.code))),{type:u,binding:$,...X}=D,Q={...X,path:F,choices:C};E.push(Q);for(let z of D.type){let Y=E6(C6(z.code)),W={...D,path:F+Y,type:[z],choiceOf:B};if(D.binding)delete W.binding;E.push(W)}return E}function u6(D,F){let B=D[D.length-1],E=D.slice(0,-1),C=E[E.length-1],u=F(C,B);return[...E.slice(0,-1),u]}function WB(D,F){if(!D.discriminator)return{};let B={};for(let E of D.discriminator){if(!E.type||!["pattern","value",void 0].includes(E.type))continue;let C=E.path.trim();if(C==="$this"){if(F.pattern?.value)Object.assign(B,F.pattern.value)}else{let u=C.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let Y=z.replace("pattern","").toLowerCase();if(u.length===1&&u[0]===Y)B[Y]=F[z]}let X=["elements"];for(let z of u)if(X.push(z),u.indexOf(z)<u.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=B;for(let Y=0;Y<u.length-1;Y++){if(!z[u[Y]])z[u[Y]]={};z=z[u[Y]]}z[u[u.length-1]]=Q.value}}}return B}function AB(D,F,B){let E={match:F,schema:D};if(B?.min!==void 0&&B.min!==0)E.min=B.min;if(B?.max!==void 0)E.max=B.max;return E}function GB(D,F,B){let E=F.slicing||D.slicing||{},C=WB(E,B),u=AB(B,C,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]=u,F}function HB(D){if(!D.slicing?.slices)return{};let F={};for(let[B,E]of Object.entries(D.slicing.slices)){let{match:C,schema:u,...$}=E,{slicing:X,elements:Q,type:z,min:Y,...W}=u||{},J={};if(C?.url)J.url=C.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[B]=J}return F}function qB(D,F,B){let E={...F};if(D==="extension")E.extensions=HB(B);if(!E.elements)E.elements={};let C=B.choiceOf||D,{_required:u,...$}=B;if(E.elements[D]=$,u){if(!E.required)E.required=[];if(!E.required.includes(C))E.required.push(C)}return E}function OF(D,F,B){let E=[...D];for(let C=0;C<F.length;C++){let u=F[C],X=F[C+1]?.type==="enter"?{}:B;switch(u.type){case"enter":E.push(X);break;case"enter-slice":E.push(X);break;case"exit":E=u6(E,(Q,z)=>qB(u.el,Q,z));break;case"exit-slice":E=u6(E,(Q,z)=>GB(u,Q,z));break}}return E}function $6(D,F){let B={};if(B.name=D.name,B.type=D.type,D.url)B.url=D.url;if(D.version)B.version=D.version;if(D.description)B.description=D.description;if(D.package_name)B.package_name=D.package_name;if(D.package_version)B.package_version=D.package_version;if(D.package_id)B.package_id=D.package_id;if(B.kind=D.kind,D.derivation)B.derivation=D.derivation;if(D.baseDefinition&&D.type!=="Element")B.base=D.baseDefinition;if(D.abstract)B.abstract=D.abstract;if(B.class=MB(D),F?.package_meta)B.package_meta=F.package_meta;return B}function MB(D){if(D.kind==="resource"&&D.derivation==="constraint")return"profile";if(D.type==="Extension")return"extension";return D.kind||"unknown"}function _B(D){return(D.differential?.element||[]).filter((B)=>B.path.includes("."))}function X6(D){let B=Object.entries(D).sort((C,u)=>{let $=C[1].index??1/0,X=u[1].index??1/0;return $-X}),E={};for(let[C,u]of B)if(u.elements)E[C]={...u,elements:X6(u.elements)};else E[C]=u;return E}function b0(D,F=new WeakSet){if(Array.isArray(D))return D.map((B)=>b0(B,F));if(D&&typeof D==="object"){if(F.has(D))return"[Circular Reference]";F.add(D);let B={},E=Object.keys(D);for(let C of E)if(C==="elements"&&D[C])B[C]=X6(b0(D[C],F));else if(C==="required"&&Array.isArray(D[C]))B[C]=[...D[C]].sort();else B[C]=b0(D[C],F);return B}return D}function d2(D,F){if(D.kind==="primitive-type")return b0($6(D,F));let B=$6(D,F),E=_B(D),C=[B],u=[],$=[...E],X=0;while($.length>0){let z=$.shift();if(f2(z)){let H=y2(z);$.unshift(...H),X++;continue}let Y=P2(z),W=v2(u,Y),J=zF(u,W),_={...k2(z,D),index:X++};C=OF(C,J,_),u=W}let Q=zF(u,[]);if(C=OF(C,Q,{index:X}),C.length!==1)throw new Error(`Invalid stack state: expected 1 element, got ${C.length}`);return b0(C[0])}function YF(D){if(!D)return;return D.split("|")[0]}function KB(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:KB(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,B){let E=F.join(".");return{kind:"nested",package:B?.name||D.package_name||"undefined",version:B?.version||D.package_version||"undefined",name:E,url:`${D.url}#${E}`}}function JF(D,F,B){let E=YF(D)||D,C="unknown",u=E.split("/"),$=u[u.length-1];if($&&$.length>0)C=$.split(/[-_]/).map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("");if(C==="unknown"&&F?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(F.id))C=F.id;return{kind:"value-set",package:B?.name||F?.package_name||"undefined",version:B?.version||F?.package_version||"undefined",name:C,url:E}}function T0(D,F,B,E){let C=F.join("."),u=B||`${D.name}.${C}_binding`;return{kind:"binding",package:E?.name||D.package_name||"undefined",version:E?.version||D.package_version||"undefined",name:u,url:B?`urn:fhir:binding:${u}`:`${D.url}#${C}_binding`}}async function Z6(D,F,B){let E=PD(D,B);if(E.kind!=="profile")throw new Error(`Expected profile, got ${E.kind} for ${D.name}`);let C;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 VB(Y,F),q=Y.startsWith("http://hl7.org/fhir/");C={kind:J,package:q?"hl7.fhir.r4.core":B?.name||D.package_name||"undefined",version:q?"4.0.1":B?.version||D.package_version||"undefined",name:W,url:Y}}let u={identifier:E,base:C,dependencies:C?[C]:[]};if(D.description)u.description=D.description;let $=RB(D,B);if(Object.keys($).length>0)u.metadata=$;if(D.elements){let Y=await WF(D,[],D.elements,F,B);if(Object.keys(Y).length>0)u.fields=Y}let X=await UB(D,F);if(Object.keys(X).length>0)u.constraints=X;let Q=await LB(D,F);if(Q.length>0)u.extensions=Q;let z=NB(D);if(z.length>0)u.validation=z;return u}async function VB(D,F){try{let B=await F.resolve(D);if(B){if(B.derivation==="constraint")return"profile";if(B.kind==="resource")return"resource";if(B.kind==="complex-type")return"complex-type"}}catch(B){console.warn(`Could not resolve base schema ${D}:`,B)}if(D.includes("StructureDefinition/")&&!D.startsWith("http://hl7.org/fhir/StructureDefinition/"))return"profile";return"resource"}function RB(D,F){let B={};if(D.publisher)B.publisher=D.publisher;if(D.contact)B.contact=D.contact;if(D.copyright)B.copyright=D.copyright;if(D.purpose)B.purpose=D.purpose;if(D.experimental!==void 0)B.experimental=D.experimental;if(D.date)B.date=D.date;if(D.jurisdiction)B.jurisdiction=D.jurisdiction;if(F?.name)B.package=F.name;else if(D.package_name)B.package=D.package_name;return B}async function UB(D,F){let B={};if(!D.elements)return B;for(let[E,C]of Object.entries(D.elements)){let u={};if(C.min!==void 0)u.min=C.min;if(C.max!==void 0)u.max=String(C.max);if(C.mustSupport)u.mustSupport=!0;if(C.fixedValue!==void 0)u.fixedValue=C.fixedValue;if(C.patternValue!==void 0)u.patternValue=C.patternValue;if(C.binding)u.binding={strength:C.binding.strength,valueSet:C.binding.valueSet??""};if(C.type&&Array.isArray(C.type)&&C.type.length>0)u.types=C.type.map(($)=>{let X={code:$.code};if($.profile)X.profile=$.profile;if($.targetProfile)X.targetProfile=$.targetProfile;return X});if(C.slicing)u.slicing={discriminator:C.slicing.discriminator??[],rules:String(C.slicing),ordered:C.slicing.ordered};if(Object.keys(u).length>0)B[E]=u}return B}async function LB(D,F){let B=[];if(!D.elements)return B;for(let[E,C]of Object.entries(D.elements))if(E.includes("extension")&&C.type&&Array.isArray(C.type)){for(let u of C.type)if(u.code==="Extension"&&u.profile)B.push({path:E,profile:u.profile,min:C.min,max:String(C.max),mustSupport:C.mustSupport})}return B}function NB(D){let F=[];if(!D.elements)return F;for(let[B,E]of Object.entries(D.elements))if(E.constraint&&Array.isArray(E.constraint))for(let C of E.constraint)F.push({path:B,key:C.key,severity:C.severity,human:C.human,expression:C.expression});return F}function h2(D,F,B){let E=[],C=D.elements;for(let u of F)if(C=C?.[u],!C)break;if(C)E.push(C);return E}function g2(D){if(D.length===0)return{};let F={...D[0]};for(let B=D.length-1;B>=0;B--){let E=D[B],C=["choices","short","index","elements","required","excluded","binding","refers","elementReference","mustSupport","slices","slicing","url","extensions"];for(let[u,$]of Object.entries(E))if(!C.includes(u)&&$!==void 0)F[u]=$}for(let B of["choices","binding","refers","elementReference"])if(D[0]&&D[0][B]!==void 0)F[B]=D[0][B];return F}function p2(D,F,B){if(F.length===0)return!1;let E=F[F.length-1],C=F.slice(0,-1),u=D;for(let $ of C)if(u=u.elements?.[$],!u)break;if(u?.required?.includes(E))return!0;if(C.length===0&&E&&D.required?.includes(E))return!0;return!1}function m2(D,F,B){if(F.length===0)return!1;let E=F[F.length-1],C=F.slice(0,-1),u=D;for(let $ of C)if(u=u.elements?.[$],!u)break;if(u?.excluded?.includes(E))return!0;if(C.length===0&&E&&D.excluded?.includes(E))return!0;return!1}async function jB(D,F,B){if(!D.refers||D.refers.length===0)return;let E=[];for(let C of D.refers)try{let u=await F.resolve(C);if(u)E.push(PD(u,B))}catch{}return E}function l2(D,F,B,E,C){if(B.elementReference){let u=B.elementReference.filter(($,X)=>X%2===1).map(($)=>$).filter(($)=>$!=="elements");if(u.length>0)return H0(D,u,C)}if(B.type){let u=B.type.includes("/")?B.type:`http://hl7.org/fhir/StructureDefinition/${B.type}`,$=B.type.match(/^[a-z]/)?"primitive-type":"complex-type",X=u.startsWith("http://hl7.org/fhir/");return{kind:$,package:X?"hl7.fhir.r4.core":C?.name||"undefined",version:X?"4.0.1":C?.version||"undefined",name:B.type,url:u}}return}async function x0(D,F,B,E,C){let u={array:B.array||!1,required:p2(D,F,E),excluded:m2(D,F,E)},$=l2(D,F,B,E,C);if($)u.type=$;if(B.min!==void 0)u.min=B.min;if(B.max!==void 0)u.max=B.max;if(B.choices)u.choices=B.choices;if(B.choiceOf)u.choiceOf=B.choiceOf;if(B.binding){if(u.binding=T0(D,F,B.binding.bindingName,C),B.binding.strength==="required"&&B.type==="code"){let Q=await AF(B,E);if(Q&&Q.length>0)u.enum=Q}}let X=await jB(B,E,C);if(X)u.reference=X;return wB(u)}function wB(D){let F={};for(let[B,E]of Object.entries(D))if(E!==void 0&&E!==null){if(Array.isArray(E)&&E.length===0)continue;F[B]=E}return F}function q0(D){return D.type==="BackboneElement"||D.elements&&Object.keys(D.elements).length>0||!1}function P0(D,F,B,E,C){return{type:H0(D,F,C),array:B.array||!1,required:p2(D,F,E),excluded:m2(D,F,E)}}async function Q6(D,F){try{let B=YF(D)||D,E=await F.resolve(B);if(!E)return;if(E.expansion?.contains)return E.expansion.contains.map((u)=>({system:u.system,code:u.code,display:u.display}));let C=[];if(E.compose?.include){for(let u of E.compose.include)if(u.concept)for(let $ of u.concept)C.push({system:u.system,code:$.code,display:$.display});else if(u.system&&!u.filter)try{let $=await F.resolve(u.system);if($?.concept){let X=(Q,z)=>{for(let Y of Q)if(C.push({system:z,code:Y.code,display:Y.display}),Y.concept)X(Y.concept,z)};X($.concept,u.system)}}catch{}}return C.length>0?C:void 0}catch{return}}async function AF(D,F){if(!D.binding)return;let{strength:B,valueSet:E}=D.binding;if(!E)return;if(!(B==="required"||B==="extensible"&&D.type==="code"||B==="preferred"&&D.type==="code"))return;if(!F.resolve)return;try{let u=await Q6(E,F);if(!u||u.length===0)return;let $=u.map((X)=>X.code).filter((X)=>X&&typeof X==="string"&&X.trim().length>0);return $.length>0&&$.length<=50?$:void 0}catch(u){console.debug(`Failed to extract enum values for ${E}: ${u}`);return}}async function z6(D,F,B,E,C){if(!B.binding?.valueSet)return;let u=T0(D,F,B.binding.bindingName,C),$=l2(D,F,B,E,C),X=JF(B.binding.valueSet,void 0,C),Q={identifier:u,type:$,valueset:X,strength:B.binding.strength,dependencies:[]};if($)Q.dependencies.push($);Q.dependencies.push(X);let z=await AF(B,E);if(z)Q.enum=z;return Q}async function GF(D,F,B){let E=[],C=new Set;async function u(Q,z){for(let[Y,W]of Object.entries(Q)){let J=[...z,Y],q=J.join(".");if(C.has(q))continue;if(C.add(q),W.binding){let _=await z6(D,J,W,F,B);if(_)E.push(_)}if(W.elements)await u(W.elements,J)}}if(D.elements)await u(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 c2(D,F,B){let E=[];for(let[C,u]of Object.entries(B)){let $=[...F,C];if(q0(u))E.push([$,u]);if(u.elements)E.push(...c2(D,$,u.elements))}return E}async function IB(D,F,B,E,C){let u={};for(let[$,X]of Object.entries(B)){let Q=[...F,$];if(q0(X))u[$]=P0(D,Q,X,E,C);else u[$]=await x0(D,Q,X,E,C)}return u}async function HF(D,F,B){if(!D.elements)return[];let E=[],u=c2(D,[],D.elements).filter(([$,X])=>X.elements&&Object.keys(X.elements).length>0);for(let[$,X]of u){let Q=H0(D,$,B),z;if(X.type==="BackboneElement"||!X.type)z={kind:"complex-type",package:B?.name||"hl7.fhir.r4.core",version:B?.version||"4.0.1",name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else z={kind:"complex-type",package:B?.name||"hl7.fhir.r4.core",version:B?.version||"4.0.1",name:X.type,url:`http://hl7.org/fhir/StructureDefinition/${X.type}`};let Y=await IB(D,$,X.elements,F,B),W={identifier:Q,base:z,fields:Y};E.push(W)}return E.sort(($,X)=>$.identifier.url.localeCompare(X.identifier.url)),E}function qF(D){let F=[];for(let B of D){if(F.push(B.identifier),B.base)F.push(B.base);for(let E of Object.values(B.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 WF(D,F,B,E,C){let u={};for(let[$,X]of Object.entries(B)){let Q=[...F,$],z=h2(D,Q,E),Y=z.length>0?g2(z):X;if(q0(Y))u[$]=P0(D,Q,Y,E,C);else u[$]=await x0(D,Q,Y,E,C)}return u}function O6(D){let F=[];for(let B of Object.values(D)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding)}return F}function Y6(D){let F=new Set,B=[];for(let E of D){let C=E.url;if(!F.has(C))F.add(C),B.push(E)}return B.sort((E,C)=>E.name.localeCompare(C.name)),B}function bB(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 TB(D,F,B){try{let E=PD(D,B);E.kind="value-set";let C={identifier:E,description:D.description};if(D.elements){let u=[];for(let[$,X]of Object.entries(D.elements))if("code"in X&&X.code)u.push({code:X.code,display:X.short||X.definition,system:X.system});if(u.length>0)C.concept=u}return C}catch(E){return console.warn(`Failed to transform value set ${D.name}: ${E}`),null}}async function xB(D,F,B){try{let E=PD(D,B),C;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;C={kind:"complex-type",package:B?.name||"hl7.fhir.r4.core",version:B?.version||"4.0.1",name:Q,url:X}}else C={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let u={identifier:E,base:C,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(C)u.dependencies.push(C);if(D.elements){let X=await WF(D,[],D.elements,F,B);if(Object.keys(X).length>0)u.fields=X,u.dependencies.push(...O6(X))}let $=await HF(D,F,B);if($.length>0)u.nested=$,u.dependencies.push(...qF($));return u.dependencies=Y6(u.dependencies),u.dependencies=u.dependencies.filter((X)=>X.url!==E.url),u}catch(E){return console.warn(`Failed to transform extension ${D.name}: ${E}`),null}}async function MF(D,F,B){let E=[];if(!B&&(D.package_name||D.package_id))B={name:D.package_name||D.package_id||"undefined",version:D.package_version||"undefined"};let C=PD(D,B);if(C.kind==="profile"){let z=await Z6(D,F,B);E.push(z);let Y=await GF(D,F,B);return E.push(...Y),E}if(C.kind==="value-set"||D.kind==="value-set"){let z=await TB(D,F,B);if(z)E.push(z);return E}if(bB(D,C)){let z=await xB(D,F,B);if(z)E.push(z);return E}let u;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/");u={kind:J,package:q?"hl7.fhir.r4.core":B?.name||D.package_name||"undefined",version:q?"4.0.1":B?.version||D.package_version||"undefined",name:Y,url:z}}let $={identifier:C,dependencies:[]},X=[];if(u)$.base=u,X.push(u);if(D.description)$.description=D.description;if(D.kind!=="primitive-type"&&D.elements){let z=await WF(D,[],D.elements,F,B);if(Object.keys(z).length>0)$.fields=z;X.push(...O6(z));let Y=await HF(D,F,B);if(Y.length>0)$.nested=Y,X.push(...qF(Y))}$.dependencies=X,$.dependencies=Y6($.dependencies),$.dependencies=$.dependencies.filter((z)=>z.url!==C.url),E.push($);let Q=await GF(D,F,B);return E.push(...Q),E}async function o2(D,F,B){let E=[];for(let C of D){let u=await MF(C,F,B);E.push(...u)}return E}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||JD({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 B=this.cacheConfig?.forceRegenerate??!1;if(this.cache&&!B){let J=this.cache.getByPackage(D);if(J.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${D} (${J.length} schemas)`),J}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({}),C=E.filter((J)=>J.resourceType==="StructureDefinition"),u=E.filter((J)=>J.resourceType==="ValueSet");this.logger.info(`Found ${C.length} StructureDefinitions and ${u.length} ValueSets in package`),this.logger.progress(`Converting ${C.length} StructureDefinitions to FHIRSchemas`);let $=this.applyStructureDefinitionTreeshaking(C),X=[],Q=0,z=0;for(let J of $)try{let q=d2(J);X.push(q),Q++,this.logger.debug(`Converted StructureDefinition: ${J.name||J.id} (${J.resourceType})`)}catch(q){z++,this.logger.warn(`Failed to convert StructureDefinition ${J.name||J.id}: ${q instanceof Error?q.message:String(q)}`)}if(this.logger.success(`Schema conversion completed: ${Q}/${$.length} successful, ${z} failed`),u.length>0)this.logger.debug(`${u.length} ValueSets available for enum extraction`);let Y={name:D,version:F||"latest"},W=await this.generateFromSchemas(X,Y);if(this.cache&&W.length>0){this.logger.info(`Caching ${W.length} generated schemas for package: ${D}`);for(let J of W)await this.cache.set(J);this.logger.success(`Cached ${W.length} TypeSchemas for package: ${D}`)}return W}async generateFromSchema(D,F){return this.logger.info("Transforming FHIR schema to TypeSchema"),MF(D,this.manager,F)}async generateFromSchemas(D,F){this.logger.info(`Transforming ${D.length} FHIR schemas to TypeSchema`);let B=await o2(D,this.manager,F),E=[],C=this.groupTypeSchemas(B);if(E.push(...C.resources),E.push(...C.complexTypes),E.push(...C.primitives),C.profiles.length>0){this.logger.info(`Enhancing ${C.profiles.length} profiles`);let u=await this.enhanceProfiles(C.profiles);E.push(...u)}if(C.extensions.length>0){this.logger.info(`Enhancing ${C.extensions.length} extensions`);let u=await this.enhanceExtensions(C.extensions);E.push(...u)}if(C.valueSets.length>0){this.logger.info(`Enhancing ${C.valueSets.length} value sets`);let u=await this.enhanceValueSets(C.valueSets);E.push(...u)}if(C.codeSystems.length>0){this.logger.info(`Enhancing ${C.codeSystems.length} code systems`);let u=await this.enhanceCodeSystems(C.codeSystems);E.push(...u)}return this.logger.success(`Generated ${E.length} enhanced FHIR type schemas: ${C.resources.length} resources, ${C.complexTypes.length} complex types, ${C.primitives.length} primitives`),E}groupTypeSchemas(D){let F={resources:[],complexTypes:[],primitives:[],profiles:[],extensions:[],valueSets:[],codeSystems:[]};for(let B of D)switch(B.identifier.kind){case"resource":F.resources.push(B);break;case"complex-type":F.complexTypes.push(B);break;case"primitive-type":F.primitives.push(B);break;case"binding":if("metadata"in B&&B.metadata?.isExtension)F.extensions.push(B);else F.complexTypes.push(B);break;case"value-set":F.valueSets.push(B);break;default:if("metadata"in B&&B.metadata?.isCodeSystem)F.codeSystems.push(B);else F.complexTypes.push(B);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 B=new Map,E=new Map,C=new Map;for(let z of D){let Y=z.name||z.id;if(Y)B.set(Y,z),E.set(Y,new Set),C.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)),C.set(Y,new Set(J))}let u=new Set;for(let z of F)if(B.has(z))u.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(B.has(J))u.add(J),$(J,Y)};for(let z of Array.from(u))$(z);let X=D.filter((z)=>{let Y=z.name||z.id;return Y&&u.has(Y)}),Q=new Set;for(let z of D){let Y=z.name||z.id;if(Y&&!u.has(Y)){if(Array.from(C.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,B=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 C of E)if(C.type)for(let u of C.type){if(u.code){if(F.add(u.code),u.code==="Reference"&&u.targetProfile)for(let $ of u.targetProfile){let X=this.extractResourceNameFromUrl($);if(X)B.add(X)}}if(u.profile)for(let $ of u.profile){let X=this.extractResourceNameFromUrl($);if(X)F.add(X)}}}return{realDeps:Array.from(F),refTargets:Array.from(B)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as PB}from"node:fs/promises";class M0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await PB(D,"utf-8"),B=this.options.format==="auto"?this.detectFormat(F,D):this.options.format;return this.parseFromString(F,B)}async parseFromString(D,F){let B=F||this.detectFormat(D),E;if(B==="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 B of D){let E=await this.parseFromFile(B);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((B)=>this.matchesIdentifier(B.identifier,F))}findByUrl(D,F){return D.find((B)=>B.identifier.url===F)}findByKind(D,F){return D.filter((B)=>B.identifier.kind===F)}findByPackage(D,F){return D.filter((B)=>B.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 B of Object.values(D.fields)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding);if("reference"in B&&B.reference)F.push(...B.reference)}if("nested"in D&&D.nested)for(let B of D.nested){F.push(B.identifier),F.push(B.base);for(let E of Object.values(B.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 B=D;if(F.push(B.valueset),B.type)F.push(B.type)}return this.deduplicateDependencies(F)}resolveDependencies(D,F){let B=this.getDependencies(F),E=[];for(let C of B){let u=this.findByUrl(D,C.url);if(u)E.push(u)}return E}detectFormat(D,F){if(F){if(F.endsWith(".ndjson"))return"ndjson";if(F.endsWith(".json"))return"json"}let B=D.trim();if(B.includes(`
85
+ `;class Q3{constructor(D,F,B,E){var C,u,$;this.yargs=D,this.usage=F,this.command=B,this.shim=E,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=($=((C=this.shim.getEnv("SHELL"))===null||C===void 0?void 0:C.includes("zsh"))||((u=this.shim.getEnv("ZSH_NAME"))===null||u===void 0?void 0:u.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,B,E){let C=this.command.getCommandHandlers();for(let $=0,X=D.length;$<X;++$)if(C[D[$]]&&C[D[$]].builder){let Q=C[D[$]].builder;if(g0(Q)){this.indexAfterLastReset=$+1;let z=this.yargs.getInternalMethods().reset();return Q(z,!0),z.argv}}let u=[];this.commandCompletions(u,D,B),this.optionCompletions(u,D,F,B),this.choicesFromOptionsCompletions(u,D,F,B),this.choicesFromPositionalsCompletions(u,D,F,B),E(null,u)}commandCompletions(D,F,B){let E=this.yargs.getInternalMethods().getContext().commands;if(!B.match(/^-/)&&E[E.length-1]!==B&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((C)=>{let u=kD(C[0]).cmd;if(F.indexOf(u)===-1)if(!this.zshShell)D.push(u);else{let $=C[1]||"";D.push(u.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,B,E){if((E.match(/^-/)||E===""&&D.length===0)&&!this.previousArgHasChoices(F)){let C=this.yargs.getOptions(),u=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(C.key).forEach(($)=>{let X=!!C.configuration["boolean-negation"]&&C.boolean.includes($);if(!u.includes($)&&!C.hiddenOptions.includes($)&&!this.argsContainKey(F,$,X))this.completeOptionKey($,D,E,X&&!!C.default[$])})}}choicesFromOptionsCompletions(D,F,B,E){if(this.previousArgHasChoices(F)){let C=this.getPreviousArgChoices(F);if(C&&C.length>0)D.push(...C.map((u)=>u.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,B,E){if(E===""&&D.length>0&&this.previousArgHasChoices(F))return;let C=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],u=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=C[B._.length-u-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],B="";if(!F.startsWith("-")&&D.length>1)B=F,F=D[D.length-2];if(!F.startsWith("-"))return;let E=F.replace(/^-+/,""),C=this.yargs.getOptions(),u=[E,...this.yargs.getAliases()[E]||[]],$;for(let X of u)if(Object.prototype.hasOwnProperty.call(C.key,X)&&Array.isArray(C.choices[X])){$=C.choices[X];break}if($)return $.filter((X)=>!B||X.startsWith(B))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,B){let E=(C)=>D.indexOf((/^[^0-9]$/.test(C)?"-":"--")+C)!==-1;if(E(F))return!0;if(B&&E(`no-${F}`))return!0;if(this.aliases){for(let C of this.aliases[F])if(E(C))return!0}return!1}completeOptionKey(D,F,B,E){var C,u,$,X;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),q=(u=(C=this===null||this===void 0?void 0:this.aliases)===null||C===void 0?void 0:C[D])===null||u===void 0?void 0:u.find((I)=>{let g=J[I];return typeof g==="string"&&g.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(B)&&Y(D)?"-":"--";if(F.push(W+Q),E)F.push(W+"no-"+Q)}customCompletion(D,F,B,E){if(YD(this.customCompletionFunction,null,this.shim),h8(this.customCompletionFunction)){let C=this.customCompletionFunction(B,F);if(s(C))return C.then((u)=>{this.shim.process.nextTick(()=>{E(null,u)})}).catch((u)=>{this.shim.process.nextTick(()=>{E(u,void 0)})});return E(null,C)}else if(g8(this.customCompletionFunction))return this.customCompletionFunction(B,F,(C=E)=>this.defaultCompletion(D,F,B,C),(C)=>{E(null,C)});else return this.customCompletionFunction(B,F,(C)=>{E(null,C)})}getCompletion(D,F){let B=D.length?D[D.length-1]:"",E=this.yargs.parse(D,!0),C=this.customCompletionFunction?(u)=>this.customCompletion(D,u,B,F):(u)=>this.defaultCompletion(D,u,B,F);return s(E)?E.then(C):C(E)}generateCompletionScript(D,F){let B=this.zshShell?Z3:X3,E=this.shim.path.basename(D);if(D.match(/\.js$/))D=`./${D}`;return B=B.replace(/{{app_name}}/g,E),B=B.replace(/{{completion_command}}/g,F),B.replace(/{{app_path}}/g,D)}registerFunction(D){this.customCompletionFunction=D}setParsed(D){this.aliases=D.aliases}}function z3(D,F,B,E){return new Q3(D,F,B,E)}function h8(D){return D.length<3}function g8(D){return D.length>3}function O3(D,F){if(D.length===0)return F.length;if(F.length===0)return D.length;let B=[],E;for(E=0;E<=F.length;E++)B[E]=[E];let C;for(C=0;C<=D.length;C++)B[0][C]=C;for(E=1;E<=F.length;E++)for(C=1;C<=D.length;C++)if(F.charAt(E-1)===D.charAt(C-1))B[E][C]=B[E-1][C-1];else if(E>1&&C>1&&F.charAt(E-2)===D.charAt(C-1)&&F.charAt(E-1)===D.charAt(C-2))B[E][C]=B[E-2][C-2]+1;else B[E][C]=Math.min(B[E-1][C-1]+1,Math.min(B[E][C-1]+1,B[E-1][C]+1));return B[F.length][D.length]}var Y3=["$0","--","_"];function J3(D,F,B){let E=B.y18n.__,C=B.y18n.__n,u={};u.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(C("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(C("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()))}},u.positionalCount=function Y(W,J){if(J<W)F.fail(C("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+""))},u.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 I of Object.keys(q)){let g=q[I];if(g&&M.indexOf(g)<0)M.push(g)}let G=M.length?`
86
+ ${M.join(`
87
+ `)}`:"";F.fail(C("Missing required argument: %s","Missing required arguments: %s",Object.keys(q).length,Object.keys(q).join(", ")+G))}},u.unknownArguments=function Y(W,J,q,M,G=!0){var I;let g=D.getInternalMethods().getCommandInstance().getCommands(),p=[],QD=D.getInternalMethods().getContext();if(Object.keys(W).forEach((V)=>{if(!Y3.includes(V)&&!Object.prototype.hasOwnProperty.call(q,V)&&!Object.prototype.hasOwnProperty.call(D.getInternalMethods().getParseContext(),V)&&!u.isValidAndSomeAliasIsNotNew(V,J))p.push(V)}),G&&(QD.commands.length>0||g.length>0||M))W._.slice(QD.commands.length).forEach((V)=>{if(!g.includes(""+V))p.push(""+V)});if(G){let L=((I=D.getDemandedCommands()._)===null||I===void 0?void 0:I.max)||0,k=QD.commands.length+L;if(k<W._.length)W._.slice(k).forEach((d)=>{if(d=String(d),!QD.commands.includes(d)&&!p.includes(d))p.push(d)})}if(p.length)F.fail(C("Unknown argument: %s","Unknown arguments: %s",p.length,p.map((V)=>V.trim()?V:`"${V}"`).join(", ")))},u.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(C("Unknown command: %s","Unknown commands: %s",q.length,q.join(", "))),!0;else return!1},u.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])},u.limitedChoices=function Y(W){let J=D.getOptions(),q={};if(!Object.keys(J.choices).length)return;Object.keys(W).forEach((I)=>{if(Y3.indexOf(I)===-1&&Object.prototype.hasOwnProperty.call(J.choices,I))[].concat(W[I]).forEach((g)=>{if(J.choices[I].indexOf(g)===-1&&g!==void 0)q[I]=(q[I]||[]).concat(g)})});let M=Object.keys(q);if(!M.length)return;let G=E("Invalid values:");M.forEach((I)=>{G+=`
88
+ ${E("Argument: %s, Given: %s, Choices: %s",I,F.stringifiedValues(q[I]),F.stringifiedValues(J.choices[I]))}`}),F.fail(G)};let $={};u.implies=function Y(W,J){if(N("<string|object> [array|number|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{u.implies(q,W[q])});else{if(D.global(W),!$[W])$[W]=[];if(Array.isArray(J))J.forEach((q)=>u.implies(W,q));else YD(J,void 0,B),$[W].push(J)}},u.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}u.implications=function Y(W){let J=[];if(Object.keys($).forEach((q)=>{let M=q;($[q]||[]).forEach((G)=>{let I=M,g=G;if(I=X(W,I),G=X(W,G),I&&!G)J.push(` ${M} -> ${g}`)})}),J.length){let q=`${E("Implications failed:")}
89
+ `;J.forEach((M)=>{q+=M}),F.fail(q)}};let Q={};u.conflicts=function Y(W,J){if(N("<string|object> [array|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{u.conflicts(q,W[q])});else{if(D.global(W),!Q[W])Q[W]=[];if(Array.isArray(J))J.forEach((q)=>u.conflicts(W,q));else Q[W].push(J)}},u.getConflicting=()=>Q,u.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[B.Parser.camelCase(J)]!==void 0&&W[B.Parser.camelCase(q)]!==void 0)F.fail(E("Arguments %s and %s are mutually exclusive",J,q))})})},u.recommendCommands=function Y(W,J){J=J.sort((I,g)=>g.length-I.length);let M=null,G=1/0;for(let I=0,g;(g=J[I])!==void 0;I++){let p=O3(W,g);if(p<=3&&p<G)G=p,M=g}if(M)F.fail(E("Did you mean %s?",M))},u.reset=function Y(W){return $=fD($,(J)=>!W[J]),Q=fD(Q,(J)=>!W[J]),u};let z=[];return u.freeze=function Y(){z.push({implied:$,conflicting:Q})},u.unfreeze=function Y(){let W=z.pop();YD(W,void 0,B),{implied:$,conflicting:Q}=W},u}var rF=[],N0;function j0(D,F,B,E){N0=E;let C={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return C;let u=/\.json|\..*rc$/.test(D.extends),$=null;if(!u)try{$=import.meta.resolve(D.extends)}catch(X){return D}else $=m8(F,D.extends);p8($),rF.push($),C=u?JSON.parse(N0.readFileSync($,"utf8")):E.require(D.extends),delete D.extends,C=j0(C,N0.path.dirname($),B,N0)}return rF=[],B?W3(C,D):Object.assign({},C,D)}function p8(D){if(rF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function m8(D,F){return N0.path.resolve(D,F)}function W3(D,F){let B={};function E(C){return C&&typeof C==="object"&&!Array.isArray(C)}Object.assign(B,D);for(let C of Object.keys(F))if(E(F[C])&&E(B[C]))B[C]=W3(D[C],F[C]);else B[C]=F[C];return B}var j=function(D,F,B,E,C){if(E==="m")throw new TypeError("Private method is not writable");if(E==="a"&&!C)throw new TypeError("Private accessor was defined without a setter");if(typeof F==="function"?D!==F||!C:!F.has(D))throw new TypeError("Cannot write private member to an object whose class did not declare it");return E==="a"?C.call(D,B):C?C.value=B:F.set(D,B),B},Z=function(D,F,B,E){if(B==="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 B==="m"?E:B==="a"?E.call(D):E?E.value:F.get(D)},FD,iD,w0,WD,GD,m0,dD,tD,l0,_D,c0,KD,wD,HD,VD,o0,sD,ZD,x,n0,i0,qD,rD,Y0,aD,hD,t0,f,eD,D0,F0,h,s0,ID,a;function S3(D){return(F=[],B=D.process.cwd(),E)=>{let C=new v3(F,B,E,D);return Object.defineProperty(C,"argv",{get:()=>{return C.parse()},enumerable:!0}),C.help(),C.version(),C}}var A3=Symbol("copyDoubleDash"),G3=Symbol("copyDoubleDash"),aF=Symbol("deleteFromParserHintObject"),H3=Symbol("emitWarning"),q3=Symbol("freeze"),M3=Symbol("getDollarZero"),B0=Symbol("getParserConfiguration"),_3=Symbol("getUsageConfiguration"),eF=Symbol("guessLocale"),K3=Symbol("guessVersion"),V3=Symbol("parsePositionalNumbers"),D2=Symbol("pkgUp"),gD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),F2=Symbol("populateParserHintArrayDictionary"),B2=Symbol("populateParserHintDictionary"),E2=Symbol("sanitizeKey"),C2=Symbol("setKey"),u2=Symbol("unfreeze"),R3=Symbol("validateAsync"),U3=Symbol("getCommandInstance"),L3=Symbol("getContext"),N3=Symbol("getHasOutput"),j3=Symbol("getLoggerInstance"),w3=Symbol("getParseContext"),I3=Symbol("getUsageInstance"),T3=Symbol("getValidationInstance"),r0=Symbol("hasParseCallback"),b3=Symbol("isGlobalContext"),E0=Symbol("postProcess"),x3=Symbol("rebase"),$2=Symbol("reset"),I0=Symbol("runYargsParserAndExecuteCommands"),X2=Symbol("runValidation"),P3=Symbol("setHasOutput"),C0=Symbol("kTrackManuallySetKeys"),l8="en_US";class v3{constructor(D=[],F,B,E){this.customScriptName=!1,this.parsed=!1,FD.set(this,void 0),iD.set(this,void 0),w0.set(this,{commands:[],fullCommands:[]}),WD.set(this,null),GD.set(this,null),m0.set(this,"show-hidden"),dD.set(this,null),tD.set(this,!0),l0.set(this,{}),_D.set(this,!0),c0.set(this,[]),KD.set(this,void 0),wD.set(this,{}),HD.set(this,!1),VD.set(this,null),o0.set(this,!0),sD.set(this,void 0),ZD.set(this,""),x.set(this,void 0),n0.set(this,void 0),i0.set(this,{}),qD.set(this,null),rD.set(this,null),Y0.set(this,{}),aD.set(this,{}),hD.set(this,void 0),t0.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),s0.set(this,{}),ID.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,n0,B,"f"),j(this,KD,new tF(this),"f"),this.$0=this[M3](),this[$2](),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,m0,"f"),j(this,sD,this[G3](),"f"),Z(this,f,"f").y18n.setLocale(l8)}addHelpOpt(D,F){if(N("[string|boolean] [string]",[D,F],arguments.length),Z(this,VD,"f"))this[aF](Z(this,VD,"f")),j(this,VD,null,"f");if(D===!1&&F===void 0)return this;return j(this,VD,typeof D==="string"?D:"help","f"),this.boolean(Z(this,VD,"f")),this.describe(Z(this,VD,"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 B=typeof D==="string"?D:Z(this,m0,"f");return this.boolean(B),this.describe(B,F||Z(this,h,"f").deferY18nLookup("Show hidden options")),Z(this,x,"f").showHiddenOpt=B,this}showHidden(D,F){return this.addShowHiddenOpt(D,F)}alias(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[F2](this.alias.bind(this),"alias",D,F),this}array(D){return N("<array|string>",[D],arguments.length),this[gD]("array",D),this[C0](D),this}boolean(D){return N("<array|string>",[D],arguments.length),this[gD]("boolean",D),this[C0](D),this}check(D,F){return N("<function> [boolean]",[D,F],arguments.length),this.middleware((B,E)=>{return nD(()=>{return D(B,E.getOptions())},(C)=>{if(!C)Z(this,h,"f").fail(Z(this,f,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof C==="string"||C instanceof Error)Z(this,h,"f").fail(C.toString(),C);return B},(C)=>{return Z(this,h,"f").fail(C.message?C.message:C.toString(),C),B})},!1,F),this}choices(D,F){return N("<object|string|array> [string|array]",[D,F],arguments.length),this[F2](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 B=D;return Z(this,x,"f").key[B]=!0,Z(this,KD,"f").addCoerceMiddleware((E,C)=>{var u;let $=(u=C.getAliases()[B])!==null&&u!==void 0?u:[],X=[B,...$].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)})},B),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,B){if(N("[object|string] [string|function] [function]",[D,F,B],arguments.length),typeof D==="object"&&!Array.isArray(D))return D=j0(D,Z(this,iD,"f"),this[B0]()["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")B=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]=B||!0}),this}completion(D,F,B){if(N("[string] [string|boolean|function] [function]",[D,F,B],arguments.length),typeof F==="function")B=F,F=void 0;if(j(this,GD,D||Z(this,GD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(Z(this,GD,"f"),F),B)Z(this,WD,"f").registerFunction(B);return this}command(D,F,B,E,C,u){return N("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,B,E,C,u],arguments.length),Z(this,FD,"f").addHandler(D,F,B,E,C,u),this}commands(D,F,B,E,C,u){return this.command(D,F,B,E,C,u)}commandDir(D,F){N("<string> [object]",[D,F],arguments.length);let B=Z(this,n0,"f")||Z(this,f,"f").require;return Z(this,FD,"f").addDirectory(D,B,Z(this,f,"f").getCallerFile(),F),this}count(D){return N("<array|string>",[D],arguments.length),this[gD]("count",D),this[C0](D),this}default(D,F,B){if(N("<object|string|array> [*] [string]",[D,F,B],arguments.length),B)iF(D,Z(this,f,"f")),Z(this,x,"f").defaultDescription[D]=B;if(typeof F==="function"){if(iF(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,B){return this.default(D,F,B)}demandCommand(D=1,F,B,E){if(N("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,B,E],arguments.length),typeof F!=="number")B=F,F=1/0;return this.global("_",!1),Z(this,x,"f").demandedCommands._={min:D,max:F,minMsg:B,maxMsg:E},this}demand(D,F,B){if(Array.isArray(F))F.forEach((E)=>{YD(B,!0,Z(this,f,"f")),this.demandOption(E,B)}),F=1/0;else if(typeof F!=="number")B=F,F=1/0;if(typeof D==="number")YD(B,!0,Z(this,f,"f")),this.demandCommand(D,F,B,B);else if(Array.isArray(D))D.forEach((E)=>{YD(B,!0,Z(this,f,"f")),this.demandOption(E,B)});else if(typeof B==="string")this.demandOption(D,B);else if(B===!0||typeof B==="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[C2](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((B)=>this.example(...B));else Z(this,h,"f").example(D,F);return this}exit(D,F){if(j(this,HD,!0,"f"),j(this,dD,F,"f"),Z(this,_D,"f"))Z(this,f,"f").process.exit(D)}exitProcess(D=!0){return N("[boolean]",[D],arguments.length),j(this,_D,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((B,E)=>{Z(this,WD,"f").getCompletion(D,(C,u)=>{if(C)E(C);else B(u)})});else return Z(this,WD,"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,_D,"f")}getGroups(){return Object.assign({},Z(this,wD,"f"),Z(this,aD,"f"))}getHelp(){if(j(this,HD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[I0](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((B)=>D.indexOf(B)===-1);else D.forEach((B)=>{if(!Z(this,x,"f").local.includes(B))Z(this,x,"f").local.push(B)});return this}group(D,F){N("<string|array> <string>",[D,F],arguments.length);let B=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]=(B||[]).concat(D).filter((C)=>{if(E[C])return!1;return E[C]=!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[eF](),Z(this,f,"f").y18n.getLocale();return j(this,tD,!1,"f"),Z(this,f,"f").y18n.setLocale(D),this}middleware(D,F,B){return Z(this,KD,"f").addMiddleware(D,!!F,B)}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[gD]("normalize",D),this}number(D){return N("<array|string>",[D],arguments.length),this[gD]("number",D),this[C0](D),this}option(D,F){if(N("<string|object> [object]",[D,F],arguments.length),typeof D==="object")Object.keys(D).forEach((B)=>{this.options(B,D[B])});else{if(typeof F!=="object")F={};if(this[C0](D),Z(this,ID,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[H3](['"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 B=F.deprecate||F.deprecated;if(B)this.deprecateOption(D,B);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 C=F.describe||F.description||F.desc,u=Z(this,h,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(u,D)||typeof C==="string")this.describe(D,C);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,B){if(N("[string|array] [function|boolean|object] [function]",[D,F,B],arguments.length),this[q3](),typeof D==="undefined")D=Z(this,hD,"f");if(typeof F==="object")j(this,rD,F,"f"),F=B;if(typeof F==="function")j(this,qD,F,"f"),F=!1;if(!F)j(this,hD,D,"f");if(Z(this,qD,"f"))j(this,_D,!1,"f");let E=this[I0](D,!!F),C=this.parsed;if(Z(this,WD,"f").setParsed(this.parsed),s(E))return E.then((u)=>{if(Z(this,qD,"f"))Z(this,qD,"f").call(this,Z(this,dD,"f"),u,Z(this,ZD,"f"));return u}).catch((u)=>{if(Z(this,qD,"f"))Z(this,qD,"f")(u,this.parsed.argv,Z(this,ZD,"f"));throw u}).finally(()=>{this[u2](),this.parsed=C});else{if(Z(this,qD,"f"))Z(this,qD,"f").call(this,Z(this,dD,"f"),E,Z(this,ZD,"f"));this[u2](),this.parsed=C}return E}parseAsync(D,F,B){let E=this.parse(D,F,B);return!s(E)?Promise.resolve(E):E}parseSync(D,F,B){let E=this.parse(D,F,B);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,i0,D,"f"),this}pkgConf(D,F){N("<string> [string]",[D,F],arguments.length);let B=null,E=this[D2](F||Z(this,iD,"f"));if(E[D]&&typeof E[D]==="object")B=j0(E[D],F||Z(this,iD,"f"),this[B0]()["deep-merge-config"]||!1,Z(this,f,"f")),Z(this,x,"f").configObjects=(Z(this,x,"f").configObjects||[]).concat(B);return this}positional(D,F){N("<string> <object>",[D,F],arguments.length);let B=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];F=fD(F,(u,$)=>{if(u==="type"&&!["string","number","boolean"].includes($))return!1;return B.includes(u)});let E=Z(this,w0,"f").fullCommands[Z(this,w0,"f").fullCommands.length-1],C=E?Z(this,FD,"f").cmdToParseOptions(E):{array:[],alias:{},default:{},demand:{}};return z0(C).forEach((u)=>{let $=C[u];if(Array.isArray($)){if($.indexOf(D)!==-1)F[u]=!0}else if($[D]&&!(u in F))F[u]=$[D]}),this.group(D,Z(this,h,"f").getPositionalGroupName()),this.option(D,F)}recommendCommands(D=!0){return N("[boolean]",[D],arguments.length),j(this,t0,D,"f"),this}required(D,F,B){return this.demand(D,F,B)}require(D,F,B){return this.demand(D,F,B)}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,WD,"f").generateCompletionScript(D,F||Z(this,GD,"f")||"completion")),this}showHelp(D){if(N("[string|function]",[D],arguments.length),j(this,HD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let B=this[I0](Z(this,hD,"f"),void 0,void 0,0,!0);if(s(B))return B.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[gD]("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[gD]("string",D),this[C0](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,B,E){if(N("<string|null|undefined> [string|boolean] [function|object] [function]",[D,F,B,E],arguments.length),F!==void 0)if(YD(D,null,Z(this,f,"f")),(D||"").match(/^\$0( |$)/))return this.command(D,F,B,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,s0,D,"f"),this}version(D,F,B){if(N("[boolean|string] [string] [string]",[D,F,B],arguments.length),Z(this,ID,"f"))this[aF](Z(this,ID,"f")),Z(this,h,"f").version(void 0),j(this,ID,null,"f");if(arguments.length===0)B=this[K3](),D="version";else if(arguments.length===1){if(D===!1)return this;B=D,D="version"}else if(arguments.length===2)B=F,F=void 0;return j(this,ID,typeof D==="string"?D:"version","f"),F=F||Z(this,h,"f").deferY18nLookup("Show version number"),Z(this,h,"f").version(B||void 0),this.boolean(Z(this,ID,"f")),this.describe(Z(this,ID,"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,w0=new WeakMap,WD=new WeakMap,GD=new WeakMap,m0=new WeakMap,dD=new WeakMap,tD=new WeakMap,l0=new WeakMap,_D=new WeakMap,c0=new WeakMap,KD=new WeakMap,wD=new WeakMap,HD=new WeakMap,VD=new WeakMap,o0=new WeakMap,sD=new WeakMap,ZD=new WeakMap,x=new WeakMap,n0=new WeakMap,i0=new WeakMap,qD=new WeakMap,rD=new WeakMap,Y0=new WeakMap,aD=new WeakMap,hD=new WeakMap,t0=new WeakMap,f=new WeakMap,eD=new WeakMap,D0=new WeakMap,F0=new WeakMap,h=new WeakMap,s0=new WeakMap,ID=new WeakMap,a=new WeakMap,A3)](D){if(!D._||!D["--"])return D;D._.push.apply(D._,D["--"]);try{delete D["--"]}catch(F){}return D}[G3](){return{log:(...D)=>{if(!this[r0]())console.log(...D);if(j(this,HD,!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[r0]())console.error(...D);if(j(this,HD,!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")}}}[aF](D){z0(Z(this,x,"f")).forEach((F)=>{if(((E)=>E==="configObjects")(F))return;let B=Z(this,x,"f")[F];if(Array.isArray(B)){if(B.includes(D))B.splice(B.indexOf(D),1)}else if(typeof B==="object")delete B[D]}),delete Z(this,h,"f").getDescriptions()[D]}[H3](D,F,B){if(!Z(this,l0,"f")[B])Z(this,f,"f").process.emitWarning(D,F),Z(this,l0,"f")[B]=!0}[q3](){Z(this,c0,"f").push({options:Z(this,x,"f"),configObjects:Z(this,x,"f").configObjects.slice(0),exitProcess:Z(this,_D,"f"),groups:Z(this,wD,"f"),strict:Z(this,eD,"f"),strictCommands:Z(this,D0,"f"),strictOptions:Z(this,F0,"f"),completionCommand:Z(this,GD,"f"),output:Z(this,ZD,"f"),exitError:Z(this,dD,"f"),hasOutput:Z(this,HD,"f"),parsed:this.parsed,parseFn:Z(this,qD,"f"),parseContext:Z(this,rD,"f")}),Z(this,h,"f").freeze(),Z(this,a,"f").freeze(),Z(this,FD,"f").freeze(),Z(this,KD,"f").freeze()}[M3](){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((B)=>{let E=this[x3](Z(this,iD,"f"),B);return B.match(/^(\/|([a-zA-Z]:)?\\)/)&&E.length<B.length?E:B}).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}[B0](){return Z(this,i0,"f")}[_3](){return Z(this,s0,"f")}[eF](){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(/[.:].*/,""))}[K3](){return this[D2]().version||"unknown"}[V3](D){let F=D["--"]?D["--"]:D._;for(let B=0,E;(E=F[B])!==void 0;B++)if(Z(this,f,"f").Parser.looksLikeNumber(E)&&Number.isSafeInteger(Math.floor(parseFloat(`${E}`))))F[B]=Number(E);return D}[D2](D){let F=D||"*";if(Z(this,Y0,"f")[F])return Z(this,Y0,"f")[F];let B={};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 C=Z(this,f,"f").findUp(E,(u,$)=>{if($.includes("package.json"))return"package.json";else return});YD(C,void 0,Z(this,f,"f")),B=JSON.parse(Z(this,f,"f").readFileSync(C,"utf8"))}catch(E){}return Z(this,Y0,"f")[F]=B||{},Z(this,Y0,"f")[F]}[gD](D,F){F=[].concat(F),F.forEach((B)=>{B=this[E2](B),Z(this,x,"f")[D].push(B)})}[J0](D,F,B,E){this[B2](D,F,B,E,(C,u,$)=>{Z(this,x,"f")[C][u]=$})}[F2](D,F,B,E){this[B2](D,F,B,E,(C,u,$)=>{Z(this,x,"f")[C][u]=(Z(this,x,"f")[C][u]||[]).concat($)})}[B2](D,F,B,E,C){if(Array.isArray(B))B.forEach((u)=>{D(u,E)});else if(((u)=>typeof u==="object")(B))for(let u of z0(B))D(u,B[u]);else C(F,this[E2](B),E)}[E2](D){if(D==="__proto__")return"___proto___";return D}[C2](D,F){return this[J0](this[C2].bind(this),"key",D,F),this}[u2](){var D,F,B,E,C,u,$,X,Q,z,Y,W;let J=Z(this,c0,"f").pop();YD(J,void 0,Z(this,f,"f"));let q;D=this,F=this,B=this,E=this,C=this,u=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,_D,M,"f")}}.value,groups:{set value(M){j(B,wD,M,"f")}}.value,output:{set value(M){j(E,ZD,M,"f")}}.value,exitError:{set value(M){j(C,dD,M,"f")}}.value,hasOutput:{set value(M){j(u,HD,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,GD,M,"f")}}.value,parseFn:{set value(M){j(Y,qD,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,KD,"f").unfreeze()}[R3](D,F){return nD(F,(B)=>{return D(B),B})}getInternalMethods(){return{getCommandInstance:this[U3].bind(this),getContext:this[L3].bind(this),getHasOutput:this[N3].bind(this),getLoggerInstance:this[j3].bind(this),getParseContext:this[w3].bind(this),getParserConfiguration:this[B0].bind(this),getUsageConfiguration:this[_3].bind(this),getUsageInstance:this[I3].bind(this),getValidationInstance:this[T3].bind(this),hasParseCallback:this[r0].bind(this),isGlobalContext:this[b3].bind(this),postProcess:this[E0].bind(this),reset:this[$2].bind(this),runValidation:this[X2].bind(this),runYargsParserAndExecuteCommands:this[I0].bind(this),setHasOutput:this[P3].bind(this)}}[U3](){return Z(this,FD,"f")}[L3](){return Z(this,w0,"f")}[N3](){return Z(this,HD,"f")}[j3](){return Z(this,sD,"f")}[w3](){return Z(this,rD,"f")||{}}[I3](){return Z(this,h,"f")}[T3](){return Z(this,a,"f")}[r0](){return!!Z(this,qD,"f")}[b3](){return Z(this,o0,"f")}[E0](D,F,B,E){if(B)return D;if(s(D))return D;if(!F)D=this[A3](D);if(this[B0]()["parse-positional-numbers"]||this[B0]()["parse-positional-numbers"]===void 0)D=this[V3](D);if(E)D=oD(D,this,Z(this,KD,"f").getMiddleware(),!1);return D}[$2](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 B={};F.local.forEach((u)=>{B[u]=!0,(D[u]||[]).forEach(($)=>{B[$]=!0})}),Object.assign(Z(this,aD,"f"),Object.keys(Z(this,wD,"f")).reduce((u,$)=>{let X=Z(this,wD,"f")[$].filter((Q)=>!(Q in B));if(X.length>0)u[$]=X;return u},{})),j(this,wD,{},"f");let E=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],C=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(E.forEach((u)=>{F[u]=(Z(this,x,"f")[u]||[]).filter(($)=>!B[$])}),C.forEach((u)=>{F[u]=fD(Z(this,x,"f")[u],($)=>!B[$])}),F.envPrefix=Z(this,x,"f").envPrefix,j(this,x,F,"f"),j(this,h,Z(this,h,"f")?Z(this,h,"f").reset(B):$3(this,Z(this,f,"f")),"f"),j(this,a,Z(this,a,"f")?Z(this,a,"f").reset(B):J3(this,Z(this,h,"f"),Z(this,f,"f")),"f"),j(this,FD,Z(this,FD,"f")?Z(this,FD,"f").reset():E3(Z(this,h,"f"),Z(this,a,"f"),Z(this,KD,"f"),Z(this,f,"f")),"f"),!Z(this,WD,"f"))j(this,WD,z3(this,Z(this,h,"f"),Z(this,FD,"f"),Z(this,f,"f")),"f");return Z(this,KD,"f").reset(),j(this,GD,null,"f"),j(this,ZD,"","f"),j(this,dD,null,"f"),j(this,HD,!1,"f"),this.parsed=!1,this}[x3](D,F){return Z(this,f,"f").path.relative(D,F)}[I0](D,F,B,E=0,C=!1){var u,$,X,Q;let z=!!B||C;D=D||Z(this,hD,"f"),Z(this,x,"f").__=Z(this,f,"f").y18n.__,Z(this,x,"f").configuration=this[B0]();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,I=!1,g=!1;if(Object.keys(q).forEach((p)=>{if(p===Z(this,VD,"f")&&q[p])I=!0;else if(p===Z(this,ID,"f")&&q[p])g=!0}),q.$0=this.$0,this.parsed=J,E===0)Z(this,h,"f").clearCachedHelpMessage();try{if(this[eF](),F)return this[E0](q,Y,!!B,!1);if(Z(this,VD,"f")){if([Z(this,VD,"f")].concat(G[Z(this,VD,"f")]||[]).filter((k)=>k.length>1).includes(""+q._[q._.length-1]))q._.pop(),I=!0}j(this,o0,!1,"f");let p=Z(this,FD,"f").getCommands(),QD=((u=Z(this,WD,"f"))===null||u===void 0?void 0:u.completionKey)?[($=Z(this,WD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(X=Z(this,WD,"f"))===null||X===void 0?void 0:X.completionKey])!==null&&Q!==void 0?Q:[]].some((L)=>Object.prototype.hasOwnProperty.call(q,L)):!1,V=I||QD||C;if(q._.length){if(p.length){let L;for(let k=E||0,d;q._[k]!==void 0;k++)if(d=String(q._[k]),p.includes(d)&&d!==Z(this,GD,"f")){let t=Z(this,FD,"f").runCommand(d,this,J,k+1,C,I||g||C);return this[E0](t,Y,!!B,!1)}else if(!L&&d!==Z(this,GD,"f")){L=d;break}if(!Z(this,FD,"f").hasDefaultCommand()&&Z(this,t0,"f")&&L&&!V)Z(this,a,"f").recommendCommands(L,p)}if(Z(this,GD,"f")&&q._.includes(Z(this,GD,"f"))&&!QD){if(Z(this,_D,"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,C,I||g||C);return this[E0](L,Y,!!B,!1)}if(QD){if(Z(this,_D,"f"))yD(!0);D=[].concat(D);let L=D.slice(D.indexOf(`--${Z(this,WD,"f").completionKey}`)+1);return Z(this,WD,"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,!!B,!1)}if(!Z(this,HD,"f")){if(I){if(Z(this,_D,"f"))yD(!0);z=!0,this.showHelp((L)=>{Z(this,sD,"f").log(L),this.exit(0)})}else if(g){if(Z(this,_D,"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[X2](G,{},J.error);if(!B)M=oD(q,this,Z(this,KD,"f").getMiddleware(),!0);if(M=this[R3](L,M!==null&&M!==void 0?M:q),s(M)&&!B)M=M.then(()=>{return oD(q,this,Z(this,KD,"f").getMiddleware(),!1)})}}}catch(p){if(p instanceof DD)Z(this,h,"f").fail(p.message,p);else throw p}return this[E0](M!==null&&M!==void 0?M:q,Y,!!B,!0)}[X2](D,F,B,E){let C={...this.getDemandedOptions()};return(u)=>{if(B)throw new DD(B.message);Z(this,a,"f").nonOptionCount(u),Z(this,a,"f").requiredArguments(u,C);let $=!1;if(Z(this,D0,"f"))$=Z(this,a,"f").unknownCommands(u);if(Z(this,eD,"f")&&!$)Z(this,a,"f").unknownArguments(u,D,F,!!E);else if(Z(this,F0,"f"))Z(this,a,"f").unknownArguments(u,D,{},!1,!1);Z(this,a,"f").limitedChoices(u),Z(this,a,"f").implications(u),Z(this,a,"f").conflicting(u)}}[P3](){j(this,HD,!0,"f")}[C0](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 C3(D){return!!D&&typeof D.getInternalMethods==="function"}var c8=S3(nF),k3=c8;import{performance as d3}from"node:perf_hooks";var pD=k0(Q2(),1);class t8{total;message;current=0;barLength=30;startTime=d3.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(d3.now()-this.startTime);console.log(pD.default.green(`✅ ${D||this.message} ${pD.default.gray(`(${F}ms)`)}`))}render(D){let F=Math.round(this.current/this.total*100),B=Math.round(this.current/this.total*this.barLength),E=this.barLength-B,C=pD.default.green("█".repeat(B))+pD.default.gray("░".repeat(E)),u=`${this.current}/${this.total}`,$=D?pD.default.gray(` ${D}`):"";if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(`${this.message} ${C} ${pD.default.cyan(u)} ${pD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
93
+ `)}}var $D=k0(Q2(),1);class DF{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,B){let E=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",C=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${E}${B(D)} ${C}${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=(B)=>B){let B=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${B}${E}${F(D)}`)}dim(D){this.plain(D,$D.default.gray)}child(D){return new DF({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${D}`:D})}configure(D){this.options={...this.options,...D}}}var u0=new DF;function FF(D){u0.success(D)}function RD(D,F){u0.error(D,F)}function z2(D){u0.warn(D)}function BF(D){u0.info(D)}function O2(D){u0.step(D)}function h3(D){u0.dim(D)}function Y2(D){u0.configure(D)}function JD(D={}){return new DF(D)}function J2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function W2(D,F,B){let E=D;if(F)E+=` ${$D.default.gray(`(${F}ms)`)}`;if(FF(E),B)Object.entries(B).forEach(([C,u])=>{h3(` ${C}: ${u}`)})}function $0(D,F="•"){D.forEach((B)=>{console.log($D.default.gray(` ${F} ${B}`))})}import{existsSync as sB}from"node:fs";import{resolve as rB}from"node:path";import{existsSync as EF,mkdirSync as g3}from"node:fs";import{readdir as p3,readFile as s8,stat as r8,unlink as m3,writeFile as a8}from"node:fs/promises";import{join as A2}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,B]of this.cache.entries())if(B.identifier.url===D)return this.cache.delete(F);return!1}getByPackage(D){let F=[];for(let B of this.cache.values())if(B.identifier.package===D)F.push(B);return F}getByKind(D){let F=[];for(let B of this.cache.values())if(B.identifier.kind===D)F.push(B);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(!EF(this.cacheDir))g3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!EF(this.cacheDir))return;try{let F=(await p3(this.cacheDir)).filter((B)=>B.endsWith(".typeschema.json"));for(let B of F){let E=A2(this.cacheDir,B),C=await r8(E);if(this.config.maxAge){if(Date.now()-C.mtimeMs>this.config.maxAge){await m3(E);continue}}try{let u=await s8(E,"utf-8"),$=JSON.parse(u);if(this.config.validateCached){if(!$.schema?.identifier)continue}let X=this.generateKey($.schema.identifier);this.cache.set(X,$.schema)}catch(u){console.warn(`Failed to load cached schema from ${B}:`,u)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!EF(this.cacheDir))g3(this.cacheDir,{recursive:!0});let F={schema:D,timestamp:Date.now(),version:D.identifier.version},B=`${D.identifier.package}-${D.identifier.version}-${D.identifier.kind}-${D.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),E=A2(this.cacheDir,B);try{await a8(E,JSON.stringify(F,null,2),"utf-8")}catch(C){console.warn(`Failed to persist schema to ${E}:`,C)}}async clearDisk(){if(!this.cacheDir||!EF(this.cacheDir))return;try{let F=(await p3(this.cacheDir)).filter((B)=>B.endsWith(".typeschema.json"));for(let B of F)await m3(A2(this.cacheDir,B))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as e8}from"crypto";var G2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return e8("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:G2,get:(C)=>D[C],set:(C,u)=>{if(D[C]=u,u.url){if(!F[u.url])F[u.url]=[];let $=F[u.url];if($&&!$.includes(C))$.push(C)}},has:(C)=>(C in D),clear:()=>{Object.keys(D).forEach((C)=>delete D[C]),Object.keys(F).forEach((C)=>delete F[C])},size:()=>Object.keys(D).length,getIdsByUrl:(C)=>F[C]||[],createReference:(C,u)=>({id:C,resourceType:u.resourceType}),getAllReferences:()=>D}};import*as x2 from"path";import*as F6 from"fs/promises";var l3="https://fs.get-ig.org/pkgs/";import*as CF from"fs/promises";import*as c3 from"path";var A0=async(D)=>{try{return await CF.access(D),!0}catch{return!1}},G0=async(D)=>{try{await CF.mkdir(D,{recursive:!0})}catch{}},uF=async(D)=>{let F=c3.join(D,".index.json");return A0(F)};import{exec as DB}from"child_process";import{promisify as FB}from"util";var o3=FB(DB);async function H2(){try{return await o3("bun --version"),"bun"}catch{try{return await o3("npm --version"),"npm"}catch{return null}}}import*as i3 from"fs/promises";import*as t3 from"path";import{exec as BB}from"child_process";import{promisify as EB}from"util";var n3=EB(BB),q2=async(D,F,B)=>{await G0(F);let E=t3.join(F,"package.json");if(!await A0(E))await i3.writeFile(E,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let C=await H2();if(!C)throw new Error("No package manager found. Please install npm or bun.");for(let u of D)try{if(C==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},X=B?`cd ${F} && bun add ${u} --registry ${B}`:`cd ${F} && bun add ${u}`;await n3(X,{env:$,maxBuffer:10485760})}else{let $=B?`cd ${F} && npm add ${u} --registry ${B}`:`cd ${F} && npm add ${u}`;await n3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${u}:`,$),$}};var $F=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as XF from"fs/promises";import*as K2 from"path";import*as M2 from"fs/promises";import*as _2 from"path";import{createHash as s3}from"crypto";var T0=async(D)=>{try{let F=_2.join(D,"package-lock.json");try{let B=await M2.readFile(F,"utf-8");return s3("sha256").update(B).digest("hex")}catch{let B=_2.join(D,"bun.lock"),E=await M2.readFile(B,"utf-8");return s3("sha256").update(E).digest("hex")}}catch{return null}};var V2=async(D,F,B)=>{let E=await T0(B),C={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:E||void 0},u=K2.join(F,"index.json");await XF.writeFile(u,JSON.stringify(C,null,2))},R2=async(D)=>{try{let F=K2.join(D,"index.json"),B=await XF.readFile(F,"utf-8");return JSON.parse(B)}catch{return null}};var r3=(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 B of F)if(D[B]!==void 0&&typeof D[B]!=="string")return!1;return!0},a3=(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)=>r3(F))},U2=(D,F)=>{try{let B=JSON.parse(D);if(!a3(B))return null;return B}catch{return null}};import*as e3 from"fs/promises";import*as L2 from"path";var ZF=async(D,F,B)=>{let E=L2.join(D,".index.json");try{let C=await e3.readFile(E,"utf-8"),u=U2(C,E);if(!u)return;for(let $ of u.files){if(!$.url)continue;let X=L2.join(D,$.filename),Q=B.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:X});B.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:X,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:u["index-version"],url:$.url,version:$.version,kind:$.kind,type:$.type,package:{name:F.name,version:F.version}};if(!B.entries[$.url])B.entries[$.url]=[];let Y=B.entries[$.url];if(Y)Y.push(z)}}catch{}};import*as D6 from"fs/promises";import*as QF from"path";var zF=async(D,F)=>{try{let B=QF.join(D,"package.json"),E=await D6.readFile(B,"utf-8"),C=JSON.parse(E),u={id:{name:C.name,version:C.version},path:D,canonical:C.canonical,fhirVersions:C.fhirVersions};F.packages[C.name]=u,await ZF(D,C,F);let $=QF.join(D,"examples");if(await A0(QF.join($,".index.json")))await ZF($,C,F)}catch{}};import*as N2 from"fs/promises";import*as j2 from"path";var w2=async(D,F)=>{try{let B=await N2.readdir(D,{withFileTypes:!0});for(let E of B){if(!E.isDirectory())continue;let C=j2.join(D,E.name);if(E.name.startsWith("@")){let u=await N2.readdir(C,{withFileTypes:!0});for(let $ of u){if(!$.isDirectory())continue;let X=j2.join(C,$.name);if(await uF(X))await zF(X,F)}}else if(await uF(C))await zF(C,F)}}catch{}};var I2=async(D,F,B,E)=>{if(F.package)try{return await E(D,{package:F.package.name,version:F.package.version})}catch{}return null};var T2={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 b2=(D,F)=>{if(F.length===0)return D;let B=F.map((E)=>E.toLowerCase());return D.filter((E)=>{if(!E.url)return!1;let u=[E.url.toLowerCase(),E.type?.toLowerCase()||"",E.resourceType?.toLowerCase()||""].join(" ");return B.every(($)=>{let X=u.split(/[\/\-_\.\s]+/);if(X.some((Y)=>Y.startsWith($)))return!0;let z=T2[$]||[];for(let Y of z)if(X.some((W)=>W.startsWith(Y)))return!0;return u.includes($)})})};var xD=(D)=>{let{packages:F,workingDir:B}=D,E=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:l3,C=x2.join(B,"node_modules"),u=x2.join(B,".fcm","cache"),$=$F(),X=!1,Q=new Map,z=()=>{if(!X)throw new Error("CanonicalManager not initialized. Call init() first.")},Y=async()=>{if(X)return;await G0(B),await G0(u);let V=await T0(B),L=await R2(u);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 q2(F,B,E),$=$F(),await w2(C,$),await V2($,u,B)}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 I2(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 F6.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}`)}},I=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:I,search:async(V)=>{let L=await I(V);return await Promise.all(L.map((d)=>G(d)))},smartSearch:async(V,L)=>{z();let k=await I({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 b2(k,V)},getSearchParametersForResource:async(V)=>{if(z(),Q.has(V))return Q.get(V);let k=(await I({})).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 P2(D){let E=D.path.split(".").slice(1).map(($)=>({el:$}));if(E.length===0)return[];let C=E.length-1,u={};if(D.slicing){if(u.slicing={...D.slicing},D.min!==void 0)u.slicing.min=D.min;if(D.max&&D.max!=="*")u.slicing.max=parseInt(D.max)}if(D.sliceName){if(u.slice={},D.min!==void 0)u.slice.min=D.min;if(D.max&&D.max!=="*")u.slice.max=parseInt(D.max);u.sliceName=D.sliceName}return E[C]={...E[C],...u},E}function S2(D,F){let B=[],E=Math.min(D.length,F.length);for(let C=0;C<E;C++)if(D[C].el===F[C].el)B.push({el:D[C].el});else break;return B}function v2(D,F){let B=[];for(let E=0;E<F.length;E++)if(E<D.length&&D[E].el===F[E].el)B.push({...D[E],...F[E],...D[E].slicing&&!F[E].slicing&&{slicing:D[E].slicing}});else B.push(F[E]);return B}function CB(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function B6(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function uB(D,F,B,E){let C=[];for(let u=D-1;u>=F;u--){let $=B[u];if($.sliceName)C.push(B6($));C.push({type:"exit",el:$.el})}if(F>0){let u=B[F-1],$=E[F-1];if(CB(u,$))C.push(B6(u))}return C}function $B(D,F,B,E){let C=[];if(D>0&&D<=F){let u=B[D-1]||{},$=E[D-1];if($.sliceName&&(!u.sliceName||u.sliceName!==$.sliceName))C.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return C}for(let u=D;u<F;u++){let $=E[u];if(C.push({type:"enter",el:$.el}),$.sliceName)C.push({type:"enter-slice",sliceName:$.sliceName})}return C}function OF(D,F){let B=D.length,E=F.length,u=S2(D,F).length,$=uB(B,u,D,F),X=$B(u,E,D,F);return[...$,...X]}function C6(D,F){if(!D)return;return D.find((B)=>B.url===F)}function E6(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 XB(D){let F={};for(let[B,E]of Object.entries(D))if(typeof B==="string"&&B.startsWith("pattern")){let C=E6(B.replace(/^pattern/,""));F.pattern={type:C,value:E}}else if(typeof B==="string"&&B.startsWith("fixed")){let C=E6(B.replace(/^fixed/,""));F.pattern={type:C,value:E}}else F[B]=E;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function ZB(D){let F=[];for(let B of D)if(B.targetProfile){let E=Array.isArray(B.targetProfile)?B.targetProfile:[B.targetProfile];F.push(...E)}return F.length>0?[...new Set(F)].sort():void 0}function QB(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let B=ZB(D.type);return{...D,type:[{code:"Reference"}],...B&&{refers:B}}}return D}function zB(D,F){let B=(u)=>{let $={strength:u.strength,...u.valueSet&&{valueSet:u.valueSet}},X=C6(u.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(X?.valueString)$.bindingName=X.valueString;return $};if(D.choices){let{binding:u,...$}=D;return $}if(D.choiceOf&&F.snapshot){let u=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((X)=>X.path===u);if($?.binding)return{...D,binding:B($.binding)}}if(D.binding?.valueSet)return{...D,binding:B(D.binding)};let{binding:E,...C}=D;return C}function OB(D){if(!D.constraint||D.constraint.length===0)return D;let F={};for(let B of D.constraint)F[B.key]={expression:B.expression,human:B.human,severity:B.severity};return{...D,constraint:F}}function YB(D,F){if(!D.type||D.type.length===0)return D;let B=D.type[0]?.extension?.[0];if(B?.url==="http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"&&B.valueUrl)return{...D,type:B.valueUrl};let E=D.type[0].code,C={...D,type:E};if(F.kind==="logical"){let u=C6(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(u?.valueCanonical)C.defaultType=u.valueCanonical}return C}function JB(D){if(D.type?.[0]?.code!=="Extension")return D;let B=D.type[0]?.profile?.[0];if(!B)return D;return{...D,url:B,...D.min&&{min:D.min},...D.max&&D.max!=="*"&&{max:parseInt(D.max)}}}function WB(D){if(D.url)return D;let F=D.max==="*"||D.min&&D.min>=2||D.max&&parseInt(D.max)>=2,B=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(B)E._required=!0;return E}function AB(D,F){let B=D.substring(1).split("."),E=[F.url];for(let C of B.slice(1))E.push("elements",C);return E}function GB(D,F){if(!D.contentReference)return D;let{contentReference:B,...E}=D;return{...E,elementReference:AB(B,F)}}function HB(D){let{path:F,slicing:B,sliceName:E,id:C,mapping:u,example:$,alias:X,condition:Q,comment:z,definition:Y,requirements:W,extension:J,...q}=D;return q}function k2(D,F){let B=QB(D);return B=HB(B),B=zB(B,F),B=OB(B),B=GB(B,F),B=JB(B),B=WB(B),B=YB(B,F),B=XB(B),B}function f2(D){if(D.path.endsWith("[x]"))return!0;if(D.type&&D.type.length>1)return new Set(D.type.map((B)=>B.code)).size>1;return!1}function u6(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function $6(D){let F=D.split("/");return F[F.length-1]}function y2(D){let F=D.path.replace(/\[x\]$/,""),B=F.split(".").pop()||"";if(!D.type)return[];let E=[],C=D.type.map((z)=>B+u6($6(z.code))),{type:u,binding:$,...X}=D,Q={...X,path:F,choices:C};E.push(Q);for(let z of D.type){let Y=u6($6(z.code)),W={...D,path:F+Y,type:[z],choiceOf:B};if(D.binding)delete W.binding;E.push(W)}return E}function X6(D,F){let B=D[D.length-1],E=D.slice(0,-1),C=E[E.length-1],u=F(C,B);return[...E.slice(0,-1),u]}function qB(D,F){if(!D.discriminator)return{};let B={};for(let E of D.discriminator){if(!E.type||!["pattern","value",void 0].includes(E.type))continue;let C=E.path.trim();if(C==="$this"){if(F.pattern?.value)Object.assign(B,F.pattern.value)}else{let u=C.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let Y=z.replace("pattern","").toLowerCase();if(u.length===1&&u[0]===Y)B[Y]=F[z]}let X=["elements"];for(let z of u)if(X.push(z),u.indexOf(z)<u.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=B;for(let Y=0;Y<u.length-1;Y++){if(!z[u[Y]])z[u[Y]]={};z=z[u[Y]]}z[u[u.length-1]]=Q.value}}}return B}function MB(D,F,B){let E={match:F,schema:D};if(B?.min!==void 0&&B.min!==0)E.min=B.min;if(B?.max!==void 0)E.max=B.max;return E}function _B(D,F,B){let E=F.slicing||D.slicing||{},C=qB(E,B),u=MB(B,C,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]=u,F}function KB(D){if(!D.slicing?.slices)return{};let F={};for(let[B,E]of Object.entries(D.slicing.slices)){let{match:C,schema:u,...$}=E,{slicing:X,elements:Q,type:z,min:Y,...W}=u||{},J={};if(C?.url)J.url=C.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[B]=J}return F}function VB(D,F,B){let E={...F};if(D==="extension")E.extensions=KB(B);if(!E.elements)E.elements={};let C=B.choiceOf||D,{_required:u,...$}=B;if(E.elements[D]=$,u){if(!E.required)E.required=[];if(!E.required.includes(C))E.required.push(C)}return E}function YF(D,F,B){let E=[...D];for(let C=0;C<F.length;C++){let u=F[C],X=F[C+1]?.type==="enter"?{}:B;switch(u.type){case"enter":E.push(X);break;case"enter-slice":E.push(X);break;case"exit":E=X6(E,(Q,z)=>VB(u.el,Q,z));break;case"exit-slice":E=X6(E,(Q,z)=>_B(u,Q,z));break}}return E}function Z6(D,F){let B={};if(B.name=D.name,B.type=D.type,D.url)B.url=D.url;if(D.version)B.version=D.version;if(D.description)B.description=D.description;if(D.package_name)B.package_name=D.package_name;if(D.package_version)B.package_version=D.package_version;if(D.package_id)B.package_id=D.package_id;if(B.kind=D.kind,D.derivation)B.derivation=D.derivation;if(D.baseDefinition&&D.type!=="Element")B.base=D.baseDefinition;if(D.abstract)B.abstract=D.abstract;if(B.class=RB(D),F?.package_meta)B.package_meta=F.package_meta;return B}function RB(D){if(D.kind==="resource"&&D.derivation==="constraint")return"profile";if(D.type==="Extension")return"extension";return D.kind||"unknown"}function UB(D){return(D.differential?.element||[]).filter((B)=>B.path.includes("."))}function Q6(D){let B=Object.entries(D).sort((C,u)=>{let $=C[1].index??1/0,X=u[1].index??1/0;return $-X}),E={};for(let[C,u]of B)if(u.elements)E[C]={...u,elements:Q6(u.elements)};else E[C]=u;return E}function b0(D,F=new WeakSet){if(Array.isArray(D))return D.map((B)=>b0(B,F));if(D&&typeof D==="object"){if(F.has(D))return"[Circular Reference]";F.add(D);let B={},E=Object.keys(D);for(let C of E)if(C==="elements"&&D[C])B[C]=Q6(b0(D[C],F));else if(C==="required"&&Array.isArray(D[C]))B[C]=[...D[C]].sort();else B[C]=b0(D[C],F);return B}return D}function d2(D,F){if(D.kind==="primitive-type")return b0(Z6(D,F));let B=Z6(D,F),E=UB(D),C=[B],u=[],$=[...E],X=0;while($.length>0){let z=$.shift();if(f2(z)){let G=y2(z);$.unshift(...G),X++;continue}let Y=P2(z),W=v2(u,Y),J=OF(u,W),M={...k2(z,D),index:X++};C=YF(C,J,M),u=W}let Q=OF(u,[]);if(C=YF(C,Q,{index:X}),C.length!==1)throw new Error(`Invalid stack state: expected 1 element, got ${C.length}`);return b0(C[0])}function JF(D){if(!D)return;return D.split("|")[0]}function LB(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:LB(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,B){let E=F.join(".");return{kind:"nested",package:B?.name||D.package_name||"undefined",version:B?.version||D.package_version||"undefined",name:E,url:`${D.url}#${E}`}}function q0(D,F,B){let E=JF(D)||D,C="unknown",u=E.split("/"),$=u[u.length-1];if($&&$.length>0)C=$.split(/[-_]/).map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("");if(C==="unknown"&&F?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(F.id))C=F.id;return{kind:"value-set",package:B?.name||F?.package_name||"undefined",version:B?.version||F?.package_version||"undefined",name:C,url:E}}function x0(D,F,B,E){let C=F.join("."),u=B||`${D.name}.${C}_binding`;return{kind:"binding",package:E?.name||D.package_name||"undefined",version:E?.version||D.package_version||"undefined",name:u,url:B?`urn:fhir:binding:${u}`:`${D.url}#${C}_binding`}}async function z6(D,F,B){let E=PD(D,B);if(E.kind!=="profile")throw new Error(`Expected profile, got ${E.kind} for ${D.name}`);let C;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 NB(Y,F),q=Y.startsWith("http://hl7.org/fhir/");C={kind:J,package:q?"hl7.fhir.r4.core":B?.name||D.package_name||"undefined",version:q?"4.0.1":B?.version||D.package_version||"undefined",name:W,url:Y}}let u={identifier:E,base:C,dependencies:C?[C]:[]};if(D.description)u.description=D.description;let $=jB(D,B);if(Object.keys($).length>0)u.metadata=$;if(D.elements){let Y=await WF(D,[],D.elements,F,B);if(Object.keys(Y).length>0)u.fields=Y}let X=await wB(D,F);if(Object.keys(X).length>0)u.constraints=X;let Q=await IB(D,F);if(Q.length>0)u.extensions=Q;let z=TB(D);if(z.length>0)u.validation=z;return u}async function NB(D,F){try{let B=await F.resolve(D);if(B){if(B.derivation==="constraint")return"profile";if(B.kind==="resource")return"resource";if(B.kind==="complex-type")return"complex-type"}}catch(B){console.warn(`Could not resolve base schema ${D}:`,B)}if(D.includes("StructureDefinition/")&&!D.startsWith("http://hl7.org/fhir/StructureDefinition/"))return"profile";return"resource"}function jB(D,F){let B={};if(D.publisher)B.publisher=D.publisher;if(D.contact)B.contact=D.contact;if(D.copyright)B.copyright=D.copyright;if(D.purpose)B.purpose=D.purpose;if(D.experimental!==void 0)B.experimental=D.experimental;if(D.date)B.date=D.date;if(D.jurisdiction)B.jurisdiction=D.jurisdiction;if(F?.name)B.package=F.name;else if(D.package_name)B.package=D.package_name;return B}async function wB(D,F){let B={};if(!D.elements)return B;for(let[E,C]of Object.entries(D.elements)){let u={};if(C.min!==void 0)u.min=C.min;if(C.max!==void 0)u.max=String(C.max);if(C.mustSupport)u.mustSupport=!0;if(C.fixedValue!==void 0)u.fixedValue=C.fixedValue;if(C.patternValue!==void 0)u.patternValue=C.patternValue;if(C.binding)u.binding={strength:C.binding.strength,valueSet:C.binding.valueSet??""};if(C.type&&Array.isArray(C.type)&&C.type.length>0)u.types=C.type.map(($)=>{let X={code:$.code};if($.profile)X.profile=$.profile;if($.targetProfile)X.targetProfile=$.targetProfile;return X});if(C.slicing)u.slicing={discriminator:C.slicing.discriminator??[],rules:String(C.slicing),ordered:C.slicing.ordered};if(Object.keys(u).length>0)B[E]=u}return B}async function IB(D,F){let B=[];if(!D.elements)return B;for(let[E,C]of Object.entries(D.elements))if(E.includes("extension")&&C.type&&Array.isArray(C.type)){for(let u of C.type)if(u.code==="Extension"&&u.profile)B.push({path:E,profile:u.profile,min:C.min,max:String(C.max),mustSupport:C.mustSupport})}return B}function TB(D){let F=[];if(!D.elements)return F;for(let[B,E]of Object.entries(D.elements))if(E.constraint&&Array.isArray(E.constraint))for(let C of E.constraint)F.push({path:B,key:C.key,severity:C.severity,human:C.human,expression:C.expression});return F}function h2(D,F,B){let E=[],C=D.elements;for(let u of F)if(C=C?.[u],!C)break;if(C)E.push(C);return E}function g2(D){if(D.length===0)return{};let F={...D[0]};for(let B=D.length-1;B>=0;B--){let E=D[B],C=["choices","short","index","elements","required","excluded","binding","refers","elementReference","mustSupport","slices","slicing","url","extensions"];for(let[u,$]of Object.entries(E))if(!C.includes(u)&&$!==void 0)F[u]=$}for(let B of["choices","binding","refers","elementReference"])if(D[0]&&D[0][B]!==void 0)F[B]=D[0][B];return F}function p2(D,F,B){if(F.length===0)return!1;let E=F[F.length-1],C=F.slice(0,-1),u=D;for(let $ of C)if(u=u.elements?.[$],!u)break;if(u?.required?.includes(E))return!0;if(C.length===0&&E&&D.required?.includes(E))return!0;return!1}function m2(D,F,B){if(F.length===0)return!1;let E=F[F.length-1],C=F.slice(0,-1),u=D;for(let $ of C)if(u=u.elements?.[$],!u)break;if(u?.excluded?.includes(E))return!0;if(C.length===0&&E&&D.excluded?.includes(E))return!0;return!1}async function bB(D,F,B){if(!D.refers||D.refers.length===0)return;let E=[];for(let C of D.refers)try{let u=await F.resolve(C);if(u)E.push(PD(u,B))}catch{}return E}function l2(D,F,B,E,C){if(B.elementReference){let u=B.elementReference.filter(($,X)=>X%2===1).map(($)=>$).filter(($)=>$!=="elements");if(u.length>0)return H0(D,u,C)}if(B.type){let u=B.type.includes("/")?B.type:`http://hl7.org/fhir/StructureDefinition/${B.type}`,$=B.type.match(/^[a-z]/)?"primitive-type":"complex-type",X=u.startsWith("http://hl7.org/fhir/");return{kind:$,package:X?"hl7.fhir.r4.core":C?.name||"undefined",version:X?"4.0.1":C?.version||"undefined",name:B.type,url:u}}return}async function P0(D,F,B,E,C){let u={array:B.array||!1,required:p2(D,F,E),excluded:m2(D,F,E)},$=l2(D,F,B,E,C);if($)u.type=$;if(B.min!==void 0)u.min=B.min;if(B.max!==void 0)u.max=B.max;if(B.choices)u.choices=B.choices;if(B.choiceOf)u.choiceOf=B.choiceOf;if(B.binding){if(u.binding=x0(D,F,B.binding.bindingName,C),B.binding.strength==="required"&&B.type==="code"){let Q=await AF(B,E);if(Q&&Q.length>0)u.enum=Q}}let X=await bB(B,E,C);if(X)u.reference=X;return xB(u)}function xB(D){let F={};for(let[B,E]of Object.entries(D))if(E!==void 0&&E!==null){if(Array.isArray(E)&&E.length===0)continue;F[B]=E}return F}function M0(D){return D.type==="BackboneElement"||D.elements&&Object.keys(D.elements).length>0||!1}function S0(D,F,B,E,C){return{type:H0(D,F,C),array:B.array||!1,required:p2(D,F,E),excluded:m2(D,F,E)}}async function O6(D,F){try{let B=JF(D)||D,E=await F.resolve(B);if(!E)return;if(E.expansion?.contains)return E.expansion.contains.map((u)=>({system:u.system,code:u.code,display:u.display}));let C=[];if(E.compose?.include){for(let u of E.compose.include)if(u.concept)for(let $ of u.concept)C.push({system:u.system,code:$.code,display:$.display});else if(u.system&&!u.filter)try{let $=await F.resolve(u.system);if($?.concept){let X=(Q,z)=>{for(let Y of Q)if(C.push({system:z,code:Y.code,display:Y.display}),Y.concept)X(Y.concept,z)};X($.concept,u.system)}}catch{}}return C.length>0?C:void 0}catch{return}}async function AF(D,F){if(!D.binding)return;let{strength:B,valueSet:E}=D.binding;if(!E)return;if(!(B==="required"||B==="extensible"&&(D.type==="code"||D.type==="Coding")||B==="preferred"&&(D.type==="code"||D.type==="Coding")))return;if(!F.resolve)return;try{let u=await O6(E,F);if(!u||u.length===0)return;let $=u.map((X)=>X.code).filter((X)=>X&&typeof X==="string"&&X.trim().length>0);return $.length>0&&$.length<=100?$:void 0}catch(u){console.debug(`Failed to extract enum values for ${E}: ${u}`);return}}async function Y6(D,F,B,E,C){if(!B.binding?.valueSet)return;let u=x0(D,F,B.binding.bindingName,C),$=l2(D,F,B,E,C),X=q0(B.binding.valueSet,void 0,C),Q={identifier:u,type:$,valueset:X,strength:B.binding.strength,dependencies:[]};if($)Q.dependencies.push($);Q.dependencies.push(X);let z=await AF(B,E);if(z)Q.enum=z;return Q}async function GF(D,F,B){let E=[],C=new Set;async function u(Q,z){for(let[Y,W]of Object.entries(Q)){let J=[...z,Y],q=J.join(".");if(C.has(q))continue;if(C.add(q),W.binding){let M=await Y6(D,J,W,F,B);if(M)E.push(M)}if(W.elements)await u(W.elements,J)}}if(D.elements)await u(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 c2(D,F,B){let E=[];for(let[C,u]of Object.entries(B)){let $=[...F,C];if(M0(u))E.push([$,u]);if(u.elements)E.push(...c2(D,$,u.elements))}return E}async function PB(D,F,B,E,C){let u={};for(let[$,X]of Object.entries(B)){let Q=[...F,$];if(M0(X))u[$]=S0(D,Q,X,E,C);else u[$]=await P0(D,Q,X,E,C)}return u}async function HF(D,F,B){if(!D.elements)return[];let E=[],u=c2(D,[],D.elements).filter(([$,X])=>X.elements&&Object.keys(X.elements).length>0);for(let[$,X]of u){let Q=H0(D,$,B),z;if(X.type==="BackboneElement"||!X.type)z={kind:"complex-type",package:B?.name||"hl7.fhir.r4.core",version:B?.version||"4.0.1",name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else z={kind:"complex-type",package:B?.name||"hl7.fhir.r4.core",version:B?.version||"4.0.1",name:X.type,url:`http://hl7.org/fhir/StructureDefinition/${X.type}`};let Y=await PB(D,$,X.elements,F,B),W={identifier:Q,base:z,fields:Y};E.push(W)}return E.sort(($,X)=>$.identifier.url.localeCompare(X.identifier.url)),E}function qF(D){let F=[];for(let B of D){if(F.push(B.identifier),B.base)F.push(B.base);for(let E of Object.values(B.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 WF(D,F,B,E,C){let u={};for(let[$,X]of Object.entries(B)){let Q=[...F,$],z=h2(D,Q,E),Y=z.length>0?g2(z):X;if(M0(Y))u[$]=S0(D,Q,Y,E,C);else u[$]=await P0(D,Q,Y,E,C)}return u}function J6(D){let F=[];for(let B of Object.values(D)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding)}return F}function W6(D){let F=new Set,B=[];for(let E of D){let C=E.url;if(!F.has(C))F.add(C),B.push(E)}return B.sort((E,C)=>E.name.localeCompare(C.name)),B}function SB(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 vB(D,F,B){try{let E=PD(D,B);E.kind="value-set";let C={identifier:E,description:D.description};if(D.elements){let u=[];for(let[$,X]of Object.entries(D.elements))if("code"in X&&X.code)u.push({code:X.code,display:X.short||X.definition,system:X.system});if(u.length>0)C.concept=u}return C}catch(E){return console.warn(`Failed to transform value set ${D.name}: ${E}`),null}}async function kB(D,F,B){try{let E=PD(D,B),C;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;C={kind:"complex-type",package:B?.name||"hl7.fhir.r4.core",version:B?.version||"4.0.1",name:Q,url:X}}else C={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let u={identifier:E,base:C,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(C)u.dependencies.push(C);if(D.elements){let X=await WF(D,[],D.elements,F,B);if(Object.keys(X).length>0)u.fields=X,u.dependencies.push(...J6(X))}let $=await HF(D,F,B);if($.length>0)u.nested=$,u.dependencies.push(...qF($));return u.dependencies=W6(u.dependencies),u.dependencies=u.dependencies.filter((X)=>X.url!==E.url),u}catch(E){return console.warn(`Failed to transform extension ${D.name}: ${E}`),null}}async function MF(D,F,B){let E=[];if(!B&&(D.package_name||D.package_id))B={name:D.package_name||D.package_id||"undefined",version:D.package_version||"undefined"};let C=PD(D,B);if(C.kind==="profile"){let z=await z6(D,F,B);E.push(z);let Y=await GF(D,F,B);return E.push(...Y),E}if(C.kind==="value-set"||D.kind==="value-set"){let z=await vB(D,F,B);if(z)E.push(z);return E}if(SB(D,C)){let z=await kB(D,F,B);if(z)E.push(z);return E}let u;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/");u={kind:J,package:q?"hl7.fhir.r4.core":B?.name||D.package_name||"undefined",version:q?"4.0.1":B?.version||D.package_version||"undefined",name:Y,url:z}}let $={identifier:C,dependencies:[]},X=[];if(u)$.base=u,X.push(u);if(D.description)$.description=D.description;if(D.kind!=="primitive-type"&&D.elements){let z=await WF(D,[],D.elements,F,B);if(Object.keys(z).length>0)$.fields=z;X.push(...J6(z));let Y=await HF(D,F,B);if(Y.length>0)$.nested=Y,X.push(...qF(Y))}$.dependencies=X,$.dependencies=W6($.dependencies),$.dependencies=$.dependencies.filter((z)=>z.url!==C.url),E.push($);let Q=await GF(D,F,B);return E.push(...Q),E}async function o2(D,F,B){let E=[];for(let C of D){let u=await MF(C,F,B);E.push(...u)}return E}async function fB(D,F){try{let B=await F.resolve(D);if(!B||B.resourceType!=="CodeSystem")return;let E=[],C=(u,$)=>{for(let X of u)if(E.push({system:$,code:X.code,display:X.display}),X.concept)C(X.concept,$)};if(B.concept)C(B.concept,D);return E}catch{return}}async function A6(D,F){let B=[];if(D.concept){for(let E of D.concept)B.push({system:D.system,code:E.code,display:E.display});return B}if(D.system&&!D.filter){let E=await fB(D.system,F);if(E)B.push(...E)}if(D.valueSet)for(let E of D.valueSet)try{let C=await F.resolve(E);if(C){let u=await G6(C,F);if(u)B.push(...u)}}catch{}return B}async function G6(D,F){try{let B=[];if(D.compose){if(D.compose.include)for(let E of D.compose.include){let C=await A6(E,F);B.push(...C)}if(D.compose.exclude){let E=new Set;for(let C of D.compose.exclude){let u=await A6(C,F);for(let $ of u)E.add(`${$.system}|${$.code}`)}return B.filter((C)=>!E.has(`${C.system}|${C.code}`))}}return B.length>0?B:void 0}catch(B){console.error("Error extracting ValueSet concepts:",B);return}}async function n2(D,F,B){let C={identifier:q0(D.url,D,B)};if(D.description)C.description=D.description;let u=await G6(D,F);if(u&&u.length>0)C.concept=u;else if(D.compose)C.compose=D.compose;if(D.compose){let $=[],X=(Q)=>{for(let z of Q){if(z.system)$.push({kind:"value-set",package:B?.name||"undefined",version:B?.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,B))}};if(D.compose.include)X(D.compose.include);if(D.compose.exclude)X(D.compose.exclude)}return C}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||JD({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 B=this.cacheConfig?.forceRegenerate??!1;if(this.cache&&!B){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({}),C=E.filter((M)=>M.resourceType==="StructureDefinition"),u=E.filter((M)=>M.resourceType==="ValueSet");this.logger.info(`Found ${C.length} StructureDefinitions and ${u.length} ValueSets in package`),this.logger.progress(`Converting ${C.length} StructureDefinitions to FHIRSchemas`);let $=this.applyStructureDefinitionTreeshaking(C),X=[],Q=0,z=0;for(let M of $)try{let G=d2(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`),u.length>0)this.logger.debug(`${u.length} ValueSets available for enum extraction`);let Y={name:D,version:F||"latest"},W=[];if(u.length>0){this.logger.progress(`Converting ${u.length} ValueSets to TypeSchema`);let M=0,G=0;for(let I of u)try{let g=await n2(I,this.manager,Y);if(g)W.push(g),M++,this.logger.debug(`Converted ValueSet: ${I.name||I.id}`)}catch(g){G++,this.logger.warn(`Failed to convert ValueSet ${I.name||I.id}: ${g instanceof Error?g.message:String(g)}`)}this.logger.success(`ValueSet conversion completed: ${M}/${u.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"),MF(D,this.manager,F)}async generateFromSchemas(D,F){this.logger.info(`Transforming ${D.length} FHIR schemas to TypeSchema`);let B=await o2(D,this.manager,F),E=[],C=this.groupTypeSchemas(B);if(E.push(...C.resources),E.push(...C.complexTypes),E.push(...C.primitives),C.profiles.length>0){this.logger.info(`Enhancing ${C.profiles.length} profiles`);let u=await this.enhanceProfiles(C.profiles);E.push(...u)}if(C.extensions.length>0){this.logger.info(`Enhancing ${C.extensions.length} extensions`);let u=await this.enhanceExtensions(C.extensions);E.push(...u)}if(C.valueSets.length>0){this.logger.info(`Enhancing ${C.valueSets.length} value sets`);let u=await this.enhanceValueSets(C.valueSets);E.push(...u)}if(C.codeSystems.length>0){this.logger.info(`Enhancing ${C.codeSystems.length} code systems`);let u=await this.enhanceCodeSystems(C.codeSystems);E.push(...u)}return this.logger.success(`Generated ${E.length} enhanced FHIR type schemas: ${C.resources.length} resources, ${C.complexTypes.length} complex types, ${C.primitives.length} primitives`),E}groupTypeSchemas(D){let F={resources:[],complexTypes:[],primitives:[],profiles:[],extensions:[],valueSets:[],codeSystems:[]};for(let B of D)switch(B.identifier.kind){case"resource":F.resources.push(B);break;case"complex-type":F.complexTypes.push(B);break;case"primitive-type":F.primitives.push(B);break;case"binding":if("metadata"in B&&B.metadata?.isExtension)F.extensions.push(B);else F.complexTypes.push(B);break;case"value-set":F.valueSets.push(B);break;default:if("metadata"in B&&B.metadata?.isCodeSystem)F.codeSystems.push(B);else F.complexTypes.push(B);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 B=new Map,E=new Map,C=new Map;for(let z of D){let Y=z.name||z.id;if(Y)B.set(Y,z),E.set(Y,new Set),C.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)),C.set(Y,new Set(J))}let u=new Set;for(let z of F)if(B.has(z))u.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(B.has(J))u.add(J),$(J,Y)};for(let z of Array.from(u))$(z);let X=D.filter((z)=>{let Y=z.name||z.id;return Y&&u.has(Y)}),Q=new Set;for(let z of D){let Y=z.name||z.id;if(Y&&!u.has(Y)){if(Array.from(C.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,B=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 C of E)if(C.type)for(let u of C.type){if(u.code){if(F.add(u.code),u.code==="Reference"&&u.targetProfile)for(let $ of u.targetProfile){let X=this.extractResourceNameFromUrl($);if(X)B.add(X)}}if(u.profile)for(let $ of u.profile){let X=this.extractResourceNameFromUrl($);if(X)F.add(X)}}}return{realDeps:Array.from(F),refTargets:Array.from(B)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as yB}from"node:fs/promises";class _0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await yB(D,"utf-8"),B=this.options.format==="auto"?this.detectFormat(F,D):this.options.format;return this.parseFromString(F,B)}async parseFromString(D,F){let B=F||this.detectFormat(D),E;if(B==="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 B of D){let E=await this.parseFromFile(B);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((B)=>this.matchesIdentifier(B.identifier,F))}findByUrl(D,F){return D.find((B)=>B.identifier.url===F)}findByKind(D,F){return D.filter((B)=>B.identifier.kind===F)}findByPackage(D,F){return D.filter((B)=>B.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 B of Object.values(D.fields)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding);if("reference"in B&&B.reference)F.push(...B.reference)}if("nested"in D&&D.nested)for(let B of D.nested){F.push(B.identifier),F.push(B.base);for(let E of Object.values(B.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 B=D;if(F.push(B.valueset),B.type)F.push(B.type)}return this.deduplicateDependencies(F)}resolveDependencies(D,F){let B=this.getDependencies(F),E=[];for(let C of B){let u=this.findByUrl(D,C.url);if(u)E.push(u)}return E}detectFormat(D,F){if(F){if(F.endsWith(".ndjson"))return"ndjson";if(F.endsWith(".json"))return"json"}let B=D.trim();if(B.includes(`
94
94
  `)){let E=B.split(`
95
95
  `).filter((C)=>C.trim());if(E.length>1)try{if(E[0])JSON.parse(E[0]);return"ndjson"}catch{}}return"json"}parseNDJSON(D){let F=[],B=D.split(`
96
- `).filter((E)=>E.trim());for(let E of B)try{let C=JSON.parse(E);F.push(this.parseSchema(C))}catch(C){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${C}`)}return F}parseJSON(D){try{let F=JSON.parse(D);if(Array.isArray(F))return F.map((B)=>this.parseSchema(B));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,B=[];for(let E of D)if(!F.has(E.url))F.add(E.url),B.push(E);return B.sort((E,C)=>E.name.localeCompare(C.name))}}import{mkdir as J6,writeFile as _0}from"node:fs/promises";import{dirname as SB,join as K0}from"node:path";class _F{resourceTypes=new Set;resourceSearchParams=new Map;autocompleteEnabled;valueSetEnumsEnabled;logger;availableEnumTypes=new Map;static BASE_PARAM_NAMES=["_count","_offset","_sort","_summary","_elements","_lastUpdated","_profile","_security","_tag","_id","_text","_content"];constructor(D){this.autocompleteEnabled=!!D?.autocomplete,this.valueSetEnumsEnabled=!!D?.valueSetEnums,this.logger=D?.logger||JD({prefix:"SearchParam"}),this.logger.debug(`SearchParameterEnhancer initialized: autocomplete=${this.autocompleteEnabled}, valueSetEnums=${this.valueSetEnumsEnabled}`)}generateSearchParamNameUnions(){let D=_F.BASE_PARAM_NAMES.map((C)=>`'${C}'`).join(" | "),F=[];F.push(`/**
96
+ `).filter((E)=>E.trim());for(let E of B)try{let C=JSON.parse(E);F.push(this.parseSchema(C))}catch(C){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${C}`)}return F}parseJSON(D){try{let F=JSON.parse(D);if(Array.isArray(F))return F.map((B)=>this.parseSchema(B));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,B=[];for(let E of D)if(!F.has(E.url))F.add(E.url),B.push(E);return B.sort((E,C)=>E.name.localeCompare(C.name))}}function i2(D){return D.identifier.kind==="binding"}import{mkdir as H6,writeFile as K0}from"node:fs/promises";import{dirname as dB,join as V0}from"node:path";class _F{resourceTypes=new Set;resourceSearchParams=new Map;autocompleteEnabled;valueSetEnumsEnabled;logger;availableEnumTypes=new Map;static BASE_PARAM_NAMES=["_count","_offset","_sort","_summary","_elements","_lastUpdated","_profile","_security","_tag","_id","_text","_content"];constructor(D){this.autocompleteEnabled=!!D?.autocomplete,this.valueSetEnumsEnabled=!!D?.valueSetEnums,this.logger=D?.logger||JD({prefix:"SearchParam"}),this.logger.debug(`SearchParameterEnhancer initialized: autocomplete=${this.autocompleteEnabled}, valueSetEnums=${this.valueSetEnumsEnabled}`)}generateSearchParamNameUnions(){let D=_F.BASE_PARAM_NAMES.map((C)=>`'${C}'`).join(" | "),F=[];F.push(`/**
97
97
  * Base search parameter names available for all resources
98
98
  */`),F.push(`export type BaseSearchParamName = ${D};`),F.push("");let B=Array.from(this.resourceTypes).sort();for(let[C,u]of this.resourceSearchParams.entries()){let X=Array.from(new Set(u.map((z)=>z.name))).sort().map((z)=>`'${z}'`).join(" | "),Q=`${C}SearchParamName`;if(X.length>0)F.push(`/**
99
99
  * Search parameter names for ${C}
@@ -306,7 +306,7 @@ export class SearchParameterValidator {
306
306
  export interface ${D}SearchParams extends BaseEnhancedSearchParams {
307
307
  ${B.join(`
308
308
  `)}
309
- }`}getTypeScriptTypeForSearchParameter(D,F){switch(F.type){case"string":return"string | SearchModifiers['StringModifier']";case"number":return"number | SearchModifiers['NumberParameter']";case"date":return"string | SearchModifiers['DateParameter']";case"token":if(this.valueSetEnumsEnabled){let B=this.availableEnumTypes.get(`${D}${F.name}`);if(B)return`${B} | SearchModifiers['TokenSearchOptions']`}return"string | SearchModifiers['TokenParameter']";case"reference":if(F.target&&F.target.length>0)return"string | SearchModifiers['ReferenceParameter']";return"string | SearchModifiers['ReferenceParameter']";case"quantity":return"number | string | SearchModifiers['QuantityParameter']";case"uri":return"string";case"composite":return"string";default:return"string"}}getResourceTypes(){return this.resourceTypes}}class n2{resourceTypes=new Set;resourceSchemas=new Map;collectResourceData(D){this.resourceTypes.clear(),this.resourceSchemas.clear();for(let F of D)if(F.identifier.kind==="resource"&&F.identifier.name!=="DomainResource"&&F.identifier.name!=="Resource")this.resourceTypes.add(F.identifier.name),this.resourceSchemas.set(F.identifier.name,F)}generateValidationTypes(){return`/**
309
+ }`}getTypeScriptTypeForSearchParameter(D,F){switch(F.type){case"string":return"string | SearchModifiers['StringModifier']";case"number":return"number | SearchModifiers['NumberParameter']";case"date":return"string | SearchModifiers['DateParameter']";case"token":if(this.valueSetEnumsEnabled){let B=this.availableEnumTypes.get(`${D}${F.name}`);if(B)return`${B} | SearchModifiers['TokenSearchOptions']`}return"string | SearchModifiers['TokenParameter']";case"reference":if(F.target&&F.target.length>0)return"string | SearchModifiers['ReferenceParameter']";return"string | SearchModifiers['ReferenceParameter']";case"quantity":return"number | string | SearchModifiers['QuantityParameter']";case"uri":return"string";case"composite":return"string";default:return"string"}}getResourceTypes(){return this.resourceTypes}}class t2{resourceTypes=new Set;resourceSchemas=new Map;collectResourceData(D){this.resourceTypes.clear(),this.resourceSchemas.clear();for(let F of D)if(F.identifier.kind==="resource"&&F.identifier.name!=="DomainResource"&&F.identifier.name!=="Resource")this.resourceTypes.add(F.identifier.name),this.resourceSchemas.set(F.identifier.name,F)}generateValidationTypes(){return`/**
310
310
  * FHIR Resource Validation Types
311
311
  *
312
312
  * Client-side validation types and interfaces for FHIR resources.
@@ -745,7 +745,7 @@ ${D.map((F)=>` case '${F}':
745
745
  });
746
746
  result.valid = false;
747
747
  }`;default:return`// Generic resource constraints
748
- // No specific constraints for ${D}`}}getResourceTypes(){return this.resourceTypes}}class KF{options;resourceTypes=new Set;searchParameterEnhancer;validationGenerator;logger;constructor(D){this.options={clientName:"FHIRClient",includeValidation:!1,includeErrorHandling:!0,includeRequestInterceptors:!1,baseUrlOverride:"",enhancedSearch:!1,includeUtilities:!0,generateValidators:!1,useCanonicalManager:!0,defaultTimeout:30000,defaultRetries:0,includeDocumentation:!0,generateExamples:!1,chainedSearchBuilder:!1,searchAutocomplete:!0,generateValueSetEnums:!0,...D},this.logger=D.logger||JD({prefix:"REST"}),this.logger.debug(`REST client configured: ${this.options.clientName}`),this.searchParameterEnhancer=new _F({autocomplete:this.options.searchAutocomplete??!1,valueSetEnums:this.options.generateValueSetEnums??!1,logger:this.logger.child("Search")}),this.validationGenerator=new n2}collectResourceTypes(D){this.resourceTypes.clear();for(let F of D)if(F.identifier.kind==="resource"&&F.identifier.name!=="DomainResource"&&F.identifier.name!=="Resource")this.resourceTypes.add(F.identifier.name);if(this.options.enhancedSearch)this.searchParameterEnhancer.collectResourceData(D);if(this.options.includeValidation||this.options.generateValidators)this.validationGenerator.collectResourceData(D)}async generate(D){this.collectResourceTypes(D),await J6(this.options.outputDir,{recursive:!0});let F=[],B=await this.generateClientFile(),E=K0(this.options.outputDir,B.filename);await this.ensureDirectoryExists(E),await _0(E,B.content,"utf-8"),F.push({...B,path:E});let C=await this.generateTypesFile(),u=K0(this.options.outputDir,C.filename);if(await _0(u,C.content,"utf-8"),F.push({...C,path:u}),this.options.enhancedSearch){let Q=await this.generateEnhancedSearchParamsFile(),z=K0(this.options.outputDir,Q.filename);await _0(z,Q.content,"utf-8"),F.push({...Q,path:z})}if(this.options.includeValidation||this.options.generateValidators){let Q=await this.generateValidationTypesFile(),z=K0(this.options.outputDir,Q.filename);await _0(z,Q.content,"utf-8"),F.push({...Q,path:z});let Y=await this.generateValidatorsFile(),W=K0(this.options.outputDir,Y.filename);await _0(W,Y.content,"utf-8"),F.push({...Y,path:W})}let $=await this.generateUtilityFile(),X=K0(this.options.outputDir,$.filename);return await _0(X,$.content,"utf-8"),F.push({...$,path:X}),F}async generateClientFile(){let D=Array.from(this.resourceTypes).sort(),F=this.options.clientName,B=this.options.enhancedSearch?`import type {
748
+ // No specific constraints for ${D}`}}getResourceTypes(){return this.resourceTypes}}class KF{options;resourceTypes=new Set;searchParameterEnhancer;validationGenerator;logger;constructor(D){this.options={clientName:"FHIRClient",includeValidation:!1,includeErrorHandling:!0,includeRequestInterceptors:!1,baseUrlOverride:"",enhancedSearch:!1,includeUtilities:!0,generateValidators:!1,useCanonicalManager:!0,defaultTimeout:30000,defaultRetries:0,includeDocumentation:!0,generateExamples:!1,chainedSearchBuilder:!1,searchAutocomplete:!0,generateValueSetEnums:!0,...D},this.logger=D.logger||JD({prefix:"REST"}),this.logger.debug(`REST client configured: ${this.options.clientName}`),this.searchParameterEnhancer=new _F({autocomplete:this.options.searchAutocomplete??!1,valueSetEnums:this.options.generateValueSetEnums??!1,logger:this.logger.child("Search")}),this.validationGenerator=new t2}collectResourceTypes(D){this.resourceTypes.clear();for(let F of D)if(F.identifier.kind==="resource"&&F.identifier.name!=="DomainResource"&&F.identifier.name!=="Resource")this.resourceTypes.add(F.identifier.name);if(this.options.enhancedSearch)this.searchParameterEnhancer.collectResourceData(D);if(this.options.includeValidation||this.options.generateValidators)this.validationGenerator.collectResourceData(D)}async generate(D){this.collectResourceTypes(D),await H6(this.options.outputDir,{recursive:!0});let F=[],B=await this.generateClientFile(),E=V0(this.options.outputDir,B.filename);await this.ensureDirectoryExists(E),await K0(E,B.content,"utf-8"),F.push({...B,path:E});let C=await this.generateTypesFile(),u=V0(this.options.outputDir,C.filename);if(await K0(u,C.content,"utf-8"),F.push({...C,path:u}),this.options.enhancedSearch){let Q=await this.generateEnhancedSearchParamsFile(),z=V0(this.options.outputDir,Q.filename);await K0(z,Q.content,"utf-8"),F.push({...Q,path:z})}if(this.options.includeValidation||this.options.generateValidators){let Q=await this.generateValidationTypesFile(),z=V0(this.options.outputDir,Q.filename);await K0(z,Q.content,"utf-8"),F.push({...Q,path:z});let Y=await this.generateValidatorsFile(),W=V0(this.options.outputDir,Y.filename);await K0(W,Y.content,"utf-8"),F.push({...Y,path:W})}let $=await this.generateUtilityFile(),X=V0(this.options.outputDir,$.filename);return await K0(X,$.content,"utf-8"),F.push({...$,path:X}),F}async generateClientFile(){let D=Array.from(this.resourceTypes).sort(),F=this.options.clientName,B=this.options.enhancedSearch?`import type {
749
749
  EnhancedSearchParams,
750
750
  SearchParameterValidator${this.options.searchAutocomplete?`,
751
751
  SearchParamName,
@@ -1253,7 +1253,7 @@ export type ResourceTypeMap = {
1253
1253
  ${D.map((B)=>` '${B}': ${B};`).join(`
1254
1254
  `)}
1255
1255
  };
1256
- `,exports:["ResourceTypes","ResourceTypeMap",...D]}}async ensureDirectoryExists(D){let F=SB(D);await J6(F,{recursive:!0})}}S0();class r2{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),B=D.filter((E)=>!(E instanceof ND));if(F.length>0)this.reportBatchErrors(F);B.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(`
1256
+ `,exports:["ResourceTypes","ResourceTypeMap",...D]}}async ensureDirectoryExists(D){let F=dB(D);await H6(F,{recursive:!0})}}v0();class e2{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),B=D.filter((E)=>!(E instanceof ND));if(F.length>0)this.reportBatchErrors(F);B.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(`
1257
1257
  \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(`
1258
1258
  \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(`
1259
1259
  ❌ ${D.constructor.name}: ${D.message}`);let F=D.getSuggestions();if(F.length>0)console.error(`
@@ -1261,17 +1261,21 @@ ${D.map((B)=>` '${B}': ${B};`).join(`
1261
1261
  \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(`
1262
1262
  ❌ ${D.length} errors occurred during generation:`);let F=new Map;D.forEach((B)=>{let E=B.constructor.name;if(!F.has(E))F.set(E,[]);F.get(E)?.push(B)});for(let[B,E]of F){console.error(`
1263
1263
  \uD83D\uDCCB ${B} (${E.length} occurrences):`),E.forEach((u,$)=>{if(console.error(` ${$+1}. ${u.message}`),u.context?.schemaName)console.error(` Schema: ${u.context.schemaName}`)});let C=this.getCommonSuggestions(E);if(C.length>0)console.error(`
1264
- \uD83D\uDCA1 Common suggestions:`),C.forEach((u)=>{console.error(` • ${u}`)})}}getCommonSuggestions(D){let F=D.flatMap((C)=>C.getSuggestions()),B=new Map;F.forEach((C)=>{B.set(C,(B.get(C)||0)+1)});let E=Math.ceil(D.length/2);return Array.from(B.entries()).filter(([C,u])=>u>=E).map(([C,u])=>C).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 a2{errorHandler;constructor(D){this.errorHandler=D}async withErrorBoundary(D,F){try{return await D()}catch(B){throw this.errorHandler.handleError(B instanceof Error?B:new Error(String(B)),F),B}}async withBatchErrorBoundary(D,F){let B=[],E=[];for(let C of D)try{let u=await C();B.push(u)}catch(u){E.push(u instanceof Error?u:new Error(String(u)))}if(E.length>0)throw this.errorHandler.handleBatchErrors(E),new s2(`${E.length} operations failed`,E.filter((C)=>C instanceof ND));return B}}S0();S0();import{access as e2,mkdir as vB,rm as kB,stat as W6,writeFile as fB}from"node:fs/promises";import{dirname as D1,join as Z0,relative as yB}from"node:path";class F1{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,B={}){let E=performance.now(),C=Z0(this.options.outputDir,D),u=B.encoding||"utf-8",$=B.overwrite??this.options.overwrite;try{if(!$)try{await e2(C),this.logger.debug(`Skipping existing file: ${D}`);let z=await W6(C);return{path:C,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(D1(C)),await fB(C,F,u);let X=performance.now()-E,Q=Buffer.byteLength(F,u);return this.logger.debug(`Written ${D} (${Q} bytes, ${X.toFixed(2)}ms)`),{path:C,size:Q,writeTime:X}}catch(X){throw new X0(`Failed to write file '${D}': ${X}`,"write",C,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()),B=[];for(let E=0;E<F.length;E+=this.options.batchSize){let u=F.slice(E,E+this.options.batchSize).map(([X,Q])=>this.writeFile(X,Q)),$=await Promise.all(u);if(B.push(...$),E+this.options.batchSize<F.length)await new Promise((X)=>setTimeout(X,10))}return B}async ensureDirectory(D){try{await vB(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 "${D1(D)}"`})}}async cleanDirectory(D="."){let F=Z0(this.options.outputDir,D);try{await e2(F),this.logger.debug(`Cleaning directory: ${D}`),await kB(F,{recursive:!0,force:!0})}catch(B){if(B?.code!=="ENOENT")throw new X0(`Failed to clean directory '${D}': ${B}`,"delete",F,B instanceof Error?B:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let B=D1(Z0(this.options.outputDir,D)),E=Z0(this.options.outputDir,F),C=yB(B,E);if(!C.startsWith("."))C=`./${C}`;return C.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=Z0(this.options.outputDir,D);try{return await e2(F),!0}catch{return!1}}async getFileStats(D){let F=Z0(this.options.outputDir,D);try{return{size:(await W6(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 C1{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 t2(`Invalid generator configuration: ${F.errors.join(", ")}`,"configuration",D);if(this.options=this.mergeWithDefaults(D),this.logger=D.logger||JD({prefix:this.getLanguageName(),verbose:this.options.verbose||!1}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new r2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new a2(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),F.warnings.length>0)F.warnings.forEach((B)=>{this.logger.warn(`Configuration warning: ${B}`)})}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 F1({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 B=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${B.toFixed(2)}ms (avg ${(B/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(D){let F=this.fileManager.writeFile,B=new Map;this.fileManager.writeFile=async(E,C)=>{let u={path:`${this.options.outputDir}/${E}`,size:Buffer.byteLength(C,"utf-8"),writeTime:0};return B.set(E,u),u};try{let E=await this.generate(D);return E.forEach((C)=>{let u=B.get(C.filename);if(u)C.path=u.path,C.size=u.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}=(H6(),IF(G6));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}=IF(q6);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}=IF(_6);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=[],B=[],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&&!xF("node:path").isAbsolute(D.outputDir))B.push("Using relative path for outputDir - consider using absolute path"),E.push("Use path.resolve() to convert to absolute path");if(D.validate===!1)B.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:B,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((B)=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(B),this.reportProgress("validation",D.indexOf(B)+1,D.length,`Validated ${B.identifier?.name||"schema"}`)},{schema:B,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${D.length} schemas`)}async validateSchema(D){let F=[],B=D.identifier?.name||"unknown";if(this.logger.debug(`\uD83D\uDD0D Validating schema: ${B} (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,C]of Object.entries(D.fields)){if(!E.trim())F.push("Field name cannot be empty");if(!C)F.push(`Field '${E}' is null or undefined`)}if(await this.detectCircularReferences(D))this.logger.warn(`⚠️ Circular reference detected in schema '${B}' - this may be expected for FHIR primitive types`);if(F.length>0)throw this.logger.error(`❌ Schema validation failed for '${B}': ${F.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(D,null,2)}`),new i2(`Schema validation failed for '${D.identifier?.name||"unknown"}'`,D,F);this.logger.debug(`✅ Schema validation passed for '${B}'`)}async detectCircularReferences(D){let F=new Set,B=new Set;return((C)=>{let u=C.identifier?.name;if(!u)return!1;if(B.has(u))return!0;if(F.has(u))return!1;if(B.add(u),"fields"in C&&C.fields){for(let $ of Object.values(C.fields))if($?.type?.name===u)return!0}return B.delete(u),F.add(u),!1})(D)}async generateFiles(D){let F=D.map((B,E)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let C=await this.generateFileForSchema(B,E,D.length);return this.generatedFiles.push(C),C},{schema:B,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`)}async generateFileForSchema(D,F,B){let E=performance.now(),C={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},u=await this.generateSchemaContent(D,C);if(this.options.validate)await this.validateContent(u,C);let $=C.filename+this.getFileExtension(),X=await this.fileManager.writeFile($,u),Q=performance.now()-E;return this.reportProgress("writing",F+1,B,`Generated ${$} (${X.size} bytes)`),{path:X.path,filename:$,content:u,exports:this.extractExports(u),size:X.size,timestamp:new Date,metadata:{generationTime:Q,schemaCount:1,templateName:C.templateName?.toString(),warnings:[]}}}ensureFileExtension(D){let F=this.getFileExtension();return D.endsWith(F)?D:`${D}${F}`}extractExports(D){let F=[],B=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=B.exec(D))!==null)if(E[1]){let u=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...u)}let C=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((E=C.exec(D))!==null)if(E[1])F.push(E[1]);return[...new Set(F)]}reportProgress(D,F,B,E,C){if(this.progressCallback)this.progressCallback(D,F,B,E,C);if(E&&this.options.verbose)this.logger.debug(`[${D}] ${E} (${F}/${B})`)}async runPostGenerationHooks(){}getCachedOrCompute(D,F){if(this.cache.has(D))return this.cache.get(D);let B=F();if(B instanceof Promise)return B.then((E)=>{return this.cache.set(D,E),E});else return this.cache.set(D,B),B}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((B,E)=>B+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 u1{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 B=this.mapType(D.element);return this.mapArray(B)}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 K6(D);case"PascalCase":return dB(D);case"snake_case":return V6(D);case"kebab-case":return hB(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function K6(D){return D.replace(/[-_\s]+(.)?/g,(F,B)=>B?.toUpperCase()||"")}function dB(D){let F=K6(D);return F.charAt(0).toUpperCase()+F.slice(1)}function V6(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function hB(D){return V6(D).replace(/_/g,"-")}class $1 extends u1{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 B=D[0]?.name||"unknown";return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[B==="unknown"?"unknown":`'${B}'`],nullable:!1,metadata:{referencedType:B,referencedSchema:D[0]}}}return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[D.map((B)=>{let E=B.name||"unknown";return E==="unknown"?"unknown":`'${E}'`}).join(" | ")],nullable:!1,metadata:{referencedTypes:D.map((B)=>B.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 B=this.tsOptions.preferUndefined?"undefined":"null";return{...D,name:`${D.name} | ${B}`,nullable:!0,metadata:{...D.metadata,nullabilityType:B,wasOptional:!0}}}mapEnum(D,F){let B=F?this.formatTypeName(F):"CodedValue";return{name:D.map((C)=>`'${C}'`).join(" | "),isPrimitive:!1,nullable:!1,metadata:{enumName:B,values:D,isUnionType:!0}}}formatTypeName(D){return this.applyNamingConvention(D)}formatFieldName(D){return gB(D)}formatFileName(D){return this.applyNamingConvention(D)}generateInterfaceField(D,F,B){return`${this.formatFieldName(D)}${B?"":"?"}: ${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 B of D){let E=this.generateImportStatement(B);if(E)F.add(E)}return Array.from(F).sort()}}function gB(D){return D.replace(/[-_\s]+(.)?/g,(F,B)=>B?.toUpperCase()||"")}class RF extends C1{profilesByPackage=new Map;resourceTypes=new Set;get tsOptions(){return this.options}getLanguageName(){return"TypeScript"}getFileExtension(){return".ts"}createTypeMapper(){let D=this.options;return new $1({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 B=this.generateTypeScriptInterface(D),E="";if("nested"in D&&D.nested&&Array.isArray(D.nested))E=D.nested.map((u)=>this.generateNestedTypeInterface(D.identifier.name,u)).join(`
1264
+ \uD83D\uDCA1 Common suggestions:`),C.forEach((u)=>{console.error(` • ${u}`)})}}getCommonSuggestions(D){let F=D.flatMap((C)=>C.getSuggestions()),B=new Map;F.forEach((C)=>{B.set(C,(B.get(C)||0)+1)});let E=Math.ceil(D.length/2);return Array.from(B.entries()).filter(([C,u])=>u>=E).map(([C,u])=>C).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 D1{errorHandler;constructor(D){this.errorHandler=D}async withErrorBoundary(D,F){try{return await D()}catch(B){throw this.errorHandler.handleError(B instanceof Error?B:new Error(String(B)),F),B}}async withBatchErrorBoundary(D,F){let B=[],E=[];for(let C of D)try{let u=await C();B.push(u)}catch(u){E.push(u instanceof Error?u:new Error(String(u)))}if(E.length>0)throw this.errorHandler.handleBatchErrors(E),new a2(`${E.length} operations failed`,E.filter((C)=>C instanceof ND));return B}}v0();v0();import{access as F1,mkdir as hB,rm as gB,stat as q6,writeFile as pB}from"node:fs/promises";import{dirname as B1,join as Z0,relative as mB}from"node:path";class E1{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,B={}){let E=performance.now(),C=Z0(this.options.outputDir,D),u=B.encoding||"utf-8",$=B.overwrite??this.options.overwrite;try{if(!$)try{await F1(C),this.logger.debug(`Skipping existing file: ${D}`);let z=await q6(C);return{path:C,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(B1(C)),await pB(C,F,u);let X=performance.now()-E,Q=Buffer.byteLength(F,u);return this.logger.debug(`Written ${D} (${Q} bytes, ${X.toFixed(2)}ms)`),{path:C,size:Q,writeTime:X}}catch(X){throw new X0(`Failed to write file '${D}': ${X}`,"write",C,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()),B=[];for(let E=0;E<F.length;E+=this.options.batchSize){let u=F.slice(E,E+this.options.batchSize).map(([X,Q])=>this.writeFile(X,Q)),$=await Promise.all(u);if(B.push(...$),E+this.options.batchSize<F.length)await new Promise((X)=>setTimeout(X,10))}return B}async ensureDirectory(D){try{await hB(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 "${B1(D)}"`})}}async cleanDirectory(D="."){let F=Z0(this.options.outputDir,D);try{await F1(F),this.logger.debug(`Cleaning directory: ${D}`),await gB(F,{recursive:!0,force:!0})}catch(B){if(B?.code!=="ENOENT")throw new X0(`Failed to clean directory '${D}': ${B}`,"delete",F,B instanceof Error?B:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let B=B1(Z0(this.options.outputDir,D)),E=Z0(this.options.outputDir,F),C=mB(B,E);if(!C.startsWith("."))C=`./${C}`;return C.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=Z0(this.options.outputDir,D);try{return await F1(F),!0}catch{return!1}}async getFileStats(D){let F=Z0(this.options.outputDir,D);try{return{size:(await q6(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 $1{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 r2(`Invalid generator configuration: ${F.errors.join(", ")}`,"configuration",D);if(this.options=this.mergeWithDefaults(D),this.logger=D.logger||JD({prefix:this.getLanguageName(),verbose:this.options.verbose||!1}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new e2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new D1(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),F.warnings.length>0)F.warnings.forEach((B)=>{this.logger.warn(`Configuration warning: ${B}`)})}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 E1({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 B=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${B.toFixed(2)}ms (avg ${(B/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(D){let F=this.fileManager.writeFile,B=new Map;this.fileManager.writeFile=async(E,C)=>{let u={path:`${this.options.outputDir}/${E}`,size:Buffer.byteLength(C,"utf-8"),writeTime:0};return B.set(E,u),u};try{let E=await this.generate(D);return E.forEach((C)=>{let u=B.get(C.filename);if(u)C.path=u.path,C.size=u.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}=(K6(),IF(_6));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}=IF(V6);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}=IF(U6);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=[],B=[],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&&!xF("node:path").isAbsolute(D.outputDir))B.push("Using relative path for outputDir - consider using absolute path"),E.push("Use path.resolve() to convert to absolute path");if(D.validate===!1)B.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:B,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((B)=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(B),this.reportProgress("validation",D.indexOf(B)+1,D.length,`Validated ${B.identifier?.name||"schema"}`)},{schema:B,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${D.length} schemas`)}async validateSchema(D){let F=[],B=D.identifier?.name||"unknown";if(this.logger.debug(`\uD83D\uDD0D Validating schema: ${B} (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,C]of Object.entries(D.fields)){if(!E.trim())F.push("Field name cannot be empty");if(!C)F.push(`Field '${E}' is null or undefined`)}if(await this.detectCircularReferences(D))this.logger.warn(`⚠️ Circular reference detected in schema '${B}' - this may be expected for FHIR primitive types`);if(F.length>0)throw this.logger.error(`❌ Schema validation failed for '${B}': ${F.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(D,null,2)}`),new s2(`Schema validation failed for '${D.identifier?.name||"unknown"}'`,D,F);this.logger.debug(`✅ Schema validation passed for '${B}'`)}async detectCircularReferences(D){let F=new Set,B=new Set;return((C)=>{let u=C.identifier?.name;if(!u)return!1;if(B.has(u))return!0;if(F.has(u))return!1;if(B.add(u),"fields"in C&&C.fields){for(let $ of Object.values(C.fields))if($?.type?.name===u)return!0}return B.delete(u),F.add(u),!1})(D)}async generateFiles(D){let F=D.map((B,E)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let C=await this.generateFileForSchema(B,E,D.length);return this.generatedFiles.push(C),C},{schema:B,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`)}async generateFileForSchema(D,F,B){let E=performance.now(),C={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},u=await this.generateSchemaContent(D,C);if(this.options.validate)await this.validateContent(u,C);let $=C.filename+this.getFileExtension(),X=await this.fileManager.writeFile($,u),Q=performance.now()-E;return this.reportProgress("writing",F+1,B,`Generated ${$} (${X.size} bytes)`),{path:X.path,filename:$,content:u,exports:this.extractExports(u),size:X.size,timestamp:new Date,metadata:{generationTime:Q,schemaCount:1,templateName:C.templateName?.toString(),warnings:[]}}}ensureFileExtension(D){let F=this.getFileExtension();return D.endsWith(F)?D:`${D}${F}`}extractExports(D){let F=[],B=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=B.exec(D))!==null)if(E[1]){let u=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...u)}let C=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((E=C.exec(D))!==null)if(E[1])F.push(E[1]);return[...new Set(F)]}reportProgress(D,F,B,E,C){if(this.progressCallback)this.progressCallback(D,F,B,E,C);if(E&&this.options.verbose)this.logger.debug(`[${D}] ${E} (${F}/${B})`)}async runPostGenerationHooks(){}getCachedOrCompute(D,F){if(this.cache.has(D))return this.cache.get(D);let B=F();if(B instanceof Promise)return B.then((E)=>{return this.cache.set(D,E),E});else return this.cache.set(D,B),B}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((B,E)=>B+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 X1{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 B=this.mapType(D.element);return this.mapArray(B)}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 L6(D);case"PascalCase":return lB(D);case"snake_case":return N6(D);case"kebab-case":return cB(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function L6(D){return D.replace(/[-_\s]+(.)?/g,(F,B)=>B?.toUpperCase()||"")}function lB(D){let F=L6(D);return F.charAt(0).toUpperCase()+F.slice(1)}function N6(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function cB(D){return N6(D).replace(/_/g,"-")}class Z1 extends X1{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 B=D[0]?.name||"unknown";return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[B==="unknown"?"unknown":`'${B}'`],nullable:!1,metadata:{referencedType:B,referencedSchema:D[0]}}}return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[D.map((B)=>{let E=B.name||"unknown";return E==="unknown"?"unknown":`'${E}'`}).join(" | ")],nullable:!1,metadata:{referencedTypes:D.map((B)=>B.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 B=this.tsOptions.preferUndefined?"undefined":"null";return{...D,name:`${D.name} | ${B}`,nullable:!0,metadata:{...D.metadata,nullabilityType:B,wasOptional:!0}}}mapEnum(D,F){let B=F?this.formatTypeName(F):"CodedValue";return{name:D.map((C)=>`'${C}'`).join(" | "),isPrimitive:!1,nullable:!1,metadata:{enumName:B,values:D,isUnionType:!0}}}formatTypeName(D){return this.applyNamingConvention(D)}formatFieldName(D){return oB(D)}formatFileName(D){return this.applyNamingConvention(D)}generateInterfaceField(D,F,B){return`${this.formatFieldName(D)}${B?"":"?"}: ${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 B of D){let E=this.generateImportStatement(B);if(E)F.add(E)}return Array.from(F).sort()}}function oB(D){return D.replace(/[-_\s]+(.)?/g,(F,B)=>B?.toUpperCase()||"")}class RF extends $1{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 Z1({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 B=this.generateTypeScriptInterface(D),E="";if("nested"in D&&D.nested&&Array.isArray(D.nested))E=D.nested.map((u)=>this.generateNestedTypeInterface(D.identifier.name,u)).join(`
1265
1265
 
1266
1266
  `);if(E)return`${B}
1267
1267
 
1268
- ${E}`;return B}filterAndSortSchemas(D){return D.filter((F)=>!this.shouldSkipSchema(F))}async validateContent(D,F){let B=/export\s+(interface|class|type|enum)\s+\w+/.test(D),E=D.includes("{")&&D.includes("}");if(!B)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 B of D){let E=await this.transformSchema(B);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()},B=await this.generateSchemaContent(D,F);if(!B.trim())return;let E=this.extractImportsFromContent(B,D),C=this.extractExportsFromContent(B,D),u=this.getFilenameForSchema(D);return{content:B,imports:E,exports:Array.from(C),filename:u}}shouldSkipSchema(D){if(D.identifier.kind==="value-set"||D.identifier.kind==="binding"||D.identifier.kind==="primitive-type")return!0;if(D.identifier.url?.includes("/extension/")&&!this.tsOptions.includeExtensions)return!0;return!1}getFilenameForSchema(D){return`${this.typeMapper.formatFileName(D.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(D,F){let B=new Map,E=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,C;while((C=E.exec(D))!==null){let u=C[1],$=C[2];if(!u||!$)continue;let X=u.split(",").map((Q)=>Q.trim());for(let Q of X)B.set(Q,$)}return B}extractExportsFromContent(D,F){let B=new Set,E=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,C;while((C=E.exec(D))!==null)if(C[1])B.add(C[1]);return B.add(this.typeMapper.formatTypeName(F.identifier.name)),B}sanitizePackageName(D){return D.replace(/[^a-zA-Z0-9-_.]/g,"-")}generateReferenceInterface(D){let F=[],B=new Set;if("fields"in D&&D.fields)for(let[,E]of Object.entries(D.fields))this.collectFieldImports(E).forEach((u)=>B.add(u));if(F.push("import type { ResourceType } from './utilities.js';"),B.size>0){let E=Array.from(B).sort();for(let C of E)F.push(`import type { ${C} } from './${C}.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,C]of Object.entries(D.fields))if(E==="type")F.push(" type?: T;");else{let u=this.generateFieldLines(E,C);for(let $ of u)if($)F.push(` ${$}`)}return F.push("}"),F.join(`
1269
- `)}generateTypeScriptInterface(D){let F=[],B=this.typeMapper.formatTypeName(D.identifier.name),E=new Set;if("fields"in D&&D.fields)for(let[,C]of Object.entries(D.fields))this.collectFieldImports(C).forEach(($)=>E.add($));if("nested"in D&&D.nested&&Array.isArray(D.nested)){for(let C of D.nested)if(C.fields)for(let[,u]of Object.entries(C.fields))this.collectFieldImports(u).forEach((X)=>E.add(X))}if(E.size>0){let C=Array.from(E).sort();for(let u of C)F.push(`import type { ${u} } from './${u}.js';`);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 ${B} {`),D.identifier.kind==="resource")F.push(` resourceType: '${B}';`);if("fields"in D&&D.fields)for(let[C,u]of Object.entries(D.fields)){let $=this.generateFieldLines(C,u);for(let X of $)if(X)F.push(` ${X}`)}return F.push("}"),F.join(`
1270
- `)}collectFieldImports(D){let F=[];if("choices"in D&&D.choices&&Array.isArray(D.choices))return F;if("type"in D&&D.type){if(D.type.kind==="nested")return F;let B=this.typeMapper.mapType(D.type);if(!B.isPrimitive&&B.name!=="any"){if(!["string","number","boolean","Date","object","unknown","any"].includes(B.name))F.push(B.name)}}return[...new Set(F)]}extractReferenceTypes(D){let F=[];if(!Array.isArray(D))return F;for(let B of D){if(!B||typeof B!=="object")continue;if(B.kind==="resource"&&B.name){let E=this.typeMapper.formatTypeName(B.name);F.push(E)}}return[...new Set(F)]}generateNestedTypeInterface(D,F){let B=[],E=this.typeMapper.formatTypeName(`${D}${this.capitalizeFirst(F.identifier.name)}`);if(this.tsOptions.includeDocuments&&F.description){if(B.push("/**"),B.push(` * ${F.description}`),F.identifier.url)B.push(` * @see ${F.identifier.url}`);B.push(" */")}if(B.push(`export interface ${E} {`),F.fields)for(let[C,u]of Object.entries(F.fields)){let $=this.generateFieldLines(C,u);for(let X of $)if(X)B.push(` ${X}`)}return B.push("}"),B.join(`
1271
- `)}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 B=this.generateFieldLine(D,F);return B?[B]:[]}generateFieldLine(D,F){let B="any",E=!1,C=!1;if("type"in F&&F.type){if(B=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;B=this.typeMapper.formatTypeName(`${z}${this.capitalizeFirst(Y)}`)}else B=this.typeMapper.formatTypeName(F.type.name)}else if(B==="Reference"&&F.reference&&Array.isArray(F.reference)){let Q=this.extractReferenceTypes(F.reference);if(Q.length>0)Q.forEach((Y)=>this.resourceTypes.add(Y)),B=`Reference<${Q.map((Y)=>`'${Y}'`).join(" | ")}>`}}if("required"in F)E=F.required;if("array"in F)C=F.array;return`${D}${E?"":"?"}: ${B}${C?"[]":""};`}extractExports(D){let F=[],B=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=B.exec(D))!==null)if(E[1]){let u=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...u)}let C=[/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 u of C){let $;while(($=u.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 runPostGenerationHooks(){await super.runPostGenerationHooks(),await this.generateUtilitiesFile()}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 u=E===F.length-1?";":"";D.push(` | '${F[E]}'${u}`)}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 B=D.join(`
1272
- `);await this.fileManager.writeFile("utilities.ts",B),this.logger.info(`Generated utilities.ts with ${this.resourceTypes.size} resource types`)}}class UF{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||JD({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 B=this.loadFromPackage(D,F);return this.pendingOperations.push(B),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`,B=new RF({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,logger:this.logger.child("TS"),verbose:this.options.verbose,validate:!0,overwrite:this.options.overwrite});return this.generators.set("typescript",B),this.logger.debug(`Configured TypeScript generator (${D.moduleFormat||"esm"})`),this}restClient(D={}){let F=`${this.options.outputDir}/client`,B=new KF({outputDir:F,logger:this.logger.child("REST"),...D});return this.generators.set("restclient",B),this.logger.debug(`Configured REST client generator (${D.clientName||"FHIRClient"})`),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}ensureTypeScriptForRestClient(){let D=this.generators.has("restclient"),F=this.generators.has("typescript");if(D&&!F)this.logger.debug("Automatically adding TypeScript generator for REST client"),this.typescript({moduleFormat:"esm",generateIndex:!0,includeDocuments:!1,namingConvention:"PascalCase"})}async generate(){this.ensureTypeScriptForRestClient();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(B){this.logger.error("Code generation failed",B instanceof Error?B:new Error(String(B))),F.errors.push(B instanceof Error?B.message:String(B)),F.success=!1}finally{F.duration=performance.now()-D}return F}async build(){await this.resolveSchemas();let D={};for(let[F,B]of this.generators.entries())if(B.build)D[F]=await B.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 B=new SD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);this.typeSchemaGenerator=B;let E=await B.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 B=await new M0({format:"auto",validate:this.options.validate}).parseFromFiles(D);if(this.schemas=[...this.schemas,...B],this.cache)this.cache.setMany(B)}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,B=0;for(let[E,C]of this.generators.entries()){this.reportProgress("Generating",2+B/F,4,`Generating ${E}...`);try{let u=await C.generate(this.schemas);D.filesGenerated.push(...u.map(($)=>$.path||$.filename))}catch(u){D.errors.push(`${E} generator failed: ${u instanceof Error?u.message:String(u)}`)}B++}}reportProgress(D,F,B,E){if(this.progressCallback)this.progressCallback(D,F,B,E);if(this.options.verbose&&E)this.logger.debug(`[${D}] ${E}`)}}import{existsSync as pB}from"node:fs";import{readFile as mB}from"node:fs/promises";import{resolve as R6}from"node:path";var LF={outputDir:"./generated",verbose:!1,overwrite:!0,validate:!0,cache:!0,restClient:{clientName:"FHIRClient",includeValidation:!1,includeErrorHandling:!0,includeRequestInterceptors:!1,baseUrlOverride:"",enhancedSearch:!1,chainedSearchBuilder:!1,searchAutocomplete:!0,generateValueSetEnums:!0,includeUtilities:!0,generateValidators:!1,useCanonicalManager:!0,defaultTimeout:30000,defaultRetries:0,includeDocumentation:!0,generateExamples:!1},typescript:{moduleFormat:"esm",generateIndex:!0,includeDocuments:!1,namingConvention:"PascalCase",strictMode:!0,includeProfiles:!0,includeExtensions:!1,includeValueSets:!0,includeCodeSystems:!1,includeOperations:!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:""},NF=["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 U6{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 B=D;if(B.outputDir!==void 0&&typeof B.outputDir!=="string")F.errors.push({path:"outputDir",message:"outputDir must be a string",value:B.outputDir});let E=["verbose","overwrite","validate","cache"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.errors.push({path:C,message:`${C} must be a boolean`,value:B[C]});if(B.typescript!==void 0){let C=this.validateTypeScriptConfig(B.typescript);F.errors.push(...C)}if(B.typeSchema!==void 0){let C=this.validateTypeSchemaConfig(B.typeSchema);F.errors.push(...C)}if(B.restClient!==void 0){let C=this.validateRestClientConfig(B.restClient);F.errors.push(...C)}if(B.packages!==void 0)if(!Array.isArray(B.packages))F.errors.push({path:"packages",message:"packages must be an array",value:B.packages});else B.packages.forEach((C,u)=>{if(typeof C!=="string")F.errors.push({path:`packages[${u}]`,message:"package name must be a string",value:C})});if(B.files!==void 0)if(!Array.isArray(B.files))F.errors.push({path:"files",message:"files must be an array",value:B.files});else B.files.forEach((C,u)=>{if(typeof C!=="string")F.errors.push({path:`files[${u}]`,message:"file path must be a string",value:C})});if(F.valid=F.errors.length===0,F.valid)F.config=B;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 B=D;if(B.moduleFormat!==void 0){if(!["esm","cjs"].includes(B.moduleFormat))F.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:B.moduleFormat})}if(B.namingConvention!==void 0){if(!["PascalCase","camelCase"].includes(B.namingConvention))F.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:B.namingConvention})}let E=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.${C}`,message:`${C} must be a boolean`,value:B[C]});if(B.validatorOptions!==void 0){let C=this.validateValidatorOptions(B.validatorOptions);F.push(...C)}if(B.guardOptions!==void 0){let C=this.validateGuardOptions(B.guardOptions);F.push(...C)}if(B.profileOptions!==void 0){let C=this.validateProfileOptions(B.profileOptions);F.push(...C)}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 B=D,E=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.validatorOptions.${C}`,message:`${C} must be a boolean`,value:B[C]});return F}validateRestClientConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"restClient",message:"restClient config must be an object",value:D}),F;let B=D;if(B.clientName!==void 0&&typeof B.clientName!=="string")F.push({path:"restClient.clientName",message:"clientName must be a string",value:B.clientName});if(B.baseUrlOverride!==void 0&&typeof B.baseUrlOverride!=="string")F.push({path:"restClient.baseUrlOverride",message:"baseUrlOverride must be a string",value:B.baseUrlOverride});if(B.defaultTimeout!==void 0){if(typeof B.defaultTimeout!=="number"||B.defaultTimeout<=0)F.push({path:"restClient.defaultTimeout",message:"defaultTimeout must be a positive number",value:B.defaultTimeout})}if(B.defaultRetries!==void 0){if(typeof B.defaultRetries!=="number"||B.defaultRetries<0)F.push({path:"restClient.defaultRetries",message:"defaultRetries must be a non-negative number",value:B.defaultRetries})}let E=["includeValidation","includeErrorHandling","includeRequestInterceptors","enhancedSearch","chainedSearchBuilder","searchAutocomplete","generateValueSetEnums","includeUtilities","generateValidators","useCanonicalManager","includeDocumentation","generateExamples"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`restClient.${C}`,message:`${C} must be a boolean`,value:B[C]});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 B=D;if(B.targetTSVersion!==void 0){if(!["3.8","4.0","4.5","5.0"].includes(B.targetTSVersion))F.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:B.targetTSVersion})}let E=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.guardOptions.${C}`,message:`${C} must be a boolean`,value:B[C]});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 B=D;if(B.generateKind!==void 0){if(!["interface","type","both"].includes(B.generateKind))F.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:B.generateKind})}if(B.subfolder!==void 0&&typeof B.subfolder!=="string")F.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:B.subfolder});let E=["includeConstraints","includeDocumentation","strictMode"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.profileOptions.${C}`,message:`${C} must be a boolean`,value:B[C]});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 B=D,E=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let u of E)if(B[u]!==void 0&&typeof B[u]!=="boolean")F.push({path:`typeSchema.${u}`,message:`${u} must be a boolean`,value:B[u]});let C=["cacheDir","cacheKeyPrefix"];for(let u of C)if(B[u]!==void 0&&typeof B[u]!=="string")F.push({path:`typeSchema.${u}`,message:`${u} must be a string`,value:B[u]});if(B.maxAge!==void 0){if(typeof B.maxAge!=="number"||B.maxAge<=0)F.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:B.maxAge})}if(B.profiles!==void 0)if(typeof B.profiles!=="object"||B.profiles===null)F.push({path:"typeSchema.profiles",message:"profiles must be an object",value:B.profiles});else{let u=B.profiles;if(u.autoDetect!==void 0&&typeof u.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:u.autoDetect})}return F}}class L6{validator=new U6;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...LF}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith(".js")){let C=await import(R6(D));F=C.default||C}else{let E=await mB(D,"utf-8");F=JSON.parse(E)}let B=this.validator.validate(F);if(!B.valid){let E=B.errors.map((C)=>`${C.path}: ${C.message}`).join(`
1268
+ ${E}`;return B}filterAndSortSchemas(D){return this.collectedValueSets=this.collectValueSets(D),D.filter((F)=>!this.shouldSkipSchema(F))}async validateContent(D,F){let B=/export\s+(interface|class|type|enum)\s+\w+/.test(D),E=D.includes("{")&&D.includes("}");if(!B)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 B of D){let E=await this.transformSchema(B);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()},B=await this.generateSchemaContent(D,F);if(!B.trim())return;let E=this.extractImportsFromContent(B,D),C=this.extractExportsFromContent(B,D),u=this.getFilenameForSchema(D);return{content:B,imports:E,exports:Array.from(C),filename:u}}shouldGenerateValueSet(D){if(!i2(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 B of D)if(this.shouldGenerateValueSet(B)&&i2(B)){let E=this.typeMapper.formatTypeName(B.identifier.name);F.set(E,B)}return F}shouldUseValueSetType(D){if(!D)return!1;let F=this.typeMapper.formatTypeName(D.name);return this.collectedValueSets.has(F)}getValueSetTypeName(D){return this.typeMapper.formatTypeName(D.name)}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 B=F.split("StructureDefinition/")[1];if(B){let E=B.includes("-"),C=D.identifier.kind==="profile";if(E&&C)return!0}}}return!1}getFilenameForSchema(D){return`${this.typeMapper.formatFileName(D.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(D,F){let B=new Map,E=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,C;while((C=E.exec(D))!==null){let u=C[1],$=C[2];if(!u||!$)continue;let X=u.split(",").map((Q)=>Q.trim());for(let Q of X)B.set(Q,$)}return B}extractExportsFromContent(D,F){let B=new Set,E=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,C;while((C=E.exec(D))!==null)if(C[1])B.add(C[1]);return B.add(this.typeMapper.formatTypeName(F.identifier.name)),B}sanitizePackageName(D){return D.replace(/[^a-zA-Z0-9-_.]/g,"-")}generateReferenceInterface(D){let F=[],B=new Set;if("fields"in D&&D.fields)for(let[,E]of Object.entries(D.fields))this.collectFieldImports(E).forEach((u)=>B.add(u));if(F.push("import type { ResourceType } from './utilities.js';"),B.size>0){let E=Array.from(B).sort();for(let C of E)F.push(`import type { ${C} } from './${C}.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,C]of Object.entries(D.fields))if(E==="type")F.push(" type?: T;");else{let u=this.generateFieldLines(E,C);for(let $ of u)if($)F.push(` ${$}`)}return F.push("}"),F.join(`
1269
+ `)}generateTypeScriptInterface(D){let F=[],B=this.typeMapper.formatTypeName(D.identifier.name),E=new Set,C=new Set;if("fields"in D&&D.fields)for(let[,u]of Object.entries(D.fields)){let $=this.collectFieldImports(u);for(let X of $)if(this.collectedValueSets.has(X))C.add(X);else E.add(X)}if("nested"in D&&D.nested&&Array.isArray(D.nested)){for(let u of D.nested)if(u.fields)for(let[,$]of Object.entries(u.fields)){let X=this.collectFieldImports($);for(let Q of X)if(this.collectedValueSets.has(Q))C.add(Q);else E.add(Q)}}if(E.size>0){let u=Array.from(E).sort();for(let $ of u)F.push(`import type { ${$} } from './${$}.js';`)}if(C.size>0){let $=Array.from(C).sort().join(", ");F.push(`import type { ${$} } from './valuesets/index.js';`)}if(E.size>0||C.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 ${B} {`),D.identifier.kind==="resource")F.push(` resourceType: '${B}';`);if("fields"in D&&D.fields)for(let[u,$]of Object.entries(D.fields)){let X=this.generateFieldLines(u,$);for(let Q of X)if(Q)F.push(` ${Q}`)}return F.push("}"),F.join(`
1270
+ `)}collectFieldImports(D){let F=[];if("choices"in D&&D.choices&&Array.isArray(D.choices))return F;if(D.binding&&this.shouldUseValueSetType(D.binding)){let B=this.getValueSetTypeName(D.binding);return F.push(B),F}if("type"in D&&D.type){if(D.type.kind==="nested")return F;let B=this.typeMapper.mapType(D.type);if(!B.isPrimitive&&B.name!=="any"){if(!["string","number","boolean","Date","object","unknown","any"].includes(B.name))F.push(B.name)}}return[...new Set(F)]}extractReferenceTypes(D){let F=[];if(!Array.isArray(D))return F;for(let B of D){if(!B||typeof B!=="object")continue;if(B.kind==="resource"&&B.name){let E=this.typeMapper.formatTypeName(B.name);F.push(E)}}return[...new Set(F)]}generateNestedTypeInterface(D,F){let B=[],E=this.typeMapper.formatTypeName(`${D}${this.capitalizeFirst(F.identifier.name)}`);if(this.tsOptions.includeDocuments&&F.description){if(B.push("/**"),B.push(` * ${F.description}`),F.identifier.url)B.push(` * @see ${F.identifier.url}`);B.push(" */")}if(B.push(`export interface ${E} {`),F.fields)for(let[C,u]of Object.entries(F.fields)){let $=this.generateFieldLines(C,u);for(let X of $)if(X)B.push(` ${X}`)}return B.push("}"),B.join(`
1271
+ `)}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 B=this.generateFieldLine(D,F);return B?[B]:[]}generateFieldLine(D,F){let B="any",E=!1,C=!1;if("type"in F&&F.type){if(F.binding&&this.shouldUseValueSetType(F.binding))B=this.getValueSetTypeName(F.binding);else if(B=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;B=this.typeMapper.formatTypeName(`${z}${this.capitalizeFirst(Y)}`)}else B=this.typeMapper.formatTypeName(F.type.name)}else if(B==="Reference"&&F.reference&&Array.isArray(F.reference)){let Q=this.extractReferenceTypes(F.reference);if(Q.length>0)Q.forEach((Y)=>this.resourceTypes.add(Y)),B=`Reference<${Q.map((Y)=>`'${Y}'`).join(" | ")}>`}}if("required"in F)E=F.required;if("array"in F)C=F.array;return`${D}${E?"":"?"}: ${B}${C?"[]":""};`}extractExports(D){let F=[],B=/export\s*\{\s*([^}]+)\s*\}/g,E;while((E=B.exec(D))!==null)if(E[1]){let u=E[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...u)}let C=[/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 u of C){let $;while(($=u.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 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 u=E===F.length-1?";":"";D.push(` | '${F[E]}'${u}`)}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 B=D.join(`
1272
+ `);await this.fileManager.writeFile("utilities.ts",B),this.logger.info(`Generated utilities.ts with ${this.resourceTypes.size} resource types`)}generateValueSetFile(D){let F=this.typeMapper.formatTypeName(D.identifier.name),B=D.enum?.map((C)=>` '${C}'`).join(`,
1273
+ `)||"",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 = [`),B)E.push(B);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(`
1274
+ `)}async generateValueSetFiles(){if(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)return;for(let[D,F]of this.collectedValueSets){let B=this.generateValueSetFile(F),E=`valuesets/${D}.ts`;await this.fileManager.writeFile(E,B),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 B=D.join(`
1275
+ `);await this.fileManager.writeFile("valuesets/index.ts",B),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.collectedValueSets.size>0)D.push(""),D.push("// Value Sets"),D.push('export * from "./valuesets/index.js";');let F=D.join(`
1276
+ `);await this.fileManager.writeFile("index.ts",F),this.logger.info(`Generated index.ts with type exports${this.collectedValueSets.size>0?" and value sets":""}`)}}class UF{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||JD({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 B=this.loadFromPackage(D,F);return this.pendingOperations.push(B),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`,B=new RF({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",B),this.logger.debug(`Configured TypeScript generator (${D.moduleFormat||"esm"})`),this}restClient(D={}){let F=`${this.options.outputDir}/client`,B=new KF({outputDir:F,logger:this.logger.child("REST"),...D});return this.generators.set("restclient",B),this.logger.debug(`Configured REST client generator (${D.clientName||"FHIRClient"})`),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}ensureTypeScriptForRestClient(){let D=this.generators.has("restclient"),F=this.generators.has("typescript");if(D&&!F)this.logger.debug("Automatically adding TypeScript generator for REST client"),this.typescript({moduleFormat:"esm",generateIndex:!0,includeDocuments:!1,namingConvention:"PascalCase"})}async generate(){this.ensureTypeScriptForRestClient();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(B){this.logger.error("Code generation failed",B instanceof Error?B:new Error(String(B))),F.errors.push(B instanceof Error?B.message:String(B)),F.success=!1}finally{F.duration=performance.now()-D}return F}async build(){await this.resolveSchemas();let D={};for(let[F,B]of this.generators.entries())if(B.build)D[F]=await B.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 B=new SD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);this.typeSchemaGenerator=B;let E=await B.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 B=await new _0({format:"auto",validate:this.options.validate}).parseFromFiles(D);if(this.schemas=[...this.schemas,...B],this.cache)this.cache.setMany(B)}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,B=0;for(let[E,C]of this.generators.entries()){this.reportProgress("Generating",2+B/F,4,`Generating ${E}...`);try{let u=await C.generate(this.schemas);D.filesGenerated.push(...u.map(($)=>$.path||$.filename))}catch(u){D.errors.push(`${E} generator failed: ${u instanceof Error?u.message:String(u)}`)}B++}}reportProgress(D,F,B,E){if(this.progressCallback)this.progressCallback(D,F,B,E);if(this.options.verbose&&E)this.logger.debug(`[${D}] ${E}`)}}import{existsSync as nB}from"node:fs";import{readFile as iB}from"node:fs/promises";import{resolve as j6}from"node:path";var LF={outputDir:"./generated",verbose:!1,overwrite:!0,validate:!0,cache:!0,restClient:{clientName:"FHIRClient",includeValidation:!1,includeErrorHandling:!0,includeRequestInterceptors:!1,baseUrlOverride:"",enhancedSearch:!1,chainedSearchBuilder:!1,searchAutocomplete:!0,generateValueSetEnums:!0,includeUtilities:!0,generateValidators:!1,useCanonicalManager:!0,defaultTimeout:30000,defaultRetries:0,includeDocumentation:!0,generateExamples:!1},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:""},NF=["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 w6{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 B=D;if(B.outputDir!==void 0&&typeof B.outputDir!=="string")F.errors.push({path:"outputDir",message:"outputDir must be a string",value:B.outputDir});let E=["verbose","overwrite","validate","cache"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.errors.push({path:C,message:`${C} must be a boolean`,value:B[C]});if(B.typescript!==void 0){let C=this.validateTypeScriptConfig(B.typescript);F.errors.push(...C)}if(B.typeSchema!==void 0){let C=this.validateTypeSchemaConfig(B.typeSchema);F.errors.push(...C)}if(B.restClient!==void 0){let C=this.validateRestClientConfig(B.restClient);F.errors.push(...C)}if(B.packages!==void 0)if(!Array.isArray(B.packages))F.errors.push({path:"packages",message:"packages must be an array",value:B.packages});else B.packages.forEach((C,u)=>{if(typeof C!=="string")F.errors.push({path:`packages[${u}]`,message:"package name must be a string",value:C})});if(B.files!==void 0)if(!Array.isArray(B.files))F.errors.push({path:"files",message:"files must be an array",value:B.files});else B.files.forEach((C,u)=>{if(typeof C!=="string")F.errors.push({path:`files[${u}]`,message:"file path must be a string",value:C})});if(F.valid=F.errors.length===0,F.valid)F.config=B;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 B=D;if(B.moduleFormat!==void 0){if(!["esm","cjs"].includes(B.moduleFormat))F.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:B.moduleFormat})}if(B.namingConvention!==void 0){if(!["PascalCase","camelCase"].includes(B.namingConvention))F.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:B.namingConvention})}let E=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.${C}`,message:`${C} must be a boolean`,value:B[C]});if(B.validatorOptions!==void 0){let C=this.validateValidatorOptions(B.validatorOptions);F.push(...C)}if(B.guardOptions!==void 0){let C=this.validateGuardOptions(B.guardOptions);F.push(...C)}if(B.profileOptions!==void 0){let C=this.validateProfileOptions(B.profileOptions);F.push(...C)}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 B=D,E=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.validatorOptions.${C}`,message:`${C} must be a boolean`,value:B[C]});return F}validateRestClientConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"restClient",message:"restClient config must be an object",value:D}),F;let B=D;if(B.clientName!==void 0&&typeof B.clientName!=="string")F.push({path:"restClient.clientName",message:"clientName must be a string",value:B.clientName});if(B.baseUrlOverride!==void 0&&typeof B.baseUrlOverride!=="string")F.push({path:"restClient.baseUrlOverride",message:"baseUrlOverride must be a string",value:B.baseUrlOverride});if(B.defaultTimeout!==void 0){if(typeof B.defaultTimeout!=="number"||B.defaultTimeout<=0)F.push({path:"restClient.defaultTimeout",message:"defaultTimeout must be a positive number",value:B.defaultTimeout})}if(B.defaultRetries!==void 0){if(typeof B.defaultRetries!=="number"||B.defaultRetries<0)F.push({path:"restClient.defaultRetries",message:"defaultRetries must be a non-negative number",value:B.defaultRetries})}let E=["includeValidation","includeErrorHandling","includeRequestInterceptors","enhancedSearch","chainedSearchBuilder","searchAutocomplete","generateValueSetEnums","includeUtilities","generateValidators","useCanonicalManager","includeDocumentation","generateExamples"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`restClient.${C}`,message:`${C} must be a boolean`,value:B[C]});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 B=D;if(B.targetTSVersion!==void 0){if(!["3.8","4.0","4.5","5.0"].includes(B.targetTSVersion))F.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:B.targetTSVersion})}let E=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.guardOptions.${C}`,message:`${C} must be a boolean`,value:B[C]});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 B=D;if(B.generateKind!==void 0){if(!["interface","type","both"].includes(B.generateKind))F.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:B.generateKind})}if(B.subfolder!==void 0&&typeof B.subfolder!=="string")F.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:B.subfolder});let E=["includeConstraints","includeDocumentation","strictMode"];for(let C of E)if(B[C]!==void 0&&typeof B[C]!=="boolean")F.push({path:`typescript.profileOptions.${C}`,message:`${C} must be a boolean`,value:B[C]});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 B=D,E=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let u of E)if(B[u]!==void 0&&typeof B[u]!=="boolean")F.push({path:`typeSchema.${u}`,message:`${u} must be a boolean`,value:B[u]});let C=["cacheDir","cacheKeyPrefix"];for(let u of C)if(B[u]!==void 0&&typeof B[u]!=="string")F.push({path:`typeSchema.${u}`,message:`${u} must be a string`,value:B[u]});if(B.maxAge!==void 0){if(typeof B.maxAge!=="number"||B.maxAge<=0)F.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:B.maxAge})}if(B.profiles!==void 0)if(typeof B.profiles!=="object"||B.profiles===null)F.push({path:"typeSchema.profiles",message:"profiles must be an object",value:B.profiles});else{let u=B.profiles;if(u.autoDetect!==void 0&&typeof u.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:u.autoDetect})}return F}}class I6{validator=new w6;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...LF}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith(".js")){let C=await import(j6(D));F=C.default||C}else{let E=await iB(D,"utf-8");F=JSON.parse(E)}let B=this.validator.validate(F);if(!B.valid){let E=B.errors.map((C)=>`${C.path}: ${C.message}`).join(`
1273
1277
  `);throw new Error(`Configuration validation failed:
1274
- ${E}`)}return this.mergeWithDefaults(B.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 NF){let B=R6(D,F);if(pB(B))return B}return null}mergeWithDefaults(D){let F={...LF,...D,typescript:{...LF.typescript,...D.typescript}};if(D.restClient!==void 0)F.restClient={...LF.restClient,...D.restClient};else delete F.restClient;return F}}var lB=new L6;async function jF(D){return lB.autoload(D)}var N6={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(" ");RD(`Invalid syntax: 'atomic-codegen generate ${$}'
1278
+ ${E}`)}return this.mergeWithDefaults(B.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 NF){let B=j6(D,F);if(nB(B))return B}return null}mergeWithDefaults(D){let F={...LF,...D,typescript:{...LF.typescript,...D.typescript}};if(D.restClient!==void 0)F.restClient={...LF.restClient,...D.restClient};else delete F.restClient;return F}}var tB=new I6;async function jF(D){return tB.autoload(D)}var T6={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(" ");RD(`Invalid syntax: 'atomic-codegen generate ${$}'
1275
1279
 
1276
1280
  The CLI has been simplified and no longer uses subcommands.
1277
1281
 
@@ -1279,7 +1283,7 @@ The CLI has been simplified and no longer uses subcommands.
1279
1283
  `+`❌ Old: atomic-codegen generate typescript
1280
1284
 
1281
1285
  `+`All generation settings are now configured in your config file.
1282
- Create an atomic-codegen.config.ts file to get started.`),process.exit(1)}let F=process.cwd(),B=await nB(F);if(!B){let $=NF.map((X)=>` - ${X}`).join(`
1286
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1)}let F=process.cwd(),B=await aB(F);if(!B){let $=NF.map((X)=>` - ${X}`).join(`
1283
1287
  `);RD(`No configuration file found. Please create one of the following files in your project root:
1284
1288
  ${$}
1285
1289
 
@@ -1292,13 +1296,13 @@ export default defineConfig({
1292
1296
  typescript: {
1293
1297
  generateIndex: true
1294
1298
  }
1295
- });`),process.exit(1)}let E=await jF(F),C=D.verbose??E.verbose??!1,u=JD({verbose:C,prefix:"Generate"});try{if(O2("Starting generation from config"),C)u.info(`Config file: ${B}`),u.info(`Output directory: ${E.outputDir||"./generated"}`),u.info(`Packages: ${E.packages?.length||0}`),u.info(`Files: ${E.files?.length||0}`),u.info(`TypeScript generation: ${E.typescript?"enabled":"disabled"}`),u.info(`REST Client generation: ${E.restClient?"enabled":"disabled"}`);let $=new UF({outputDir:E.outputDir||"./generated",verbose:C,overwrite:E.overwrite??!0,validate:E.validate??!0,cache:E.cache??!0,typeSchemaConfig:E.typeSchema,logger:u});if(E.packages&&E.packages.length>0){u.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){u.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(C)u.info("Configuring TypeScript generation from config"),u.debug(`Module format: ${E.typescript.moduleFormat||"esm"}`),u.debug(`Generate index: ${E.typescript.generateIndex??!0}`),u.debug(`Include docs: ${E.typescript.includeDocuments??!1}`),u.debug(`Naming convention: ${E.typescript.namingConvention||"PascalCase"}`);$.typescript(E.typescript)}if(E.restClient){if(C)u.info("Configuring REST Client generation from config"),u.debug(`Client name: ${E.restClient.clientName||"FHIRClient"}`),u.debug(`Include validation: ${E.restClient.includeValidation??!1}`),u.debug(`Enhanced search: ${E.restClient.enhancedSearch??!1}`);$.restClient(E.restClient)}if(!E.typescript&&!E.restClient)throw new Error("No generators configured. Please enable 'typescript' or 'restClient' in your config file.");if(C)$.onProgress((Q,z,Y,W)=>{let J=Math.round(z/Y*100);u.progress(`[${Q}] ${J}% - ${W||"Processing..."}`)});u.step("Executing generation...");let X=await $.generate();if(X.success){if(DF(`Generated ${X.filesGenerated.length} files in ${X.duration.toFixed(2)}ms`),u.dim(`Output directory: ${X.outputDir}`),X.warnings.length>0)for(let Q of X.warnings)z2(Q)}else{RD(`Generation failed with ${X.errors.length} errors`);for(let Q of X.errors)u.dim(` ${Q}`);process.exit(1)}}catch($){RD("Generation failed with unexpected error",$ instanceof Error?$:new Error(String($))),process.exit(1)}}};async function nB(D){for(let F of NF){let B=oB(D,F);if(cB(B))return B}return null}import{mkdir as iB,writeFile as tB}from"node:fs/promises";import{dirname as sB}from"node:path";var j6={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=JD({verbose:D.verbose,prefix:"TypeSchema"});try{let B=await jF(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:B.typeSchema?.singleFile??!1,C=E?"ndjson":D.format;F.debug(`Format: ${C}${E&&D.format==="json"?" (forced from json due to singleFile)":""}`);let u=D.treeshake&&D.treeshake.length>0?D.treeshake:B.typeSchema?.treeshake;if(u&&u.length>0)F.info(`Treeshaking enabled for ResourceTypes: ${u.join(", ")}`);if(E)F.info("Single file output enabled (NDJSON format)");let $=Date.now(),X=new SD({verbose:D.verbose,treeshake:u}),Q=[];for(let J of D.packages){let[q,_]=J.includes("@")?J.split("@"):[J,void 0];F.progress(`Processing package: ${q}${_?`@${_}`:""}`);let H=await X.generateFromPackage(q,_);Q.push(...H)}if(Q.length===0)throw new Error("No schemas were generated from the specified packages");let z=D.output;await iB(sB(z),{recursive:!0});let Y;if(C==="json")Y=JSON.stringify(Q,null,2);else Y=Q.map((J)=>JSON.stringify(J)).join(`
1296
- `);await tB(z,Y,"utf-8");let W=Date.now()-$;if(W2(`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(B){F.error("Failed to generate TypeSchema",B instanceof Error?B:new Error(String(B))),process.exit(1)}}};var w6={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:(D)=>{return D.command(j6).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){FF("Available typeschema subcommands:"),$0(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
1299
+ });`),process.exit(1)}let E=await jF(F),C=D.verbose??E.verbose??!1,u=JD({verbose:C,prefix:"Generate"});try{if(O2("Starting generation from config"),C)u.info(`Config file: ${B}`),u.info(`Output directory: ${E.outputDir||"./generated"}`),u.info(`Packages: ${E.packages?.length||0}`),u.info(`Files: ${E.files?.length||0}`),u.info(`TypeScript generation: ${E.typescript?"enabled":"disabled"}`),u.info(`REST Client generation: ${E.restClient?"enabled":"disabled"}`);let $=new UF({outputDir:E.outputDir||"./generated",verbose:C,overwrite:E.overwrite??!0,validate:E.validate??!0,cache:E.cache??!0,typeSchemaConfig:E.typeSchema,logger:u});if(E.packages&&E.packages.length>0){u.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){u.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(C)u.info("Configuring TypeScript generation from config"),u.debug(`Module format: ${E.typescript.moduleFormat||"esm"}`),u.debug(`Generate index: ${E.typescript.generateIndex??!0}`),u.debug(`Include docs: ${E.typescript.includeDocuments??!1}`),u.debug(`Naming convention: ${E.typescript.namingConvention||"PascalCase"}`);$.typescript(E.typescript)}if(E.restClient){if(C)u.info("Configuring REST Client generation from config"),u.debug(`Client name: ${E.restClient.clientName||"FHIRClient"}`),u.debug(`Include validation: ${E.restClient.includeValidation??!1}`),u.debug(`Enhanced search: ${E.restClient.enhancedSearch??!1}`);$.restClient(E.restClient)}if(!E.typescript&&!E.restClient)throw new Error("No generators configured. Please enable 'typescript' or 'restClient' in your config file.");if(C)$.onProgress((Q,z,Y,W)=>{let J=Math.round(z/Y*100);u.progress(`[${Q}] ${J}% - ${W||"Processing..."}`)});u.step("Executing generation...");let X=await $.generate();if(X.success){if(FF(`Generated ${X.filesGenerated.length} files in ${X.duration.toFixed(2)}ms`),u.dim(`Output directory: ${X.outputDir}`),X.warnings.length>0)for(let Q of X.warnings)z2(Q)}else{RD(`Generation failed with ${X.errors.length} errors`);for(let Q of X.errors)u.dim(` ${Q}`);process.exit(1)}}catch($){RD("Generation failed with unexpected error",$ instanceof Error?$:new Error(String($))),process.exit(1)}}};async function aB(D){for(let F of NF){let B=rB(D,F);if(sB(B))return B}return null}import{mkdir as eB,writeFile as DE}from"node:fs/promises";import{dirname as FE}from"node:path";var b6={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=JD({verbose:D.verbose,prefix:"TypeSchema"});try{let B=await jF(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:B.typeSchema?.singleFile??!1,C=E?"ndjson":D.format;F.debug(`Format: ${C}${E&&D.format==="json"?" (forced from json due to singleFile)":""}`);let u=D.treeshake&&D.treeshake.length>0?D.treeshake:B.typeSchema?.treeshake;if(u&&u.length>0)F.info(`Treeshaking enabled for ResourceTypes: ${u.join(", ")}`);if(E)F.info("Single file output enabled (NDJSON format)");let $=Date.now(),X=new SD({verbose:D.verbose,treeshake:u}),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 eB(FE(z),{recursive:!0});let Y;if(C==="json")Y=JSON.stringify(Q,null,2);else Y=Q.map((J)=>JSON.stringify(J)).join(`
1300
+ `);await DE(z,Y,"utf-8");let W=Date.now()-$;if(W2(`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(B){F.error("Failed to generate TypeSchema",B instanceof Error?B:new Error(String(B))),process.exit(1)}}};var x6={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:(D)=>{return D.command(b6).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){BF("Available typeschema subcommands:"),$0(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
1297
1301
  Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
1298
1302
  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))RD(`Unknown typeschema subcommand: ${D.subcommand}
1299
- `),FF("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(`
1300
- Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1)}};async function rB(D){Y2({verbose:D.verbose||D.debug,timestamp:D.debug})}function aB(){return S3(cF(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(rB).command(w6).command(N6).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)J2("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(`
1303
+ `),BF("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(`
1304
+ Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1)}};async function BE(D){Y2({verbose:D.verbose||D.debug,timestamp:D.debug})}function EE(){return k3(cF(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(BE).command(x6).command(T6).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)J2("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(`
1301
1305
  Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
1302
1306
  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(`
1303
1307
  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,B)=>{if(F)RD(F.message,F);else RD(D);RD(`
1304
- Use --help for usage information`),process.exit(1)}).wrap(Math.min(120,process.stdout.columns||80))}async function I6(){await aB().parseAsync()}if(xF.main==xF.module)I6().catch((D)=>{console.error("CLI Error:",D instanceof Error?D.message:D),process.exit(1)});
1308
+ Use --help for usage information`),process.exit(1)}).wrap(Math.min(120,process.stdout.columns||80))}async function P6(){await EE().parseAsync()}if(xF.main==xF.module)P6().catch((D)=>{console.error("CLI Error:",D instanceof Error?D.message:D),process.exit(1)});